implemented omnidirectional shadowmapping using depth textures (2D, Rect
[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 #define R_SHADOW_SHADOWMAP_NUMCUBEMAPS 8
144
145 extern void R_Shadow_EditLights_Init(void);
146
147 typedef enum r_shadow_rendermode_e
148 {
149         R_SHADOW_RENDERMODE_NONE,
150         R_SHADOW_RENDERMODE_ZPASS_STENCIL,
151         R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL,
152         R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE,
153         R_SHADOW_RENDERMODE_ZFAIL_STENCIL,
154         R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL,
155         R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE,
156         R_SHADOW_RENDERMODE_LIGHT_VERTEX,
157         R_SHADOW_RENDERMODE_LIGHT_DOT3,
158         R_SHADOW_RENDERMODE_LIGHT_GLSL,
159         R_SHADOW_RENDERMODE_VISIBLEVOLUMES,
160         R_SHADOW_RENDERMODE_VISIBLELIGHTING,
161         R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE,
162         R_SHADOW_RENDERMODE_SHADOWMAP2D,
163         R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE,
164 }
165 r_shadow_rendermode_t;
166
167 r_shadow_rendermode_t r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
168 r_shadow_rendermode_t r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_NONE;
169 r_shadow_rendermode_t r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_NONE;
170 r_shadow_rendermode_t r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_NONE;
171 qboolean r_shadow_usingshadowmaprect;
172 qboolean r_shadow_usingshadowmap2d;
173 qboolean r_shadow_usingshadowmapcube;
174 float r_shadow_shadowmap_bias;
175 float r_shadow_shadowmap_texturescale[2];
176 float r_shadow_shadowmap_parameters[4];
177 int r_shadow_drawbuffer;
178 int r_shadow_readbuffer;
179 GLuint r_shadow_fborectangle;
180 GLuint r_shadow_fbocubeside[R_SHADOW_SHADOWMAP_NUMCUBEMAPS][6];
181 GLuint r_shadow_fbo2d;
182 int r_shadow_shadowmapmaxsize;
183 int r_shadow_lightscissor[4];
184
185 int maxshadowtriangles;
186 int *shadowelements;
187
188 int maxshadowvertices;
189 float *shadowvertex3f;
190
191 int maxshadowmark;
192 int numshadowmark;
193 int *shadowmark;
194 int *shadowmarklist;
195 int shadowmarkcount;
196
197 int maxvertexupdate;
198 int *vertexupdate;
199 int *vertexremap;
200 int vertexupdatenum;
201
202 int r_shadow_buffer_numleafpvsbytes;
203 unsigned char *r_shadow_buffer_visitingleafpvs;
204 unsigned char *r_shadow_buffer_leafpvs;
205 int *r_shadow_buffer_leaflist;
206
207 int r_shadow_buffer_numsurfacepvsbytes;
208 unsigned char *r_shadow_buffer_surfacepvs;
209 int *r_shadow_buffer_surfacelist;
210
211 int r_shadow_buffer_numshadowtrispvsbytes;
212 unsigned char *r_shadow_buffer_shadowtrispvs;
213 int r_shadow_buffer_numlighttrispvsbytes;
214 unsigned char *r_shadow_buffer_lighttrispvs;
215
216 rtexturepool_t *r_shadow_texturepool;
217 rtexture_t *r_shadow_attenuationgradienttexture;
218 rtexture_t *r_shadow_attenuation2dtexture;
219 rtexture_t *r_shadow_attenuation3dtexture;
220 rtexture_t *r_shadow_lightcorona;
221 rtexture_t *r_shadow_shadowmaprectangletexture;
222 rtexture_t *r_shadow_shadowmap2dtexture;
223 rtexture_t *r_shadow_shadowmapcubeprojectiontexture;
224 rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
225 int r_shadow_shadowmapsize; // changes for each light based on distance
226 int r_shadow_shadowmaplod; // changes for each light based on distance
227
228 // lights are reloaded when this changes
229 char r_shadow_mapname[MAX_QPATH];
230
231 // used only for light filters (cubemaps)
232 rtexturepool_t *r_shadow_filters_texturepool;
233
234 cvar_t r_shadow_bumpscale_basetexture = {0, "r_shadow_bumpscale_basetexture", "0", "generate fake bumpmaps from diffuse textures at this bumpyness, try 4 to match tenebrae, higher values increase depth, requires r_restart to take effect"};
235 cvar_t r_shadow_bumpscale_bumpmap = {0, "r_shadow_bumpscale_bumpmap", "4", "what magnitude to interpret _bump.tga textures as, higher values increase depth, requires r_restart to take effect"};
236 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
237 cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"};
238 cvar_t r_shadow_gloss = {CVAR_SAVE, "r_shadow_gloss", "1", "0 disables gloss (specularity) rendering, 1 uses gloss if textures are found, 2 forces a flat metallic specular effect on everything without textures (similar to tenebrae)"};
239 cvar_t r_shadow_gloss2intensity = {0, "r_shadow_gloss2intensity", "0.125", "how bright the forced flat gloss should look if r_shadow_gloss is 2"};
240 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
241 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
242 cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
243 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
244 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
245 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
246 cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"};
247 cvar_t r_shadow_portallight = {0, "r_shadow_portallight", "1", "use portal culling to exactly determine lit triangles when compiling world lights"};
248 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "1000000", "how far to cast shadows"};
249 cvar_t r_shadow_frontsidecasting = {0, "r_shadow_frontsidecasting", "1", "whether to cast shadows from illuminated triangles (front side of model) or unlit triangles (back side of model)"};
250 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
251 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
252 cvar_t r_shadow_realtime_dlight_svbspculling = {0, "r_shadow_realtime_dlight_svbspculling", "0", "enables svbsp optimization on dynamic lights (very slow!)"};
253 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal optimization on dynamic lights (slow!)"};
254 cvar_t r_shadow_realtime_world = {CVAR_SAVE, "r_shadow_realtime_world", "0", "enables rendering of full world lighting (whether loaded from the map, or a .rtlights file, or a .ent file, or a .lights file produced by hlight)"};
255 cvar_t r_shadow_realtime_world_lightmaps = {CVAR_SAVE, "r_shadow_realtime_world_lightmaps", "0", "brightness to render lightmaps when using full world lighting, try 0.5 for a tenebrae-like appearance"};
256 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
257 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
258 cvar_t r_shadow_realtime_world_compileshadow = {0, "r_shadow_realtime_world_compileshadow", "1", "enables compilation of shadows from world lights for higher performance rendering"};
259 cvar_t r_shadow_realtime_world_compilesvbsp = {0, "r_shadow_realtime_world_compilesvbsp", "1", "enables svbsp optimization during compilation"};
260 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation"};
261 cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1", "use scissor optimization of light rendering (restricts rendering to the portion of the screen affected by the light)"};
262 cvar_t r_shadow_shadowmapping = {CVAR_SAVE, "r_shadow_shadowmapping", "0", "enables use of shadowmapping (depth texture sampling) instead of stencil shadow volumes, requires gl_fbo 1"};
263 cvar_t r_shadow_shadowmapping_filterquality = {CVAR_SAVE, "r_shadow_shadowmapping_filterquality", "0", "shadowmap filter modes: 0 = no filtering, 1 = bilinear, 2 = bilinear small blur (fast), 3 = bilinear large blur (slow)"};
264 cvar_t r_shadow_shadowmapping_minsize = {CVAR_SAVE, "r_shadow_shadowmapping_minsize", "32", "shadowmap size limit"};
265 cvar_t r_shadow_shadowmapping_maxsize = {CVAR_SAVE, "r_shadow_shadowmapping_maxsize", "1024", "shadowmap size limit"};
266 cvar_t r_shadow_shadowmapping_lod_bias = {CVAR_SAVE, "r_shadow_shadowmapping_lod_bias", "8", "shadowmap size bias"};
267 cvar_t r_shadow_shadowmapping_lod_scale = {CVAR_SAVE, "r_shadow_shadowmapping_lod_scale", "1", "shadowmap size scaling parameter"};
268 cvar_t r_shadow_shadowmapping_bordersize = {CVAR_SAVE, "r_shadow_shadowmapping_bordersize", "6", "shadowmap size bias for filtering"};
269 cvar_t r_shadow_shadowmapping_nearclip = {CVAR_SAVE, "r_shadow_shadowmapping_nearclip", "1", "shadowmap nearclip in world units"};
270 cvar_t r_shadow_shadowmapping_bias = {CVAR_SAVE, "r_shadow_shadowmapping_bias", "0.03", "shadowmap bias parameter (this is multiplied by nearclip * 1024 / lodsize)"};
271 cvar_t r_shadow_culltriangles = {0, "r_shadow_culltriangles", "1", "performs more expensive tests to remove unnecessary triangles of lit surfaces"};
272 cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
273 cvar_t r_shadow_polygonoffset = {0, "r_shadow_polygonoffset", "1", "how much to push shadow volumes into the distance when rendering, to reduce chances of zfighting artifacts (should not be less than 0)"};
274 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect r_glsl lighting)"};
275 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
276 cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksm the proportion of hidden pixels controls corona intensity"};
277 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
278 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
279 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
280 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
281 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
282 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
283 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
284 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
285 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
286 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
287
288 // note the table actually includes one more value, just to avoid the need to clamp the distance index due to minor math error
289 #define ATTENTABLESIZE 256
290 // 1D gradient, 2D circle and 3D sphere attenuation textures
291 #define ATTEN1DSIZE 32
292 #define ATTEN2DSIZE 64
293 #define ATTEN3DSIZE 32
294
295 static float r_shadow_attendividebias; // r_shadow_lightattenuationdividebias
296 static float r_shadow_attenlinearscale; // r_shadow_lightattenuationlinearscale
297 static float r_shadow_attentable[ATTENTABLESIZE+1];
298
299 rtlight_t *r_shadow_compilingrtlight;
300 static memexpandablearray_t r_shadow_worldlightsarray;
301 dlight_t *r_shadow_selectedlight;
302 dlight_t r_shadow_bufferlight;
303 vec3_t r_editlights_cursorlocation;
304
305 extern int con_vislines;
306
307 typedef struct cubemapinfo_s
308 {
309         char basename[64];
310         rtexture_t *texture;
311 }
312 cubemapinfo_t;
313
314 #define MAX_CUBEMAPS 256
315 static int numcubemaps;
316 static cubemapinfo_t cubemaps[MAX_CUBEMAPS];
317
318 void R_Shadow_UncompileWorldLights(void);
319 void R_Shadow_ClearWorldLights(void);
320 void R_Shadow_SaveWorldLights(void);
321 void R_Shadow_LoadWorldLights(void);
322 void R_Shadow_LoadLightsFile(void);
323 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
324 void R_Shadow_EditLights_Reload_f(void);
325 void R_Shadow_ValidateCvars(void);
326 static void R_Shadow_MakeTextures(void);
327
328 // VorteX: custom editor light sprites
329 #define EDLIGHTSPRSIZE                  8
330 cachepic_t *r_editlights_sprcursor;
331 cachepic_t *r_editlights_sprlight;
332 cachepic_t *r_editlights_sprnoshadowlight;
333 cachepic_t *r_editlights_sprcubemaplight;
334 cachepic_t *r_editlights_sprcubemapnoshadowlight;
335 cachepic_t *r_editlights_sprselection;
336
337 void r_shadow_start(void)
338 {
339         // allocate vertex processing arrays
340         numcubemaps = 0;
341         r_shadow_attenuationgradienttexture = NULL;
342         r_shadow_attenuation2dtexture = NULL;
343         r_shadow_attenuation3dtexture = NULL;
344         r_shadow_shadowmaprectangletexture = NULL;
345         memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
346         r_shadow_shadowmapcubeprojectiontexture = NULL;
347         r_shadow_shadowmap2dtexture = NULL;
348         r_shadow_shadowmapmaxsize = 0;
349         r_shadow_shadowmapsize = 0;
350         r_shadow_shadowmaplod = 0;
351         r_shadow_fborectangle = 0;
352         memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside));
353         r_shadow_fbo2d = 0;
354         r_shadow_texturepool = NULL;
355         r_shadow_filters_texturepool = NULL;
356         R_Shadow_ValidateCvars();
357         R_Shadow_MakeTextures();
358         maxshadowtriangles = 0;
359         shadowelements = NULL;
360         maxshadowvertices = 0;
361         shadowvertex3f = NULL;
362         maxvertexupdate = 0;
363         vertexupdate = NULL;
364         vertexremap = NULL;
365         vertexupdatenum = 0;
366         maxshadowmark = 0;
367         numshadowmark = 0;
368         shadowmark = NULL;
369         shadowmarklist = NULL;
370         shadowmarkcount = 0;
371         r_shadow_buffer_numleafpvsbytes = 0;
372         r_shadow_buffer_visitingleafpvs = NULL;
373         r_shadow_buffer_leafpvs = NULL;
374         r_shadow_buffer_leaflist = NULL;
375         r_shadow_buffer_numsurfacepvsbytes = 0;
376         r_shadow_buffer_surfacepvs = NULL;
377         r_shadow_buffer_surfacelist = NULL;
378         r_shadow_buffer_numshadowtrispvsbytes = 0;
379         r_shadow_buffer_shadowtrispvs = NULL;
380         r_shadow_buffer_numlighttrispvsbytes = 0;
381         r_shadow_buffer_lighttrispvs = NULL;
382 }
383
384 void r_shadow_shutdown(void)
385 {
386         int i;
387         CHECKGLERROR
388         R_Shadow_UncompileWorldLights();
389         CHECKGLERROR
390         numcubemaps = 0;
391         r_shadow_attenuationgradienttexture = NULL;
392         r_shadow_attenuation2dtexture = NULL;
393         r_shadow_attenuation3dtexture = NULL;
394         r_shadow_shadowmaprectangletexture = NULL;
395         memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
396         r_shadow_shadowmapcubeprojectiontexture = NULL;
397         r_shadow_shadowmap2dtexture = NULL;
398         r_shadow_shadowmapmaxsize = 0;
399         r_shadow_shadowmapsize = 0;
400         r_shadow_shadowmaplod = 0;
401         CHECKGLERROR
402         if (r_shadow_fborectangle)
403                 qglDeleteFramebuffersEXT(1, &r_shadow_fborectangle);
404         r_shadow_fborectangle = 0;
405         CHECKGLERROR
406         for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
407                 if (r_shadow_fbocubeside[i])
408                         qglDeleteFramebuffersEXT(6, r_shadow_fbocubeside[i]);
409         memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside));
410         CHECKGLERROR
411         if (r_shadow_fbo2d)
412                 qglDeleteFramebuffersEXT(1, &r_shadow_fbo2d);
413         r_shadow_fbo2d = 0;
414         CHECKGLERROR
415         R_FreeTexturePool(&r_shadow_texturepool);
416         R_FreeTexturePool(&r_shadow_filters_texturepool);
417         maxshadowtriangles = 0;
418         if (shadowelements)
419                 Mem_Free(shadowelements);
420         shadowelements = NULL;
421         if (shadowvertex3f)
422                 Mem_Free(shadowvertex3f);
423         shadowvertex3f = NULL;
424         maxvertexupdate = 0;
425         if (vertexupdate)
426                 Mem_Free(vertexupdate);
427         vertexupdate = NULL;
428         if (vertexremap)
429                 Mem_Free(vertexremap);
430         vertexremap = NULL;
431         vertexupdatenum = 0;
432         maxshadowmark = 0;
433         numshadowmark = 0;
434         if (shadowmark)
435                 Mem_Free(shadowmark);
436         shadowmark = NULL;
437         if (shadowmarklist)
438                 Mem_Free(shadowmarklist);
439         shadowmarklist = NULL;
440         shadowmarkcount = 0;
441         r_shadow_buffer_numleafpvsbytes = 0;
442         if (r_shadow_buffer_visitingleafpvs)
443                 Mem_Free(r_shadow_buffer_visitingleafpvs);
444         r_shadow_buffer_visitingleafpvs = NULL;
445         if (r_shadow_buffer_leafpvs)
446                 Mem_Free(r_shadow_buffer_leafpvs);
447         r_shadow_buffer_leafpvs = NULL;
448         if (r_shadow_buffer_leaflist)
449                 Mem_Free(r_shadow_buffer_leaflist);
450         r_shadow_buffer_leaflist = NULL;
451         r_shadow_buffer_numsurfacepvsbytes = 0;
452         if (r_shadow_buffer_surfacepvs)
453                 Mem_Free(r_shadow_buffer_surfacepvs);
454         r_shadow_buffer_surfacepvs = NULL;
455         if (r_shadow_buffer_surfacelist)
456                 Mem_Free(r_shadow_buffer_surfacelist);
457         r_shadow_buffer_surfacelist = NULL;
458         r_shadow_buffer_numshadowtrispvsbytes = 0;
459         if (r_shadow_buffer_shadowtrispvs)
460                 Mem_Free(r_shadow_buffer_shadowtrispvs);
461         r_shadow_buffer_numlighttrispvsbytes = 0;
462         if (r_shadow_buffer_lighttrispvs)
463                 Mem_Free(r_shadow_buffer_lighttrispvs);
464 }
465
466 void r_shadow_newmap(void)
467 {
468         if (cl.worldmodel && strncmp(cl.worldmodel->name, r_shadow_mapname, sizeof(r_shadow_mapname)))
469                 R_Shadow_EditLights_Reload_f();
470 }
471
472 void R_Shadow_Help_f(void)
473 {
474         Con_Printf(
475 "Documentation on r_shadow system:\n"
476 "Settings:\n"
477 "r_shadow_bumpscale_basetexture : base texture as bumpmap with this scale\n"
478 "r_shadow_bumpscale_bumpmap : depth scale for bumpmap conversion\n"
479 "r_shadow_debuglight : render only this light number (-1 = all)\n"
480 "r_shadow_gloss 0/1/2 : no gloss, gloss textures only, force gloss\n"
481 "r_shadow_gloss2intensity : brightness of forced gloss\n"
482 "r_shadow_glossintensity : brightness of textured gloss\n"
483 "r_shadow_lightattenuationlinearscale : used to generate attenuation texture\n"
484 "r_shadow_lightattenuationdividebias : used to generate attenuation texture\n"
485 "r_shadow_lightintensityscale : scale rendering brightness of all lights\n"
486 "r_shadow_lightradiusscale : scale rendering radius of all lights\n"
487 "r_shadow_portallight : use portal visibility for static light precomputation\n"
488 "r_shadow_projectdistance : shadow volume projection distance\n"
489 "r_shadow_realtime_dlight : use high quality dynamic lights in normal mode\n"
490 "r_shadow_realtime_dlight_shadows : cast shadows from dlights\n"
491 "r_shadow_realtime_world : use high quality world lighting mode\n"
492 "r_shadow_realtime_world_lightmaps : use lightmaps in addition to lights\n"
493 "r_shadow_realtime_world_shadows : cast shadows from world lights\n"
494 "r_shadow_realtime_world_compile : compile surface/visibility information\n"
495 "r_shadow_realtime_world_compileshadow : compile shadow geometry\n"
496 "r_shadow_scissor : use scissor optimization\n"
497 "r_shadow_polygonfactor : nudge shadow volumes closer/further\n"
498 "r_shadow_polygonoffset : nudge shadow volumes closer/further\n"
499 "r_shadow_texture3d : use 3d attenuation texture (if hardware supports)\n"
500 "r_showlighting : useful for performance testing; bright = slow!\n"
501 "r_showshadowvolumes : useful for performance testing; bright = slow!\n"
502 "Commands:\n"
503 "r_shadow_help : this help\n"
504         );
505 }
506
507 void R_Shadow_Init(void)
508 {
509         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
510         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
511         Cvar_RegisterVariable(&r_shadow_usenormalmap);
512         Cvar_RegisterVariable(&r_shadow_debuglight);
513         Cvar_RegisterVariable(&r_shadow_gloss);
514         Cvar_RegisterVariable(&r_shadow_gloss2intensity);
515         Cvar_RegisterVariable(&r_shadow_glossintensity);
516         Cvar_RegisterVariable(&r_shadow_glossexponent);
517         Cvar_RegisterVariable(&r_shadow_glossexact);
518         Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
519         Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
520         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
521         Cvar_RegisterVariable(&r_shadow_lightradiusscale);
522         Cvar_RegisterVariable(&r_shadow_portallight);
523         Cvar_RegisterVariable(&r_shadow_projectdistance);
524         Cvar_RegisterVariable(&r_shadow_frontsidecasting);
525         Cvar_RegisterVariable(&r_shadow_realtime_dlight);
526         Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
527         Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
528         Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
529         Cvar_RegisterVariable(&r_shadow_realtime_world);
530         Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
531         Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
532         Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
533         Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
534         Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
535         Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
536         Cvar_RegisterVariable(&r_shadow_scissor);
537         Cvar_RegisterVariable(&r_shadow_shadowmapping);
538         Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
539         Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
540         Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
541         Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
542         Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
543         Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
544         Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
545         Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
546         Cvar_RegisterVariable(&r_shadow_culltriangles);
547         Cvar_RegisterVariable(&r_shadow_polygonfactor);
548         Cvar_RegisterVariable(&r_shadow_polygonoffset);
549         Cvar_RegisterVariable(&r_shadow_texture3d);
550         Cvar_RegisterVariable(&r_coronas);
551         Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
552         Cvar_RegisterVariable(&r_coronas_occlusionquery);
553         Cvar_RegisterVariable(&gl_flashblend);
554         Cvar_RegisterVariable(&gl_ext_separatestencil);
555         Cvar_RegisterVariable(&gl_ext_stenciltwoside);
556         if (gamemode == GAME_TENEBRAE)
557         {
558                 Cvar_SetValue("r_shadow_gloss", 2);
559                 Cvar_SetValue("r_shadow_bumpscale_basetexture", 4);
560         }
561         Cmd_AddCommand("r_shadow_help", R_Shadow_Help_f, "prints documentation on console commands and variables used by realtime lighting and shadowing system");
562         R_Shadow_EditLights_Init();
563         Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
564         maxshadowtriangles = 0;
565         shadowelements = NULL;
566         maxshadowvertices = 0;
567         shadowvertex3f = NULL;
568         maxvertexupdate = 0;
569         vertexupdate = NULL;
570         vertexremap = NULL;
571         vertexupdatenum = 0;
572         maxshadowmark = 0;
573         numshadowmark = 0;
574         shadowmark = NULL;
575         shadowmarklist = NULL;
576         shadowmarkcount = 0;
577         r_shadow_buffer_numleafpvsbytes = 0;
578         r_shadow_buffer_visitingleafpvs = NULL;
579         r_shadow_buffer_leafpvs = NULL;
580         r_shadow_buffer_leaflist = NULL;
581         r_shadow_buffer_numsurfacepvsbytes = 0;
582         r_shadow_buffer_surfacepvs = NULL;
583         r_shadow_buffer_surfacelist = NULL;
584         r_shadow_buffer_shadowtrispvs = NULL;
585         r_shadow_buffer_lighttrispvs = NULL;
586         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap);
587 }
588
589 matrix4x4_t matrix_attenuationxyz =
590 {
591         {
592                 {0.5, 0.0, 0.0, 0.5},
593                 {0.0, 0.5, 0.0, 0.5},
594                 {0.0, 0.0, 0.5, 0.5},
595                 {0.0, 0.0, 0.0, 1.0}
596         }
597 };
598
599 matrix4x4_t matrix_attenuationz =
600 {
601         {
602                 {0.0, 0.0, 0.5, 0.5},
603                 {0.0, 0.0, 0.0, 0.5},
604                 {0.0, 0.0, 0.0, 0.5},
605                 {0.0, 0.0, 0.0, 1.0}
606         }
607 };
608
609 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles)
610 {
611         // make sure shadowelements is big enough for this volume
612         if (maxshadowtriangles < numtriangles)
613         {
614                 maxshadowtriangles = numtriangles;
615                 if (shadowelements)
616                         Mem_Free(shadowelements);
617                 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[24]));
618         }
619         // make sure shadowvertex3f is big enough for this volume
620         if (maxshadowvertices < numvertices)
621         {
622                 maxshadowvertices = numvertices;
623                 if (shadowvertex3f)
624                         Mem_Free(shadowvertex3f);
625                 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[6]));
626         }
627 }
628
629 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
630 {
631         int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
632         int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
633         int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
634         int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
635         if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
636         {
637                 if (r_shadow_buffer_visitingleafpvs)
638                         Mem_Free(r_shadow_buffer_visitingleafpvs);
639                 if (r_shadow_buffer_leafpvs)
640                         Mem_Free(r_shadow_buffer_leafpvs);
641                 if (r_shadow_buffer_leaflist)
642                         Mem_Free(r_shadow_buffer_leaflist);
643                 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
644                 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
645                 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
646                 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
647         }
648         if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
649         {
650                 if (r_shadow_buffer_surfacepvs)
651                         Mem_Free(r_shadow_buffer_surfacepvs);
652                 if (r_shadow_buffer_surfacelist)
653                         Mem_Free(r_shadow_buffer_surfacelist);
654                 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
655                 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
656                 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
657         }
658         if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
659         {
660                 if (r_shadow_buffer_shadowtrispvs)
661                         Mem_Free(r_shadow_buffer_shadowtrispvs);
662                 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
663                 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
664         }
665         if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
666         {
667                 if (r_shadow_buffer_lighttrispvs)
668                         Mem_Free(r_shadow_buffer_lighttrispvs);
669                 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
670                 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
671         }
672 }
673
674 void R_Shadow_PrepareShadowMark(int numtris)
675 {
676         // make sure shadowmark is big enough for this volume
677         if (maxshadowmark < numtris)
678         {
679                 maxshadowmark = numtris;
680                 if (shadowmark)
681                         Mem_Free(shadowmark);
682                 if (shadowmarklist)
683                         Mem_Free(shadowmarklist);
684                 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
685                 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
686                 shadowmarkcount = 0;
687         }
688         shadowmarkcount++;
689         // if shadowmarkcount wrapped we clear the array and adjust accordingly
690         if (shadowmarkcount == 0)
691         {
692                 shadowmarkcount = 1;
693                 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
694         }
695         numshadowmark = 0;
696 }
697
698 static int R_Shadow_ConstructShadowVolume_ZFail(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
699 {
700         int i, j;
701         int outtriangles = 0, outvertices = 0;
702         const int *element;
703         const float *vertex;
704         float ratio, direction[3], projectvector[3];
705
706         if (projectdirection)
707                 VectorScale(projectdirection, projectdistance, projectvector);
708         else
709                 VectorClear(projectvector);
710
711         // create the vertices
712         if (projectdirection)
713         {
714                 for (i = 0;i < numshadowmarktris;i++)
715                 {
716                         element = inelement3i + shadowmarktris[i] * 3;
717                         for (j = 0;j < 3;j++)
718                         {
719                                 if (vertexupdate[element[j]] != vertexupdatenum)
720                                 {
721                                         vertexupdate[element[j]] = vertexupdatenum;
722                                         vertexremap[element[j]] = outvertices;
723                                         vertex = invertex3f + element[j] * 3;
724                                         // project one copy of the vertex according to projectvector
725                                         VectorCopy(vertex, outvertex3f);
726                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
727                                         outvertex3f += 6;
728                                         outvertices += 2;
729                                 }
730                         }
731                 }
732         }
733         else
734         {
735                 for (i = 0;i < numshadowmarktris;i++)
736                 {
737                         element = inelement3i + shadowmarktris[i] * 3;
738                         for (j = 0;j < 3;j++)
739                         {
740                                 if (vertexupdate[element[j]] != vertexupdatenum)
741                                 {
742                                         vertexupdate[element[j]] = vertexupdatenum;
743                                         vertexremap[element[j]] = outvertices;
744                                         vertex = invertex3f + element[j] * 3;
745                                         // project one copy of the vertex to the sphere radius of the light
746                                         // (FIXME: would projecting it to the light box be better?)
747                                         VectorSubtract(vertex, projectorigin, direction);
748                                         ratio = projectdistance / VectorLength(direction);
749                                         VectorCopy(vertex, outvertex3f);
750                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
751                                         outvertex3f += 6;
752                                         outvertices += 2;
753                                 }
754                         }
755                 }
756         }
757
758         if (r_shadow_frontsidecasting.integer)
759         {
760                 for (i = 0;i < numshadowmarktris;i++)
761                 {
762                         int remappedelement[3];
763                         int markindex;
764                         const int *neighbortriangle;
765
766                         markindex = shadowmarktris[i] * 3;
767                         element = inelement3i + markindex;
768                         neighbortriangle = inneighbor3i + markindex;
769                         // output the front and back triangles
770                         outelement3i[0] = vertexremap[element[0]];
771                         outelement3i[1] = vertexremap[element[1]];
772                         outelement3i[2] = vertexremap[element[2]];
773                         outelement3i[3] = vertexremap[element[2]] + 1;
774                         outelement3i[4] = vertexremap[element[1]] + 1;
775                         outelement3i[5] = vertexremap[element[0]] + 1;
776
777                         outelement3i += 6;
778                         outtriangles += 2;
779                         // output the sides (facing outward from this triangle)
780                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
781                         {
782                                 remappedelement[0] = vertexremap[element[0]];
783                                 remappedelement[1] = vertexremap[element[1]];
784                                 outelement3i[0] = remappedelement[1];
785                                 outelement3i[1] = remappedelement[0];
786                                 outelement3i[2] = remappedelement[0] + 1;
787                                 outelement3i[3] = remappedelement[1];
788                                 outelement3i[4] = remappedelement[0] + 1;
789                                 outelement3i[5] = remappedelement[1] + 1;
790
791                                 outelement3i += 6;
792                                 outtriangles += 2;
793                         }
794                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
795                         {
796                                 remappedelement[1] = vertexremap[element[1]];
797                                 remappedelement[2] = vertexremap[element[2]];
798                                 outelement3i[0] = remappedelement[2];
799                                 outelement3i[1] = remappedelement[1];
800                                 outelement3i[2] = remappedelement[1] + 1;
801                                 outelement3i[3] = remappedelement[2];
802                                 outelement3i[4] = remappedelement[1] + 1;
803                                 outelement3i[5] = remappedelement[2] + 1;
804
805                                 outelement3i += 6;
806                                 outtriangles += 2;
807                         }
808                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
809                         {
810                                 remappedelement[0] = vertexremap[element[0]];
811                                 remappedelement[2] = vertexremap[element[2]];
812                                 outelement3i[0] = remappedelement[0];
813                                 outelement3i[1] = remappedelement[2];
814                                 outelement3i[2] = remappedelement[2] + 1;
815                                 outelement3i[3] = remappedelement[0];
816                                 outelement3i[4] = remappedelement[2] + 1;
817                                 outelement3i[5] = remappedelement[0] + 1;
818
819                                 outelement3i += 6;
820                                 outtriangles += 2;
821                         }
822                 }
823         }
824         else
825         {
826                 for (i = 0;i < numshadowmarktris;i++)
827                 {
828                         int remappedelement[3];
829                         int markindex;
830                         const int *neighbortriangle;
831
832                         markindex = shadowmarktris[i] * 3;
833                         element = inelement3i + markindex;
834                         neighbortriangle = inneighbor3i + markindex;
835                         // output the front and back triangles
836                         outelement3i[0] = vertexremap[element[2]];
837                         outelement3i[1] = vertexremap[element[1]];
838                         outelement3i[2] = vertexremap[element[0]];
839                         outelement3i[3] = vertexremap[element[0]] + 1;
840                         outelement3i[4] = vertexremap[element[1]] + 1;
841                         outelement3i[5] = vertexremap[element[2]] + 1;
842
843                         outelement3i += 6;
844                         outtriangles += 2;
845                         // output the sides (facing outward from this triangle)
846                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
847                         {
848                                 remappedelement[0] = vertexremap[element[0]];
849                                 remappedelement[1] = vertexremap[element[1]];
850                                 outelement3i[0] = remappedelement[0];
851                                 outelement3i[1] = remappedelement[1];
852                                 outelement3i[2] = remappedelement[1] + 1;
853                                 outelement3i[3] = remappedelement[0];
854                                 outelement3i[4] = remappedelement[1] + 1;
855                                 outelement3i[5] = remappedelement[0] + 1;
856
857                                 outelement3i += 6;
858                                 outtriangles += 2;
859                         }
860                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
861                         {
862                                 remappedelement[1] = vertexremap[element[1]];
863                                 remappedelement[2] = vertexremap[element[2]];
864                                 outelement3i[0] = remappedelement[1];
865                                 outelement3i[1] = remappedelement[2];
866                                 outelement3i[2] = remappedelement[2] + 1;
867                                 outelement3i[3] = remappedelement[1];
868                                 outelement3i[4] = remappedelement[2] + 1;
869                                 outelement3i[5] = remappedelement[1] + 1;
870
871                                 outelement3i += 6;
872                                 outtriangles += 2;
873                         }
874                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
875                         {
876                                 remappedelement[0] = vertexremap[element[0]];
877                                 remappedelement[2] = vertexremap[element[2]];
878                                 outelement3i[0] = remappedelement[2];
879                                 outelement3i[1] = remappedelement[0];
880                                 outelement3i[2] = remappedelement[0] + 1;
881                                 outelement3i[3] = remappedelement[2];
882                                 outelement3i[4] = remappedelement[0] + 1;
883                                 outelement3i[5] = remappedelement[2] + 1;
884
885                                 outelement3i += 6;
886                                 outtriangles += 2;
887                         }
888                 }
889         }
890         if (outnumvertices)
891                 *outnumvertices = outvertices;
892         return outtriangles;
893 }
894
895 static int R_Shadow_ConstructShadowVolume_ZPass(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
896 {
897         int i, j, k;
898         int outtriangles = 0, outvertices = 0;
899         const int *element;
900         const float *vertex;
901         float ratio, direction[3], projectvector[3];
902         qboolean side[4];
903
904         if (projectdirection)
905                 VectorScale(projectdirection, projectdistance, projectvector);
906         else
907                 VectorClear(projectvector);
908
909         for (i = 0;i < numshadowmarktris;i++)
910         {
911                 int remappedelement[3];
912                 int markindex;
913                 const int *neighbortriangle;
914
915                 markindex = shadowmarktris[i] * 3;
916                 neighbortriangle = inneighbor3i + markindex;
917                 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
918                 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
919                 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
920                 if (side[0] + side[1] + side[2] == 0)
921                         continue;
922
923                 side[3] = side[0];
924                 element = inelement3i + markindex;
925
926                 // create the vertices
927                 for (j = 0;j < 3;j++)
928                 {
929                         if (side[j] + side[j+1] == 0)
930                                 continue;
931                         k = element[j];
932                         if (vertexupdate[k] != vertexupdatenum)
933                         {
934                                 vertexupdate[k] = vertexupdatenum;
935                                 vertexremap[k] = outvertices;
936                                 vertex = invertex3f + k * 3;
937                                 VectorCopy(vertex, outvertex3f);
938                                 if (projectdirection)
939                                 {
940                                         // project one copy of the vertex according to projectvector
941                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
942                                 }
943                                 else
944                                 {
945                                         // project one copy of the vertex to the sphere radius of the light
946                                         // (FIXME: would projecting it to the light box be better?)
947                                         VectorSubtract(vertex, projectorigin, direction);
948                                         ratio = projectdistance / VectorLength(direction);
949                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
950                                 }
951                                 outvertex3f += 6;
952                                 outvertices += 2;
953                         }
954                 }
955
956                 // output the sides (facing outward from this triangle)
957                 if (!side[0])
958                 {
959                         remappedelement[0] = vertexremap[element[0]];
960                         remappedelement[1] = vertexremap[element[1]];
961                         outelement3i[0] = remappedelement[1];
962                         outelement3i[1] = remappedelement[0];
963                         outelement3i[2] = remappedelement[0] + 1;
964                         outelement3i[3] = remappedelement[1];
965                         outelement3i[4] = remappedelement[0] + 1;
966                         outelement3i[5] = remappedelement[1] + 1;
967
968                         outelement3i += 6;
969                         outtriangles += 2;
970                 }
971                 if (!side[1])
972                 {
973                         remappedelement[1] = vertexremap[element[1]];
974                         remappedelement[2] = vertexremap[element[2]];
975                         outelement3i[0] = remappedelement[2];
976                         outelement3i[1] = remappedelement[1];
977                         outelement3i[2] = remappedelement[1] + 1;
978                         outelement3i[3] = remappedelement[2];
979                         outelement3i[4] = remappedelement[1] + 1;
980                         outelement3i[5] = remappedelement[2] + 1;
981
982                         outelement3i += 6;
983                         outtriangles += 2;
984                 }
985                 if (!side[2])
986                 {
987                         remappedelement[0] = vertexremap[element[0]];
988                         remappedelement[2] = vertexremap[element[2]];
989                         outelement3i[0] = remappedelement[0];
990                         outelement3i[1] = remappedelement[2];
991                         outelement3i[2] = remappedelement[2] + 1;
992                         outelement3i[3] = remappedelement[0];
993                         outelement3i[4] = remappedelement[2] + 1;
994                         outelement3i[5] = remappedelement[0] + 1;
995
996                         outelement3i += 6;
997                         outtriangles += 2;
998                 }
999         }
1000         if (outnumvertices)
1001                 *outnumvertices = outvertices;
1002         return outtriangles;
1003 }
1004
1005 void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const vec3_t projectorigin, const vec3_t projectdirection, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs)
1006 {
1007         int t, tend;
1008         const int *e;
1009         const float *v[3];
1010         float normal[3];
1011         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1012                 return;
1013         tend = firsttriangle + numtris;
1014         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1015         {
1016                 // surface box entirely inside light box, no box cull
1017                 if (projectdirection)
1018                 {
1019                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1020                         {
1021                                 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1022                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1023                                         shadowmarklist[numshadowmark++] = t;
1024                         }
1025                 }
1026                 else
1027                 {
1028                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1029                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1030                                         shadowmarklist[numshadowmark++] = t;
1031                 }
1032         }
1033         else
1034         {
1035                 // surface box not entirely inside light box, cull each triangle
1036                 if (projectdirection)
1037                 {
1038                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1039                         {
1040                                 v[0] = invertex3f + e[0] * 3;
1041                                 v[1] = invertex3f + e[1] * 3;
1042                                 v[2] = invertex3f + e[2] * 3;
1043                                 TriangleNormal(v[0], v[1], v[2], normal);
1044                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1045                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1046                                         shadowmarklist[numshadowmark++] = t;
1047                         }
1048                 }
1049                 else
1050                 {
1051                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1052                         {
1053                                 v[0] = invertex3f + e[0] * 3;
1054                                 v[1] = invertex3f + e[1] * 3;
1055                                 v[2] = invertex3f + e[2] * 3;
1056                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1057                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1058                                         shadowmarklist[numshadowmark++] = t;
1059                         }
1060                 }
1061         }
1062 }
1063
1064 qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1065 {
1066 #if 1
1067         return false;
1068 #else
1069         if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1070                 return false;
1071         // check if the shadow volume intersects the near plane
1072         //
1073         // a ray between the eye and light origin may intersect the caster,
1074         // indicating that the shadow may touch the eye location, however we must
1075         // test the near plane (a polygon), not merely the eye location, so it is
1076         // easiest to enlarge the caster bounding shape slightly for this.
1077         // TODO
1078         return true;
1079 #endif
1080 }
1081
1082 void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, const int *elements, const int *neighbors, const vec3_t projectorigin, const vec3_t projectdirection, float projectdistance, int nummarktris, const int *marktris, vec3_t trismins, vec3_t trismaxs)
1083 {
1084         int i, tris, outverts;
1085         if (projectdistance < 0.1)
1086         {
1087                 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1088                 return;
1089         }
1090         if (!numverts || !nummarktris)
1091                 return;
1092         // make sure shadowelements is big enough for this volume
1093         if (maxshadowtriangles < nummarktris || maxshadowvertices < numverts)
1094                 R_Shadow_ResizeShadowArrays((numverts + 255) & ~255, (nummarktris + 255) & ~255);
1095
1096         if (maxvertexupdate < numverts)
1097         {
1098                 maxvertexupdate = numverts;
1099                 if (vertexupdate)
1100                         Mem_Free(vertexupdate);
1101                 if (vertexremap)
1102                         Mem_Free(vertexremap);
1103                 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1104                 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1105                 vertexupdatenum = 0;
1106         }
1107         vertexupdatenum++;
1108         if (vertexupdatenum == 0)
1109         {
1110                 vertexupdatenum = 1;
1111                 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1112                 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1113         }
1114
1115         for (i = 0;i < nummarktris;i++)
1116                 shadowmark[marktris[i]] = shadowmarkcount;
1117
1118         if (r_shadow_compilingrtlight)
1119         {
1120                 // if we're compiling an rtlight, capture the mesh
1121                 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1122                 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1123                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1124                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1125         }
1126         else
1127         {
1128                 // decide which type of shadow to generate and set stencil mode
1129                 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1130                 // generate the sides or a solid volume, depending on type
1131                 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1132                         tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1133                 else
1134                         tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1135                 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1136                 r_refdef.stats.lights_shadowtriangles += tris;
1137                 CHECKGLERROR
1138                 R_Mesh_VertexPointer(shadowvertex3f, 0, 0);
1139                 GL_LockArrays(0, outverts);
1140                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1141                 {
1142                         // increment stencil if frontface is infront of depthbuffer
1143                         GL_CullFace(r_refdef.view.cullface_front);
1144                         qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1145                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1146                         // decrement stencil if backface is infront of depthbuffer
1147                         GL_CullFace(r_refdef.view.cullface_back);
1148                         qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1149                 }
1150                 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1151                 {
1152                         // decrement stencil if backface is behind depthbuffer
1153                         GL_CullFace(r_refdef.view.cullface_front);
1154                         qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1155                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1156                         // increment stencil if frontface is behind depthbuffer
1157                         GL_CullFace(r_refdef.view.cullface_back);
1158                         qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1159                 }
1160                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1161                 GL_LockArrays(0, 0);
1162                 CHECKGLERROR
1163         }
1164 }
1165
1166 void R_Shadow_ShadowMapFromList(int numverts, int numtris, const float *vertex3f, int vertex3f_bufferobject, int vertex3f_bufferoffset, const int *elements, int nummarktris, const int *marktris)
1167 {
1168         int i, tris = nummarktris;
1169         int *outelement3i;
1170         const int *element;
1171         if (!numverts || !nummarktris)
1172                 return;
1173         // make sure shadowelements is big enough for this mesh
1174         if (maxshadowtriangles < nummarktris || maxshadowvertices < numverts)
1175                 R_Shadow_ResizeShadowArrays((numverts + 255) & ~255, (nummarktris + 255) & ~255);
1176
1177         // gather up the (sparse) triangles into one array
1178         outelement3i = shadowelements;
1179         for (i = 0;i < nummarktris;i++)
1180         {
1181                 element = elements + marktris[i] * 3;
1182                 outelement3i[0] = element[0];
1183                 outelement3i[1] = element[1];
1184                 outelement3i[2] = element[2];
1185                 outelement3i += 3;
1186         }
1187
1188         r_refdef.stats.lights_dynamicshadowtriangles += tris;
1189         r_refdef.stats.lights_shadowtriangles += tris;
1190         R_Mesh_VertexPointer(vertex3f, vertex3f_bufferobject, vertex3f_bufferoffset);
1191         R_Mesh_Draw(0, numverts, 0, tris, shadowelements, NULL, 0, 0);
1192 }
1193
1194 static void R_Shadow_MakeTextures_MakeCorona(void)
1195 {
1196         float dx, dy;
1197         int x, y, a;
1198         unsigned char pixels[32][32][4];
1199         for (y = 0;y < 32;y++)
1200         {
1201                 dy = (y - 15.5f) * (1.0f / 16.0f);
1202                 for (x = 0;x < 32;x++)
1203                 {
1204                         dx = (x - 15.5f) * (1.0f / 16.0f);
1205                         a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1206                         a = bound(0, a, 255);
1207                         pixels[y][x][0] = a;
1208                         pixels[y][x][1] = a;
1209                         pixels[y][x][2] = a;
1210                         pixels[y][x][3] = 255;
1211                 }
1212         }
1213         r_shadow_lightcorona = R_LoadTexture2D(r_shadow_texturepool, "lightcorona", 32, 32, &pixels[0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR, NULL);
1214 }
1215
1216 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1217 {
1218         float dist = sqrt(x*x+y*y+z*z);
1219         float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1220         // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1221         return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1222 }
1223
1224 static void R_Shadow_MakeTextures(void)
1225 {
1226         int x, y, z;
1227         float intensity, dist;
1228         unsigned int *data;
1229         R_FreeTexturePool(&r_shadow_texturepool);
1230         r_shadow_texturepool = R_AllocTexturePool();
1231         r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1232         r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1233         data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1234         // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1235         for (x = 0;x <= ATTENTABLESIZE;x++)
1236         {
1237                 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1238                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1239                 r_shadow_attentable[x] = bound(0, intensity, 1);
1240         }
1241         // 1D gradient texture
1242         for (x = 0;x < ATTEN1DSIZE;x++)
1243                 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1244         r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
1245         // 2D circle texture
1246         for (y = 0;y < ATTEN2DSIZE;y++)
1247                 for (x = 0;x < ATTEN2DSIZE;x++)
1248                         data[y*ATTEN2DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), 0);
1249         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
1250         // 3D sphere texture
1251         if (r_shadow_texture3d.integer && gl_texture3d)
1252         {
1253                 for (z = 0;z < ATTEN3DSIZE;z++)
1254                         for (y = 0;y < ATTEN3DSIZE;y++)
1255                                 for (x = 0;x < ATTEN3DSIZE;x++)
1256                                         data[(z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375));
1257                 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
1258         }
1259         else
1260                 r_shadow_attenuation3dtexture = NULL;
1261         Mem_Free(data);
1262
1263         R_Shadow_MakeTextures_MakeCorona();
1264
1265         // Editor light sprites
1266         r_editlights_sprcursor = Draw_CachePic ("gfx/editlights/cursor");
1267         r_editlights_sprlight = Draw_CachePic ("gfx/editlights/light");
1268         r_editlights_sprnoshadowlight = Draw_CachePic ("gfx/editlights/noshadow");
1269         r_editlights_sprcubemaplight = Draw_CachePic ("gfx/editlights/cubemaplight");
1270         r_editlights_sprcubemapnoshadowlight = Draw_CachePic ("gfx/editlights/cubemapnoshadowlight");
1271         r_editlights_sprselection = Draw_CachePic ("gfx/editlights/selection");
1272 }
1273
1274 void R_Shadow_ValidateCvars(void)
1275 {
1276         if (r_shadow_texture3d.integer && !gl_texture3d)
1277                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1278         if (gl_ext_separatestencil.integer && !gl_support_separatestencil)
1279                 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1280         if (gl_ext_stenciltwoside.integer && !gl_support_stenciltwoside)
1281                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1282 }
1283
1284 void R_Shadow_RenderMode_Begin(void)
1285 {
1286         GLint drawbuffer;
1287         GLint readbuffer;
1288         R_Shadow_ValidateCvars();
1289
1290         if (!r_shadow_attenuation2dtexture
1291          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1292          || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1293          || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1294                 R_Shadow_MakeTextures();
1295
1296         CHECKGLERROR
1297         R_Mesh_ColorPointer(NULL, 0, 0);
1298         R_Mesh_ResetTextureState();
1299         GL_BlendFunc(GL_ONE, GL_ZERO);
1300         GL_DepthRange(0, 1);
1301         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1302         GL_DepthTest(true);
1303         GL_DepthMask(false);
1304         GL_Color(0, 0, 0, 1);
1305         GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.y - r_refdef.view.height, r_refdef.view.width, r_refdef.view.height);
1306
1307         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1308
1309         if (gl_ext_separatestencil.integer)
1310         {
1311                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1312                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1313         }
1314         else if (gl_ext_stenciltwoside.integer)
1315         {
1316                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1317                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1318         }
1319         else
1320         {
1321                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1322                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1323         }
1324
1325         if (r_glsl.integer && gl_support_fragment_shader)
1326                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
1327         else if (gl_dot3arb && gl_texturecubemap && r_textureunits.integer >= 2 && gl_combine.integer && gl_stencil)
1328                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_DOT3;
1329         else
1330                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
1331
1332         CHECKGLERROR
1333         qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
1334         qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
1335         r_shadow_drawbuffer = drawbuffer;
1336         r_shadow_readbuffer = readbuffer;
1337 }
1338
1339 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
1340 {
1341         rsurface.rtlight = rtlight;
1342 }
1343
1344 void R_Shadow_RenderMode_Reset(void)
1345 {
1346         CHECKGLERROR
1347         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE)
1348         {
1349                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1350         }
1351         if (gl_support_ext_framebuffer_object)
1352         {
1353                 qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);CHECKGLERROR
1354         }
1355         qglDrawBuffer(r_shadow_drawbuffer);CHECKGLERROR
1356         qglReadBuffer(r_shadow_readbuffer);CHECKGLERROR
1357         R_SetViewport(&r_refdef.view.viewport);
1358         GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
1359         R_Mesh_ColorPointer(NULL, 0, 0);
1360         R_Mesh_ResetTextureState();
1361         GL_DepthRange(0, 1);
1362         GL_DepthTest(true);
1363         GL_DepthMask(false);
1364         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1365         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
1366         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1367         qglStencilMask(~0);CHECKGLERROR
1368         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
1369         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
1370         GL_CullFace(r_refdef.view.cullface_back);
1371         GL_Color(1, 1, 1, 1);
1372         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
1373         GL_BlendFunc(GL_ONE, GL_ZERO);
1374         R_SetupGenericShader(false);
1375         r_shadow_usingshadowmaprect = false;
1376         r_shadow_usingshadowmapcube = false;
1377         r_shadow_usingshadowmap2d = false;
1378         CHECKGLERROR
1379 }
1380
1381 void R_Shadow_ClearStencil(void)
1382 {
1383         CHECKGLERROR
1384         GL_Clear(GL_STENCIL_BUFFER_BIT);
1385         r_refdef.stats.lights_clears++;
1386 }
1387
1388 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
1389 {
1390         r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
1391         if (r_shadow_rendermode == mode)
1392                 return;
1393         CHECKGLERROR
1394         R_Shadow_RenderMode_Reset();
1395         GL_ColorMask(0, 0, 0, 0);
1396         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
1397         R_SetupDepthOrShadowShader();
1398         qglDepthFunc(GL_LESS);CHECKGLERROR
1399         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1400         r_shadow_rendermode = mode;
1401         switch(mode)
1402         {
1403         default:
1404                 break;
1405         case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
1406                 GL_CullFace(GL_NONE);
1407                 qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1408                 qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1409                 break;
1410         case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
1411                 GL_CullFace(GL_NONE);
1412                 qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1413                 qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1414                 break;
1415         case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
1416                 GL_CullFace(GL_NONE);
1417                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1418                 qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
1419                 qglStencilMask(~0);CHECKGLERROR
1420                 qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1421                 qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
1422                 qglStencilMask(~0);CHECKGLERROR
1423                 qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1424                 break;
1425         case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
1426                 GL_CullFace(GL_NONE);
1427                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1428                 qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
1429                 qglStencilMask(~0);CHECKGLERROR
1430                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1431                 qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
1432                 qglStencilMask(~0);CHECKGLERROR
1433                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1434                 break;
1435         }
1436 }
1437
1438 void R_Shadow_RenderMode_ShadowMap(int side, qboolean clear, int size)
1439 {
1440         int i;
1441         int status;
1442         int maxsize;
1443         float nearclip, farclip;
1444         r_viewport_t viewport;
1445         CHECKGLERROR
1446         maxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, 2048);
1447         if (r_shadow_shadowmapmaxsize != maxsize)
1448         {
1449                 r_shadow_shadowmapmaxsize = maxsize;
1450
1451                 if (r_shadow_fborectangle)
1452                         qglDeleteFramebuffersEXT(1, &r_shadow_fborectangle);
1453                 r_shadow_fborectangle = 0;
1454
1455                 if (r_shadow_fbo2d)
1456                         qglDeleteFramebuffersEXT(1, &r_shadow_fbo2d);
1457                 r_shadow_fbo2d = 0;
1458
1459                 for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
1460                         if (r_shadow_fbocubeside[i])
1461                                 qglDeleteFramebuffersEXT(6, r_shadow_fbocubeside[i]);
1462                 memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside));
1463
1464                 if (r_shadow_shadowmaprectangletexture)
1465                         R_FreeTexture(r_shadow_shadowmaprectangletexture);
1466                 r_shadow_shadowmaprectangletexture = NULL;
1467
1468                 if (r_shadow_shadowmap2dtexture)
1469                         R_FreeTexture(r_shadow_shadowmap2dtexture);
1470                 r_shadow_shadowmap2dtexture = NULL;
1471
1472                 if (r_shadow_shadowmapcubeprojectiontexture)
1473                         R_FreeTexture(r_shadow_shadowmapcubeprojectiontexture);
1474                 r_shadow_shadowmapcubeprojectiontexture = NULL;
1475
1476                 for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
1477                         if (r_shadow_shadowmapcubetexture[i])
1478                                 R_FreeTexture(r_shadow_shadowmapcubetexture[i]);
1479                 memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
1480
1481                 CHECKGLERROR
1482         }
1483         nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
1484         farclip = 1.0f;
1485         r_shadow_shadowmap_bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
1486         r_shadow_shadowmap_parameters[0] = 1.0f - r_shadow_shadowmapping_bordersize.value / size;
1487         r_shadow_shadowmap_parameters[1] = 1.0f - r_shadow_shadowmapping_bordersize.value / size;
1488         r_shadow_shadowmap_parameters[2] = -(farclip + nearclip) / (farclip - nearclip);
1489         r_shadow_shadowmap_parameters[3] = -2.0f * nearclip * farclip / (farclip - nearclip);
1490         if (!r_shadow_shadowmapcubeprojectiontexture)
1491                 r_shadow_shadowmapcubeprojectiontexture = R_LoadTextureCubeProjection(r_shadow_texturepool, "shadowmapcubeprojection");
1492         if (r_shadow_shadowmapping.integer == 3)
1493         {
1494                 // complex unrolled cube approach (more flexible)
1495                 if (!r_shadow_shadowmap2dtexture)
1496                 {
1497 #if 1
1498                         r_shadow_shadowmap2dtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", size*2, size*4);
1499                         qglGenFramebuffersEXT(1, &r_shadow_fbo2d);CHECKGLERROR
1500                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbo2d);CHECKGLERROR
1501                         qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_shadowmap2dtexture), 0);CHECKGLERROR
1502 #endif
1503                 }
1504                 CHECKGLERROR
1505                 R_Shadow_RenderMode_Reset();
1506                 if (r_shadow_shadowmap2dtexture)
1507                 {
1508                         // render depth into the fbo, do not render color at all
1509                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbo2d);CHECKGLERROR
1510                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1511                         qglReadBuffer(GL_NONE);CHECKGLERROR
1512                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1513                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1514                         {
1515                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1516                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1517                         }
1518                         R_SetupDepthOrShadowShader();
1519                 }
1520                 else
1521                 {
1522                         R_SetupShowDepthShader();
1523                         qglClearColor(1,1,1,1);CHECKGLERROR
1524                 }
1525                 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapping_bordersize.integer, nearclip, farclip, NULL);
1526                 r_shadow_shadowmap_texturescale[0] = (float)size / R_TextureWidth(r_shadow_shadowmap2dtexture);
1527                 r_shadow_shadowmap_texturescale[1] = (float)size / R_TextureHeight(r_shadow_shadowmap2dtexture);
1528                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
1529         }
1530         else if (r_shadow_shadowmapping.integer == 2)
1531         {
1532                 // complex unrolled cube approach (more flexible)
1533                 if (!r_shadow_shadowmaprectangletexture)
1534                 {
1535 #if 1
1536                         r_shadow_shadowmaprectangletexture = R_LoadTextureShadowMapRectangle(r_shadow_texturepool, "shadowmap", size*2, size*4);
1537                         qglGenFramebuffersEXT(1, &r_shadow_fborectangle);CHECKGLERROR
1538                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
1539                         qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_RECTANGLE_ARB, R_GetTexture(r_shadow_shadowmaprectangletexture), 0);CHECKGLERROR
1540 #endif
1541                 }
1542                 CHECKGLERROR
1543                 R_Shadow_RenderMode_Reset();
1544                 if (r_shadow_shadowmaprectangletexture)
1545                 {
1546                         // render depth into the fbo, do not render color at all
1547                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
1548                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1549                         qglReadBuffer(GL_NONE);CHECKGLERROR
1550                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1551                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1552                         {
1553                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1554                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1555                         }
1556                         R_SetupDepthOrShadowShader();
1557                 }
1558                 else
1559                 {
1560                         R_SetupShowDepthShader();
1561                         qglClearColor(1,1,1,1);CHECKGLERROR
1562                 }
1563                 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapping_bordersize.integer, nearclip, farclip, NULL);
1564                 r_shadow_shadowmap_texturescale[0] = size;
1565                 r_shadow_shadowmap_texturescale[1] = size;
1566                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE;
1567         }
1568         else
1569         {
1570                 // simple cube approach
1571                 if (!r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod])
1572                 {
1573 #if 1
1574                         r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod] = R_LoadTextureShadowMapCube(r_shadow_texturepool, "shadowmapcube", size);
1575                         qglGenFramebuffersEXT(6, r_shadow_fbocubeside[r_shadow_shadowmaplod]);CHECKGLERROR
1576                         for (i = 0;i < 6;i++)
1577                         {
1578                                 qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbocubeside[r_shadow_shadowmaplod][i]);CHECKGLERROR
1579                                 qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + i, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]), 0);CHECKGLERROR
1580                         }
1581 #endif
1582                 }
1583                 CHECKGLERROR
1584                 R_Shadow_RenderMode_Reset();
1585                 if (r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod])
1586                 {
1587                         // render depth into the fbo, do not render color at all
1588                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbocubeside[r_shadow_shadowmaplod][side]);CHECKGLERROR
1589                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1590                         qglReadBuffer(GL_NONE);CHECKGLERROR
1591                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1592                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1593                         {
1594                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1595                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1596                         }
1597                         R_SetupDepthOrShadowShader();
1598                 }
1599                 else
1600                 {
1601                         R_SetupShowDepthShader();
1602                         qglClearColor(1,1,1,1);CHECKGLERROR
1603                 }
1604                 R_Viewport_InitCubeSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, nearclip, farclip, NULL);
1605                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
1606                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureWidth(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
1607                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE;
1608         }
1609         CHECKGLERROR
1610         R_SetViewport(&viewport);
1611         GL_PolygonOffset(0, 0);
1612         GL_CullFace(GL_NONE); // quake is backwards
1613         GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
1614         GL_DepthMask(true);
1615         GL_DepthTest(true);
1616         qglClearDepth(1);CHECKGLERROR
1617         CHECKGLERROR
1618         if (clear)
1619                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |  GL_STENCIL_BUFFER_BIT);
1620         CHECKGLERROR
1621 }
1622
1623 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
1624 {
1625         CHECKGLERROR
1626         R_Shadow_RenderMode_Reset();
1627         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1628         if (!transparent)
1629         {
1630                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
1631         }
1632         if (stenciltest)
1633         {
1634                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1635                 // only draw light where this geometry was already rendered AND the
1636                 // stencil is 128 (values other than this mean shadow)
1637                 qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR
1638         }
1639         r_shadow_rendermode = r_shadow_lightingrendermode;
1640         // do global setup needed for the chosen lighting mode
1641         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
1642         {
1643                 R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap)); // light filter
1644                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
1645                 CHECKGLERROR
1646                 if (shadowmapping)
1647                 {
1648                         if (r_shadow_shadowmapping.integer == 3)
1649                         {
1650                                 r_shadow_usingshadowmap2d = true;
1651                                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D, R_GetTexture(r_shadow_shadowmap2dtexture));
1652                                 CHECKGLERROR
1653                         }
1654                         else if (r_shadow_shadowmapping.integer == 2)
1655                         {
1656                                 r_shadow_usingshadowmaprect = true;
1657                                 R_Mesh_TexBindRectangle(GL20TU_SHADOWMAPRECT, R_GetTexture(r_shadow_shadowmaprectangletexture));
1658                                 CHECKGLERROR
1659                         }
1660                         else
1661                         {
1662                                 r_shadow_usingshadowmapcube = true;
1663                                 R_Mesh_TexBindCubeMap(GL20TU_SHADOWMAPCUBE, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]));
1664                                 CHECKGLERROR
1665                         }
1666                 }
1667         }
1668         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_VERTEX)
1669                 R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
1670         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1671         CHECKGLERROR
1672 }
1673
1674 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
1675 {
1676         CHECKGLERROR
1677         R_Shadow_RenderMode_Reset();
1678         GL_BlendFunc(GL_ONE, GL_ONE);
1679         GL_DepthRange(0, 1);
1680         GL_DepthTest(r_showshadowvolumes.integer < 2);
1681         GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
1682         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
1683         GL_CullFace(GL_NONE);
1684         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
1685 }
1686
1687 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
1688 {
1689         CHECKGLERROR
1690         R_Shadow_RenderMode_Reset();
1691         GL_BlendFunc(GL_ONE, GL_ONE);
1692         GL_DepthRange(0, 1);
1693         GL_DepthTest(r_showlighting.integer < 2);
1694         GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
1695         if (!transparent)
1696         {
1697                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
1698         }
1699         if (stenciltest)
1700         {
1701                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1702                 qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR
1703         }
1704         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
1705 }
1706
1707 void R_Shadow_RenderMode_End(void)
1708 {
1709         CHECKGLERROR
1710         R_Shadow_RenderMode_Reset();
1711         R_Shadow_RenderMode_ActiveLight(NULL);
1712         GL_DepthMask(true);
1713         GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.y - r_refdef.view.height, r_refdef.view.width, r_refdef.view.height);
1714         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1715 }
1716
1717 int bboxedges[12][2] =
1718 {
1719         // top
1720         {0, 1}, // +X
1721         {0, 2}, // +Y
1722         {1, 3}, // Y, +X
1723         {2, 3}, // X, +Y
1724         // bottom
1725         {4, 5}, // +X
1726         {4, 6}, // +Y
1727         {5, 7}, // Y, +X
1728         {6, 7}, // X, +Y
1729         // verticals
1730         {0, 4}, // +Z
1731         {1, 5}, // X, +Z
1732         {2, 6}, // Y, +Z
1733         {3, 7}, // XY, +Z
1734 };
1735
1736 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
1737 {
1738         int i, ix1, iy1, ix2, iy2;
1739         float x1, y1, x2, y2;
1740         vec4_t v, v2;
1741         float vertex[20][3];
1742         int j, k;
1743         vec4_t plane4f;
1744         int numvertices;
1745         float corner[8][4];
1746         float dist[8];
1747         int sign[8];
1748         float f;
1749
1750         r_shadow_lightscissor[0] = r_refdef.view.x;
1751         r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
1752         r_shadow_lightscissor[2] = r_refdef.view.width;
1753         r_shadow_lightscissor[3] = r_refdef.view.height;
1754
1755         if (!r_shadow_scissor.integer)
1756                 return false;
1757
1758         // if view is inside the light box, just say yes it's visible
1759         if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs))
1760                 return false;
1761
1762         x1 = y1 = x2 = y2 = 0;
1763
1764         // transform all corners that are infront of the nearclip plane
1765         VectorNegate(r_refdef.view.frustum[4].normal, plane4f);
1766         plane4f[3] = r_refdef.view.frustum[4].dist;
1767         numvertices = 0;
1768         for (i = 0;i < 8;i++)
1769         {
1770                 Vector4Set(corner[i], (i & 1) ? maxs[0] : mins[0], (i & 2) ? maxs[1] : mins[1], (i & 4) ? maxs[2] : mins[2], 1);
1771                 dist[i] = DotProduct4(corner[i], plane4f);
1772                 sign[i] = dist[i] > 0;
1773                 if (!sign[i])
1774                 {
1775                         VectorCopy(corner[i], vertex[numvertices]);
1776                         numvertices++;
1777                 }
1778         }
1779         // if some points are behind the nearclip, add clipped edge points to make
1780         // sure that the scissor boundary is complete
1781         if (numvertices > 0 && numvertices < 8)
1782         {
1783                 // add clipped edge points
1784                 for (i = 0;i < 12;i++)
1785                 {
1786                         j = bboxedges[i][0];
1787                         k = bboxedges[i][1];
1788                         if (sign[j] != sign[k])
1789                         {
1790                                 f = dist[j] / (dist[j] - dist[k]);
1791                                 VectorLerp(corner[j], f, corner[k], vertex[numvertices]);
1792                                 numvertices++;
1793                         }
1794                 }
1795         }
1796
1797         // if we have no points to check, the light is behind the view plane
1798         if (!numvertices)
1799                 return true;
1800
1801         // if we have some points to transform, check what screen area is covered
1802         x1 = y1 = x2 = y2 = 0;
1803         v[3] = 1.0f;
1804         //Con_Printf("%i vertices to transform...\n", numvertices);
1805         for (i = 0;i < numvertices;i++)
1806         {
1807                 VectorCopy(vertex[i], v);
1808                 R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2);
1809                 //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]);
1810                 if (i)
1811                 {
1812                         if (x1 > v2[0]) x1 = v2[0];
1813                         if (x2 < v2[0]) x2 = v2[0];
1814                         if (y1 > v2[1]) y1 = v2[1];
1815                         if (y2 < v2[1]) y2 = v2[1];
1816                 }
1817                 else
1818                 {
1819                         x1 = x2 = v2[0];
1820                         y1 = y2 = v2[1];
1821                 }
1822         }
1823
1824         // now convert the scissor rectangle to integer screen coordinates
1825         ix1 = (int)(x1 - 1.0f);
1826         iy1 = (int)(y1 - 1.0f);
1827         ix2 = (int)(x2 + 1.0f);
1828         iy2 = (int)(y2 + 1.0f);
1829         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
1830
1831         // clamp it to the screen
1832         if (ix1 < r_refdef.view.x) ix1 = r_refdef.view.x;
1833         if (iy1 < r_refdef.view.y) iy1 = r_refdef.view.y;
1834         if (ix2 > r_refdef.view.x + r_refdef.view.width) ix2 = r_refdef.view.x + r_refdef.view.width;
1835         if (iy2 > r_refdef.view.y + r_refdef.view.height) iy2 = r_refdef.view.y + r_refdef.view.height;
1836
1837         // if it is inside out, it's not visible
1838         if (ix2 <= ix1 || iy2 <= iy1)
1839                 return true;
1840
1841         // the light area is visible, set up the scissor rectangle
1842         r_shadow_lightscissor[0] = ix1;
1843         r_shadow_lightscissor[1] = vid.height - iy2;
1844         r_shadow_lightscissor[2] = ix2 - ix1;
1845         r_shadow_lightscissor[3] = iy2 - iy1;
1846
1847         r_refdef.stats.lights_scissored++;
1848         return false;
1849 }
1850
1851 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, int numtriangles, const int *element3i, const float *diffusecolor, const float *ambientcolor)
1852 {
1853         float *vertex3f = rsurface.vertex3f + 3 * firstvertex;
1854         float *normal3f = rsurface.normal3f + 3 * firstvertex;
1855         float *color4f = rsurface.array_color4f + 4 * firstvertex;
1856         float dist, dot, distintensity, shadeintensity, v[3], n[3];
1857         if (r_textureunits.integer >= 3)
1858         {
1859                 if (VectorLength2(diffusecolor) > 0)
1860                 {
1861                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1862                         {
1863                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
1864                                 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
1865                                 if ((dot = DotProduct(n, v)) < 0)
1866                                 {
1867                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1868                                         VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
1869                                 }
1870                                 else
1871                                         VectorCopy(ambientcolor, color4f);
1872                                 if (r_refdef.fogenabled)
1873                                 {
1874                                         float f;
1875                                         f = FogPoint_Model(vertex3f);
1876                                         VectorScale(color4f, f, color4f);
1877                                 }
1878                                 color4f[3] = 1;
1879                         }
1880                 }
1881                 else
1882                 {
1883                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
1884                         {
1885                                 VectorCopy(ambientcolor, color4f);
1886                                 if (r_refdef.fogenabled)
1887                                 {
1888                                         float f;
1889                                         Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
1890                                         f = FogPoint_Model(vertex3f);
1891                                         VectorScale(color4f, f, color4f);
1892                                 }
1893                                 color4f[3] = 1;
1894                         }
1895                 }
1896         }
1897         else if (r_textureunits.integer >= 2)
1898         {
1899                 if (VectorLength2(diffusecolor) > 0)
1900                 {
1901                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1902                         {
1903                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
1904                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
1905                                 {
1906                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
1907                                         if ((dot = DotProduct(n, v)) < 0)
1908                                         {
1909                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1910                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
1911                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
1912                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
1913                                         }
1914                                         else
1915                                         {
1916                                                 color4f[0] = ambientcolor[0] * distintensity;
1917                                                 color4f[1] = ambientcolor[1] * distintensity;
1918                                                 color4f[2] = ambientcolor[2] * distintensity;
1919                                         }
1920                                         if (r_refdef.fogenabled)
1921                                         {
1922                                                 float f;
1923                                                 f = FogPoint_Model(vertex3f);
1924                                                 VectorScale(color4f, f, color4f);
1925                                         }
1926                                 }
1927                                 else
1928                                         VectorClear(color4f);
1929                                 color4f[3] = 1;
1930                         }
1931                 }
1932                 else
1933                 {
1934                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
1935                         {
1936                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
1937                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
1938                                 {
1939                                         color4f[0] = ambientcolor[0] * distintensity;
1940                                         color4f[1] = ambientcolor[1] * distintensity;
1941                                         color4f[2] = ambientcolor[2] * distintensity;
1942                                         if (r_refdef.fogenabled)
1943                                         {
1944                                                 float f;
1945                                                 f = FogPoint_Model(vertex3f);
1946                                                 VectorScale(color4f, f, color4f);
1947                                         }
1948                                 }
1949                                 else
1950                                         VectorClear(color4f);
1951                                 color4f[3] = 1;
1952                         }
1953                 }
1954         }
1955         else
1956         {
1957                 if (VectorLength2(diffusecolor) > 0)
1958                 {
1959                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1960                         {
1961                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
1962                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
1963                                 {
1964                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
1965                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
1966                                         if ((dot = DotProduct(n, v)) < 0)
1967                                         {
1968                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1969                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
1970                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
1971                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
1972                                         }
1973                                         else
1974                                         {
1975                                                 color4f[0] = ambientcolor[0] * distintensity;
1976                                                 color4f[1] = ambientcolor[1] * distintensity;
1977                                                 color4f[2] = ambientcolor[2] * distintensity;
1978                                         }
1979                                         if (r_refdef.fogenabled)
1980                                         {
1981                                                 float f;
1982                                                 f = FogPoint_Model(vertex3f);
1983                                                 VectorScale(color4f, f, color4f);
1984                                         }
1985                                 }
1986                                 else
1987                                         VectorClear(color4f);
1988                                 color4f[3] = 1;
1989                         }
1990                 }
1991                 else
1992                 {
1993                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
1994                         {
1995                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
1996                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
1997                                 {
1998                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
1999                                         color4f[0] = ambientcolor[0] * distintensity;
2000                                         color4f[1] = ambientcolor[1] * distintensity;
2001                                         color4f[2] = ambientcolor[2] * distintensity;
2002                                         if (r_refdef.fogenabled)
2003                                         {
2004                                                 float f;
2005                                                 f = FogPoint_Model(vertex3f);
2006                                                 VectorScale(color4f, f, color4f);
2007                                         }
2008                                 }
2009                                 else
2010                                         VectorClear(color4f);
2011                                 color4f[3] = 1;
2012                         }
2013                 }
2014         }
2015 }
2016
2017 // TODO: use glTexGen instead of feeding vertices to texcoordpointer?
2018
2019 static void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(int firstvertex, int numvertices, int numtriangles, const int *element3i)
2020 {
2021         int i;
2022         float       *out3f     = rsurface.array_texcoord3f + 3 * firstvertex;
2023         const float *vertex3f  = rsurface.vertex3f         + 3 * firstvertex;
2024         const float *svector3f = rsurface.svector3f        + 3 * firstvertex;
2025         const float *tvector3f = rsurface.tvector3f        + 3 * firstvertex;
2026         const float *normal3f  = rsurface.normal3f         + 3 * firstvertex;
2027         float lightdir[3];
2028         for (i = 0;i < numvertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
2029         {
2030                 VectorSubtract(rsurface.entitylightorigin, vertex3f, lightdir);
2031                 // the cubemap normalizes this for us
2032                 out3f[0] = DotProduct(svector3f, lightdir);
2033                 out3f[1] = DotProduct(tvector3f, lightdir);
2034                 out3f[2] = DotProduct(normal3f, lightdir);
2035         }
2036 }
2037
2038 static void R_Shadow_GenTexCoords_Specular_NormalCubeMap(int firstvertex, int numvertices, int numtriangles, const int *element3i)
2039 {
2040         int i;
2041         float       *out3f     = rsurface.array_texcoord3f + 3 * firstvertex;
2042         const float *vertex3f  = rsurface.vertex3f         + 3 * firstvertex;
2043         const float *svector3f = rsurface.svector3f        + 3 * firstvertex;
2044         const float *tvector3f = rsurface.tvector3f        + 3 * firstvertex;
2045         const float *normal3f  = rsurface.normal3f         + 3 * firstvertex;
2046         float lightdir[3], eyedir[3], halfdir[3];
2047         for (i = 0;i < numvertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
2048         {
2049                 VectorSubtract(rsurface.entitylightorigin, vertex3f, lightdir);
2050                 VectorNormalize(lightdir);
2051                 VectorSubtract(rsurface.modelorg, vertex3f, eyedir);
2052                 VectorNormalize(eyedir);
2053                 VectorAdd(lightdir, eyedir, halfdir);
2054                 // the cubemap normalizes this for us
2055                 out3f[0] = DotProduct(svector3f, halfdir);
2056                 out3f[1] = DotProduct(tvector3f, halfdir);
2057                 out3f[2] = DotProduct(normal3f, halfdir);
2058         }
2059 }
2060
2061 static void R_Shadow_RenderLighting_VisibleLighting(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt)
2062 {
2063         // used to display how many times a surface is lit for level design purposes
2064         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2065 }
2066
2067 static void R_Shadow_RenderLighting_Light_GLSL(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt)
2068 {
2069         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
2070         R_SetupSurfaceShader(lightcolorbase, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT);
2071         if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND))
2072                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
2073         else
2074                 R_Mesh_ColorPointer(NULL, 0, 0);
2075         R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
2076         R_Mesh_TexMatrix(1, &rsurface.texture->currentbackgroundtexmatrix);
2077         R_Mesh_TexBind(GL20TU_NORMAL, R_GetTexture(rsurface.texture->currentskinframe->nmap));
2078         R_Mesh_TexBind(GL20TU_COLOR, R_GetTexture(rsurface.texture->basetexture));
2079         R_Mesh_TexBind(GL20TU_GLOSS, R_GetTexture(rsurface.texture->glosstexture));
2080         if (rsurface.texture->backgroundcurrentskinframe)
2081         {
2082                 R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->nmap));
2083                 R_Mesh_TexBind(GL20TU_SECONDARY_COLOR, R_GetTexture(rsurface.texture->backgroundbasetexture));
2084                 R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS, R_GetTexture(rsurface.texture->backgroundglosstexture));
2085                 R_Mesh_TexBind(GL20TU_SECONDARY_GLOW, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->glow));
2086         }
2087         //R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap));
2088         R_Mesh_TexBind(GL20TU_FOGMASK, R_GetTexture(r_texture_fogattenuation));
2089         if(rsurface.texture->colormapping)
2090         {
2091                 R_Mesh_TexBind(GL20TU_PANTS, R_GetTexture(rsurface.texture->currentskinframe->pants));
2092                 R_Mesh_TexBind(GL20TU_SHIRT, R_GetTexture(rsurface.texture->currentskinframe->shirt));
2093         }
2094         R_Mesh_TexBind(GL20TU_ATTENUATION, R_GetTexture(r_shadow_attenuationgradienttexture));
2095         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
2096         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
2097         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
2098         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
2099         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
2100         {
2101                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
2102         }
2103         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2104         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
2105         {
2106                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
2107         }
2108 }
2109
2110 static void R_Shadow_RenderLighting_Light_Dot3_Finalize(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, float r, float g, float b)
2111 {
2112         // shared final code for all the dot3 layers
2113         int renders;
2114         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2115         for (renders = 0;renders < 64 && (r > 0 || g > 0 || b > 0);renders++, r--, g--, b--)
2116         {
2117                 GL_Color(bound(0, r, 1), bound(0, g, 1), bound(0, b, 1), 1);
2118                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2119         }
2120 }
2121
2122 static void R_Shadow_RenderLighting_Light_Dot3_AmbientPass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *basetexture, float colorscale)
2123 {
2124         rmeshstate_t m;
2125         // colorscale accounts for how much we multiply the brightness
2126         // during combine.
2127         //
2128         // mult is how many times the final pass of the lighting will be
2129         // performed to get more brightness than otherwise possible.
2130         //
2131         // Limit mult to 64 for sanity sake.
2132         GL_Color(1,1,1,1);
2133         if (r_shadow_texture3d.integer && rsurface.rtlight->currentcubemap != r_texture_whitecube && r_textureunits.integer >= 4)
2134         {
2135                 // 3 3D combine path (Geforce3, Radeon 8500)
2136                 memset(&m, 0, sizeof(m));
2137                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2138                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2139                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2140                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2141                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2142                 m.tex[1] = R_GetTexture(basetexture);
2143                 m.pointer_texcoord[1] = rsurface.texcoordtexture2f;
2144                 m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
2145                 m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
2146                 m.texmatrix[1] = rsurface.texture->currenttexmatrix;
2147                 m.texcubemap[2] = R_GetTexture(rsurface.rtlight->currentcubemap);
2148                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2149                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2150                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2151                 m.texmatrix[2] = rsurface.entitytolight;
2152                 GL_BlendFunc(GL_ONE, GL_ONE);
2153         }
2154         else if (r_shadow_texture3d.integer && rsurface.rtlight->currentcubemap == r_texture_whitecube && r_textureunits.integer >= 2)
2155         {
2156                 // 2 3D combine path (Geforce3, original Radeon)
2157                 memset(&m, 0, sizeof(m));
2158                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2159                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2160                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2161                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2162                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2163                 m.tex[1] = R_GetTexture(basetexture);
2164                 m.pointer_texcoord[1] = rsurface.texcoordtexture2f;
2165                 m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
2166                 m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
2167                 m.texmatrix[1] = rsurface.texture->currenttexmatrix;
2168                 GL_BlendFunc(GL_ONE, GL_ONE);
2169         }
2170         else if (r_textureunits.integer >= 4 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2171         {
2172                 // 4 2D combine path (Geforce3, Radeon 8500)
2173                 memset(&m, 0, sizeof(m));
2174                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2175                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2176                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2177                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2178                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2179                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2180                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2181                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2182                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2183                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2184                 m.tex[2] = R_GetTexture(basetexture);
2185                 m.pointer_texcoord[2] = rsurface.texcoordtexture2f;
2186                 m.pointer_texcoord_bufferobject[2] = rsurface.texcoordtexture2f_bufferobject;
2187                 m.pointer_texcoord_bufferoffset[2] = rsurface.texcoordtexture2f_bufferoffset;
2188                 m.texmatrix[2] = rsurface.texture->currenttexmatrix;
2189                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2190                 {
2191                         m.texcubemap[3] = R_GetTexture(rsurface.rtlight->currentcubemap);
2192                         m.pointer_texcoord3f[3] = rsurface.vertex3f;
2193                         m.pointer_texcoord_bufferobject[3] = rsurface.vertex3f_bufferobject;
2194                         m.pointer_texcoord_bufferoffset[3] = rsurface.vertex3f_bufferoffset;
2195                         m.texmatrix[3] = rsurface.entitytolight;
2196                 }
2197                 GL_BlendFunc(GL_ONE, GL_ONE);
2198         }
2199         else if (r_textureunits.integer >= 3 && rsurface.rtlight->currentcubemap == r_texture_whitecube)
2200         {
2201                 // 3 2D combine path (Geforce3, original Radeon)
2202                 memset(&m, 0, sizeof(m));
2203                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2204                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2205                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2206                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2207                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2208                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2209                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2210                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2211                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2212                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2213                 m.tex[2] = R_GetTexture(basetexture);
2214                 m.pointer_texcoord[2] = rsurface.texcoordtexture2f;
2215                 m.pointer_texcoord_bufferobject[2] = rsurface.texcoordtexture2f_bufferobject;
2216                 m.pointer_texcoord_bufferoffset[2] = rsurface.texcoordtexture2f_bufferoffset;
2217                 m.texmatrix[2] = rsurface.texture->currenttexmatrix;
2218                 GL_BlendFunc(GL_ONE, GL_ONE);
2219         }
2220         else
2221         {
2222                 // 2/2/2 2D combine path (any dot3 card)
2223                 memset(&m, 0, sizeof(m));
2224                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2225                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2226                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2227                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2228                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2229                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2230                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2231                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2232                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2233                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2234                 R_Mesh_TextureState(&m);
2235                 GL_ColorMask(0,0,0,1);
2236                 GL_BlendFunc(GL_ONE, GL_ZERO);
2237                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2238
2239                 // second pass
2240                 memset(&m, 0, sizeof(m));
2241                 m.tex[0] = R_GetTexture(basetexture);
2242                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2243                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2244                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2245                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2246                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2247                 {
2248                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2249                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2250                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2251                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2252                         m.texmatrix[1] = rsurface.entitytolight;
2253                 }
2254                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2255         }
2256         // this final code is shared
2257         R_Mesh_TextureState(&m);
2258         R_Shadow_RenderLighting_Light_Dot3_Finalize(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
2259 }
2260
2261 static void R_Shadow_RenderLighting_Light_Dot3_DiffusePass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *basetexture, rtexture_t *normalmaptexture, float colorscale)
2262 {
2263         rmeshstate_t m;
2264         // colorscale accounts for how much we multiply the brightness
2265         // during combine.
2266         //
2267         // mult is how many times the final pass of the lighting will be
2268         // performed to get more brightness than otherwise possible.
2269         //
2270         // Limit mult to 64 for sanity sake.
2271         GL_Color(1,1,1,1);
2272         // generate normalization cubemap texcoords
2273         R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(firstvertex, numvertices, numtriangles, element3i);
2274         if (r_shadow_texture3d.integer && r_textureunits.integer >= 4)
2275         {
2276                 // 3/2 3D combine path (Geforce3, Radeon 8500)
2277                 memset(&m, 0, sizeof(m));
2278                 m.tex[0] = R_GetTexture(normalmaptexture);
2279                 m.texcombinergb[0] = GL_REPLACE;
2280                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2281                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2282                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2283                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2284                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2285                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2286                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2287                 m.pointer_texcoord_bufferobject[1] = 0;
2288                 m.pointer_texcoord_bufferoffset[1] = 0;
2289                 m.tex3d[2] = R_GetTexture(r_shadow_attenuation3dtexture);
2290                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2291                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2292                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2293                 m.texmatrix[2] = rsurface.entitytoattenuationxyz;
2294                 R_Mesh_TextureState(&m);
2295                 GL_ColorMask(0,0,0,1);
2296                 GL_BlendFunc(GL_ONE, GL_ZERO);
2297                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2298
2299                 // second pass
2300                 memset(&m, 0, sizeof(m));
2301                 m.tex[0] = R_GetTexture(basetexture);
2302                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2303                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2304                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2305                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2306                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2307                 {
2308                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2309                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2310                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2311                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2312                         m.texmatrix[1] = rsurface.entitytolight;
2313                 }
2314                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2315         }
2316         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2317         {
2318                 // 1/2/2 3D combine path (original Radeon)
2319                 memset(&m, 0, sizeof(m));
2320                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2321                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2322                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2323                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2324                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2325                 R_Mesh_TextureState(&m);
2326                 GL_ColorMask(0,0,0,1);
2327                 GL_BlendFunc(GL_ONE, GL_ZERO);
2328                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2329
2330                 // second pass
2331                 memset(&m, 0, sizeof(m));
2332                 m.tex[0] = R_GetTexture(normalmaptexture);
2333                 m.texcombinergb[0] = GL_REPLACE;
2334                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2335                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2336                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2337                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2338                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2339                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2340                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2341                 m.pointer_texcoord_bufferobject[1] = 0;
2342                 m.pointer_texcoord_bufferoffset[1] = 0;
2343                 R_Mesh_TextureState(&m);
2344                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2345                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2346
2347                 // second pass
2348                 memset(&m, 0, sizeof(m));
2349                 m.tex[0] = R_GetTexture(basetexture);
2350                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2351                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2352                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2353                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2354                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2355                 {
2356                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2357                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2358                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2359                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2360                         m.texmatrix[1] = rsurface.entitytolight;
2361                 }
2362                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2363         }
2364         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap == r_texture_whitecube)
2365         {
2366                 // 2/2 3D combine path (original Radeon)
2367                 memset(&m, 0, sizeof(m));
2368                 m.tex[0] = R_GetTexture(normalmaptexture);
2369                 m.texcombinergb[0] = GL_REPLACE;
2370                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2371                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2372                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2373                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2374                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2375                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2376                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2377                 m.pointer_texcoord_bufferobject[1] = 0;
2378                 m.pointer_texcoord_bufferoffset[1] = 0;
2379                 R_Mesh_TextureState(&m);
2380                 GL_ColorMask(0,0,0,1);
2381                 GL_BlendFunc(GL_ONE, GL_ZERO);
2382                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2383
2384                 // second pass
2385                 memset(&m, 0, sizeof(m));
2386                 m.tex[0] = R_GetTexture(basetexture);
2387                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2388                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2389                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2390                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2391                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
2392                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2393                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2394                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2395                 m.texmatrix[1] = rsurface.entitytoattenuationxyz;
2396                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2397         }
2398         else if (r_textureunits.integer >= 4)
2399         {
2400                 // 4/2 2D combine path (Geforce3, Radeon 8500)
2401                 memset(&m, 0, sizeof(m));
2402                 m.tex[0] = R_GetTexture(normalmaptexture);
2403                 m.texcombinergb[0] = GL_REPLACE;
2404                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2405                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2406                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2407                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2408                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2409                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2410                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2411                 m.pointer_texcoord_bufferobject[1] = 0;
2412                 m.pointer_texcoord_bufferoffset[1] = 0;
2413                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
2414                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2415                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2416                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2417                 m.texmatrix[2] = rsurface.entitytoattenuationxyz;
2418                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
2419                 m.pointer_texcoord3f[3] = rsurface.vertex3f;
2420                 m.pointer_texcoord_bufferobject[3] = rsurface.vertex3f_bufferobject;
2421                 m.pointer_texcoord_bufferoffset[3] = rsurface.vertex3f_bufferoffset;
2422                 m.texmatrix[3] = rsurface.entitytoattenuationz;
2423                 R_Mesh_TextureState(&m);
2424                 GL_ColorMask(0,0,0,1);
2425                 GL_BlendFunc(GL_ONE, GL_ZERO);
2426                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2427
2428                 // second pass
2429                 memset(&m, 0, sizeof(m));
2430                 m.tex[0] = R_GetTexture(basetexture);
2431                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2432                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2433                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2434                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2435                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2436                 {
2437                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2438                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2439                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2440                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2441                         m.texmatrix[1] = rsurface.entitytolight;
2442                 }
2443                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2444         }
2445         else
2446         {
2447                 // 2/2/2 2D combine path (any dot3 card)
2448                 memset(&m, 0, sizeof(m));
2449                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2450                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2451                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2452                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2453                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2454                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2455                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2456                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2457                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2458                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2459                 R_Mesh_TextureState(&m);
2460                 GL_ColorMask(0,0,0,1);
2461                 GL_BlendFunc(GL_ONE, GL_ZERO);
2462                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2463
2464                 // second pass
2465                 memset(&m, 0, sizeof(m));
2466                 m.tex[0] = R_GetTexture(normalmaptexture);
2467                 m.texcombinergb[0] = GL_REPLACE;
2468                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2469                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2470                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2471                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2472                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2473                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2474                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2475                 m.pointer_texcoord_bufferobject[1] = 0;
2476                 m.pointer_texcoord_bufferoffset[1] = 0;
2477                 R_Mesh_TextureState(&m);
2478                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2479                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2480
2481                 // second pass
2482                 memset(&m, 0, sizeof(m));
2483                 m.tex[0] = R_GetTexture(basetexture);
2484                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2485                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2486                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2487                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2488                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2489                 {
2490                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2491                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2492                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2493                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2494                         m.texmatrix[1] = rsurface.entitytolight;
2495                 }
2496                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2497         }
2498         // this final code is shared
2499         R_Mesh_TextureState(&m);
2500         R_Shadow_RenderLighting_Light_Dot3_Finalize(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
2501 }
2502
2503 static void R_Shadow_RenderLighting_Light_Dot3_SpecularPass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *glosstexture, rtexture_t *normalmaptexture, float colorscale)
2504 {
2505         float glossexponent;
2506         rmeshstate_t m;
2507         // FIXME: detect blendsquare!
2508         //if (!gl_support_blendsquare)
2509         //      return;
2510         GL_Color(1,1,1,1);
2511         // generate normalization cubemap texcoords
2512         R_Shadow_GenTexCoords_Specular_NormalCubeMap(firstvertex, numvertices, numtriangles, element3i);
2513         if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2514         {
2515                 // 2/0/0/1/2 3D combine blendsquare path
2516                 memset(&m, 0, sizeof(m));
2517                 m.tex[0] = R_GetTexture(normalmaptexture);
2518                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2519                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2520                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2521                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2522                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2523                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2524                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2525                 m.pointer_texcoord_bufferobject[1] = 0;
2526                 m.pointer_texcoord_bufferoffset[1] = 0;
2527                 R_Mesh_TextureState(&m);
2528                 GL_ColorMask(0,0,0,1);
2529                 // this squares the result
2530                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2531                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2532
2533                 // second and third pass
2534                 R_Mesh_ResetTextureState();
2535                 // square alpha in framebuffer a few times to make it shiny
2536                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
2537                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
2538                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2539
2540                 // fourth pass
2541                 memset(&m, 0, sizeof(m));
2542                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2543                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2544                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2545                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2546                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2547                 R_Mesh_TextureState(&m);
2548                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2549                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2550
2551                 // fifth pass
2552                 memset(&m, 0, sizeof(m));
2553                 m.tex[0] = R_GetTexture(glosstexture);
2554                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2555                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2556                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2557                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2558                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2559                 {
2560                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2561                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2562                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2563                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2564                         m.texmatrix[1] = rsurface.entitytolight;
2565                 }
2566                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2567         }
2568         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap == r_texture_whitecube /* && gl_support_blendsquare*/) // FIXME: detect blendsquare!
2569         {
2570                 // 2/0/0/2 3D combine blendsquare path
2571                 memset(&m, 0, sizeof(m));
2572                 m.tex[0] = R_GetTexture(normalmaptexture);
2573                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2574                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2575                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2576                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2577                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2578                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2579                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2580                 m.pointer_texcoord_bufferobject[1] = 0;
2581                 m.pointer_texcoord_bufferoffset[1] = 0;
2582                 R_Mesh_TextureState(&m);
2583                 GL_ColorMask(0,0,0,1);
2584                 // this squares the result
2585                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2586                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2587
2588                 // second and third pass
2589                 R_Mesh_ResetTextureState();
2590                 // square alpha in framebuffer a few times to make it shiny
2591                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
2592                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
2593                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2594
2595                 // fourth pass
2596                 memset(&m, 0, sizeof(m));
2597                 m.tex[0] = R_GetTexture(glosstexture);
2598                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2599                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2600                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2601                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2602                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
2603                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2604                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2605                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2606                 m.texmatrix[1] = rsurface.entitytoattenuationxyz;
2607                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2608         }
2609         else
2610         {
2611                 // 2/0/0/2/2 2D combine blendsquare path
2612                 memset(&m, 0, sizeof(m));
2613                 m.tex[0] = R_GetTexture(normalmaptexture);
2614                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2615                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2616                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2617                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2618                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2619                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2620                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2621                 m.pointer_texcoord_bufferobject[1] = 0;
2622                 m.pointer_texcoord_bufferoffset[1] = 0;
2623                 R_Mesh_TextureState(&m);
2624                 GL_ColorMask(0,0,0,1);
2625                 // this squares the result
2626                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2627                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2628
2629                 // second and third pass
2630                 R_Mesh_ResetTextureState();
2631                 // square alpha in framebuffer a few times to make it shiny
2632                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
2633                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
2634                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2635
2636                 // fourth pass
2637                 memset(&m, 0, sizeof(m));
2638                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2639                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2640                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2641                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2642                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2643                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2644                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2645                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2646                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2647                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2648                 R_Mesh_TextureState(&m);
2649                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2650                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2651
2652                 // fifth pass
2653                 memset(&m, 0, sizeof(m));
2654                 m.tex[0] = R_GetTexture(glosstexture);
2655                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2656                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2657                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2658                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2659                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2660                 {
2661                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2662                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2663                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2664                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2665                         m.texmatrix[1] = rsurface.entitytolight;
2666                 }
2667                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2668         }
2669         // this final code is shared
2670         R_Mesh_TextureState(&m);
2671         R_Shadow_RenderLighting_Light_Dot3_Finalize(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
2672 }
2673
2674 static void R_Shadow_RenderLighting_Light_Dot3(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt)
2675 {
2676         // ARB path (any Geforce, any Radeon)
2677         qboolean doambient = ambientscale > 0;
2678         qboolean dodiffuse = diffusescale > 0;
2679         qboolean dospecular = specularscale > 0;
2680         if (!doambient && !dodiffuse && !dospecular)
2681                 return;
2682         R_Mesh_ColorPointer(NULL, 0, 0);
2683         if (doambient)
2684                 R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, basetexture, ambientscale * r_refdef.view.colorscale);
2685         if (dodiffuse)
2686                 R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, basetexture, normalmaptexture, diffusescale * r_refdef.view.colorscale);
2687         if (dopants)
2688         {
2689                 if (doambient)
2690                         R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorpants, pantstexture, ambientscale * r_refdef.view.colorscale);
2691                 if (dodiffuse)
2692                         R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorpants, pantstexture, normalmaptexture, diffusescale * r_refdef.view.colorscale);
2693         }
2694         if (doshirt)
2695         {
2696                 if (doambient)
2697                         R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorshirt, shirttexture, ambientscale * r_refdef.view.colorscale);
2698                 if (dodiffuse)
2699                         R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorshirt, shirttexture, normalmaptexture, diffusescale * r_refdef.view.colorscale);
2700         }
2701         if (dospecular)
2702                 R_Shadow_RenderLighting_Light_Dot3_SpecularPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, glosstexture, normalmaptexture, specularscale * r_refdef.view.colorscale);
2703 }
2704
2705 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
2706 {
2707         int renders;
2708         int i;
2709         int stop;
2710         int newfirstvertex;
2711         int newlastvertex;
2712         int newnumtriangles;
2713         int *newe;
2714         const int *e;
2715         float *c;
2716         int maxtriangles = 4096;
2717         int newelements[4096*3];
2718         R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, numtriangles, element3i, diffusecolor2, ambientcolor2);
2719         for (renders = 0;renders < 64;renders++)
2720         {
2721                 stop = true;
2722                 newfirstvertex = 0;
2723                 newlastvertex = 0;
2724                 newnumtriangles = 0;
2725                 newe = newelements;
2726                 // due to low fillrate on the cards this vertex lighting path is
2727                 // designed for, we manually cull all triangles that do not
2728                 // contain a lit vertex
2729                 // this builds batches of triangles from multiple surfaces and
2730                 // renders them at once
2731                 for (i = 0, e = element3i;i < numtriangles;i++, e += 3)
2732                 {
2733                         if (VectorLength2(rsurface.array_color4f + e[0] * 4) + VectorLength2(rsurface.array_color4f + e[1] * 4) + VectorLength2(rsurface.array_color4f + e[2] * 4) >= 0.01)
2734                         {
2735                                 if (newnumtriangles)
2736                                 {
2737                                         newfirstvertex = min(newfirstvertex, e[0]);
2738                                         newlastvertex  = max(newlastvertex, e[0]);
2739                                 }
2740                                 else
2741                                 {
2742                                         newfirstvertex = e[0];
2743                                         newlastvertex = e[0];
2744                                 }
2745                                 newfirstvertex = min(newfirstvertex, e[1]);
2746                                 newlastvertex  = max(newlastvertex, e[1]);
2747                                 newfirstvertex = min(newfirstvertex, e[2]);
2748                                 newlastvertex  = max(newlastvertex, e[2]);
2749                                 newe[0] = e[0];
2750                                 newe[1] = e[1];
2751                                 newe[2] = e[2];
2752                                 newnumtriangles++;
2753                                 newe += 3;
2754                                 if (newnumtriangles >= maxtriangles)
2755                                 {
2756                                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, 0);
2757                                         newnumtriangles = 0;
2758                                         newe = newelements;
2759                                         stop = false;
2760                                 }
2761                         }
2762                 }
2763                 if (newnumtriangles >= 1)
2764                 {
2765                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, 0);
2766                         stop = false;
2767                 }
2768                 // if we couldn't find any lit triangles, exit early
2769                 if (stop)
2770                         break;
2771                 // now reduce the intensity for the next overbright pass
2772                 // we have to clamp to 0 here incase the drivers have improper
2773                 // handling of negative colors
2774                 // (some old drivers even have improper handling of >1 color)
2775                 stop = true;
2776                 for (i = 0, c = rsurface.array_color4f + 4 * firstvertex;i < numvertices;i++, c += 4)
2777                 {
2778                         if (c[0] > 1 || c[1] > 1 || c[2] > 1)
2779                         {
2780                                 c[0] = max(0, c[0] - 1);
2781                                 c[1] = max(0, c[1] - 1);
2782                                 c[2] = max(0, c[2] - 1);
2783                                 stop = false;
2784                         }
2785                         else
2786                                 VectorClear(c);
2787                 }
2788                 // another check...
2789                 if (stop)
2790                         break;
2791         }
2792 }
2793
2794 static void R_Shadow_RenderLighting_Light_Vertex(int firstvertex, int numvertices, int numtriangles, const int *element3i, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt)
2795 {
2796         // OpenGL 1.1 path (anything)
2797         float ambientcolorbase[3], diffusecolorbase[3];
2798         float ambientcolorpants[3], diffusecolorpants[3];
2799         float ambientcolorshirt[3], diffusecolorshirt[3];
2800         rmeshstate_t m;
2801         VectorScale(lightcolorbase, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorbase);
2802         VectorScale(lightcolorbase, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorbase);
2803         VectorScale(lightcolorpants, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorpants);
2804         VectorScale(lightcolorpants, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorpants);
2805         VectorScale(lightcolorshirt, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorshirt);
2806         VectorScale(lightcolorshirt, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorshirt);
2807         memset(&m, 0, sizeof(m));
2808         m.tex[0] = R_GetTexture(basetexture);
2809         m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2810         m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2811         m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2812         m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2813         if (r_textureunits.integer >= 2)
2814         {
2815                 // voodoo2 or TNT
2816                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2817                 m.texmatrix[1] = rsurface.entitytoattenuationxyz;
2818                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2819                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2820                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2821                 if (r_textureunits.integer >= 3)
2822                 {
2823                         // Voodoo4 or Kyro (or Geforce3/Radeon with gl_combine off)
2824                         m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
2825                         m.texmatrix[2] = rsurface.entitytoattenuationz;
2826                         m.pointer_texcoord3f[2] = rsurface.vertex3f;
2827                         m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2828                         m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2829                 }
2830         }
2831         R_Mesh_TextureState(&m);
2832         //R_Mesh_TexBind(0, R_GetTexture(basetexture));
2833         R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorbase, ambientcolorbase);
2834         if (dopants)
2835         {
2836                 R_Mesh_TexBind(0, R_GetTexture(pantstexture));
2837                 R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorpants, ambientcolorpants);
2838         }
2839         if (doshirt)
2840         {
2841                 R_Mesh_TexBind(0, R_GetTexture(shirttexture));
2842                 R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorshirt, ambientcolorshirt);
2843         }
2844 }
2845
2846 extern cvar_t gl_lightmaps;
2847 void R_Shadow_RenderLighting(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject)
2848 {
2849         float ambientscale, diffusescale, specularscale;
2850         vec3_t lightcolorbase, lightcolorpants, lightcolorshirt;
2851         rtexture_t *nmap;
2852         // calculate colors to render this texture with
2853         lightcolorbase[0] = rsurface.rtlight->currentcolor[0] * rsurface.texture->dlightcolor[0];
2854         lightcolorbase[1] = rsurface.rtlight->currentcolor[1] * rsurface.texture->dlightcolor[1];
2855         lightcolorbase[2] = rsurface.rtlight->currentcolor[2] * rsurface.texture->dlightcolor[2];
2856         ambientscale = rsurface.rtlight->ambientscale;
2857         diffusescale = rsurface.rtlight->diffusescale;
2858         specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale;
2859         if (!r_shadow_usenormalmap.integer)
2860         {
2861                 ambientscale += 1.0f * diffusescale;
2862                 diffusescale = 0;
2863                 specularscale = 0;
2864         }
2865         if ((ambientscale + diffusescale) * VectorLength2(lightcolorbase) + specularscale * VectorLength2(lightcolorbase) < (1.0f / 1048576.0f))
2866                 return;
2867         RSurf_SetupDepthAndCulling();
2868         nmap = rsurface.texture->currentskinframe->nmap;
2869         if (gl_lightmaps.integer)
2870                 nmap = r_texture_blanknormalmap;
2871         if (rsurface.texture->colormapping && !gl_lightmaps.integer)
2872         {
2873                 qboolean dopants = rsurface.texture->currentskinframe->pants != NULL && VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f);
2874                 qboolean doshirt = rsurface.texture->currentskinframe->shirt != NULL && VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
2875                 if (dopants)
2876                 {
2877                         lightcolorpants[0] = lightcolorbase[0] * rsurface.colormap_pantscolor[0];
2878                         lightcolorpants[1] = lightcolorbase[1] * rsurface.colormap_pantscolor[1];
2879                         lightcolorpants[2] = lightcolorbase[2] * rsurface.colormap_pantscolor[2];
2880                 }
2881                 else
2882                         VectorClear(lightcolorpants);
2883                 if (doshirt)
2884                 {
2885                         lightcolorshirt[0] = lightcolorbase[0] * rsurface.colormap_shirtcolor[0];
2886                         lightcolorshirt[1] = lightcolorbase[1] * rsurface.colormap_shirtcolor[1];
2887                         lightcolorshirt[2] = lightcolorbase[2] * rsurface.colormap_shirtcolor[2];
2888                 }
2889                 else
2890                         VectorClear(lightcolorshirt);
2891                 switch (r_shadow_rendermode)
2892                 {
2893                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2894                         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
2895                         R_Shadow_RenderLighting_VisibleLighting(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface.texture->basetexture, rsurface.texture->currentskinframe->pants, rsurface.texture->currentskinframe->shirt, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, dopants, doshirt);
2896                         break;
2897                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2898                         R_Shadow_RenderLighting_Light_GLSL(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface.texture->basetexture, rsurface.texture->currentskinframe->pants, rsurface.texture->currentskinframe->shirt, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, dopants, doshirt);
2899                         break;
2900                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2901                         R_Shadow_RenderLighting_Light_Dot3(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface.texture->basetexture, rsurface.texture->currentskinframe->pants, rsurface.texture->currentskinframe->shirt, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, dopants, doshirt);
2902                         break;
2903                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
2904                         R_Shadow_RenderLighting_Light_Vertex(firstvertex, numvertices, numtriangles, element3i + firsttriangle * 3, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface.texture->basetexture, rsurface.texture->currentskinframe->pants, rsurface.texture->currentskinframe->shirt, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, dopants, doshirt);
2905                         break;
2906                 default:
2907                         Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
2908                         break;
2909                 }
2910         }
2911         else
2912         {
2913                 switch (r_shadow_rendermode)
2914                 {
2915                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2916                         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
2917                         R_Shadow_RenderLighting_VisibleLighting(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, vec3_origin, vec3_origin, rsurface.texture->basetexture, r_texture_black, r_texture_black, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, false, false);
2918                         break;
2919                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2920                         R_Shadow_RenderLighting_Light_GLSL(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, vec3_origin, vec3_origin, rsurface.texture->basetexture, r_texture_black, r_texture_black, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, false, false);
2921                         break;
2922                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2923                         R_Shadow_RenderLighting_Light_Dot3(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, vec3_origin, vec3_origin, rsurface.texture->basetexture, r_texture_black, r_texture_black, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, false, false);
2924                         break;
2925                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
2926                         R_Shadow_RenderLighting_Light_Vertex(firstvertex, numvertices, numtriangles, element3i + firsttriangle * 3, lightcolorbase, vec3_origin, vec3_origin, rsurface.texture->basetexture, r_texture_black, r_texture_black, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, false, false);
2927                         break;
2928                 default:
2929                         Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
2930                         break;
2931                 }
2932         }
2933 }
2934
2935 void R_RTLight_Update(rtlight_t *rtlight, int isstatic, matrix4x4_t *matrix, vec3_t color, int style, const char *cubemapname, int shadow, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
2936 {
2937         matrix4x4_t tempmatrix = *matrix;
2938         Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
2939
2940         // if this light has been compiled before, free the associated data
2941         R_RTLight_Uncompile(rtlight);
2942
2943         // clear it completely to avoid any lingering data
2944         memset(rtlight, 0, sizeof(*rtlight));
2945
2946         // copy the properties
2947         rtlight->matrix_lighttoworld = tempmatrix;
2948         Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &tempmatrix);
2949         Matrix4x4_OriginFromMatrix(&tempmatrix, rtlight->shadoworigin);
2950         rtlight->radius = Matrix4x4_ScaleFromMatrix(&tempmatrix);
2951         VectorCopy(color, rtlight->color);
2952         rtlight->cubemapname[0] = 0;
2953         if (cubemapname && cubemapname[0])
2954                 strlcpy(rtlight->cubemapname, cubemapname, sizeof(rtlight->cubemapname));
2955         rtlight->shadow = shadow;
2956         rtlight->corona = corona;
2957         rtlight->style = style;
2958         rtlight->isstatic = isstatic;
2959         rtlight->coronasizescale = coronasizescale;
2960         rtlight->ambientscale = ambientscale;
2961         rtlight->diffusescale = diffusescale;
2962         rtlight->specularscale = specularscale;
2963         rtlight->flags = flags;
2964
2965         // compute derived data
2966         //rtlight->cullradius = rtlight->radius;
2967         //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
2968         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
2969         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
2970         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
2971         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
2972         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
2973         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
2974 }
2975
2976 // compiles rtlight geometry
2977 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
2978 void R_RTLight_Compile(rtlight_t *rtlight)
2979 {
2980         int i;
2981         int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
2982         int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
2983         entity_render_t *ent = r_refdef.scene.worldentity;
2984         dp_model_t *model = r_refdef.scene.worldmodel;
2985         unsigned char *data;
2986         shadowmesh_t *mesh;
2987
2988         // compile the light
2989         rtlight->compiled = true;
2990         rtlight->static_numleafs = 0;
2991         rtlight->static_numleafpvsbytes = 0;
2992         rtlight->static_leaflist = NULL;
2993         rtlight->static_leafpvs = NULL;
2994         rtlight->static_numsurfaces = 0;
2995         rtlight->static_surfacelist = NULL;
2996         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
2997         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
2998         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
2999         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3000         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3001         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3002
3003         if (model && model->GetLightInfo)
3004         {
3005                 // this variable must be set for the CompileShadowVolume code
3006                 r_shadow_compilingrtlight = rtlight;
3007                 R_Shadow_EnlargeLeafSurfaceTrisBuffer(model->brush.num_leafs, model->num_surfaces, model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles, model->surfmesh.num_triangles);
3008                 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, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs);
3009                 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
3010                 numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
3011                 numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
3012                 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numsurfaces + sizeof(int) * numleafs + numleafpvsbytes + numshadowtrispvsbytes + numlighttrispvsbytes);
3013                 rtlight->static_numsurfaces = numsurfaces;
3014                 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
3015                 rtlight->static_numleafs = numleafs;
3016                 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
3017                 rtlight->static_numleafpvsbytes = numleafpvsbytes;
3018                 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
3019                 rtlight->static_numshadowtrispvsbytes = numshadowtrispvsbytes;
3020                 rtlight->static_shadowtrispvs = (unsigned char *)data;data += numshadowtrispvsbytes;
3021                 rtlight->static_numlighttrispvsbytes = numlighttrispvsbytes;
3022                 rtlight->static_lighttrispvs = (unsigned char *)data;data += numlighttrispvsbytes;
3023                 if (rtlight->static_numsurfaces)
3024                         memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
3025                 if (rtlight->static_numleafs)
3026                         memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
3027                 if (rtlight->static_numleafpvsbytes)
3028                         memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
3029                 if (rtlight->static_numshadowtrispvsbytes)
3030                         memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes);
3031                 if