]> icculus.org git repositories - divverent/darkplaces.git/blob - r_shadow.c
avoid unnecessary texture offset scaling in shadowmap lookups
[divverent/darkplaces.git] / r_shadow.c
1
2 /*
3 Terminology: Stencil Shadow Volume (sometimes called Stencil Shadows)
4 An extrusion of the lit faces, beginning at the original geometry and ending
5 further from the light source than the original geometry (presumably at least
6 as far as the light's radius, if the light has a radius at all), capped at
7 both front and back to avoid any problems (extrusion from dark faces also
8 works but has a different set of problems)
9
10 This is normally rendered using Carmack's Reverse technique, in which
11 backfaces behind zbuffer (zfail) increment the stencil, and frontfaces behind
12 zbuffer (zfail) decrement the stencil, the result is a stencil value of zero
13 where shadows did not intersect the visible geometry, suitable as a stencil
14 mask for rendering lighting everywhere but shadow.
15
16 In our case to hopefully avoid the Creative Labs patent, we draw the backfaces
17 as decrement and the frontfaces as increment, and we redefine the DepthFunc to
18 GL_LESS (the patent uses GL_GEQUAL) which causes zfail when behind surfaces
19 and zpass when infront (the patent draws where zpass with a GL_GEQUAL test),
20 additionally we clear stencil to 128 to avoid the need for the unclamped
21 incr/decr extension (not related to patent).
22
23 Patent warning:
24 This algorithm may be covered by Creative's patent (US Patent #6384822),
25 however that patent is quite specific about increment on backfaces and
26 decrement on frontfaces where zpass with GL_GEQUAL depth test, which is
27 opposite this implementation and partially opposite Carmack's Reverse paper
28 (which uses GL_LESS, but increments on backfaces and decrements on frontfaces).
29
30
31
32 Terminology: Stencil Light Volume (sometimes called Light Volumes)
33 Similar to a Stencil Shadow Volume, but inverted; rather than containing the
34 areas in shadow it contains the areas in light, this can only be built
35 quickly for certain limited cases (such as portal visibility from a point),
36 but is quite useful for some effects (sunlight coming from sky polygons is
37 one possible example, translucent occluders is another example).
38
39
40
41 Terminology: Optimized Stencil Shadow Volume
42 A Stencil Shadow Volume that has been processed sufficiently to ensure it has
43 no duplicate coverage of areas (no need to shadow an area twice), often this
44 greatly improves performance but is an operation too costly to use on moving
45 lights (however completely optimal Stencil Light Volumes can be constructed
46 in some ideal cases).
47
48
49
50 Terminology: Per Pixel Lighting (sometimes abbreviated PPL)
51 Per pixel evaluation of lighting equations, at a bare minimum this involves
52 DOT3 shading of diffuse lighting (per pixel dotproduct of negated incidence
53 vector and surface normal, using a texture of the surface bumps, called a
54 NormalMap) if supported by hardware; in our case there is support for cards
55 which are incapable of DOT3, the quality is quite poor however.  Additionally
56 it is desirable to have specular evaluation per pixel, per vertex
57 normalization of specular halfangle vectors causes noticable distortion but
58 is unavoidable on hardware without GL_ARB_fragment_program or
59 GL_ARB_fragment_shader.
60
61
62
63 Terminology: Normalization CubeMap
64 A cubemap containing normalized dot3-encoded (vectors of length 1 or less
65 encoded as RGB colors) for any possible direction, this technique allows per
66 pixel calculation of incidence vector for per pixel lighting purposes, which
67 would not otherwise be possible per pixel without GL_ARB_fragment_program or
68 GL_ARB_fragment_shader.
69
70
71
72 Terminology: 2D+1D Attenuation Texturing
73 A very crude approximation of light attenuation with distance which results
74 in cylindrical light shapes which fade vertically as a streak (some games
75 such as Doom3 allow this to be rotated to be less noticable in specific
76 cases), the technique is simply modulating lighting by two 2D textures (which
77 can be the same) on different axes of projection (XY and Z, typically), this
78 is the second best technique available without 3D Attenuation Texturing,
79 GL_ARB_fragment_program or GL_ARB_fragment_shader technology.
80
81
82
83 Terminology: 2D+1D Inverse Attenuation Texturing
84 A clever method described in papers on the Abducted engine, this has a squared
85 distance texture (bright on the outside, black in the middle), which is used
86 twice using GL_ADD blending, the result of this is used in an inverse modulate
87 (GL_ONE_MINUS_DST_ALPHA, GL_ZERO) to implement the equation
88 lighting*=(1-((X*X+Y*Y)+(Z*Z))) which is spherical (unlike 2D+1D attenuation
89 texturing).
90
91
92
93 Terminology: 3D Attenuation Texturing
94 A slightly crude approximation of light attenuation with distance, its flaws
95 are limited radius and resolution (performance tradeoffs).
96
97
98
99 Terminology: 3D Attenuation-Normalization Texturing
100 A 3D Attenuation Texture merged with a Normalization CubeMap, by making the
101 vectors shorter the lighting becomes darker, a very effective optimization of
102 diffuse lighting if 3D Attenuation Textures are already used.
103
104
105
106 Terminology: Light Cubemap Filtering
107 A technique for modeling non-uniform light distribution according to
108 direction, for example a lantern may use a cubemap to describe the light
109 emission pattern of the cage around the lantern (as well as soot buildup
110 discoloring the light in certain areas), often also used for softened grate
111 shadows and light shining through a stained glass window (done crudely by
112 texturing the lighting with a cubemap), another good example would be a disco
113 light.  This technique is used heavily in many games (Doom3 does not support
114 this however).
115
116
117
118 Terminology: Light Projection Filtering
119 A technique for modeling shadowing of light passing through translucent
120 surfaces, allowing stained glass windows and other effects to be done more
121 elegantly than possible with Light Cubemap Filtering by applying an occluder
122 texture to the lighting combined with a stencil light volume to limit the lit
123 area, this technique is used by Doom3 for spotlights and flashlights, among
124 other things, this can also be used more generally to render light passing
125 through multiple translucent occluders in a scene (using a light volume to
126 describe the area beyond the occluder, and thus mask off rendering of all
127 other areas).
128
129
130
131 Terminology: Doom3 Lighting
132 A combination of Stencil Shadow Volume, Per Pixel Lighting, Normalization
133 CubeMap, 2D+1D Attenuation Texturing, and Light Projection Filtering, as
134 demonstrated by the game Doom3.
135 */
136
137 #include "quakedef.h"
138 #include "r_shadow.h"
139 #include "cl_collision.h"
140 #include "portals.h"
141 #include "image.h"
142
143 #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_texturescale[2];
175 float r_shadow_shadowmap_parameters[4];
176 int r_shadow_drawbuffer;
177 int r_shadow_readbuffer;
178 GLuint r_shadow_fborectangle;
179 GLuint r_shadow_fbocubeside[R_SHADOW_SHADOWMAP_NUMCUBEMAPS][6];
180 GLuint r_shadow_fbo2d;
181 int r_shadow_shadowmode;
182 int r_shadow_shadowmapfilterquality;
183 int r_shadow_shadowmaptexturetype;
184 int r_shadow_shadowmapmaxsize;
185 qboolean r_shadow_shadowmapvsdct;
186 qboolean r_shadow_shadowmapsampler;
187 int r_shadow_shadowmappcf;
188 int r_shadow_shadowmapborder;
189 int r_shadow_lightscissor[4];
190
191 int maxshadowtriangles;
192 int *shadowelements;
193
194 int maxshadowvertices;
195 float *shadowvertex3f;
196
197 int maxshadowmark;
198 int numshadowmark;
199 int *shadowmark;
200 int *shadowmarklist;
201 int shadowmarkcount;
202
203 int maxvertexupdate;
204 int *vertexupdate;
205 int *vertexremap;
206 int vertexupdatenum;
207
208 int r_shadow_buffer_numleafpvsbytes;
209 unsigned char *r_shadow_buffer_visitingleafpvs;
210 unsigned char *r_shadow_buffer_leafpvs;
211 int *r_shadow_buffer_leaflist;
212
213 int r_shadow_buffer_numsurfacepvsbytes;
214 unsigned char *r_shadow_buffer_surfacepvs;
215 int *r_shadow_buffer_surfacelist;
216
217 int r_shadow_buffer_numshadowtrispvsbytes;
218 unsigned char *r_shadow_buffer_shadowtrispvs;
219 int r_shadow_buffer_numlighttrispvsbytes;
220 unsigned char *r_shadow_buffer_lighttrispvs;
221
222 rtexturepool_t *r_shadow_texturepool;
223 rtexture_t *r_shadow_attenuationgradienttexture;
224 rtexture_t *r_shadow_attenuation2dtexture;
225 rtexture_t *r_shadow_attenuation3dtexture;
226 rtexture_t *r_shadow_lightcorona;
227 rtexture_t *r_shadow_shadowmaprectangletexture;
228 rtexture_t *r_shadow_shadowmap2dtexture;
229 rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
230 rtexture_t *r_shadow_shadowmapvsdcttexture;
231 int r_shadow_shadowmapsize; // changes for each light based on distance
232 int r_shadow_shadowmaplod; // changes for each light based on distance
233
234 // lights are reloaded when this changes
235 char r_shadow_mapname[MAX_QPATH];
236
237 // used only for light filters (cubemaps)
238 rtexturepool_t *r_shadow_filters_texturepool;
239
240 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"};
241 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"};
242 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
243 cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"};
244 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)"};
245 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"};
246 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
247 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
248 cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
249 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
250 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
251 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
252 cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"};
253 cvar_t r_shadow_portallight = {0, "r_shadow_portallight", "1", "use portal culling to exactly determine lit triangles when compiling world lights"};
254 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "1000000", "how far to cast shadows"};
255 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)"};
256 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
257 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
258 cvar_t r_shadow_realtime_dlight_svbspculling = {0, "r_shadow_realtime_dlight_svbspculling", "0", "enables svbsp optimization on dynamic lights (very slow!)"};
259 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal optimization on dynamic lights (slow!)"};
260 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)"};
261 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"};
262 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
263 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
264 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"};
265 cvar_t r_shadow_realtime_world_compilesvbsp = {0, "r_shadow_realtime_world_compilesvbsp", "1", "enables svbsp optimization during compilation"};
266 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation"};
267 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)"};
268 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"};
269 cvar_t r_shadow_shadowmapping_texturetype = {CVAR_SAVE, "r_shadow_shadowmapping_texturetype", "0", "shadowmap texture types: 0 = auto-select, 1 = 2D, 2 = rectangle, 3 = cubemap"};
270 cvar_t r_shadow_shadowmapping_filterquality = {CVAR_SAVE, "r_shadow_shadowmapping_filterquality", "-1", "shadowmap filter modes: -1 = auto-select, 0 = no filtering, 1 = bilinear, 2 = bilinear 2x2 blur (fast), 3 = 3x3 blur (moderate), 4 = 4x4 blur (slow)"};
271 cvar_t r_shadow_shadowmapping_vsdct = {CVAR_SAVE, "r_shadow_shadowmapping_vsdct", "1", "enables use of virtual shadow depth cube texture"};
272 cvar_t r_shadow_shadowmapping_minsize = {CVAR_SAVE, "r_shadow_shadowmapping_minsize", "32", "shadowmap size limit"};
273 cvar_t r_shadow_shadowmapping_maxsize = {CVAR_SAVE, "r_shadow_shadowmapping_maxsize", "512", "shadowmap size limit"};
274 cvar_t r_shadow_shadowmapping_lod_bias = {CVAR_SAVE, "r_shadow_shadowmapping_lod_bias", "16", "shadowmap size bias"};
275 cvar_t r_shadow_shadowmapping_lod_scale = {CVAR_SAVE, "r_shadow_shadowmapping_lod_scale", "128", "shadowmap size scaling parameter"};
276 cvar_t r_shadow_shadowmapping_bordersize = {CVAR_SAVE, "r_shadow_shadowmapping_bordersize", "4", "shadowmap size bias for filtering"};
277 cvar_t r_shadow_shadowmapping_nearclip = {CVAR_SAVE, "r_shadow_shadowmapping_nearclip", "1", "shadowmap nearclip in world units"};
278 cvar_t r_shadow_shadowmapping_bias = {CVAR_SAVE, "r_shadow_shadowmapping_bias", "0.03", "shadowmap bias parameter (this is multiplied by nearclip * 1024 / lodsize)"};
279 cvar_t r_shadow_culltriangles = {0, "r_shadow_culltriangles", "1", "performs more expensive tests to remove unnecessary triangles of lit surfaces"};
280 cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
281 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)"};
282 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)"};
283 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
284 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"};
285 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
286 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
287 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
288 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
289 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
290 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
291 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
292 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
293 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
294 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
295
296 // note the table actually includes one more value, just to avoid the need to clamp the distance index due to minor math error
297 #define ATTENTABLESIZE 256
298 // 1D gradient, 2D circle and 3D sphere attenuation textures
299 #define ATTEN1DSIZE 32
300 #define ATTEN2DSIZE 64
301 #define ATTEN3DSIZE 32
302
303 static float r_shadow_attendividebias; // r_shadow_lightattenuationdividebias
304 static float r_shadow_attenlinearscale; // r_shadow_lightattenuationlinearscale
305 static float r_shadow_attentable[ATTENTABLESIZE+1];
306
307 rtlight_t *r_shadow_compilingrtlight;
308 static memexpandablearray_t r_shadow_worldlightsarray;
309 dlight_t *r_shadow_selectedlight;
310 dlight_t r_shadow_bufferlight;
311 vec3_t r_editlights_cursorlocation;
312
313 extern int con_vislines;
314
315 typedef struct cubemapinfo_s
316 {
317         char basename[64];
318         rtexture_t *texture;
319 }
320 cubemapinfo_t;
321
322 #define MAX_CUBEMAPS 256
323 static int numcubemaps;
324 static cubemapinfo_t cubemaps[MAX_CUBEMAPS];
325
326 void R_Shadow_UncompileWorldLights(void);
327 void R_Shadow_ClearWorldLights(void);
328 void R_Shadow_SaveWorldLights(void);
329 void R_Shadow_LoadWorldLights(void);
330 void R_Shadow_LoadLightsFile(void);
331 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
332 void R_Shadow_EditLights_Reload_f(void);
333 void R_Shadow_ValidateCvars(void);
334 static void R_Shadow_MakeTextures(void);
335
336 // VorteX: custom editor light sprites
337 #define EDLIGHTSPRSIZE                  8
338 cachepic_t *r_editlights_sprcursor;
339 cachepic_t *r_editlights_sprlight;
340 cachepic_t *r_editlights_sprnoshadowlight;
341 cachepic_t *r_editlights_sprcubemaplight;
342 cachepic_t *r_editlights_sprcubemapnoshadowlight;
343 cachepic_t *r_editlights_sprselection;
344
345 void R_Shadow_SetShadowMode(void)
346 {
347         r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, 2048);
348         r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0;
349         r_shadow_shadowmapfilterquality = r_shadow_shadowmapping_filterquality.integer;
350         r_shadow_shadowmaptexturetype = r_shadow_shadowmapping_texturetype.integer;
351         r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
352         r_shadow_shadowmaplod = -1;
353         r_shadow_shadowmapsampler = false;
354         r_shadow_shadowmappcf = 0;
355         r_shadow_shadowmode = 0;
356         if(r_shadow_shadowmapping.integer)
357         {
358                 if(r_shadow_shadowmapfilterquality < 0)
359                 {
360                         if(strstr(gl_vendor, "NVIDIA")) 
361                         {
362                                 r_shadow_shadowmapsampler = gl_support_arb_shadow;
363                                 r_shadow_shadowmappcf = 1;
364                         }
365                         else if(gl_support_amd_texture_texture4 || gl_support_arb_texture_gather) 
366                                 r_shadow_shadowmappcf = 1;
367                         else if(strstr(gl_vendor, "ATI")) 
368                                 r_shadow_shadowmappcf = 1;
369                         else 
370                                 r_shadow_shadowmapsampler = gl_support_arb_shadow;
371                 }
372                 else 
373                 {
374                         switch (r_shadow_shadowmapfilterquality)
375                         {
376                         case 1:
377                                 r_shadow_shadowmapsampler = gl_support_arb_shadow;
378                                 break;
379                         case 2:
380                                 r_shadow_shadowmapsampler = gl_support_arb_shadow;
381                                 r_shadow_shadowmappcf = 1;
382                                 break;
383                         case 3:
384                                 r_shadow_shadowmappcf = 1;
385                                 break;
386                         case 4:
387                                 r_shadow_shadowmappcf = 2;
388                                 break;
389                         }
390                 }
391                 r_shadow_shadowmode = r_shadow_shadowmaptexturetype;
392                 if(r_shadow_shadowmode <= 0)
393                 {
394                         if((gl_support_amd_texture_texture4 || gl_support_arb_texture_gather) && r_shadow_shadowmappcf && !r_shadow_shadowmapsampler)
395                                 r_shadow_shadowmode = 1;
396                         else if(gl_texturerectangle) 
397                                 r_shadow_shadowmode = 2;
398                         else
399                                 r_shadow_shadowmode = 1;
400                 }
401         }
402 }
403
404 void R_Shadow_FreeShadowMaps(void)
405 {
406         int i;
407
408         R_Shadow_SetShadowMode();
409
410         if (r_shadow_fborectangle)
411                 qglDeleteFramebuffersEXT(1, &r_shadow_fborectangle);
412         r_shadow_fborectangle = 0;
413         CHECKGLERROR
414
415         if (r_shadow_fbo2d)
416                 qglDeleteFramebuffersEXT(1, &r_shadow_fbo2d);
417         r_shadow_fbo2d = 0;
418         CHECKGLERROR
419         for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
420                 if (r_shadow_fbocubeside[i][0])
421                         qglDeleteFramebuffersEXT(6, r_shadow_fbocubeside[i]);
422         memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside));
423         CHECKGLERROR
424
425         if (r_shadow_shadowmaprectangletexture)
426                 R_FreeTexture(r_shadow_shadowmaprectangletexture);
427         r_shadow_shadowmaprectangletexture = NULL;
428
429         if (r_shadow_shadowmap2dtexture)
430                 R_FreeTexture(r_shadow_shadowmap2dtexture);
431         r_shadow_shadowmap2dtexture = NULL;
432
433         for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
434                 if (r_shadow_shadowmapcubetexture[i])
435                         R_FreeTexture(r_shadow_shadowmapcubetexture[i]);
436         memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
437
438         if (r_shadow_shadowmapvsdcttexture)
439                 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
440         r_shadow_shadowmapvsdcttexture = NULL;
441
442         CHECKGLERROR
443 }
444
445 void r_shadow_start(void)
446 {
447         // allocate vertex processing arrays
448         numcubemaps = 0;
449         r_shadow_attenuationgradienttexture = NULL;
450         r_shadow_attenuation2dtexture = NULL;
451         r_shadow_attenuation3dtexture = NULL;
452         r_shadow_shadowmode = 0;
453         r_shadow_shadowmaprectangletexture = NULL;
454         r_shadow_shadowmap2dtexture = NULL;
455         memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
456         r_shadow_shadowmapvsdcttexture = NULL;
457         r_shadow_shadowmapmaxsize = 0;
458         r_shadow_shadowmapsize = 0;
459         r_shadow_shadowmaplod = 0;
460         r_shadow_shadowmapfilterquality = 0;
461         r_shadow_shadowmaptexturetype = 0;
462         r_shadow_shadowmapvsdct = false;
463         r_shadow_shadowmapsampler = false;
464         r_shadow_shadowmappcf = 0;
465         r_shadow_fborectangle = 0;
466         r_shadow_fbo2d = 0;
467         memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside));
468
469         R_Shadow_FreeShadowMaps();
470
471         r_shadow_texturepool = NULL;
472         r_shadow_filters_texturepool = NULL;
473         R_Shadow_ValidateCvars();
474         R_Shadow_MakeTextures();
475         maxshadowtriangles = 0;
476         shadowelements = NULL;
477         maxshadowvertices = 0;
478         shadowvertex3f = NULL;
479         maxvertexupdate = 0;
480         vertexupdate = NULL;
481         vertexremap = NULL;
482         vertexupdatenum = 0;
483         maxshadowmark = 0;
484         numshadowmark = 0;
485         shadowmark = NULL;
486         shadowmarklist = NULL;
487         shadowmarkcount = 0;
488         r_shadow_buffer_numleafpvsbytes = 0;
489         r_shadow_buffer_visitingleafpvs = NULL;
490         r_shadow_buffer_leafpvs = NULL;
491         r_shadow_buffer_leaflist = NULL;
492         r_shadow_buffer_numsurfacepvsbytes = 0;
493         r_shadow_buffer_surfacepvs = NULL;
494         r_shadow_buffer_surfacelist = NULL;
495         r_shadow_buffer_numshadowtrispvsbytes = 0;
496         r_shadow_buffer_shadowtrispvs = NULL;
497         r_shadow_buffer_numlighttrispvsbytes = 0;
498         r_shadow_buffer_lighttrispvs = NULL;
499 }
500
501 void r_shadow_shutdown(void)
502 {
503         CHECKGLERROR
504         R_Shadow_UncompileWorldLights();
505
506         R_Shadow_FreeShadowMaps();
507
508         CHECKGLERROR
509         numcubemaps = 0;
510         r_shadow_attenuationgradienttexture = NULL;
511         r_shadow_attenuation2dtexture = NULL;
512         r_shadow_attenuation3dtexture = NULL;
513         R_FreeTexturePool(&r_shadow_texturepool);
514         R_FreeTexturePool(&r_shadow_filters_texturepool);
515         maxshadowtriangles = 0;
516         if (shadowelements)
517                 Mem_Free(shadowelements);
518         shadowelements = NULL;
519         if (shadowvertex3f)
520                 Mem_Free(shadowvertex3f);
521         shadowvertex3f = NULL;
522         maxvertexupdate = 0;
523         if (vertexupdate)
524                 Mem_Free(vertexupdate);
525         vertexupdate = NULL;
526         if (vertexremap)
527                 Mem_Free(vertexremap);
528         vertexremap = NULL;
529         vertexupdatenum = 0;
530         maxshadowmark = 0;
531         numshadowmark = 0;
532         if (shadowmark)
533                 Mem_Free(shadowmark);
534         shadowmark = NULL;
535         if (shadowmarklist)
536                 Mem_Free(shadowmarklist);
537         shadowmarklist = NULL;
538         shadowmarkcount = 0;
539         r_shadow_buffer_numleafpvsbytes = 0;
540         if (r_shadow_buffer_visitingleafpvs)
541                 Mem_Free(r_shadow_buffer_visitingleafpvs);
542         r_shadow_buffer_visitingleafpvs = NULL;
543         if (r_shadow_buffer_leafpvs)
544                 Mem_Free(r_shadow_buffer_leafpvs);
545         r_shadow_buffer_leafpvs = NULL;
546         if (r_shadow_buffer_leaflist)
547                 Mem_Free(r_shadow_buffer_leaflist);
548         r_shadow_buffer_leaflist = NULL;
549         r_shadow_buffer_numsurfacepvsbytes = 0;
550         if (r_shadow_buffer_surfacepvs)
551                 Mem_Free(r_shadow_buffer_surfacepvs);
552         r_shadow_buffer_surfacepvs = NULL;
553         if (r_shadow_buffer_surfacelist)
554                 Mem_Free(r_shadow_buffer_surfacelist);
555         r_shadow_buffer_surfacelist = NULL;
556         r_shadow_buffer_numshadowtrispvsbytes = 0;
557         if (r_shadow_buffer_shadowtrispvs)
558                 Mem_Free(r_shadow_buffer_shadowtrispvs);
559         r_shadow_buffer_numlighttrispvsbytes = 0;
560         if (r_shadow_buffer_lighttrispvs)
561                 Mem_Free(r_shadow_buffer_lighttrispvs);
562 }
563
564 void r_shadow_newmap(void)
565 {
566         if (cl.worldmodel && strncmp(cl.worldmodel->name, r_shadow_mapname, sizeof(r_shadow_mapname)))
567                 R_Shadow_EditLights_Reload_f();
568 }
569
570 void R_Shadow_Help_f(void)
571 {
572         Con_Printf(
573 "Documentation on r_shadow system:\n"
574 "Settings:\n"
575 "r_shadow_bumpscale_basetexture : base texture as bumpmap with this scale\n"
576 "r_shadow_bumpscale_bumpmap : depth scale for bumpmap conversion\n"
577 "r_shadow_debuglight : render only this light number (-1 = all)\n"
578 "r_shadow_gloss 0/1/2 : no gloss, gloss textures only, force gloss\n"
579 "r_shadow_gloss2intensity : brightness of forced gloss\n"
580 "r_shadow_glossintensity : brightness of textured gloss\n"
581 "r_shadow_lightattenuationlinearscale : used to generate attenuation texture\n"
582 "r_shadow_lightattenuationdividebias : used to generate attenuation texture\n"
583 "r_shadow_lightintensityscale : scale rendering brightness of all lights\n"
584 "r_shadow_lightradiusscale : scale rendering radius of all lights\n"
585 "r_shadow_portallight : use portal visibility for static light precomputation\n"
586 "r_shadow_projectdistance : shadow volume projection distance\n"
587 "r_shadow_realtime_dlight : use high quality dynamic lights in normal mode\n"
588 "r_shadow_realtime_dlight_shadows : cast shadows from dlights\n"
589 "r_shadow_realtime_world : use high quality world lighting mode\n"
590 "r_shadow_realtime_world_lightmaps : use lightmaps in addition to lights\n"
591 "r_shadow_realtime_world_shadows : cast shadows from world lights\n"
592 "r_shadow_realtime_world_compile : compile surface/visibility information\n"
593 "r_shadow_realtime_world_compileshadow : compile shadow geometry\n"
594 "r_shadow_scissor : use scissor optimization\n"
595 "r_shadow_polygonfactor : nudge shadow volumes closer/further\n"
596 "r_shadow_polygonoffset : nudge shadow volumes closer/further\n"
597 "r_shadow_texture3d : use 3d attenuation texture (if hardware supports)\n"
598 "r_showlighting : useful for performance testing; bright = slow!\n"
599 "r_showshadowvolumes : useful for performance testing; bright = slow!\n"
600 "Commands:\n"
601 "r_shadow_help : this help\n"
602         );
603 }
604
605 void R_Shadow_Init(void)
606 {
607         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
608         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
609         Cvar_RegisterVariable(&r_shadow_usenormalmap);
610         Cvar_RegisterVariable(&r_shadow_debuglight);
611         Cvar_RegisterVariable(&r_shadow_gloss);
612         Cvar_RegisterVariable(&r_shadow_gloss2intensity);
613         Cvar_RegisterVariable(&r_shadow_glossintensity);
614         Cvar_RegisterVariable(&r_shadow_glossexponent);
615         Cvar_RegisterVariable(&r_shadow_glossexact);
616         Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
617         Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
618         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
619         Cvar_RegisterVariable(&r_shadow_lightradiusscale);
620         Cvar_RegisterVariable(&r_shadow_portallight);
621         Cvar_RegisterVariable(&r_shadow_projectdistance);
622         Cvar_RegisterVariable(&r_shadow_frontsidecasting);
623         Cvar_RegisterVariable(&r_shadow_realtime_dlight);
624         Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
625         Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
626         Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
627         Cvar_RegisterVariable(&r_shadow_realtime_world);
628         Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
629         Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
630         Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
631         Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
632         Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
633         Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
634         Cvar_RegisterVariable(&r_shadow_scissor);
635         Cvar_RegisterVariable(&r_shadow_shadowmapping);
636         Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct);
637         Cvar_RegisterVariable(&r_shadow_shadowmapping_texturetype);
638         Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
639         Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
640         Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
641         Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
642         Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
643         Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
644         Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
645         Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
646         Cvar_RegisterVariable(&r_shadow_culltriangles);
647         Cvar_RegisterVariable(&r_shadow_polygonfactor);
648         Cvar_RegisterVariable(&r_shadow_polygonoffset);
649         Cvar_RegisterVariable(&r_shadow_texture3d);
650         Cvar_RegisterVariable(&r_coronas);
651         Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
652         Cvar_RegisterVariable(&r_coronas_occlusionquery);
653         Cvar_RegisterVariable(&gl_flashblend);
654         Cvar_RegisterVariable(&gl_ext_separatestencil);
655         Cvar_RegisterVariable(&gl_ext_stenciltwoside);
656         if (gamemode == GAME_TENEBRAE)
657         {
658                 Cvar_SetValue("r_shadow_gloss", 2);
659                 Cvar_SetValue("r_shadow_bumpscale_basetexture", 4);
660         }
661         Cmd_AddCommand("r_shadow_help", R_Shadow_Help_f, "prints documentation on console commands and variables used by realtime lighting and shadowing system");
662         R_Shadow_EditLights_Init();
663         Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
664         maxshadowtriangles = 0;
665         shadowelements = NULL;
666         maxshadowvertices = 0;
667         shadowvertex3f = NULL;
668         maxvertexupdate = 0;
669         vertexupdate = NULL;
670         vertexremap = NULL;
671         vertexupdatenum = 0;
672         maxshadowmark = 0;
673         numshadowmark = 0;
674         shadowmark = NULL;
675         shadowmarklist = NULL;
676         shadowmarkcount = 0;
677         r_shadow_buffer_numleafpvsbytes = 0;
678         r_shadow_buffer_visitingleafpvs = NULL;
679         r_shadow_buffer_leafpvs = NULL;
680         r_shadow_buffer_leaflist = NULL;
681         r_shadow_buffer_numsurfacepvsbytes = 0;
682         r_shadow_buffer_surfacepvs = NULL;
683         r_shadow_buffer_surfacelist = NULL;
684         r_shadow_buffer_shadowtrispvs = NULL;
685         r_shadow_buffer_lighttrispvs = NULL;
686         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap);
687 }
688
689 matrix4x4_t matrix_attenuationxyz =
690 {
691         {
692                 {0.5, 0.0, 0.0, 0.5},
693                 {0.0, 0.5, 0.0, 0.5},
694                 {0.0, 0.0, 0.5, 0.5},
695                 {0.0, 0.0, 0.0, 1.0}
696         }
697 };
698
699 matrix4x4_t matrix_attenuationz =
700 {
701         {
702                 {0.0, 0.0, 0.5, 0.5},
703                 {0.0, 0.0, 0.0, 0.5},
704                 {0.0, 0.0, 0.0, 0.5},
705                 {0.0, 0.0, 0.0, 1.0}
706         }
707 };
708
709 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles)
710 {
711         // make sure shadowelements is big enough for this volume
712         if (maxshadowtriangles < numtriangles)
713         {
714                 maxshadowtriangles = numtriangles;
715                 if (shadowelements)
716                         Mem_Free(shadowelements);
717                 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[24]));
718         }
719         // make sure shadowvertex3f is big enough for this volume
720         if (maxshadowvertices < numvertices)
721         {
722                 maxshadowvertices = numvertices;
723                 if (shadowvertex3f)
724                         Mem_Free(shadowvertex3f);
725                 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[6]));
726         }
727 }
728
729 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
730 {
731         int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
732         int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
733         int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
734         int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
735         if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
736         {
737                 if (r_shadow_buffer_visitingleafpvs)
738                         Mem_Free(r_shadow_buffer_visitingleafpvs);
739                 if (r_shadow_buffer_leafpvs)
740                         Mem_Free(r_shadow_buffer_leafpvs);
741                 if (r_shadow_buffer_leaflist)
742                         Mem_Free(r_shadow_buffer_leaflist);
743                 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
744                 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
745                 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
746                 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
747         }
748         if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
749         {
750                 if (r_shadow_buffer_surfacepvs)
751                         Mem_Free(r_shadow_buffer_surfacepvs);
752                 if (r_shadow_buffer_surfacelist)
753                         Mem_Free(r_shadow_buffer_surfacelist);
754                 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
755                 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
756                 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
757         }
758         if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
759         {
760                 if (r_shadow_buffer_shadowtrispvs)
761                         Mem_Free(r_shadow_buffer_shadowtrispvs);
762                 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
763                 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
764         }
765         if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
766         {
767                 if (r_shadow_buffer_lighttrispvs)
768                         Mem_Free(r_shadow_buffer_lighttrispvs);
769                 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
770                 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
771         }
772 }
773
774 void R_Shadow_PrepareShadowMark(int numtris)
775 {
776         // make sure shadowmark is big enough for this volume
777         if (maxshadowmark < numtris)
778         {
779                 maxshadowmark = numtris;
780                 if (shadowmark)
781                         Mem_Free(shadowmark);
782                 if (shadowmarklist)
783                         Mem_Free(shadowmarklist);
784                 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
785                 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
786                 shadowmarkcount = 0;
787         }
788         shadowmarkcount++;
789         // if shadowmarkcount wrapped we clear the array and adjust accordingly
790         if (shadowmarkcount == 0)
791         {
792                 shadowmarkcount = 1;
793                 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
794         }
795         numshadowmark = 0;
796 }
797
798 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)
799 {
800         int i, j;
801         int outtriangles = 0, outvertices = 0;
802         const int *element;
803         const float *vertex;
804         float ratio, direction[3], projectvector[3];
805
806         if (projectdirection)
807                 VectorScale(projectdirection, projectdistance, projectvector);
808         else
809                 VectorClear(projectvector);
810
811         // create the vertices
812         if (projectdirection)
813         {
814                 for (i = 0;i < numshadowmarktris;i++)
815                 {
816                         element = inelement3i + shadowmarktris[i] * 3;
817                         for (j = 0;j < 3;j++)
818                         {
819                                 if (vertexupdate[element[j]] != vertexupdatenum)
820                                 {
821                                         vertexupdate[element[j]] = vertexupdatenum;
822                                         vertexremap[element[j]] = outvertices;
823                                         vertex = invertex3f + element[j] * 3;
824                                         // project one copy of the vertex according to projectvector
825                                         VectorCopy(vertex, outvertex3f);
826                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
827                                         outvertex3f += 6;
828                                         outvertices += 2;
829                                 }
830                         }
831                 }
832         }
833         else
834         {
835                 for (i = 0;i < numshadowmarktris;i++)
836                 {
837                         element = inelement3i + shadowmarktris[i] * 3;
838                         for (j = 0;j < 3;j++)
839                         {
840                                 if (vertexupdate[element[j]] != vertexupdatenum)
841                                 {
842                                         vertexupdate[element[j]] = vertexupdatenum;
843                                         vertexremap[element[j]] = outvertices;
844                                         vertex = invertex3f + element[j] * 3;
845                                         // project one copy of the vertex to the sphere radius of the light
846                                         // (FIXME: would projecting it to the light box be better?)
847                                         VectorSubtract(vertex, projectorigin, direction);
848                                         ratio = projectdistance / VectorLength(direction);
849                                         VectorCopy(vertex, outvertex3f);
850                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
851                                         outvertex3f += 6;
852                                         outvertices += 2;
853                                 }
854                         }
855                 }
856         }
857
858         if (r_shadow_frontsidecasting.integer)
859         {
860                 for (i = 0;i < numshadowmarktris;i++)
861                 {
862                         int remappedelement[3];
863                         int markindex;
864                         const int *neighbortriangle;
865
866                         markindex = shadowmarktris[i] * 3;
867                         element = inelement3i + markindex;
868                         neighbortriangle = inneighbor3i + markindex;
869                         // output the front and back triangles
870                         outelement3i[0] = vertexremap[element[0]];
871                         outelement3i[1] = vertexremap[element[1]];
872                         outelement3i[2] = vertexremap[element[2]];
873                         outelement3i[3] = vertexremap[element[2]] + 1;
874                         outelement3i[4] = vertexremap[element[1]] + 1;
875                         outelement3i[5] = vertexremap[element[0]] + 1;
876
877                         outelement3i += 6;
878                         outtriangles += 2;
879                         // output the sides (facing outward from this triangle)
880                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
881                         {
882                                 remappedelement[0] = vertexremap[element[0]];
883                                 remappedelement[1] = vertexremap[element[1]];
884                                 outelement3i[0] = remappedelement[1];
885                                 outelement3i[1] = remappedelement[0];
886                                 outelement3i[2] = remappedelement[0] + 1;
887                                 outelement3i[3] = remappedelement[1];
888                                 outelement3i[4] = remappedelement[0] + 1;
889                                 outelement3i[5] = remappedelement[1] + 1;
890
891                                 outelement3i += 6;
892                                 outtriangles += 2;
893                         }
894                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
895                         {
896                                 remappedelement[1] = vertexremap[element[1]];
897                                 remappedelement[2] = vertexremap[element[2]];
898                                 outelement3i[0] = remappedelement[2];
899                                 outelement3i[1] = remappedelement[1];
900                                 outelement3i[2] = remappedelement[1] + 1;
901                                 outelement3i[3] = remappedelement[2];
902                                 outelement3i[4] = remappedelement[1] + 1;
903                                 outelement3i[5] = remappedelement[2] + 1;
904
905                                 outelement3i += 6;
906                                 outtriangles += 2;
907                         }
908                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
909                         {
910                                 remappedelement[0] = vertexremap[element[0]];
911                                 remappedelement[2] = vertexremap[element[2]];
912                                 outelement3i[0] = remappedelement[0];
913                                 outelement3i[1] = remappedelement[2];
914                                 outelement3i[2] = remappedelement[2] + 1;
915                                 outelement3i[3] = remappedelement[0];
916                                 outelement3i[4] = remappedelement[2] + 1;
917                                 outelement3i[5] = remappedelement[0] + 1;
918
919                                 outelement3i += 6;
920                                 outtriangles += 2;
921                         }
922                 }
923         }
924         else
925         {
926                 for (i = 0;i < numshadowmarktris;i++)
927                 {
928                         int remappedelement[3];
929                         int markindex;
930                         const int *neighbortriangle;
931
932                         markindex = shadowmarktris[i] * 3;
933                         element = inelement3i + markindex;
934                         neighbortriangle = inneighbor3i + markindex;
935                         // output the front and back triangles
936                         outelement3i[0] = vertexremap[element[2]];
937                         outelement3i[1] = vertexremap[element[1]];
938                         outelement3i[2] = vertexremap[element[0]];
939                         outelement3i[3] = vertexremap[element[0]] + 1;
940                         outelement3i[4] = vertexremap[element[1]] + 1;
941                         outelement3i[5] = vertexremap[element[2]] + 1;
942
943                         outelement3i += 6;
944                         outtriangles += 2;
945                         // output the sides (facing outward from this triangle)
946                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
947                         {
948                                 remappedelement[0] = vertexremap[element[0]];
949                                 remappedelement[1] = vertexremap[element[1]];
950                                 outelement3i[0] = remappedelement[0];
951                                 outelement3i[1] = remappedelement[1];
952                                 outelement3i[2] = remappedelement[1] + 1;
953                                 outelement3i[3] = remappedelement[0];
954                                 outelement3i[4] = remappedelement[1] + 1;
955                                 outelement3i[5] = remappedelement[0] + 1;
956
957                                 outelement3i += 6;
958                                 outtriangles += 2;
959                         }
960                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
961                         {
962                                 remappedelement[1] = vertexremap[element[1]];
963                                 remappedelement[2] = vertexremap[element[2]];
964                                 outelement3i[0] = remappedelement[1];
965                                 outelement3i[1] = remappedelement[2];
966                                 outelement3i[2] = remappedelement[2] + 1;
967                                 outelement3i[3] = remappedelement[1];
968                                 outelement3i[4] = remappedelement[2] + 1;
969                                 outelement3i[5] = remappedelement[1] + 1;
970
971                                 outelement3i += 6;
972                                 outtriangles += 2;
973                         }
974                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
975                         {
976                                 remappedelement[0] = vertexremap[element[0]];
977                                 remappedelement[2] = vertexremap[element[2]];
978                                 outelement3i[0] = remappedelement[2];
979                                 outelement3i[1] = remappedelement[0];
980                                 outelement3i[2] = remappedelement[0] + 1;
981                                 outelement3i[3] = remappedelement[2];
982                                 outelement3i[4] = remappedelement[0] + 1;
983                                 outelement3i[5] = remappedelement[2] + 1;
984
985                                 outelement3i += 6;
986                                 outtriangles += 2;
987                         }
988                 }
989         }
990         if (outnumvertices)
991                 *outnumvertices = outvertices;
992         return outtriangles;
993 }
994
995 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)
996 {
997         int i, j, k;
998         int outtriangles = 0, outvertices = 0;
999         const int *element;
1000         const float *vertex;
1001         float ratio, direction[3], projectvector[3];
1002         qboolean side[4];
1003
1004         if (projectdirection)
1005                 VectorScale(projectdirection, projectdistance, projectvector);
1006         else
1007                 VectorClear(projectvector);
1008
1009         for (i = 0;i < numshadowmarktris;i++)
1010         {
1011                 int remappedelement[3];
1012                 int markindex;
1013                 const int *neighbortriangle;
1014
1015                 markindex = shadowmarktris[i] * 3;
1016                 neighbortriangle = inneighbor3i + markindex;
1017                 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
1018                 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
1019                 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
1020                 if (side[0] + side[1] + side[2] == 0)
1021                         continue;
1022
1023                 side[3] = side[0];
1024                 element = inelement3i + markindex;
1025
1026                 // create the vertices
1027                 for (j = 0;j < 3;j++)
1028                 {
1029                         if (side[j] + side[j+1] == 0)
1030                                 continue;
1031                         k = element[j];
1032                         if (vertexupdate[k] != vertexupdatenum)
1033                         {
1034                                 vertexupdate[k] = vertexupdatenum;
1035                                 vertexremap[k] = outvertices;
1036                                 vertex = invertex3f + k * 3;
1037                                 VectorCopy(vertex, outvertex3f);
1038                                 if (projectdirection)
1039                                 {
1040                                         // project one copy of the vertex according to projectvector
1041                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
1042                                 }
1043                                 else
1044                                 {
1045                                         // project one copy of the vertex to the sphere radius of the light
1046                                         // (FIXME: would projecting it to the light box be better?)
1047                                         VectorSubtract(vertex, projectorigin, direction);
1048                                         ratio = projectdistance / VectorLength(direction);
1049                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1050                                 }
1051                                 outvertex3f += 6;
1052                                 outvertices += 2;
1053                         }
1054                 }
1055
1056                 // output the sides (facing outward from this triangle)
1057                 if (!side[0])
1058                 {
1059                         remappedelement[0] = vertexremap[element[0]];
1060                         remappedelement[1] = vertexremap[element[1]];
1061                         outelement3i[0] = remappedelement[1];
1062                         outelement3i[1] = remappedelement[0];
1063                         outelement3i[2] = remappedelement[0] + 1;
1064                         outelement3i[3] = remappedelement[1];
1065                         outelement3i[4] = remappedelement[0] + 1;
1066                         outelement3i[5] = remappedelement[1] + 1;
1067
1068                         outelement3i += 6;
1069                         outtriangles += 2;
1070                 }
1071                 if (!side[1])
1072                 {
1073                         remappedelement[1] = vertexremap[element[1]];
1074                         remappedelement[2] = vertexremap[element[2]];
1075                         outelement3i[0] = remappedelement[2];
1076                         outelement3i[1] = remappedelement[1];
1077                         outelement3i[2] = remappedelement[1] + 1;
1078                         outelement3i[3] = remappedelement[2];
1079                         outelement3i[4] = remappedelement[1] + 1;
1080                         outelement3i[5] = remappedelement[2] + 1;
1081
1082                         outelement3i += 6;
1083                         outtriangles += 2;
1084                 }
1085                 if (!side[2])
1086                 {
1087                         remappedelement[0] = vertexremap[element[0]];
1088                         remappedelement[2] = vertexremap[element[2]];
1089                         outelement3i[0] = remappedelement[0];
1090                         outelement3i[1] = remappedelement[2];
1091                         outelement3i[2] = remappedelement[2] + 1;
1092                         outelement3i[3] = remappedelement[0];
1093                         outelement3i[4] = remappedelement[2] + 1;
1094                         outelement3i[5] = remappedelement[0] + 1;
1095
1096                         outelement3i += 6;
1097                         outtriangles += 2;
1098                 }
1099         }
1100         if (outnumvertices)
1101                 *outnumvertices = outvertices;
1102         return outtriangles;
1103 }
1104
1105 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)
1106 {
1107         int t, tend;
1108         const int *e;
1109         const float *v[3];
1110         float normal[3];
1111         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1112                 return;
1113         tend = firsttriangle + numtris;
1114         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1115         {
1116                 // surface box entirely inside light box, no box cull
1117                 if (projectdirection)
1118                 {
1119                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1120                         {
1121                                 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1122                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1123                                         shadowmarklist[numshadowmark++] = t;
1124                         }
1125                 }
1126                 else
1127                 {
1128                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1129                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1130                                         shadowmarklist[numshadowmark++] = t;
1131                 }
1132         }
1133         else
1134         {
1135                 // surface box not entirely inside light box, cull each triangle
1136                 if (projectdirection)
1137                 {
1138                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1139                         {
1140                                 v[0] = invertex3f + e[0] * 3;
1141                                 v[1] = invertex3f + e[1] * 3;
1142                                 v[2] = invertex3f + e[2] * 3;
1143                                 TriangleNormal(v[0], v[1], v[2], normal);
1144                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1145                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1146                                         shadowmarklist[numshadowmark++] = t;
1147                         }
1148                 }
1149                 else
1150                 {
1151                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1152                         {
1153                                 v[0] = invertex3f + e[0] * 3;
1154                                 v[1] = invertex3f + e[1] * 3;
1155                                 v[2] = invertex3f + e[2] * 3;
1156                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1157                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1158                                         shadowmarklist[numshadowmark++] = t;
1159                         }
1160                 }
1161         }
1162 }
1163
1164 qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1165 {
1166 #if 1
1167         return false;
1168 #else
1169         if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1170                 return false;
1171         // check if the shadow volume intersects the near plane
1172         //
1173         // a ray between the eye and light origin may intersect the caster,
1174         // indicating that the shadow may touch the eye location, however we must
1175         // test the near plane (a polygon), not merely the eye location, so it is
1176         // easiest to enlarge the caster bounding shape slightly for this.
1177         // TODO
1178         return true;
1179 #endif
1180 }
1181
1182 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)
1183 {
1184         int i, tris, outverts;
1185         if (projectdistance < 0.1)
1186         {
1187                 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1188                 return;
1189         }
1190         if (!numverts || !nummarktris)
1191                 return;
1192         // make sure shadowelements is big enough for this volume
1193         if (maxshadowtriangles < nummarktris || maxshadowvertices < numverts)
1194                 R_Shadow_ResizeShadowArrays((numverts + 255) & ~255, (nummarktris + 255) & ~255);
1195
1196         if (maxvertexupdate < numverts)
1197         {
1198                 maxvertexupdate = numverts;
1199                 if (vertexupdate)
1200                         Mem_Free(vertexupdate);
1201                 if (vertexremap)
1202                         Mem_Free(vertexremap);
1203                 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1204                 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1205                 vertexupdatenum = 0;
1206         }
1207         vertexupdatenum++;
1208         if (vertexupdatenum == 0)
1209         {
1210                 vertexupdatenum = 1;
1211                 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1212                 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1213         }
1214
1215         for (i = 0;i < nummarktris;i++)
1216                 shadowmark[marktris[i]] = shadowmarkcount;
1217
1218         if (r_shadow_compilingrtlight)
1219         {
1220                 // if we're compiling an rtlight, capture the mesh
1221                 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1222                 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1223                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1224                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1225         }
1226         else
1227         {
1228                 // decide which type of shadow to generate and set stencil mode
1229                 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1230                 // generate the sides or a solid volume, depending on type
1231                 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1232                         tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1233                 else
1234                         tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1235                 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1236                 r_refdef.stats.lights_shadowtriangles += tris;
1237                 CHECKGLERROR
1238                 R_Mesh_VertexPointer(shadowvertex3f, 0, 0);
1239                 GL_LockArrays(0, outverts);
1240                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1241                 {
1242                         // increment stencil if frontface is infront of depthbuffer
1243                         GL_CullFace(r_refdef.view.cullface_front);
1244                         qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1245                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1246                         // decrement stencil if backface is infront of depthbuffer
1247                         GL_CullFace(r_refdef.view.cullface_back);
1248                         qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1249                 }
1250                 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1251                 {
1252                         // decrement stencil if backface is behind depthbuffer
1253                         GL_CullFace(r_refdef.view.cullface_front);
1254                         qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1255                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1256                         // increment stencil if frontface is behind depthbuffer
1257                         GL_CullFace(r_refdef.view.cullface_back);
1258                         qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1259                 }
1260                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1261                 GL_LockArrays(0, 0);
1262                 CHECKGLERROR
1263         }
1264 }
1265
1266 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)
1267 {
1268         int i, tris = nummarktris;
1269         int *outelement3i;
1270         const int *element;
1271         if (!numverts || !nummarktris)
1272                 return;
1273         // make sure shadowelements is big enough for this mesh
1274         if (maxshadowtriangles < nummarktris || maxshadowvertices < numverts)
1275                 R_Shadow_ResizeShadowArrays((numverts + 255) & ~255, (nummarktris + 255) & ~255);
1276
1277         // gather up the (sparse) triangles into one array
1278         outelement3i = shadowelements;
1279         for (i = 0;i < nummarktris;i++)
1280         {
1281                 element = elements + marktris[i] * 3;
1282                 outelement3i[0] = element[0];
1283                 outelement3i[1] = element[1];
1284                 outelement3i[2] = element[2];
1285                 outelement3i += 3;
1286         }
1287
1288         r_refdef.stats.lights_dynamicshadowtriangles += tris;
1289         r_refdef.stats.lights_shadowtriangles += tris;
1290         R_Mesh_VertexPointer(vertex3f, vertex3f_bufferobject, vertex3f_bufferoffset);
1291         R_Mesh_Draw(0, numverts, 0, tris, shadowelements, NULL, 0, 0);
1292 }
1293
1294 static void R_Shadow_MakeTextures_MakeCorona(void)
1295 {
1296         float dx, dy;
1297         int x, y, a;
1298         unsigned char pixels[32][32][4];
1299         for (y = 0;y < 32;y++)
1300         {
1301                 dy = (y - 15.5f) * (1.0f / 16.0f);
1302                 for (x = 0;x < 32;x++)
1303                 {
1304                         dx = (x - 15.5f) * (1.0f / 16.0f);
1305                         a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1306                         a = bound(0, a, 255);
1307                         pixels[y][x][0] = a;
1308                         pixels[y][x][1] = a;
1309                         pixels[y][x][2] = a;
1310                         pixels[y][x][3] = 255;
1311                 }
1312         }
1313         r_shadow_lightcorona = R_LoadTexture2D(r_shadow_texturepool, "lightcorona", 32, 32, &pixels[0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR, NULL);
1314 }
1315
1316 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1317 {
1318         float dist = sqrt(x*x+y*y+z*z);
1319         float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1320         // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1321         return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1322 }
1323
1324 static void R_Shadow_MakeTextures(void)
1325 {
1326         int x, y, z;
1327         float intensity, dist;
1328         unsigned int *data;
1329         R_FreeTexturePool(&r_shadow_texturepool);
1330         r_shadow_texturepool = R_AllocTexturePool();
1331         r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1332         r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1333         data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1334         // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1335         for (x = 0;x <= ATTENTABLESIZE;x++)
1336         {
1337                 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1338                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1339                 r_shadow_attentable[x] = bound(0, intensity, 1);
1340         }
1341         // 1D gradient texture
1342         for (x = 0;x < ATTEN1DSIZE;x++)
1343                 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1344         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);
1345         // 2D circle texture
1346         for (y = 0;y < ATTEN2DSIZE;y++)
1347                 for (x = 0;x < ATTEN2DSIZE;x++)
1348                         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);
1349         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);
1350         // 3D sphere texture
1351         if (r_shadow_texture3d.integer && gl_texture3d)
1352         {
1353                 for (z = 0;z < ATTEN3DSIZE;z++)
1354                         for (y = 0;y < ATTEN3DSIZE;y++)
1355                                 for (x = 0;x < ATTEN3DSIZE;x++)
1356                                         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));
1357                 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);
1358         }
1359         else
1360                 r_shadow_attenuation3dtexture = NULL;
1361         Mem_Free(data);
1362
1363         R_Shadow_MakeTextures_MakeCorona();
1364
1365         // Editor light sprites
1366         r_editlights_sprcursor = Draw_CachePic ("gfx/editlights/cursor");
1367         r_editlights_sprlight = Draw_CachePic ("gfx/editlights/light");
1368         r_editlights_sprnoshadowlight = Draw_CachePic ("gfx/editlights/noshadow");
1369         r_editlights_sprcubemaplight = Draw_CachePic ("gfx/editlights/cubemaplight");
1370         r_editlights_sprcubemapnoshadowlight = Draw_CachePic ("gfx/editlights/cubemapnoshadowlight");
1371         r_editlights_sprselection = Draw_CachePic ("gfx/editlights/selection");
1372 }
1373
1374 void R_Shadow_ValidateCvars(void)
1375 {
1376         if (r_shadow_texture3d.integer && !gl_texture3d)
1377                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1378         if (gl_ext_separatestencil.integer && !gl_support_separatestencil)
1379                 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1380         if (gl_ext_stenciltwoside.integer && !gl_support_stenciltwoside)
1381                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1382 }
1383
1384 void R_Shadow_RenderMode_Begin(void)
1385 {
1386         GLint drawbuffer;
1387         GLint readbuffer;
1388         R_Shadow_ValidateCvars();
1389
1390         if (!r_shadow_attenuation2dtexture
1391          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1392          || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1393          || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1394                 R_Shadow_MakeTextures();
1395
1396         CHECKGLERROR
1397         R_Mesh_ColorPointer(NULL, 0, 0);
1398         R_Mesh_ResetTextureState();
1399         GL_BlendFunc(GL_ONE, GL_ZERO);
1400         GL_DepthRange(0, 1);
1401         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1402         GL_DepthTest(true);
1403         GL_DepthMask(false);
1404         GL_Color(0, 0, 0, 1);
1405         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1406
1407         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1408
1409         if (gl_ext_separatestencil.integer)
1410         {
1411                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1412                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1413         }
1414         else if (gl_ext_stenciltwoside.integer)
1415         {
1416                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1417                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1418         }
1419         else
1420         {
1421                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1422                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1423         }
1424
1425         if (r_glsl.integer && gl_support_fragment_shader)
1426                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
1427         else if (gl_dot3arb && gl_texturecubemap && r_textureunits.integer >= 2 && gl_combine.integer && gl_stencil)
1428                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_DOT3;
1429         else
1430                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
1431
1432         CHECKGLERROR
1433         qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
1434         qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
1435         r_shadow_drawbuffer = drawbuffer;
1436         r_shadow_readbuffer = readbuffer;
1437 }
1438
1439 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
1440 {
1441         rsurface.rtlight = rtlight;
1442 }
1443
1444 void R_Shadow_RenderMode_Reset(void)
1445 {
1446         CHECKGLERROR
1447         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE)
1448         {
1449                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1450         }
1451         if (gl_support_ext_framebuffer_object)
1452         {
1453                 qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);CHECKGLERROR
1454         }
1455         qglDrawBuffer(r_shadow_drawbuffer);CHECKGLERROR
1456         qglReadBuffer(r_shadow_readbuffer);CHECKGLERROR
1457         R_SetViewport(&r_refdef.view.viewport);
1458         GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
1459         R_Mesh_ColorPointer(NULL, 0, 0);
1460         R_Mesh_ResetTextureState();
1461         GL_DepthRange(0, 1);
1462         GL_DepthTest(true);
1463         GL_DepthMask(false);
1464         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1465         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
1466         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1467         qglStencilMask(~0);CHECKGLERROR
1468         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
1469         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
1470         GL_CullFace(r_refdef.view.cullface_back);
1471         GL_Color(1, 1, 1, 1);
1472         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
1473         GL_BlendFunc(GL_ONE, GL_ZERO);
1474         R_SetupGenericShader(false);
1475         r_shadow_usingshadowmaprect = false;
1476         r_shadow_usingshadowmapcube = false;
1477         r_shadow_usingshadowmap2d = false;
1478         CHECKGLERROR
1479 }
1480
1481 void R_Shadow_ClearStencil(void)
1482 {
1483         CHECKGLERROR
1484         GL_Clear(GL_STENCIL_BUFFER_BIT);
1485         r_refdef.stats.lights_clears++;
1486 }
1487
1488 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
1489 {
1490         r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
1491         if (r_shadow_rendermode == mode)
1492                 return;
1493         CHECKGLERROR
1494         R_Shadow_RenderMode_Reset();
1495         GL_ColorMask(0, 0, 0, 0);
1496         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
1497         R_SetupDepthOrShadowShader();
1498         qglDepthFunc(GL_LESS);CHECKGLERROR
1499         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1500         r_shadow_rendermode = mode;
1501         switch(mode)
1502         {
1503         default:
1504                 break;
1505         case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
1506                 GL_CullFace(GL_NONE);
1507                 qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1508                 qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1509                 break;
1510         case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
1511                 GL_CullFace(GL_NONE);
1512                 qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1513                 qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1514                 break;
1515         case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
1516                 GL_CullFace(GL_NONE);
1517                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1518                 qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
1519                 qglStencilMask(~0);CHECKGLERROR
1520                 qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1521                 qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
1522                 qglStencilMask(~0);CHECKGLERROR
1523                 qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1524                 break;
1525         case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
1526                 GL_CullFace(GL_NONE);
1527                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1528                 qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
1529                 qglStencilMask(~0);CHECKGLERROR
1530                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1531                 qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
1532                 qglStencilMask(~0);CHECKGLERROR
1533                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1534                 break;
1535         }
1536 }
1537
1538 static void R_Shadow_MakeVSDCT(void)
1539 {
1540         // maps to a 2x3 texture rectangle with normalized coordinates
1541         // +-
1542         // XX
1543         // YY
1544         // ZZ
1545         // stores abs(dir.xy), offset.xy/2.5
1546         unsigned char data[4*6] =
1547         {
1548                 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
1549                 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
1550                 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
1551                 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
1552                 0,   0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
1553                 0,   0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
1554         };
1555         r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_ALWAYSPRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALPHA, NULL); 
1556 }
1557
1558 void R_Shadow_RenderMode_ShadowMap(int side, qboolean clear, int size)
1559 {
1560         int i;
1561         int status;
1562         int maxsize;
1563         float nearclip, farclip, bias;
1564         r_viewport_t viewport;
1565         CHECKGLERROR
1566         maxsize = r_shadow_shadowmapmaxsize;
1567         nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
1568         farclip = 1.0f;
1569         bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
1570         r_shadow_shadowmap_parameters[2] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
1571         r_shadow_shadowmap_parameters[3] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
1572         if (r_shadow_shadowmode == 1)
1573         {
1574                 // complex unrolled cube approach (more flexible)
1575                 if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
1576                         R_Shadow_MakeVSDCT();
1577                 if (!r_shadow_shadowmap2dtexture)
1578                 {
1579 #if 1
1580                         int w = maxsize*2, h = gl_support_arb_texture_non_power_of_two ? maxsize*3 : maxsize*4;
1581                         r_shadow_shadowmap2dtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", w, h, r_shadow_shadowmapsampler);
1582                         qglGenFramebuffersEXT(1, &r_shadow_fbo2d);CHECKGLERROR
1583                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbo2d);CHECKGLERROR
1584                         qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_shadowmap2dtexture), 0);CHECKGLERROR
1585 #endif
1586                 }
1587                 CHECKGLERROR
1588                 R_Shadow_RenderMode_Reset();
1589                 if (r_shadow_shadowmap2dtexture)
1590                 {
1591                         // render depth into the fbo, do not render color at all
1592                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbo2d);CHECKGLERROR
1593                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1594                         qglReadBuffer(GL_NONE);CHECKGLERROR
1595                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1596                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1597                         {
1598                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1599                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1600                         }
1601                         R_SetupDepthOrShadowShader();
1602                 }
1603                 else
1604                 {
1605                         R_SetupShowDepthShader();
1606                         qglClearColor(1,1,1,1);CHECKGLERROR
1607                 }
1608                 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
1609                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
1610                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
1611                 r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
1612                 r_shadow_shadowmap_parameters[1] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
1613                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
1614         }
1615         else if (r_shadow_shadowmode == 2)
1616         {
1617                 // complex unrolled cube approach (more flexible)
1618                 if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
1619                         R_Shadow_MakeVSDCT();
1620                 if (!r_shadow_shadowmaprectangletexture)
1621                 {
1622 #if 1
1623                         r_shadow_shadowmaprectangletexture = R_LoadTextureShadowMapRectangle(r_shadow_texturepool, "shadowmap", maxsize*2, maxsize*3, r_shadow_shadowmapsampler);
1624                         qglGenFramebuffersEXT(1, &r_shadow_fborectangle);CHECKGLERROR
1625                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
1626                         qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_RECTANGLE_ARB, R_GetTexture(r_shadow_shadowmaprectangletexture), 0);CHECKGLERROR
1627 #endif
1628                 }
1629                 CHECKGLERROR
1630                 R_Shadow_RenderMode_Reset();
1631                 if (r_shadow_shadowmaprectangletexture)
1632                 {
1633                         // render depth into the fbo, do not render color at all
1634                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
1635                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1636                         qglReadBuffer(GL_NONE);CHECKGLERROR
1637                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1638                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1639                         {
1640                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1641                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1642                         }
1643                         R_SetupDepthOrShadowShader();
1644                 }
1645                 else
1646                 {
1647                         R_SetupShowDepthShader();
1648                         qglClearColor(1,1,1,1);CHECKGLERROR
1649                 }
1650                 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
1651                 r_shadow_shadowmap_texturescale[0] = 1.0f;
1652                 r_shadow_shadowmap_texturescale[1] = 1.0f;
1653                 r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
1654                 r_shadow_shadowmap_parameters[1] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
1655                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE;
1656         }
1657         else if (r_shadow_shadowmode == 3)
1658         {
1659                 // simple cube approach
1660                 if (!r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod])
1661                 {
1662  #if 1
1663                         r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod] = R_LoadTextureShadowMapCube(r_shadow_texturepool, "shadowmapcube", bound(1, maxsize >> r_shadow_shadowmaplod, 2048), r_shadow_shadowmapsampler);
1664                         qglGenFramebuffersEXT(6, r_shadow_fbocubeside[r_shadow_shadowmaplod]);CHECKGLERROR
1665                         for (i = 0;i < 6;i++)
1666                         {
1667                                 qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbocubeside[r_shadow_shadowmaplod][i]);CHECKGLERROR
1668                                 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
1669                         }
1670  #endif
1671                 }
1672                 CHECKGLERROR
1673                 R_Shadow_RenderMode_Reset();
1674                 if (r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod])
1675                 {
1676                         // render depth into the fbo, do not render color at all
1677                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbocubeside[r_shadow_shadowmaplod][side]);CHECKGLERROR
1678                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1679                         qglReadBuffer(GL_NONE);CHECKGLERROR
1680                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1681                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1682                         {
1683                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1684                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1685                         }
1686                         R_SetupDepthOrShadowShader();
1687                 }
1688                 else
1689                 {
1690                         R_SetupShowDepthShader();
1691                         qglClearColor(1,1,1,1);CHECKGLERROR
1692                 }
1693                 R_Viewport_InitCubeSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, nearclip, farclip, NULL);
1694                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
1695                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureWidth(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
1696                 r_shadow_shadowmap_parameters[0] = 1.0f;
1697                 r_shadow_shadowmap_parameters[1] = 1.0f;
1698                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE;
1699         }
1700         CHECKGLERROR
1701         R_SetViewport(&viewport);
1702         GL_PolygonOffset(0, 0);
1703         GL_CullFace(GL_NONE); // quake is backwards
1704         GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
1705         GL_DepthMask(true);
1706         GL_DepthTest(true);
1707         qglClearDepth(1);CHECKGLERROR
1708         CHECKGLERROR
1709         if (clear)
1710                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |  GL_STENCIL_BUFFER_BIT);
1711         CHECKGLERROR
1712 }
1713
1714 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
1715 {
1716         CHECKGLERROR
1717         R_Shadow_RenderMode_Reset();
1718         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1719         if (!transparent)
1720         {
1721                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
1722         }
1723         if (stenciltest)
1724         {
1725                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1726                 // only draw light where this geometry was already rendered AND the
1727                 // stencil is 128 (values other than this mean shadow)
1728                 qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR
1729         }
1730         r_shadow_rendermode = r_shadow_lightingrendermode;
1731         // do global setup needed for the chosen lighting mode
1732         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
1733         {
1734                 R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap)); // light filter
1735                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
1736                 CHECKGLERROR
1737                 if (shadowmapping)
1738                 {
1739                         if (r_shadow_shadowmode == 1)
1740                         {
1741                                 r_shadow_usingshadowmap2d = true;
1742                                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D, R_GetTexture(r_shadow_shadowmap2dtexture));
1743                                 CHECKGLERROR
1744                         }
1745                         else if (r_shadow_shadowmode == 2)
1746                         {
1747                                 r_shadow_usingshadowmaprect = true;
1748                                 R_Mesh_TexBindRectangle(GL20TU_SHADOWMAPRECT, R_GetTexture(r_shadow_shadowmaprectangletexture));
1749                                 CHECKGLERROR
1750                         }
1751                         else if (r_shadow_shadowmode == 3)
1752                         {
1753                                 r_shadow_usingshadowmapcube = true;
1754                                 R_Mesh_TexBindCubeMap(GL20TU_SHADOWMAPCUBE, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]));
1755                                 CHECKGLERROR
1756                         }
1757
1758                         if (r_shadow_shadowmapvsdct && (r_shadow_usingshadowmap2d || r_shadow_usingshadowmaprect))
1759                         {
1760                                 R_Mesh_TexBindCubeMap(GL20TU_CUBEPROJECTION, R_GetTexture(r_shadow_shadowmapvsdcttexture));
1761                                 CHECKGLERROR
1762                         }
1763                 }
1764         }
1765         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_VERTEX)
1766                 R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
1767         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1768         CHECKGLERROR
1769 }
1770
1771 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
1772 {
1773         CHECKGLERROR
1774         R_Shadow_RenderMode_Reset();
1775         GL_BlendFunc(GL_ONE, GL_ONE);
1776         GL_DepthRange(0, 1);
1777         GL_DepthTest(r_showshadowvolumes.integer < 2);
1778         GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
1779         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
1780         GL_CullFace(GL_NONE);
1781         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
1782 }
1783
1784 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
1785 {
1786         CHECKGLERROR
1787         R_Shadow_RenderMode_Reset();
1788         GL_BlendFunc(GL_ONE, GL_ONE);
1789         GL_DepthRange(0, 1);
1790         GL_DepthTest(r_showlighting.integer < 2);
1791         GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
1792         if (!transparent)
1793         {
1794                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
1795         }
1796         if (stenciltest)
1797         {
1798                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1799                 qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR
1800         }
1801         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
1802 }
1803
1804 void R_Shadow_RenderMode_End(void)
1805 {
1806         CHECKGLERROR
1807         R_Shadow_RenderMode_Reset();
1808         R_Shadow_RenderMode_ActiveLight(NULL);
1809         GL_DepthMask(true);
1810         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1811         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1812 }
1813
1814 int bboxedges[12][2] =
1815 {
1816         // top
1817         {0, 1}, // +X
1818         {0, 2}, // +Y
1819         {1, 3}, // Y, +X
1820         {2, 3}, // X, +Y
1821         // bottom
1822         {4, 5}, // +X
1823         {4, 6}, // +Y
1824         {5, 7}, // Y, +X
1825         {6, 7}, // X, +Y
1826         // verticals
1827         {0, 4}, // +Z
1828         {1, 5}, // X, +Z
1829         {2, 6}, // Y, +Z
1830         {3, 7}, // XY, +Z
1831 };
1832
1833 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
1834 {
1835         int i, ix1, iy1, ix2, iy2;
1836         float x1, y1, x2, y2;
1837         vec4_t v, v2;
1838         float vertex[20][3];
1839         int j, k;
1840         vec4_t plane4f;
1841         int numvertices;
1842         float corner[8][4];
1843         float dist[8];
1844         int sign[8];
1845         float f;
1846
1847         r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
1848         r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
1849         r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
1850         r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
1851
1852         if (!r_shadow_scissor.integer)
1853                 return false;
1854
1855         // if view is inside the light box, just say yes it's visible
1856         if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs))
1857                 return false;
1858
1859         x1 = y1 = x2 = y2 = 0;
1860
1861         // transform all corners that are infront of the nearclip plane
1862         VectorNegate(r_refdef.view.frustum[4].normal, plane4f);
1863         plane4f[3] = r_refdef.view.frustum[4].dist;
1864         numvertices = 0;
1865         for (i = 0;i < 8;i++)
1866         {
1867                 Vector4Set(corner[i], (i & 1) ? maxs[0] : mins[0], (i & 2) ? maxs[1] : mins[1], (i & 4) ? maxs[2] : mins[2], 1);
1868                 dist[i] = DotProduct4(corner[i], plane4f);
1869                 sign[i] = dist[i] > 0;
1870                 if (!sign[i])
1871                 {
1872                         VectorCopy(corner[i], vertex[numvertices]);
1873                         numvertices++;
1874                 }
1875         }
1876         // if some points are behind the nearclip, add clipped edge points to make
1877         // sure that the scissor boundary is complete
1878         if (numvertices > 0 && numvertices < 8)
1879         {
1880                 // add clipped edge points
1881                 for (i = 0;i < 12;i++)
1882                 {
1883                         j = bboxedges[i][0];
1884                         k = bboxedges[i][1];
1885                         if (sign[j] != sign[k])
1886                         {
1887                                 f = dist[j] / (dist[j] - dist[k]);
1888                                 VectorLerp(corner[j], f, corner[k], vertex[numvertices]);
1889                                 numvertices++;
1890                         }
1891                 }
1892         }
1893
1894         // if we have no points to check, the light is behind the view plane
1895         if (!numvertices)
1896                 return true;
1897
1898         // if we have some points to transform, check what screen area is covered
1899         x1 = y1 = x2 = y2 = 0;
1900         v[3] = 1.0f;
1901         //Con_Printf("%i vertices to transform...\n", numvertices);
1902         for (i = 0;i < numvertices;i++)
1903         {
1904                 VectorCopy(vertex[i], v);
1905                 R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2);
1906                 //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]);
1907                 if (i)
1908                 {
1909                         if (x1 > v2[0]) x1 = v2[0];
1910                         if (x2 < v2[0]) x2 = v2[0];
1911                         if (y1 > v2[1]) y1 = v2[1];
1912                         if (y2 < v2[1]) y2 = v2[1];
1913                 }
1914                 else
1915                 {
1916                         x1 = x2 = v2[0];
1917                         y1 = y2 = v2[1];
1918                 }
1919         }
1920
1921         // now convert the scissor rectangle to integer screen coordinates
1922         ix1 = (int)(x1 - 1.0f);
1923         iy1 = vid.height - (int)(y2 - 1.0f);
1924         ix2 = (int)(x2 + 1.0f);
1925         iy2 = vid.height - (int)(y1 + 1.0f);
1926         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
1927
1928         // clamp it to the screen
1929         if (ix1 < r_refdef.view.viewport.x) ix1 = r_refdef.view.viewport.x;
1930         if (iy1 < r_refdef.view.viewport.y) iy1 = r_refdef.view.viewport.y;
1931         if (ix2 > r_refdef.view.viewport.x + r_refdef.view.viewport.width) ix2 = r_refdef.view.viewport.x + r_refdef.view.viewport.width;
1932         if (iy2 > r_refdef.view.viewport.y + r_refdef.view.viewport.height) iy2 = r_refdef.view.viewport.y + r_refdef.view.viewport.height;
1933
1934         // if it is inside out, it's not visible
1935         if (ix2 <= ix1 || iy2 <= iy1)
1936                 return true;
1937
1938         // the light area is visible, set up the scissor rectangle
1939         r_shadow_lightscissor[0] = ix1;
1940         r_shadow_lightscissor[1] = iy1;
1941         r_shadow_lightscissor[2] = ix2 - ix1;
1942         r_shadow_lightscissor[3] = iy2 - iy1;
1943
1944         r_refdef.stats.lights_scissored++;
1945         return false;
1946 }
1947
1948 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, int numtriangles, const int *element3i, const float *diffusecolor, const float *ambientcolor)
1949 {
1950         float *vertex3f = rsurface.vertex3f + 3 * firstvertex;
1951         float *normal3f = rsurface.normal3f + 3 * firstvertex;
1952         float *color4f = rsurface.array_color4f + 4 * firstvertex;
1953         float dist, dot, distintensity, shadeintensity, v[3], n[3];
1954         if (r_textureunits.integer >= 3)
1955         {
1956                 if (VectorLength2(diffusecolor) > 0)
1957                 {
1958                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1959                         {
1960                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
1961                                 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
1962                                 if ((dot = DotProduct(n, v)) < 0)
1963                                 {
1964                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1965                                         VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
1966                                 }
1967                                 else
1968                                         VectorCopy(ambientcolor, color4f);
1969                                 if (r_refdef.fogenabled)
1970                                 {
1971                                         float f;
1972                                         f = FogPoint_Model(vertex3f);
1973                                         VectorScale(color4f, f, color4f);
1974                                 }
1975                                 color4f[3] = 1;
1976                         }
1977                 }
1978                 else
1979                 {
1980                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
1981                         {
1982                                 VectorCopy(ambientcolor, color4f);
1983                                 if (r_refdef.fogenabled)
1984                                 {
1985                                         float f;
1986                                         Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
1987                                         f = FogPoint_Model(vertex3f);
1988                                         VectorScale(color4f, f, color4f);
1989                                 }
1990                                 color4f[3] = 1;
1991                         }
1992                 }
1993         }
1994         else if (r_textureunits.integer >= 2)
1995         {
1996                 if (VectorLength2(diffusecolor) > 0)
1997                 {
1998                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1999                         {
2000                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2001                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
2002                                 {
2003                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
2004                                         if ((dot = DotProduct(n, v)) < 0)
2005                                         {
2006                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
2007                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
2008                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
2009                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
2010                                         }
2011                                         else
2012                                         {
2013                                                 color4f[0] = ambientcolor[0] * distintensity;
2014                                                 color4f[1] = ambientcolor[1] * distintensity;
2015                                                 color4f[2] = ambientcolor[2] * distintensity;
2016                                         }
2017                                         if (r_refdef.fogenabled)
2018                                         {
2019                                                 float f;
2020                                                 f = FogPoint_Model(vertex3f);
2021                                                 VectorScale(color4f, f, color4f);
2022                                         }
2023                                 }
2024                                 else
2025                                         VectorClear(color4f);
2026                                 color4f[3] = 1;
2027                         }
2028                 }
2029                 else
2030                 {
2031                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
2032                         {
2033                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2034                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
2035                                 {
2036                                         color4f[0] = ambientcolor[0] * distintensity;
2037                                         color4f[1] = ambientcolor[1] * distintensity;
2038                                         color4f[2] = ambientcolor[2] * distintensity;
2039                                         if (r_refdef.fogenabled)
2040                                         {
2041                                                 float f;
2042                                                 f = FogPoint_Model(vertex3f);
2043                                                 VectorScale(color4f, f, color4f);
2044                                         }
2045                                 }
2046                                 else
2047                                         VectorClear(color4f);
2048                                 color4f[3] = 1;
2049                         }
2050                 }
2051         }
2052         else
2053         {
2054                 if (VectorLength2(diffusecolor) > 0)
2055                 {
2056                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
2057                         {
2058                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2059                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
2060                                 {
2061                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
2062                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
2063                                         if ((dot = DotProduct(n, v)) < 0)
2064                                         {
2065                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
2066                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
2067                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
2068                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
2069                                         }
2070                                         else
2071                                         {
2072                                                 color4f[0] = ambientcolor[0] * distintensity;
2073                                                 color4f[1] = ambientcolor[1] * distintensity;
2074                                                 color4f[2] = ambientcolor[2] * distintensity;
2075                                         }
2076                                         if (r_refdef.fogenabled)
2077                                         {
2078                                                 float f;
2079                                                 f = FogPoint_Model(vertex3f);
2080                                                 VectorScale(color4f, f, color4f);
2081                                         }
2082                                 }
2083                                 else
2084                                         VectorClear(color4f);
2085                                 color4f[3] = 1;
2086                         }
2087                 }
2088                 else
2089                 {
2090                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
2091                         {
2092                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2093                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
2094                                 {
2095                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
2096                                         color4f[0] = ambientcolor[0] * distintensity;
2097                                         color4f[1] = ambientcolor[1] * distintensity;
2098                                         color4f[2] = ambientcolor[2] * distintensity;
2099                                         if (r_refdef.fogenabled)
2100                                         {
2101                                                 float f;
2102                                                 f = FogPoint_Model(vertex3f);
2103                                                 VectorScale(color4f, f, color4f);
2104                                         }
2105                                 }
2106                                 else
2107                                         VectorClear(color4f);
2108                                 color4f[3] = 1;
2109                         }
2110                 }
2111         }
2112 }
2113
2114 // TODO: use glTexGen instead of feeding vertices to texcoordpointer?
2115
2116 static void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(int firstvertex, int numvertices, int numtriangles, const int *element3i)
2117 {
2118         int i;
2119         float       *out3f     = rsurface.array_texcoord3f + 3 * firstvertex;
2120         const float *vertex3f  = rsurface.vertex3f         + 3 * firstvertex;
2121         const float *svector3f = rsurface.svector3f        + 3 * firstvertex;
2122         const float *tvector3f = rsurface.tvector3f        + 3 * firstvertex;
2123         const float *normal3f  = rsurface.normal3f         + 3 * firstvertex;
2124         float lightdir[3];
2125         for (i = 0;i < numvertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
2126         {
2127                 VectorSubtract(rsurface.entitylightorigin, vertex3f, lightdir);
2128                 // the cubemap normalizes this for us
2129                 out3f[0] = DotProduct(svector3f, lightdir);
2130                 out3f[1] = DotProduct(tvector3f, lightdir);
2131                 out3f[2] = DotProduct(normal3f, lightdir);
2132         }
2133 }
2134
2135 static void R_Shadow_GenTexCoords_Specular_NormalCubeMap(int firstvertex, int numvertices, int numtriangles, const int *element3i)
2136 {
2137         int i;
2138         float       *out3f     = rsurface.array_texcoord3f + 3 * firstvertex;
2139         const float *vertex3f  = rsurface.vertex3f         + 3 * firstvertex;
2140         const float *svector3f = rsurface.svector3f        + 3 * firstvertex;
2141         const float *tvector3f = rsurface.tvector3f        + 3 * firstvertex;
2142         const float *normal3f  = rsurface.normal3f         + 3 * firstvertex;
2143         float lightdir[3], eyedir[3], halfdir[3];
2144         for (i = 0;i < numvertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
2145         {
2146                 VectorSubtract(rsurface.entitylightorigin, vertex3f, lightdir);
2147                 VectorNormalize(lightdir);
2148                 VectorSubtract(rsurface.modelorg, vertex3f, eyedir);
2149                 VectorNormalize(eyedir);
2150                 VectorAdd(lightdir, eyedir, halfdir);
2151                 // the cubemap normalizes this for us
2152                 out3f[0] = DotProduct(svector3f, halfdir);
2153                 out3f[1] = DotProduct(tvector3f, halfdir);
2154                 out3f[2] = DotProduct(normal3f, halfdir);
2155         }
2156 }
2157
2158 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)
2159 {
2160         // used to display how many times a surface is lit for level design purposes
2161         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2162 }
2163
2164 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)
2165 {
2166         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
2167         R_SetupSurfaceShader(lightcolorbase, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT);
2168         if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND))
2169                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
2170         else
2171                 R_Mesh_ColorPointer(NULL, 0, 0);
2172         R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
2173         R_Mesh_TexMatrix(1, &rsurface.texture->currentbackgroundtexmatrix);
2174         R_Mesh_TexBind(GL20TU_NORMAL, R_GetTexture(rsurface.texture->currentskinframe->nmap));
2175         R_Mesh_TexBind(GL20TU_COLOR, R_GetTexture(rsurface.texture->basetexture));
2176         R_Mesh_TexBind(GL20TU_GLOSS, R_GetTexture(rsurface.texture->glosstexture));
2177         if (rsurface.texture->backgroundcurrentskinframe)
2178         {
2179                 R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->nmap));
2180                 R_Mesh_TexBind(GL20TU_SECONDARY_COLOR, R_GetTexture(rsurface.texture->backgroundbasetexture));
2181                 R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS, R_GetTexture(rsurface.texture->backgroundglosstexture));
2182                 R_Mesh_TexBind(GL20TU_SECONDARY_GLOW, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->glow));
2183         }
2184         //R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap));
2185         R_Mesh_TexBind(GL20TU_FOGMASK, R_GetTexture(r_texture_fogattenuation));
2186         if(rsurface.texture->colormapping)
2187         {
2188                 R_Mesh_TexBind(GL20TU_PANTS, R_GetTexture(rsurface.texture->currentskinframe->pants));
2189                 R_Mesh_TexBind(GL20TU_SHIRT, R_GetTexture(rsurface.texture->currentskinframe->shirt));
2190         }
2191         R_Mesh_TexBind(GL20TU_ATTENUATION, R_GetTexture(r_shadow_attenuationgradienttexture));
2192         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
2193         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
2194         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
2195         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
2196         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
2197         {
2198                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
2199         }
2200         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2201         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
2202         {
2203                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
2204         }
2205 }
2206
2207 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)
2208 {
2209         // shared final code for all the dot3 layers
2210         int renders;
2211         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2212         for (renders = 0;renders < 64 && (r > 0 || g > 0 || b > 0);renders++, r--, g--, b--)
2213         {
2214                 GL_Color(bound(0, r, 1), bound(0, g, 1), bound(0, b, 1), 1);
2215                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2216         }
2217 }
2218
2219 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)
2220 {
2221         rmeshstate_t m;
2222         // colorscale accounts for how much we multiply the brightness
2223         // during combine.
2224         //
2225         // mult is how many times the final pass of the lighting will be
2226         // performed to get more brightness than otherwise possible.
2227         //
2228         // Limit mult to 64 for sanity sake.
2229         GL_Color(1,1,1,1);
2230         if (r_shadow_texture3d.integer && rsurface.rtlight->currentcubemap != r_texture_whitecube && r_textureunits.integer >= 4)
2231         {
2232                 // 3 3D combine path (Geforce3, Radeon 8500)
2233                 memset(&m, 0, sizeof(m));
2234                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2235                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2236                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2237                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2238                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2239                 m.tex[1] = R_GetTexture(basetexture);
2240                 m.pointer_texcoord[1] = rsurface.texcoordtexture2f;
2241                 m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
2242                 m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
2243                 m.texmatrix[1] = rsurface.texture->currenttexmatrix;
2244                 m.texcubemap[2] = R_GetTexture(rsurface.rtlight->currentcubemap);
2245                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2246                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2247                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2248                 m.texmatrix[2] = rsurface.entitytolight;
2249                 GL_BlendFunc(GL_ONE, GL_ONE);
2250         }
2251         else if (r_shadow_texture3d.integer && rsurface.rtlight->currentcubemap == r_texture_whitecube && r_textureunits.integer >= 2)
2252         {
2253                 // 2 3D combine path (Geforce3, original Radeon)
2254                 memset(&m, 0, sizeof(m));
2255                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2256                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2257                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2258                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2259                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2260                 m.tex[1] = R_GetTexture(basetexture);
2261                 m.pointer_texcoord[1] = rsurface.texcoordtexture2f;
2262                 m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
2263                 m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
2264                 m.texmatrix[1] = rsurface.texture->currenttexmatrix;
2265                 GL_BlendFunc(GL_ONE, GL_ONE);
2266         }
2267         else if (r_textureunits.integer >= 4 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2268         {
2269                 // 4 2D combine path (Geforce3, Radeon 8500)
2270                 memset(&m, 0, sizeof(m));
2271                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2272                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2273                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2274                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2275                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2276                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2277                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2278                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2279                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2280                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2281                 m.tex[2] = R_GetTexture(basetexture);
2282                 m.pointer_texcoord[2] = rsurface.texcoordtexture2f;
2283                 m.pointer_texcoord_bufferobject[2] = rsurface.texcoordtexture2f_bufferobject;
2284                 m.pointer_texcoord_bufferoffset[2] = rsurface.texcoordtexture2f_bufferoffset;
2285                 m.texmatrix[2] = rsurface.texture->currenttexmatrix;
2286                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2287                 {
2288                         m.texcubemap[3] = R_GetTexture(rsurface.rtlight->currentcubemap);
2289                         m.pointer_texcoord3f[3] = rsurface.vertex3f;
2290                         m.pointer_texcoord_bufferobject[3] = rsurface.vertex3f_bufferobject;
2291                         m.pointer_texcoord_bufferoffset[3] = rsurface.vertex3f_bufferoffset;
2292                         m.texmatrix[3] = rsurface.entitytolight;
2293                 }
2294                 GL_BlendFunc(GL_ONE, GL_ONE);
2295         }
2296         else if (r_textureunits.integer >= 3 && rsurface.rtlight->currentcubemap == r_texture_whitecube)
2297         {
2298                 // 3 2D combine path (Geforce3, original Radeon)
2299                 memset(&m, 0, sizeof(m));
2300                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2301                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2302                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2303                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2304                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2305                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2306                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2307                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2308                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2309                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2310                 m.tex[2] = R_GetTexture(basetexture);
2311                 m.pointer_texcoord[2] = rsurface.texcoordtexture2f;
2312                 m.pointer_texcoord_bufferobject[2] = rsurface.texcoordtexture2f_bufferobject;
2313                 m.pointer_texcoord_bufferoffset[2] = rsurface.texcoordtexture2f_bufferoffset;
2314                 m.texmatrix[2] = rsurface.texture->currenttexmatrix;
2315                 GL_BlendFunc(GL_ONE, GL_ONE);
2316         }
2317         else
2318         {
2319                 // 2/2/2 2D combine path (any dot3 card)
2320                 memset(&m, 0, sizeof(m));
2321                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2322                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2323                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2324                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2325                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2326                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2327                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2328                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2329                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2330                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2331                 R_Mesh_TextureState(&m);
2332                 GL_ColorMask(0,0,0,1);
2333                 GL_BlendFunc(GL_ONE, GL_ZERO);
2334                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2335
2336                 // second pass
2337                 memset(&m, 0, sizeof(m));
2338                 m.tex[0] = R_GetTexture(basetexture);
2339                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2340                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2341                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2342                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2343                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2344                 {
2345                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2346                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2347                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2348                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2349                         m.texmatrix[1] = rsurface.entitytolight;
2350                 }
2351                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2352         }
2353         // this final code is shared
2354         R_Mesh_TextureState(&m);
2355         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);
2356 }
2357
2358 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)
2359 {
2360         rmeshstate_t m;
2361         // colorscale accounts for how much we multiply the brightness
2362         // during combine.
2363         //
2364         // mult is how many times the final pass of the lighting will be
2365         // performed to get more brightness than otherwise possible.
2366         //
2367         // Limit mult to 64 for sanity sake.
2368         GL_Color(1,1,1,1);
2369         // generate normalization cubemap texcoords
2370         R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(firstvertex, numvertices, numtriangles, element3i);
2371         if (r_shadow_texture3d.integer && r_textureunits.integer >= 4)
2372         {
2373                 // 3/2 3D combine path (Geforce3, Radeon 8500)
2374                 memset(&m, 0, sizeof(m));
2375                 m.tex[0] = R_GetTexture(normalmaptexture);
2376                 m.texcombinergb[0] = GL_REPLACE;
2377                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2378                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2379                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2380                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2381                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2382                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2383                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2384                 m.pointer_texcoord_bufferobject[1] = 0;
2385                 m.pointer_texcoord_bufferoffset[1] = 0;
2386                 m.tex3d[2] = R_GetTexture(r_shadow_attenuation3dtexture);
2387                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2388                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2389                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2390                 m.texmatrix[2] = rsurface.entitytoattenuationxyz;
2391                 R_Mesh_TextureState(&m);
2392                 GL_ColorMask(0,0,0,1);
2393                 GL_BlendFunc(GL_ONE, GL_ZERO);
2394                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2395
2396                 // second pass
2397                 memset(&m, 0, sizeof(m));
2398                 m.tex[0] = R_GetTexture(basetexture);
2399                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2400                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2401                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2402                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2403                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2404                 {
2405                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2406                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2407                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2408                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2409                         m.texmatrix[1] = rsurface.entitytolight;
2410                 }
2411                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2412         }
2413         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2414         {
2415                 // 1/2/2 3D combine path (original Radeon)
2416                 memset(&m, 0, sizeof(m));
2417                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2418                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2419                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2420                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2421                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2422                 R_Mesh_TextureState(&m);
2423                 GL_ColorMask(0,0,0,1);
2424                 GL_BlendFunc(GL_ONE, GL_ZERO);
2425                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2426
2427                 // second pass
2428                 memset(&m, 0, sizeof(m));
2429                 m.tex[0] = R_GetTexture(normalmaptexture);
2430                 m.texcombinergb[0] = GL_REPLACE;
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                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2436                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2437                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2438                 m.pointer_texcoord_bufferobject[1] = 0;
2439                 m.pointer_texcoord_bufferoffset[1] = 0;
2440                 R_Mesh_TextureState(&m);
2441                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2442                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2443
2444                 // second pass
2445                 memset(&m, 0, sizeof(m));
2446                 m.tex[0] = R_GetTexture(basetexture);
2447                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2448                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2449                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2450                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2451                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2452                 {
2453                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2454                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2455                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2456                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2457                         m.texmatrix[1] = rsurface.entitytolight;
2458                 }
2459                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2460         }
2461         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap == r_texture_whitecube)
2462         {
2463                 // 2/2 3D combine path (original Radeon)
2464                 memset(&m, 0, sizeof(m));
2465                 m.tex[0] = R_GetTexture(normalmaptexture);
2466                 m.texcombinergb[0] = GL_REPLACE;
2467                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2468                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2469                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2470                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2471                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2472                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2473                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2474                 m.pointer_texcoord_bufferobject[1] = 0;
2475                 m.pointer_texcoord_bufferoffset[1] = 0;
2476                 R_Mesh_TextureState(&m);
2477                 GL_ColorMask(0,0,0,1);
2478                 GL_BlendFunc(GL_ONE, 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                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
2489                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2490                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2491                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2492                 m.texmatrix[1] = rsurface.entitytoattenuationxyz;
2493                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2494         }
2495         else if (r_textureunits.integer >= 4)
2496         {
2497                 // 4/2 2D combine path (Geforce3, Radeon 8500)
2498                 memset(&m, 0, sizeof(m));
2499                 m.tex[0] = R_GetTexture(normalmaptexture);
2500                 m.texcombinergb[0] = GL_REPLACE;
2501                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2502                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2503                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2504                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2505                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2506                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2507                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2508                 m.pointer_texcoord_bufferobject[1] = 0;
2509                 m.pointer_texcoord_bufferoffset[1] = 0;
2510                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
2511                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2512                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2513                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2514                 m.texmatrix[2] = rsurface.entitytoattenuationxyz;
2515                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
2516                 m.pointer_texcoord3f[3] = rsurface.vertex3f;
2517                 m.pointer_texcoord_bufferobject[3] = rsurface.vertex3f_bufferobject;
2518                 m.pointer_texcoord_bufferoffset[3] = rsurface.vertex3f_bufferoffset;
2519                 m.texmatrix[3] = rsurface.entitytoattenuationz;
2520                 R_Mesh_TextureState(&m);
2521                 GL_ColorMask(0,0,0,1);
2522                 GL_BlendFunc(GL_ONE, GL_ZERO);
2523                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2524
2525                 // second pass
2526                 memset(&m, 0, sizeof(m));
2527                 m.tex[0] = R_GetTexture(basetexture);
2528                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2529                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2530                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2531                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2532                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2533                 {
2534                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2535                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2536                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2537                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2538                         m.texmatrix[1] = rsurface.entitytolight;
2539                 }
2540                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2541         }
2542         else
2543         {
2544                 // 2/2/2 2D combine path (any dot3 card)
2545                 memset(&m, 0, sizeof(m));
2546                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2547                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2548                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2549                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2550                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2551                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2552                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2553                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2554                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2555                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2556                 R_Mesh_TextureState(&m);
2557                 GL_ColorMask(0,0,0,1);
2558                 GL_BlendFunc(GL_ONE, GL_ZERO);
2559                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2560
2561                 // second pass
2562                 memset(&m, 0, sizeof(m));
2563                 m.tex[0] = R_GetTexture(normalmaptexture);
2564                 m.texcombinergb[0] = GL_REPLACE;
2565                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2566                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2567                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2568                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2569                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2570                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2571                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2572                 m.pointer_texcoord_bufferobject[1] = 0;
2573                 m.pointer_texcoord_bufferoffset[1] = 0;
2574                 R_Mesh_TextureState(&m);
2575                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2576                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2577
2578                 // second pass
2579                 memset(&m, 0, sizeof(m));
2580                 m.tex[0] = R_GetTexture(basetexture);
2581                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2582                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2583                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2584                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2585                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2586                 {
2587                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2588                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2589                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2590                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2591                         m.texmatrix[1] = rsurface.entitytolight;
2592                 }
2593                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2594         }
2595         // this final code is shared
2596         R_Mesh_TextureState(&m);
2597         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);
2598 }
2599
2600 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)
2601 {
2602         float glossexponent;
2603         rmeshstate_t m;
2604         // FIXME: detect blendsquare!
2605         //if (!gl_support_blendsquare)
2606         //      return;
2607         GL_Color(1,1,1,1);
2608         // generate normalization cubemap texcoords
2609         R_Shadow_GenTexCoords_Specular_NormalCubeMap(firstvertex, numvertices, numtriangles, element3i);
2610         if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2611         {
2612                 // 2/0/0/1/2 3D combine blendsquare path
2613                 memset(&m, 0, sizeof(m));
2614                 m.tex[0] = R_GetTexture(normalmaptexture);
2615                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2616                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2617                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2618                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2619                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2620                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2621                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2622                 m.pointer_texcoord_bufferobject[1] = 0;
2623                 m.pointer_texcoord_bufferoffset[1] = 0;
2624                 R_Mesh_TextureState(&m);
2625                 GL_ColorMask(0,0,0,1);
2626                 // this squares the result
2627                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2628                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2629
2630                 // second and third pass
2631                 R_Mesh_ResetTextureState();
2632                 // square alpha in framebuffer a few times to make it shiny
2633                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
2634                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
2635                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2636
2637                 // fourth pass
2638                 memset(&m, 0, sizeof(m));
2639                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2640                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2641                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2642                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2643                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2644                 R_Mesh_TextureState(&m);
2645                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2646                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2647
2648                 // fifth pass
2649                 memset(&m, 0, sizeof(m));
2650                 m.tex[0] = R_GetTexture(glosstexture);
2651                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2652                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2653                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2654                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2655                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2656                 {
2657                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2658                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2659                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2660                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2661                         m.texmatrix[1] = rsurface.entitytolight;
2662                 }
2663                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2664         }
2665         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap == r_texture_whitecube /* && gl_support_blendsquare*/) // FIXME: detect blendsquare!
2666         {
2667                 // 2/0/0/2 3D combine blendsquare path
2668                 memset(&m, 0, sizeof(m));
2669                 m.tex[0] = R_GetTexture(normalmaptexture);
2670                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2671                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2672                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2673                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2674                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2675                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2676                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2677                 m.pointer_texcoord_bufferobject[1] = 0;
2678                 m.pointer_texcoord_bufferoffset[1] = 0;
2679                 R_Mesh_TextureState(&m);
2680                 GL_ColorMask(0,0,0,1);
2681                 // this squares the result
2682                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2683                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2684
2685                 // second and third pass
2686                 R_Mesh_ResetTextureState();
2687                 // square alpha in framebuffer a few times to make it shiny
2688                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
2689                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
2690                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2691
2692                 // fourth pass
2693                 memset(&m, 0, sizeof(m));
2694                 m.tex[0] = R_GetTexture(glosstexture);
2695                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2696                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2697                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2698                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2699                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
2700                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2701                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2702                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2703                 m.texmatrix[1] = rsurface.entitytoattenuationxyz;
2704                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2705         }
2706         else
2707         {
2708                 // 2/0/0/2/2 2D combine blendsquare path
2709                 memset(&m, 0, sizeof(m));
2710                 m.tex[0] = R_GetTexture(normalmaptexture);
2711                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2712                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2713                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2714                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2715                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2716                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2717                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2718                 m.pointer_texcoord_bufferobject[1] = 0;
2719                 m.pointer_texcoord_bufferoffset[1] = 0;
2720                 R_Mesh_TextureState(&m);
2721                 GL_ColorMask(0,0,0,1);
2722                 // this squares the result
2723                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2724                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2725
2726                 // second and third pass
2727                 R_Mesh_ResetTextureState();
2728                 // square alpha in framebuffer a few times to make it shiny
2729                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
2730                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
2731                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2732
2733                 // fourth pass
2734                 memset(&m, 0, sizeof(m));
2735                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2736                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2737                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2738                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2739                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2740                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2741                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2742                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2743                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2744                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2745                 R_Mesh_TextureState(&m);
2746                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2747                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2748
2749                 // fifth pass
2750                 memset(&m, 0, sizeof(m));
2751                 m.tex[0] = R_GetTexture(glosstexture);
2752                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2753                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2754                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2755                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2756                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2757                 {
2758                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2759                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2760                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2761                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2762                         m.texmatrix[1] = rsurface.entitytolight;
2763                 }
2764                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2765         }
2766         // this final code is shared
2767         R_Mesh_TextureState(&m);
2768         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);
2769 }
2770
2771 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)
2772 {
2773         // ARB path (any Geforce, any Radeon)
2774         qboolean doambient = ambientscale > 0;
2775         qboolean dodiffuse = diffusescale > 0;
2776         qboolean dospecular = specularscale > 0;
2777         if (!doambient && !dodiffuse && !dospecular)
2778                 return;
2779         R_Mesh_ColorPointer(NULL, 0, 0);
2780         if (doambient)
2781                 R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, basetexture, ambientscale * r_refdef.view.colorscale);
2782         if (dodiffuse)
2783                 R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, basetexture, normalmaptexture, diffusescale * r_refdef.view.colorscale);
2784         if (dopants)
2785         {
2786                 if (doambient)
2787                         R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorpants, pantstexture, ambientscale * r_refdef.view.colorscale);
2788                 if (dodiffuse)
2789                         R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorpants, pantstexture, normalmaptexture, diffusescale * r_refdef.view.colorscale);
2790         }
2791         if (doshirt)
2792         {
2793                 if (doambient)
2794                         R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorshirt, shirttexture, ambientscale * r_refdef.view.colorscale);
2795                 if (dodiffuse)
2796                         R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorshirt, shirttexture, normalmaptexture, diffusescale * r_refdef.view.colorscale);
2797         }
2798         if (dospecular)
2799                 R_Shadow_RenderLighting_Light_Dot3_SpecularPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, glosstexture, normalmaptexture, specularscale * r_refdef.view.colorscale);
2800 }
2801
2802 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
2803 {
2804         int renders;
2805         int i;
2806         int stop;
2807         int newfirstvertex;
2808         int newlastvertex;
2809         int newnumtriangles;
2810         int *newe;
2811         const int *e;
2812         float *c;
2813         int maxtriangles = 4096;
2814         int newelements[4096*3];
2815         R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, numtriangles, element3i, diffusecolor2, ambientcolor2);
2816         for (renders = 0;renders < 64;renders++)
2817         {
2818                 stop = true;
2819                 newfirstvertex = 0;
2820                 newlastvertex = 0;
2821                 newnumtriangles = 0;
2822                 newe = newelements;
2823                 // due to low fillrate on the cards this vertex lighting path is
2824                 // designed for, we manually cull all triangles that do not
2825                 // contain a lit vertex
2826                 // this builds batches of triangles from multiple surfaces and
2827                 // renders them at once
2828                 for (i = 0, e = element3i;i < numtriangles;i++, e += 3)
2829                 {
2830                         if (VectorLength2(rsurface.array_color4f + e[0] * 4) + VectorLength2(rsurface.array_color4f + e[1] * 4) + VectorLength2(rsurface.array_color4f + e[2] * 4) >= 0.01)
2831                         {
2832                                 if (newnumtriangles)
2833                                 {
2834                                         newfirstvertex = min(newfirstvertex, e[0]);
2835                                         newlastvertex  = max(newlastvertex, e[0]);
2836                                 }
2837                                 else
2838                                 {
2839                                         newfirstvertex = e[0];
2840                                         newlastvertex = e[0];
2841                                 }
2842                                 newfirstvertex = min(newfirstvertex, e[1]);
2843                                 newlastvertex  = max(newlastvertex, e[1]);
2844                                 newfirstvertex = min(newfirstvertex, e[2]);
2845                                 newlastvertex  = max(newlastvertex, e[2]);
2846                                 newe[0] = e[0];
2847                                 newe[1] = e[1];
2848                                 newe[2] = e[2];
2849                                 newnumtriangles++;
2850                                 newe += 3;
2851                                 if (newnumtriangles >= maxtriangles)
2852                                 {
2853                                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, 0);
2854                                         newnumtriangles = 0;
2855                                         newe = newelements;
2856                                         stop = false;
2857                                 }
2858                         }
2859                 }
2860                 if (newnumtriangles >= 1)
2861                 {
2862                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, 0);
2863                         stop = false;
2864                 }
2865                 // if we couldn't find any lit triangles, exit early
2866                 if (stop)
2867                         break;
2868                 // now reduce the intensity for the next overbright pass
2869                 // we have to clamp to 0 here incase the drivers have improper
2870                 // handling of negative colors
2871                 // (some old drivers even have improper handling of >1 color)
2872                 stop = true;
2873                 for (i = 0, c = rsurface.array_color4f + 4 * firstvertex;i < numvertices;i++, c += 4)
2874                 {
2875                         if (c[0] > 1 || c[1] > 1 || c[2] > 1)
2876                         {
2877                                 c[0] = max(0, c[0] - 1);
2878                                 c[1] = max(0, c[1] - 1);
2879                                 c[2] = max(0, c[2] - 1);
2880                                 stop = false;
2881                         }
2882                         else
2883                                 VectorClear(c);
2884                 }
2885                 // another check...
2886                 if (stop)
2887                         break;
2888         }
2889 }
2890
2891 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)
2892 {
2893         // OpenGL 1.1 path (anything)
2894         float ambientcolorbase[3], diffusecolorbase[3];
2895         float ambientcolorpants[3], diffusecolorpants[3];
2896         float ambientcolorshirt[3], diffusecolorshirt[3];
2897         rmeshstate_t m;
2898         VectorScale(lightcolorbase, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorbase);
2899         VectorScale(lightcolorbase, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorbase);
2900         VectorScale(lightcolorpants, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorpants);
2901         VectorScale(lightcolorpants, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorpants);
2902         VectorScale(lightcolorshirt, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorshirt);
2903         VectorScale(lightcolorshirt, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorshirt);
2904         memset(&m, 0, sizeof(m));
2905         m.tex[0] = R_GetTexture(basetexture);
2906         m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2907         m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2908         m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2909         m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2910         if (r_textureunits.integer >= 2)
2911         {
2912                 // voodoo2 or TNT
2913                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2914                 m.texmatrix[1] = rsurface.entitytoattenuationxyz;
2915                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2916                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2917                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2918                 if (r_textureunits.integer >= 3)
2919                 {
2920                         // Voodoo4 or Kyro (or Geforce3/Radeon with gl_combine off)
2921                         m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
2922                         m.texmatrix[2] = rsurface.entitytoattenuationz;
2923                         m.pointer_texcoord3f[2] = rsurface.vertex3f;
2924                         m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2925                         m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2926                 }
2927         }
2928         R_Mesh_TextureState(&m);
2929         //R_Mesh_TexBind(0, R_GetTexture(basetexture));
2930         R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorbase, ambientcolorbase);
2931         if (dopants)
2932         {
2933                 R_Mesh_TexBind(0, R_GetTexture(pantstexture));
2934                 R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorpants, ambientcolorpants);
2935         }
2936         if (doshirt)
2937         {
2938                 R_Mesh_TexBind(0, R_GetTexture(shirttexture));
2939                 R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorshirt, ambientcolorshirt);
2940         }
2941 }
2942
2943 extern cvar_t gl_lightmaps;
2944 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)
2945 {
2946         float ambientscale, diffusescale, specularscale;
2947         vec3_t lightcolorbase, lightcolorpants, lightcolorshirt;
2948         rtexture_t *nmap;
2949         // calculate colors to render this texture with
2950         lightcolorbase[0] = rsurface.rtlight->currentcolor[0] * rsurface.texture->dlightcolor[0];
2951         lightcolorbase[1] = rsurface.rtlight->currentcolor[1] * rsurface.texture->dlightcolor[1];
2952         lightcolorbase[2] = rsurface.rtlight->currentcolor[2] * rsurface.texture->dlightcolor[2];
2953         ambientscale = rsurface.rtlight->ambientscale;
2954         diffusescale = rsurface.rtlight->diffusescale;
2955         specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale;
2956         if (!r_shadow_usenormalmap.integer)
2957         {
2958                 ambientscale += 1.0f * diffusescale;
2959                 diffusescale = 0;
2960                 specularscale = 0;
2961         }
2962         if ((ambientscale + diffusescale) * VectorLength2(lightcolorbase) + specularscale * VectorLength2(lightcolorbase) < (1.0f / 1048576.0f))
2963                 return;
2964         RSurf_SetupDepthAndCulling();
2965         nmap = rsurface.texture->currentskinframe->nmap;
2966         if (gl_lightmaps.integer)
2967                 nmap = r_texture_blanknormalmap;
2968         if (rsurface.texture->colormapping && !gl_lightmaps.integer)
2969         {
2970                 qboolean dopants = rsurface.texture->currentskinframe->pants != NULL && VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f);
2971                 qboolean doshirt = rsurface.texture->currentskinframe->shirt != NULL && VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
2972                 if (dopants)
2973                 {
2974                         lightcolorpants[0] = lightcolorbase[0] * rsurface.colormap_pantscolor[0];
2975                         lightcolorpants[1] = lightcolorbase[1] * rsurface.colormap_pantscolor[1];
2976                         lightcolorpants[2] = lightcolorbase[2] * rsurface.colormap_pantscolor[2];
2977                 }
2978                 else
2979                         VectorClear(lightcolorpants);
2980                 if (doshirt)
2981                 {
2982                         lightcolorshirt[0] = lightcolorbase[0] * rsurface.colormap_shirtcolor[0];
2983                         lightcolorshirt[1] = lightcolorbase[1] * rsurface.colormap_shirtcolor[1];
2984                         lightcolorshirt[2] = lightcolorbase[2] * rsurface.colormap_shirtcolor[2];
2985                 }
2986                 else
2987                         VectorClear(lightcolorshirt);
2988                 switch (r_shadow_rendermode)
2989                 {
2990                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2991                         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
2992                         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);
2993                         break;
2994                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2995                         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);
2996                         break;
2997                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2998                         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);
2999                         break;
3000                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3001                         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);
3002                         break;
3003                 default:
3004                         Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
3005                         break;
3006                 }
3007         }
3008         else
3009         {
3010                 switch (r_shadow_rendermode)
3011                 {
3012                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
3013                         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
3014                         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);
3015                         break;
3016                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
3017                         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);
3018                         break;
3019                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
3020                         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);
3021                         break;
3022                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3023                         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);
3024                         break;
3025                 default:
3026                         Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
3027                         break;
3028                 }
3029         }
3030 }
3031
3032 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)
3033 {
3034         matrix4x4_t tempmatrix = *matrix;
3035         Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
3036
3037         // if this light has been compiled before, free the associated data
3038         R_RTLight_Uncompile(rtlight);
3039
3040         // clear it completely to avoid any lingering data
3041         memset(rtlight, 0, sizeof(*rtlight));
3042
3043         // copy the properties
3044         rtlight->matrix_lighttoworld = tempmatrix;
3045         Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &tempmatrix);
3046         Matrix4x4_OriginFromMatrix(&tempmatrix, rtlight->shadoworigin);
3047         rtlight->radius = Matrix4x4_ScaleFromMatrix(&tempmatrix);
3048         VectorCopy(color, rtlight->color);
3049         rtlight->cubemapname[0] = 0;
3050         if (cubemapname && cubemapname[0])
3051                 strlcpy(rtlight->cubemapname, cubemapname, sizeof(rtlight->cubemapname));
3052         rtlight->shadow = shadow;
3053         rtlight->corona = corona;
3054         rtlight->style = style;
3055         rtlight->isstatic = isstatic;
3056         rtlight->coronasizescale = coronasizescale;
3057         rtlight->ambientscale = ambientscale;
3058         rtlight->diffusescale = diffusescale;
3059         rtlight->specularscale = specularscale;
3060         rtlight->flags = flags;
3061
3062         // compute derived data
3063         //rtlight->cullradius = rtlight->radius;
3064         //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
3065         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3066         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3067         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3068         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3069         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3070         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3071 }
3072
3073 // compiles rtlight geometry
3074 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
3075 void R_RTLight_Compile(rtlight_t *rtlight)
3076 {
3077         int i;
3078         int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
3079         int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
3080         entity_render_t *ent = r_refdef.scene.worldentity;
3081         dp_model_t *model = r_refdef.scene.worldmodel;
3082         unsigned char *data;
3083         shadowmesh_t *mesh;
3084
3085         // compile the light
3086         rtlight->compiled = true;
3087         rtlight->static_numleafs = 0;
3088         rtlight->static_numleafpvsbytes = 0;
3089         rtlight->static_leaflist = NULL;
3090         rtlight->static_leafpvs = NULL;
3091         rtlight->static_numsurfaces = 0;
3092         rtlight->static_surfacelist = NULL;
3093         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3094         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3095         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3096         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3097         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3098         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3099
3100         if (model && model->GetLightInfo)
3101         {
3102                 // this variable must be set for the CompileShadowVolume code
3103                 r_shadow_compilingrtlight = rtlight;
3104                 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);
3105                 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);
3106                 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
3107                 numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
3108                 numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
3109                 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numsurfaces + sizeof(int) * numleafs + numleafpvsbytes + numshadowtrispvsbytes + numlighttrispvsbytes);
3110                 rtlight->static_numsurfaces = numsurfaces;
3111                 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
3112                 rtlight->static_numleafs = numleafs;
3113                 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
3114                 rtlight->static_numleafpvsbytes = numleafpvsbytes;
3115                 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
3116                 rtlight->static_numshadowtrispvsbytes = numshadowtrispvsbytes;
3117                 rtlight->static_shadowtrispvs = (unsigned char *)data;data += numshadowtrispvsbytes;
3118                 rtlight->static_numlighttrispvsbytes = numlighttrispvsbytes;
3119                 rtlight->static_lighttrispvs = (unsigned char *)data;data += numlighttrispvsbytes;
3120                 if (rtlight->static_numsurfaces)
3121                         memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
3122                 if (rtlight->static_numleafs)
3123                         memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
3124                 if (rtlight->static_numleafpvsbytes)
3125                         memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
3126                 if (rtlight->static_numshadowtrispvsbytes)
3127                         memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes);
3128                 if (rtlight->static_numlighttrispvsbytes)
3129                         memcpy(rtlight->static_lighttrispvs, r_shadow_buffer_lighttrispvs, rtlight->static_numlighttrispvsbytes);
3130                 if (model->CompileShadowVolume && rtlight->shadow)
3131                         model->CompileShadowVolume(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3132                 // now we're done compiling the rtlight
3133                 r_shadow_compilingrtlight = NULL;
3134         }
3135
3136
3137         // use smallest available cullradius - box radius or light radius
3138         //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
3139         //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
3140
3141         shadowzpasstris = 0;
3142         if (rtlight->static_meshchain_shadow_zpass)
3143                 for (mesh = rtlight->static_meshchain_shadow_zpass;mesh;mesh = mesh->next)
3144                         shadowzpasstris += mesh->numtriangles;
3145
3146         shadowzfailtris = 0;
3147         if (rtlight->static_meshchain_shadow_zfail)
3148                 for (mesh = rtlight->static_meshchain_shadow_zfail;mesh;mesh = mesh->next)
3149                         shadowzfailtris += mesh->numtriangles;
3150
3151         lighttris = 0;
3152         if (rtlight->static_numlighttrispvsbytes)
3153                 for (i = 0;i < rtlight->static_numlighttrispvsbytes*8;i++)
3154                         if (CHECKPVSBIT(rtlight->static_lighttrispvs, i))
3155                                 lighttris++;
3156
3157         shadowtris = 0;
3158         if (rtlight->static_numlighttrispvsbytes)
3159                 for (i = 0;i < rtlight->static_numshadowtrispvsbytes*8;i++)
3160                         if (CHECKPVSBIT(rtlight->static_shadowtrispvs, i))
3161                                 shadowtris++;
3162
3163         if (developer.integer >= 10)
3164                 Con_Printf("static light built: %f %f %f : %f %f %f box, %i light triangles, %i shadow triangles, %i zpass/%i zfail compiled shadow volume triangles\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], lighttris, shadowtris, shadowzpasstris, shadowzfailtris);
3165 }
3166
3167 void R_RTLight_Uncompile(rtlight_t *rtlight)
3168 {
3169         if (rtlight->compiled)
3170         {
3171                 if (rtlight->static_meshchain_shadow_zpass)
3172                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zpass);
3173                 rtlight->static_meshchain_shadow_zpass = NULL;
3174                 if (rtlight->static_meshchain_shadow_zfail)
3175                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zfail);
3176                 rtlight->static_meshchain_shadow_zfail = NULL;
3177                 // these allocations are grouped
3178                 if (rtlight->static_surfacelist)
3179                         Mem_Free(rtlight->static_surfacelist);
3180                 rtlight->static_numleafs = 0;
3181                 rtlight->static_numleafpvsbytes = 0;
3182                 rtlight->static_leaflist = NULL;
3183                 rtlight->static_leafpvs = NULL;
3184                 rtlight->static_numsurfaces = 0;
3185                 rtlight->static_surfacelist = NULL;
3186                 rtlight->static_numshadowtrispvsbytes = 0;
3187                 rtlight->static_shadowtrispvs = NULL;
3188                 rtlight->static_numlighttrispvsbytes = 0;
3189                 rtlight->static_lighttrispvs = NULL;
3190                 rtlight->compiled = false;
3191         }
3192 }
3193
3194 void R_Shadow_UncompileWorldLights(void)
3195 {
3196         size_t lightindex;
3197         dlight_t *light;
3198         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
3199         for (lightindex = 0;lightindex < range;lightindex++)
3200         {
3201                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3202                 if (!light)
3203                         continue;
3204                 R_RTLight_Uncompile(&light->rtlight);
3205         }
3206 }
3207
3208 void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight)
3209 {
3210         int i, j;
3211         mplane_t plane;
3212         // reset the count of frustum planes
3213         // see rsurface.rtlight_frustumplanes definition for how much this array
3214         // can hold
3215         rsurface.rtlight_numfrustumplanes = 0;
3216
3217         // haven't implemented a culling path for ortho rendering
3218         if (!r_refdef.view.useperspective)
3219         {
3220                 // check if the light is on screen and copy the 4 planes if it is
3221                 for (i = 0;i < 4;i++)
3222                         if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3223                                 break;
3224                 if (i == 4)
3225                         for (i = 0;i < 4;i++)
3226                                 rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = r_refdef.view.frustum[i];
3227                 return;
3228         }
3229
3230 #if 1
3231         // generate a deformed frustum that includes the light origin, this is
3232         // used to cull shadow casting surfaces that can not possibly cast a
3233         // shadow onto the visible light-receiving surfaces, which can be a
3234         // performance gain
3235         //
3236         // if the light origin is onscreen the result will be 4 planes exactly
3237         // if the light origin is offscreen on only one axis the result will
3238         // be exactly 5 planes (split-side case)
3239         // if the light origin is offscreen on two axes the result will be
3240         // exactly 4 planes (stretched corner case)
3241         for (i = 0;i < 4;i++)
3242         {
3243                 // quickly reject standard frustum planes that put the light
3244                 // origin outside the frustum
3245                 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3246                         continue;
3247                 // copy the plane
3248                 rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = r_refdef.view.frustum[i];
3249         }
3250         // if all the standard frustum planes were accepted, the light is onscreen
3251         // otherwise we need to generate some more planes below...
3252         if (rsurface.rtlight_numfrustumplanes < 4)
3253         {
3254                 // at least one of the stock frustum planes failed, so we need to
3255                 // create one or two custom planes to enclose the light origin
3256                 for (i = 0;i < 4;i++)
3257                 {
3258                         // create a plane using the view origin and light origin, and a
3259                         // single point from the frustum corner set
3260                         TriangleNormal(r_refdef.view.origin, r_refdef.view.frustumcorner[i], rtlight->shadoworigin, plane.normal);
3261                         VectorNormalize(plane.normal);
3262                         plane.dist = DotProduct(r_refdef.view.origin, plane.normal);
3263                         // see if this plane is backwards and flip it if so
3264                         for (j = 0;j < 4;j++)
3265                                 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3266                                         break;
3267                         if (j < 4)
3268                         {
3269                                 VectorNegate(plane.normal, plane.normal);
3270                                 plane.dist *= -1;
3271                                 // flipped plane, test again to see if it is now valid
3272                                 for (j = 0;j < 4;j++)
3273                                         if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3274                                                 break;
3275                                 // if the plane is still not valid, then it is dividing the
3276                                 // frustum and has to be rejected
3277                                 if (j < 4)
3278                                         continue;
3279                         }
3280                         // we have created a valid plane, compute extra info
3281                         PlaneClassify(&plane);
3282                         // copy the plane
3283                         rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = plane;
3284 #if 1
3285                         // if we've found 5 frustum planes then we have constructed a
3286                         // proper split-side case and do not need to keep searching for
3287                         // planes to enclose the light origin
3288                         if (rsurface.rtlight_numfrustumplanes == 5)
3289                                 break;
3290 #endif
3291                 }
3292         }
3293 #endif
3294
3295 #if 0
3296         for (i = 0;i < rsurface.rtlight_numfrustumplanes;i++)
3297         {
3298                 plane = rsurface.rtlight_frustumplanes[i];
3299                 Con_Printf("light %p plane #%i %f %f %f : %f (%f %f %f %f %f)\n", rtlight, i, plane.normal[0], plane.normal[1], plane.normal[2], plane.dist, PlaneDiff(r_refdef.view.frustumcorner[0], &plane), PlaneDiff(r_refdef.view.frustumcorner[1], &plane), PlaneDiff(r_refdef.view.frustumcorner[2], &plane), PlaneDiff(r_refdef.view.frustumcorner[3], &plane), PlaneDiff(rtlight->shadoworigin, &plane));
3300         }
3301 #endif
3302
3303 #if 0
3304         // now add the light-space box planes if the light box is rotated, as any
3305         // caster outside the oriented light box is irrelevant (even if it passed
3306         // the worldspace light box, which is axial)
3307         if (rtlight->matrix_lighttoworld.m[0][0] != 1 || rtlight->matrix_lighttoworld.m[1][1] != 1 || rtlight->matrix_lighttoworld.m[2][2] != 1)
3308         {
3309                 for (i = 0;i < 6;i++)
3310                 {
3311                         vec3_t v;
3312                         VectorClear(v);
3313                         v[i >> 1] = (i & 1) ? -1 : 1;
3314                         Matrix4x4_Transform(&rtlight->matrix_lighttoworld, v, plane.normal);
3315                         VectorSubtract(plane.normal, rtlight->shadoworigin, plane.normal);
3316                         plane.dist = VectorNormalizeLength(plane.normal);
3317                         plane.dist += DotProduct(plane.normal, rtlight->shadoworigin);
3318                         rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = plane;
3319                 }
3320         }
3321 #endif
3322
3323 #if 0
3324         // add the world-space reduced box planes
3325         for (i = 0;i < 6;i++)
3326         {
3327                 VectorClear(plane.normal);
3328                 plane.normal[i >> 1] = (i & 1) ? -1 : 1;
3329                 plane.dist = (i & 1) ? -rsurface.rtlight_cullmaxs[i >> 1] : rsurface.rtlight_cullmins[i >> 1];
3330                 rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = plane;
3331         }
3332 #endif
3333
3334 #if 0
3335         {
3336         int j, oldnum;
3337         vec3_t points[8];
3338         vec_t bestdist;
3339         // reduce all plane distances to tightly fit the rtlight cull box, which
3340         // is in worldspace
3341         VectorSet(points[0], rsurface.rtlight_cullmins[0], rsurface.rtlight_cullmins[1], rsurface.rtlight_cullmins[2]);
3342         VectorSet(points[1], rsurface.rtlight_cullmaxs[0], rsurface.rtlight_cullmins[1], rsurface.rtlight_cullmins[2]);
3343         VectorSet(points[2], rsurface.rtlight_cullmins[0], rsurface.rtlight_cullmaxs[1], rsurface.rtlight_cullmins[2]);
3344         VectorSet(points[3], rsurface.rtlight_cullmaxs[0], rsurface.rtlight_cullmaxs[1], rsurface.rtlight_cullmins[2]);
3345         VectorSet(points[4], rsurface.rtlight_cullmins[0], rsurface.rtlight_cullmins[1], rsurface.rtlight_cullmaxs[2]);
3346         VectorSet(points[5], rsurface.rtlight_cullmaxs[0], rsurface.rtlight_cullmins[1], rsurface.rtlight_cullmaxs[2]);
3347         VectorSet(points[6], rsurface.rtlight_cullmins[0], rsurface.rtlight_cullmaxs[1], rsurface.rtlight_cullmaxs[2]);
3348         VectorSet(points[7], rsurface.rtlight_cullmaxs[0], rsurface.rtlight_cullmaxs[1], rsurface.rtlight_cullmaxs[2]);
3349         oldnum = rsurface.rtlight_numfrustumplanes;
3350         rsurface.rtlight_numfrustumplanes = 0;
3351         for (j = 0;j < oldnum;j++)
3352         {
3353                 // find the nearest point on the box to this plane
3354                 bestdist = DotProduct(rsurface.rtlight_frustumplanes[j].normal, points[0]);
3355                 for (i = 1;i < 8;i++)
3356                 {
3357                         dist = DotProduct(rsurface.rtlight_frustumplanes[j].normal, points[i]);
3358                         if (bestdist > dist)
3359                                 bestdist = dist;
3360                 }
3361                 Con_Printf("light %p %splane #%i %f %f %f : %f < %f\n", rtlight, rsurface.rtlight_frustumplanes[j].dist < bestdist + 0.03125 ? "^2" : "^1", j, rsurface.rtlight_frustumplanes[j].normal[0], rsurface.rtlight_frustumplanes[j].normal[1], rsurface.rtlight_frustumplanes[j].normal[2], rsurface.rtlight_frustumplanes[j].dist, bestdist);
3362                 // if the nearest point is near or behind the plane, we want this
3363                 // plane, otherwise the plane is useless as it won't cull anything
3364                 if (rsurface.rtlight_frustumplanes[j].dist < bestdist + 0.03125)
3365                 {
3366                         PlaneClassify(&rsurface.rtlight_frustumplanes[j]);
3367                         rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = rsurface.rtlight_frustumplanes[j];
3368                 }
3369         }
3370         }
3371 #endif
3372 }
3373
3374 void R_Shadow_DrawWorldShadow(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
3375 {
3376         qboolean zpass;
3377         shadowmesh_t *mesh;
3378         int t, tend;
3379         int surfacelistindex;
3380         msurface_t *surface;
3381
3382         RSurf_ActiveWorldEntity();
3383         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D)
3384         {
3385                 if (r_refdef.scene.worldentity->model)
3386                         r_refdef.scene.worldmodel->DrawShadowMap(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs);
3387                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3388                 return;
3389         }
3390
3391         if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3392         {
3393                 CHECKGLERROR
3394                 zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3395                 R_Shadow_RenderMode_StencilShadowVolumes(zpass);
3396                 mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail;
3397                 for (;mesh;mesh = mesh->next)
3398                 {
3399                         r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
3400                         R_Mesh_VertexPointer(mesh->vertex3f, mesh->vbo, mesh->vbooffset_vertex3f);
3401                         GL_LockArrays(0, mesh->numverts);
3402                         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
3403                         {
3404                                 // increment stencil if frontface is infront of depthbuffer
3405                                 GL_CullFace(r_refdef.view.cullface_back);
3406                                 qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
3407                                 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3s, mesh->ebo3i, mesh->ebo3s);
3408                                 // decrement stencil if backface is infront of depthbuffer
3409                                 GL_CullFace(r_refdef.view.cullface_front);
3410                                 qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
3411                         }
3412                         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
3413                         {
3414                                 // decrement stencil if backface is behind depthbuffer
3415                                 GL_CullFace(r_refdef.view.cullface_front);
3416                                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
3417                                 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3s, mesh->ebo3i, mesh->ebo3s);
3418                                 // increment stencil if frontface is behind depthbuffer
3419                                 GL_CullFace(r_refdef.view.cullface_back);
3420                                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
3421                         }
3422                         R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3s, mesh->ebo3i, mesh->ebo3s);
3423                         GL_LockArrays(0, 0);
3424                 }
3425                 CHECKGLERROR
3426         }
3427         else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh && r_shadow_culltriangles.integer)
3428         {
3429                 R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles);
3430                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
3431                 {
3432                         surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[surfacelistindex];
3433                         for (t = surface->num_firstshadowmeshtriangle, tend = t + surface->num_triangles;t < tend;t++)
3434                                 if (CHECKPVSBIT(trispvs, t))
3435                                         shadowmarklist[numshadowmark++] = t;
3436                 }
3437                 R_Shadow_VolumeFromList(r_refdef.scene.worldmodel->brush.shadowmesh->numverts, r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles, r_refdef.scene.worldmodel->brush.shadowmesh->vertex3f, r_refdef.scene.worldmodel->brush.shadowmesh->element3i, r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius + r_refdef.scene.worldmodel->radius*2 + r_shadow_projectdistance.value, numshadowmark, shadowmarklist, r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3438         }
3439         else if (numsurfaces)
3440                 r_refdef.scene.worldmodel->DrawShadowVolume(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs);
3441
3442         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3443 }
3444
3445 void R_Shadow_DrawEntityShadow(entity_render_t *ent)
3446 {
3447         vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
3448         vec_t relativeshadowradius;
3449         RSurf_ActiveModelEntity(ent, false, false);
3450         Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, relativeshadoworigin);
3451         relativeshadowradius = rsurface.rtlight->radius / ent->scale;
3452         relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
3453         relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
3454         relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
3455         relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
3456         relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
3457         relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
3458         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D)
3459                 ent->model->DrawShadowMap(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
3460         else
3461                 ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
3462         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3463 }
3464
3465 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
3466 {
3467         // set up properties for rendering light onto this entity
3468         RSurf_ActiveModelEntity(ent, true, true);
3469         GL_AlphaTest(false);
3470         Matrix4x4_Concat(&rsurface.entitytolight, &rsurface.rtlight->matrix_worldtolight, &ent->matrix);
3471         Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3472         Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3473         Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3474         if (r_shadow_lightingrendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
3475                 R_Mesh_TexMatrix(3, &rsurface.entitytolight);
3476 }
3477
3478 void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
3479 {
3480         if (!r_refdef.scene.worldmodel->DrawLight)
3481                 return;
3482
3483         // set up properties for rendering light onto this entity
3484         RSurf_ActiveWorldEntity();
3485         GL_AlphaTest(false);
3486         rsurface.entitytolight = rsurface.rtlight->matrix_worldtolight;
3487         Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3488         Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3489         VectorCopy(rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3490         if (r_shadow_lightingrendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
3491                 R_Mesh_TexMatrix(3, &rsurface.entitytolight);
3492
3493         r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, trispvs);
3494
3495         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3496 }
3497
3498 void R_Shadow_DrawEntityLight(entity_render_t *ent)
3499 {
3500         dp_model_t *model = ent->model;
3501         if (!model->DrawLight)
3502                 return;
3503
3504         R_Shadow_SetupEntityLight(ent);
3505
3506         model->DrawLight(ent, model->nummodelsurfaces, model->sortedmodelsurfaces, NULL);
3507
3508         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3509 }
3510
3511 /*
3512 {{  0,   0, 0}, "px",  true,  true,  true},
3513 {{  0,  90, 0}, "py", false,  true, false},
3514 {{  0, 180, 0}, "nx", false, false,  true},
3515 {{  0, 270, 0}, "ny",  true, false, false},
3516 {{-90, 180, 0}, "pz", false, false,  true},
3517 {{ 90, 180, 0}, "nz", false, false,  true}
3518 */
3519
3520 static const double shadowviewmat16[6][4][4] =
3521 {
3522         {
3523                 {-1,  0,  0, 0},
3524                 { 0, -1,  0, 0},
3525                 { 0,  0,  1, 0},
3526                 { 0,  0,  0, 1},
3527         },
3528         {
3529                 { 0, -1,  0, 0},
3530                 {-1,  0,  0, 0},
3531                 { 0,  0,  1, 0},
3532                 { 0,  0,  0, 1},
3533         },
3534         {
3535                 {-1,  0,  0, 0},
3536                 { 0, -1,  0, 0},
3537                 { 0,  0,  1, 0},
3538                 { 0,  0,  0, 1},
3539         },
3540         {
3541                 { 0, -1,  0, 0},
3542                 {-1,  0,  0, 0},
3543                 { 0,  0,  1, 0},
3544                 { 0,  0,  0, 1},
3545         },
3546         {
3547                 { 0,  0,  1, 0},
3548                 { 0, -1,  0, 0},
3549                 { 1,  0,  0, 0},
3550                 { 0,  0,  0, 1},
3551         },
3552         {
3553                 { 0,  0, -1, 0},
3554                 { 0, -1,  0, 0},
3555                 {-1,  0,  0, 0},
3556                 { 0,  0,  0, 1},
3557         },
3558 };
3559
3560 void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
3561 {
3562         int i;
3563         float f;
3564         int numleafs, numsurfaces;
3565         int *leaflist, *surfacelist;
3566         unsigned char *leafpvs, *shadowtrispvs, *lighttrispvs;
3567         int numlightentities;
3568         int numlightentities_noselfshadow;
3569         int numshadowentities;
3570         int numshadowentities_noselfshadow;
3571         static entity_render_t *lightentities[MAX_EDICTS];
3572         static entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
3573         static entity_render_t *shadowentities[MAX_EDICTS];
3574         static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
3575         vec3_t nearestpoint;
3576         vec_t distance;
3577         qboolean castshadows;
3578         int lodlinear;
3579
3580         // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
3581         // skip lights that are basically invisible (color 0 0 0)
3582         if (VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f))
3583                 return;
3584
3585         // loading is done before visibility checks because loading should happen
3586         // all at once at the start of a level, not when it stalls gameplay.
3587         // (especially important to benchmarks)
3588         // compile light
3589         if (rtlight->isstatic && !rtlight->compiled && r_shadow_realtime_world_compile.integer)
3590                 R_RTLight_Compile(rtlight);
3591         // load cubemap
3592         rtlight->currentcubemap = rtlight->cubemapname[0] ? R_Shadow_Cubemap(rtlight->cubemapname) : r_texture_whitecube;
3593
3594         // look up the light style value at this time
3595         f = (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
3596         VectorScale(rtlight->color, f, rtlight->currentcolor);
3597         /*
3598         if (rtlight->selected)
3599         {
3600                 f = 2 + sin(realtime * M_PI * 4.0);
3601                 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
3602         }
3603         */
3604
3605         // if lightstyle is currently off, don't draw the light
3606         if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
3607                 return;
3608
3609         // if the light box is offscreen, skip it
3610         if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
3611                 return;
3612
3613         VectorCopy(rtlight->cullmins, rsurface.rtlight_cullmins);
3614         VectorCopy(rtlight->cullmaxs, rsurface.rtlight_cullmaxs);
3615
3616         if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
3617         {
3618                 // compiled light, world available and can receive realtime lighting
3619                 // retrieve leaf information
3620                 numleafs = rtlight->static_numleafs;
3621                 leaflist = rtlight->static_leaflist;
3622                 leafpvs = rtlight->static_leafpvs;
3623                 numsurfaces = rtlight->static_numsurfaces;
3624                 surfacelist = rtlight->static_surfacelist;
3625                 shadowtrispvs = rtlight->static_shadowtrispvs;
3626                 lighttrispvs = rtlight->static_lighttrispvs;
3627         }
3628         else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->GetLightInfo)
3629         {
3630                 // dynamic light, world available and can receive realtime lighting
3631                 // calculate lit surfaces and leafs
3632                 R_Shadow_EnlargeLeafSurfaceTrisBuffer(r_refdef.scene.worldmodel->brush.num_leafs, r_refdef.scene.worldmodel->num_surfaces, r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles, r_refdef.scene.worldmodel->surfmesh.num_triangles);
3633                 r_refdef.scene.worldmodel->GetLightInfo(r_refdef.scene.worldentity, rtlight->shadoworigin, rtlight->radius, rsurface.rtlight_cullmins, rsurface.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);
3634                 leaflist = r_shadow_buffer_leaflist;
3635                 leafpvs = r_shadow_buffer_leafpvs;
3636                 surfacelist = r_shadow_buffer_surfacelist;
3637                 shadowtrispvs = r_shadow_buffer_shadowtrispvs;
3638                 lighttrispvs = r_shadow_buffer_lighttrispvs;
3639                 // if the reduced leaf bounds are offscreen, skip it
3640                 if (R_CullBox(rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs))
3641                         return;
3642         }
3643         else
3644         {
3645                 // no world
3646                 numleafs = 0;
3647                 leaflist = NULL;
3648                 leafpvs = NULL;
3649                 numsurfaces = 0;
3650                 surfacelist = NULL;
3651                 shadowtrispvs = NULL;
3652                 lighttrispvs = NULL;
3653         }
3654         // check if light is illuminating any visible leafs
3655         if (numleafs)
3656         {
3657                 for (i = 0;i < numleafs;i++)
3658                         if (r_refdef.viewcache.world_leafvisible[leaflist[i]])
3659                                 break;
3660                 if (i == numleafs)
3661                         return;
3662         }
3663         // set up a scissor rectangle for this light
3664         if (R_Shadow_ScissorForBBox(rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs))
3665                 return;
3666
3667         R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
3668
3669         // make a list of lit entities and shadow casting entities
3670         numlightentities = 0;
3671         numlightentities_noselfshadow = 0;
3672         numshadowentities = 0;
3673         numshadowentities_noselfshadow = 0;
3674         // add dynamic entities that are lit by the light
3675         if (r_drawentities.integer)
3676         {
3677                 for (i = 0;i < r_refdef.scene.numentities;i++)
3678                 {
3679                         dp_model_t *model;
3680                         entity_render_t *ent = r_refdef.scene.entities[i];
3681                         vec3_t org;
3682                         if (!BoxesOverlap(ent->mins, ent->maxs, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs))
3683                                 continue;
3684                         // skip the object entirely if it is not within the valid
3685                         // shadow-casting region (which includes the lit region)
3686                         if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rsurface.rtlight_numfrustumplanes, rsurface.rtlight_frustumplanes))
3687                                 continue;
3688                         if (!(model = ent->model))
3689                                 continue;
3690                         if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT))
3691                         {
3692                                 // this entity wants to receive light, is visible, and is
3693                                 // inside the light box
3694                                 // TODO: check if the surfaces in the model can receive light
3695                                 // so now check if it's in a leaf seen by the light
3696                                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs))
3697                                         continue;
3698                                 if (ent->flags & RENDER_NOSELFSHADOW)
3699                                         lightentities_noselfshadow[numlightentities_noselfshadow++] = ent;
3700                                 else
3701                                         lightentities[numlightentities++] = ent;
3702                                 // since it is lit, it probably also casts a shadow...
3703                                 // about the VectorDistance2 - light emitting entities should not cast their own shadow
3704                                 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
3705                                 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
3706                                 {
3707                                         // note: exterior models without the RENDER_NOSELFSHADOW
3708                                         // flag still create a RENDER_NOSELFSHADOW shadow but
3709                                         // are lit normally, this means that they are
3710                                         // self-shadowing but do not shadow other
3711                                         // RENDER_NOSELFSHADOW entities such as the gun
3712                                         // (very weird, but keeps the player shadow off the gun)
3713                                         if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
3714                                                 shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
3715                                         else
3716                                                 shadowentities[numshadowentities++] = ent;
3717                                 }
3718                         }
3719                         else if (ent->flags & RENDER_SHADOW)
3720                         {
3721                                 // this entity is not receiving light, but may still need to
3722                                 // cast a shadow...
3723                                 // TODO: check if the surfaces in the model can cast shadow
3724                                 // now check if it is in a leaf seen by the light
3725                                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs))
3726                                         continue;
3727                                 // about the VectorDistance2 - light emitting entities should not cast their own shadow
3728                                 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
3729                                 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
3730                                 {
3731                                         if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
3732                                                 shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
3733                                         else
3734                                                 shadowentities[numshadowentities++] = ent;
3735                                 }
3736                         }
3737                 }
3738         }
3739
3740         // return if there's nothing at all to light
3741         if (!numlightentities && !numsurfaces)
3742                 return;
3743
3744         // don't let sound skip if going slow
3745         if (r_refdef.scene.extraupdate)
3746                 S_ExtraUpdate ();
3747
3748         // make this the active rtlight for rendering purposes
3749         R_Shadow_RenderMode_ActiveLight(rtlight);
3750         // count this light in the r_speeds
3751         r_refdef.stats.lights++;
3752
3753         if (r_showshadowvolumes.integer && r_refdef.view.showdebug && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows))
3754         {
3755                 // optionally draw visible shape of the shadow volumes
3756                 // for performance analysis by level designers
3757                 R_Shadow_RenderMode_VisibleShadowVolumes();
3758                 if (numsurfaces)
3759                         R_Shadow_DrawWorldShadow(numsurfaces, surfacelist, shadowtrispvs);
3760                 for (i = 0;i < numshadowentities;i++)
3761                         R_Shadow_DrawEntityShadow(shadowentities[i]);
3762                 for (i = 0;i < numshadowentities_noselfshadow;i++)
3763                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
3764         }
3765
3766         if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow)
3767         {
3768                 // optionally draw the illuminated areas
3769                 // for performance analysis by level designers
3770                 R_Shadow_RenderMode_VisibleLighting(false, false);
3771                 if (numsurfaces)
3772                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
3773                 for (i = 0;i < numlightentities;i++)
3774                         R_Shadow_DrawEntityLight(lightentities[i]);
3775                 for (i = 0;i < numlightentities_noselfshadow;i++)
3776                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
3777         }
3778
3779         castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
3780
3781         nearestpoint[0] = bound(rtlight->cullmins[0], r_refdef.view.origin[0], rtlight->cullmaxs[0]);
3782         nearestpoint[1] = bound(rtlight->cullmins[1], r_refdef.view.origin[1], rtlight->cullmaxs[1]);
3783         nearestpoint[2] = bound(rtlight->cullmins[2], r_refdef.view.origin[2], rtlight->cullmaxs[2]);
3784         distance = VectorDistance(nearestpoint, r_refdef.view.origin);
3785         lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance));
3786         lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapping_maxsize.integer);
3787
3788         if (castshadows && r_shadow_shadowmode >= 1 && r_shadow_shadowmode <= 3 && r_glsl.integer && gl_support_fragment_shader)
3789         {
3790                 int side;
3791                 int size;
3792
3793                 r_shadow_shadowmaplod = 0;
3794                 for (i = 1;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
3795                         if ((r_shadow_shadowmapping_maxsize.integer >> i) > lodlinear)
3796                                 r_shadow_shadowmaplod = i;
3797
3798                 size = r_shadow_shadowmode == 3 ? r_shadow_shadowmapping_maxsize.integer >> r_shadow_shadowmaplod : lodlinear;
3799                 size = bound(1, size, 2048);
3800
3801                 //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size);
3802
3803                 // render shadow casters into 6 sided depth texture
3804                 for (side = 0;side < 6;side++)
3805                 {
3806                         R_Shadow_RenderMode_ShadowMap(side, true, size);
3807                         if (numsurfaces)
3808                                 R_Shadow_DrawWorldShadow(numsurfaces, surfacelist, shadowtrispvs);
3809                         for (i = 0;i < numshadowentities;i++)
3810                                 R_Shadow_DrawEntityShadow(shadowentities[i]);
3811                 }
3812
3813                 if (numlightentities_noselfshadow)
3814                 {
3815                         // render lighting using the depth texture as shadowmap
3816                         // draw lighting in the unmasked areas
3817                         R_Shadow_RenderMode_Lighting(false, false, true);
3818                         for (i = 0;i < numlightentities_noselfshadow;i++)
3819                                 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
3820                 }
3821
3822                 // render shadow casters into 6 sided depth texture
3823                 for (side = 0;side < 6;side++)
3824                 {
3825                         R_Shadow_RenderMode_ShadowMap(side, false, size);
3826                         for (i = 0;i < numshadowentities_noselfshadow;i++)
3827                                 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
3828                 }
3829
3830                 // render lighting using the depth texture as shadowmap
3831                 // draw lighting in the unmasked areas
3832                 R_Shadow_RenderMode_Lighting(false, false, true);
3833                 // draw lighting in the unmasked areas
3834                 if (numsurfaces)
3835                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
3836                 for (i = 0;i < numlightentities;i++)
3837                         R_Shadow_DrawEntityLight(lightentities[i]);
3838         }
3839         else if (castshadows && gl_stencil)
3840         {
3841                 // draw stencil shadow volumes to mask off pixels that are in shadow
3842                 // so that they won't receive lighting
3843                 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
3844                 R_Shadow_ClearStencil();
3845                 if (numsurfaces)
3846                         R_Shadow_DrawWorldShadow(numsurfaces, surfacelist, shadowtrispvs);
3847                 for (i = 0;i < numshadowentities;i++)
3848                         R_Shadow_DrawEntityShadow(shadowentities[i]);
3849                 if (numlightentities_noselfshadow)
3850                 {
3851                         // draw lighting in the unmasked areas
3852                         R_Shadow_RenderMode_Lighting(true, false, false);
3853                         for (i = 0;i < numlightentities_noselfshadow;i++)
3854                                 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
3855
3856                         // optionally draw the illuminated areas
3857                         // for performance analysis by level designers
3858                         if (r_showlighting.integer && r_refdef.view.showdebug)
3859                         {
3860                                 R_Shadow_RenderMode_VisibleLighting(!r_showdisabledepthtest.integer, false);
3861                                 for (i = 0;i < numlightentities_noselfshadow;i++)
3862                                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
3863                         }
3864                 }
3865                 for (i = 0;i < numshadowentities_noselfshadow;i++)
3866                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
3867
3868                 if (numsurfaces + numlightentities)
3869                 {
3870                         // draw lighting in the unmasked areas
3871                         R_Shadow_RenderMode_Lighting(true, false, false);
3872                         if (numsurfaces)
3873                                 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
3874                         for (i = 0;i < numlightentities;i++)
3875                                 R_Shadow_DrawEntityLight(lightentities[i]);
3876                 }
3877         }
3878         else
3879         {
3880                 if (numsurfaces + numlightentities)
3881                 {
3882                         // draw lighting in the unmasked areas
3883                         R_Shadow_RenderMode_Lighting(false, false, false);
3884                         if (numsurfaces)
3885                                 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
3886                         for (i = 0;i < numlightentities;i++)
3887                                 R_Shadow_DrawEntityLight(lightentities[i]);
3888                         for (i = 0;i < numlightentities_noselfshadow;i++)
3889                                 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
3890                 }
3891         }
3892 }
3893
3894 void R_Shadow_DrawLightSprites(void);
3895 void R_ShadowVolumeLighting(qboolean visible)
3896 {
3897         int flag;
3898         int lnum;
3899         size_t lightindex;
3900         dlight_t *light;
3901         size_t range;
3902
3903         if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, 2048) || 
3904                 (r_shadow_shadowmode != 0) != (r_shadow_shadowmapping.integer != 0) || 
3905                 r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0) || 
3906                 r_shadow_shadowmaptexturetype != r_shadow_shadowmapping_texturetype.integer ||
3907                 r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer || 
3908                 r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16))
3909                 R_Shadow_FreeShadowMaps();
3910
3911         if (r_editlights.integer)
3912                 R_Shadow_DrawLightSprites();
3913
3914         R_Shadow_RenderMode_Begin();
3915
3916         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
3917         if (r_shadow_debuglight.integer >= 0)
3918         {
3919                 lightindex = r_shadow_debuglight.integer;
3920                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3921                 if (light && (light->flags & flag))
3922                         R_DrawRTLight(&light->rtlight, visible);
3923         }
3924         else
3925         {
3926                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
3927                 for (lightindex = 0;lightindex < range;lightindex++)
3928                 {
3929                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3930                         if (light && (light->flags & flag))
3931                                 R_DrawRTLight(&light->rtlight, visible);
3932                 }
3933         }
3934         if (r_refdef.scene.rtdlight)
3935                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
3936                         R_DrawRTLight(r_refdef.scene.lights[lnum], visible);
3937
3938         R_Shadow_RenderMode_End();
3939 }
3940
3941 extern const float r_screenvertex3f[12];
3942 extern void R_SetupView(qboolean allowwaterclippingplane);
3943 extern void R_ResetViewRendering3D(void);
3944 extern void R_ResetViewRendering2D(void);
3945 extern cvar_t r_shadows;
3946 extern cvar_t r_shadows_darken;
3947 extern cvar_t r_shadows_drawafterrtlighting;
3948 extern cvar_t r_shadows_castfrombmodels;
3949 extern cvar_t r_shadows_throwdistance;
3950 extern cvar_t r_shadows_throwdirection;
3951 void R_DrawModelShadows(void)
3952 {
3953         int i;
3954         float relativethrowdistance;
3955         entity_render_t *ent;
3956         vec3_t relativelightorigin;
3957         vec3_t relativelightdirection;
3958         vec3_t relativeshadowmins, relativeshadowmaxs;
3959         vec3_t tmp, shadowdir;
3960
3961         if (!r_drawentities.integer || !gl_stencil)
3962                 return;
3963
3964         CHECKGLERROR
3965         R_ResetViewRendering3D();
3966         //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
3967         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
3968         R_Shadow_RenderMode_Begin();
3969         R_Shadow_RenderMode_ActiveLight(NULL);
3970         r_shadow_lightscissor[0] = r_refdef.view.x;
3971         r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
3972         r_shadow_lightscissor[2] = r_refdef.view.width;
3973         r_shadow_lightscissor[3] = r_refdef.view.height;
3974         R_Shadow_RenderMode_StencilShadowVolumes(false);
3975
3976         // get shadow dir
3977         if (r_shadows.integer == 2)
3978         {
3979                 Math_atov(r_shadows_throwdirection.string, shadowdir);
3980                 VectorNormalize(shadowdir);
3981         }
3982
3983         R_Shadow_ClearStencil();
3984
3985         for (i = 0;i < r_refdef.scene.numentities;i++)
3986         {
3987                 ent = r_refdef.scene.entities[i];
3988
3989                 // cast shadows from anything of the map (submodels are optional)
3990                 if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
3991                 {
3992                         relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
3993                         VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
3994                         VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
3995                         if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
3996                                 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
3997                         else
3998                         {
3999                                 if(ent->entitynumber != 0)
4000                                 {
4001                                         // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
4002                                         int entnum, entnum2, recursion;
4003                                         entnum = entnum2 = ent->entitynumber;
4004                                         for(recursion = 32; recursion > 0; --recursion)
4005                                         {
4006                                                 entnum2 = cl.entities[entnum].state_current.tagentity;
4007                                                 if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
4008                                                         entnum = entnum2;
4009                                                 else
4010                                                         break;
4011                                         }
4012                                         if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
4013                                         {
4014                                                 VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
4015                                                 // transform into modelspace of OUR entity
4016                                                 Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
4017                                                 Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
4018                                         }
4019                                         else
4020                                                 VectorNegate(ent->modellight_lightdir, relativelightdirection);
4021                                 }
4022                                 else
4023                                         VectorNegate(ent->modellight_lightdir, relativelightdirection);
4024                         }
4025
4026                         VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
4027                         RSurf_ActiveModelEntity(ent, false, false);
4028                         ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
4029                         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
4030                 }
4031         }
4032
4033         // not really the right mode, but this will disable any silly stencil features
4034         R_Shadow_RenderMode_End();
4035
4036         // set up ortho view for rendering this pass
4037         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
4038         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
4039         //GL_ScissorTest(true);
4040         //R_Mesh_Matrix(&identitymatrix);
4041         //R_Mesh_ResetTextureState();
4042         R_ResetViewRendering2D();
4043         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
4044         R_Mesh_ColorPointer(NULL, 0, 0);
4045         R_SetupGenericShader(false);
4046
4047         // set up a darkening blend on shadowed areas
4048         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4049         //GL_DepthRange(0, 1);
4050         //GL_DepthTest(false);
4051         //GL_DepthMask(false);
4052         //GL_PolygonOffset(0, 0);CHECKGLERROR
4053         GL_Color(0, 0, 0, r_shadows_darken.value);
4054         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
4055         //qglDepthFunc(GL_ALWAYS);CHECKGLERROR
4056         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
4057         qglStencilMask(~0);CHECKGLERROR
4058         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
4059         qglStencilFunc(GL_NOTEQUAL, 128, ~0);CHECKGLERROR
4060
4061         // apply the blend to the shadowed areas
4062         R_Mesh_Draw(0, 4, 0, 2, NULL, polygonelements, 0, 0);
4063
4064         // restore the viewport
4065         R_SetViewport(&r_refdef.view.viewport);
4066
4067         // restore other state to normal
4068         //R_Shadow_RenderMode_End();
4069 }
4070
4071 void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
4072 {
4073         float zdist;
4074         vec3_t centerorigin;
4075         // if it's too close, skip it
4076         if (VectorLength(rtlight->color) < (1.0f / 256.0f))
4077                 return;
4078         zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
4079         if (zdist < 32)
4080                 return;
4081         if (usequery && r_numqueries + 2 <= r_maxqueries)
4082         {
4083                 rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
4084                 rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
4085                 VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
4086
4087                 CHECKGLERROR
4088                 // NOTE: we can't disable depth testing using R_DrawSprite's depthdisable argument, which calls GL_DepthTest, as that's broken in the ATI drivers
4089                 qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
4090                 qglDepthFunc(GL_ALWAYS);
4091                 R_DrawSprite(GL_ONE, GL_ZERO, r_shadow_lightcorona, NULL, false, false, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale, 1, 1, 1, 1);
4092                 qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
4093                 qglDepthFunc(GL_LEQUAL);
4094                 qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
4095                 R_DrawSprite(GL_ONE, GL_ZERO, r_shadow_lightcorona, NULL, false, false, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale, 1, 1, 1, 1);
4096                 qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
4097                 CHECKGLERROR
4098         }
4099         rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
4100 }
4101
4102 void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
4103 {
4104         vec3_t color;
4105         GLint allpixels = 0, visiblepixels = 0;
4106         // now we have to check the query result
4107         if (rtlight->corona_queryindex_visiblepixels)
4108         {
4109                 CHECKGLERROR
4110                 qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
4111                 qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
4112                 CHECKGLERROR
4113                 //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
4114                 if (visiblepixels < 1 || allpixels < 1)
4115                         return;
4116                 rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
4117                 cscale *= rtlight->corona_visibility;
4118         }
4119         else
4120         {
4121                 // FIXME: these traces should scan all render entities instead of cl.world
4122                 if (CL_Move(r_refdef.view.origin, vec3_origin, vec3_origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction < 1)
4123                         return;
4124         }
4125         VectorScale(rtlight->color, cscale, color);
4126         if (VectorLength(color) > (1.0f / 256.0f))
4127                 R_DrawSprite(GL_ONE, GL_ONE, r_shadow_lightcorona, NULL, true, false, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale, color[0], color[1], color[2], 1);
4128 }
4129
4130 void R_DrawCoronas(void)
4131 {
4132         int i, flag;
4133         qboolean usequery;
4134         size_t lightindex;
4135         dlight_t *light;
4136         rtlight_t *rtlight;
4137         size_t range;
4138         if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
4139                 return;
4140         if (r_waterstate.renderingscene)
4141                 return;
4142         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4143         R_Mesh_Matrix(&identitymatrix);
4144
4145         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4146
4147         // check occlusion of coronas
4148         // use GL_ARB_occlusion_query if available
4149         // otherwise use raytraces
4150         r_numqueries = 0;
4151         usequery = gl_support_arb_occlusion_query && r_coronas_occlusionquery.integer;
4152         if (usequery)
4153         {
4154                 GL_ColorMask(0,0,0,0);
4155                 if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
4156                 if (r_maxqueries < R_MAX_OCCLUSION_QUERIES)
4157                 {
4158                         i = r_maxqueries;
4159                         r_maxqueries = (range + r_refdef.scene.numlights) * 4;
4160                         r_maxqueries = min(r_maxqueries, R_MAX_OCCLUSION_QUERIES);
4161                         CHECKGLERROR
4162                         qglGenQueriesARB(r_maxqueries - i, r_queries + i);
4163                         CHECKGLERROR
4164                 }
4165         }
4166         for (lightindex = 0;lightindex < range;lightindex++)
4167         {
4168                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4169                 if (!light)
4170                         continue;
4171                 rtlight = &light->rtlight;
4172                 rtlight->corona_visibility = 0;
4173                 rtlight->corona_queryindex_visiblepixels = 0;
4174                 rtlight->corona_queryindex_allpixels = 0;
4175                 if (!(rtlight->flags & flag))
4176                         continue;
4177                 if (rtlight->corona <= 0)
4178                         continue;
4179                 if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
4180                         continue;
4181                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
4182         }
4183         for (i = 0;i < r_refdef.scene.numlights;i++)
4184         {
4185                 rtlight = r_refdef.scene.lights[i];
4186                 rtlight->corona_visibility = 0;
4187                 rtlight->corona_queryindex_visiblepixels = 0;
4188                 rtlight->corona_queryindex_allpixels = 0;
4189                 if (!(rtlight->flags & flag))
4190                         continue;
4191                 if (rtlight->corona <= 0)
4192                         continue;
4193                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
4194         }
4195         if (usequery)
4196                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
4197
4198         // now draw the coronas using the query data for intensity info
4199         for (lightindex = 0;lightindex < range;lightindex++)
4200         {
4201                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4202                 if (!light)
4203                         continue;
4204                 rtlight = &light->rtlight;
4205                 if (rtlight->corona_visibility <= 0)
4206                         continue;
4207                 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
4208         }
4209         for (i = 0;i < r_refdef.scene.numlights;i++)
4210         {
4211                 rtlight = r_refdef.scene.lights[i];
4212                 if (rtlight->corona_visibility <= 0)
4213                         continue;
4214                 if (gl_flashblend.integer)
4215                         R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
4216                 else
4217                         R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
4218         }
4219 }
4220
4221
4222
4223 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
4224 typedef struct suffixinfo_s
4225 {
4226         char *suffix;
4227         qboolean flipx, flipy, flipdiagonal;
4228 }
4229 suffixinfo_t;
4230 static suffixinfo_t suffix[3][6] =
4231 {
4232         {
4233                 {"px",   false, false, false},
4234                 {"nx",   false, false, false},
4235                 {"py",   false, false, false},
4236                 {"ny",   false, false, false},
4237                 {"pz",   false, false, false},
4238                 {"nz",   false, false, false}
4239         },
4240         {
4241                 {"posx", false, false, false},
4242                 {"negx", false, false, false},
4243                 {"posy", false, false, false},
4244                 {"negy", false, false, false},
4245                 {"posz", false, false, false},
4246                 {"negz", false, false, false}
4247         },
4248         {
4249                 {"rt",    true, false,  true},
4250                 {"lf",   false,  true,  true},
4251                 {"ft",    true,  true, false},
4252                 {"bk",   false, false, false},
4253                 {"up",    true, false,  true},
4254                 {"dn",    true, false,  true}
4255         }
4256 };
4257
4258 static int componentorder[4] = {0, 1, 2, 3};
4259
4260 rtexture_t *R_Shadow_LoadCubemap(const char *basename)
4261 {
4262         int i, j, cubemapsize;
4263         unsigned char *cubemappixels, *image_buffer;
4264         rtexture_t *cubemaptexture;
4265         char name[256];
4266         // must start 0 so the first loadimagepixels has no requested width/height
4267         cubemapsize = 0;
4268         cubemappixels = NULL;
4269         cubemaptexture = NULL;
4270         // keep trying different suffix groups (posx, px, rt) until one loads
4271         for (j = 0;j < 3 && !cubemappixels;j++)
4272         {
4273                 // load the 6 images in the suffix group
4274                 for (i = 0;i < 6;i++)
4275                 {
4276                         // generate an image name based on the base and and suffix
4277                         dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
4278                         // load it
4279                         if ((image_buffer = loadimagepixelsbgra(name, false, false)))
4280                         {
4281                                 // an image loaded, make sure width and height are equal
4282                                 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
4283                                 {
4284                                         // if this is the first image to load successfully, allocate the cubemap memory
4285                                         if (!cubemappixels && image_width >= 1)
4286                                         {
4287                                                 cubemapsize = image_width;
4288                                                 // note this clears to black, so unavailable sides are black
4289                                                 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
4290                                         }
4291                                         // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
4292                                         if (cubemappixels)
4293                                                 Image_CopyMux(cubemappixels+i*cubemapsize*cubemapsize*4, image_buffer, cubemapsize, cubemapsize, suffix[j][i].flipx, suffix[j][i].flipy, suffix[j][i].flipdiagonal, 4, 4, componentorder);
4294                                 }
4295                                 else
4296                                         Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
4297                                 // free the image
4298                                 Mem_Free(image_buffer);
4299                         }
4300                 }
4301         }
4302         // if a cubemap loaded, upload it
4303         if (cubemappixels)
4304         {
4305                 if (developer_loading.integer)
4306                         Con_Printf("loading cubemap \"%s\"\n", basename);
4307
4308                 if (!r_shadow_filters_texturepool)
4309                         r_shadow_filters_texturepool = R_AllocTexturePool();
4310                 cubemaptexture = R_LoadTextureCubeMap(r_shadow_filters_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, TEXF_PRECACHE | (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR, NULL);
4311                 Mem_Free(cubemappixels);
4312         }
4313         else
4314         {
4315                 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
4316                 if (developer_loading.integer)
4317                 {
4318                         Con_Printf("(tried tried images ");
4319                         for (j = 0;j < 3;j++)
4320                                 for (i = 0;i < 6;i++)
4321                                         Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
4322                         Con_Print(" and was unable to find any of them).\n");
4323                 }
4324         }
4325         return cubemaptexture;
4326 }
4327
4328 rtexture_t *R_Shadow_Cubemap(const char *basename)
4329 {
4330         int i;
4331         for (i = 0;i < numcubemaps;i++)
4332                 if (!strcasecmp(cubemaps[i].basename, basename))
4333                         return cubemaps[i].texture ? cubemaps[i].texture : r_texture_whitecube;
4334         if (i >= MAX_CUBEMAPS)
4335                 return r_texture_whitecube;
4336         numcubemaps++;
4337         strlcpy(cubemaps[i].basename, basename, sizeof(cubemaps[i].basename));
4338         cubemaps[i].texture = R_Shadow_LoadCubemap(cubemaps[i].basename);
4339         return cubemaps[i].texture;
4340 }
4341
4342 void R_Shadow_FreeCubemaps(void)
4343 {
4344         int i;
4345         for (i = 0;i < numcubemaps;i++)
4346         {
4347                 if (developer_loading.integer)
4348                         Con_Printf("unloading cubemap \"%s\"\n", cubemaps[i].basename);
4349                 if (cubemaps[i].texture)
4350                         R_FreeTexture(cubemaps[i].texture);
4351         }
4352
4353         numcubemaps = 0;
4354         R_FreeTexturePool(&r_shadow_filters_texturepool);
4355 }
4356
4357 dlight_t *R_Shadow_NewWorldLight(void)
4358 {
4359         return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray);
4360 }
4361
4362 void R_Shadow_UpdateWorldLight(dlight_t *light, vec3_t origin, vec3_t angles, vec3_t color, vec_t radius, vec_t corona, int style, int shadowenable, const char *cubemapname, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
4363 {
4364         matrix4x4_t matrix;
4365         // validate parameters
4366         if (style < 0 || style >= MAX_LIGHTSTYLES)
4367         {
4368                 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
4369                 style = 0;
4370         }
4371         if (!cubemapname)
4372                 cubemapname = "";
4373
4374         // copy to light properties
4375         VectorCopy(origin, light->origin);
4376         light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
4377         light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
4378         light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
4379         light->color[0] = max(color[0], 0);
4380         light->color[1] = max(color[1], 0);
4381         light->color[2] = max(color[2], 0);
4382         light->radius = max(radius, 0);
4383         light->style = style;
4384         light->shadow = shadowenable;
4385         light->corona = corona;
4386         strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
4387         light->coronasizescale = coronasizescale;
4388         light->ambientscale = ambientscale;
4389         light->diffusescale = diffusescale;
4390         light->specularscale = specularscale;
4391         light->flags = flags;
4392
4393         // update renderable light data
4394         Matrix4x4_CreateFromQuakeEntity(&matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], light->radius);
4395         R_RTLight_Update(&light->rtlight, true, &matrix, light->color, light->style, light->cubemapname[0] ? light->cubemapname : NULL, light->shadow, light->corona, light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
4396 }
4397
4398 void R_Shadow_FreeWorldLight(dlight_t *light)
4399 {
4400         if (r_shadow_selectedlight == light)
4401                 r_shadow_selectedlight = NULL;
4402         R_RTLight_Uncompile(&light->rtlight);
4403         Mem_ExpandableArray_FreeRecord(&r_shadow_worldlightsarray, light);
4404 }
4405
4406 void R_Shadow_ClearWorldLights(void)
4407 {
4408         size_t lightindex;
4409         dlight_t *light;
4410         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4411         for (lightindex = 0;lightindex < range;lightindex++)
4412         {
4413                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4414                 if (light)
4415                         R_Shadow_FreeWorldLight(light);
4416         }
4417         r_shadow_selectedlight = NULL;
4418         R_Shadow_FreeCubemaps();
4419 }
4420
4421 void R_Shadow_SelectLight(dlight_t *light)
4422 {
4423         if (r_shadow_selectedlight)
4424                 r_shadow_selectedlight->selected = false;
4425         r_shadow_selectedlight = light;
4426         if (r_shadow_selectedlight)
4427                 r_shadow_selectedlight->selected = true;
4428 }
4429
4430 void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
4431 {
4432         // this is never batched (there can be only one)
4433         R_DrawSprite(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, r_editlights_sprcursor->tex, r_editlights_sprcursor->tex, false, false, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE, 1, 1, 1, 1);
4434 }
4435
4436 void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
4437 {
4438         float intensity;
4439         float s;
4440         vec3_t spritecolor;
4441         cachepic_t *pic;
4442
4443         // this is never batched (due to the ent parameter changing every time)
4444         // so numsurfaces == 1 and surfacelist[0] == lightnumber
4445         const dlight_t *light = (dlight_t *)ent;
4446         s = EDLIGHTSPRSIZE;
4447         intensity = 0.5f;
4448         VectorScale(light->color, intensity, spritecolor);
4449         if (VectorLength(spritecolor) < 0.1732f)
4450                 VectorSet(spritecolor, 0.1f, 0.1f, 0.1f);
4451         if (VectorLength(spritecolor) > 1.0f)
4452                 VectorNormalize(spritecolor);
4453
4454         // draw light sprite
4455         if (light->cubemapname[0] && !light->shadow)
4456                 pic = r_editlights_sprcubemapnoshadowlight;
4457         else if (light->cubemapname[0])
4458                 pic = r_editlights_sprcubemaplight;
4459         else if (!light->shadow)
4460                 pic = r_editlights_sprnoshadowlight;
4461         else
4462                 pic = r_editlights_sprlight;
4463         R_DrawSprite(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, pic->tex, pic->tex, false, false, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s, spritecolor[0], spritecolor[1], spritecolor[2], 1);
4464         // draw selection sprite if light is selected
4465         if (light->selected)
4466                 R_DrawSprite(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, r_editlights_sprselection->tex, r_editlights_sprselection->tex, false, false, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s, 1, 1, 1, 1);
4467         // VorteX todo: add normalmode/realtime mode light overlay sprites?
4468 }
4469
4470 void R_Shadow_DrawLightSprites(void)
4471 {
4472         size_t lightindex;
4473         dlight_t *light;
4474         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4475         for (lightindex = 0;lightindex < range;lightindex++)
4476         {
4477                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4478                 if (light)
4479                         R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
4480         }
4481         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
4482 }
4483
4484 void R_Shadow_SelectLightInView(void)
4485 {
4486         float bestrating, rating, temp[3];
4487         dlight_t *best;
4488         size_t lightindex;
4489         dlight_t *light;
4490         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4491         best = NULL;
4492         bestrating = 0;
4493         for (lightindex = 0;lightindex < range;lightindex++)
4494         {
4495                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4496                 if (!light)
4497                         continue;
4498                 VectorSubtract(light->origin, r_refdef.view.origin, temp);
4499                 rating = (DotProduct(temp, r_refdef.view.forward) / sqrt(DotProduct(temp, temp)));
4500                 if (rating >= 0.95)
4501                 {
4502                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
4503                         if (bestrating < rating && CL_Move(light->origin, vec3_origin, vec3_origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction == 1.0f)
4504                         {
4505                                 bestrating = rating;
4506                                 best = light;
4507                         }
4508                 }
4509         }
4510         R_Shadow_SelectLight(best);
4511 }
4512
4513 void R_Shadow_LoadWorldLights(void)
4514 {
4515         int n, a, style, shadow, flags;
4516         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
4517         float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
4518         if (cl.worldmodel == NULL)
4519         {
4520                 Con_Print("No map loaded.\n");
4521                 return;
4522         }
4523         FS_StripExtension (cl.worldmodel->name, name, sizeof (name));
4524         strlcat (name, ".rtlights", sizeof (name));
4525         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
4526         if (lightsstring)
4527         {
4528                 s = lightsstring;
4529                 n = 0;
4530                 while (*s)
4531                 {
4532                         t = s;
4533                         /*
4534                         shadow = true;
4535                         for (;COM_Parse(t, true) && strcmp(
4536                         if (COM_Parse(t, true))
4537                         {
4538                                 if (com_token[0] == '!')
4539                                 {
4540                                         shadow = false;
4541                                         origin[0] = atof(com_token+1);
4542                                 }
4543                                 else
4544                                         origin[0] = atof(com_token);
4545                                 if (Com_Parse(t
4546                         }
4547                         */
4548                         t = s;
4549                         while (*s && *s != '\n' && *s != '\r')
4550                                 s++;
4551                         if (!*s)
4552                                 break;
4553                         tempchar = *s;
4554                         shadow = true;
4555                         // check for modifier flags
4556                         if (*t == '!')
4557                         {
4558                                 shadow = false;
4559                                 t++;
4560                         }
4561                         *s = 0;
4562 #if _MSC_VER >= 1400
4563 #define sscanf sscanf_s
4564 #endif
4565                         cubemapname[sizeof(cubemapname)-1] = 0;
4566 #if MAX_QPATH != 128
4567 #error update this code if MAX_QPATH changes
4568 #endif
4569                         a = sscanf(t, "%f %f %f %f %f %f %f %d %127s %f %f %f %f %f %f %f %f %i", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, cubemapname
4570 #if _MSC_VER >= 1400
4571 , sizeof(cubemapname)
4572 #endif
4573 , &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
4574                         *s = tempchar;
4575                         if (a < 18)
4576                                 flags = LIGHTFLAG_REALTIMEMODE;
4577                         if (a < 17)
4578                                 specularscale = 1;
4579                         if (a < 16)
4580                                 diffusescale = 1;
4581                         if (a < 15)
4582                                 ambientscale = 0;
4583                         if (a < 14)
4584                                 coronasizescale = 0.25f;
4585                         if (a < 13)
4586                                 VectorClear(angles);
4587                         if (a < 10)
4588                                 corona = 0;
4589                         if (a < 9 || !strcmp(cubemapname, "\"\""))
4590                                 cubemapname[0] = 0;
4591                         // remove quotes on cubemapname
4592                         if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
4593                         {
4594                                 size_t namelen;
4595                                 namelen = strlen(cubemapname) - 2;
4596                                 memmove(cubemapname, cubemapname + 1, namelen);
4597                                 cubemapname[namelen] = '\0';
4598                         }
4599                         if (a < 8)
4600                         {
4601                                 Con_Printf("found %d parameters on line %i, should be 8 or more parameters (origin[0] origin[1] origin[2] radius color[0] color[1] color[2] style \"cubemapname\" corona angles[0] angles[1] angles[2] coronasizescale ambientscale diffusescale specularscale flags)\n", a, n + 1);
4602                                 break;
4603                         }
4604                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
4605                         if (*s == '\r')
4606                                 s++;
4607                         if (*s == '\n')
4608                                 s++;
4609                         n++;
4610                 }
4611                 if (*s)
4612                         Con_Printf("invalid rtlights file \"%s\"\n", name);
4613                 Mem_Free(lightsstring);
4614         }
4615 }
4616
4617 void R_Shadow_SaveWorldLights(void)
4618 {
4619         size_t lightindex;
4620         dlight_t *light;
4621         size_t bufchars, bufmaxchars;
4622         char *buf, *oldbuf;
4623         char name[MAX_QPATH];
4624         char line[MAX_INPUTLINE];
4625         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
4626         // I hate lines which are 3 times my screen size :( --blub
4627         if (!range)
4628                 return;
4629         if (cl.worldmodel == NULL)
4630         {
4631                 Con_Print("No map loaded.\n");
4632                 return;
4633         }
4634         FS_StripExtension (cl.worldmodel->name, name, sizeof (name));
4635         strlcat (name, ".rtlights", sizeof (name));
4636         bufchars = bufmaxchars = 0;
4637         buf = NULL;
4638         for (lightindex = 0;lightindex < range;lightindex++)
4639         {
4640                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4641                 if (!light)
4642                         continue;
4643                 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
4644                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f %f %f %f %f %i\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2], light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
4645                 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
4646                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2]);
4647                 else
4648                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style);
4649                 if (bufchars + strlen(line) > bufmaxchars)
4650                 {
4651                         bufmaxchars = bufchars + strlen(line) + 2048;
4652                         oldbuf = buf;
4653                         buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
4654                         if (oldbuf)
4655                         {
4656                                 if (bufchars)
4657                                         memcpy(buf, oldbuf, bufchars);
4658                                 Mem_Free(oldbuf);
4659                         }
4660                 }
4661                 if (strlen(line))
4662                 {
4663                         memcpy(buf + bufchars, line, strlen(line));
4664                         bufchars += strlen(line);
4665                 }
4666         }
4667         if (bufchars)
4668                 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
4669         if (buf)
4670                 Mem_Free(buf);
4671 }
4672
4673 void R_Shadow_LoadLightsFile(void)
4674 {
4675         int n, a, style;
4676         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
4677         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
4678         if (cl.worldmodel == NULL)
4679         {
4680                 Con_Print("No map loaded.\n");
4681                 return;
4682         }
4683         FS_StripExtension (cl.worldmodel->name, name, sizeof (name));
4684         strlcat (name, ".lights", sizeof (name));
4685         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
4686         if (lightsstring)
4687         {
4688                 s = lightsstring;
4689                 n = 0;
4690                 while (*s)
4691                 {
4692                         t = s;
4693                         while (*s && *s != '\n' && *s != '\r')
4694                                 s++;
4695                         if (!*s)
4696                                 break;
4697                         tempchar = *s;
4698                         *s = 0;
4699                         a = sscanf(t, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d", &origin[0], &origin[1], &origin[2], &falloff, &color[0], &color[1], &color[2], &subtract, &spotdir[0], &spotdir[1], &spotdir[2], &spotcone, &distbias, &style);
4700                         *s = tempchar;
4701                         if (a < 14)
4702                         {
4703                                 Con_Printf("invalid lights file, found %d parameters on line %i, should be 14 parameters (origin[0] origin[1] origin[2] falloff light[0] light[1] light[2] subtract spotdir[0] spotdir[1] spotdir[2] spotcone distancebias style)\n", a, n + 1);
4704                                 break;
4705                         }
4706                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
4707                         radius = bound(15, radius, 4096);
4708                         VectorScale(color, (2.0f / (8388608.0f)), color);
4709                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
4710                         if (*s == '\r')
4711                                 s++;
4712                         if (*s == '\n')
4713                                 s++;
4714                         n++;
4715                 }
4716                 if (*s)
4717                         Con_Printf("invalid lights file \"%s\"\n", name);
4718                 Mem_Free(lightsstring);
4719         }
4720 }
4721
4722 // tyrlite/hmap2 light types in the delay field
4723 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
4724
4725 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
4726 {
4727         int entnum, style, islight, skin, pflags, effects, type, n;
4728         char *entfiledata;
4729         const char *data;
4730         float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
4731         char key[256], value[MAX_INPUTLINE];
4732
4733         if (cl.worldmodel == NULL)
4734         {
4735                 Con_Print("No map loaded.\n");
4736                 return;
4737         }
4738         // try to load a .ent file first
4739         FS_StripExtension (cl.worldmodel->name, key, sizeof (key));
4740         strlcat (key, ".ent", sizeof (key));
4741         data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
4742         // and if that is not found, fall back to the bsp file entity string
4743         if (!data)
4744                 data = cl.worldmodel->brush.entities;
4745         if (!data)
4746                 return;
4747         for (entnum = 0;COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{';entnum++)
4748         {
4749                 type = LIGHTTYPE_MINUSX;
4750                 origin[0] = origin[1] = origin[2] = 0;
4751                 originhack[0] = originhack[1] = originhack[2] = 0;
4752                 angles[0] = angles[1] = angles[2] = 0;
4753                 color[0] = color[1] = color[2] = 1;
4754                 light[0] = light[1] = light[2] = 1;light[3] = 300;
4755                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
4756                 fadescale = 1;
4757                 lightscale = 1;
4758                 style = 0;
4759                 skin = 0;
4760                 pflags = 0;
4761                 effects = 0;
4762                 islight = false;
4763                 while (1)
4764                 {
4765                         if (!COM_ParseToken_Simple(&data, false, false))
4766                                 break; // error
4767                         if (com_token[0] == '}')
4768                                 break; // end of entity
4769                         if (com_token[0] == '_')
4770                                 strlcpy(key, com_token + 1, sizeof(key));
4771                         else
4772                                 strlcpy(key, com_token, sizeof(key));
4773                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
4774                                 key[strlen(key)-1] = 0;
4775                         if (!COM_ParseToken_Simple(&data, false, false))
4776                                 break; // error
4777                         strlcpy(value, com_token, sizeof(value));
4778
4779                         // now that we have the key pair worked out...
4780                         if (!strcmp("light", key))
4781                         {
4782                                 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
4783                                 if (n == 1)
4784                                 {
4785                                         // quake
4786                                         light[0] = vec[0] * (1.0f / 256.0f);
4787                                         light[1] = vec[0] * (1.0f / 256.0f);
4788                                         light[2] = vec[0] * (1.0f / 256.0f);
4789                                         light[3] = vec[0];
4790                                 }
4791                                 else if (n == 4)
4792                                 {
4793                                         // halflife
4794                                         light[0] = vec[0] * (1.0f / 255.0f);
4795                                         light[1] = vec[1] * (1.0f / 255.0f);
4796                                         light[2] = vec[2] * (1.0f / 255.0f);
4797                                         light[3] = vec[3];
4798                                 }
4799                         }
4800                         else if (!strcmp("delay", key))
4801                                 type = atoi(value);
4802                         else if (!strcmp("origin", key))
4803                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
4804                         else if (!strcmp("angle", key))
4805                                 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
4806                         else if (!strcmp("angles", key))
4807                                 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
4808                         else if (!strcmp("color", key))
4809                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
4810                         else if (!strcmp("wait", key))
4811                                 fadescale = atof(value);
4812                         else if (!strcmp("classname", key))
4813                         {
4814                                 if (!strncmp(value, "light", 5))
4815                                 {
4816                                         islight = true;
4817                                         if (!strcmp(value, "light_fluoro"))
4818                                         {
4819                                                 originhack[0] = 0;
4820                                                 originhack[1] = 0;
4821                                                 originhack[2] = 0;
4822                                                 overridecolor[0] = 1;
4823                                                 overridecolor[1] = 1;
4824                                                 overridecolor[2] = 1;
4825                                         }
4826                                         if (!strcmp(value, "light_fluorospark"))
4827                                         {
4828                                                 originhack[0] = 0;
4829                                                 originhack[1] = 0;
4830                                                 originhack[2] = 0;
4831                                                 overridecolor[0] = 1;
4832                                                 overridecolor[1] = 1;
4833                                                 overridecolor[2] = 1;
4834                                         }
4835                                         if (!strcmp(value, "light_globe"))
4836                                         {
4837                                                 originhack[0] = 0;
4838                                                 originhack[1] = 0;
4839                                                 originhack[2] = 0;
4840                                                 overridecolor[0] = 1;
4841                                                 overridecolor[1] = 0.8;
4842                                                 overridecolor[2] = 0.4;
4843                                         }
4844                                         if (!strcmp(value, "light_flame_large_yellow"))
4845                                         {
4846                                                 originhack[0] = 0;
4847                                                 originhack[1] = 0;
4848                                                 originhack[2] = 0;
4849                                                 overridecolor[0] = 1;
4850                                                 overridecolor[1] = 0.5;
4851                                                 overridecolor[2] = 0.1;
4852                                         }
4853                                         if (!strcmp(value, "light_flame_small_yellow"))
4854                                         {
4855                                                 originhack[0] = 0;
4856                                                 originhack[1] = 0;
4857                                                 originhack[2] = 0;
4858                                                 overridecolor[0] = 1;
4859                                                 overridecolor[1] = 0.5;
4860                                                 overridecolor[2] = 0.1;
4861                                         }
4862                                         if (!strcmp(value, "light_torch_small_white"))
4863                                         {
4864                                                 originhack[0] = 0;
4865                                                 originhack[1] = 0;
4866                                                 originhack[2] = 0;
4867                                                 overridecolor[0] = 1;
4868                                                 overridecolor[1] = 0.5;
4869                                                 overridecolor[2] = 0.1;
4870                                         }
4871                                         if (!strcmp(value, "light_torch_small_walltorch"))
4872                                         {
4873                                                 originhack[0] = 0;
4874                                                 originhack[1] = 0;
4875                                                 originhack[2] = 0;
4876                                                 overridecolor[0] = 1;
4877                                                 overridecolor[1] = 0.5;
4878                                                 overridecolor[2] = 0.1;
4879                                         }
4880                                 }
4881                         }
4882                         else if (!strcmp("style", key))
4883                                 style = atoi(value);
4884                         else if (!strcmp("skin", key))
4885                                 skin = (int)atof(value);
4886                         else if (!strcmp("pflags", key))
4887                                 pflags = (int)atof(value);
4888                         else if (!strcmp("effects", key))
4889                                 effects = (int)atof(value);
4890                         else if (cl.worldmodel->type == mod_brushq3)
4891                         {
4892                                 if (!strcmp("scale", key))
4893                                         lightscale = atof(value);
4894                                 if (!strcmp("fade", key))
4895                                         fadescale = atof(value);
4896                         }
4897                 }
4898                 if (!islight)
4899                         continue;
4900                 if (lightscale <= 0)
4901                         lightscale = 1;
4902                 if (fadescale <= 0)
4903                         fadescale = 1;
4904                 if (color[0] == color[1] && color[0] == color[2])
4905                 {
4906                         color[0] *= overridecolor[0];
4907                         color[1] *= overridecolor[1];
4908                         color[2] *= overridecolor[2];
4909                 }
4910                 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
4911                 color[0] = color[0] * light[0];
4912                 color[1] = color[1] * light[1];
4913                 color[2] = color[2] * light[2];
4914                 switch (type)
4915                 {
4916                 case LIGHTTYPE_MINUSX:
4917                         break;
4918                 case LIGHTTYPE_RECIPX:
4919                         radius *= 2;
4920                         VectorScale(color, (1.0f / 16.0f), color);
4921                         break;
4922                 case LIGHTTYPE_RECIPXX:
4923                         radius *= 2;
4924                         VectorScale(color, (1.0f / 16.0f), color);
4925                         break;
4926                 default:
4927                 case LIGHTTYPE_NONE:
4928                         break;
4929                 case LIGHTTYPE_SUN:
4930                         break;
4931                 case LIGHTTYPE_MINUSXX:
4932                         break;
4933                 }
4934                 VectorAdd(origin, originhack, origin);
4935                 if (radius >= 1)
4936                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va("cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
4937         }
4938         if (entfiledata)
4939                 Mem_Free(entfiledata);
4940 }
4941
4942
4943 void R_Shadow_SetCursorLocationForView(void)
4944 {
4945         vec_t dist, push;
4946         vec3_t dest, endpos;
4947         trace_t trace;
4948         VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest);
4949         trace = CL_Move(r_refdef.view.origin, vec3_origin, vec3_origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false);
4950         if (trace.fraction < 1)
4951         {
4952                 dist = trace.fraction * r_editlights_cursordistance.value;
4953                 push = r_editlights_cursorpushback.value;
4954                 if (push > dist)
4955                         push = dist;
4956                 push = -push;
4957                 VectorMA(trace.endpos, push, r_refdef.view.forward, endpos);
4958                 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
4959         }
4960         else
4961         {
4962                 VectorClear( endpos );
4963         }
4964         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
4965         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
4966         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
4967 }
4968
4969 void R_Shadow_UpdateWorldLightSelection(void)
4970 {
4971         if (r_editlights.integer)
4972         {
4973                 R_Shadow_SetCursorLocationForView();
4974                 R_Shadow_SelectLightInView();
4975         }
4976         else
4977                 R_Shadow_SelectLight(NULL);
4978 }
4979
4980 void R_Shadow_EditLights_Clear_f(void)
4981 {
4982         R_Shadow_ClearWorldLights();
4983 }
4984
4985 void R_Shadow_EditLights_Reload_f(void)
4986 {
4987         if (!cl.worldmodel)
4988                 return;
4989         strlcpy(r_shadow_mapname, cl.worldmodel->name, sizeof(r_shadow_mapname));
4990         R_Shadow_ClearWorldLights();
4991         R_Shadow_LoadWorldLights();
4992         if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
4993         {
4994                 R_Shadow_LoadLightsFile();
4995                 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
4996                         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
4997         }
4998 }
4999
5000 void R_Shadow_EditLights_Save_f(void)
5001 {
5002         if (!cl.worldmodel)
5003                 return;
5004         R_Shadow_SaveWorldLights();
5005 }
5006
5007 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
5008 {
5009         R_Shadow_ClearWorldLights();
5010         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
5011 }
5012
5013 void R_Shadow_EditLights_ImportLightsFile_f(void)
5014 {
5015         R_Shadow_ClearWorldLights();
5016         R_Shadow_LoadLightsFile();
5017 }
5018
5019 void R_Shadow_EditLights_Spawn_f(void)
5020 {
5021         vec3_t color;
5022         if (!r_editlights.integer)
5023         {
5024                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
5025                 return;
5026         }
5027         if (Cmd_Argc() != 1)
5028         {
5029                 Con_Print("r_editlights_spawn does not take parameters\n");
5030                 return;
5031         }
5032         color[0] = color[1] = color[2] = 1;
5033         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5034 }
5035
5036 void R_Shadow_EditLights_Edit_f(void)
5037 {
5038         vec3_t origin, angles, color;
5039         vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
5040         int style, shadows, flags, normalmode, realtimemode;
5041         char cubemapname[MAX_INPUTLINE];
5042         if (!r_editlights.integer)
5043         {
5044                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
5045                 return;
5046         }
5047         if (!r_shadow_selectedlight)
5048         {
5049                 Con_Print("No selected light.\n");
5050                 return;
5051         }
5052         VectorCopy(r_shadow_selectedlight->origin, origin);
5053         VectorCopy(r_shadow_selectedlight->angles, angles);
5054         VectorCopy(r_shadow_selectedlight->color, color);
5055         radius = r_shadow_selectedlight->radius;
5056         style = r_shadow_selectedlight->style;
5057         if (r_shadow_selectedlight->cubemapname)
5058                 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
5059         else
5060                 cubemapname[0] = 0;
5061         shadows = r_shadow_selectedlight->shadow;
5062         corona = r_shadow_selectedlight->corona;
5063         coronasizescale = r_shadow_selectedlight->coronasizescale;
5064         ambientscale = r_shadow_selectedlight->ambientscale;
5065         diffusescale = r_shadow_selectedlight->diffusescale;
5066         specularscale = r_shadow_selectedlight->specularscale;
5067         flags = r_shadow_selectedlight->flags;
5068         normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
5069         realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
5070         if (!strcmp(Cmd_Argv(1), "origin"))
5071         {
5072                 if (Cmd_Argc() != 5)
5073                 {
5074                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
5075                         return;
5076                 }
5077                 origin[0] = atof(Cmd_Argv(2));
5078                 origin[1] = atof(Cmd_Argv(3));
5079                 origin[2] = atof(Cmd_Argv(4));
5080         }
5081         else if (!strcmp(Cmd_Argv(1), "originx"))
5082         {
5083                 if (Cmd_Argc() != 3)
5084                 {
5085                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5086                         return;
5087                 }
5088                 origin[0] = atof(Cmd_Argv(2));
5089         }
5090         else if (!strcmp(Cmd_Argv(1), "originy"))
5091         {
5092                 if (Cmd_Argc() != 3)
5093                 {
5094                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5095                         return;
5096                 }
5097                 origin[1] = atof(Cmd_Argv(2));
5098         }
5099         else if (!strcmp(Cmd_Argv(1), "originz"))
5100         {
5101                 if (Cmd_Argc() != 3)
5102                 {
5103                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5104                         return;
5105                 }
5106                 origin[2] = atof(Cmd_Argv(2));
5107         }
5108         else if (!strcmp(Cmd_Argv(1), "move"))
5109         {
5110                 if (Cmd_Argc() != 5)
5111                 {
5112                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
5113                         return;
5114                 }
5115                 origin[0] += atof(Cmd_Argv(2));
5116                 origin[1] += atof(Cmd_Argv(3));
5117                 origin[2] += atof(Cmd_Argv(4));
5118         }
5119         else if (!strcmp(Cmd_Argv(1), "movex"))
5120         {
5121                 if (Cmd_Argc() != 3)
5122                 {
5123                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5124                         return;
5125                 }
5126                 origin[0] += atof(Cmd_Argv(2));
5127         }
5128         else if (!strcmp(Cmd_Argv(1), "movey"))
5129         {
5130                 if (Cmd_Argc() != 3)
5131                 {
5132                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5133                         return;
5134                 }
5135                 origin[1] += atof(Cmd_Argv(2));
5136         }
5137         else if (!strcmp(Cmd_Argv(1), "movez"))
5138         {
5139                 if (Cmd_Argc() != 3)
5140                 {
5141                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5142                         return;
5143                 }
5144                 origin[2] += atof(Cmd_Argv(2));
5145         }
5146         else if (!strcmp(Cmd_Argv(1), "angles"))
5147         {
5148                 if (Cmd_Argc() != 5)
5149                 {
5150                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
5151                         return;
5152                 }
5153                 angles[0] = atof(Cmd_Argv(2));
5154                 angles[1] = atof(Cmd_Argv(3));
5155                 angles[2] = atof(Cmd_Argv(4));
5156         }
5157         else if (!strcmp(Cmd_Argv(1), "anglesx"))
5158         {
5159                 if (Cmd_Argc() != 3)
5160                 {
5161                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5162                         return;
5163                 }
5164                 angles[0] = atof(Cmd_Argv(2));
5165         }
5166         else if (!strcmp(Cmd_Argv(1), "anglesy"))
5167         {
5168                 if (Cmd_Argc() != 3)
5169                 {
5170                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5171                         return;
5172                 }
5173                 angles[1] = atof(Cmd_Argv(2));
5174         }
5175         else if (!strcmp(Cmd_Argv(1), "anglesz"))
5176         {
5177                 if (Cmd_Argc() != 3)
5178                 {
5179                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5180                         return;
5181                 }
5182                 angles[2] = atof(Cmd_Argv(2));
5183         }
5184         else if (!strcmp(Cmd_Argv(1), "color"))
5185         {
5186                 if (Cmd_Argc() != 5)
5187                 {
5188                         Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
5189                         return;
5190                 }
5191                 color[0] = atof(Cmd_Argv(2));
5192                 color[1] = atof(Cmd_Argv(3));
5193                 color[2] = atof(Cmd_Argv(4));
5194         }
5195         else if (!strcmp(Cmd_Argv(1), "radius"))
5196         {
5197                 if (Cmd_Argc() != 3)
5198                 {
5199                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5200                         return;
5201                 }
5202                 radius = atof(Cmd_Argv(2));
5203         }
5204         else if (!strcmp(Cmd_Argv(1), "colorscale"))
5205         {
5206                 if (Cmd_Argc() == 3)
5207                 {
5208                         double scale = atof(Cmd_Argv(2));
5209                         color[0] *= scale;
5210                         color[1] *= scale;
5211                         color[2] *= scale;
5212                 }
5213                 else
5214                 {
5215                         if (Cmd_Argc() != 5)
5216                         {
5217                                 Con_Printf("usage: r_editlights_edit %s red green blue  (OR grey instead of red green blue)\n", Cmd_Argv(1));
5218                                 return;
5219                         }
5220                         color[0] *= atof(Cmd_Argv(2));
5221                         color[1] *= atof(Cmd_Argv(3));
5222                         color[2] *= atof(Cmd_Argv(4));
5223                 }
5224         }
5225         else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
5226         {
5227                 if (Cmd_Argc() != 3)
5228                 {
5229                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5230                         return;
5231                 }
5232                 radius *= atof(Cmd_Argv(2));
5233         }
5234         else if (!strcmp(Cmd_Argv(1), "style"))
5235         {
5236                 if (Cmd_Argc() != 3)
5237                 {
5238                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5239                         return;
5240                 }
5241                 style = atoi(Cmd_Argv(2));
5242         }
5243         else if (!strcmp(Cmd_Argv(1), "cubemap"))
5244         {
5245                 if (Cmd_Argc() > 3)
5246                 {
5247                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5248                         return;
5249                 }
5250                 if (Cmd_Argc() == 3)
5251                         strlcpy(cubemapname, Cmd_Argv(2), sizeof(cubemapname));
5252                 else
5253                         cubemapname[0] = 0;
5254         }
5255         else if (!strcmp(Cmd_Argv(1), "shadows"))
5256         {
5257                 if (Cmd_Argc() != 3)
5258                 {
5259                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5260                         return;
5261                 }
5262                 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
5263         }
5264         else if (!strcmp(Cmd_Argv(1), "corona"))
5265         {
5266                 if (Cmd_Argc() != 3)
5267                 {
5268                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5269                         return;
5270                 }
5271                 corona = atof(Cmd_Argv(2));
5272         }
5273         else if (!strcmp(Cmd_Argv(1), "coronasize"))
5274         {
5275                 if (Cmd_Argc() != 3)
5276                 {
5277                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5278                         return;
5279                 }
5280                 coronasizescale = atof(Cmd_Argv(2));
5281         }
5282         else if (!strcmp(Cmd_Argv(1), "ambient"))
5283         {
5284                 if (Cmd_Argc() != 3)
5285                 {
5286                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5287                         return;
5288                 }
5289                 ambientscale = atof(Cmd_Argv(2));
5290         }
5291         else if (!strcmp(Cmd_Argv(1), "diffuse"))
5292         {
5293                 if (Cmd_Argc() != 3)
5294                 {
5295                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5296                         return;
5297                 }
5298                 diffusescale = atof(Cmd_Argv(2));
5299         }
5300         else if (!strcmp(Cmd_Argv(1), "specular"))
5301         {
5302                 if (Cmd_Argc() != 3)
5303                 {
5304                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5305                         return;
5306                 }
5307                 specularscale = atof(Cmd_Argv(2));
5308         }
5309         else if (!strcmp(Cmd_Argv(1), "normalmode"))
5310         {
5311                 if (Cmd_Argc() != 3)
5312                 {
5313                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5314                         return;
5315                 }
5316                 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
5317         }
5318         else if (!strcmp(Cmd_Argv(1), "realtimemode"))
5319         {
5320                 if (Cmd_Argc() != 3)
5321                 {
5322                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
5323                         return;
5324                 }
5325                 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
5326         }
5327         else
5328         {
5329                 Con_Print("usage: r_editlights_edit [property] [value]\n");
5330                 Con_Print("Selected light's properties:\n");
5331                 Con_Printf("Origin       : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
5332                 Con_Printf("Angles       : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
5333                 Con_Printf("Color        : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
5334                 Con_Printf("Radius       : %f\n", r_shadow_selectedlight->radius);
5335                 Con_Printf("Corona       : %f\n", r_shadow_selectedlight->corona);
5336                 Con_Printf("Style        : %i\n", r_shadow_selectedlight->style);
5337                 Con_Printf("Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
5338                 Con_Printf("Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);
5339                 Con_Printf("CoronaSize   : %f\n", r_shadow_selectedlight->coronasizescale);
5340                 Con_Printf("Ambient      : %f\n", r_shadow_selectedlight->ambientscale);
5341                 Con_Printf("Diffuse      : %f\n", r_shadow_selectedlight->diffusescale);
5342                 Con_Printf("Specular     : %f\n", r_shadow_selectedlight->specularscale);
5343                 Con_Printf("NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
5344                 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
5345                 return;
5346         }
5347         flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
5348         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
5349 }
5350
5351 void R_Shadow_EditLights_EditAll_f(void)
5352 {
5353         size_t lightindex;
5354         dlight_t *light;
5355         size_t range;
5356
5357         if (!r_editlights.integer)
5358         {
5359                 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
5360                 return;
5361         }
5362
5363         // EditLights doesn't seem to have a "remove" command or something so:
5364         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5365         for (lightindex = 0;lightindex < range;lightindex++)
5366         {
5367                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5368                 if (!light)
5369                         continue;
5370                 R_Shadow_SelectLight(light);
5371                 R_Shadow_EditLights_Edit_f();
5372         }
5373 }
5374
5375 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
5376 {
5377         int lightnumber, lightcount;
5378         size_t lightindex, range;
5379         dlight_t *light;
5380         float x, y;
5381         char temp[256];
5382         if (!r_editlights.integer)
5383                 return;
5384         x = vid_conwidth.value - 240;
5385         y = 5;
5386         DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
5387         lightnumber = -1;
5388         lightcount = 0;
5389         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5390         for (lightindex = 0;lightindex < range;lightindex++)
5391         {
5392                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5393                 if (!light)
5394                         continue;
5395                 if (light == r_shadow_selectedlight)
5396                         lightnumber = lightindex;
5397                 lightcount++;
5398         }
5399         dpsnprintf(temp, sizeof(temp), "Cursor origin: %.0f %.0f %.0f", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2]); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false);y += 8;
5400         dpsnprintf(temp, sizeof(temp), "Total lights : %i active (%i total)", lightcount, (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false);y += 8;
5401         y += 8;
5402         if (r_shadow_selectedlight == NULL)
5403                 return;
5404         dpsnprintf(temp, sizeof(temp), "Light #%i properties:", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5405         dpsnprintf(temp, sizeof(temp), "Origin       : %.0f %.0f %.0f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5406         dpsnprintf(temp, sizeof(temp), "Angles       : %.0f %.0f %.0f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5407         dpsnprintf(temp, sizeof(temp), "Color        : %.2f %.2f %.2f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5408         dpsnprintf(temp, sizeof(temp), "Radius       : %.0f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5409         dpsnprintf(temp, sizeof(temp), "Corona       : %.0f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5410         dpsnprintf(temp, sizeof(temp), "Style        : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5411         dpsnprintf(temp, sizeof(temp), "Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5412         dpsnprintf(temp, sizeof(temp), "Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5413         dpsnprintf(temp, sizeof(temp), "CoronaSize   : %.2f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5414         dpsnprintf(temp, sizeof(temp), "Ambient      : %.2f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5415         dpsnprintf(temp, sizeof(temp), "Diffuse      : %.2f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5416         dpsnprintf(temp, sizeof(temp), "Specular     : %.2f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5417         dpsnprintf(temp, sizeof(temp), "NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5418         dpsnprintf(temp, sizeof(temp), "RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
5419 }
5420
5421 void R_Shadow_EditLights_ToggleShadow_f(void)
5422 {
5423         if (!r_editlights.integer)
5424         {
5425                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
5426                 return;
5427         }
5428         if (!r_shadow_selectedlight)
5429         {
5430                 Con_Print("No selected light.\n");
5431                 return;
5432         }
5433         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, r_shadow_selectedlight->corona, r_shadow_selectedlight->style, !r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags);
5434 }
5435
5436 void R_Shadow_EditLights_ToggleCorona_f(void)
5437 {
5438         if (!r_editlights.integer)
5439         {
5440                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
5441                 return;
5442         }
5443         if (!r_shadow_selectedlight)
5444         {
5445                 Con_Print("No selected light.\n");
5446                 return;
5447         }
5448         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, !r_shadow_selectedlight->corona, r_shadow_selectedlight->style, r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags);
5449 }
5450
5451 void R_Shadow_EditLights_Remove_f(void)
5452 {
5453         if (!r_editlights.integer)
5454         {
5455                 Con_Print("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
5456                 return;
5457         }
5458         if (!r_shadow_selectedlight)
5459         {
5460                 Con_Print("No selected light.\n");
5461                 return;
5462         }
5463         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
5464         r_shadow_selectedlight = NULL;
5465 }
5466
5467 void R_Shadow_EditLights_Help_f(void)
5468 {
5469         Con_Print(
5470 "Documentation on r_editlights system:\n"
5471 "Settings:\n"
5472 "r_editlights : enable/disable editing mode\n"
5473 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
5474 "r_editlights_cursorpushback : push back cursor this far from surface\n"
5475 "r_editlights_cursorpushoff : push cursor off surface this far\n"
5476 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
5477 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
5478 "Commands:\n"
5479 "r_editlights_help : this help\n"
5480 "r_editlights_clear : remove all lights\n"
5481 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
5482 "r_editlights_save : save to .rtlights file\n"
5483 "r_editlights_spawn : create a light with default settings\n"
5484 "r_editlights_edit command : edit selected light - more documentation below\n"
5485 "r_editlights_remove : remove selected light\n"
5486 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
5487 "r_editlights_importlightentitiesfrommap : reload light entities\n"
5488 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
5489 "Edit commands:\n"
5490 "origin x y z : set light location\n"
5491 "originx x: set x component of light location\n"
5492 "originy y: set y component of light location\n"
5493 "originz z: set z component of light location\n"
5494 "move x y z : adjust light location\n"
5495 "movex x: adjust x component of light location\n"
5496 "movey y: adjust y component of light location\n"
5497 "movez z: adjust z component of light location\n"
5498 "angles x y z : set light angles\n"
5499 "anglesx x: set x component of light angles\n"
5500 "anglesy y: set y component of light angles\n"
5501 "anglesz z: set z component of light angles\n"
5502 "color r g b : set color of light (can be brighter than 1 1 1)\n"
5503 "radius radius : set radius (size) of light\n"
5504 "colorscale grey : multiply color of light (1 does nothing)\n"
5505 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
5506 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
5507 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
5508 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
5509 "cubemap basename : set filter cubemap of light (not yet supported)\n"
5510 "shadows 1/0 : turn on/off shadows\n"
5511 "corona n : set corona intensity\n"
5512 "coronasize n : set corona size (0-1)\n"
5513 "ambient n : set ambient intensity (0-1)\n"
5514 "diffuse n : set diffuse intensity (0-1)\n"
5515 "specular n : set specular intensity (0-1)\n"
5516 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
5517 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
5518 "<nothing> : print light properties to console\n"
5519         );
5520 }
5521
5522 void R_Shadow_EditLights_CopyInfo_f(void)
5523 {
5524         if (!r_editlights.integer)
5525         {
5526                 Con_Print("Cannot copy light info when not in editing mode.  Set r_editlights to 1.\n");
5527                 return;
5528         }
5529         if (!r_shadow_selectedlight)
5530         {
5531                 Con_Print("No selected light.\n");
5532                 return;
5533         }
5534         VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
5535         VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
5536         r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
5537         r_shadow_bufferlight.style = r_shadow_selectedlight->style;
5538         if (r_shadow_selectedlight->cubemapname)
5539                 strlcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname, sizeof(r_shadow_bufferlight.cubemapname));
5540         else
5541                 r_shadow_bufferlight.cubemapname[0] = 0;
5542         r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
5543         r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
5544         r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
5545         r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
5546         r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
5547         r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
5548         r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
5549 }
5550
5551 void R_Shadow_EditLights_PasteInfo_f(void)
5552 {
5553         if (!r_editlights.integer)
5554         {
5555                 Con_Print("Cannot paste light info when not in editing mode.  Set r_editlights to 1.\n");
5556                 return;
5557         }
5558         if (!r_shadow_selectedlight)
5559         {
5560                 Con_Print("No selected light.\n");
5561                 return;
5562         }
5563         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_bufferlight.angles, r_shadow_bufferlight.color, r_shadow_bufferlight.radius, r_shadow_bufferlight.corona, r_shadow_bufferlight.style, r_shadow_bufferlight.shadow, r_shadow_bufferlight.cubemapname, r_shadow_bufferlight.coronasizescale, r_shadow_bufferlight.ambientscale, r_shadow_bufferlight.diffusescale, r_shadow_bufferlight.specularscale, r_shadow_bufferlight.flags);
5564 }
5565
5566 void R_Shadow_EditLights_Init(void)
5567 {
5568         Cvar_RegisterVariable(&r_editlights);
5569         Cvar_RegisterVariable(&r_editlights_cursordistance);
5570         Cvar_RegisterVariable(&r_editlights_cursorpushback);
5571         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
5572         Cvar_RegisterVariable(&r_editlights_cursorgrid);
5573         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
5574         Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
5575         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
5576         Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f, "reloads rtlights file (or imports from .lights file or .ent file or the map itself)");
5577         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
5578         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
5579         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
5580         Cmd_AddCommand("r_editlights_editall", R_Shadow_EditLights_EditAll_f, "changes a property on ALL lights at once (tip: use radiusscale and colorscale to alter these properties)");
5581         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
5582         Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
5583         Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
5584         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
5585         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
5586         Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
5587         Cmd_AddCommand("r_editlights_pasteinfo", R_Shadow_EditLights_PasteInfo_f, "apply the stored properties onto the selected light (making it exactly identical except for origin)");
5588 }
5589
5590
5591
5592 /*
5593 =============================================================================
5594
5595 LIGHT SAMPLING
5596
5597 =============================================================================
5598 */
5599
5600 void R_CompleteLightPoint(vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const vec3_t p, int dynamic)
5601 {
5602         VectorClear(diffusecolor);
5603         VectorClear(diffusenormal);
5604
5605         if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
5606         {
5607                 ambientcolor[0] = ambientcolor[1] = ambientcolor[2] = r_refdef.scene.ambient * (2.0f / 128.0f);
5608                 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambientcolor, diffusecolor, diffusenormal);
5609         }
5610         else
5611                 VectorSet(ambientcolor, 1, 1, 1);
5612
5613         if (dynamic)
5614         {
5615                 int i;
5616                 float f, v[3];
5617                 rtlight_t *light;
5618                 for (i = 0;i < r_refdef.scene.numlights;i++)
5619                 {
5620                         light = r_refdef.scene.lights[i];
5621                         Matrix4x4_Transform(&light->matrix_worldtolight, p, v);
5622                         f = 1 - VectorLength2(v);
5623                         if (f > 0 && CL_Move(p, vec3_origin, vec3_origin, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction == 1)
5624                                 VectorMA(ambientcolor, f, light->currentcolor, ambientcolor);
5625                 }
5626         }
5627 }