made darkplaces able to compile as C++ again, and fixed all conversion warnings when...
[divverent/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         renderstats.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         rmeshstate_t m;
706         if (r_shadow_compilingrtlight)
707         {
708                 // if we're compiling an rtlight, capture the mesh
709                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, numtriangles, element3i);
710                 return;
711         }
712         renderstats.lights_shadowtriangles += numtriangles;
713         memset(&m, 0, sizeof(m));
714         m.pointer_vertex = vertex3f;
715         R_Mesh_State(&m);
716         GL_LockArrays(0, numvertices);
717         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCIL)
718         {
719                 // decrement stencil if backface is behind depthbuffer
720                 qglCullFace(GL_BACK); // quake is backwards, this culls front faces
721                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
722                 R_Mesh_Draw(0, numvertices, numtriangles, element3i);
723                 // increment stencil if frontface is behind depthbuffer
724                 qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
725                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
726         }
727         R_Mesh_Draw(0, numvertices, numtriangles, element3i);
728         GL_LockArrays(0, 0);
729 }
730
731 static void R_Shadow_MakeTextures(void)
732 {
733         int x, y, z, d;
734         float v[3], intensity;
735         unsigned char *data;
736         R_FreeTexturePool(&r_shadow_texturepool);
737         r_shadow_texturepool = R_AllocTexturePool();
738         r_shadow_attenpower = r_shadow_lightattenuationpower.value;
739         r_shadow_attenscale = r_shadow_lightattenuationscale.value;
740 #define ATTEN2DSIZE 64
741 #define ATTEN3DSIZE 32
742         data = (unsigned char *)Mem_Alloc(tempmempool, max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE*4, ATTEN2DSIZE*ATTEN2DSIZE*4));
743         for (y = 0;y < ATTEN2DSIZE;y++)
744         {
745                 for (x = 0;x < ATTEN2DSIZE;x++)
746                 {
747                         v[0] = ((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375);
748                         v[1] = ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375);
749                         v[2] = 0;
750                         intensity = 1.0f - sqrt(DotProduct(v, v));
751                         if (intensity > 0)
752                                 intensity = pow(intensity, r_shadow_attenpower) * r_shadow_attenscale * 256.0f;
753                         d = (int)bound(0, intensity, 255);
754                         data[(y*ATTEN2DSIZE+x)*4+0] = d;
755                         data[(y*ATTEN2DSIZE+x)*4+1] = d;
756                         data[(y*ATTEN2DSIZE+x)*4+2] = d;
757                         data[(y*ATTEN2DSIZE+x)*4+3] = d;
758                 }
759         }
760         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
761         if (r_shadow_texture3d.integer)
762         {
763                 for (z = 0;z < ATTEN3DSIZE;z++)
764                 {
765                         for (y = 0;y < ATTEN3DSIZE;y++)
766                         {
767                                 for (x = 0;x < ATTEN3DSIZE;x++)
768                                 {
769                                         v[0] = ((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
770                                         v[1] = ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
771                                         v[2] = ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
772                                         intensity = 1.0f - sqrt(DotProduct(v, v));
773                                         if (intensity > 0)
774                                                 intensity = pow(intensity, r_shadow_attenpower) * r_shadow_attenscale * 256.0f;
775                                         d = (int)bound(0, intensity, 255);
776                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+0] = d;
777                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+1] = d;
778                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+2] = d;
779                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+3] = d;
780                                 }
781                         }
782                 }
783                 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
784         }
785         Mem_Free(data);
786 }
787
788 void R_Shadow_ValidateCvars(void)
789 {
790         if (r_shadow_texture3d.integer && !gl_texture3d)
791                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
792         if (gl_ext_stenciltwoside.integer && !gl_support_stenciltwoside)
793                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
794 }
795
796 // light currently being rendered
797 rtlight_t *r_shadow_rtlight;
798
799 // this is the location of the eye in entity space
800 vec3_t r_shadow_entityeyeorigin;
801 // this is the location of the light in entity space
802 vec3_t r_shadow_entitylightorigin;
803 // this transforms entity coordinates to light filter cubemap coordinates
804 // (also often used for other purposes)
805 matrix4x4_t r_shadow_entitytolight;
806 // based on entitytolight this transforms -1 to +1 to 0 to 1 for purposes
807 // of attenuation texturing in full 3D (Z result often ignored)
808 matrix4x4_t r_shadow_entitytoattenuationxyz;
809 // this transforms only the Z to S, and T is always 0.5
810 matrix4x4_t r_shadow_entitytoattenuationz;
811
812 void R_Shadow_RenderMode_Begin(void)
813 {
814         rmeshstate_t m;
815
816         R_Shadow_ValidateCvars();
817
818         if (!r_shadow_attenuation2dtexture
819          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
820          || r_shadow_lightattenuationpower.value != r_shadow_attenpower
821          || r_shadow_lightattenuationscale.value != r_shadow_attenscale)
822                 R_Shadow_MakeTextures();
823
824         memset(&m, 0, sizeof(m));
825         R_Mesh_State(&m);
826         GL_BlendFunc(GL_ONE, GL_ZERO);
827         GL_DepthMask(false);
828         GL_DepthTest(true);
829         GL_Color(0, 0, 0, 1);
830         qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
831         qglEnable(GL_CULL_FACE);
832         GL_Scissor(r_view_x, r_view_y, r_view_width, r_view_height);
833
834         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
835
836         if (gl_ext_stenciltwoside.integer)
837                 r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCILTWOSIDE;
838         else
839                 r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCIL;
840
841         if (r_glsl.integer && gl_support_fragment_shader)
842                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
843         else if (gl_dot3arb && gl_texturecubemap && r_textureunits.integer >= 2 && gl_combine.integer && gl_stencil)
844                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_DOT3;
845         else
846                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
847 }
848
849 void R_Shadow_RenderMode_ActiveLight(rtlight_t *rtlight)
850 {
851         r_shadow_rtlight = rtlight;
852 }
853
854 void R_Shadow_RenderMode_Reset(void)
855 {
856         rmeshstate_t m;
857         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
858         {
859                 qglUseProgramObjectARB(0);
860                 // HACK HACK HACK: work around for bug in NVIDIAI 6xxx drivers that causes GL_OUT_OF_MEMORY and/or software rendering
861                 qglBegin(GL_TRIANGLES);
862                 qglEnd();
863                 CHECKGLERROR
864         }
865         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCILTWOSIDE)
866                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
867         memset(&m, 0, sizeof(m));
868         R_Mesh_State(&m);
869 }
870
871 void R_Shadow_RenderMode_StencilShadowVolumes(void)
872 {
873         R_Shadow_RenderMode_Reset();
874         GL_Color(1, 1, 1, 1);
875         GL_ColorMask(0, 0, 0, 0);
876         GL_BlendFunc(GL_ONE, GL_ZERO);
877         GL_DepthMask(false);
878         GL_DepthTest(true);
879         qglPolygonOffset(r_shadowpolygonfactor, r_shadowpolygonoffset);
880         qglDepthFunc(GL_LESS);
881         qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
882         qglEnable(GL_STENCIL_TEST);
883         qglStencilFunc(GL_ALWAYS, 128, ~0);
884         r_shadow_rendermode = r_shadow_shadowingrendermode;
885         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCILTWOSIDE)
886         {
887                 qglDisable(GL_CULL_FACE);
888                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
889                 qglActiveStencilFaceEXT(GL_BACK); // quake is backwards, this is front faces
890                 qglStencilMask(~0);
891                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
892                 qglActiveStencilFaceEXT(GL_FRONT); // quake is backwards, this is back faces
893                 qglStencilMask(~0);
894                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
895         }
896         else
897         {
898                 qglEnable(GL_CULL_FACE);
899                 qglStencilMask(~0);
900                 // this is changed by every shadow render so its value here is unimportant
901                 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
902         }
903         GL_Clear(GL_STENCIL_BUFFER_BIT);
904         renderstats.lights_clears++;
905 }
906
907 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent)
908 {
909         R_Shadow_RenderMode_Reset();
910         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
911         GL_DepthMask(false);
912         GL_DepthTest(true);
913         qglPolygonOffset(r_polygonfactor, r_polygonoffset);
914         //qglDisable(GL_POLYGON_OFFSET_FILL);
915         GL_Color(1, 1, 1, 1);
916         GL_ColorMask(r_refdef.colormask[0], r_refdef.colormask[1], r_refdef.colormask[2], 1);
917         if (transparent)
918                 qglDepthFunc(GL_LEQUAL);
919         else
920                 qglDepthFunc(GL_EQUAL);
921         qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
922         qglEnable(GL_CULL_FACE);
923         if (stenciltest)
924                 qglEnable(GL_STENCIL_TEST);
925         else
926                 qglDisable(GL_STENCIL_TEST);
927         qglStencilMask(~0);
928         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
929         // only draw light where this geometry was already rendered AND the
930         // stencil is 128 (values other than this mean shadow)
931         qglStencilFunc(GL_EQUAL, 128, ~0);
932         r_shadow_rendermode = r_shadow_lightingrendermode;
933         // do global setup needed for the chosen lighting mode
934         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
935         {
936                 R_Mesh_TexBind(0, R_GetTexture(r_texture_blanknormalmap)); // normal
937                 R_Mesh_TexBind(1, R_GetTexture(r_texture_white)); // diffuse
938                 R_Mesh_TexBind(2, R_GetTexture(r_texture_white)); // gloss
939                 R_Mesh_TexBindCubeMap(3, R_GetTexture(r_shadow_rtlight->currentcubemap)); // light filter
940                 R_Mesh_TexBind(4, R_GetTexture(r_texture_fogattenuation)); // fog
941                 R_Mesh_TexBind(5, R_GetTexture(r_texture_white)); // pants
942                 R_Mesh_TexBind(6, R_GetTexture(r_texture_white)); // shirt
943                 //R_Mesh_TexMatrix(3, r_shadow_entitytolight); // light filter matrix
944                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
945                 GL_ColorMask(r_refdef.colormask[0], r_refdef.colormask[1], r_refdef.colormask[2], 0);
946                 CHECKGLERROR
947         }
948 }
949
950 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
951 {
952         R_Shadow_RenderMode_Reset();
953         GL_BlendFunc(GL_ONE, GL_ONE);
954         GL_DepthMask(false);
955         GL_DepthTest(!r_showdisabledepthtest.integer);
956         qglPolygonOffset(r_polygonfactor, r_polygonoffset);
957         GL_Color(0.0, 0.0125, 0.1, 1);
958         GL_ColorMask(r_refdef.colormask[0], r_refdef.colormask[1], r_refdef.colormask[2], 1);
959         qglDepthFunc(GL_GEQUAL);
960         qglCullFace(GL_FRONT); // this culls back
961         qglDisable(GL_CULL_FACE);
962         qglDisable(GL_STENCIL_TEST);
963         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
964 }
965
966 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
967 {
968         R_Shadow_RenderMode_Reset();
969         GL_BlendFunc(GL_ONE, GL_ONE);
970         GL_DepthMask(false);
971         GL_DepthTest(!r_showdisabledepthtest.integer);
972         qglPolygonOffset(r_polygonfactor, r_polygonoffset);
973         GL_Color(0.1, 0.0125, 0, 1);
974         GL_ColorMask(r_refdef.colormask[0], r_refdef.colormask[1], r_refdef.colormask[2], 1);
975         if (transparent)
976                 qglDepthFunc(GL_LEQUAL);
977         else
978                 qglDepthFunc(GL_EQUAL);
979         qglCullFace(GL_FRONT); // this culls back
980         qglEnable(GL_CULL_FACE);
981         if (stenciltest)
982                 qglEnable(GL_STENCIL_TEST);
983         else
984                 qglDisable(GL_STENCIL_TEST);
985         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
986 }
987
988 void R_Shadow_RenderMode_End(void)
989 {
990         R_Shadow_RenderMode_Reset();
991         R_Shadow_RenderMode_ActiveLight(NULL);
992         GL_BlendFunc(GL_ONE, GL_ZERO);
993         GL_DepthMask(true);
994         GL_DepthTest(true);
995         qglPolygonOffset(r_polygonfactor, r_polygonoffset);
996         //qglDisable(GL_POLYGON_OFFSET_FILL);
997         GL_Color(1, 1, 1, 1);
998         GL_ColorMask(r_refdef.colormask[0], r_refdef.colormask[1], r_refdef.colormask[2], 1);
999         GL_Scissor(r_view_x, r_view_y, r_view_width, r_view_height);
1000         qglDepthFunc(GL_LEQUAL);
1001         qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
1002         qglEnable(GL_CULL_FACE);
1003         qglDisable(GL_STENCIL_TEST);
1004         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
1005         if (gl_support_stenciltwoside)
1006                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
1007         qglStencilMask(~0);
1008         qglStencilFunc(GL_ALWAYS, 128, ~0);
1009         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1010 }
1011
1012 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
1013 {
1014         int i, ix1, iy1, ix2, iy2;
1015         float x1, y1, x2, y2;
1016         vec4_t v, v2;
1017         rmesh_t mesh;
1018         mplane_t planes[11];
1019         float vertex3f[256*3];
1020
1021         // if view is inside the light box, just say yes it's visible
1022         if (BoxesOverlap(r_vieworigin, r_vieworigin, mins, maxs))
1023         {
1024                 GL_Scissor(r_view_x, r_view_y, r_view_width, r_view_height);
1025                 return false;
1026         }
1027
1028         // create a temporary brush describing the area the light can affect in worldspace
1029         VectorNegate(frustum[0].normal, planes[ 0].normal);planes[ 0].dist = -frustum[0].dist;
1030         VectorNegate(frustum[1].normal, planes[ 1].normal);planes[ 1].dist = -frustum[1].dist;
1031         VectorNegate(frustum[2].normal, planes[ 2].normal);planes[ 2].dist = -frustum[2].dist;
1032         VectorNegate(frustum[3].normal, planes[ 3].normal);planes[ 3].dist = -frustum[3].dist;
1033         VectorNegate(frustum[4].normal, planes[ 4].normal);planes[ 4].dist = -frustum[4].dist;
1034         VectorSet   (planes[ 5].normal,  1, 0, 0);         planes[ 5].dist =  maxs[0];
1035         VectorSet   (planes[ 6].normal, -1, 0, 0);         planes[ 6].dist = -mins[0];
1036         VectorSet   (planes[ 7].normal, 0,  1, 0);         planes[ 7].dist =  maxs[1];
1037         VectorSet   (planes[ 8].normal, 0, -1, 0);         planes[ 8].dist = -mins[1];
1038         VectorSet   (planes[ 9].normal, 0, 0,  1);         planes[ 9].dist =  maxs[2];
1039         VectorSet   (planes[10].normal, 0, 0, -1);         planes[10].dist = -mins[2];
1040
1041         // turn the brush into a mesh
1042         memset(&mesh, 0, sizeof(rmesh_t));
1043         mesh.maxvertices = 256;
1044         mesh.vertex3f = vertex3f;
1045         mesh.epsilon2 = (1.0f / (32.0f * 32.0f));
1046         R_Mesh_AddBrushMeshFromPlanes(&mesh, 11, planes);
1047
1048         // if that mesh is empty, the light is not visible at all
1049         if (!mesh.numvertices)
1050                 return true;
1051
1052         if (!r_shadow_scissor.integer)
1053                 return false;
1054
1055         // if that mesh is not empty, check what area of the screen it covers
1056         x1 = y1 = x2 = y2 = 0;
1057         v[3] = 1.0f;
1058         for (i = 0;i < mesh.numvertices;i++)
1059         {
1060                 VectorCopy(mesh.vertex3f + i * 3, v);
1061                 GL_TransformToScreen(v, v2);
1062                 //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]);
1063                 if (i)
1064                 {
1065                         if (x1 > v2[0]) x1 = v2[0];
1066                         if (x2 < v2[0]) x2 = v2[0];
1067                         if (y1 > v2[1]) y1 = v2[1];
1068                         if (y2 < v2[1]) y2 = v2[1];
1069                 }
1070                 else
1071                 {
1072                         x1 = x2 = v2[0];
1073                         y1 = y2 = v2[1];
1074                 }
1075         }
1076
1077         // now convert the scissor rectangle to integer screen coordinates
1078         ix1 = (int)(x1 - 1.0f);
1079         iy1 = (int)(y1 - 1.0f);
1080         ix2 = (int)(x2 + 1.0f);
1081         iy2 = (int)(y2 + 1.0f);
1082         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
1083
1084         // clamp it to the screen
1085         if (ix1 < r_view_x) ix1 = r_view_x;
1086         if (iy1 < r_view_y) iy1 = r_view_y;
1087         if (ix2 > r_view_x + r_view_width) ix2 = r_view_x + r_view_width;
1088         if (iy2 > r_view_y + r_view_height) iy2 = r_view_y + r_view_height;
1089
1090         // if it is inside out, it's not visible
1091         if (ix2 <= ix1 || iy2 <= iy1)
1092                 return true;
1093
1094         // the light area is visible, set up the scissor rectangle
1095         GL_Scissor(ix1, vid.height - iy2, ix2 - ix1, iy2 - iy1);
1096         //qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);
1097         //qglEnable(GL_SCISSOR_TEST);
1098         renderstats.lights_scissored++;
1099         return false;
1100 }
1101
1102 static void R_Shadow_RenderSurfacesLighting_Light_Vertex_Shading(const msurface_t *surface, const float *diffusecolor, const float *ambientcolor)
1103 {
1104         int numverts = surface->num_vertices;
1105         float *vertex3f = rsurface_vertex3f + 3 * surface->num_firstvertex;
1106         float *normal3f = rsurface_normal3f + 3 * surface->num_firstvertex;
1107         float *color4f = rsurface_array_color4f + 4 * surface->num_firstvertex;
1108         float dist, dot, distintensity, shadeintensity, v[3], n[3];
1109         if (r_textureunits.integer >= 3)
1110         {
1111                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1112                 {
1113                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1114                         Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1115                         if ((dot = DotProduct(n, v)) < 0)
1116                         {
1117                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1118                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]);
1119                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]);
1120                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]);
1121                                 if (fogenabled)
1122                                 {
1123                                         float f = VERTEXFOGTABLE(VectorDistance(v, r_shadow_entityeyeorigin));
1124                                         VectorScale(color4f, f, color4f);
1125                                 }
1126                         }
1127                         else
1128                                 VectorClear(color4f);
1129                         color4f[3] = 1;
1130                 }
1131         }
1132         else if (r_textureunits.integer >= 2)
1133         {
1134                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1135                 {
1136                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1137                         if ((dist = fabs(v[2])) < 1)
1138                         {
1139                                 distintensity = pow(1 - dist, r_shadow_attenpower) * r_shadow_attenscale;
1140                                 Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1141                                 if ((dot = DotProduct(n, v)) < 0)
1142                                 {
1143                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1144                                         color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
1145                                         color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
1146                                         color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
1147                                 }
1148                                 else
1149                                 {
1150                                         color4f[0] = ambientcolor[0] * distintensity;
1151                                         color4f[1] = ambientcolor[1] * distintensity;
1152                                         color4f[2] = ambientcolor[2] * distintensity;
1153                                 }
1154                                 if (fogenabled)
1155                                 {
1156                                         float f = VERTEXFOGTABLE(VectorDistance(v, r_shadow_entityeyeorigin));
1157                                         VectorScale(color4f, f, color4f);
1158                                 }
1159                         }
1160                         else
1161                                 VectorClear(color4f);
1162                         color4f[3] = 1;
1163                 }
1164         }
1165         else
1166         {
1167                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1168                 {
1169                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1170                         if ((dist = DotProduct(v, v)) < 1)
1171                         {
1172                                 dist = sqrt(dist);
1173                                 distintensity = pow(1 - dist, r_shadow_attenpower) * r_shadow_attenscale;
1174                                 Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1175                                 if ((dot = DotProduct(n, v)) < 0)
1176                                 {
1177                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1178                                         color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
1179                                         color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
1180                                         color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
1181                                 }
1182                                 else
1183                                 {
1184                                         color4f[0] = ambientcolor[0] * distintensity;
1185                                         color4f[1] = ambientcolor[1] * distintensity;
1186                                         color4f[2] = ambientcolor[2] * distintensity;
1187                                 }
1188                                 if (fogenabled)
1189                                 {
1190                                         float f = VERTEXFOGTABLE(VectorDistance(v, r_shadow_entityeyeorigin));
1191                                         VectorScale(color4f, f, color4f);
1192                                 }
1193                         }
1194                         else
1195                                 VectorClear(color4f);
1196                         color4f[3] = 1;
1197                 }
1198         }
1199 }
1200
1201 // TODO: use glTexGen instead of feeding vertices to texcoordpointer?
1202
1203 static void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(float *out3f, int numverts, const float *vertex3f, const float *svector3f, const float *tvector3f, const float *normal3f, const vec3_t relativelightorigin)
1204 {
1205         int i;
1206         float lightdir[3];
1207         for (i = 0;i < numverts;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
1208         {
1209                 VectorSubtract(relativelightorigin, vertex3f, lightdir);
1210                 // the cubemap normalizes this for us
1211                 out3f[0] = DotProduct(svector3f, lightdir);
1212                 out3f[1] = DotProduct(tvector3f, lightdir);
1213                 out3f[2] = DotProduct(normal3f, lightdir);
1214         }
1215 }
1216
1217 static void R_Shadow_GenTexCoords_Specular_NormalCubeMap(float *out3f, int numverts, const float *vertex3f, const float *svector3f, const float *tvector3f, const float *normal3f, const vec3_t relativelightorigin, const vec3_t relativeeyeorigin)
1218 {
1219         int i;
1220         float lightdir[3], eyedir[3], halfdir[3];
1221         for (i = 0;i < numverts;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
1222         {
1223                 VectorSubtract(relativelightorigin, vertex3f, lightdir);
1224                 VectorNormalize(lightdir);
1225                 VectorSubtract(relativeeyeorigin, vertex3f, eyedir);
1226                 VectorNormalize(eyedir);
1227                 VectorAdd(lightdir, eyedir, halfdir);
1228                 // the cubemap normalizes this for us
1229                 out3f[0] = DotProduct(svector3f, halfdir);
1230                 out3f[1] = DotProduct(tvector3f, halfdir);
1231                 out3f[2] = DotProduct(normal3f, halfdir);
1232         }
1233 }
1234
1235 static void R_Shadow_RenderSurfacesLighting_VisibleLighting(const entity_render_t *ent, const texture_t *texture, 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)
1236 {
1237         // used to display how many times a surface is lit for level design purposes
1238         int surfacelistindex;
1239         model_t *model = ent->model;
1240         rmeshstate_t m;
1241         GL_Color(0.1, 0.025, 0, 1);
1242         memset(&m, 0, sizeof(m));
1243         R_Mesh_State(&m);
1244         RSurf_SetPointersForPass(false, false);
1245         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1246         {
1247                 const msurface_t *surface = surfacelist[surfacelistindex];
1248                 if (rsurface_dynamicvertex)
1249                         RSurf_PrepareDynamicSurfaceVertices(surface);
1250                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1251                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);
1252                 GL_LockArrays(0, 0);
1253         }
1254 }
1255
1256 static void R_Shadow_RenderSurfacesLighting_Light_GLSL(const entity_render_t *ent, const texture_t *texture, 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)
1257 {
1258         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
1259         int surfacelistindex;
1260         model_t *model = ent->model;
1261         R_SetupSurfaceShader(ent, texture, r_shadow_entityeyeorigin, lightcolorbase, false);
1262         RSurf_SetPointersForPass(false, true);
1263         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1264         {
1265                 const msurface_t *surface = surfacelist[surfacelistindex];
1266                 const int *elements = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1267                 if (rsurface_dynamicvertex)
1268                         RSurf_PrepareDynamicSurfaceVertices(surface);
1269                 R_Mesh_TexCoordPointer(0, 2, model->surfmesh.data_texcoordtexture2f);
1270                 R_Mesh_TexCoordPointer(1, 3, rsurface_svector3f);
1271                 R_Mesh_TexCoordPointer(2, 3, rsurface_tvector3f);
1272                 R_Mesh_TexCoordPointer(3, 3, rsurface_normal3f);
1273                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1274                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1275                 GL_LockArrays(0, 0);
1276         }
1277 }
1278
1279 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(const entity_render_t *ent, const texture_t *texture, const msurface_t *surface, const vec3_t lightcolorbase, rtexture_t *basetexture, float colorscale)
1280 {
1281         int renders;
1282         model_t *model = ent->model;
1283         float color2[3];
1284         rmeshstate_t m;
1285         const int *elements = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1286         GL_Color(1,1,1,1);
1287         // colorscale accounts for how much we multiply the brightness
1288         // during combine.
1289         //
1290         // mult is how many times the final pass of the lighting will be
1291         // performed to get more brightness than otherwise possible.
1292         //
1293         // Limit mult to 64 for sanity sake.
1294         if (r_shadow_texture3d.integer && r_shadow_rtlight->currentcubemap != r_texture_whitecube && r_textureunits.integer >= 4)
1295         {
1296                 // 3 3D combine path (Geforce3, Radeon 8500)
1297                 memset(&m, 0, sizeof(m));
1298                 m.pointer_vertex = rsurface_vertex3f;
1299                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1300                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1301                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1302                 m.tex[1] = R_GetTexture(basetexture);
1303                 m.pointer_texcoord[1] = model->surfmesh.data_texcoordtexture2f;
1304                 m.texmatrix[1] = texture->currenttexmatrix;
1305                 m.texcubemap[2] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1306                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1307                 m.texmatrix[2] = r_shadow_entitytolight;
1308                 GL_BlendFunc(GL_ONE, GL_ONE);
1309         }
1310         else if (r_shadow_texture3d.integer && r_shadow_rtlight->currentcubemap == r_texture_whitecube && r_textureunits.integer >= 2)
1311         {
1312                 // 2 3D combine path (Geforce3, original Radeon)
1313                 memset(&m, 0, sizeof(m));
1314                 m.pointer_vertex = rsurface_vertex3f;
1315                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1316                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1317                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1318                 m.tex[1] = R_GetTexture(basetexture);
1319                 m.pointer_texcoord[1] = model->surfmesh.data_texcoordtexture2f;
1320                 m.texmatrix[1] = texture->currenttexmatrix;
1321                 GL_BlendFunc(GL_ONE, GL_ONE);
1322         }
1323         else if (r_textureunits.integer >= 4 && r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1324         {
1325                 // 4 2D combine path (Geforce3, Radeon 8500)
1326                 memset(&m, 0, sizeof(m));
1327                 m.pointer_vertex = rsurface_vertex3f;
1328                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1329                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1330                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1331                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1332                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1333                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1334                 m.tex[2] = R_GetTexture(basetexture);
1335                 m.pointer_texcoord[2] = model->surfmesh.data_texcoordtexture2f;
1336                 m.texmatrix[2] = texture->currenttexmatrix;
1337                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1338                 {
1339                         m.texcubemap[3] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1340                         m.pointer_texcoord3f[3] = rsurface_vertex3f;
1341                         m.texmatrix[3] = r_shadow_entitytolight;
1342                 }
1343                 GL_BlendFunc(GL_ONE, GL_ONE);
1344         }
1345         else if (r_textureunits.integer >= 3 && r_shadow_rtlight->currentcubemap == r_texture_whitecube)
1346         {
1347                 // 3 2D combine path (Geforce3, original Radeon)
1348                 memset(&m, 0, sizeof(m));
1349                 m.pointer_vertex = rsurface_vertex3f;
1350                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1351                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1352                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1353                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1354                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1355                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1356                 m.tex[2] = R_GetTexture(basetexture);
1357                 m.pointer_texcoord[2] = model->surfmesh.data_texcoordtexture2f;
1358                 m.texmatrix[2] = texture->currenttexmatrix;
1359                 GL_BlendFunc(GL_ONE, GL_ONE);
1360         }
1361         else
1362         {
1363                 // 2/2/2 2D combine path (any dot3 card)
1364                 memset(&m, 0, sizeof(m));
1365                 m.pointer_vertex = rsurface_vertex3f;
1366                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1367                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1368                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1369                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1370                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1371                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1372                 R_Mesh_State(&m);
1373                 GL_ColorMask(0,0,0,1);
1374                 GL_BlendFunc(GL_ONE, GL_ZERO);
1375                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1376                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1377                 GL_LockArrays(0, 0);
1378
1379                 memset(&m, 0, sizeof(m));
1380                 m.pointer_vertex = rsurface_vertex3f;
1381                 m.tex[0] = R_GetTexture(basetexture);
1382                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1383                 m.texmatrix[0] = texture->currenttexmatrix;
1384                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1385                 {
1386                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1387                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1388                         m.texmatrix[1] = r_shadow_entitytolight;
1389                 }
1390                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1391         }
1392         // this final code is shared
1393         R_Mesh_State(&m);
1394         GL_ColorMask(r_refdef.colormask[0], r_refdef.colormask[1], r_refdef.colormask[2], 0);
1395         VectorScale(lightcolorbase, colorscale, color2);
1396         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1397         for (renders = 0;renders < 64 && (color2[0] > 0 || color2[1] > 0 || color2[2] > 0);renders++, color2[0]--, color2[1]--, color2[2]--)
1398         {
1399                 GL_Color(bound(0, color2[0], 1), bound(0, color2[1], 1), bound(0, color2[2], 1), 1);
1400                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1401         }
1402         GL_LockArrays(0, 0);
1403 }
1404
1405 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(const entity_render_t *ent, const texture_t *texture, const msurface_t *surface, const vec3_t lightcolorbase, rtexture_t *basetexture, rtexture_t *normalmaptexture, float colorscale)
1406 {
1407         int renders;
1408         model_t *model = ent->model;
1409         float color2[3];
1410         rmeshstate_t m;
1411         const int *elements = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1412         GL_Color(1,1,1,1);
1413         // colorscale accounts for how much we multiply the brightness
1414         // during combine.
1415         //
1416         // mult is how many times the final pass of the lighting will be
1417         // performed to get more brightness than otherwise possible.
1418         //
1419         // Limit mult to 64 for sanity sake.
1420         if (r_shadow_texture3d.integer && r_textureunits.integer >= 4)
1421         {
1422                 // 3/2 3D combine path (Geforce3, Radeon 8500)
1423                 memset(&m, 0, sizeof(m));
1424                 m.pointer_vertex = rsurface_vertex3f;
1425                 m.tex[0] = R_GetTexture(normalmaptexture);
1426                 m.texcombinergb[0] = GL_REPLACE;
1427                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1428                 m.texmatrix[0] = texture->currenttexmatrix;
1429                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1430                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1431                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1432                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(rsurface_array_texcoord3f + 3 * surface->num_firstvertex, surface->num_vertices, rsurface_vertex3f + 3 * surface->num_firstvertex, rsurface_svector3f + 3 * surface->num_firstvertex, rsurface_tvector3f + 3 * surface->num_firstvertex, rsurface_normal3f + 3 * surface->num_firstvertex, r_shadow_entitylightorigin);
1433                 m.tex3d[2] = R_GetTexture(r_shadow_attenuation3dtexture);
1434                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1435                 m.texmatrix[2] = r_shadow_entitytoattenuationxyz;
1436                 R_Mesh_State(&m);
1437                 GL_ColorMask(0,0,0,1);
1438                 GL_BlendFunc(GL_ONE, GL_ZERO);
1439                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1440                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1441                 GL_LockArrays(0, 0);
1442
1443                 memset(&m, 0, sizeof(m));
1444                 m.pointer_vertex = rsurface_vertex3f;
1445                 m.tex[0] = R_GetTexture(basetexture);
1446                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1447                 m.texmatrix[0] = texture->currenttexmatrix;
1448                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1449                 {
1450                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1451                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1452                         m.texmatrix[1] = r_shadow_entitytolight;
1453                 }
1454                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1455         }
1456         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1457         {
1458                 // 1/2/2 3D combine path (original Radeon)
1459                 memset(&m, 0, sizeof(m));
1460                 m.pointer_vertex = rsurface_vertex3f;
1461                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1462                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1463                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1464                 R_Mesh_State(&m);
1465                 GL_ColorMask(0,0,0,1);
1466                 GL_BlendFunc(GL_ONE, GL_ZERO);
1467                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1468                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1469                 GL_LockArrays(0, 0);
1470
1471                 memset(&m, 0, sizeof(m));
1472                 m.pointer_vertex = rsurface_vertex3f;
1473                 m.tex[0] = R_GetTexture(normalmaptexture);
1474                 m.texcombinergb[0] = GL_REPLACE;
1475                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1476                 m.texmatrix[0] = texture->currenttexmatrix;
1477                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1478                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1479                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1480                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(rsurface_array_texcoord3f + 3 * surface->num_firstvertex, surface->num_vertices, rsurface_vertex3f + 3 * surface->num_firstvertex, rsurface_svector3f + 3 * surface->num_firstvertex, rsurface_tvector3f + 3 * surface->num_firstvertex, rsurface_normal3f + 3 * surface->num_firstvertex, r_shadow_entitylightorigin);
1481                 R_Mesh_State(&m);
1482                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1483                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1484                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1485                 GL_LockArrays(0, 0);
1486
1487                 memset(&m, 0, sizeof(m));
1488                 m.pointer_vertex = rsurface_vertex3f;
1489                 m.tex[0] = R_GetTexture(basetexture);
1490                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1491                 m.texmatrix[0] = texture->currenttexmatrix;
1492                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1493                 {
1494                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1495                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1496                         m.texmatrix[1] = r_shadow_entitytolight;
1497                 }
1498                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1499         }
1500         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap == r_texture_whitecube)
1501         {
1502                 // 2/2 3D combine path (original Radeon)
1503                 memset(&m, 0, sizeof(m));
1504                 m.pointer_vertex = rsurface_vertex3f;
1505                 m.tex[0] = R_GetTexture(normalmaptexture);
1506                 m.texcombinergb[0] = GL_REPLACE;
1507                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1508                 m.texmatrix[0] = texture->currenttexmatrix;
1509                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1510                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1511                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1512                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(rsurface_array_texcoord3f + 3 * surface->num_firstvertex, surface->num_vertices, rsurface_vertex3f + 3 * surface->num_firstvertex, rsurface_svector3f + 3 * surface->num_firstvertex, rsurface_tvector3f + 3 * surface->num_firstvertex, rsurface_normal3f + 3 * surface->num_firstvertex, r_shadow_entitylightorigin);
1513                 R_Mesh_State(&m);
1514                 GL_ColorMask(0,0,0,1);
1515                 GL_BlendFunc(GL_ONE, GL_ZERO);
1516                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1517                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1518                 GL_LockArrays(0, 0);
1519
1520                 memset(&m, 0, sizeof(m));
1521                 m.pointer_vertex = rsurface_vertex3f;
1522                 m.tex[0] = R_GetTexture(basetexture);
1523                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1524                 m.texmatrix[0] = texture->currenttexmatrix;
1525                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
1526                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1527                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1528                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1529         }
1530         else if (r_textureunits.integer >= 4)
1531         {
1532                 // 4/2 2D combine path (Geforce3, Radeon 8500)
1533                 memset(&m, 0, sizeof(m));
1534                 m.pointer_vertex = rsurface_vertex3f;
1535                 m.tex[0] = R_GetTexture(normalmaptexture);
1536                 m.texcombinergb[0] = GL_REPLACE;
1537                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1538                 m.texmatrix[0] = texture->currenttexmatrix;
1539                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1540                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1541                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1542                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(rsurface_array_texcoord3f + 3 * surface->num_firstvertex, surface->num_vertices, rsurface_vertex3f + 3 * surface->num_firstvertex, rsurface_svector3f + 3 * surface->num_firstvertex, rsurface_tvector3f + 3 * surface->num_firstvertex, rsurface_normal3f + 3 * surface->num_firstvertex, r_shadow_entitylightorigin);
1543                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
1544                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1545                 m.texmatrix[2] = r_shadow_entitytoattenuationxyz;
1546                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
1547                 m.pointer_texcoord3f[3] = rsurface_vertex3f;
1548                 m.texmatrix[3] = r_shadow_entitytoattenuationz;
1549                 R_Mesh_State(&m);
1550                 GL_ColorMask(0,0,0,1);
1551                 GL_BlendFunc(GL_ONE, GL_ZERO);
1552                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1553                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1554                 GL_LockArrays(0, 0);
1555
1556                 memset(&m, 0, sizeof(m));
1557                 m.pointer_vertex = rsurface_vertex3f;
1558                 m.tex[0] = R_GetTexture(basetexture);
1559                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1560                 m.texmatrix[0] = texture->currenttexmatrix;
1561                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1562                 {
1563                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1564                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1565                         m.texmatrix[1] = r_shadow_entitytolight;
1566                 }
1567                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1568         }
1569         else
1570         {
1571                 // 2/2/2 2D combine path (any dot3 card)
1572                 memset(&m, 0, sizeof(m));
1573                 m.pointer_vertex = rsurface_vertex3f;
1574                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1575                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1576                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1577                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1578                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1579                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1580                 R_Mesh_State(&m);
1581                 GL_ColorMask(0,0,0,1);
1582                 GL_BlendFunc(GL_ONE, GL_ZERO);
1583                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1584                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1585                 GL_LockArrays(0, 0);
1586
1587                 memset(&m, 0, sizeof(m));
1588                 m.pointer_vertex = rsurface_vertex3f;
1589                 m.tex[0] = R_GetTexture(normalmaptexture);
1590                 m.texcombinergb[0] = GL_REPLACE;
1591                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1592                 m.texmatrix[0] = texture->currenttexmatrix;
1593                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1594                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1595                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1596                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(rsurface_array_texcoord3f + 3 * surface->num_firstvertex, surface->num_vertices, rsurface_vertex3f + 3 * surface->num_firstvertex, rsurface_svector3f + 3 * surface->num_firstvertex, rsurface_tvector3f + 3 * surface->num_firstvertex, rsurface_normal3f + 3 * surface->num_firstvertex, r_shadow_entitylightorigin);
1597                 R_Mesh_State(&m);
1598                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1599                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1600                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1601                 GL_LockArrays(0, 0);
1602
1603                 memset(&m, 0, sizeof(m));
1604                 m.pointer_vertex = rsurface_vertex3f;
1605                 m.tex[0] = R_GetTexture(basetexture);
1606                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1607                 m.texmatrix[0] = texture->currenttexmatrix;
1608                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1609                 {
1610                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1611                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1612                         m.texmatrix[1] = r_shadow_entitytolight;
1613                 }
1614                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1615         }
1616         // this final code is shared
1617         R_Mesh_State(&m);
1618         GL_ColorMask(r_refdef.colormask[0], r_refdef.colormask[1], r_refdef.colormask[2], 0);
1619         VectorScale(lightcolorbase, colorscale, color2);
1620         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1621         for (renders = 0;renders < 64 && (color2[0] > 0 || color2[1] > 0 || color2[2] > 0);renders++, color2[0]--, color2[1]--, color2[2]--)
1622         {
1623                 GL_Color(bound(0, color2[0], 1), bound(0, color2[1], 1), bound(0, color2[2], 1), 1);
1624                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1625         }
1626         GL_LockArrays(0, 0);
1627 }
1628
1629 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_SpecularPass(const entity_render_t *ent, const texture_t *texture, const msurface_t *surface, const vec3_t lightcolorbase, rtexture_t *glosstexture, rtexture_t *normalmaptexture, float colorscale)
1630 {
1631         int renders;
1632         model_t *model = ent->model;
1633         float color2[3];
1634         rmeshstate_t m;
1635         const int *elements = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1636         // FIXME: detect blendsquare!
1637         //if (!gl_support_blendsquare)
1638         //      return;
1639         GL_Color(1,1,1,1);
1640         if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap != r_texture_whitecube /* && gl_support_blendsquare*/) // FIXME: detect blendsquare!
1641         {
1642                 // 2/0/0/1/2 3D combine blendsquare path
1643                 memset(&m, 0, sizeof(m));
1644                 m.pointer_vertex = rsurface_vertex3f;
1645                 m.tex[0] = R_GetTexture(normalmaptexture);
1646                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1647                 m.texmatrix[0] = texture->currenttexmatrix;
1648                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1649                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1650                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1651                 R_Shadow_GenTexCoords_Specular_NormalCubeMap(rsurface_array_texcoord3f + 3 * surface->num_firstvertex, surface->num_vertices, rsurface_vertex3f + 3 * surface->num_firstvertex, rsurface_svector3f + 3 * surface->num_firstvertex, rsurface_tvector3f + 3 * surface->num_firstvertex, rsurface_normal3f + 3 * surface->num_firstvertex, r_shadow_entitylightorigin, r_shadow_entityeyeorigin);
1652                 R_Mesh_State(&m);
1653                 GL_ColorMask(0,0,0,1);
1654                 // this squares the result
1655                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1656                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1657                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1658                 GL_LockArrays(0, 0);
1659
1660                 memset(&m, 0, sizeof(m));
1661                 m.pointer_vertex = rsurface_vertex3f;
1662                 R_Mesh_State(&m);
1663                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1664                 // square alpha in framebuffer a few times to make it shiny
1665                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1666                 // these comments are a test run through this math for intensity 0.5
1667                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1668                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1669                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1670                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1671                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1672                 GL_LockArrays(0, 0);
1673
1674                 memset(&m, 0, sizeof(m));
1675                 m.pointer_vertex = rsurface_vertex3f;
1676                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1677                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1678                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1679                 R_Mesh_State(&m);
1680                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1681                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1682                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1683                 GL_LockArrays(0, 0);
1684
1685                 memset(&m, 0, sizeof(m));
1686                 m.pointer_vertex = rsurface_vertex3f;
1687                 m.tex[0] = R_GetTexture(glosstexture);
1688                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1689                 m.texmatrix[0] = texture->currenttexmatrix;
1690                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1691                 {
1692                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1693                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1694                         m.texmatrix[1] = r_shadow_entitytolight;
1695                 }
1696                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1697         }
1698         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap == r_texture_whitecube /* && gl_support_blendsquare*/) // FIXME: detect blendsquare!
1699         {
1700                 // 2/0/0/2 3D combine blendsquare path
1701                 memset(&m, 0, sizeof(m));
1702                 m.pointer_vertex = rsurface_vertex3f;
1703                 m.tex[0] = R_GetTexture(normalmaptexture);
1704                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1705                 m.texmatrix[0] = texture->currenttexmatrix;
1706                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1707                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1708                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1709                 R_Shadow_GenTexCoords_Specular_NormalCubeMap(rsurface_array_texcoord3f + 3 * surface->num_firstvertex, surface->num_vertices, rsurface_vertex3f + 3 * surface->num_firstvertex, rsurface_svector3f + 3 * surface->num_firstvertex, rsurface_tvector3f + 3 * surface->num_firstvertex, rsurface_normal3f + 3 * surface->num_firstvertex, r_shadow_entitylightorigin, r_shadow_entityeyeorigin);
1710                 R_Mesh_State(&m);
1711                 GL_ColorMask(0,0,0,1);
1712                 // this squares the result
1713                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1714                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1715                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1716                 GL_LockArrays(0, 0);
1717
1718                 memset(&m, 0, sizeof(m));
1719                 m.pointer_vertex = rsurface_vertex3f;
1720                 R_Mesh_State(&m);
1721                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1722                 // square alpha in framebuffer a few times to make it shiny
1723                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1724                 // these comments are a test run through this math for intensity 0.5
1725                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1726                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1727                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1728                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1729                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1730                 GL_LockArrays(0, 0);
1731
1732                 memset(&m, 0, sizeof(m));
1733                 m.pointer_vertex = rsurface_vertex3f;
1734                 m.tex[0] = R_GetTexture(glosstexture);
1735                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1736                 m.texmatrix[0] = texture->currenttexmatrix;
1737                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
1738                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1739                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1740                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1741         }
1742         else
1743         {
1744                 // 2/0/0/2/2 2D combine blendsquare path
1745                 memset(&m, 0, sizeof(m));
1746                 m.pointer_vertex = rsurface_vertex3f;
1747                 m.tex[0] = R_GetTexture(normalmaptexture);
1748                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1749                 m.texmatrix[0] = texture->currenttexmatrix;
1750                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1751                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1752                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1753                 R_Shadow_GenTexCoords_Specular_NormalCubeMap(rsurface_array_texcoord3f + 3 * surface->num_firstvertex, surface->num_vertices, rsurface_vertex3f + 3 * surface->num_firstvertex, rsurface_svector3f + 3 * surface->num_firstvertex, rsurface_tvector3f + 3 * surface->num_firstvertex, rsurface_normal3f + 3 * surface->num_firstvertex, r_shadow_entitylightorigin, r_shadow_entityeyeorigin);
1754                 R_Mesh_State(&m);
1755                 GL_ColorMask(0,0,0,1);
1756                 // this squares the result
1757                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1758                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1759                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1760                 GL_LockArrays(0, 0);
1761
1762                 memset(&m, 0, sizeof(m));
1763                 m.pointer_vertex = rsurface_vertex3f;
1764                 R_Mesh_State(&m);
1765                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1766                 // square alpha in framebuffer a few times to make it shiny
1767                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1768                 // these comments are a test run through this math for intensity 0.5
1769                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1770                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1771                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1772                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1773                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1774                 GL_LockArrays(0, 0);
1775
1776                 memset(&m, 0, sizeof(m));
1777                 m.pointer_vertex = rsurface_vertex3f;
1778                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1779                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1780                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1781                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1782                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1783                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1784                 R_Mesh_State(&m);
1785                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1786                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1787                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1788                 GL_LockArrays(0, 0);
1789
1790                 memset(&m, 0, sizeof(m));
1791                 m.pointer_vertex = rsurface_vertex3f;
1792                 m.tex[0] = R_GetTexture(glosstexture);
1793                 m.pointer_texcoord[0] = model->surfmesh.data_texcoordtexture2f;
1794                 m.texmatrix[0] = texture->currenttexmatrix;
1795                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1796                 {
1797                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1798                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1799                         m.texmatrix[1] = r_shadow_entitytolight;
1800                 }
1801                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1802         }
1803         R_Mesh_State(&m);
1804         GL_ColorMask(r_refdef.colormask[0], r_refdef.colormask[1], r_refdef.colormask[2], 0);
1805         VectorScale(lightcolorbase, colorscale, color2);
1806         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1807         for (renders = 0;renders < 64 && (color2[0] > 0 || color2[1] > 0 || color2[2] > 0);renders++, color2[0]--, color2[1]--, color2[2]--)
1808         {
1809                 GL_Color(bound(0, color2[0], 1), bound(0, color2[1], 1), bound(0, color2[2], 1), 1);
1810                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1811         }
1812         GL_LockArrays(0, 0);
1813 }
1814
1815 static void R_Shadow_RenderSurfacesLighting_Light_Dot3(const entity_render_t *ent, const texture_t *texture, 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)
1816 {
1817         // ARB path (any Geforce, any Radeon)
1818         int surfacelistindex;
1819         qboolean doambient = r_shadow_rtlight->ambientscale > 0;
1820         qboolean dodiffuse = r_shadow_rtlight->diffusescale > 0;
1821         qboolean dospecular = specularscale > 0;
1822         if (!doambient && !dodiffuse && !dospecular)
1823                 return;
1824         RSurf_SetPointersForPass(false, true);
1825         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1826         {
1827                 const msurface_t *surface = surfacelist[surfacelistindex];
1828                 if (rsurface_dynamicvertex)
1829                         RSurf_PrepareDynamicSurfaceVertices(surface);
1830                 if (doambient)
1831                         R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(ent, texture, surface, lightcolorbase, basetexture, r_shadow_rtlight->ambientscale);
1832                 if (dodiffuse)
1833                         R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(ent, texture, surface, lightcolorbase, basetexture, normalmaptexture, r_shadow_rtlight->diffusescale);
1834                 if (dopants)
1835                 {
1836                         if (doambient)
1837                                 R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(ent, texture, surface, lightcolorpants, pantstexture, r_shadow_rtlight->ambientscale);
1838                         if (dodiffuse)
1839                                 R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(ent, texture, surface, lightcolorpants, pantstexture, normalmaptexture, r_shadow_rtlight->diffusescale);
1840                 }
1841                 if (doshirt)
1842                 {
1843                         if (doambient)
1844                                 R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(ent, texture, surface, lightcolorshirt, shirttexture, r_shadow_rtlight->ambientscale);
1845                         if (dodiffuse)
1846                                 R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(ent, texture, surface, lightcolorshirt, shirttexture, normalmaptexture, r_shadow_rtlight->diffusescale);
1847                 }
1848                 if (dospecular)
1849                         R_Shadow_RenderSurfacesLighting_Light_Dot3_SpecularPass(ent, texture, surface, lightcolorbase, glosstexture, normalmaptexture, specularscale);
1850         }
1851 }
1852
1853 void R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(const model_t *model, const msurface_t *surface, vec3_t diffusecolor2, vec3_t ambientcolor2)
1854 {
1855         int renders;
1856         const int *elements = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1857         R_Shadow_RenderSurfacesLighting_Light_Vertex_Shading(surface, diffusecolor2, ambientcolor2);
1858         for (renders = 0;renders < 64 && (ambientcolor2[0] > renders || ambientcolor2[1] > renders || ambientcolor2[2] > renders || diffusecolor2[0] > renders || diffusecolor2[1] > renders || diffusecolor2[2] > renders);renders++)
1859         {
1860                 int i;
1861                 float *c;
1862 #if 1
1863                 // due to low fillrate on the cards this vertex lighting path is
1864                 // designed for, we manually cull all triangles that do not
1865                 // contain a lit vertex
1866                 int draw;
1867                 const int *e;
1868                 int newnumtriangles;
1869                 int *newe;
1870                 int newelements[3072];
1871                 draw = false;
1872                 newnumtriangles = 0;
1873                 newe = newelements;
1874                 for (i = 0, e = elements;i < surface->num_triangles;i++, e += 3)
1875                 {
1876                         if (newnumtriangles >= 1024)
1877                         {
1878                                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1879                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, newnumtriangles, newelements);
1880                                 GL_LockArrays(0, 0);
1881                                 newnumtriangles = 0;
1882                                 newe = newelements;
1883                         }
1884                         if (VectorLength2(rsurface_array_color4f + e[0] * 4) + VectorLength2(rsurface_array_color4f + e[1] * 4) + VectorLength2(rsurface_array_color4f + e[2] * 4) >= 0.01)
1885                         {
1886                                 newe[0] = e[0];
1887                                 newe[1] = e[1];
1888                                 newe[2] = e[2];
1889                                 newnumtriangles++;
1890                                 newe += 3;
1891                                 draw = true;
1892                         }
1893                 }
1894                 if (newnumtriangles >= 1)
1895                 {
1896                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1897                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, newnumtriangles, newelements);
1898                         GL_LockArrays(0, 0);
1899                         draw = true;
1900                 }
1901                 if (!draw)
1902                         break;
1903 #else
1904                 for (i = 0, c = rsurface_array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
1905                         if (VectorLength2(c))
1906                                 goto goodpass;
1907                 break;
1908 goodpass:
1909                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
1910                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, elements);
1911                 GL_LockArrays(0, 0);
1912 #endif
1913                 // now reduce the intensity for the next overbright pass
1914                 for (i = 0, c = rsurface_array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
1915                 {
1916                         c[0] = max(0, c[0] - 1);
1917                         c[1] = max(0, c[1] - 1);
1918                         c[2] = max(0, c[2] - 1);
1919                 }
1920         }
1921 }
1922
1923 static void R_Shadow_RenderSurfacesLighting_Light_Vertex(const entity_render_t *ent, const texture_t *texture, 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)
1924 {
1925         int surfacelistindex;
1926         model_t *model = ent->model;
1927         float ambientcolorbase[3], diffusecolorbase[3];
1928         float ambientcolorpants[3], diffusecolorpants[3];
1929         float ambientcolorshirt[3], diffusecolorshirt[3];
1930         rmeshstate_t m;
1931         VectorScale(lightcolorbase, r_shadow_rtlight->ambientscale * 2, ambientcolorbase);
1932         VectorScale(lightcolorbase, r_shadow_rtlight->diffusescale * 2, diffusecolorbase);
1933         VectorScale(lightcolorpants, r_shadow_rtlight->ambientscale * 2, ambientcolorpants);
1934         VectorScale(lightcolorpants, r_shadow_rtlight->diffusescale * 2, diffusecolorpants);
1935         VectorScale(lightcolorshirt, r_shadow_rtlight->ambientscale * 2, ambientcolorshirt);
1936         VectorScale(lightcolorshirt, r_shadow_rtlight->diffusescale * 2, diffusecolorshirt);
1937         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1938         memset(&m, 0, sizeof(m));
1939         m.tex[0] = R_GetTexture(basetexture);
1940         if (r_textureunits.integer >= 2)
1941         {
1942                 // voodoo2
1943                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1944                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1945                 if (r_textureunits.integer >= 3)
1946                 {
1947                         // Geforce3/Radeon class but not using dot3
1948                         m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
1949                         m.texmatrix[2] = r_shadow_entitytoattenuationz;
1950                 }
1951         }
1952         m.pointer_color = rsurface_array_color4f;
1953         R_Mesh_State(&m);
1954         RSurf_SetPointersForPass(true, false);
1955         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1956         {
1957                 const msurface_t *surface = surfacelist[surfacelistindex];
1958                 if (rsurface_dynamicvertex)
1959                         RSurf_PrepareDynamicSurfaceVertices(surface);
1960                 // OpenGL 1.1 path (anything)
1961                 R_Mesh_TexCoordPointer(0, 2, model->surfmesh.data_texcoordtexture2f);
1962                 R_Mesh_TexMatrix(0, &texture->currenttexmatrix);
1963                 if (r_textureunits.integer >= 2)
1964                 {
1965                         // voodoo2 or TNT
1966                         R_Mesh_TexCoordPointer(1, 3, rsurface_vertex3f);
1967                         if (r_textureunits.integer >= 3)
1968                         {
1969                                 // Voodoo4 or Kyro (or Geforce3/Radeon with gl_combine off)
1970                                 R_Mesh_TexCoordPointer(2, 3, rsurface_vertex3f);
1971                         }
1972                 }
1973                 R_Mesh_TexBind(0, R_GetTexture(basetexture));
1974                 R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, surface, diffusecolorbase, ambientcolorbase);
1975                 if (dopants)
1976                 {
1977                         R_Mesh_TexBind(0, R_GetTexture(pantstexture));
1978                         R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, surface, diffusecolorpants, ambientcolorpants);
1979                 }
1980                 if (doshirt)
1981                 {
1982                         R_Mesh_TexBind(0, R_GetTexture(shirttexture));
1983                         R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, surface, diffusecolorshirt, ambientcolorshirt);
1984                 }
1985         }
1986 }
1987
1988 void R_Shadow_RenderSurfacesLighting(const entity_render_t *ent, const texture_t *texture, int numsurfaces, msurface_t **surfacelist)
1989 {
1990         // FIXME: support MATERIALFLAG_NODEPTHTEST
1991         vec3_t lightcolorbase, lightcolorpants, lightcolorshirt;
1992         // calculate colors to render this texture with
1993         lightcolorbase[0] = r_shadow_rtlight->currentcolor[0] * ent->colormod[0] * texture->currentalpha;
1994         lightcolorbase[1] = r_shadow_rtlight->currentcolor[1] * ent->colormod[1] * texture->currentalpha;
1995         lightcolorbase[2] = r_shadow_rtlight->currentcolor[2] * ent->colormod[2] * texture->currentalpha;
1996         if ((r_shadow_rtlight->ambientscale + r_shadow_rtlight->diffusescale) * VectorLength2(lightcolorbase) + (r_shadow_rtlight->specularscale * texture->specularscale) * VectorLength2(lightcolorbase) < (1.0f / 1048576.0f))
1997                 return;
1998         if ((texture->textureflags & Q3TEXTUREFLAG_TWOSIDED) || (ent->flags & RENDER_NOCULLFACE))
1999                 qglDisable(GL_CULL_FACE);
2000         else
2001                 qglEnable(GL_CULL_FACE);
2002         RSurf_PrepareForBatch(ent, texture, r_shadow_entityeyeorigin);
2003         if (texture->colormapping)
2004         {
2005                 qboolean dopants = texture->skin.pants != NULL && VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f);
2006                 qboolean doshirt = texture->skin.shirt != NULL && VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f);
2007                 if (dopants)
2008                 {
2009                         lightcolorpants[0] = lightcolorbase[0] * ent->colormap_pantscolor[0];
2010                         lightcolorpants[1] = lightcolorbase[1] * ent->colormap_pantscolor[1];
2011                         lightcolorpants[2] = lightcolorbase[2] * ent->colormap_pantscolor[2];
2012                 }
2013                 else
2014                         VectorClear(lightcolorpants);
2015                 if (doshirt)
2016                 {
2017                         lightcolorshirt[0] = lightcolorbase[0] * ent->colormap_shirtcolor[0];
2018                         lightcolorshirt[1] = lightcolorbase[1] * ent->colormap_shirtcolor[1];
2019                         lightcolorshirt[2] = lightcolorbase[2] * ent->colormap_shirtcolor[2];
2020                 }
2021                 else
2022                         VectorClear(lightcolorshirt);
2023                 switch (r_shadow_rendermode)
2024                 {
2025                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2026                         R_Shadow_RenderSurfacesLighting_VisibleLighting(ent, texture, numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, texture->basetexture, texture->skin.pants, texture->skin.shirt, texture->skin.nmap, texture->glosstexture, r_shadow_rtlight->specularscale * texture->specularscale, dopants, doshirt);
2027                         break;
2028                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2029                         R_Shadow_RenderSurfacesLighting_Light_GLSL(ent, texture, numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, texture->basetexture, texture->skin.pants, texture->skin.shirt, texture->skin.nmap, texture->glosstexture, r_shadow_rtlight->specularscale * texture->specularscale, dopants, doshirt);
2030                         break;
2031                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2032                         R_Shadow_RenderSurfacesLighting_Light_Dot3(ent, texture, numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, texture->basetexture, texture->skin.pants, texture->skin.shirt, texture->skin.nmap, texture->glosstexture, r_shadow_rtlight->specularscale * texture->specularscale, dopants, doshirt);
2033                         break;
2034                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
2035                         R_Shadow_RenderSurfacesLighting_Light_Vertex(ent, texture, numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, texture->basetexture, texture->skin.pants, texture->skin.shirt, texture->skin.nmap, texture->glosstexture, r_shadow_rtlight->specularscale * texture->specularscale, dopants, doshirt);
2036                         break;
2037                 default:
2038                         Con_Printf("R_Shadow_RenderSurfacesLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
2039                         break;
2040                 }
2041         }
2042         else
2043         {
2044                 switch (r_shadow_rendermode)
2045                 {
2046                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2047                         R_Shadow_RenderSurfacesLighting_VisibleLighting(ent, texture, numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, texture->basetexture, r_texture_black, r_texture_black, texture->skin.nmap, texture->glosstexture, r_shadow_rtlight->specularscale * texture->specularscale, false, false);
2048                         break;
2049                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2050                         R_Shadow_RenderSurfacesLighting_Light_GLSL(ent, texture, numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, texture->basetexture, r_texture_black, r_texture_black, texture->skin.nmap, texture->glosstexture, r_shadow_rtlight->specularscale * texture->specularscale, false, false);
2051                         break;
2052                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2053                         R_Shadow_RenderSurfacesLighting_Light_Dot3(ent, texture, numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, texture->basetexture, r_texture_black, r_texture_black, texture->skin.nmap, texture->glosstexture, r_shadow_rtlight->specularscale * texture->specularscale, false, false);
2054                         break;
2055                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
2056                         R_Shadow_RenderSurfacesLighting_Light_Vertex(ent, texture, numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, texture->basetexture, r_texture_black, r_texture_black, texture->skin.nmap, texture->glosstexture, r_shadow_rtlight->specularscale * texture->specularscale, false, false);
2057                         break;
2058                 default:
2059                         Con_Printf("R_Shadow_RenderSurfacesLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
2060                         break;
2061                 }
2062         }
2063 }
2064
2065 void R_RTLight_Update(dlight_t *light, int isstatic)
2066 {
2067         int j, k;
2068         float scale;
2069         rtlight_t *rtlight = &light->rtlight;
2070         R_RTLight_Uncompile(rtlight);
2071         memset(rtlight, 0, sizeof(*rtlight));
2072
2073         VectorCopy(light->origin, rtlight->shadoworigin);
2074         VectorCopy(light->color, rtlight->color);
2075         rtlight->radius = light->radius;
2076         //rtlight->cullradius = rtlight->radius;
2077         //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
2078         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
2079         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
2080         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
2081         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
2082         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
2083         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
2084         rtlight->cubemapname[0] = 0;
2085         if (light->cubemapname[0])
2086                 strcpy(rtlight->cubemapname, light->cubemapname);
2087         else if (light->cubemapnum > 0)
2088                 sprintf(rtlight->cubemapname, "cubemaps/%i", light->cubemapnum);
2089         rtlight->shadow = light->shadow;
2090         rtlight->corona = light->corona;
2091         rtlight->style = light->style;
2092         rtlight->isstatic = isstatic;
2093         rtlight->coronasizescale = light->coronasizescale;
2094         rtlight->ambientscale = light->ambientscale;
2095         rtlight->diffusescale = light->diffusescale;
2096         rtlight->specularscale = light->specularscale;
2097         rtlight->flags = light->flags;
2098         Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &light->matrix);
2099         // ConcatScale won't work here because this needs to scale rotate and
2100         // translate, not just rotate
2101         scale = 1.0f / rtlight->radius;
2102         for (k = 0;k < 3;k++)
2103                 for (j = 0;j < 4;j++)
2104                         rtlight->matrix_worldtolight.m[k][j] *= scale;
2105 }
2106
2107 // compiles rtlight geometry
2108 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
2109 void R_RTLight_Compile(rtlight_t *rtlight)
2110 {
2111         int shadowmeshes, shadowtris, numleafs, numleafpvsbytes, numsurfaces;
2112         entity_render_t *ent = r_refdef.worldentity;
2113         model_t *model = r_refdef.worldmodel;
2114         unsigned char *data;
2115
2116         // compile the light
2117         rtlight->compiled = true;
2118         rtlight->static_numleafs = 0;
2119         rtlight->static_numleafpvsbytes = 0;
2120         rtlight->static_leaflist = NULL;
2121         rtlight->static_leafpvs = NULL;
2122         rtlight->static_numsurfaces = 0;
2123         rtlight->static_surfacelist = NULL;
2124         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
2125         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
2126         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
2127         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
2128         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
2129         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
2130
2131         if (model && model->GetLightInfo)
2132         {
2133                 // this variable must be set for the CompileShadowVolume code
2134                 r_shadow_compilingrtlight = rtlight;
2135                 R_Shadow_EnlargeLeafSurfaceBuffer(model->brush.num_leafs, model->num_surfaces);
2136                 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);
2137                 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
2138                 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numleafs + numleafpvsbytes + sizeof(int) * numsurfaces);
2139                 rtlight->static_numleafs = numleafs;
2140                 rtlight->static_numleafpvsbytes = numleafpvsbytes;
2141                 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
2142                 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
2143                 rtlight->static_numsurfaces = numsurfaces;
2144                 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
2145                 if (numleafs)
2146                         memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
2147                 if (numleafpvsbytes)
2148                         memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
2149                 if (numsurfaces)
2150                         memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
2151                 if (model->CompileShadowVolume && rtlight->shadow)
2152                         model->CompileShadowVolume(ent, rtlight->shadoworigin, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
2153                 // now we're done compiling the rtlight
2154                 r_shadow_compilingrtlight = NULL;
2155         }
2156
2157
2158         // use smallest available cullradius - box radius or light radius
2159         //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
2160         //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
2161
2162         shadowmeshes = 0;
2163         shadowtris = 0;
2164         if (rtlight->static_meshchain_shadow)
2165         {
2166                 shadowmesh_t *mesh;
2167                 for (mesh = rtlight->static_meshchain_shadow;mesh;mesh = mesh->next)
2168                 {
2169                         shadowmeshes++;
2170                         shadowtris += mesh->numtriangles;
2171                 }
2172         }
2173
2174         if (developer.integer >= 10)
2175                 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);
2176 }
2177
2178 void R_RTLight_Uncompile(rtlight_t *rtlight)
2179 {
2180         if (rtlight->compiled)
2181         {
2182                 if (rtlight->static_meshchain_shadow)
2183                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow);
2184                 rtlight->static_meshchain_shadow = NULL;
2185                 // these allocations are grouped
2186                 if (rtlight->static_leaflist)
2187                         Mem_Free(rtlight->static_leaflist);
2188                 rtlight->static_numleafs = 0;
2189                 rtlight->static_numleafpvsbytes = 0;
2190                 rtlight->static_leaflist = NULL;
2191                 rtlight->static_leafpvs = NULL;
2192                 rtlight->static_numsurfaces = 0;
2193                 rtlight->static_surfacelist = NULL;
2194                 rtlight->compiled = false;
2195         }
2196 }
2197
2198 void R_Shadow_UncompileWorldLights(void)
2199 {
2200         dlight_t *light;
2201         for (light = r_shadow_worldlightchain;light;light = light->next)
2202                 R_RTLight_Uncompile(&light->rtlight);
2203 }
2204
2205 void R_Shadow_DrawEntityShadow(entity_render_t *ent, int numsurfaces, int *surfacelist)
2206 {
2207         model_t *model = ent->model;
2208         vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
2209         vec_t relativeshadowradius;
2210         if (ent == r_refdef.worldentity)
2211         {
2212                 if (r_shadow_rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
2213                 {
2214                         shadowmesh_t *mesh;
2215                         R_Mesh_Matrix(&ent->matrix);
2216                         for (mesh = r_shadow_rtlight->static_meshchain_shadow;mesh;mesh = mesh->next)
2217                         {
2218                                 renderstats.lights_shadowtriangles += mesh->numtriangles;
2219                                 R_Mesh_VertexPointer(mesh->vertex3f);
2220                                 GL_LockArrays(0, mesh->numverts);
2221                                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCIL)
2222                                 {
2223                                         // decrement stencil if backface is behind depthbuffer
2224                                         qglCullFace(GL_BACK); // quake is backwards, this culls front faces
2225                                         qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
2226                                         R_Mesh_Draw(0, mesh->numverts, mesh->numtriangles, mesh->element3i);
2227                                         // increment stencil if frontface is behind depthbuffer
2228                                         qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
2229                                         qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
2230                                 }
2231                                 R_Mesh_Draw(0, mesh->numverts, mesh->numtriangles, mesh->element3i);
2232                                 GL_LockArrays(0, 0);
2233                         }
2234                 }
2235                 else if (numsurfaces)
2236                 {
2237                         R_Mesh_Matrix(&ent->matrix);
2238                         model->DrawShadowVolume(ent, r_shadow_rtlight->shadoworigin, r_shadow_rtlight->radius, numsurfaces, surfacelist, r_shadow_rtlight->cullmins, r_shadow_rtlight->cullmaxs);
2239                 }
2240         }
2241         else
2242         {
2243                 Matrix4x4_Transform(&ent->inversematrix, r_shadow_rtlight->shadoworigin, relativeshadoworigin);
2244                 relativeshadowradius = r_shadow_rtlight->radius / ent->scale;
2245                 relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
2246                 relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
2247                 relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
2248                 relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
2249                 relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
2250                 relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
2251                 R_Mesh_Matrix(&ent->matrix);
2252                 model->DrawShadowVolume(ent, relativeshadoworigin, relativeshadowradius, model->nummodelsurfaces, model->surfacelist, relativeshadowmins, relativeshadowmaxs);
2253         }
2254 }
2255
2256 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
2257 {
2258         // set up properties for rendering light onto this entity
2259         Matrix4x4_Concat(&r_shadow_entitytolight, &r_shadow_rtlight->matrix_worldtolight, &ent->matrix);
2260         Matrix4x4_Concat(&r_shadow_entitytoattenuationxyz, &matrix_attenuationxyz, &r_shadow_entitytolight);
2261         Matrix4x4_Concat(&r_shadow_entitytoattenuationz, &matrix_attenuationz, &r_shadow_entitytolight);
2262         Matrix4x4_Transform(&ent->inversematrix, r_shadow_rtlight->shadoworigin, r_shadow_entitylightorigin);
2263         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, r_shadow_entityeyeorigin);
2264         R_Mesh_Matrix(&ent->matrix);
2265 }
2266
2267 void R_Shadow_DrawEntityLight(entity_render_t *ent, int numsurfaces, int *surfacelist)
2268 {
2269         model_t *model = ent->model;
2270         if (!model->DrawLight)
2271                 return;
2272         R_Shadow_SetupEntityLight(ent);
2273         if (ent == r_refdef.worldentity)
2274                 model->DrawLight(ent, numsurfaces, surfacelist);
2275         else
2276                 model->DrawLight(ent, model->nummodelsurfaces, model->surfacelist);
2277 }
2278
2279 void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
2280 {
2281         int i, usestencil;
2282         float f;
2283         int numleafs, numsurfaces;
2284         int *leaflist, *surfacelist;
2285         unsigned char *leafpvs;
2286         int numlightentities;
2287         int numshadowentities;
2288         entity_render_t *lightentities[MAX_EDICTS];
2289         entity_render_t *shadowentities[MAX_EDICTS];
2290
2291         // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
2292         // skip lights that are basically invisible (color 0 0 0)
2293         if (VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f))
2294                 return;
2295
2296         // loading is done before visibility checks because loading should happen
2297         // all at once at the start of a level, not when it stalls gameplay.
2298         // (especially important to benchmarks)
2299         // compile light
2300         if (rtlight->isstatic && !rtlight->compiled && r_shadow_realtime_world_compile.integer)
2301                 R_RTLight_Compile(rtlight);
2302         // load cubemap
2303         rtlight->currentcubemap = rtlight->cubemapname[0] ? R_Shadow_Cubemap(rtlight->cubemapname) : r_texture_whitecube;
2304
2305         // look up the light style value at this time
2306         f = (rtlight->style >= 0 ? r_refdef.lightstylevalue[rtlight->style] : 128) * (1.0f / 256.0f) * r_shadow_lightintensityscale.value;
2307         VectorScale(rtlight->color, f, rtlight->currentcolor);
2308         /*
2309         if (rtlight->selected)
2310         {
2311                 f = 2 + sin(realtime * M_PI * 4.0);
2312                 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
2313         }
2314         */
2315
2316         // if lightstyle is currently off, don't draw the light
2317         if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
2318                 return;
2319
2320         // if the light box is offscreen, skip it
2321         if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
2322                 return;
2323
2324         if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
2325         {
2326                 // compiled light, world available and can receive realtime lighting
2327                 // retrieve leaf information
2328                 numleafs = rtlight->static_numleafs;
2329                 leaflist = rtlight->static_leaflist;
2330                 leafpvs = rtlight->static_leafpvs;
2331                 numsurfaces = rtlight->static_numsurfaces;
2332                 surfacelist = rtlight->static_surfacelist;
2333         }
2334         else if (r_refdef.worldmodel && r_refdef.worldmodel->GetLightInfo)
2335         {
2336                 // dynamic light, world available and can receive realtime lighting
2337                 // calculate lit surfaces and leafs
2338                 R_Shadow_EnlargeLeafSurfaceBuffer(r_refdef.worldmodel->brush.num_leafs, r_refdef.worldmodel->num_surfaces);
2339                 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);
2340                 leaflist = r_shadow_buffer_leaflist;
2341                 leafpvs = r_shadow_buffer_leafpvs;
2342                 surfacelist = r_shadow_buffer_surfacelist;
2343                 // if the reduced leaf bounds are offscreen, skip it
2344                 if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
2345                         return;
2346         }
2347         else
2348         {
2349                 // no world
2350                 numleafs = 0;
2351                 leaflist = NULL;
2352                 leafpvs = NULL;
2353                 numsurfaces = 0;
2354                 surfacelist = NULL;
2355         }
2356         // check if light is illuminating any visible leafs
2357         if (numleafs)
2358         {
2359                 for (i = 0;i < numleafs;i++)
2360                         if (r_worldleafvisible[leaflist[i]])
2361                                 break;
2362                 if (i == numleafs)
2363                         return;
2364         }
2365         // set up a scissor rectangle for this light
2366         if (R_Shadow_ScissorForBBox(rtlight->cullmins, rtlight->cullmaxs))
2367                 return;
2368
2369         // make a list of lit entities and shadow casting entities
2370         numlightentities = 0;
2371         numshadowentities = 0;
2372         // don't count the world unless some surfaces are actually lit
2373         if (numsurfaces)
2374         {
2375                 lightentities[numlightentities++] = r_refdef.worldentity;
2376                 shadowentities[numshadowentities++] = r_refdef.worldentity;
2377         }
2378         // add dynamic entities that are lit by the light
2379         if (r_drawentities.integer)
2380         {
2381                 for (i = 0;i < r_refdef.numentities;i++)
2382                 {
2383                         model_t *model;
2384                         entity_render_t *ent = r_refdef.entities[i];
2385                         if (BoxesOverlap(ent->mins, ent->maxs, rtlight->cullmins, rtlight->cullmaxs)
2386                          && (model = ent->model)
2387                          && !(ent->flags & RENDER_TRANSPARENT)
2388                          && (r_refdef.worldmodel == NULL || r_refdef.worldmodel->brush.BoxTouchingLeafPVS == NULL || r_refdef.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.worldmodel, leafpvs, ent->mins, ent->maxs)))
2389                         {
2390                                 // about the VectorDistance2 - light emitting entities should not cast their own shadow
2391                                 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(ent->origin, rtlight->shadoworigin) > 0.1)
2392                                         shadowentities[numshadowentities++] = ent;
2393                                 if (ent->visframe == r_framecount && (ent->flags & RENDER_LIGHT) && model->DrawLight)
2394                                         lightentities[numlightentities++] = ent;
2395                         }
2396                 }
2397         }
2398
2399         // return if there's nothing at all to light
2400         if (!numlightentities)
2401                 return;
2402
2403         // don't let sound skip if going slow
2404         if (r_refdef.extraupdate)
2405                 S_ExtraUpdate ();
2406
2407         // make this the active rtlight for rendering purposes
2408         R_Shadow_RenderMode_ActiveLight(rtlight);
2409         // count this light in the r_speeds
2410         renderstats.lights++;
2411
2412         usestencil = false;
2413         if (numshadowentities && rtlight->shadow && (rtlight->isstatic ? r_rtworldshadows : r_rtdlightshadows))
2414         {
2415                 // draw stencil shadow volumes to mask off pixels that are in shadow
2416                 // so that they won't receive lighting
2417                 if (gl_stencil)
2418                 {
2419                         usestencil = true;
2420                         R_Shadow_RenderMode_StencilShadowVolumes();
2421                         for (i = 0;i < numshadowentities;i++)
2422                                 R_Shadow_DrawEntityShadow(shadowentities[i], numsurfaces, surfacelist);
2423                 }
2424
2425                 // optionally draw visible shape of the shadow volumes
2426                 // for performance analysis by level designers
2427                 if (r_showshadowvolumes.integer)
2428                 {
2429                         R_Shadow_RenderMode_VisibleShadowVolumes();
2430                         for (i = 0;i < numshadowentities;i++)
2431                                 R_Shadow_DrawEntityShadow(shadowentities[i], numsurfaces, surfacelist);
2432                 }
2433         }
2434
2435         if (numlightentities)
2436         {
2437                 // draw lighting in the unmasked areas
2438                 R_Shadow_RenderMode_Lighting(usestencil, false);
2439                 for (i = 0;i < numlightentities;i++)
2440                         R_Shadow_DrawEntityLight(lightentities[i], numsurfaces, surfacelist);
2441
2442                 // optionally draw the illuminated areas
2443                 // for performance analysis by level designers
2444                 if (r_showlighting.integer)
2445                 {
2446                         R_Shadow_RenderMode_VisibleLighting(usestencil && !r_showdisabledepthtest.integer, false);
2447                         for (i = 0;i < numlightentities;i++)
2448                                 R_Shadow_DrawEntityLight(lightentities[i], numsurfaces, surfacelist);
2449                 }
2450         }
2451 }
2452
2453 void R_ShadowVolumeLighting(qboolean visible)
2454 {
2455         int lnum, flag;
2456         dlight_t *light;
2457
2458         if (r_refdef.worldmodel && strncmp(r_refdef.worldmodel->name, r_shadow_mapname, sizeof(r_shadow_mapname)))
2459                 R_Shadow_EditLights_Reload_f();
2460
2461         R_Shadow_RenderMode_Begin();
2462
2463         flag = r_rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2464         if (r_shadow_debuglight.integer >= 0)
2465         {
2466                 for (lnum = 0, light = r_shadow_worldlightchain;light;lnum++, light = light->next)
2467                         if (lnum == r_shadow_debuglight.integer && (light->flags & flag))
2468                                 R_DrawRTLight(&light->rtlight, visible);
2469         }
2470         else
2471                 for (lnum = 0, light = r_shadow_worldlightchain;light;lnum++, light = light->next)
2472                         if (light->flags & flag)
2473                                 R_DrawRTLight(&light->rtlight, visible);
2474         if (r_rtdlight)
2475                 for (lnum = 0;lnum < r_refdef.numlights;lnum++)
2476                         R_DrawRTLight(&r_refdef.lights[lnum]->rtlight, visible);
2477
2478         R_Shadow_RenderMode_End();
2479 }
2480
2481 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
2482 typedef struct suffixinfo_s
2483 {
2484         char *suffix;
2485         qboolean flipx, flipy, flipdiagonal;
2486 }
2487 suffixinfo_t;
2488 static suffixinfo_t suffix[3][6] =
2489 {
2490         {
2491                 {"px",   false, false, false},
2492                 {"nx",   false, false, false},
2493                 {"py",   false, false, false},
2494                 {"ny",   false, false, false},
2495                 {"pz",   false, false, false},
2496                 {"nz",   false, false, false}
2497         },
2498         {
2499                 {"posx", false, false, false},
2500                 {"negx", false, false, false},
2501                 {"posy", false, false, false},
2502                 {"negy", false, false, false},
2503                 {"posz", false, false, false},
2504                 {"negz", false, false, false}
2505         },
2506         {
2507                 {"rt",    true, false,  true},
2508                 {"lf",   false,  true,  true},
2509                 {"ft",    true,  true, false},
2510                 {"bk",   false, false, false},
2511                 {"up",    true, false,  true},
2512                 {"dn",    true, false,  true}
2513         }
2514 };
2515
2516 static int componentorder[4] = {0, 1, 2, 3};
2517
2518 rtexture_t *R_Shadow_LoadCubemap(const char *basename)
2519 {
2520         int i, j, cubemapsize;
2521         unsigned char *cubemappixels, *image_rgba;
2522         rtexture_t *cubemaptexture;
2523         char name[256];
2524         // must start 0 so the first loadimagepixels has no requested width/height
2525         cubemapsize = 0;
2526         cubemappixels = NULL;
2527         cubemaptexture = NULL;
2528         // keep trying different suffix groups (posx, px, rt) until one loads
2529         for (j = 0;j < 3 && !cubemappixels;j++)
2530         {
2531                 // load the 6 images in the suffix group
2532                 for (i = 0;i < 6;i++)
2533                 {
2534                         // generate an image name based on the base and and suffix
2535                         dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
2536                         // load it
2537                         if ((image_rgba = loadimagepixels(name, false, cubemapsize, cubemapsize)))
2538                         {
2539                                 // an image loaded, make sure width and height are equal
2540                                 if (image_width == image_height)
2541                                 {
2542                                         // if this is the first image to load successfully, allocate the cubemap memory
2543                                         if (!cubemappixels && image_width >= 1)
2544                                         {
2545                                                 cubemapsize = image_width;
2546                                                 // note this clears to black, so unavailable sides are black
2547                                                 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
2548                                         }
2549                                         // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
2550                                         if (cubemappixels)
2551                                                 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);
2552                                 }
2553                                 else
2554                                         Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
2555                                 // free the image
2556                                 Mem_Free(image_rgba);
2557                         }
2558                 }
2559         }
2560         // if a cubemap loaded, upload it
2561         if (cubemappixels)
2562         {
2563                 if (!r_shadow_filters_texturepool)
2564                         r_shadow_filters_texturepool = R_AllocTexturePool();
2565                 cubemaptexture = R_LoadTextureCubeMap(r_shadow_filters_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
2566                 Mem_Free(cubemappixels);
2567         }
2568         else
2569         {
2570                 Con_Printf("Failed to load Cubemap \"%s\", tried ", basename);
2571                 for (j = 0;j < 3;j++)
2572                         for (i = 0;i < 6;i++)
2573                                 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
2574                 Con_Print(" and was unable to find any of them.\n");
2575         }
2576         return cubemaptexture;
2577 }
2578
2579 rtexture_t *R_Shadow_Cubemap(const char *basename)
2580 {
2581         int i;
2582         for (i = 0;i < numcubemaps;i++)
2583                 if (!strcasecmp(cubemaps[i].basename, basename))
2584                         return cubemaps[i].texture;
2585         if (i >= MAX_CUBEMAPS)
2586                 return r_texture_whitecube;
2587         numcubemaps++;
2588         strcpy(cubemaps[i].basename, basename);
2589         cubemaps[i].texture = R_Shadow_LoadCubemap(cubemaps[i].basename);
2590         if (!cubemaps[i].texture)
2591                 cubemaps[i].texture = r_texture_whitecube;
2592         return cubemaps[i].texture;
2593 }
2594
2595 void R_Shadow_FreeCubemaps(void)
2596 {
2597         numcubemaps = 0;
2598         R_FreeTexturePool(&r_shadow_filters_texturepool);
2599 }
2600
2601 dlight_t *R_Shadow_NewWorldLight(void)
2602 {
2603         dlight_t *light;
2604         light = (dlight_t *)Mem_Alloc(r_main_mempool, sizeof(dlight_t));
2605         light->next = r_shadow_worldlightchain;
2606         r_shadow_worldlightchain = light;
2607         return light;
2608 }
2609
2610 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)
2611 {
2612         VectorCopy(origin, light->origin);
2613         light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
2614         light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
2615         light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
2616         light->color[0] = max(color[0], 0);
2617         light->color[1] = max(color[1], 0);
2618         light->color[2] = max(color[2], 0);
2619         light->radius = max(radius, 0);
2620         light->style = style;
2621         if (light->style < 0 || light->style >= MAX_LIGHTSTYLES)
2622         {
2623                 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
2624                 light->style = 0;
2625         }
2626         light->shadow = shadowenable;
2627         light->corona = corona;
2628         if (!cubemapname)
2629                 cubemapname = "";
2630         strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
2631         light->coronasizescale = coronasizescale;
2632         light->ambientscale = ambientscale;
2633         light->diffusescale = diffusescale;
2634         light->specularscale = specularscale;
2635         light->flags = flags;
2636         Matrix4x4_CreateFromQuakeEntity(&light->matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], 1);
2637
2638         R_RTLight_Update(light, true);
2639 }
2640
2641 void R_Shadow_FreeWorldLight(dlight_t *light)
2642 {
2643         dlight_t **lightpointer;
2644         R_RTLight_Uncompile(&light->rtlight);
2645         for (lightpointer = &r_shadow_worldlightchain;*lightpointer && *lightpointer != light;lightpointer = &(*lightpointer)->next);
2646         if (*lightpointer != light)
2647                 Sys_Error("R_Shadow_FreeWorldLight: light not linked into chain");
2648         *lightpointer = light->next;
2649         Mem_Free(light);
2650 }
2651
2652 void R_Shadow_ClearWorldLights(void)
2653 {
2654         while (r_shadow_worldlightchain)
2655                 R_Shadow_FreeWorldLight(r_shadow_worldlightchain);
2656         r_shadow_selectedlight = NULL;
2657         R_Shadow_FreeCubemaps();
2658 }
2659
2660 void R_Shadow_SelectLight(dlight_t *light)
2661 {
2662         if (r_shadow_selectedlight)
2663                 r_shadow_selectedlight->selected = false;
2664         r_shadow_selectedlight = light;
2665         if (r_shadow_selectedlight)
2666                 r_shadow_selectedlight->selected = true;
2667 }
2668
2669 void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, int surfacenumber, const rtlight_t *rtlight)
2670 {
2671         float scale = r_editlights_cursorgrid.value * 0.5f;
2672         R_DrawSprite(GL_SRC_ALPHA, GL_ONE, r_crosshairs[1]->tex, NULL, false, r_editlights_cursorlocation, r_viewright, r_viewup, scale, -scale, -scale, scale, 1, 1, 1, 0.5f);
2673 }
2674
2675 void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, int surfacenumber, const rtlight_t *rtlight)
2676 {
2677         float intensity;
2678         const dlight_t *light = (dlight_t *)ent;
2679         intensity = 0.5;
2680         if (light->selected)
2681                 intensity = 0.75 + 0.25 * sin(realtime * M_PI * 4.0);
2682         if (!light->shadow)
2683                 intensity *= 0.5f;
2684         R_DrawSprite(GL_SRC_ALPHA, GL_ONE, r_crosshairs[surfacenumber]->tex, NULL, false, light->origin, r_viewright, r_viewup, 8, -8, -8, 8, intensity, intensity, intensity, 0.5);
2685 }
2686
2687 void R_Shadow_DrawLightSprites(void)
2688 {
2689         int i;
2690         dlight_t *light;
2691
2692         for (i = 0, light = r_shadow_worldlightchain;light;i++, light = light->next)
2693                 R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 1+(i % 5), &light->rtlight);
2694         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
2695 }
2696
2697 void R_Shadow_SelectLightInView(void)
2698 {
2699         float bestrating, rating, temp[3];
2700         dlight_t *best, *light;
2701         best = NULL;
2702         bestrating = 0;
2703         for (light = r_shadow_worldlightchain;light;light = light->next)
2704         {
2705                 VectorSubtract(light->origin, r_vieworigin, temp);
2706                 rating = (DotProduct(temp, r_viewforward) / sqrt(DotProduct(temp, temp)));
2707                 if (rating >= 0.95)
2708                 {
2709                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
2710                         if (bestrating < rating && CL_TraceBox(light->origin, vec3_origin, vec3_origin, r_vieworigin, true, NULL, SUPERCONTENTS_SOLID, false).fraction == 1.0f)
2711                         {
2712                                 bestrating = rating;
2713                                 best = light;
2714                         }
2715                 }
2716         }
2717         R_Shadow_SelectLight(best);
2718 }
2719
2720 void R_Shadow_LoadWorldLights(void)
2721 {
2722         int n, a, style, shadow, flags;
2723         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
2724         float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
2725         if (r_refdef.worldmodel == NULL)
2726         {
2727                 Con_Print("No map loaded.\n");
2728                 return;
2729         }
2730         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2731         strlcat (name, ".rtlights", sizeof (name));
2732         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
2733         if (lightsstring)
2734         {
2735                 s = lightsstring;
2736                 n = 0;
2737                 while (*s)
2738                 {
2739                         t = s;
2740                         /*
2741                         shadow = true;
2742                         for (;COM_Parse(t, true) && strcmp(
2743                         if (COM_Parse(t, true))
2744                         {
2745                                 if (com_token[0] == '!')
2746                                 {
2747                                         shadow = false;
2748                                         origin[0] = atof(com_token+1);
2749                                 }
2750                                 else
2751                                         origin[0] = atof(com_token);
2752                                 if (Com_Parse(t
2753                         }
2754                         */
2755                         t = s;
2756                         while (*s && *s != '\n' && *s != '\r')
2757                                 s++;
2758                         if (!*s)
2759                                 break;
2760                         tempchar = *s;
2761                         shadow = true;
2762                         // check for modifier flags
2763                         if (*t == '!')
2764                         {
2765                                 shadow = false;
2766                                 t++;
2767                         }
2768                         *s = 0;
2769                         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);
2770                         *s = tempchar;
2771                         if (a < 18)
2772                                 flags = LIGHTFLAG_REALTIMEMODE;
2773                         if (a < 17)
2774                                 specularscale = 1;
2775                         if (a < 16)
2776                                 diffusescale = 1;
2777                         if (a < 15)
2778                                 ambientscale = 0;
2779                         if (a < 14)
2780                                 coronasizescale = 0.25f;
2781                         if (a < 13)
2782                                 VectorClear(angles);
2783                         if (a < 10)
2784                                 corona = 0;
2785                         if (a < 9 || !strcmp(cubemapname, "\"\""))
2786                                 cubemapname[0] = 0;
2787                         // remove quotes on cubemapname
2788                         if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
2789                         {
2790                                 cubemapname[strlen(cubemapname)-1] = 0;
2791                                 strcpy(cubemapname, cubemapname + 1);
2792                         }
2793                         if (a < 8)
2794                         {
2795                                 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);
2796                                 break;
2797                         }
2798                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
2799                         if (*s == '\r')
2800                                 s++;
2801                         if (*s == '\n')
2802                                 s++;
2803                         n++;
2804                 }
2805                 if (*s)
2806                         Con_Printf("invalid rtlights file \"%s\"\n", name);
2807                 Mem_Free(lightsstring);
2808         }
2809 }
2810
2811 void R_Shadow_SaveWorldLights(void)
2812 {
2813         dlight_t *light;
2814         size_t bufchars, bufmaxchars;
2815         char *buf, *oldbuf;
2816         char name[MAX_QPATH];
2817         char line[MAX_INPUTLINE];
2818         if (!r_shadow_worldlightchain)
2819                 return;
2820         if (r_refdef.worldmodel == NULL)
2821         {
2822                 Con_Print("No map loaded.\n");
2823                 return;
2824         }
2825         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2826         strlcat (name, ".rtlights", sizeof (name));
2827         bufchars = bufmaxchars = 0;
2828         buf = NULL;
2829         for (light = r_shadow_worldlightchain;light;light = light->next)
2830         {
2831                 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
2832                         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);
2833                 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
2834                         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]);
2835                 else
2836                         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);
2837                 if (bufchars + strlen(line) > bufmaxchars)
2838                 {
2839                         bufmaxchars = bufchars + strlen(line) + 2048;
2840                         oldbuf = buf;
2841                         buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
2842                         if (oldbuf)
2843                         {
2844                                 if (bufchars)
2845                                         memcpy(buf, oldbuf, bufchars);
2846                                 Mem_Free(oldbuf);
2847                         }
2848                 }
2849                 if (strlen(line))
2850                 {
2851                         memcpy(buf + bufchars, line, strlen(line));
2852                         bufchars += strlen(line);
2853                 }
2854         }
2855         if (bufchars)
2856                 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
2857         if (buf)
2858                 Mem_Free(buf);
2859 }
2860
2861 void R_Shadow_LoadLightsFile(void)
2862 {
2863         int n, a, style;
2864         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
2865         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
2866         if (r_refdef.worldmodel == NULL)
2867         {
2868                 Con_Print("No map loaded.\n");
2869                 return;
2870         }
2871         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2872         strlcat (name, ".lights", sizeof (name));
2873         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
2874         if (lightsstring)
2875         {
2876                 s = lightsstring;
2877                 n = 0;
2878                 while (*s)
2879                 {
2880                         t = s;
2881                         while (*s && *s != '\n' && *s != '\r')
2882                                 s++;
2883                         if (!*s)
2884                                 break;
2885                         tempchar = *s;
2886                         *s = 0;
2887                         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);
2888                         *s = tempchar;
2889                         if (a < 14)
2890                         {
2891                                 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);
2892                                 break;
2893                         }
2894                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
2895                         radius = bound(15, radius, 4096);
2896                         VectorScale(color, (2.0f / (8388608.0f)), color);
2897                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
2898                         if (*s == '\r')
2899                                 s++;
2900                         if (*s == '\n')
2901                                 s++;
2902                         n++;
2903                 }
2904                 if (*s)
2905                         Con_Printf("invalid lights file \"%s\"\n", name);
2906                 Mem_Free(lightsstring);
2907         }
2908 }
2909
2910 // tyrlite/hmap2 light types in the delay field
2911 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
2912
2913 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
2914 {
2915         int entnum, style, islight, skin, pflags, effects, type, n;
2916         char *entfiledata;
2917         const char *data;
2918         float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
2919         char key[256], value[MAX_INPUTLINE];
2920
2921         if (r_refdef.worldmodel == NULL)
2922         {
2923                 Con_Print("No map loaded.\n");
2924                 return;
2925         }
2926         // try to load a .ent file first
2927         FS_StripExtension (r_refdef.worldmodel->name, key, sizeof (key));
2928         strlcat (key, ".ent", sizeof (key));
2929         data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
2930         // and if that is not found, fall back to the bsp file entity string
2931         if (!data)
2932                 data = r_refdef.worldmodel->brush.entities;
2933         if (!data)
2934                 return;
2935         for (entnum = 0;COM_ParseToken(&data, false) && com_token[0] == '{';entnum++)
2936         {
2937                 type = LIGHTTYPE_MINUSX;
2938                 origin[0] = origin[1] = origin[2] = 0;
2939                 originhack[0] = originhack[1] = originhack[2] = 0;
2940                 angles[0] = angles[1] = angles[2] = 0;
2941                 color[0] = color[1] = color[2] = 1;
2942                 light[0] = light[1] = light[2] = 1;light[3] = 300;
2943                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
2944                 fadescale = 1;
2945                 lightscale = 1;
2946                 style = 0;
2947                 skin = 0;
2948                 pflags = 0;
2949                 effects = 0;
2950                 islight = false;
2951                 while (1)
2952                 {
2953                         if (!COM_ParseToken(&data, false))
2954                                 break; // error
2955                         if (com_token[0] == '}')
2956                                 break; // end of entity
2957                         if (com_token[0] == '_')
2958                                 strcpy(key, com_token + 1);
2959                         else
2960                                 strcpy(key, com_token);
2961                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
2962                                 key[strlen(key)-1] = 0;
2963                         if (!COM_ParseToken(&data, false))
2964                                 break; // error
2965                         strcpy(value, com_token);
2966
2967                         // now that we have the key pair worked out...
2968                         if (!strcmp("light", key))
2969                         {
2970                                 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
2971                                 if (n == 1)
2972                                 {
2973                                         // quake
2974                                         light[0] = vec[0] * (1.0f / 256.0f);
2975                                         light[1] = vec[0] * (1.0f / 256.0f);
2976                                         light[2] = vec[0] * (1.0f / 256.0f);
2977                                         light[3] = vec[0];
2978                                 }
2979                                 else if (n == 4)
2980                                 {
2981                                         // halflife
2982                                         light[0] = vec[0] * (1.0f / 255.0f);
2983                                         light[1] = vec[1] * (1.0f / 255.0f);
2984                                         light[2] = vec[2] * (1.0f / 255.0f);
2985                                         light[3] = vec[3];
2986                                 }
2987                         }
2988                         else if (!strcmp("delay", key))
2989                                 type = atoi(value);
2990                         else if (!strcmp("origin", key))
2991                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
2992                         else if (!strcmp("angle", key))
2993                                 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
2994                         else if (!strcmp("angles", key))
2995                                 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
2996                         else if (!strcmp("color", key))
2997                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
2998                         else if (!strcmp("wait", key))
2999                                 fadescale = atof(value);
3000                         else if (!strcmp("classname", key))
3001                         {
3002                                 if (!strncmp(value, "light", 5))
3003                                 {
3004                                         islight = true;
3005                                         if (!strcmp(value, "light_fluoro"))
3006                                         {
3007                                                 originhack[0] = 0;
3008                                                 originhack[1] = 0;
3009                                                 originhack[2] = 0;
3010                                                 overridecolor[0] = 1;
3011                                                 overridecolor[1] = 1;
3012                                                 overridecolor[2] = 1;
3013                                         }
3014                                         if (!strcmp(value, "light_fluorospark"))
3015                                         {
3016                                                 originhack[0] = 0;
3017                                                 originhack[1] = 0;
3018                                                 originhack[2] = 0;
3019                                                 overridecolor[0] = 1;
3020                                                 overridecolor[1] = 1;
3021                                                 overridecolor[2] = 1;
3022                                         }
3023                                         if (!strcmp(value, "light_globe"))
3024                                         {
3025                                                 originhack[0] = 0;
3026                                                 originhack[1] = 0;
3027                                                 originhack[2] = 0;
3028                                                 overridecolor[0] = 1;
3029                                                 overridecolor[1] = 0.8;
3030                                                 overridecolor[2] = 0.4;
3031                                         }
3032                                         if (!strcmp(value, "light_flame_large_yellow"))
3033                                         {
3034                                                 originhack[0] = 0;
3035                                                 originhack[1] = 0;
3036                                                 originhack[2] = 0;
3037                                                 overridecolor[0] = 1;
3038                                                 overridecolor[1] = 0.5;
3039                                                 overridecolor[2] = 0.1;
3040                                         }
3041                                         if (!strcmp(value, "light_flame_small_yellow"))
3042                                         {
3043                                                 originhack[0] = 0;
3044                                                 originhack[1] = 0;
3045                                                 originhack[2] = 0;
3046                                                 overridecolor[0] = 1;
3047                                                 overridecolor[1] = 0.5;
3048                                                 overridecolor[2] = 0.1;
3049                                         }
3050                                         if (!strcmp(value, "light_torch_small_white"))
3051                                         {
3052                                                 originhack[0] = 0;
3053                                                 originhack[1] = 0;
3054                                                 originhack[2] = 0;
3055                                                 overridecolor[0] = 1;
3056                                                 overridecolor[1] = 0.5;
3057                                                 overridecolor[2] = 0.1;
3058                                         }
3059                                         if (!strcmp(value, "light_torch_small_walltorch"))
3060                                         {
3061                                                 originhack[0] = 0;
3062                                                 originhack[1] = 0;
3063                                                 originhack[2] = 0;
3064                                                 overridecolor[0] = 1;
3065                                                 overridecolor[1] = 0.5;
3066                                                 overridecolor[2] = 0.1;
3067                                         }
3068                                 }
3069                         }
3070                         else if (!strcmp("style", key))
3071                                 style = atoi(value);
3072                         else if (!strcmp("skin", key))
3073                                 skin = (int)atof(value);
3074                         else if (!strcmp("pflags", key))
3075                                 pflags = (int)atof(value);
3076                         else if (!strcmp("effects", key))
3077                                 effects = (int)atof(value);
3078                         else if (r_refdef.worldmodel->type == mod_brushq3)
3079                         {
3080                                 if (!strcmp("scale", key))
3081                                         lightscale = atof(value);
3082                                 if (!strcmp("fade", key))
3083                                         fadescale = atof(value);
3084                         }
3085                 }
3086                 if (!islight)
3087                         continue;
3088                 if (lightscale <= 0)
3089                         lightscale = 1;
3090                 if (fadescale <= 0)
3091                         fadescale = 1;
3092                 if (color[0] == color[1] && color[0] == color[2])
3093                 {
3094                         color[0] *= overridecolor[0];
3095                         color[1] *= overridecolor[1];
3096                         color[2] *= overridecolor[2];
3097                 }
3098                 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
3099                 color[0] = color[0] * light[0];
3100                 color[1] = color[1] * light[1];
3101                 color[2] = color[2] * light[2];
3102                 switch (type)
3103                 {
3104                 case LIGHTTYPE_MINUSX:
3105                         break;
3106                 case LIGHTTYPE_RECIPX:
3107                         radius *= 2;
3108                         VectorScale(color, (1.0f / 16.0f), color);
3109                         break;
3110                 case LIGHTTYPE_RECIPXX:
3111                         radius *= 2;
3112                         VectorScale(color, (1.0f / 16.0f), color);
3113                         break;
3114                 default:
3115                 case LIGHTTYPE_NONE:
3116                         break;
3117                 case LIGHTTYPE_SUN:
3118                         break;
3119                 case LIGHTTYPE_MINUSXX:
3120                         break;
3121                 }
3122                 VectorAdd(origin, originhack, origin);
3123                 if (radius >= 1)
3124                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va("cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
3125         }
3126         if (entfiledata)
3127                 Mem_Free(entfiledata);
3128 }
3129
3130
3131 void R_Shadow_SetCursorLocationForView(void)
3132 {
3133         vec_t dist, push;
3134         vec3_t dest, endpos;
3135         trace_t trace;
3136         VectorMA(r_vieworigin, r_editlights_cursordistance.value, r_viewforward, dest);
3137         trace = CL_TraceBox(r_vieworigin, vec3_origin, vec3_origin, dest, true, NULL, SUPERCONTENTS_SOLID, false);
3138         if (trace.fraction < 1)
3139         {
3140                 dist = trace.fraction * r_editlights_cursordistance.value;
3141                 push = r_editlights_cursorpushback.value;
3142                 if (push > dist)
3143                         push = dist;
3144                 push = -push;
3145                 VectorMA(trace.endpos, push, r_viewforward, endpos);
3146                 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
3147         }
3148         else
3149         {
3150                 VectorClear( endpos );
3151         }
3152         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
3153         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
3154         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
3155 }
3156
3157 void R_Shadow_UpdateWorldLightSelection(void)
3158 {
3159         if (r_editlights.integer)
3160         {
3161                 R_Shadow_SetCursorLocationForView();
3162                 R_Shadow_SelectLightInView();
3163                 R_Shadow_DrawLightSprites();
3164         }
3165         else
3166                 R_Shadow_SelectLight(NULL);
3167 }
3168
3169 void R_Shadow_EditLights_Clear_f(void)
3170 {
3171         R_Shadow_ClearWorldLights();
3172 }
3173
3174 void R_Shadow_EditLights_Reload_f(void)
3175 {
3176         if (!r_refdef.worldmodel)
3177                 return;
3178         strlcpy(r_shadow_mapname, r_refdef.worldmodel->name, sizeof(r_shadow_mapname));
3179         R_Shadow_ClearWorldLights();
3180         R_Shadow_LoadWorldLights();
3181         if (r_shadow_worldlightchain == NULL)
3182         {
3183                 R_Shadow_LoadLightsFile();
3184                 if (r_shadow_worldlightchain == NULL)
3185                         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
3186         }
3187 }
3188
3189 void R_Shadow_EditLights_Save_f(void)
3190 {
3191         if (!r_refdef.worldmodel)
3192                 return;
3193         R_Shadow_SaveWorldLights();
3194 }
3195
3196 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
3197 {
3198         R_Shadow_ClearWorldLights();
3199         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
3200 }
3201
3202 void R_Shadow_EditLights_ImportLightsFile_f(void)
3203 {
3204         R_Shadow_ClearWorldLights();
3205         R_Shadow_LoadLightsFile();
3206 }
3207
3208 void R_Shadow_EditLights_Spawn_f(void)
3209 {
3210         vec3_t color;
3211         if (!r_editlights.integer)
3212         {
3213                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
3214                 return;
3215         }
3216         if (Cmd_Argc() != 1)
3217         {
3218                 Con_Print("r_editlights_spawn does not take parameters\n");
3219                 return;
3220         }
3221         color[0] = color[1] = color[2] = 1;
3222         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
3223 }
3224
3225 void R_Shadow_EditLights_Edit_f(void)
3226 {
3227         vec3_t origin, angles, color;
3228         vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
3229         int style, shadows, flags, normalmode, realtimemode;
3230         char cubemapname[MAX_INPUTLINE];
3231         if (!r_editlights.integer)
3232         {
3233                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
3234                 return;
3235         }
3236         if (!r_shadow_selectedlight)
3237         {
3238                 Con_Print("No selected light.\n");
3239                 return;
3240         }
3241         VectorCopy(r_shadow_selectedlight->origin, origin);
3242         VectorCopy(r_shadow_selectedlight->angles, angles);
3243         VectorCopy(r_shadow_selectedlight->color, color);
3244         radius = r_shadow_selectedlight->radius;
3245         style = r_shadow_selectedlight->style;
3246         if (r_shadow_selectedlight->cubemapname)
3247                 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
3248         else
3249                 cubemapname[0] = 0;
3250         shadows = r_shadow_selectedlight->shadow;
3251         corona = r_shadow_selectedlight->corona;
3252         coronasizescale = r_shadow_selectedlight->coronasizescale;
3253         ambientscale = r_shadow_selectedlight->ambientscale;
3254         diffusescale = r_shadow_selectedlight->diffusescale;
3255         specularscale = r_shadow_selectedlight->specularscale;
3256         flags = r_shadow_selectedlight->flags;
3257         normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
3258         realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
3259         if (!strcmp(Cmd_Argv(1), "origin"))
3260         {
3261                 if (Cmd_Argc() != 5)
3262                 {
3263                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
3264                         return;
3265                 }
3266                 origin[0] = atof(Cmd_Argv(2));
3267                 origin[1] = atof(Cmd_Argv(3));
3268                 origin[2] = atof(Cmd_Argv(4));
3269         }
3270         else if (!strcmp(Cmd_Argv(1), "originx"))
3271         {
3272                 if (Cmd_Argc() != 3)
3273                 {
3274                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3275                         return;
3276                 }
3277                 origin[0] = atof(Cmd_Argv(2));
3278         }
3279         else if (!strcmp(Cmd_Argv(1), "originy"))
3280         {
3281                 if (Cmd_Argc() != 3)
3282                 {
3283                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3284                         return;
3285                 }
3286                 origin[1] = atof(Cmd_Argv(2));
3287         }
3288         else if (!strcmp(Cmd_Argv(1), "originz"))
3289         {
3290                 if (Cmd_Argc() != 3)
3291                 {
3292                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3293                         return;
3294                 }
3295                 origin[2] = atof(Cmd_Argv(2));
3296         }
3297         else if (!strcmp(Cmd_Argv(1), "move"))
3298         {
3299                 if (Cmd_Argc() != 5)
3300                 {
3301                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
3302                         return;
3303                 }
3304                 origin[0] += atof(Cmd_Argv(2));
3305                 origin[1] += atof(Cmd_Argv(3));
3306                 origin[2] += atof(Cmd_Argv(4));
3307         }
3308         else if (!strcmp(Cmd_Argv(1), "movex"))
3309         {
3310                 if (Cmd_Argc() != 3)
3311                 {
3312                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3313                         return;
3314                 }
3315                 origin[0] += atof(Cmd_Argv(2));
3316         }
3317         else if (!strcmp(Cmd_Argv(1), "movey"))
3318         {
3319                 if (Cmd_Argc() != 3)
3320                 {
3321                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3322                         return;
3323                 }
3324                 origin[1] += atof(Cmd_Argv(2));
3325         }
3326         else if (!strcmp(Cmd_Argv(1), "movez"))
3327         {
3328                 if (Cmd_Argc() != 3)
3329                 {
3330                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3331                         return;
3332                 }
3333                 origin[2] += atof(Cmd_Argv(2));
3334         }
3335         else if (!strcmp(Cmd_Argv(1), "angles"))
3336         {
3337                 if (Cmd_Argc() != 5)
3338                 {
3339                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
3340                         return;
3341                 }
3342                 angles[0] = atof(Cmd_Argv(2));
3343                 angles[1] = atof(Cmd_Argv(3));
3344                 angles[2] = atof(Cmd_Argv(4));
3345         }
3346         else if (!strcmp(Cmd_Argv(1), "anglesx"))
3347         {
3348                 if (Cmd_Argc() != 3)
3349                 {
3350                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3351                         return;
3352                 }
3353                 angles[0] = atof(Cmd_Argv(2));
3354         }
3355         else if (!strcmp(Cmd_Argv(1), "anglesy"))
3356         {
3357                 if (Cmd_Argc() != 3)
3358                 {
3359                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3360                         return;
3361                 }
3362                 angles[1] = atof(Cmd_Argv(2));
3363         }
3364         else if (!strcmp(Cmd_Argv(1), "anglesz"))
3365         {
3366                 if (Cmd_Argc() != 3)
3367                 {
3368                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3369                         return;
3370                 }
3371                 angles[2] = atof(Cmd_Argv(2));
3372         }
3373         else if (!strcmp(Cmd_Argv(1), "color"))
3374         {
3375                 if (Cmd_Argc() != 5)
3376                 {
3377                         Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
3378                         return;
3379                 }
3380                 color[0] = atof(Cmd_Argv(2));
3381                 color[1] = atof(Cmd_Argv(3));
3382                 color[2] = atof(Cmd_Argv(4));
3383         }
3384         else if (!strcmp(Cmd_Argv(1), "radius"))
3385         {
3386                 if (Cmd_Argc() != 3)
3387                 {
3388                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3389                         return;
3390                 }
3391                 radius = atof(Cmd_Argv(2));
3392         }
3393         else if (!strcmp(Cmd_Argv(1), "colorscale"))
3394         {
3395                 if (Cmd_Argc() == 3)
3396                 {
3397                         double scale = atof(Cmd_Argv(2));
3398                         color[0] *= scale;
3399                         color[1] *= scale;
3400                         color[2] *= scale;
3401                 }
3402                 else
3403                 {
3404                         if (Cmd_Argc() != 5)
3405                         {
3406                                 Con_Printf("usage: r_editlights_edit %s red green blue  (OR grey instead of red green blue)\n", Cmd_Argv(1));
3407                                 return;
3408                         }
3409                         color[0] *= atof(Cmd_Argv(2));
3410                         color[1] *= atof(Cmd_Argv(3));
3411                         color[2] *= atof(Cmd_Argv(4));
3412                 }
3413         }
3414         else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
3415         {
3416                 if (Cmd_Argc() != 3)
3417                 {
3418                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3419                         return;
3420                 }
3421                 radius *= atof(Cmd_Argv(2));
3422         }
3423         else if (!strcmp(Cmd_Argv(1), "style"))
3424         {
3425                 if (Cmd_Argc() != 3)
3426                 {
3427                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3428                         return;
3429                 }
3430                 style = atoi(Cmd_Argv(2));
3431         }
3432         else if (!strcmp(Cmd_Argv(1), "cubemap"))
3433         {
3434                 if (Cmd_Argc() > 3)
3435                 {
3436                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3437                         return;
3438                 }
3439                 if (Cmd_Argc() == 3)
3440                         strcpy(cubemapname, Cmd_Argv(2));
3441                 else
3442                         cubemapname[0] = 0;
3443         }
3444         else if (!strcmp(Cmd_Argv(1), "shadows"))
3445         {
3446                 if (Cmd_Argc() != 3)
3447                 {
3448                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3449                         return;
3450                 }
3451                 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
3452         }
3453         else if (!strcmp(Cmd_Argv(1), "corona"))
3454         {
3455                 if (Cmd_Argc() != 3)
3456                 {
3457                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3458                         return;
3459                 }
3460                 corona = atof(Cmd_Argv(2));
3461         }
3462         else if (!strcmp(Cmd_Argv(1), "coronasize"))
3463         {
3464                 if (Cmd_Argc() != 3)
3465                 {
3466                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3467                         return;
3468                 }
3469                 coronasizescale = atof(Cmd_Argv(2));
3470         }
3471         else if (!strcmp(Cmd_Argv(1), "ambient"))
3472         {
3473                 if (Cmd_Argc() != 3)
3474                 {
3475                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3476                         return;
3477                 }
3478                 ambientscale = atof(Cmd_Argv(2));
3479         }
3480         else if (!strcmp(Cmd_Argv(1), "diffuse"))
3481         {
3482                 if (Cmd_Argc() != 3)
3483                 {
3484                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3485                         return;
3486                 }
3487                 diffusescale = atof(Cmd_Argv(2));
3488         }
3489         else if (!strcmp(Cmd_Argv(1), "specular"))
3490         {
3491                 if (Cmd_Argc() != 3)
3492                 {
3493                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3494                         return;
3495                 }
3496                 specularscale = atof(Cmd_Argv(2));
3497         }