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