more cleaning of matrix4x4_t struct access
[xonotic/darkplaces.git] / r_shadow.c
1
2 /*
3 Terminology: Stencil Shadow Volume (sometimes called Stencil Shadows)
4 An extrusion of the lit faces, beginning at the original geometry and ending
5 further from the light source than the original geometry (presumably at least
6 as far as the light's radius, if the light has a radius at all), capped at
7 both front and back to avoid any problems (extrusion from dark faces also
8 works but has a different set of problems)
9
10 This is normally rendered using Carmack's Reverse technique, in which
11 backfaces behind zbuffer (zfail) increment the stencil, and frontfaces behind
12 zbuffer (zfail) decrement the stencil, the result is a stencil value of zero
13 where shadows did not intersect the visible geometry, suitable as a stencil
14 mask for rendering lighting everywhere but shadow.
15
16 In our case to hopefully avoid the Creative Labs patent, we draw the backfaces
17 as decrement and the frontfaces as increment, and we redefine the DepthFunc to
18 GL_LESS (the patent uses GL_GEQUAL) which causes zfail when behind surfaces
19 and zpass when infront (the patent draws where zpass with a GL_GEQUAL test),
20 additionally we clear stencil to 128 to avoid the need for the unclamped
21 incr/decr extension (not related to patent).
22
23 Patent warning:
24 This algorithm may be covered by Creative's patent (US Patent #6384822),
25 however that patent is quite specific about increment on backfaces and
26 decrement on frontfaces where zpass with GL_GEQUAL depth test, which is
27 opposite this implementation and partially opposite Carmack's Reverse paper
28 (which uses GL_LESS, but increments on backfaces and decrements on frontfaces).
29
30
31
32 Terminology: Stencil Light Volume (sometimes called Light Volumes)
33 Similar to a Stencil Shadow Volume, but inverted; rather than containing the
34 areas in shadow it contains the areas in light, this can only be built
35 quickly for certain limited cases (such as portal visibility from a point),
36 but is quite useful for some effects (sunlight coming from sky polygons is
37 one possible example, translucent occluders is another example).
38
39
40
41 Terminology: Optimized Stencil Shadow Volume
42 A Stencil Shadow Volume that has been processed sufficiently to ensure it has
43 no duplicate coverage of areas (no need to shadow an area twice), often this
44 greatly improves performance but is an operation too costly to use on moving
45 lights (however completely optimal Stencil Light Volumes can be constructed
46 in some ideal cases).
47
48
49
50 Terminology: Per Pixel Lighting (sometimes abbreviated PPL)
51 Per pixel evaluation of lighting equations, at a bare minimum this involves
52 DOT3 shading of diffuse lighting (per pixel dotproduct of negated incidence
53 vector and surface normal, using a texture of the surface bumps, called a
54 NormalMap) if supported by hardware; in our case there is support for cards
55 which are incapable of DOT3, the quality is quite poor however.  Additionally
56 it is desirable to have specular evaluation per pixel, per vertex
57 normalization of specular halfangle vectors causes noticable distortion but
58 is unavoidable on hardware without GL_ARB_fragment_program or
59 GL_ARB_fragment_shader.
60
61
62
63 Terminology: Normalization CubeMap
64 A cubemap containing normalized dot3-encoded (vectors of length 1 or less
65 encoded as RGB colors) for any possible direction, this technique allows per
66 pixel calculation of incidence vector for per pixel lighting purposes, which
67 would not otherwise be possible per pixel without GL_ARB_fragment_program or
68 GL_ARB_fragment_shader.
69
70
71
72 Terminology: 2D+1D Attenuation Texturing
73 A very crude approximation of light attenuation with distance which results
74 in cylindrical light shapes which fade vertically as a streak (some games
75 such as Doom3 allow this to be rotated to be less noticable in specific
76 cases), the technique is simply modulating lighting by two 2D textures (which
77 can be the same) on different axes of projection (XY and Z, typically), this
78 is the second best technique available without 3D Attenuation Texturing,
79 GL_ARB_fragment_program or GL_ARB_fragment_shader technology.
80
81
82
83 Terminology: 2D+1D Inverse Attenuation Texturing
84 A clever method described in papers on the Abducted engine, this has a squared
85 distance texture (bright on the outside, black in the middle), which is used
86 twice using GL_ADD blending, the result of this is used in an inverse modulate
87 (GL_ONE_MINUS_DST_ALPHA, GL_ZERO) to implement the equation
88 lighting*=(1-((X*X+Y*Y)+(Z*Z))) which is spherical (unlike 2D+1D attenuation
89 texturing).
90
91
92
93 Terminology: 3D Attenuation Texturing
94 A slightly crude approximation of light attenuation with distance, its flaws
95 are limited radius and resolution (performance tradeoffs).
96
97
98
99 Terminology: 3D Attenuation-Normalization Texturing
100 A 3D Attenuation Texture merged with a Normalization CubeMap, by making the
101 vectors shorter the lighting becomes darker, a very effective optimization of
102 diffuse lighting if 3D Attenuation Textures are already used.
103
104
105
106 Terminology: Light Cubemap Filtering
107 A technique for modeling non-uniform light distribution according to
108 direction, for example a lantern may use a cubemap to describe the light
109 emission pattern of the cage around the lantern (as well as soot buildup
110 discoloring the light in certain areas), often also used for softened grate
111 shadows and light shining through a stained glass window (done crudely by
112 texturing the lighting with a cubemap), another good example would be a disco
113 light.  This technique is used heavily in many games (Doom3 does not support
114 this however).
115
116
117
118 Terminology: Light Projection Filtering
119 A technique for modeling shadowing of light passing through translucent
120 surfaces, allowing stained glass windows and other effects to be done more
121 elegantly than possible with Light Cubemap Filtering by applying an occluder
122 texture to the lighting combined with a stencil light volume to limit the lit
123 area, this technique is used by Doom3 for spotlights and flashlights, among
124 other things, this can also be used more generally to render light passing
125 through multiple translucent occluders in a scene (using a light volume to
126 describe the area beyond the occluder, and thus mask off rendering of all
127 other areas).
128
129
130
131 Terminology: Doom3 Lighting
132 A combination of Stencil Shadow Volume, Per Pixel Lighting, Normalization
133 CubeMap, 2D+1D Attenuation Texturing, and Light Projection Filtering, as
134 demonstrated by the game Doom3.
135 */
136
137 #include "quakedef.h"
138 #include "r_shadow.h"
139 #include "cl_collision.h"
140 #include "portals.h"
141 #include "image.h"
142
143 extern void R_Shadow_EditLights_Init(void);
144
145 typedef enum r_shadow_rendermode_e
146 {
147         R_SHADOW_RENDERMODE_NONE,
148         R_SHADOW_RENDERMODE_STENCIL,
149         R_SHADOW_RENDERMODE_STENCILTWOSIDE,
150         R_SHADOW_RENDERMODE_LIGHT_VERTEX,
151         R_SHADOW_RENDERMODE_LIGHT_DOT3,
152         R_SHADOW_RENDERMODE_LIGHT_GLSL,
153         R_SHADOW_RENDERMODE_VISIBLEVOLUMES,
154         R_SHADOW_RENDERMODE_VISIBLELIGHTING,
155 }
156 r_shadow_rendermode_t;
157
158 r_shadow_rendermode_t r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
159 r_shadow_rendermode_t r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_NONE;
160 r_shadow_rendermode_t r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_NONE;
161
162 int maxshadowtriangles;
163 int *shadowelements;
164
165 int maxshadowvertices;
166 float *shadowvertex3f;
167
168 int maxshadowmark;
169 int numshadowmark;
170 int *shadowmark;
171 int *shadowmarklist;
172 int shadowmarkcount;
173
174 int maxvertexupdate;
175 int *vertexupdate;
176 int *vertexremap;
177 int vertexupdatenum;
178
179 int r_shadow_buffer_numleafpvsbytes;
180 unsigned char *r_shadow_buffer_leafpvs;
181 int *r_shadow_buffer_leaflist;
182
183 int r_shadow_buffer_numsurfacepvsbytes;
184 unsigned char *r_shadow_buffer_surfacepvs;
185 int *r_shadow_buffer_surfacelist;
186
187 rtexturepool_t *r_shadow_texturepool;
188 rtexture_t *r_shadow_attenuation2dtexture;
189 rtexture_t *r_shadow_attenuation3dtexture;
190
191 // lights are reloaded when this changes
192 char r_shadow_mapname[MAX_QPATH];
193
194 // used only for light filters (cubemaps)
195 rtexturepool_t *r_shadow_filters_texturepool;
196
197 cvar_t r_shadow_bumpscale_basetexture = {0, "r_shadow_bumpscale_basetexture", "0", "generate fake bumpmaps from diffuse textures at this bumpyness, try 4 to match tenebrae, higher values increase depth, requires r_restart to take effect"};
198 cvar_t r_shadow_bumpscale_bumpmap = {0, "r_shadow_bumpscale_bumpmap", "4", "what magnitude to interpret _bump.tga textures as, higher values increase depth, requires r_restart to take effect"};
199 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
200 cvar_t r_shadow_gloss = {CVAR_SAVE, "r_shadow_gloss", "1", "0 disables gloss (specularity) rendering, 1 uses gloss if textures are found, 2 forces a flat metallic specular effect on everything without textures (similar to tenebrae)"};
201 cvar_t r_shadow_gloss2intensity = {0, "r_shadow_gloss2intensity", "0.25", "how bright the forced flat gloss should look if r_shadow_gloss is 2"};
202 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
203 cvar_t r_shadow_lightattenuationpower = {0, "r_shadow_lightattenuationpower", "0.5", "changes attenuation texture generation (does not affect r_glsl lighting)"};
204 cvar_t r_shadow_lightattenuationscale = {0, "r_shadow_lightattenuationscale", "1", "changes attenuation texture generation (does not affect r_glsl lighting)"};
205 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
206 cvar_t r_shadow_portallight = {0, "r_shadow_portallight", "1", "use portal culling to exactly determine lit triangles when compiling world lights"};
207 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "1000000", "how far to cast shadows"};
208 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
209 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
210 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal culling optimizations on dynamic lights (slow!  you probably don't want this!)"};
211 cvar_t r_shadow_realtime_world = {CVAR_SAVE, "r_shadow_realtime_world", "0", "enables rendering of full world lighting (whether loaded from the map, or a .rtlights file, or a .ent file, or a .lights file produced by hlight)"};
212 cvar_t r_shadow_realtime_world_dlightshadows = {CVAR_SAVE, "r_shadow_realtime_world_dlightshadows", "1", "enables shadows from dynamic lights when using full world lighting"};
213 cvar_t r_shadow_realtime_world_lightmaps = {CVAR_SAVE, "r_shadow_realtime_world_lightmaps", "0", "brightness to render lightmaps when using full world lighting, try 0.5 for a tenebrae-like appearance"};
214 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
215 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
216 cvar_t r_shadow_realtime_world_compileshadow = {0, "r_shadow_realtime_world_compileshadow", "1", "enables compilation of shadows from world lights for higher performance rendering"};
217 cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1", "use scissor optimization of light rendering (restricts rendering to the portion of the screen affected by the light)"};
218 cvar_t r_shadow_shadow_polygonfactor = {0, "r_shadow_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
219 cvar_t r_shadow_shadow_polygonoffset = {0, "r_shadow_shadow_polygonoffset", "1", "how much to push shadow volumes into the distance when rendering, to reduce chances of zfighting artifacts (should not be less than 0)"};
220 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect r_glsl lighting)"};
221 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
222 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
223 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
224 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
225 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
226 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
227 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
228
229 float r_shadow_attenpower, r_shadow_attenscale;
230
231 rtlight_t *r_shadow_compilingrtlight;
232 dlight_t *r_shadow_worldlightchain;
233 dlight_t *r_shadow_selectedlight;
234 dlight_t r_shadow_bufferlight;
235 vec3_t r_editlights_cursorlocation;
236
237 extern int con_vislines;
238
239 typedef struct cubemapinfo_s
240 {
241         char basename[64];
242         rtexture_t *texture;
243 }
244 cubemapinfo_t;
245
246 #define MAX_CUBEMAPS 256
247 static int numcubemaps;
248 static cubemapinfo_t cubemaps[MAX_CUBEMAPS];
249
250 void R_Shadow_UncompileWorldLights(void);
251 void R_Shadow_ClearWorldLights(void);
252 void R_Shadow_SaveWorldLights(void);
253 void R_Shadow_LoadWorldLights(void);
254 void R_Shadow_LoadLightsFile(void);
255 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
256 void R_Shadow_EditLights_Reload_f(void);
257 void R_Shadow_ValidateCvars(void);
258 static void R_Shadow_MakeTextures(void);
259 void R_Shadow_DrawWorldLightShadowVolume(matrix4x4_t *matrix, dlight_t *light);
260
261 void r_shadow_start(void)
262 {
263         // allocate vertex processing arrays
264         numcubemaps = 0;
265         r_shadow_attenuation2dtexture = NULL;
266         r_shadow_attenuation3dtexture = NULL;
267         r_shadow_texturepool = NULL;
268         r_shadow_filters_texturepool = NULL;
269         R_Shadow_ValidateCvars();
270         R_Shadow_MakeTextures();
271         maxshadowtriangles = 0;
272         shadowelements = NULL;
273         maxshadowvertices = 0;
274         shadowvertex3f = NULL;
275         maxvertexupdate = 0;
276         vertexupdate = NULL;
277         vertexremap = NULL;
278         vertexupdatenum = 0;
279         maxshadowmark = 0;
280         numshadowmark = 0;
281         shadowmark = NULL;
282         shadowmarklist = NULL;
283         shadowmarkcount = 0;
284         r_shadow_buffer_numleafpvsbytes = 0;
285         r_shadow_buffer_leafpvs = NULL;
286         r_shadow_buffer_leaflist = NULL;
287         r_shadow_buffer_numsurfacepvsbytes = 0;
288         r_shadow_buffer_surfacepvs = NULL;
289         r_shadow_buffer_surfacelist = NULL;
290 }
291
292 void r_shadow_shutdown(void)
293 {
294         R_Shadow_UncompileWorldLights();
295         numcubemaps = 0;
296         r_shadow_attenuation2dtexture = NULL;
297         r_shadow_attenuation3dtexture = NULL;
298         R_FreeTexturePool(&r_shadow_texturepool);
299         R_FreeTexturePool(&r_shadow_filters_texturepool);
300         maxshadowtriangles = 0;
301         if (shadowelements)
302                 Mem_Free(shadowelements);
303         shadowelements = NULL;
304         if (shadowvertex3f)
305                 Mem_Free(shadowvertex3f);
306         shadowvertex3f = NULL;
307         maxvertexupdate = 0;
308         if (vertexupdate)
309                 Mem_Free(vertexupdate);
310         vertexupdate = NULL;
311         if (vertexremap)
312                 Mem_Free(vertexremap);
313         vertexremap = NULL;
314         vertexupdatenum = 0;
315         maxshadowmark = 0;
316         numshadowmark = 0;
317         if (shadowmark)
318                 Mem_Free(shadowmark);
319         shadowmark = NULL;
320         if (shadowmarklist)
321                 Mem_Free(shadowmarklist);
322         shadowmarklist = NULL;
323         shadowmarkcount = 0;
324         r_shadow_buffer_numleafpvsbytes = 0;
325         if (r_shadow_buffer_leafpvs)
326                 Mem_Free(r_shadow_buffer_leafpvs);
327         r_shadow_buffer_leafpvs = NULL;
328         if (r_shadow_buffer_leaflist)
329                 Mem_Free(r_shadow_buffer_leaflist);
330         r_shadow_buffer_leaflist = NULL;
331         r_shadow_buffer_numsurfacepvsbytes = 0;
332         if (r_shadow_buffer_surfacepvs)
333                 Mem_Free(r_shadow_buffer_surfacepvs);
334         r_shadow_buffer_surfacepvs = NULL;
335         if (r_shadow_buffer_surfacelist)
336                 Mem_Free(r_shadow_buffer_surfacelist);
337         r_shadow_buffer_surfacelist = NULL;
338 }
339
340 void r_shadow_newmap(void)
341 {
342 }
343
344 void R_Shadow_Help_f(void)
345 {
346         Con_Printf(
347 "Documentation on r_shadow system:\n"
348 "Settings:\n"
349 "r_shadow_bumpscale_basetexture : base texture as bumpmap with this scale\n"
350 "r_shadow_bumpscale_bumpmap : depth scale for bumpmap conversion\n"
351 "r_shadow_debuglight : render only this light number (-1 = all)\n"
352 "r_shadow_gloss 0/1/2 : no gloss, gloss textures only, force gloss\n"
353 "r_shadow_gloss2intensity : brightness of forced gloss\n"
354 "r_shadow_glossintensity : brightness of textured gloss\n"
355 "r_shadow_lightattenuationpower : used to generate attenuation texture\n"
356 "r_shadow_lightattenuationscale : used to generate attenuation texture\n"
357 "r_shadow_lightintensityscale : scale rendering brightness of all lights\n"
358 "r_shadow_portallight : use portal visibility for static light precomputation\n"
359 "r_shadow_projectdistance : shadow volume projection distance\n"
360 "r_shadow_realtime_dlight : use high quality dynamic lights in normal mode\n"
361 "r_shadow_realtime_dlight_shadows : cast shadows from dlights\n"
362 "r_shadow_realtime_dlight_portalculling : work hard to reduce graphics work\n"
363 "r_shadow_realtime_world : use high quality world lighting mode\n"
364 "r_shadow_realtime_world_dlightshadows : cast shadows from dlights\n"
365 "r_shadow_realtime_world_lightmaps : use lightmaps in addition to lights\n"
366 "r_shadow_realtime_world_shadows : cast shadows from world lights\n"
367 "r_shadow_realtime_world_compile : compile surface/visibility information\n"
368 "r_shadow_realtime_world_compileshadow : compile shadow geometry\n"
369 "r_shadow_scissor : use scissor optimization\n"
370 "r_shadow_shadow_polygonfactor : nudge shadow volumes closer/further\n"
371 "r_shadow_shadow_polygonoffset : nudge shadow volumes closer/further\n"
372 "r_shadow_texture3d : use 3d attenuation texture (if hardware supports)\n"
373 "r_showlighting : useful for performance testing; bright = slow!\n"
374 "r_showshadowvolumes : useful for performance testing; bright = slow!\n"
375 "Commands:\n"
376 "r_shadow_help : this help\n"
377         );
378 }
379
380 void R_Shadow_Init(void)
381 {
382         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
383         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
384         Cvar_RegisterVariable(&r_shadow_debuglight);
385         Cvar_RegisterVariable(&r_shadow_gloss);
386         Cvar_RegisterVariable(&r_shadow_gloss2intensity);
387         Cvar_RegisterVariable(&r_shadow_glossintensity);
388         Cvar_RegisterVariable(&r_shadow_lightattenuationpower);
389         Cvar_RegisterVariable(&r_shadow_lightattenuationscale);
390         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
391         Cvar_RegisterVariable(&r_shadow_portallight);
392         Cvar_RegisterVariable(&r_shadow_projectdistance);
393         Cvar_RegisterVariable(&r_shadow_realtime_dlight);
394         Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
395         Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
396         Cvar_RegisterVariable(&r_shadow_realtime_world);
397         Cvar_RegisterVariable(&r_shadow_realtime_world_dlightshadows);
398         Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
399         Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
400         Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
401         Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
402         Cvar_RegisterVariable(&r_shadow_scissor);
403         Cvar_RegisterVariable(&r_shadow_shadow_polygonfactor);
404         Cvar_RegisterVariable(&r_shadow_shadow_polygonoffset);
405         Cvar_RegisterVariable(&r_shadow_texture3d);
406         Cvar_RegisterVariable(&gl_ext_stenciltwoside);
407         if (gamemode == GAME_TENEBRAE)
408         {
409                 Cvar_SetValue("r_shadow_gloss", 2);
410                 Cvar_SetValue("r_shadow_bumpscale_basetexture", 4);
411         }
412         Cmd_AddCommand("r_shadow_help", R_Shadow_Help_f, "prints documentation on console commands and variables used by realtime lighting and shadowing system");
413         R_Shadow_EditLights_Init();
414         r_shadow_worldlightchain = NULL;
415         maxshadowtriangles = 0;
416         shadowelements = NULL;
417         maxshadowvertices = 0;
418         shadowvertex3f = NULL;
419         maxvertexupdate = 0;
420         vertexupdate = NULL;
421         vertexremap = NULL;
422         vertexupdatenum = 0;
423         maxshadowmark = 0;
424         numshadowmark = 0;
425         shadowmark = NULL;
426         shadowmarklist = NULL;
427         shadowmarkcount = 0;
428         r_shadow_buffer_numleafpvsbytes = 0;
429         r_shadow_buffer_leafpvs = NULL;
430         r_shadow_buffer_leaflist = NULL;
431         r_shadow_buffer_numsurfacepvsbytes = 0;
432         r_shadow_buffer_surfacepvs = NULL;
433         r_shadow_buffer_surfacelist = NULL;
434         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap);
435 }
436
437 matrix4x4_t matrix_attenuationxyz =
438 {
439         {
440                 {0.5, 0.0, 0.0, 0.5},
441                 {0.0, 0.5, 0.0, 0.5},
442                 {0.0, 0.0, 0.5, 0.5},
443                 {0.0, 0.0, 0.0, 1.0}
444         }
445 };
446
447 matrix4x4_t matrix_attenuationz =
448 {
449         {
450                 {0.0, 0.0, 0.5, 0.5},
451                 {0.0, 0.0, 0.0, 0.5},
452                 {0.0, 0.0, 0.0, 0.5},
453                 {0.0, 0.0, 0.0, 1.0}
454         }
455 };
456
457 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles)
458 {
459         // make sure shadowelements is big enough for this volume
460         if (maxshadowtriangles < numtriangles)
461         {
462                 maxshadowtriangles = numtriangles;
463                 if (shadowelements)
464                         Mem_Free(shadowelements);
465                 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[24]));
466         }
467         // make sure shadowvertex3f is big enough for this volume
468         if (maxshadowvertices < numvertices)
469         {
470                 maxshadowvertices = numvertices;
471                 if (shadowvertex3f)
472                         Mem_Free(shadowvertex3f);
473                 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[6]));
474         }
475 }
476
477 static void R_Shadow_EnlargeLeafSurfaceBuffer(int numleafs, int numsurfaces)
478 {
479         int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
480         int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
481         if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
482         {
483                 if (r_shadow_buffer_leafpvs)
484                         Mem_Free(r_shadow_buffer_leafpvs);
485                 if (r_shadow_buffer_leaflist)
486                         Mem_Free(r_shadow_buffer_leaflist);
487                 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
488                 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
489                 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
490         }
491         if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
492         {
493                 if (r_shadow_buffer_surfacepvs)
494                         Mem_Free(r_shadow_buffer_surfacepvs);
495                 if (r_shadow_buffer_surfacelist)
496                         Mem_Free(r_shadow_buffer_surfacelist);
497                 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
498                 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
499                 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
500         }
501 }
502
503 void R_Shadow_PrepareShadowMark(int numtris)
504 {
505         // make sure shadowmark is big enough for this volume
506         if (maxshadowmark < numtris)
507         {
508                 maxshadowmark = numtris;
509                 if (shadowmark)
510                         Mem_Free(shadowmark);
511                 if (shadowmarklist)
512                         Mem_Free(shadowmarklist);
513                 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
514                 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
515                 shadowmarkcount = 0;
516         }
517         shadowmarkcount++;
518         // if shadowmarkcount wrapped we clear the array and adjust accordingly
519         if (shadowmarkcount == 0)
520         {
521                 shadowmarkcount = 1;
522                 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
523         }
524         numshadowmark = 0;
525 }
526
527 int R_Shadow_ConstructShadowVolume(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
528 {
529         int i, j;
530         int outtriangles = 0, outvertices = 0;
531         const int *element;
532         const float *vertex;
533
534         if (maxvertexupdate < innumvertices)
535         {
536                 maxvertexupdate = innumvertices;
537                 if (vertexupdate)
538                         Mem_Free(vertexupdate);
539                 if (vertexremap)
540                         Mem_Free(vertexremap);
541                 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
542                 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
543                 vertexupdatenum = 0;
544         }
545         vertexupdatenum++;
546         if (vertexupdatenum == 0)
547         {
548                 vertexupdatenum = 1;
549                 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
550                 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
551         }
552
553         for (i = 0;i < numshadowmarktris;i++)
554                 shadowmark[shadowmarktris[i]] = shadowmarkcount;
555
556         for (i = 0;i < numshadowmarktris;i++)
557         {
558                 element = inelement3i + shadowmarktris[i] * 3;
559                 // make sure the vertices are created
560                 for (j = 0;j < 3;j++)
561                 {
562                         if (vertexupdate[element[j]] != vertexupdatenum)
563                         {
564                                 float ratio, direction[3];
565                                 vertexupdate[element[j]] = vertexupdatenum;
566                                 vertexremap[element[j]] = outvertices;
567                                 vertex = invertex3f + element[j] * 3;
568                                 // project one copy of the vertex to the sphere radius of the light
569                                 // (FIXME: would projecting it to the light box be better?)
570                                 VectorSubtract(vertex, projectorigin, direction);
571                                 ratio = projectdistance / VectorLength(direction);
572                                 VectorCopy(vertex, outvertex3f);
573                                 VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
574                                 outvertex3f += 6;
575                                 outvertices += 2;
576                         }
577                 }
578         }
579
580         for (i = 0;i < numshadowmarktris;i++)
581         {
582                 int remappedelement[3];
583                 int markindex;
584                 const int *neighbortriangle;
585
586                 markindex = shadowmarktris[i] * 3;
587                 element = inelement3i + markindex;
588                 neighbortriangle = inneighbor3i + markindex;
589                 // output the front and back triangles
590                 outelement3i[0] = vertexremap[element[0]];
591                 outelement3i[1] = vertexremap[element[1]];
592                 outelement3i[2] = vertexremap[element[2]];
593                 outelement3i[3] = vertexremap[element[2]] + 1;
594                 outelement3i[4] = vertexremap[element[1]] + 1;
595                 outelement3i[5] = vertexremap[element[0]] + 1;
596
597                 outelement3i += 6;
598                 outtriangles += 2;
599                 // output the sides (facing outward from this triangle)
600                 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
601                 {
602                         remappedelement[0] = vertexremap[element[0]];
603                         remappedelement[1] = vertexremap[element[1]];
604                         outelement3i[0] = remappedelement[1];
605                         outelement3i[1] = remappedelement[0];
606                         outelement3i[2] = remappedelement[0] + 1;
607                         outelement3i[3] = remappedelement[1];
608                         outelement3i[4] = remappedelement[0] + 1;
609                         outelement3i[5] = remappedelement[1] + 1;
610
611                         outelement3i += 6;
612                         outtriangles += 2;
613                 }
614                 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
615                 {
616                         remappedelement[1] = vertexremap[element[1]];
617                         remappedelement[2] = vertexremap[element[2]];
618                         outelement3i[0] = remappedelement[2];
619                         outelement3i[1] = remappedelement[1];
620                         outelement3i[2] = remappedelement[1] + 1;
621                         outelement3i[3] = remappedelement[2];
622                         outelement3i[4] = remappedelement[1] + 1;
623                         outelement3i[5] = remappedelement[2] + 1;
624
625                         outelement3i += 6;
626                         outtriangles += 2;
627                 }
628                 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
629                 {
630                         remappedelement[0] = vertexremap[element[0]];
631                         remappedelement[2] = vertexremap[element[2]];
632                         outelement3i[0] = remappedelement[0];
633                         outelement3i[1] = remappedelement[2];
634                         outelement3i[2] = remappedelement[2] + 1;
635                         outelement3i[3] = remappedelement[0];
636                         outelement3i[4] = remappedelement[2] + 1;
637                         outelement3i[5] = remappedelement[0] + 1;
638
639                         outelement3i += 6;
640                         outtriangles += 2;
641                 }
642         }
643         if (outnumvertices)
644                 *outnumvertices = outvertices;
645         return outtriangles;
646 }
647
648 void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, const int *elements, const int *neighbors, const vec3_t projectorigin, float projectdistance, int nummarktris, const int *marktris)
649 {
650         int tris, outverts;
651         if (projectdistance < 0.1)
652         {
653                 Con_Printf("R_Shadow_Volume: projectdistance %f\n");
654                 return;
655         }
656         if (!numverts || !nummarktris)
657                 return;
658         // make sure shadowelements is big enough for this volume
659         if (maxshadowtriangles < nummarktris || maxshadowvertices < numverts)
660                 R_Shadow_ResizeShadowArrays((numverts + 255) & ~255, (nummarktris + 255) & ~255);
661         tris = R_Shadow_ConstructShadowVolume(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdistance, nummarktris, marktris);
662         r_refdef.stats.lights_dynamicshadowtriangles += tris;
663         R_Shadow_RenderVolume(outverts, tris, shadowvertex3f, shadowelements);
664 }
665
666 void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const vec3_t projectorigin, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs)
667 {
668         int t, tend;
669         const int *e;
670         const float *v[3];
671         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
672                 return;
673         tend = firsttriangle + numtris;
674         if (surfacemins[0] >= lightmins[0] && surfacemaxs[0] <= lightmaxs[0]
675          && surfacemins[1] >= lightmins[1] && surfacemaxs[1] <= lightmaxs[1]
676          && surfacemins[2] >= lightmins[2] && surfacemaxs[2] <= lightmaxs[2])
677         {
678                 // surface box entirely inside light box, no box cull
679                 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
680                         if (PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
681                                 shadowmarklist[numshadowmark++] = t;
682         }
683         else
684         {
685                 // surface box not entirely inside light box, cull each triangle
686                 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
687                 {
688                         v[0] = invertex3f + e[0] * 3;
689                         v[1] = invertex3f + e[1] * 3;
690                         v[2] = invertex3f + e[2] * 3;
691                         if (PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
692                          && lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0]))
693                          && lightmins[0] < max(v[0][0], max(v[1][0], v[2][0]))
694                          && lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1]))
695                          && lightmins[1] < max(v[0][1], max(v[1][1], v[2][1]))
696                          && lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2]))
697                          && lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
698                                 shadowmarklist[numshadowmark++] = t;
699                 }
700         }
701 }
702
703 void R_Shadow_RenderVolume(int numvertices, int numtriangles, const float *vertex3f, const int *element3i)
704 {
705         if (r_shadow_compilingrtlight)
706         {
707                 // if we're compiling an rtlight, capture the mesh
708                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, numtriangles, element3i);
709                 return;
710         }
711         r_refdef.stats.lights_shadowtriangles += numtriangles;
712         CHECKGLERROR
713         R_Mesh_VertexPointer(vertex3f);
714         GL_LockArrays(0, numvertices);
715         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCIL)
716         {
717                 // decrement stencil if backface is behind depthbuffer
718                 qglCullFace(GL_BACK);CHECKGLERROR // quake is backwards, this culls front faces
719                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
720                 R_Mesh_Draw(0, numvertices, numtriangles, element3i);
721                 // increment stencil if frontface is behind depthbuffer
722                 qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
723                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
724         }
725         R_Mesh_Draw(0, numvertices, numtriangles, element3i);
726         GL_LockArrays(0, 0);
727         CHECKGLERROR
728 }
729
730 static void R_Shadow_MakeTextures(void)
731 {
732         int x, y, z, d;
733         float v[3], intensity;
734         unsigned char *data;
735         R_FreeTexturePool(&r_shadow_texturepool);
736         r_shadow_texturepool = R_AllocTexturePool();
737         r_shadow_attenpower = r_shadow_lightattenuationpower.value;
738         r_shadow_attenscale = r_shadow_lightattenuationscale.value;
739 #define ATTEN2DSIZE 64
740 #define ATTEN3DSIZE 32
741         data = (unsigned char *)Mem_Alloc(tempmempool, max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE*4, ATTEN2DSIZE*ATTEN2DSIZE*4));
742         for (y = 0;y < ATTEN2DSIZE;y++)
743         {
744                 for (x = 0;x < ATTEN2DSIZE;x++)
745                 {
746                         v[0] = ((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375);
747                         v[1] = ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375);
748                         v[2] = 0;
749                         intensity = 1.0f - sqrt(DotProduct(v, v));
750                         if (intensity > 0)
751                                 intensity = pow(intensity, r_shadow_attenpower) * r_shadow_attenscale * 256.0f;
752                         d = (int)bound(0, intensity, 255);
753                         data[(y*ATTEN2DSIZE+x)*4+0] = d;
754                         data[(y*ATTEN2DSIZE+x)*4+1] = d;
755                         data[(y*ATTEN2DSIZE+x)*4+2] = d;
756                         data[(y*ATTEN2DSIZE+x)*4+3] = d;
757                 }
758         }
759         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
760         if (r_shadow_texture3d.integer && gl_texture3d)
761         {
762                 for (z = 0;z < ATTEN3DSIZE;z++)
763                 {
764                         for (y = 0;y < ATTEN3DSIZE;y++)
765                         {
766                                 for (x = 0;x < ATTEN3DSIZE;x++)
767                                 {
768                                         v[0] = ((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
769                                         v[1] = ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
770                                         v[2] = ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
771                                         intensity = 1.0f - sqrt(DotProduct(v, v));
772                                         if (intensity > 0)
773                                                 intensity = pow(intensity, r_shadow_attenpower) * r_shadow_attenscale * 256.0f;
774                                         d = (int)bound(0, intensity, 255);
775                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+0] = d;
776                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+1] = d;
777                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+2] = d;
778                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+3] = d;
779                                 }
780                         }
781                 }
782                 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
783         }
784         Mem_Free(data);
785 }
786
787 void R_Shadow_ValidateCvars(void)
788 {
789         if (r_shadow_texture3d.integer && !gl_texture3d)
790                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
791         if (gl_ext_stenciltwoside.integer && !gl_support_stenciltwoside)
792                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
793 }
794
795 // light currently being rendered
796 rtlight_t *r_shadow_rtlight;
797
798 // this is the location of the light in entity space
799 vec3_t r_shadow_entitylightorigin;
800 // this transforms entity coordinates to light filter cubemap coordinates
801 // (also often used for other purposes)
802 matrix4x4_t r_shadow_entitytolight;
803 // based on entitytolight this transforms -1 to +1 to 0 to 1 for purposes
804 // of attenuation texturing in full 3D (Z result often ignored)
805 matrix4x4_t r_shadow_entitytoattenuationxyz;
806 // this transforms only the Z to S, and T is always 0.5
807 matrix4x4_t r_shadow_entitytoattenuationz;
808
809 void R_Shadow_RenderMode_Begin(void)
810 {
811         R_Shadow_ValidateCvars();
812
813         if (!r_shadow_attenuation2dtexture
814          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
815          || r_shadow_lightattenuationpower.value != r_shadow_attenpower
816          || r_shadow_lightattenuationscale.value != r_shadow_attenscale)
817                 R_Shadow_MakeTextures();
818
819         CHECKGLERROR
820         R_Mesh_ColorPointer(NULL);
821         R_Mesh_ResetTextureState();
822         GL_BlendFunc(GL_ONE, GL_ZERO);
823         GL_DepthMask(false);
824         GL_DepthTest(true);
825         GL_Color(0, 0, 0, 1);
826         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
827         qglEnable(GL_CULL_FACE);CHECKGLERROR
828         GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
829
830         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
831
832         if (gl_ext_stenciltwoside.integer)
833                 r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCILTWOSIDE;
834         else
835                 r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCIL;
836
837         if (r_glsl.integer && gl_support_fragment_shader)
838                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
839         else if (gl_dot3arb && gl_texturecubemap && r_textureunits.integer >= 2 && gl_combine.integer && gl_stencil)
840                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_DOT3;
841         else
842                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
843 }
844
845 void R_Shadow_RenderMode_ActiveLight(rtlight_t *rtlight)
846 {
847         r_shadow_rtlight = rtlight;
848 }
849
850 void R_Shadow_RenderMode_Reset(void)
851 {
852         CHECKGLERROR
853         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
854         {
855                 qglUseProgramObjectARB(0);CHECKGLERROR
856         }
857         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCILTWOSIDE)
858         {
859                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
860         }
861         R_Mesh_ColorPointer(NULL);
862         R_Mesh_ResetTextureState();
863 }
864
865 void R_Shadow_RenderMode_StencilShadowVolumes(void)
866 {
867         CHECKGLERROR
868         R_Shadow_RenderMode_Reset();
869         GL_Color(1, 1, 1, 1);
870         GL_ColorMask(0, 0, 0, 0);
871         GL_BlendFunc(GL_ONE, GL_ZERO);
872         GL_DepthMask(false);
873         GL_DepthTest(true);
874         qglPolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
875         qglDepthFunc(GL_LESS);CHECKGLERROR
876         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
877         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
878         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
879         r_shadow_rendermode = r_shadow_shadowingrendermode;
880         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCILTWOSIDE)
881         {
882                 qglDisable(GL_CULL_FACE);CHECKGLERROR
883                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
884                 qglActiveStencilFaceEXT(GL_BACK);CHECKGLERROR // quake is backwards, this is front faces
885                 qglStencilMask(~0);CHECKGLERROR
886                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
887                 qglActiveStencilFaceEXT(GL_FRONT);CHECKGLERROR // quake is backwards, this is back faces
888                 qglStencilMask(~0);CHECKGLERROR
889                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
890         }
891         else
892         {
893                 qglEnable(GL_CULL_FACE);CHECKGLERROR
894                 qglStencilMask(~0);CHECKGLERROR
895                 // this is changed by every shadow render so its value here is unimportant
896                 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
897         }
898         GL_Clear(GL_STENCIL_BUFFER_BIT);
899         r_refdef.stats.lights_clears++;
900 }
901
902 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent)
903 {
904         CHECKGLERROR
905         R_Shadow_RenderMode_Reset();
906         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
907         GL_DepthMask(false);
908         GL_DepthTest(true);
909         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
910         //qglDisable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
911         GL_Color(1, 1, 1, 1);
912         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
913         if (transparent)
914         {
915                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
916         }
917         else
918         {
919                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
920         }
921         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
922         qglEnable(GL_CULL_FACE);CHECKGLERROR
923         if (stenciltest)
924         {
925                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
926         }
927         else
928         {
929                 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
930         }
931         qglStencilMask(~0);CHECKGLERROR
932         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
933         // only draw light where this geometry was already rendered AND the
934         // stencil is 128 (values other than this mean shadow)
935         qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR
936         r_shadow_rendermode = r_shadow_lightingrendermode;
937         // do global setup needed for the chosen lighting mode
938         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
939         {
940                 R_Mesh_TexBind(0, R_GetTexture(r_texture_blanknormalmap)); // normal
941                 R_Mesh_TexBind(1, R_GetTexture(r_texture_white)); // diffuse
942                 R_Mesh_TexBind(2, R_GetTexture(r_texture_white)); // gloss
943                 R_Mesh_TexBindCubeMap(3, R_GetTexture(r_shadow_rtlight->currentcubemap)); // light filter
944                 R_Mesh_TexBind(4, R_GetTexture(r_texture_fogattenuation)); // fog
945                 R_Mesh_TexBind(5, R_GetTexture(r_texture_white)); // pants
946                 R_Mesh_TexBind(6, R_GetTexture(r_texture_white)); // shirt
947                 R_Mesh_TexBind(7, R_GetTexture(r_texture_white)); // lightmap
948                 R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap)); // deluxemap
949                 R_Mesh_TexBind(9, R_GetTexture(r_texture_black)); // glow
950                 //R_Mesh_TexMatrix(3, r_shadow_entitytolight); // light filter matrix
951                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
952                 GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 0);
953                 CHECKGLERROR
954         }
955 }
956
957 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
958 {
959         CHECKGLERROR
960         R_Shadow_RenderMode_Reset();
961         GL_BlendFunc(GL_ONE, GL_ONE);
962         GL_DepthMask(false);
963         GL_DepthTest(!r_showdisabledepthtest.integer);
964         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
965         GL_Color(0.0, 0.0125 * r_view.colorscale, 0.1 * r_view.colorscale, 1);
966         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
967         qglDepthFunc(GL_GEQUAL);CHECKGLERROR
968         qglCullFace(GL_FRONT);CHECKGLERROR // this culls back
969         qglDisable(GL_CULL_FACE);CHECKGLERROR
970         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
971         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
972 }
973
974 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
975 {
976         CHECKGLERROR
977         R_Shadow_RenderMode_Reset();
978         GL_BlendFunc(GL_ONE, GL_ONE);
979         GL_DepthMask(false);
980         GL_DepthTest(!r_showdisabledepthtest.integer);
981         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
982         GL_Color(0.1 * r_view.colorscale, 0.0125 * r_view.colorscale, 0, 1);
983         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
984         if (transparent)
985         {
986                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
987         }
988         else
989         {
990                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
991         }
992         qglCullFace(GL_FRONT);CHECKGLERROR // this culls back
993         qglEnable(GL_CULL_FACE);CHECKGLERROR
994         if (stenciltest)
995         {
996                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
997         }
998         else
999         {
1000                 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1001         }
1002         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
1003 }
1004
1005 void R_Shadow_RenderMode_End(void)
1006 {
1007         CHECKGLERROR
1008         R_Shadow_RenderMode_Reset();
1009         R_Shadow_RenderMode_ActiveLight(NULL);
1010         GL_BlendFunc(GL_ONE, GL_ZERO);
1011         GL_DepthMask(true);
1012         GL_DepthTest(true);
1013         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
1014         //qglDisable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
1015         GL_Color(1, 1, 1, 1);
1016         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
1017         GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
1018         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1019         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
1020         qglEnable(GL_CULL_FACE);CHECKGLERROR
1021         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1022         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
1023         if (gl_support_stenciltwoside)
1024         {
1025                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1026         }
1027         qglStencilMask(~0);CHECKGLERROR
1028         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
1029         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1030 }
1031
1032 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
1033 {
1034         int i, ix1, iy1, ix2, iy2;
1035         float x1, y1, x2, y2;
1036         vec4_t v, v2;
1037         rmesh_t mesh;
1038         mplane_t planes[11];
1039         float vertex3f[256*3];
1040
1041         // if view is inside the light box, just say yes it's visible
1042         if (BoxesOverlap(r_view.origin, r_view.origin, mins, maxs))
1043         {
1044                 GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
1045                 return false;
1046         }
1047
1048         // create a temporary brush describing the area the light can affect in worldspace
1049         VectorNegate(r_view.frustum[0].normal, planes[ 0].normal);planes[ 0].dist = -r_view.frustum[0].dist;
1050         VectorNegate(r_view.frustum[1].normal, planes[ 1].normal);planes[ 1].dist = -r_view.frustum[1].dist;
1051         VectorNegate(r_view.frustum[2].normal, planes[ 2].normal);planes[ 2].dist = -r_view.frustum[2].dist;
1052         VectorNegate(r_view.frustum[3].normal, planes[ 3].normal);planes[ 3].dist = -r_view.frustum[3].dist;
1053         VectorNegate(r_view.frustum[4].normal, planes[ 4].normal);planes[ 4].dist = -r_view.frustum[4].dist;
1054         VectorSet   (planes[ 5].normal,  1, 0, 0);         planes[ 5].dist =  maxs[0];
1055         VectorSet   (planes[ 6].normal, -1, 0, 0);         planes[ 6].dist = -mins[0];
1056         VectorSet   (planes[ 7].normal, 0,  1, 0);         planes[ 7].dist =  maxs[1];
1057         VectorSet   (planes[ 8].normal, 0, -1, 0);         planes[ 8].dist = -mins[1];
1058         VectorSet   (planes[ 9].normal, 0, 0,  1);         planes[ 9].dist =  maxs[2];
1059         VectorSet   (planes[10].normal, 0, 0, -1);         planes[10].dist = -mins[2];
1060
1061         // turn the brush into a mesh
1062         memset(&mesh, 0, sizeof(rmesh_t));
1063         mesh.maxvertices = 256;
1064         mesh.vertex3f = vertex3f;
1065         mesh.epsilon2 = (1.0f / (32.0f * 32.0f));
1066         R_Mesh_AddBrushMeshFromPlanes(&mesh, 11, planes);
1067
1068         // if that mesh is empty, the light is not visible at all
1069         if (!mesh.numvertices)
1070                 return true;
1071
1072         if (!r_shadow_scissor.integer)
1073                 return false;
1074
1075         // if that mesh is not empty, check what area of the screen it covers
1076         x1 = y1 = x2 = y2 = 0;
1077         v[3] = 1.0f;
1078         //Con_Printf("%i vertices to transform...\n", mesh.numvertices);
1079         for (i = 0;i < mesh.numvertices;i++)
1080         {
1081                 VectorCopy(mesh.vertex3f + i * 3, v);
1082                 GL_TransformToScreen(v, v2);
1083                 //Con_Printf("%.3f %.3f %.3f %.3f transformed to %.3f %.3f %.3f %.3f\n", v[0], v[1], v[2], v[3], v2[0], v2[1], v2[2], v2[3]);
1084                 if (i)
1085                 {
1086                         if (x1 > v2[0]) x1 = v2[0];
1087                         if (x2 < v2[0]) x2 = v2[0];
1088                         if (y1 > v2[1]) y1 = v2[1];
1089                         if (y2 < v2[1]) y2 = v2[1];
1090                 }
1091                 else
1092                 {
1093                         x1 = x2 = v2[0];
1094                         y1 = y2 = v2[1];
1095                 }
1096         }
1097
1098         // now convert the scissor rectangle to integer screen coordinates
1099         ix1 = (int)(x1 - 1.0f);
1100         iy1 = (int)(y1 - 1.0f);
1101         ix2 = (int)(x2 + 1.0f);
1102         iy2 = (int)(y2 + 1.0f);
1103         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
1104
1105         // clamp it to the screen
1106         if (ix1 < r_view.x) ix1 = r_view.x;
1107         if (iy1 < r_view.y) iy1 = r_view.y;
1108         if (ix2 > r_view.x + r_view.width) ix2 = r_view.x + r_view.width;
1109         if (iy2 > r_view.y + r_view.height) iy2 = r_view.y + r_view.height;
1110
1111         // if it is inside out, it's not visible
1112         if (ix2 <= ix1 || iy2 <= iy1)
1113                 return true;
1114
1115         // the light area is visible, set up the scissor rectangle
1116         GL_Scissor(ix1, iy1, ix2 - ix1, iy2 - iy1);
1117         //qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);CHECKGLERROR
1118         //qglEnable(GL_SCISSOR_TEST);CHECKGLERROR
1119         r_refdef.stats.lights_scissored++;
1120         return false;
1121 }
1122
1123 static void R_Shadow_RenderSurfacesLighting_Light_Vertex_Shading(const msurface_t *surface, const float *diffusecolor, const float *ambientcolor)
1124 {
1125         int numverts = surface->num_vertices;
1126         float *vertex3f = rsurface_vertex3f + 3 * surface->num_firstvertex;
1127         float *normal3f = rsurface_normal3f + 3 * surface->num_firstvertex;
1128         float *color4f = rsurface_array_color4f + 4 * surface->num_firstvertex;
1129         float dist, dot, distintensity, shadeintensity, v[3], n[3];
1130         if (r_textureunits.integer >= 3)
1131         {
1132                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1133                 {
1134                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1135                         Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1136                         if ((dot = DotProduct(n, v)) < 0)
1137                         {
1138                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1139                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]);
1140                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]);
1141                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]);
1142                                 if (r_refdef.fogenabled)
1143                                 {
1144                                         float f = VERTEXFOGTABLE(VectorDistance(v, rsurface_modelorg));
1145                                         VectorScale(color4f, f, color4f);
1146                                 }
1147                         }
1148                         else
1149                                 VectorClear(color4f);
1150                         color4f[3] = 1;
1151                 }
1152         }
1153         else if (r_textureunits.integer >= 2)
1154         {
1155                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1156                 {
1157                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1158                         if ((dist = fabs(v[2])) < 1)
1159                         {
1160                                 distintensity = pow(1 - dist, r_shadow_attenpower) * r_shadow_attenscale;
1161                                 Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1162                                 if ((dot = DotProduct(n, v)) < 0)
1163                                 {
1164                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1165                                         color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
1166                                         color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
1167                                         color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
1168                                 }
1169                                 else
1170                                 {
1171                                         color4f[0] = ambientcolor[0] * distintensity;
1172                                         color4f[1] = ambientcolor[1] * distintensity;
1173                                         color4f[2] = ambientcolor[2] * distintensity;
1174                                 }
1175                                 if (r_refdef.fogenabled)
1176                                 {
1177                                         float f = VERTEXFOGTABLE(VectorDistance(v, rsurface_modelorg));
1178                                         VectorScale(color4f, f, color4f);
1179                                 }
1180                         }
1181                         else
1182                                 VectorClear(color4f);
1183                         color4f[3] = 1;
1184                 }
1185         }
1186         else
1187         {
1188                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1189                 {
1190                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1191                         if ((dist = DotProduct(v, v)) < 1)
1192                         {
1193                                 dist = sqrt(dist);
1194                                 distintensity = pow(1 - dist, r_shadow_attenpower) * r_shadow_attenscale;
1195                                 Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1196                                 if ((dot = DotProduct(n, v)) < 0)
1197                                 {
1198                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1199                                         color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
1200                                         color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
1201                                         color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
1202                                 }
1203                                 else
1204                                 {
1205                                         color4f[0] = ambientcolor[0] * distintensity;
1206                                         color4f[1] = ambientcolor[1] * distintensity;
1207                                         color4f[2] = ambientcolor[2] * distintensity;
1208                                 }
1209                                 if (r_refdef.fogenabled)
1210                                 {
1211                                         float f = VERTEXFOGTABLE(VectorDistance(v, rsurface_modelorg));
1212                                         VectorScale(color4f, f, color4f);
1213                                 }
1214                         }
1215                         else
1216                                 VectorClear(color4f);
1217                         color4f[3] = 1;
1218                 }
1219         }
1220 }
1221
1222 // TODO: use glTexGen instead of feeding vertices to texcoordpointer?
1223
1224 static void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(int numsurfaces, msurface_t **surfacelist)
1225 {
1226         int surfacelistindex;
1227         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1228         {
1229                 const msurface_t *surface = surfacelist[surfacelistindex];
1230                 int i;
1231                 float *out3f = rsurface_array_texcoord3f + 3 * surface->num_firstvertex;
1232                 const float *vertex3f = rsurface_vertex3f + 3 * surface->num_firstvertex;
1233                 const float *svector3f = rsurface_svector3f + 3 * surface->num_firstvertex;
1234                 const float *tvector3f = rsurface_tvector3f + 3 * surface->num_firstvertex;
1235                 const float *normal3f = rsurface_normal3f + 3 * surface->num_firstvertex;
1236                 float lightdir[3];
1237                 for (i = 0;i < surface->num_vertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
1238                 {
1239                         VectorSubtract(r_shadow_entitylightorigin, vertex3f, lightdir);
1240                         // the cubemap normalizes this for us
1241                         out3f[0] = DotProduct(svector3f, lightdir);
1242                         out3f[1] = DotProduct(tvector3f, lightdir);
1243                         out3f[2] = DotProduct(normal3f, lightdir);
1244                 }
1245         }
1246 }
1247
1248 static void R_Shadow_GenTexCoords_Specular_NormalCubeMap(int numsurfaces, msurface_t **surfacelist)
1249 {
1250         int surfacelistindex;
1251         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1252         {
1253                 const msurface_t *surface = surfacelist[surfacelistindex];
1254                 int i;
1255                 float *out3f = rsurface_array_texcoord3f + 3 * surface->num_firstvertex;
1256                 const float *vertex3f = rsurface_vertex3f + 3 * surface->num_firstvertex;
1257                 const float *svector3f = rsurface_svector3f + 3 * surface->num_firstvertex;
1258                 const float *tvector3f = rsurface_tvector3f + 3 * surface->num_firstvertex;
1259                 const float *normal3f = rsurface_normal3f + 3 * surface->num_firstvertex;
1260                 float lightdir[3], eyedir[3], halfdir[3];
1261                 for (i = 0;i < surface->num_vertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
1262                 {
1263                         VectorSubtract(r_shadow_entitylightorigin, vertex3f, lightdir);
1264                         VectorNormalize(lightdir);
1265                         VectorSubtract(rsurface_modelorg, vertex3f, eyedir);
1266                         VectorNormalize(eyedir);
1267                         VectorAdd(lightdir, eyedir, halfdir);
1268                         // the cubemap normalizes this for us
1269                         out3f[0] = DotProduct(svector3f, halfdir);
1270                         out3f[1] = DotProduct(tvector3f, halfdir);
1271                         out3f[2] = DotProduct(normal3f, halfdir);
1272                 }
1273         }
1274 }
1275
1276 static void R_Shadow_RenderSurfacesLighting_VisibleLighting(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float specularscale, qboolean dopants, qboolean doshirt)
1277 {
1278         // used to display how many times a surface is lit for level design purposes
1279         GL_Color(0.1 * r_view.colorscale, 0.025 * r_view.colorscale, 0, 1);
1280         R_Mesh_ColorPointer(NULL);
1281         R_Mesh_ResetTextureState();
1282         RSurf_PrepareVerticesForBatch(false, false, numsurfaces, surfacelist);
1283         RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1284         GL_LockArrays(0, 0);
1285 }
1286
1287 static void R_Shadow_RenderSurfacesLighting_Light_GLSL(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float specularscale, qboolean dopants, qboolean doshirt)
1288 {
1289         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
1290         RSurf_PrepareVerticesForBatch(true, true, numsurfaces, surfacelist);
1291         R_SetupSurfaceShader(lightcolorbase, false);
1292         R_Mesh_TexCoordPointer(0, 2, rsurface_model->surfmesh.data_texcoordtexture2f);
1293         R_Mesh_TexCoordPointer(1, 3, rsurface_svector3f);
1294         R_Mesh_TexCoordPointer(2, 3, rsurface_tvector3f);
1295         R_Mesh_TexCoordPointer(3, 3, rsurface_normal3f);
1296         if (rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
1297         {
1298                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
1299         }
1300         RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1301         GL_LockArrays(0, 0);
1302         if (rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
1303         {
1304                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1305         }
1306 }
1307
1308 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_Finalize(int numsurfaces, msurface_t **surfacelist, float r, float g, float b)
1309 {
1310         // shared final code for all the dot3 layers
1311         int renders;
1312         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 0);
1313         for (renders = 0;renders < 64 && (r > 0 || g > 0 || b > 0);renders++, r--, g--, b--)
1314         {
1315                 GL_Color(bound(0, r, 1), bound(0, g, 1), bound(0, b, 1), 1);
1316                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1317                 GL_LockArrays(0, 0);
1318         }
1319 }
1320
1321 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, rtexture_t *basetexture, float colorscale)
1322 {
1323         rmeshstate_t m;
1324         // colorscale accounts for how much we multiply the brightness
1325         // during combine.
1326         //
1327         // mult is how many times the final pass of the lighting will be
1328         // performed to get more brightness than otherwise possible.
1329         //
1330         // Limit mult to 64 for sanity sake.
1331         GL_Color(1,1,1,1);
1332         if (r_shadow_texture3d.integer && r_shadow_rtlight->currentcubemap != r_texture_whitecube && r_textureunits.integer >= 4)
1333         {
1334                 // 3 3D combine path (Geforce3, Radeon 8500)
1335                 memset(&m, 0, sizeof(m));
1336                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1337                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1338                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1339                 m.tex[1] = R_GetTexture(basetexture);
1340                 m.pointer_texcoord[1] = rsurface_model->surfmesh.data_texcoordtexture2f;
1341                 m.texmatrix[1] = rsurface_texture->currenttexmatrix;
1342                 m.texcubemap[2] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1343                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1344                 m.texmatrix[2] = r_shadow_entitytolight;
1345                 GL_BlendFunc(GL_ONE, GL_ONE);
1346         }
1347         else if (r_shadow_texture3d.integer && r_shadow_rtlight->currentcubemap == r_texture_whitecube && r_textureunits.integer >= 2)
1348         {
1349                 // 2 3D combine path (Geforce3, original Radeon)
1350                 memset(&m, 0, sizeof(m));
1351                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1352                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1353                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1354                 m.tex[1] = R_GetTexture(basetexture);
1355                 m.pointer_texcoord[1] = rsurface_model->surfmesh.data_texcoordtexture2f;
1356                 m.texmatrix[1] = rsurface_texture->currenttexmatrix;
1357                 GL_BlendFunc(GL_ONE, GL_ONE);
1358         }
1359         else if (r_textureunits.integer >= 4 && r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1360         {
1361                 // 4 2D combine path (Geforce3, Radeon 8500)
1362                 memset(&m, 0, sizeof(m));
1363                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1364                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1365                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1366                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1367                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1368                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1369                 m.tex[2] = R_GetTexture(basetexture);
1370                 m.pointer_texcoord[2] = rsurface_model->surfmesh.data_texcoordtexture2f;
1371                 m.texmatrix[2] = rsurface_texture->currenttexmatrix;
1372                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1373                 {
1374                         m.texcubemap[3] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1375                         m.pointer_texcoord3f[3] = rsurface_vertex3f;
1376                         m.texmatrix[3] = r_shadow_entitytolight;
1377                 }
1378                 GL_BlendFunc(GL_ONE, GL_ONE);
1379         }
1380         else if (r_textureunits.integer >= 3 && r_shadow_rtlight->currentcubemap == r_texture_whitecube)
1381         {
1382                 // 3 2D combine path (Geforce3, original Radeon)
1383                 memset(&m, 0, sizeof(m));
1384                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1385                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1386                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1387                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1388                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1389                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1390                 m.tex[2] = R_GetTexture(basetexture);
1391                 m.pointer_texcoord[2] = rsurface_model->surfmesh.data_texcoordtexture2f;
1392                 m.texmatrix[2] = rsurface_texture->currenttexmatrix;
1393                 GL_BlendFunc(GL_ONE, GL_ONE);
1394         }
1395         else
1396         {
1397                 // 2/2/2 2D combine path (any dot3 card)
1398                 memset(&m, 0, sizeof(m));
1399                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1400                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1401                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1402                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1403                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1404                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1405                 R_Mesh_TextureState(&m);
1406                 GL_ColorMask(0,0,0,1);
1407                 GL_BlendFunc(GL_ONE, GL_ZERO);
1408                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1409                 GL_LockArrays(0, 0);
1410
1411                 // second pass
1412                 memset(&m, 0, sizeof(m));
1413                 m.tex[0] = R_GetTexture(basetexture);
1414                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1415                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1416                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1417                 {
1418                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1419                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1420                         m.texmatrix[1] = r_shadow_entitytolight;
1421                 }
1422                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1423         }
1424         // this final code is shared
1425         R_Mesh_TextureState(&m);
1426         R_Shadow_RenderSurfacesLighting_Light_Dot3_Finalize(numsurfaces, surfacelist, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
1427 }
1428
1429 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, rtexture_t *basetexture, rtexture_t *normalmaptexture, float colorscale)
1430 {
1431         rmeshstate_t m;
1432         // colorscale accounts for how much we multiply the brightness
1433         // during combine.
1434         //
1435         // mult is how many times the final pass of the lighting will be
1436         // performed to get more brightness than otherwise possible.
1437         //
1438         // Limit mult to 64 for sanity sake.
1439         GL_Color(1,1,1,1);
1440         // generate normalization cubemap texcoords
1441         R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(numsurfaces, surfacelist);
1442         if (r_shadow_texture3d.integer && r_textureunits.integer >= 4)
1443         {
1444                 // 3/2 3D combine path (Geforce3, Radeon 8500)
1445                 memset(&m, 0, sizeof(m));
1446                 m.tex[0] = R_GetTexture(normalmaptexture);
1447                 m.texcombinergb[0] = GL_REPLACE;
1448                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1449                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1450                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1451                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1452                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1453                 m.tex3d[2] = R_GetTexture(r_shadow_attenuation3dtexture);
1454                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1455                 m.texmatrix[2] = r_shadow_entitytoattenuationxyz;
1456                 R_Mesh_TextureState(&m);
1457                 GL_ColorMask(0,0,0,1);
1458                 GL_BlendFunc(GL_ONE, GL_ZERO);
1459                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1460                 GL_LockArrays(0, 0);
1461
1462                 // second pass
1463                 memset(&m, 0, sizeof(m));
1464                 m.tex[0] = R_GetTexture(basetexture);
1465                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1466                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1467                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1468                 {
1469                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1470                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1471                         m.texmatrix[1] = r_shadow_entitytolight;
1472                 }
1473                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1474         }
1475         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1476         {
1477                 // 1/2/2 3D combine path (original Radeon)
1478                 memset(&m, 0, sizeof(m));
1479                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1480                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1481                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1482                 R_Mesh_TextureState(&m);
1483                 GL_ColorMask(0,0,0,1);
1484                 GL_BlendFunc(GL_ONE, GL_ZERO);
1485                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1486                 GL_LockArrays(0, 0);
1487
1488                 // second pass
1489                 memset(&m, 0, sizeof(m));
1490                 m.tex[0] = R_GetTexture(normalmaptexture);
1491                 m.texcombinergb[0] = GL_REPLACE;
1492                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1493                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1494                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1495                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1496                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1497                 R_Mesh_TextureState(&m);
1498                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1499                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1500                 GL_LockArrays(0, 0);
1501
1502                 // second pass
1503                 memset(&m, 0, sizeof(m));
1504                 m.tex[0] = R_GetTexture(basetexture);
1505                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1506                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1507                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1508                 {
1509                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1510                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1511                         m.texmatrix[1] = r_shadow_entitytolight;
1512                 }
1513                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1514         }
1515         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap == r_texture_whitecube)
1516         {
1517                 // 2/2 3D combine path (original Radeon)
1518                 memset(&m, 0, sizeof(m));
1519                 m.tex[0] = R_GetTexture(normalmaptexture);
1520                 m.texcombinergb[0] = GL_REPLACE;
1521                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1522                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1523                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1524                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1525                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1526                 R_Mesh_TextureState(&m);
1527                 GL_ColorMask(0,0,0,1);
1528                 GL_BlendFunc(GL_ONE, GL_ZERO);
1529                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1530                 GL_LockArrays(0, 0);
1531
1532                 // second pass
1533                 memset(&m, 0, sizeof(m));
1534                 m.tex[0] = R_GetTexture(basetexture);
1535                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1536                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1537                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
1538                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1539                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1540                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1541         }
1542         else if (r_textureunits.integer >= 4)
1543         {
1544                 // 4/2 2D combine path (Geforce3, Radeon 8500)
1545                 memset(&m, 0, sizeof(m));
1546                 m.tex[0] = R_GetTexture(normalmaptexture);
1547                 m.texcombinergb[0] = GL_REPLACE;
1548                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1549                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1550                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1551                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1552                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1553                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
1554                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1555                 m.texmatrix[2] = r_shadow_entitytoattenuationxyz;
1556                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
1557                 m.pointer_texcoord3f[3] = rsurface_vertex3f;
1558                 m.texmatrix[3] = r_shadow_entitytoattenuationz;
1559                 R_Mesh_TextureState(&m);
1560                 GL_ColorMask(0,0,0,1);
1561                 GL_BlendFunc(GL_ONE, GL_ZERO);
1562                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1563                 GL_LockArrays(0, 0);
1564
1565                 // second pass
1566                 memset(&m, 0, sizeof(m));
1567                 m.tex[0] = R_GetTexture(basetexture);
1568                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1569                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1570                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1571                 {
1572                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1573                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1574                         m.texmatrix[1] = r_shadow_entitytolight;
1575                 }
1576                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1577         }
1578         else
1579         {
1580                 // 2/2/2 2D combine path (any dot3 card)
1581                 memset(&m, 0, sizeof(m));
1582                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1583                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1584                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1585                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1586                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1587                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1588                 R_Mesh_TextureState(&m);
1589                 GL_ColorMask(0,0,0,1);
1590                 GL_BlendFunc(GL_ONE, GL_ZERO);
1591                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1592                 GL_LockArrays(0, 0);
1593
1594                 // second pass
1595                 memset(&m, 0, sizeof(m));
1596                 m.tex[0] = R_GetTexture(normalmaptexture);
1597                 m.texcombinergb[0] = GL_REPLACE;
1598                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1599                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1600                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1601                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1602                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1603                 R_Mesh_TextureState(&m);
1604                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1605                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1606                 GL_LockArrays(0, 0);
1607
1608                 // second pass
1609                 memset(&m, 0, sizeof(m));
1610                 m.tex[0] = R_GetTexture(basetexture);
1611                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1612                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1613                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1614                 {
1615                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1616                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1617                         m.texmatrix[1] = r_shadow_entitytolight;
1618                 }
1619                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1620         }
1621         // this final code is shared
1622         R_Mesh_TextureState(&m);
1623         R_Shadow_RenderSurfacesLighting_Light_Dot3_Finalize(numsurfaces, surfacelist, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
1624 }
1625
1626 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_SpecularPass(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, rtexture_t *glosstexture, rtexture_t *normalmaptexture, float colorscale)
1627 {
1628         rmeshstate_t m;
1629         // FIXME: detect blendsquare!
1630         //if (!gl_support_blendsquare)
1631         //      return;
1632         GL_Color(1,1,1,1);
1633         // generate normalization cubemap texcoords
1634         R_Shadow_GenTexCoords_Specular_NormalCubeMap(numsurfaces, surfacelist);
1635         if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1636         {
1637                 // 2/0/0/1/2 3D combine blendsquare path
1638                 memset(&m, 0, sizeof(m));
1639                 m.tex[0] = R_GetTexture(normalmaptexture);
1640                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1641                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1642                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1643                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1644                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1645                 R_Mesh_TextureState(&m);
1646                 GL_ColorMask(0,0,0,1);
1647                 // this squares the result
1648                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1649                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1650                 GL_LockArrays(0, 0);
1651
1652                 // second and third pass
1653                 R_Mesh_ResetTextureState();
1654                 // square alpha in framebuffer a few times to make it shiny
1655                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1656                 // these comments are a test run through this math for intensity 0.5
1657                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1658                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1659                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1660                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1661                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1662                 GL_LockArrays(0, 0);
1663
1664                 // fourth pass
1665                 memset(&m, 0, sizeof(m));
1666                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1667                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1668                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1669                 R_Mesh_TextureState(&m);
1670                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1671                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1672                 GL_LockArrays(0, 0);
1673
1674                 // fifth pass
1675                 memset(&m, 0, sizeof(m));
1676                 m.tex[0] = R_GetTexture(glosstexture);
1677                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1678                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1679                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1680                 {
1681                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1682                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1683                         m.texmatrix[1] = r_shadow_entitytolight;
1684                 }
1685                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1686         }
1687         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap == r_texture_whitecube /* && gl_support_blendsquare*/) // FIXME: detect blendsquare!
1688         {
1689                 // 2/0/0/2 3D combine blendsquare path
1690                 memset(&m, 0, sizeof(m));
1691                 m.tex[0] = R_GetTexture(normalmaptexture);
1692                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1693                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1694                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1695                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1696                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1697                 R_Mesh_TextureState(&m);
1698                 GL_ColorMask(0,0,0,1);
1699                 // this squares the result
1700                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1701                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1702                 GL_LockArrays(0, 0);
1703
1704                 // second and third pass
1705                 R_Mesh_ResetTextureState();
1706                 // square alpha in framebuffer a few times to make it shiny
1707                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1708                 // these comments are a test run through this math for intensity 0.5
1709                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1710                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1711                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1712                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1713                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1714                 GL_LockArrays(0, 0);
1715
1716                 // fourth pass
1717                 memset(&m, 0, sizeof(m));
1718                 m.tex[0] = R_GetTexture(glosstexture);
1719                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1720                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1721                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
1722                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1723                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1724                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1725         }
1726         else
1727         {
1728                 // 2/0/0/2/2 2D combine blendsquare path
1729                 memset(&m, 0, sizeof(m));
1730                 m.tex[0] = R_GetTexture(normalmaptexture);
1731                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1732                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1733                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1734                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1735                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1736                 R_Mesh_TextureState(&m);
1737                 GL_ColorMask(0,0,0,1);
1738                 // this squares the result
1739                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1740                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1741                 GL_LockArrays(0, 0);
1742
1743                 // second and third pass
1744                 R_Mesh_ResetTextureState();
1745                 // square alpha in framebuffer a few times to make it shiny
1746                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1747                 // these comments are a test run through this math for intensity 0.5
1748                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1749                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1750                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1751                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1752                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1753                 GL_LockArrays(0, 0);
1754
1755                 // fourth pass
1756                 memset(&m, 0, sizeof(m));
1757                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1758                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1759                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1760                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1761                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1762                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1763                 R_Mesh_TextureState(&m);
1764                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1765                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1766                 GL_LockArrays(0, 0);
1767
1768                 // fifth pass
1769                 memset(&m, 0, sizeof(m));
1770                 m.tex[0] = R_GetTexture(glosstexture);
1771                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1772                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1773                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1774                 {
1775                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1776                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1777                         m.texmatrix[1] = r_shadow_entitytolight;
1778                 }
1779                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1780         }
1781         // this final code is shared
1782         R_Mesh_TextureState(&m);
1783         R_Shadow_RenderSurfacesLighting_Light_Dot3_Finalize(numsurfaces, surfacelist, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
1784 }
1785
1786 static void R_Shadow_RenderSurfacesLighting_Light_Dot3(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float specularscale, qboolean dopants, qboolean doshirt)
1787 {
1788         // ARB path (any Geforce, any Radeon)
1789         qboolean doambient = r_shadow_rtlight->ambientscale > 0;
1790         qboolean dodiffuse = r_shadow_rtlight->diffusescale > 0;
1791         qboolean dospecular = specularscale > 0;
1792         if (!doambient && !dodiffuse && !dospecular)
1793                 return;
1794         RSurf_PrepareVerticesForBatch(true, true, numsurfaces, surfacelist);
1795         R_Mesh_ColorPointer(NULL);
1796         if (doambient)
1797                 R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(numsurfaces, surfacelist, lightcolorbase, basetexture, r_shadow_rtlight->ambientscale * r_view.colorscale);
1798         if (dodiffuse)
1799                 R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(numsurfaces, surfacelist, lightcolorbase, basetexture, normalmaptexture, r_shadow_rtlight->diffusescale * r_view.colorscale);
1800         if (dopants)
1801         {
1802                 if (doambient)
1803                         R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(numsurfaces, surfacelist, lightcolorpants, pantstexture, r_shadow_rtlight->ambientscale * r_view.colorscale);
1804                 if (dodiffuse)
1805                         R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(numsurfaces, surfacelist, lightcolorpants, pantstexture, normalmaptexture, r_shadow_rtlight->diffusescale * r_view.colorscale);
1806         }
1807         if (doshirt)
1808         {
1809                 if (doambient)
1810                         R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(numsurfaces, surfacelist, lightcolorshirt, shirttexture, r_shadow_rtlight->ambientscale * r_view.colorscale);
1811                 if (dodiffuse)
1812                         R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(numsurfaces, surfacelist, lightcolorshirt, shirttexture, normalmaptexture, r_shadow_rtlight->diffusescale * r_view.colorscale);
1813         }
1814         if (dospecular)
1815                 R_Shadow_RenderSurfacesLighting_Light_Dot3_SpecularPass(numsurfaces, surfacelist, lightcolorbase, glosstexture, normalmaptexture, specularscale * r_view.colorscale);
1816 }
1817
1818 void R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(const model_t *model, int numsurfaces, msurface_t **surfacelist, vec3_t diffusecolor2, vec3_t ambientcolor2)
1819 {
1820         int surfacelistindex;
1821         int renders;
1822         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1823         {
1824                 const msurface_t *surface = surfacelist[surfacelistindex];
1825                 R_Shadow_RenderSurfacesLighting_Light_Vertex_Shading(surface, diffusecolor2, ambientcolor2);
1826         }
1827         for (renders = 0;renders < 64;renders++)
1828         {
1829                 const int *e;
1830                 int stop;
1831                 int firstvertex;
1832                 int lastvertex;
1833                 int newnumtriangles;
1834                 int *newe;
1835                 int newelements[3072];
1836                 stop = true;
1837                 firstvertex = 0;
1838                 lastvertex = 0;
1839                 newnumtriangles = 0;
1840                 newe = newelements;
1841                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1842                 {
1843                         const msurface_t *surface = surfacelist[surfacelistindex];
1844                         const int *elements = rsurface_model->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1845                         int i;
1846                         // due to low fillrate on the cards this vertex lighting path is
1847                         // designed for, we manually cull all triangles that do not
1848                         // contain a lit vertex
1849                         // this builds batches of triangles from multiple surfaces and
1850                         // renders them at once
1851                         for (i = 0, e = elements;i < surface->num_triangles;i++, e += 3)
1852                         {
1853                                 if (VectorLength2(rsurface_array_color4f + e[0] * 4) + VectorLength2(rsurface_array_color4f + e[1] * 4) + VectorLength2(rsurface_array_color4f + e[2] * 4) >= 0.01)
1854                                 {
1855                                         if (newnumtriangles)
1856                                         {
1857                                                 firstvertex = min(firstvertex, e[0]);
1858                                                 lastvertex = max(lastvertex, e[0]);
1859                                         }
1860                                         else
1861                                         {
1862                                                 firstvertex = e[0];
1863                                                 lastvertex = e[0];
1864                                         }
1865                                         firstvertex = min(firstvertex, e[1]);
1866                                         lastvertex = max(lastvertex, e[1]);
1867                                         firstvertex = min(firstvertex, e[2]);
1868                                         lastvertex = max(lastvertex, e[2]);
1869                                         newe[0] = e[0];
1870                                         newe[1] = e[1];
1871                                         newe[2] = e[2];
1872                                         newnumtriangles++;
1873                                         newe += 3;
1874                                         if (newnumtriangles >= 1024)
1875                                         {
1876                                                 GL_LockArrays(firstvertex, lastvertex - firstvertex + 1);
1877                                                 R_Mesh_Draw(firstvertex, lastvertex - firstvertex + 1, newnumtriangles, newelements);
1878                                                 newnumtriangles = 0;
1879                                                 newe = newelements;
1880                                                 stop = false;
1881                                         }
1882                                 }
1883                         }
1884                 }
1885                 if (newnumtriangles >= 1)
1886                 {
1887                         GL_LockArrays(firstvertex, lastvertex - firstvertex + 1);
1888                         R_Mesh_Draw(firstvertex, lastvertex - firstvertex + 1, newnumtriangles, newelements);
1889                         stop = false;
1890                 }
1891                 GL_LockArrays(0, 0);
1892                 // if we couldn't find any lit triangles, exit early
1893                 if (stop)
1894                         break;
1895                 // now reduce the intensity for the next overbright pass
1896                 // we have to clamp to 0 here incase the drivers have improper
1897                 // handling of negative colors
1898                 // (some old drivers even have improper handling of >1 color)
1899                 stop = true;
1900                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1901                 {
1902                         int i;
1903                         float *c;
1904                         const msurface_t *surface = surfacelist[surfacelistindex];
1905                         for (i = 0, c = rsurface_array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
1906                         {
1907                                 if (c[0] > 1 || c[1] > 1 || c[2] > 1)
1908                                 {
1909                                         c[0] = max(0, c[0] - 1);
1910                                         c[1] = max(0, c[1] - 1);
1911                                         c[2] = max(0, c[2] - 1);
1912                                         stop = false;
1913                                 }
1914                                 else
1915                                         VectorClear(c);
1916                         }
1917                 }
1918                 // another check...
1919                 if (stop)
1920                         break;
1921         }
1922 }
1923
1924 static void R_Shadow_RenderSurfacesLighting_Light_Vertex(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float specularscale, qboolean dopants, qboolean doshirt)
1925 {
1926         // OpenGL 1.1 path (anything)
1927         model_t *model = rsurface_entity->model;
1928         float ambientcolorbase[3], diffusecolorbase[3];
1929         float ambientcolorpants[3], diffusecolorpants[3];
1930         float ambientcolorshirt[3], diffusecolorshirt[3];
1931         rmeshstate_t m;
1932         VectorScale(lightcolorbase, r_shadow_rtlight->ambientscale * 2 * r_view.colorscale, ambientcolorbase);
1933         VectorScale(lightcolorbase, r_shadow_rtlight->diffusescale * 2 * r_view.colorscale, diffusecolorbase);
1934         VectorScale(lightcolorpants, r_shadow_rtlight->ambientscale * 2 * r_view.colorscale, ambientcolorpants);
1935         VectorScale(lightcolorpants, r_shadow_rtlight->diffusescale * 2 * r_view.colorscale, diffusecolorpants);
1936         VectorScale(lightcolorshirt, r_shadow_rtlight->ambientscale * 2 * r_view.colorscale, ambientcolorshirt);
1937         VectorScale(lightcolorshirt, r_shadow_rtlight->diffusescale * 2 * r_view.colorscale, diffusecolorshirt);
1938         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1939         R_Mesh_ColorPointer(rsurface_array_color4f);
1940         memset(&m, 0, sizeof(m));
1941         m.tex[0] = R_GetTexture(basetexture);
1942         m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1943         m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1944         if (r_textureunits.integer >= 2)
1945         {
1946                 // voodoo2 or TNT
1947                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1948                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1949                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1950                 if (r_textureunits.integer >= 3)
1951                 {
1952                         // Voodoo4 or Kyro (or Geforce3/Radeon with gl_combine off)
1953                         m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
1954                         m.texmatrix[2] = r_shadow_entitytoattenuationz;
1955                         m.pointer_texcoord3f[2] = rsurface_vertex3f;
1956                 }
1957         }
1958         R_Mesh_TextureState(&m);
1959         RSurf_PrepareVerticesForBatch(true, false, numsurfaces, surfacelist);
1960         R_Mesh_TexBind(0, R_GetTexture(basetexture));
1961         R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, numsurfaces, surfacelist, diffusecolorbase, ambientcolorbase);
1962         if (dopants)
1963         {
1964                 R_Mesh_TexBind(0, R_GetTexture(pantstexture));
1965                 R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, numsurfaces, surfacelist, diffusecolorpants, ambientcolorpants);
1966         }
1967         if (doshirt)
1968         {
1969                 R_Mesh_TexBind(0, R_GetTexture(shirttexture));
1970                 R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, numsurfaces, surfacelist, diffusecolorshirt, ambientcolorshirt);
1971         }
1972 }
1973
1974 void R_Shadow_RenderSurfacesLighting(int numsurfaces, msurface_t **surfacelist)
1975 {
1976         // FIXME: support MATERIALFLAG_NODEPTHTEST
1977         vec3_t lightcolorbase, lightcolorpants, lightcolorshirt;
1978         // calculate colors to render this texture with
1979         lightcolorbase[0] = r_shadow_rtlight->currentcolor[0] * rsurface_entity->colormod[0] * rsurface_texture->currentalpha;
1980         lightcolorbase[1] = r_shadow_rtlight->currentcolor[1] * rsurface_entity->colormod[1] * rsurface_texture->currentalpha;
1981         lightcolorbase[2] = r_shadow_rtlight->currentcolor[2] * rsurface_entity->colormod[2] * rsurface_texture->currentalpha;
1982         if ((r_shadow_rtlight->ambientscale + r_shadow_rtlight->diffusescale) * VectorLength2(lightcolorbase) + (r_shadow_rtlight->specularscale * rsurface_texture->specularscale) * VectorLength2(lightcolorbase) < (1.0f / 1048576.0f))
1983                 return;
1984         if ((rsurface_texture->textureflags & Q3TEXTUREFLAG_TWOSIDED) || (rsurface_entity->flags & RENDER_NOCULLFACE))
1985         {
1986                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1987         }
1988         else
1989         {
1990                 qglEnable(GL_CULL_FACE);CHECKGLERROR
1991         }
1992         if (rsurface_texture->colormapping)
1993         {
1994                 qboolean dopants = rsurface_texture->skin.pants != NULL && VectorLength2(rsurface_entity->colormap_pantscolor) >= (1.0f / 1048576.0f);
1995                 qboolean doshirt = rsurface_texture->skin.shirt != NULL && VectorLength2(rsurface_entity->colormap_shirtcolor) >= (1.0f / 1048576.0f);
1996                 if (dopants)
1997                 {
1998                         lightcolorpants[0] = lightcolorbase[0] * rsurface_entity->colormap_pantscolor[0];
1999                         lightcolorpants[1] = lightcolorbase[1] * rsurface_entity->colormap_pantscolor[1];
2000                         lightcolorpants[2] = lightcolorbase[2] * rsurface_entity->colormap_pantscolor[2];
2001                 }
2002                 else
2003                         VectorClear(lightcolorpants);
2004                 if (doshirt)
2005                 {
2006                         lightcolorshirt[0] = lightcolorbase[0] * rsurface_entity->colormap_shirtcolor[0];
2007                         lightcolorshirt[1] = lightcolorbase[1] * rsurface_entity->colormap_shirtcolor[1];
2008                         lightcolorshirt[2] = lightcolorbase[2] * rsurface_entity->colormap_shirtcolor[2];
2009                 }
2010                 else
2011                         VectorClear(lightcolorshirt);
2012                 switch (r_shadow_rendermode)
2013                 {
2014                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2015                         R_Shadow_RenderSurfacesLighting_VisibleLighting(numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface_texture->basetexture, rsurface_texture->skin.pants, rsurface_texture->skin.shirt, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, dopants, doshirt);
2016                         break;
2017                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2018                         R_Shadow_RenderSurfacesLighting_Light_GLSL(numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface_texture->basetexture, rsurface_texture->skin.pants, rsurface_texture->skin.shirt, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, dopants, doshirt);
2019                         break;
2020                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2021                         R_Shadow_RenderSurfacesLighting_Light_Dot3(numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface_texture->basetexture, rsurface_texture->skin.pants, rsurface_texture->skin.shirt, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, dopants, doshirt);
2022                         break;
2023                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
2024                         R_Shadow_RenderSurfacesLighting_Light_Vertex(numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface_texture->basetexture, rsurface_texture->skin.pants, rsurface_texture->skin.shirt, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, dopants, doshirt);
2025                         break;
2026                 default:
2027                         Con_Printf("R_Shadow_RenderSurfacesLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
2028                         break;
2029                 }
2030         }
2031         else
2032         {
2033                 switch (r_shadow_rendermode)
2034                 {
2035                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2036                         R_Shadow_RenderSurfacesLighting_VisibleLighting(numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, rsurface_texture->basetexture, r_texture_black, r_texture_black, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, false, false);
2037                         break;
2038                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2039                         R_Shadow_RenderSurfacesLighting_Light_GLSL(numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, rsurface_texture->basetexture, r_texture_black, r_texture_black, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, false, false);
2040                         break;
2041                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2042                         R_Shadow_RenderSurfacesLighting_Light_Dot3(numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, rsurface_texture->basetexture, r_texture_black, r_texture_black, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, false, false);
2043                         break;
2044                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
2045                         R_Shadow_RenderSurfacesLighting_Light_Vertex(numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, rsurface_texture->basetexture, r_texture_black, r_texture_black, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, false, false);
2046                         break;
2047                 default:
2048                         Con_Printf("R_Shadow_RenderSurfacesLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
2049                         break;
2050                 }
2051         }
2052 }
2053
2054 void R_RTLight_Update(dlight_t *light, int isstatic)
2055 {
2056         double scale;
2057         rtlight_t *rtlight = &light->rtlight;
2058         R_RTLight_Uncompile(rtlight);
2059         memset(rtlight, 0, sizeof(*rtlight));
2060
2061         VectorCopy(light->origin, rtlight->shadoworigin);
2062         VectorCopy(light->color, rtlight->color);
2063         rtlight->radius = light->radius;
2064         //rtlight->cullradius = rtlight->radius;
2065         //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
2066         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
2067         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
2068         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
2069         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
2070         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
2071         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
2072         rtlight->cubemapname[0] = 0;
2073         if (light->cubemapname[0])
2074                 strlcpy(rtlight->cubemapname, light->cubemapname, sizeof(rtlight->cubemapname));
2075         else if (light->cubemapnum > 0)
2076                 sprintf(rtlight->cubemapname, "cubemaps/%i", light->cubemapnum);
2077         rtlight->shadow = light->shadow;
2078         rtlight->corona = light->corona;
2079         rtlight->style = light->style;
2080         rtlight->isstatic = isstatic;
2081         rtlight->coronasizescale = light->coronasizescale;
2082         rtlight->ambientscale = light->ambientscale;
2083         rtlight->diffusescale = light->diffusescale;
2084         rtlight->specularscale = light->specularscale;
2085         rtlight->flags = light->flags;
2086         Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &light->matrix);
2087         // this has to scale both rotate and translate because this is an already
2088         // inverted matrix (it transforms from world to light space, not the other
2089         // way around)
2090         scale = 1.0 / rtlight->radius;
2091         Matrix4x4_Scale(&rtlight->matrix_worldtolight, scale, scale);
2092 }
2093
2094 // compiles rtlight geometry
2095 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
2096 void R_RTLight_Compile(rtlight_t *rtlight)
2097 {
2098         int shadowmeshes, shadowtris, numleafs, numleafpvsbytes, numsurfaces;
2099         entity_render_t *ent = r_refdef.worldentity;
2100         model_t *model = r_refdef.worldmodel;
2101         unsigned char *data;
2102
2103         // compile the light
2104         rtlight->compiled = true;
2105         rtlight->static_numleafs = 0;
2106         rtlight->static_numleafpvsbytes = 0;
2107         rtlight->static_leaflist = NULL;
2108         rtlight->static_leafpvs = NULL;
2109         rtlight->static_numsurfaces = 0;
2110         rtlight->static_surfacelist = NULL;
2111         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
2112         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
2113         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
2114         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
2115         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
2116         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
2117
2118         if (model && model->GetLightInfo)
2119         {
2120                 // this variable must be set for the CompileShadowVolume code
2121                 r_shadow_compilingrtlight = rtlight;
2122                 R_Shadow_EnlargeLeafSurfaceBuffer(model->brush.num_leafs, model->num_surfaces);
2123                 model->GetLightInfo(ent, rtlight->shadoworigin, rtlight->radius, rtlight->cullmins, rtlight->cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces);
2124                 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
2125                 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numleafs + numleafpvsbytes + sizeof(int) * numsurfaces);
2126                 rtlight->static_numleafs = numleafs;
2127                 rtlight->static_numleafpvsbytes = numleafpvsbytes;
2128                 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
2129                 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
2130                 rtlight->static_numsurfaces = numsurfaces;
2131                 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
2132                 if (numleafs)
2133                         memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
2134                 if (numleafpvsbytes)
2135                         memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
2136                 if (numsurfaces)
2137                         memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
2138                 if (model->CompileShadowVolume && rtlight->shadow)
2139                         model->CompileShadowVolume(ent, rtlight->shadoworigin, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
2140                 // now we're done compiling the rtlight
2141                 r_shadow_compilingrtlight = NULL;
2142         }
2143
2144
2145         // use smallest available cullradius - box radius or light radius
2146         //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
2147         //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
2148
2149         shadowmeshes = 0;
2150         shadowtris = 0;
2151         if (rtlight->static_meshchain_shadow)
2152         {
2153                 shadowmesh_t *mesh;
2154                 for (mesh = rtlight->static_meshchain_shadow;mesh;mesh = mesh->next)
2155                 {
2156                         shadowmeshes++;
2157                         shadowtris += mesh->numtriangles;
2158                 }
2159         }
2160
2161         if (developer.integer >= 10)
2162                 Con_Printf("static light built: %f %f %f : %f %f %f box, %i shadow volume triangles (in %i meshes)\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], shadowtris, shadowmeshes);
2163 }
2164
2165 void R_RTLight_Uncompile(rtlight_t *rtlight)
2166 {
2167         if (rtlight->compiled)
2168         {
2169                 if (rtlight->static_meshchain_shadow)
2170                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow);
2171                 rtlight->static_meshchain_shadow = NULL;
2172                 // these allocations are grouped
2173                 if (rtlight->static_leaflist)
2174                         Mem_Free(rtlight->static_leaflist);
2175                 rtlight->static_numleafs = 0;
2176                 rtlight->static_numleafpvsbytes = 0;
2177                 rtlight->static_leaflist = NULL;
2178                 rtlight->static_leafpvs = NULL;
2179                 rtlight->static_numsurfaces = 0;
2180                 rtlight->static_surfacelist = NULL;
2181                 rtlight->compiled = false;
2182         }
2183 }
2184
2185 void R_Shadow_UncompileWorldLights(void)
2186 {
2187         dlight_t *light;
2188         for (light = r_shadow_worldlightchain;light;light = light->next)
2189                 R_RTLight_Uncompile(&light->rtlight);
2190 }
2191
2192 void R_Shadow_DrawEntityShadow(entity_render_t *ent, int numsurfaces, int *surfacelist)
2193 {
2194         model_t *model = ent->model;
2195         vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
2196         vec_t relativeshadowradius;
2197         if (ent == r_refdef.worldentity)
2198         {
2199                 if (r_shadow_rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
2200                 {
2201                         shadowmesh_t *mesh;
2202                         R_Mesh_Matrix(&ent->matrix);
2203                         CHECKGLERROR
2204                         for (mesh = r_shadow_rtlight->static_meshchain_shadow;mesh;mesh = mesh->next)
2205                         {
2206                                 r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
2207                                 R_Mesh_VertexPointer(mesh->vertex3f);
2208                                 GL_LockArrays(0, mesh->numverts);
2209                                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCIL)
2210                                 {
2211                                         // decrement stencil if backface is behind depthbuffer
2212                                         qglCullFace(GL_BACK);CHECKGLERROR // quake is backwards, this culls front faces
2213                                         qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
2214                                         R_Mesh_Draw(0, mesh->numverts, mesh->numtriangles, mesh->element3i);
2215                                         // increment stencil if frontface is behind depthbuffer
2216                                         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
2217                                         qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
2218                                 }
2219                                 R_Mesh_Draw(0, mesh->numverts, mesh->numtriangles, mesh->element3i);
2220                                 GL_LockArrays(0, 0);
2221                         }
2222                         CHECKGLERROR
2223                 }
2224                 else if (numsurfaces)
2225                 {
2226                         R_Mesh_Matrix(&ent->matrix);
2227                         model->DrawShadowVolume(ent, r_shadow_rtlight->shadoworigin, r_shadow_rtlight->radius, numsurfaces, surfacelist, r_shadow_rtlight->cullmins, r_shadow_rtlight->cullmaxs);
2228                 }
2229         }
2230         else
2231         {
2232                 Matrix4x4_Transform(&ent->inversematrix, r_shadow_rtlight->shadoworigin, relativeshadoworigin);
2233                 relativeshadowradius = r_shadow_rtlight->radius / ent->scale;
2234                 relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
2235                 relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
2236                 relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
2237                 relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
2238                 relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
2239                 relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
2240                 R_Mesh_Matrix(&ent->matrix);
2241                 model->DrawShadowVolume(ent, relativeshadoworigin, relativeshadowradius, model->nummodelsurfaces, model->surfacelist, relativeshadowmins, relativeshadowmaxs);
2242         }
2243 }
2244
2245 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
2246 {
2247         // set up properties for rendering light onto this entity
2248         RSurf_ActiveEntity(ent, true, true);
2249         Matrix4x4_Concat(&r_shadow_entitytolight, &r_shadow_rtlight->matrix_worldtolight, &ent->matrix);
2250         Matrix4x4_Concat(&r_shadow_entitytoattenuationxyz, &matrix_attenuationxyz, &r_shadow_entitytolight);
2251         Matrix4x4_Concat(&r_shadow_entitytoattenuationz, &matrix_attenuationz, &r_shadow_entitytolight);
2252         Matrix4x4_Transform(&ent->inversematrix, r_shadow_rtlight->shadoworigin, r_shadow_entitylightorigin);
2253         if (r_shadow_lightingrendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2254                 R_Mesh_TexMatrix(3, &r_shadow_entitytolight);
2255 }
2256
2257 void R_Shadow_DrawEntityLight(entity_render_t *ent, int numsurfaces, int *surfacelist)
2258 {
2259         model_t *model = ent->model;
2260         if (!model->DrawLight)
2261                 return;
2262         R_Shadow_SetupEntityLight(ent);
2263         if (ent == r_refdef.worldentity)
2264                 model->DrawLight(ent, numsurfaces, surfacelist);
2265         else
2266                 model->DrawLight(ent, model->nummodelsurfaces, model->surfacelist);
2267 }
2268
2269 void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
2270 {
2271         int i, usestencil;
2272         float f;
2273         int numleafs, numsurfaces;
2274         int *leaflist, *surfacelist;
2275         unsigned char *leafpvs;
2276         int numlightentities;
2277         int numshadowentities;
2278         entity_render_t *lightentities[MAX_EDICTS];
2279         entity_render_t *shadowentities[MAX_EDICTS];
2280
2281         // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
2282         // skip lights that are basically invisible (color 0 0 0)
2283         if (VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f))
2284                 return;
2285
2286         // loading is done before visibility checks because loading should happen
2287         // all at once at the start of a level, not when it stalls gameplay.
2288         // (especially important to benchmarks)
2289         // compile light
2290         if (rtlight->isstatic && !rtlight->compiled && r_shadow_realtime_world_compile.integer)
2291                 R_RTLight_Compile(rtlight);
2292         // load cubemap
2293         rtlight->currentcubemap = rtlight->cubemapname[0] ? R_Shadow_Cubemap(rtlight->cubemapname) : r_texture_whitecube;
2294
2295         // look up the light style value at this time
2296         f = (rtlight->style >= 0 ? r_refdef.lightstylevalue[rtlight->style] : 128) * (1.0f / 256.0f) * r_shadow_lightintensityscale.value;
2297         VectorScale(rtlight->color, f, rtlight->currentcolor);
2298         /*
2299         if (rtlight->selected)
2300         {
2301                 f = 2 + sin(realtime * M_PI * 4.0);
2302                 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
2303         }
2304         */
2305
2306         // if lightstyle is currently off, don't draw the light
2307         if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
2308                 return;
2309
2310         // if the light box is offscreen, skip it
2311         if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
2312                 return;
2313
2314         if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
2315         {
2316                 // compiled light, world available and can receive realtime lighting
2317                 // retrieve leaf information
2318                 numleafs = rtlight->static_numleafs;
2319                 leaflist = rtlight->static_leaflist;
2320                 leafpvs = rtlight->static_leafpvs;
2321                 numsurfaces = rtlight->static_numsurfaces;
2322                 surfacelist = rtlight->static_surfacelist;
2323         }
2324         else if (r_refdef.worldmodel && r_refdef.worldmodel->GetLightInfo)
2325         {
2326                 // dynamic light, world available and can receive realtime lighting
2327                 // calculate lit surfaces and leafs
2328                 R_Shadow_EnlargeLeafSurfaceBuffer(r_refdef.worldmodel->brush.num_leafs, r_refdef.worldmodel->num_surfaces);
2329                 r_refdef.worldmodel->GetLightInfo(r_refdef.worldentity, rtlight->shadoworigin, rtlight->radius, rtlight->cullmins, rtlight->cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces);
2330                 leaflist = r_shadow_buffer_leaflist;
2331                 leafpvs = r_shadow_buffer_leafpvs;
2332                 surfacelist = r_shadow_buffer_surfacelist;
2333                 // if the reduced leaf bounds are offscreen, skip it
2334                 if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
2335                         return;
2336         }
2337         else
2338         {
2339                 // no world
2340                 numleafs = 0;
2341                 leaflist = NULL;
2342                 leafpvs = NULL;
2343                 numsurfaces = 0;
2344                 surfacelist = NULL;
2345         }
2346         // check if light is illuminating any visible leafs
2347         if (numleafs)
2348         {
2349                 for (i = 0;i < numleafs;i++)
2350                         if (r_viewcache.world_leafvisible[leaflist[i]])
2351                                 break;
2352                 if (i == numleafs)
2353                         return;
2354         }
2355         // set up a scissor rectangle for this light
2356         if (R_Shadow_ScissorForBBox(rtlight->cullmins, rtlight->cullmaxs))
2357                 return;
2358
2359         // make a list of lit entities and shadow casting entities
2360         numlightentities = 0;
2361         numshadowentities = 0;
2362         // don't count the world unless some surfaces are actually lit
2363         if (numsurfaces)
2364         {
2365                 lightentities[numlightentities++] = r_refdef.worldentity;
2366                 shadowentities[numshadowentities++] = r_refdef.worldentity;
2367         }
2368         // add dynamic entities that are lit by the light
2369         if (r_drawentities.integer)
2370         {
2371                 for (i = 0;i < r_refdef.numentities;i++)
2372                 {
2373                         model_t *model;
2374                         entity_render_t *ent = r_refdef.entities[i];
2375                         if (BoxesOverlap(ent->mins, ent->maxs, rtlight->cullmins, rtlight->cullmaxs)
2376                          && (model = ent->model)
2377                          && !(ent->flags & RENDER_TRANSPARENT)
2378                          && (r_refdef.worldmodel == NULL || r_refdef.worldmodel->brush.BoxTouchingLeafPVS == NULL || r_refdef.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.worldmodel, leafpvs, ent->mins, ent->maxs)))
2379                         {
2380                                 // about the VectorDistance2 - light emitting entities should not cast their own shadow
2381                                 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(ent->origin, rtlight->shadoworigin) > 0.1)
2382                                         shadowentities[numshadowentities++] = ent;
2383                                 if (r_viewcache.entityvisible[i] && (ent->flags & RENDER_LIGHT) && model->DrawLight)
2384                                         lightentities[numlightentities++] = ent;
2385                         }
2386                 }
2387         }
2388
2389         // return if there's nothing at all to light
2390         if (!numlightentities)
2391                 return;
2392
2393         // don't let sound skip if going slow
2394         if (r_refdef.extraupdate)
2395                 S_ExtraUpdate ();
2396
2397         // make this the active rtlight for rendering purposes
2398         R_Shadow_RenderMode_ActiveLight(rtlight);
2399         // count this light in the r_speeds
2400         r_refdef.stats.lights++;
2401
2402         usestencil = false;
2403         if (numshadowentities && rtlight->shadow && (rtlight->isstatic ? r_refdef.rtworldshadows : r_refdef.rtdlightshadows))
2404         {
2405                 // draw stencil shadow volumes to mask off pixels that are in shadow
2406                 // so that they won't receive lighting
2407                 if (gl_stencil)
2408                 {
2409                         usestencil = true;
2410                         R_Shadow_RenderMode_StencilShadowVolumes();
2411                         for (i = 0;i < numshadowentities;i++)
2412                                 R_Shadow_DrawEntityShadow(shadowentities[i], numsurfaces, surfacelist);
2413                 }
2414
2415                 // optionally draw visible shape of the shadow volumes
2416                 // for performance analysis by level designers
2417                 if (r_showshadowvolumes.integer)
2418                 {
2419                         R_Shadow_RenderMode_VisibleShadowVolumes();
2420                         for (i = 0;i < numshadowentities;i++)
2421                                 R_Shadow_DrawEntityShadow(shadowentities[i], numsurfaces, surfacelist);
2422                 }
2423         }
2424
2425         if (numlightentities)
2426         {
2427                 // draw lighting in the unmasked areas
2428                 R_Shadow_RenderMode_Lighting(usestencil, false);
2429                 for (i = 0;i < numlightentities;i++)
2430                         R_Shadow_DrawEntityLight(lightentities[i], numsurfaces, surfacelist);
2431
2432                 // optionally draw the illuminated areas
2433                 // for performance analysis by level designers
2434                 if (r_showlighting.integer)
2435                 {
2436                         R_Shadow_RenderMode_VisibleLighting(usestencil && !r_showdisabledepthtest.integer, false);
2437                         for (i = 0;i < numlightentities;i++)
2438                                 R_Shadow_DrawEntityLight(lightentities[i], numsurfaces, surfacelist);
2439                 }
2440         }
2441 }
2442
2443 void R_ShadowVolumeLighting(qboolean visible)
2444 {
2445         int lnum, flag;
2446         dlight_t *light;
2447
2448         if (r_refdef.worldmodel && strncmp(r_refdef.worldmodel->name, r_shadow_mapname, sizeof(r_shadow_mapname)))
2449                 R_Shadow_EditLights_Reload_f();
2450
2451         R_Shadow_RenderMode_Begin();
2452
2453         flag = r_refdef.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2454         if (r_shadow_debuglight.integer >= 0)
2455         {
2456                 for (lnum = 0, light = r_shadow_worldlightchain;light;lnum++, light = light->next)
2457                         if (lnum == r_shadow_debuglight.integer && (light->flags & flag))
2458                                 R_DrawRTLight(&light->rtlight, visible);
2459         }
2460         else
2461                 for (lnum = 0, light = r_shadow_worldlightchain;light;lnum++, light = light->next)
2462                         if (light->flags & flag)
2463                                 R_DrawRTLight(&light->rtlight, visible);
2464         if (r_refdef.rtdlight)
2465                 for (lnum = 0;lnum < r_refdef.numlights;lnum++)
2466                         R_DrawRTLight(&r_refdef.lights[lnum]->rtlight, visible);
2467
2468         R_Shadow_RenderMode_End();
2469 }
2470
2471 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
2472 typedef struct suffixinfo_s
2473 {
2474         char *suffix;
2475         qboolean flipx, flipy, flipdiagonal;
2476 }
2477 suffixinfo_t;
2478 static suffixinfo_t suffix[3][6] =
2479 {
2480         {
2481                 {"px",   false, false, false},
2482                 {"nx",   false, false, false},
2483                 {"py",   false, false, false},
2484                 {"ny",   false, false, false},
2485                 {"pz",   false, false, false},
2486                 {"nz",   false, false, false}
2487         },
2488         {
2489                 {"posx", false, false, false},
2490                 {"negx", false, false, false},
2491                 {"posy", false, false, false},
2492                 {"negy", false, false, false},
2493                 {"posz", false, false, false},
2494                 {"negz", false, false, false}
2495         },
2496         {
2497                 {"rt",    true, false,  true},
2498                 {"lf",   false,  true,  true},
2499                 {"ft",    true,  true, false},
2500                 {"bk",   false, false, false},
2501                 {"up",    true, false,  true},
2502                 {"dn",    true, false,  true}
2503         }
2504 };
2505
2506 static int componentorder[4] = {0, 1, 2, 3};
2507
2508 rtexture_t *R_Shadow_LoadCubemap(const char *basename)
2509 {
2510         int i, j, cubemapsize;
2511         unsigned char *cubemappixels, *image_rgba;
2512         rtexture_t *cubemaptexture;
2513         char name[256];
2514         // must start 0 so the first loadimagepixels has no requested width/height
2515         cubemapsize = 0;
2516         cubemappixels = NULL;
2517         cubemaptexture = NULL;
2518         // keep trying different suffix groups (posx, px, rt) until one loads
2519         for (j = 0;j < 3 && !cubemappixels;j++)
2520         {
2521                 // load the 6 images in the suffix group
2522                 for (i = 0;i < 6;i++)
2523                 {
2524                         // generate an image name based on the base and and suffix
2525                         dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
2526                         // load it
2527                         if ((image_rgba = loadimagepixels(name, false, cubemapsize, cubemapsize)))
2528                         {
2529                                 // an image loaded, make sure width and height are equal
2530                                 if (image_width == image_height)
2531                                 {
2532                                         // if this is the first image to load successfully, allocate the cubemap memory
2533                                         if (!cubemappixels && image_width >= 1)
2534                                         {
2535                                                 cubemapsize = image_width;
2536                                                 // note this clears to black, so unavailable sides are black
2537                                                 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
2538                                         }
2539                                         // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
2540                                         if (cubemappixels)
2541                                                 Image_CopyMux(cubemappixels+i*cubemapsize*cubemapsize*4, image_rgba, cubemapsize, cubemapsize, suffix[j][i].flipx, suffix[j][i].flipy, suffix[j][i].flipdiagonal, 4, 4, componentorder);
2542                                 }
2543                                 else
2544                                         Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
2545                                 // free the image
2546                                 Mem_Free(image_rgba);
2547                         }
2548                 }
2549         }
2550         // if a cubemap loaded, upload it
2551         if (cubemappixels)
2552         {
2553                 if (!r_shadow_filters_texturepool)
2554                         r_shadow_filters_texturepool = R_AllocTexturePool();
2555                 cubemaptexture = R_LoadTextureCubeMap(r_shadow_filters_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
2556                 Mem_Free(cubemappixels);
2557         }
2558         else
2559         {
2560                 Con_Printf("Failed to load Cubemap \"%s\", tried ", basename);
2561                 for (j = 0;j < 3;j++)
2562                         for (i = 0;i < 6;i++)
2563                                 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
2564                 Con_Print(" and was unable to find any of them.\n");
2565         }
2566         return cubemaptexture;
2567 }
2568
2569 rtexture_t *R_Shadow_Cubemap(const char *basename)
2570 {
2571         int i;
2572         for (i = 0;i < numcubemaps;i++)
2573                 if (!strcasecmp(cubemaps[i].basename, basename))
2574                         return cubemaps[i].texture;
2575         if (i >= MAX_CUBEMAPS)
2576                 return r_texture_whitecube;
2577         numcubemaps++;
2578         strlcpy(cubemaps[i].basename, basename, sizeof(cubemaps[i].basename));
2579         cubemaps[i].texture = R_Shadow_LoadCubemap(cubemaps[i].basename);
2580         if (!cubemaps[i].texture)
2581                 cubemaps[i].texture = r_texture_whitecube;
2582         return cubemaps[i].texture;
2583 }
2584
2585 void R_Shadow_FreeCubemaps(void)
2586 {
2587         numcubemaps = 0;
2588         R_FreeTexturePool(&r_shadow_filters_texturepool);
2589 }
2590
2591 dlight_t *R_Shadow_NewWorldLight(void)
2592 {
2593         dlight_t *light;
2594         light = (dlight_t *)Mem_Alloc(r_main_mempool, sizeof(dlight_t));
2595         light->next = r_shadow_worldlightchain;
2596         r_shadow_worldlightchain = light;
2597         return light;
2598 }
2599
2600 void R_Shadow_UpdateWorldLight(dlight_t *light, vec3_t origin, vec3_t angles, vec3_t color, vec_t radius, vec_t corona, int style, int shadowenable, const char *cubemapname, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
2601 {
2602         VectorCopy(origin, light->origin);
2603         light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
2604         light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
2605         light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
2606         light->color[0] = max(color[0], 0);
2607         light->color[1] = max(color[1], 0);
2608         light->color[2] = max(color[2], 0);
2609         light->radius = max(radius, 0);
2610         light->style = style;
2611         if (light->style < 0 || light->style >= MAX_LIGHTSTYLES)
2612         {
2613                 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
2614                 light->style = 0;
2615         }
2616         light->shadow = shadowenable;
2617         light->corona = corona;
2618         if (!cubemapname)
2619                 cubemapname = "";
2620         strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
2621         light->coronasizescale = coronasizescale;
2622         light->ambientscale = ambientscale;
2623         light->diffusescale = diffusescale;
2624         light->specularscale = specularscale;
2625         light->flags = flags;
2626         Matrix4x4_CreateFromQuakeEntity(&light->matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], 1);
2627
2628         R_RTLight_Update(light, true);
2629 }
2630
2631 void R_Shadow_FreeWorldLight(dlight_t *light)
2632 {
2633         dlight_t **lightpointer;
2634         R_RTLight_Uncompile(&light->rtlight);
2635         for (lightpointer = &r_shadow_worldlightchain;*lightpointer && *lightpointer != light;lightpointer = &(*lightpointer)->next);
2636         if (*lightpointer != light)
2637                 Sys_Error("R_Shadow_FreeWorldLight: light not linked into chain");
2638         *lightpointer = light->next;
2639         Mem_Free(light);
2640 }
2641
2642 void R_Shadow_ClearWorldLights(void)
2643 {
2644         while (r_shadow_worldlightchain)
2645                 R_Shadow_FreeWorldLight(r_shadow_worldlightchain);
2646         r_shadow_selectedlight = NULL;
2647         R_Shadow_FreeCubemaps();
2648 }
2649
2650 void R_Shadow_SelectLight(dlight_t *light)
2651 {
2652         if (r_shadow_selectedlight)
2653                 r_shadow_selectedlight->selected = false;
2654         r_shadow_selectedlight = light;
2655         if (r_shadow_selectedlight)
2656                 r_shadow_selectedlight->selected = true;
2657 }
2658
2659 void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2660 {
2661         // this is never batched (there can be only one)
2662         float scale = r_editlights_cursorgrid.value * 0.5f;
2663         R_DrawSprite(GL_SRC_ALPHA, GL_ONE, r_crosshairs[1]->tex, NULL, false, r_editlights_cursorlocation, r_view.right, r_view.up, scale, -scale, -scale, scale, 1, 1, 1, 0.5f);
2664 }
2665
2666 void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2667 {
2668         // this is never batched (due to the ent parameter changing every time)
2669         // so numsurfaces == 1 and surfacelist[0] == lightnumber
2670         float intensity;
2671         const dlight_t *light = (dlight_t *)ent;
2672         intensity = 0.5;
2673         if (light->selected)
2674                 intensity = 0.75 + 0.25 * sin(realtime * M_PI * 4.0);
2675         if (!light->shadow)
2676                 intensity *= 0.5f;
2677         R_DrawSprite(GL_SRC_ALPHA, GL_ONE, r_crosshairs[surfacelist[0]]->tex, NULL, false, light->origin, r_view.right, r_view.up, 8, -8, -8, 8, intensity, intensity, intensity, 0.5);
2678 }
2679
2680 void R_Shadow_DrawLightSprites(void)
2681 {
2682         int i;
2683         dlight_t *light;
2684
2685         for (i = 0, light = r_shadow_worldlightchain;light;i++, light = light->next)
2686                 R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 1+(i % 5), &light->rtlight);
2687         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
2688 }
2689
2690 void R_Shadow_SelectLightInView(void)
2691 {
2692         float bestrating, rating, temp[3];
2693         dlight_t *best, *light;
2694         best = NULL;
2695         bestrating = 0;
2696         for (light = r_shadow_worldlightchain;light;light = light->next)
2697         {
2698                 VectorSubtract(light->origin, r_view.origin, temp);
2699                 rating = (DotProduct(temp, r_view.forward) / sqrt(DotProduct(temp, temp)));
2700                 if (rating >= 0.95)
2701                 {
2702                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
2703                         if (bestrating < rating && CL_TraceBox(light->origin, vec3_origin, vec3_origin, r_view.origin, true, NULL, SUPERCONTENTS_SOLID, false).fraction == 1.0f)
2704                         {
2705                                 bestrating = rating;
2706                                 best = light;
2707                         }
2708                 }
2709         }
2710         R_Shadow_SelectLight(best);
2711 }
2712
2713 void R_Shadow_LoadWorldLights(void)
2714 {
2715         int n, a, style, shadow, flags;
2716         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
2717         float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
2718         if (r_refdef.worldmodel == NULL)
2719         {
2720                 Con_Print("No map loaded.\n");
2721                 return;
2722         }
2723         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2724         strlcat (name, ".rtlights", sizeof (name));
2725         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
2726         if (lightsstring)
2727         {
2728                 s = lightsstring;
2729                 n = 0;
2730                 while (*s)
2731                 {
2732                         t = s;
2733                         /*
2734                         shadow = true;
2735                         for (;COM_Parse(t, true) && strcmp(
2736                         if (COM_Parse(t, true))
2737                         {
2738                                 if (com_token[0] == '!')
2739                                 {
2740                                         shadow = false;
2741                                         origin[0] = atof(com_token+1);
2742                                 }
2743                                 else
2744                                         origin[0] = atof(com_token);
2745                                 if (Com_Parse(t
2746                         }
2747                         */
2748                         t = s;
2749                         while (*s && *s != '\n' && *s != '\r')
2750                                 s++;
2751                         if (!*s)
2752                                 break;
2753                         tempchar = *s;
2754                         shadow = true;
2755                         // check for modifier flags
2756                         if (*t == '!')
2757                         {
2758                                 shadow = false;
2759                                 t++;
2760                         }
2761                         *s = 0;
2762                         a = sscanf(t, "%f %f %f %f %f %f %f %d %s %f %f %f %f %f %f %f %f %i", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, cubemapname, &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
2763                         *s = tempchar;
2764                         if (a < 18)
2765                                 flags = LIGHTFLAG_REALTIMEMODE;
2766                         if (a < 17)
2767                                 specularscale = 1;
2768                         if (a < 16)
2769                                 diffusescale = 1;
2770                         if (a < 15)
2771                                 ambientscale = 0;
2772                         if (a < 14)
2773                                 coronasizescale = 0.25f;
2774                         if (a < 13)
2775                                 VectorClear(angles);
2776                         if (a < 10)
2777                                 corona = 0;
2778                         if (a < 9 || !strcmp(cubemapname, "\"\""))
2779                                 cubemapname[0] = 0;
2780                         // remove quotes on cubemapname
2781                         if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
2782                         {
2783                                 size_t namelen;
2784                                 namelen = strlen(cubemapname) - 2;
2785                                 memmove(cubemapname, cubemapname + 1, namelen);
2786                                 cubemapname[namelen] = '\0';
2787                         }
2788                         if (a < 8)
2789                         {
2790                                 Con_Printf("found %d parameters on line %i, should be 8 or more parameters (origin[0] origin[1] origin[2] radius color[0] color[1] color[2] style \"cubemapname\" corona angles[0] angles[1] angles[2] coronasizescale ambientscale diffusescale specularscale flags)\n", a, n + 1);
2791                                 break;
2792                         }
2793                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
2794                         if (*s == '\r')
2795                                 s++;
2796                         if (*s == '\n')
2797                                 s++;
2798                         n++;
2799                 }
2800                 if (*s)
2801                         Con_Printf("invalid rtlights file \"%s\"\n", name);
2802                 Mem_Free(lightsstring);
2803         }
2804 }
2805
2806 void R_Shadow_SaveWorldLights(void)
2807 {
2808         dlight_t *light;
2809         size_t bufchars, bufmaxchars;
2810         char *buf, *oldbuf;
2811         char name[MAX_QPATH];
2812         char line[MAX_INPUTLINE];
2813         if (!r_shadow_worldlightchain)
2814                 return;
2815         if (r_refdef.worldmodel == NULL)
2816         {
2817                 Con_Print("No map loaded.\n");
2818                 return;
2819         }
2820         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2821         strlcat (name, ".rtlights", sizeof (name));
2822         bufchars = bufmaxchars = 0;
2823         buf = NULL;
2824         for (light = r_shadow_worldlightchain;light;light = light->next)
2825         {
2826                 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
2827                         sprintf(line, "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f %f %f %f %f %i\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2], light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
2828                 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
2829                         sprintf(line, "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2]);
2830                 else
2831                         sprintf(line, "%s%f %f %f %f %f %f %f %d\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style);
2832                 if (bufchars + strlen(line) > bufmaxchars)
2833                 {
2834                         bufmaxchars = bufchars + strlen(line) + 2048;
2835                         oldbuf = buf;
2836                         buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
2837                         if (oldbuf)
2838                         {
2839                                 if (bufchars)
2840                                         memcpy(buf, oldbuf, bufchars);
2841                                 Mem_Free(oldbuf);
2842                         }
2843                 }
2844                 if (strlen(line))
2845                 {
2846                         memcpy(buf + bufchars, line, strlen(line));
2847                         bufchars += strlen(line);
2848                 }
2849         }
2850         if (bufchars)
2851                 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
2852         if (buf)
2853                 Mem_Free(buf);
2854 }
2855
2856 void R_Shadow_LoadLightsFile(void)
2857 {
2858         int n, a, style;
2859         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
2860         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
2861         if (r_refdef.worldmodel == NULL)
2862         {
2863                 Con_Print("No map loaded.\n");
2864                 return;
2865         }
2866         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2867         strlcat (name, ".lights", sizeof (name));
2868         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
2869         if (lightsstring)
2870         {
2871                 s = lightsstring;
2872                 n = 0;
2873                 while (*s)
2874                 {
2875                         t = s;
2876                         while (*s && *s != '\n' && *s != '\r')
2877                                 s++;
2878                         if (!*s)
2879                                 break;
2880                         tempchar = *s;
2881                         *s = 0;
2882                         a = sscanf(t, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d", &origin[0], &origin[1], &origin[2], &falloff, &color[0], &color[1], &color[2], &subtract, &spotdir[0], &spotdir[1], &spotdir[2], &spotcone, &distbias, &style);
2883                         *s = tempchar;
2884                         if (a < 14)
2885                         {
2886                                 Con_Printf("invalid lights file, found %d parameters on line %i, should be 14 parameters (origin[0] origin[1] origin[2] falloff light[0] light[1] light[2] subtract spotdir[0] spotdir[1] spotdir[2] spotcone distancebias style)\n", a, n + 1);
2887                                 break;
2888                         }
2889                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
2890                         radius = bound(15, radius, 4096);
2891                         VectorScale(color, (2.0f / (8388608.0f)), color);
2892                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
2893                         if (*s == '\r')
2894                                 s++;
2895                         if (*s == '\n')
2896                                 s++;
2897                         n++;
2898                 }
2899                 if (*s)
2900                         Con_Printf("invalid lights file \"%s\"\n", name);
2901                 Mem_Free(lightsstring);
2902         }
2903 }
2904
2905 // tyrlite/hmap2 light types in the delay field
2906 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
2907
2908 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
2909 {
2910         int entnum, style, islight, skin, pflags, effects, type, n;
2911         char *entfiledata;
2912         const char *data;
2913         float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
2914         char key[256], value[MAX_INPUTLINE];
2915
2916         if (r_refdef.worldmodel == NULL)
2917         {
2918                 Con_Print("No map loaded.\n");
2919                 return;
2920         }
2921         // try to load a .ent file first
2922         FS_StripExtension (r_refdef.worldmodel->name, key, sizeof (key));
2923         strlcat (key, ".ent", sizeof (key));
2924         data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
2925         // and if that is not found, fall back to the bsp file entity string
2926         if (!data)
2927                 data = r_refdef.worldmodel->brush.entities;
2928         if (!data)
2929                 return;
2930         for (entnum = 0;COM_ParseTokenConsole(&data) && com_token[0] == '{';entnum++)
2931         {
2932                 type = LIGHTTYPE_MINUSX;
2933                 origin[0] = origin[1] = origin[2] = 0;
2934                 originhack[0] = originhack[1] = originhack[2] = 0;
2935                 angles[0] = angles[1] = angles[2] = 0;
2936                 color[0] = color[1] = color[2] = 1;
2937                 light[0] = light[1] = light[2] = 1;light[3] = 300;
2938                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
2939                 fadescale = 1;
2940                 lightscale = 1;
2941                 style = 0;
2942                 skin = 0;
2943                 pflags = 0;
2944                 effects = 0;
2945                 islight = false;
2946                 while (1)
2947                 {
2948                         if (!COM_ParseTokenConsole(&data))
2949                                 break; // error
2950                         if (com_token[0] == '}')
2951                                 break; // end of entity
2952                         if (com_token[0] == '_')
2953                                 strlcpy(key, com_token + 1, sizeof(key));
2954                         else
2955                                 strlcpy(key, com_token, sizeof(key));
2956                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
2957                                 key[strlen(key)-1] = 0;
2958                         if (!COM_ParseTokenConsole(&data))
2959                                 break; // error
2960                         strlcpy(value, com_token, sizeof(value));
2961
2962                         // now that we have the key pair worked out...
2963                         if (!strcmp("light", key))
2964                         {
2965                                 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
2966                                 if (n == 1)
2967                                 {
2968                                         // quake
2969                                         light[0] = vec[0] * (1.0f / 256.0f);
2970                                         light[1] = vec[0] * (1.0f / 256.0f);
2971                                         light[2] = vec[0] * (1.0f / 256.0f);
2972                                         light[3] = vec[0];
2973                                 }
2974                                 else if (n == 4)
2975                                 {
2976                                         // halflife
2977                                         light[0] = vec[0] * (1.0f / 255.0f);
2978                                         light[1] = vec[1] * (1.0f / 255.0f);
2979                                         light[2] = vec[2] * (1.0f / 255.0f);
2980                                         light[3] = vec[3];
2981                                 }
2982                         }
2983                         else if (!strcmp("delay", key))
2984                                 type = atoi(value);
2985                         else if (!strcmp("origin", key))
2986                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
2987                         else if (!strcmp("angle", key))
2988                                 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
2989                         else if (!strcmp("angles", key))
2990                                 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
2991                         else if (!strcmp("color", key))
2992                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
2993                         else if (!strcmp("wait", key))
2994                                 fadescale = atof(value);
2995                         else if (!strcmp("classname", key))
2996                         {
2997                                 if (!strncmp(value, "light", 5))
2998                                 {
2999                                         islight = true;
3000                                         if (!strcmp(value, "light_fluoro"))
3001                                         {
3002                                                 originhack[0] = 0;
3003                                                 originhack[1] = 0;
3004                                                 originhack[2] = 0;
3005                                                 overridecolor[0] = 1;
3006                                                 overridecolor[1] = 1;
3007                                                 overridecolor[2] = 1;
3008                                         }
3009                                         if (!strcmp(value, "light_fluorospark"))
3010                                         {
3011                                                 originhack[0] = 0;
3012                                                 originhack[1] = 0;
3013                                                 originhack[2] = 0;
3014                                                 overridecolor[0] = 1;
3015                                                 overridecolor[1] = 1;
3016                                                 overridecolor[2] = 1;
3017                                         }
3018                                         if (!strcmp(value, "light_globe"))
3019                                         {
3020                                                 originhack[0] = 0;
3021                                                 originhack[1] = 0;
3022                                                 originhack[2] = 0;
3023                                                 overridecolor[0] = 1;
3024                                                 overridecolor[1] = 0.8;
3025                                                 overridecolor[2] = 0.4;
3026                                         }
3027                                         if (!strcmp(value, "light_flame_large_yellow"))
3028                                         {
3029                                                 originhack[0] = 0;
3030                                                 originhack[1] = 0;
3031                                                 originhack[2] = 0;
3032                                                 overridecolor[0] = 1;
3033                                                 overridecolor[1] = 0.5;
3034                                                 overridecolor[2] = 0.1;
3035                                         }
3036                                         if (!strcmp(value, "light_flame_small_yellow"))
3037                                         {
3038                                                 originhack[0] = 0;
3039                                                 originhack[1] = 0;
3040                                                 originhack[2] = 0;
3041                                                 overridecolor[0] = 1;
3042                                                 overridecolor[1] = 0.5;
3043                                                 overridecolor[2] = 0.1;
3044                                         }
3045                                         if (!strcmp(value, "light_torch_small_white"))
3046                                         {
3047                                                 originhack[0] = 0;
3048                                                 originhack[1] = 0;
3049                                                 originhack[2] = 0;
3050                                                 overridecolor[0] = 1;
3051                                                 overridecolor[1] = 0.5;
3052                                                 overridecolor[2] = 0.1;
3053                                         }
3054                                         if (!strcmp(value, "light_torch_small_walltorch"))
3055                                         {
3056                                                 originhack[0] = 0;
3057                                                 originhack[1] = 0;
3058                                                 originhack[2] = 0;
3059                                                 overridecolor[0] = 1;
3060                                                 overridecolor[1] = 0.5;
3061                                                 overridecolor[2] = 0.1;
3062                                         }
3063                                 }
3064                         }
3065             &