]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - r_shadow.c
0106ca579cef293c45066a9f0d754196d841b524
[xonotic/darkplaces.git] / r_shadow.c
1
2 #include "quakedef.h"
3 #include "r_shadow.h"
4 #include "cl_collision.h"
5 #include "portals.h"
6
7 extern void R_Shadow_EditLights_Init(void);
8
9 #define SHADOWSTAGE_NONE 0
10 #define SHADOWSTAGE_STENCIL 1
11 #define SHADOWSTAGE_LIGHT 2
12 #define SHADOWSTAGE_ERASESTENCIL 3
13
14 int r_shadowstage = SHADOWSTAGE_NONE;
15 int r_shadow_reloadlights = false;
16
17 int r_shadow_lightingmode = 0;
18
19 mempool_t *r_shadow_mempool;
20
21 int maxshadowelements;
22 int *shadowelements;
23 int maxtrianglefacinglight;
24 qbyte *trianglefacinglight;
25
26 rtexturepool_t *r_shadow_texturepool;
27 rtexture_t *r_shadow_normalscubetexture;
28 rtexture_t *r_shadow_attenuation2dtexture;
29 rtexture_t *r_shadow_attenuation3dtexture;
30 rtexture_t *r_shadow_blankbumptexture;
31 rtexture_t *r_shadow_blankglosstexture;
32 rtexture_t *r_shadow_blankwhitetexture;
33
34 cvar_t r_shadow_lightattenuationpower = {0, "r_shadow_lightattenuationpower", "0.5"};
35 cvar_t r_shadow_lightattenuationscale = {0, "r_shadow_lightattenuationscale", "1"};
36 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1"};
37 cvar_t r_shadow_realtime = {0, "r_shadow_realtime", "0"};
38 cvar_t r_shadow_gloss = {0, "r_shadow_gloss", "1"};
39 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1"};
40 cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1"};
41 cvar_t r_shadow_bumpscale_bumpmap = {0, "r_shadow_bumpscale_bumpmap", "4"};
42 cvar_t r_shadow_bumpscale_basetexture = {0, "r_shadow_bumpscale_basetexture", "0"};
43 cvar_t r_shadow_shadownudge = {0, "r_shadow_shadownudge", "1"};
44 cvar_t r_shadow_portallight = {0, "r_shadow_portallight", "1"};
45 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "100000"};
46 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1"};
47
48 int c_rt_lights, c_rt_clears, c_rt_scissored;
49 int c_rt_shadowmeshes, c_rt_shadowtris, c_rt_lightmeshes, c_rt_lighttris;
50 int c_rtcached_shadowmeshes, c_rtcached_shadowtris;
51
52 void R_Shadow_ClearWorldLights(void);
53 void R_Shadow_SaveWorldLights(void);
54 void R_Shadow_LoadWorldLights(void);
55 void R_Shadow_LoadLightsFile(void);
56 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
57
58 void r_shadow_start(void)
59 {
60         // allocate vertex processing arrays
61         r_shadow_mempool = Mem_AllocPool("R_Shadow");
62         maxshadowelements = 0;
63         shadowelements = NULL;
64         maxtrianglefacinglight = 0;
65         trianglefacinglight = NULL;
66         r_shadow_normalscubetexture = NULL;
67         r_shadow_attenuation2dtexture = NULL;
68         r_shadow_attenuation3dtexture = NULL;
69         r_shadow_blankbumptexture = NULL;
70         r_shadow_blankglosstexture = NULL;
71         r_shadow_blankwhitetexture = NULL;
72         r_shadow_texturepool = NULL;
73         R_Shadow_ClearWorldLights();
74         r_shadow_reloadlights = true;
75 }
76
77 void r_shadow_shutdown(void)
78 {
79         R_Shadow_ClearWorldLights();
80         r_shadow_reloadlights = true;
81         r_shadow_normalscubetexture = NULL;
82         r_shadow_attenuation2dtexture = NULL;
83         r_shadow_attenuation3dtexture = NULL;
84         r_shadow_blankbumptexture = NULL;
85         r_shadow_blankglosstexture = NULL;
86         r_shadow_blankwhitetexture = NULL;
87         R_FreeTexturePool(&r_shadow_texturepool);
88         maxshadowelements = 0;
89         shadowelements = NULL;
90         maxtrianglefacinglight = 0;
91         trianglefacinglight = NULL;
92         Mem_FreePool(&r_shadow_mempool);
93 }
94
95 void r_shadow_newmap(void)
96 {
97         R_Shadow_ClearWorldLights();
98         r_shadow_reloadlights = true;
99 }
100
101 void R_Shadow_Init(void)
102 {
103         Cvar_RegisterVariable(&r_shadow_lightattenuationpower);
104         Cvar_RegisterVariable(&r_shadow_lightattenuationscale);
105         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
106         Cvar_RegisterVariable(&r_shadow_realtime);
107         Cvar_RegisterVariable(&r_shadow_gloss);
108         Cvar_RegisterVariable(&r_shadow_debuglight);
109         Cvar_RegisterVariable(&r_shadow_scissor);
110         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
111         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
112         Cvar_RegisterVariable(&r_shadow_shadownudge);
113         Cvar_RegisterVariable(&r_shadow_portallight);
114         Cvar_RegisterVariable(&r_shadow_projectdistance);
115         Cvar_RegisterVariable(&r_shadow_texture3d);
116         R_Shadow_EditLights_Init();
117         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap);
118 }
119
120 void R_Shadow_ProjectVertices(float *verts, int numverts, const float *relativelightorigin, float projectdistance)
121 {
122         int i;
123         float *in, *out, diff[4];
124         in = verts;
125         out = verts + numverts * 4;
126         for (i = 0;i < numverts;i++, in += 4, out += 4)
127         {
128                 VectorSubtract(in, relativelightorigin, diff);
129                 VectorNormalizeFast(diff);
130                 VectorMA(in, projectdistance, diff, out);
131                 VectorMA(in, r_shadow_shadownudge.value, diff, in);
132         }
133 }
134
135 void R_Shadow_MakeTriangleShadowFlags(const int *elements, const float *vertex, int numtris, qbyte *trianglefacinglight, const float *relativelightorigin, float lightradius)
136 {
137         int i;
138         const float *v0, *v1, *v2;
139         for (i = 0;i < numtris;i++, elements += 3)
140         {
141                 // calculate triangle facing flag
142                 v0 = vertex + elements[0] * 4;
143                 v1 = vertex + elements[1] * 4;
144                 v2 = vertex + elements[2] * 4;
145                 // we do not need to normalize the surface normal because both sides
146                 // of the comparison use it, therefore they are both multiplied the
147                 // same amount...  furthermore the subtract can be done on the
148                 // vectors, saving a little bit of math in the dotproducts
149 #if 1
150                 // fast version
151                 // subtracts v1 from v0 and v2, combined into a crossproduct,
152                 // combined with a dotproduct of the light location relative to the
153                 // first point of the triangle (any point works, since the triangle
154                 // is obviously flat), and finally a comparison to determine if the
155                 // light is infront of the triangle (the goal of this statement)
156                 trianglefacinglight[i] =
157                    (relativelightorigin[0] - v0[0]) * ((v0[1] - v1[1]) * (v2[2] - v1[2]) - (v0[2] - v1[2]) * (v2[1] - v1[1]))
158                  + (relativelightorigin[1] - v0[1]) * ((v0[2] - v1[2]) * (v2[0] - v1[0]) - (v0[0] - v1[0]) * (v2[2] - v1[2]))
159                  + (relativelightorigin[2] - v0[2]) * ((v0[0] - v1[0]) * (v2[1] - v1[1]) - (v0[1] - v1[1]) * (v2[0] - v1[0])) > 0;
160 #else
161                 // readable version
162                 {
163                 float dir0[3], dir1[3], temp[3];
164
165                 // calculate two mostly perpendicular edge directions
166                 VectorSubtract(v0, v1, dir0);
167                 VectorSubtract(v2, v1, dir1);
168
169                 // we have two edge directions, we can calculate a third vector from
170                 // them, which is the direction of the surface normal (it's magnitude
171                 // is not 1 however)
172                 CrossProduct(dir0, dir1, temp);
173
174                 // this is entirely unnecessary, but kept for clarity
175                 //VectorNormalize(temp);
176
177                 // compare distance of light along normal, with distance of any point
178                 // of the triangle along the same normal (the triangle is planar,
179                 // I.E. flat, so all points give the same answer)
180                 // the normal is not normalized because it is used on both sides of
181                 // the comparison, so it's magnitude does not matter
182                 trianglefacinglight[i] = DotProduct(relativelightorigin, temp) >= DotProduct(v0, temp);
183                 }
184 #endif
185         }
186 }
187
188 int R_Shadow_BuildShadowVolumeTriangles(const int *elements, const int *neighbors, int numtris, int numverts, const qbyte *trianglefacinglight, int *out)
189 {
190         int i, tris;
191         // check each frontface for bordering backfaces,
192         // and cast shadow polygons from those edges,
193         // also create front and back caps for shadow volume
194         tris = 0;
195         for (i = 0;i < numtris;i++, elements += 3, neighbors += 3)
196         {
197                 if (trianglefacinglight[i])
198                 {
199                         // triangle is frontface and therefore casts shadow,
200                         // output front and back caps for shadow volume
201                         // front cap
202                         out[0] = elements[0];
203                         out[1] = elements[1];
204                         out[2] = elements[2];
205                         // rear cap (with flipped winding order)
206                         out[3] = elements[0] + numverts;
207                         out[4] = elements[2] + numverts;
208                         out[5] = elements[1] + numverts;
209                         out += 6;
210                         tris += 2;
211                         // check the edges
212                         if (neighbors[0] < 0 || !trianglefacinglight[neighbors[0]])
213                         {
214                                 out[0] = elements[1];
215                                 out[1] = elements[0];
216                                 out[2] = elements[0] + numverts;
217                                 out[3] = elements[1];
218                                 out[4] = elements[0] + numverts;
219                                 out[5] = elements[1] + numverts;
220                                 out += 6;
221                                 tris += 2;
222                         }
223                         if (neighbors[1] < 0 || !trianglefacinglight[neighbors[1]])
224                         {
225                                 out[0] = elements[2];
226                                 out[1] = elements[1];
227                                 out[2] = elements[1] + numverts;
228                                 out[3] = elements[2];
229                                 out[4] = elements[1] + numverts;
230                                 out[5] = elements[2] + numverts;
231                                 out += 6;
232                                 tris += 2;
233                         }
234                         if (neighbors[2] < 0 || !trianglefacinglight[neighbors[2]])
235                         {
236                                 out[0] = elements[0];
237                                 out[1] = elements[2];
238                                 out[2] = elements[2] + numverts;
239                                 out[3] = elements[0];
240                                 out[4] = elements[2] + numverts;
241                                 out[5] = elements[0] + numverts;
242                                 out += 6;
243                                 tris += 2;
244                         }
245                 }
246         }
247         return tris;
248 }
249
250 void R_Shadow_ResizeTriangleFacingLight(int numtris)
251 {
252         // make sure trianglefacinglight is big enough for this volume
253         if (maxtrianglefacinglight < numtris)
254         {
255                 maxtrianglefacinglight = numtris;
256                 if (trianglefacinglight)
257                         Mem_Free(trianglefacinglight);
258                 trianglefacinglight = Mem_Alloc(r_shadow_mempool, maxtrianglefacinglight);
259         }
260 }
261
262 void R_Shadow_ResizeShadowElements(int numtris)
263 {
264         // make sure shadowelements is big enough for this volume
265         if (maxshadowelements < numtris * 24)
266         {
267                 maxshadowelements = numtris * 24;
268                 if (shadowelements)
269                         Mem_Free(shadowelements);
270                 shadowelements = Mem_Alloc(r_shadow_mempool, maxshadowelements * sizeof(int));
271         }
272 }
273
274 void R_Shadow_Volume(int numverts, int numtris, int *elements, int *neighbors, vec3_t relativelightorigin, float lightradius, float projectdistance)
275 {
276         int tris;
277         if (projectdistance < 0.1)
278         {
279                 Con_Printf("R_Shadow_Volume: projectdistance %f\n");
280                 return;
281         }
282 // terminology:
283 //
284 // frontface:
285 // a triangle facing the light source
286 //
287 // backface:
288 // a triangle not facing the light source
289 //
290 // shadow volume:
291 // an extrusion of the frontfaces, beginning at the original geometry and
292 // ending further from the light source than the original geometry
293 // (presumably at least as far as the light's radius, if the light has a
294 // radius at all), capped at both front and back to avoid any problems
295 //
296 // description:
297 // draws the shadow volumes of the model.
298 // requirements:
299 // vertex locations must already be in varray_vertex before use.
300 // varray_vertex must have capacity for numverts * 2.
301
302         // make sure trianglefacinglight is big enough for this volume
303         if (maxtrianglefacinglight < numtris)
304                 R_Shadow_ResizeTriangleFacingLight(numtris);
305
306         // make sure shadowelements is big enough for this volume
307         if (maxshadowelements < numtris * 24)
308                 R_Shadow_ResizeShadowElements(numtris);
309
310         // check which triangles are facing the light
311         R_Shadow_MakeTriangleShadowFlags(elements, varray_vertex, numtris, trianglefacinglight, relativelightorigin, lightradius);
312
313         // generate projected vertices
314         // by clever use of elements we'll construct the whole shadow from
315         // the unprojected vertices and these projected vertices
316         R_Shadow_ProjectVertices(varray_vertex, numverts, relativelightorigin, projectdistance);
317
318         // output triangle elements
319         tris = R_Shadow_BuildShadowVolumeTriangles(elements, neighbors, numtris, numverts, trianglefacinglight, shadowelements);
320         R_Shadow_RenderVolume(numverts * 2, tris, shadowelements);
321 }
322
323 void R_Shadow_RenderVolume(int numverts, int numtris, int *elements)
324 {
325         if (!numverts || !numtris)
326                 return;
327         if (r_shadowstage == SHADOWSTAGE_STENCIL)
328         {
329                 // increment stencil if backface is behind depthbuffer
330                 qglCullFace(GL_BACK); // quake is backwards, this culls front faces
331                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
332                 R_Mesh_Draw(numverts, numtris, elements);
333                 c_rt_shadowmeshes++;
334                 c_rt_shadowtris += numtris;
335                 // decrement stencil if frontface is behind depthbuffer
336                 qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
337                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
338         }
339         R_Mesh_Draw(numverts, numtris, elements);
340         c_rt_shadowmeshes++;
341         c_rt_shadowtris += numtris;
342 }
343
344 void R_Shadow_RenderShadowMeshVolume(shadowmesh_t *firstmesh)
345 {
346         shadowmesh_t *mesh;
347         if (r_shadowstage == SHADOWSTAGE_STENCIL)
348         {
349                 // increment stencil if backface is behind depthbuffer
350                 qglCullFace(GL_BACK); // quake is backwards, this culls front faces
351                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
352                 for (mesh = firstmesh;mesh;mesh = mesh->next)
353                 {
354                         R_Mesh_ResizeCheck(mesh->numverts);
355                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
356                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->elements);
357                         c_rtcached_shadowmeshes++;
358                         c_rtcached_shadowtris += mesh->numtriangles;
359                 }
360                 // decrement stencil if frontface is behind depthbuffer
361                 qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
362                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
363         }
364         for (mesh = firstmesh;mesh;mesh = mesh->next)
365         {
366                 R_Mesh_ResizeCheck(mesh->numverts);
367                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
368                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->elements);
369                 c_rtcached_shadowmeshes++;
370                 c_rtcached_shadowtris += mesh->numtriangles;
371         }
372 }
373
374 float r_shadow_attenpower, r_shadow_attenscale;
375 static void R_Shadow_MakeTextures(void)
376 {
377         int x, y, z, d, side;
378         float v[3], s, t, intensity;
379         qbyte *data;
380         R_FreeTexturePool(&r_shadow_texturepool);
381         r_shadow_texturepool = R_AllocTexturePool();
382         r_shadow_attenpower = r_shadow_lightattenuationpower.value;
383         r_shadow_attenscale = r_shadow_lightattenuationscale.value;
384 #define NORMSIZE 64
385 #define ATTEN2DSIZE 64
386 #define ATTEN3DSIZE 32
387         data = Mem_Alloc(tempmempool, max(6*NORMSIZE*NORMSIZE*4, max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE*4, ATTEN2DSIZE*ATTEN2DSIZE*4)));
388         data[0] = 128;
389         data[1] = 128;
390         data[2] = 255;
391         data[3] = 255;
392         r_shadow_blankbumptexture = R_LoadTexture2D(r_shadow_texturepool, "blankbump", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
393         data[0] = 255;
394         data[1] = 255;
395         data[2] = 255;
396         data[3] = 255;
397         r_shadow_blankglosstexture = R_LoadTexture2D(r_shadow_texturepool, "blankgloss", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
398         data[0] = 255;
399         data[1] = 255;
400         data[2] = 255;
401         data[3] = 255;
402         r_shadow_blankwhitetexture = R_LoadTexture2D(r_shadow_texturepool, "blankwhite", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
403         for (side = 0;side < 6;side++)
404         {
405                 for (y = 0;y < NORMSIZE;y++)
406                 {
407                         for (x = 0;x < NORMSIZE;x++)
408                         {
409                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
410                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
411                                 switch(side)
412                                 {
413                                 case 0:
414                                         v[0] = 1;
415                                         v[1] = -t;
416                                         v[2] = -s;
417                                         break;
418                                 case 1:
419                                         v[0] = -1;
420                                         v[1] = -t;
421                                         v[2] = s;
422                                         break;
423                                 case 2:
424                                         v[0] = s;
425                                         v[1] = 1;
426                                         v[2] = t;
427                                         break;
428                                 case 3:
429                                         v[0] = s;
430                                         v[1] = -1;
431                                         v[2] = -t;
432                                         break;
433                                 case 4:
434                                         v[0] = s;
435                                         v[1] = -t;
436                                         v[2] = 1;
437                                         break;
438                                 case 5:
439                                         v[0] = -s;
440                                         v[1] = -t;
441                                         v[2] = -1;
442                                         break;
443                                 }
444                                 intensity = 127.0f / sqrt(DotProduct(v, v));
445                                 data[((side*NORMSIZE+y)*NORMSIZE+x)*4+0] = 128.0f + intensity * v[0];
446                                 data[((side*NORMSIZE+y)*NORMSIZE+x)*4+1] = 128.0f + intensity * v[1];
447                                 data[((side*NORMSIZE+y)*NORMSIZE+x)*4+2] = 128.0f + intensity * v[2];
448                                 data[((side*NORMSIZE+y)*NORMSIZE+x)*4+3] = 255;
449                         }
450                 }
451         }
452         r_shadow_normalscubetexture = R_LoadTextureCubeMap(r_shadow_texturepool, "normalscube", NORMSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
453         for (y = 0;y < ATTEN2DSIZE;y++)
454         {
455                 for (x = 0;x < ATTEN2DSIZE;x++)
456                 {
457                         v[0] = ((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375);
458                         v[1] = ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375);
459                         v[2] = 0;
460                         intensity = 1.0f - sqrt(DotProduct(v, v));
461                         if (intensity > 0)
462                                 intensity = pow(intensity, r_shadow_attenpower) * r_shadow_attenscale * 256.0f;
463                         d = bound(0, intensity, 255);
464                         data[(y*ATTEN2DSIZE+x)*4+0] = d;
465                         data[(y*ATTEN2DSIZE+x)*4+1] = d;
466                         data[(y*ATTEN2DSIZE+x)*4+2] = d;
467                         data[(y*ATTEN2DSIZE+x)*4+3] = d;
468                 }
469         }
470         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
471         if (r_shadow_texture3d.integer)
472         {
473                 for (z = 0;z < ATTEN3DSIZE;z++)
474                 {
475                         for (y = 0;y < ATTEN3DSIZE;y++)
476                         {
477                                 for (x = 0;x < ATTEN3DSIZE;x++)
478                                 {
479                                         v[0] = ((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
480                                         v[1] = ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
481                                         v[2] = ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
482                                         intensity = 1.0f - sqrt(DotProduct(v, v));
483                                         if (intensity > 0)
484                                                 intensity = pow(intensity, r_shadow_attenpower) * r_shadow_attenscale * 256.0f;
485                                         d = bound(0, intensity, 255);
486                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+0] = d;
487                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+1] = d;
488                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+2] = d;
489                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+3] = d;
490                                 }
491                         }
492                 }
493                 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
494         }
495         Mem_Free(data);
496 }
497
498 void R_Shadow_Stage_Begin(void)
499 {
500         rmeshstate_t m;
501
502         if (r_shadow_texture3d.integer && !gl_texture3d)
503                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
504
505         //cl.worldmodel->numlights = min(cl.worldmodel->numlights, 1);
506         if (!r_shadow_attenuation2dtexture
507          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
508          || r_shadow_lightattenuationpower.value != r_shadow_attenpower
509          || r_shadow_lightattenuationscale.value != r_shadow_attenscale)
510                 R_Shadow_MakeTextures();
511         if (r_shadow_reloadlights && cl.worldmodel)
512         {
513                 R_Shadow_ClearWorldLights();
514                 r_shadow_reloadlights = false;
515                 R_Shadow_LoadWorldLights();
516                 if (r_shadow_worldlightchain == NULL)
517                 {
518                         R_Shadow_LoadLightsFile();
519                         if (r_shadow_worldlightchain == NULL)
520                                 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
521                 }
522         }
523
524         memset(&m, 0, sizeof(m));
525         m.blendfunc1 = GL_ONE;
526         m.blendfunc2 = GL_ZERO;
527         R_Mesh_State(&m);
528         GL_Color(0, 0, 0, 1);
529         r_shadowstage = SHADOWSTAGE_NONE;
530
531         c_rt_lights = c_rt_clears = c_rt_scissored = 0;
532         c_rt_shadowmeshes = c_rt_shadowtris = c_rt_lightmeshes = c_rt_lighttris = 0;
533         c_rtcached_shadowmeshes = c_rtcached_shadowtris = 0;
534 }
535
536 void R_Shadow_Stage_ShadowVolumes(void)
537 {
538         rmeshstate_t m;
539         memset(&m, 0, sizeof(m));
540         R_Mesh_TextureState(&m);
541         GL_Color(1, 1, 1, 1);
542         qglColorMask(0, 0, 0, 0);
543         qglDisable(GL_BLEND);
544         qglDepthMask(0);
545         qglDepthFunc(GL_LESS);
546         qglEnable(GL_STENCIL_TEST);
547         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
548         qglStencilFunc(GL_ALWAYS, 128, 0xFF);
549         qglEnable(GL_CULL_FACE);
550         qglEnable(GL_DEPTH_TEST);
551         r_shadowstage = SHADOWSTAGE_STENCIL;
552         qglClear(GL_STENCIL_BUFFER_BIT);
553         c_rt_clears++;
554         // LordHavoc note: many shadow volumes reside entirely inside the world
555         // (that is to say they are entirely bounded by their lit surfaces),
556         // which can be optimized by handling things as an inverted light volume,
557         // with the shadow boundaries of the world being simulated by an altered
558         // (129) bias to stencil clearing on such lights
559         // FIXME: generate inverted light volumes for use as shadow volumes and
560         // optimize for them as noted above
561 }
562
563 void R_Shadow_Stage_LightWithoutShadows(void)
564 {
565         rmeshstate_t m;
566         memset(&m, 0, sizeof(m));
567         R_Mesh_TextureState(&m);
568         qglActiveTexture(GL_TEXTURE0_ARB);
569
570         qglEnable(GL_BLEND);
571         qglBlendFunc(GL_ONE, GL_ONE);
572         GL_Color(1, 1, 1, 1);
573         qglColorMask(1, 1, 1, 1);
574         qglDepthMask(0);
575         qglDepthFunc(GL_EQUAL);
576         qglDisable(GL_STENCIL_TEST);
577         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
578         qglStencilFunc(GL_EQUAL, 128, 0xFF);
579         qglEnable(GL_CULL_FACE);
580         qglEnable(GL_DEPTH_TEST);
581         r_shadowstage = SHADOWSTAGE_LIGHT;
582         c_rt_lights++;
583 }
584
585 void R_Shadow_Stage_LightWithShadows(void)
586 {
587         rmeshstate_t m;
588         memset(&m, 0, sizeof(m));
589         R_Mesh_TextureState(&m);
590         qglActiveTexture(GL_TEXTURE0_ARB);
591
592         qglEnable(GL_BLEND);
593         qglBlendFunc(GL_ONE, GL_ONE);
594         GL_Color(1, 1, 1, 1);
595         qglColorMask(1, 1, 1, 1);
596         qglDepthMask(0);
597         qglDepthFunc(GL_EQUAL);
598         qglEnable(GL_STENCIL_TEST);
599         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
600         // only draw light where this geometry was already rendered AND the
601         // stencil is 128 (values other than this mean shadow)
602         qglStencilFunc(GL_EQUAL, 128, 0xFF);
603         qglEnable(GL_CULL_FACE);
604         qglEnable(GL_DEPTH_TEST);
605         r_shadowstage = SHADOWSTAGE_LIGHT;
606         c_rt_lights++;
607 }
608
609 void R_Shadow_Stage_End(void)
610 {
611         rmeshstate_t m;
612         // attempt to restore state to what Mesh_State thinks it is
613         qglDisable(GL_BLEND);
614         qglBlendFunc(GL_ONE, GL_ZERO);
615         qglDepthMask(1);
616         // now restore the rest of the state to normal
617         GL_Color(1, 1, 1, 1);
618         qglColorMask(1, 1, 1, 1);
619         qglDisable(GL_SCISSOR_TEST);
620         qglDepthFunc(GL_LEQUAL);
621         qglDisable(GL_STENCIL_TEST);
622         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
623         qglStencilFunc(GL_ALWAYS, 128, 0xFF);
624         qglEnable(GL_CULL_FACE);
625         qglEnable(GL_DEPTH_TEST);
626         // force mesh state to reset by using various combinations of features
627         memset(&m, 0, sizeof(m));
628         m.blendfunc1 = GL_SRC_ALPHA;
629         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
630         R_Mesh_State(&m);
631         m.blendfunc1 = GL_ONE;
632         m.blendfunc2 = GL_ZERO;
633         R_Mesh_State(&m);
634         r_shadowstage = SHADOWSTAGE_NONE;
635 }
636
637 #if 0
638 int R_Shadow_ScissorForBBoxAndSphere(const float *mins, const float *maxs, const float *origin, float radius)
639 {
640         int i, ix1, iy1, ix2, iy2;
641         float x1, y1, x2, y2, x, y;
642         vec3_t smins, smaxs;
643         vec4_t v, v2;
644         if (!r_shadow_scissor.integer)
645                 return false;
646         // if view is inside the box, just say yes it's visible
647         if (r_origin[0] >= mins[0] && r_origin[0] <= maxs[0]
648          && r_origin[1] >= mins[1] && r_origin[1] <= maxs[1]
649          && r_origin[2] >= mins[2] && r_origin[2] <= maxs[2])
650         {
651                 qglDisable(GL_SCISSOR_TEST);
652                 return false;
653         }
654         VectorSubtract(r_origin, origin, v);
655         if (DotProduct(v, v) < radius * radius)
656         {
657                 qglDisable(GL_SCISSOR_TEST);
658                 return false;
659         }
660         // create viewspace bbox
661         for (i = 0;i < 8;i++)
662         {
663                 v[0] = ((i & 1) ? mins[0] : maxs[0]) - r_origin[0];
664                 v[1] = ((i & 2) ? mins[1] : maxs[1]) - r_origin[1];
665                 v[2] = ((i & 4) ? mins[2] : maxs[2]) - r_origin[2];
666                 v2[0] = DotProduct(v, vright);
667                 v2[1] = DotProduct(v, vup);
668                 v2[2] = DotProduct(v, vpn);
669                 if (i)
670                 {
671                         if (smins[0] > v2[0]) smins[0] = v2[0];
672                         if (smaxs[0] < v2[0]) smaxs[0] = v2[0];
673                         if (smins[1] > v2[1]) smins[1] = v2[1];
674                         if (smaxs[1] < v2[1]) smaxs[1] = v2[1];
675                         if (smins[2] > v2[2]) smins[2] = v2[2];
676                         if (smaxs[2] < v2[2]) smaxs[2] = v2[2];
677                 }
678                 else
679                 {
680                         smins[0] = smaxs[0] = v2[0];
681                         smins[1] = smaxs[1] = v2[1];
682                         smins[2] = smaxs[2] = v2[2];
683                 }
684         }
685         // now we have a bbox in viewspace
686         // clip it to the viewspace version of the sphere
687         v[0] = origin[0] - r_origin[0];
688         v[1] = origin[1] - r_origin[1];
689         v[2] = origin[2] - r_origin[2];
690         v2[0] = DotProduct(v, vright);
691         v2[1] = DotProduct(v, vup);
692         v2[2] = DotProduct(v, vpn);
693         if (smins[0] < v2[0] - radius) smins[0] = v2[0] - radius;
694         if (smaxs[0] < v2[0] - radius) smaxs[0] = v2[0] + radius;
695         if (smins[1] < v2[1] - radius) smins[1] = v2[1] - radius;
696         if (smaxs[1] < v2[1] - radius) smaxs[1] = v2[1] + radius;
697         if (smins[2] < v2[2] - radius) smins[2] = v2[2] - radius;
698         if (smaxs[2] < v2[2] - radius) smaxs[2] = v2[2] + radius;
699         // clip it to the view plane
700         if (smins[2] < 1)
701                 smins[2] = 1;
702         // return true if that culled the box
703         if (smins[2] >= smaxs[2])
704                 return true;
705         // ok some of it is infront of the view, transform each corner back to
706         // worldspace and then to screenspace and make screen rect
707         // initialize these variables just to avoid compiler warnings
708         x1 = y1 = x2 = y2 = 0;
709         for (i = 0;i < 8;i++)
710         {
711                 v2[0] = (i & 1) ? smins[0] : smaxs[0];
712                 v2[1] = (i & 2) ? smins[1] : smaxs[1];
713                 v2[2] = (i & 4) ? smins[2] : smaxs[2];
714                 v[0] = v2[0] * vright[0] + v2[1] * vup[0] + v2[2] * vpn[0] + r_origin[0];
715                 v[1] = v2[0] * vright[1] + v2[1] * vup[1] + v2[2] * vpn[1] + r_origin[1];
716                 v[2] = v2[0] * vright[2] + v2[1] * vup[2] + v2[2] * vpn[2] + r_origin[2];
717                 v[3] = 1.0f;
718                 GL_TransformToScreen(v, v2);
719                 //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]);
720                 x = v2[0];
721                 y = v2[1];
722                 if (i)
723                 {
724                         if (x1 > x) x1 = x;
725                         if (x2 < x) x2 = x;
726                         if (y1 > y) y1 = y;
727                         if (y2 < y) y2 = y;
728                 }
729                 else
730                 {
731                         x1 = x2 = x;
732                         y1 = y2 = y;
733                 }
734         }
735         /*
736         // this code doesn't handle boxes with any points behind view properly
737         x1 = 1000;x2 = -1000;
738         y1 = 1000;y2 = -1000;
739         for (i = 0;i < 8;i++)
740         {
741                 v[0] = (i & 1) ? mins[0] : maxs[0];
742                 v[1] = (i & 2) ? mins[1] : maxs[1];
743                 v[2] = (i & 4) ? mins[2] : maxs[2];
744                 v[3] = 1.0f;
745                 GL_TransformToScreen(v, v2);
746                 //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]);
747                 if (v2[2] > 0)
748                 {
749                         x = v2[0];
750                         y = v2[1];
751
752                         if (x1 > x) x1 = x;
753                         if (x2 < x) x2 = x;
754                         if (y1 > y) y1 = y;
755                         if (y2 < y) y2 = y;
756                 }
757         }
758         */
759         ix1 = x1 - 1.0f;
760         iy1 = y1 - 1.0f;
761         ix2 = x2 + 1.0f;
762         iy2 = y2 + 1.0f;
763         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
764         if (ix1 < r_refdef.x) ix1 = r_refdef.x;
765         if (iy1 < r_refdef.y) iy1 = r_refdef.y;
766         if (ix2 > r_refdef.x + r_refdef.width) ix2 = r_refdef.x + r_refdef.width;
767         if (iy2 > r_refdef.y + r_refdef.height) iy2 = r_refdef.y + r_refdef.height;
768         if (ix2 <= ix1 || iy2 <= iy1)
769                 return true;
770         // set up the scissor rectangle
771         qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);
772         qglEnable(GL_SCISSOR_TEST);
773         c_rt_scissored++;
774         return false;
775 }
776 #endif
777
778 int R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
779 {
780         int i, ix1, iy1, ix2, iy2;
781         float x1, y1, x2, y2, x, y, f;
782         vec3_t smins, smaxs;
783         vec4_t v, v2;
784         if (!r_shadow_scissor.integer)
785                 return false;
786         // if view is inside the box, just say yes it's visible
787         if (BoxesOverlap(r_origin, r_origin, mins, maxs))
788         {
789                 qglDisable(GL_SCISSOR_TEST);
790                 return false;
791         }
792         for (i = 0;i < 3;i++)
793         {
794                 if (vpn[i] >= 0)
795                 {
796                         v[i] = mins[i];
797                         v2[i] = maxs[i];
798                 }
799                 else
800                 {
801                         v[i] = maxs[i];
802                         v2[i] = mins[i];
803                 }
804         }
805         f = DotProduct(vpn, r_origin) + 1;
806         if (DotProduct(vpn, v2) <= f)
807         {
808                 // entirely behind nearclip plane
809                 qglDisable(GL_SCISSOR_TEST);
810                 return false;
811         }
812         if (DotProduct(vpn, v) >= f)
813         {
814                 // entirely infront of nearclip plane
815                 x1 = y1 = x2 = y2 = 0;
816                 for (i = 0;i < 8;i++)
817                 {
818                         v[0] = (i & 1) ? mins[0] : maxs[0];
819                         v[1] = (i & 2) ? mins[1] : maxs[1];
820                         v[2] = (i & 4) ? mins[2] : maxs[2];
821                         v[3] = 1.0f;
822                         GL_TransformToScreen(v, v2);
823                         //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]);
824                         x = v2[0];
825                         y = v2[1];
826                         if (i)
827                         {
828                                 if (x1 > x) x1 = x;
829                                 if (x2 < x) x2 = x;
830                                 if (y1 > y) y1 = y;
831                                 if (y2 < y) y2 = y;
832                         }
833                         else
834                         {
835                                 x1 = x2 = x;
836                                 y1 = y2 = y;
837                         }
838                 }
839         }
840         else
841         {
842                 // clipped by nearclip plane
843                 // this is nasty and crude...
844                 // create viewspace bbox
845                 for (i = 0;i < 8;i++)
846                 {
847                         v[0] = ((i & 1) ? mins[0] : maxs[0]) - r_origin[0];
848                         v[1] = ((i & 2) ? mins[1] : maxs[1]) - r_origin[1];
849                         v[2] = ((i & 4) ? mins[2] : maxs[2]) - r_origin[2];
850                         v2[0] = DotProduct(v, vright);
851                         v2[1] = DotProduct(v, vup);
852                         v2[2] = DotProduct(v, vpn);
853                         if (i)
854                         {
855                                 if (smins[0] > v2[0]) smins[0] = v2[0];
856                                 if (smaxs[0] < v2[0]) smaxs[0] = v2[0];
857                                 if (smins[1] > v2[1]) smins[1] = v2[1];
858                                 if (smaxs[1] < v2[1]) smaxs[1] = v2[1];
859                                 if (smins[2] > v2[2]) smins[2] = v2[2];
860                                 if (smaxs[2] < v2[2]) smaxs[2] = v2[2];
861                         }
862                         else
863                         {
864                                 smins[0] = smaxs[0] = v2[0];
865                                 smins[1] = smaxs[1] = v2[1];
866                                 smins[2] = smaxs[2] = v2[2];
867                         }
868                 }
869                 // now we have a bbox in viewspace
870                 // clip it to the view plane
871                 if (smins[2] < 1)
872                         smins[2] = 1;
873                 // return true if that culled the box
874                 if (smins[2] >= smaxs[2])
875                         return true;
876                 // ok some of it is infront of the view, transform each corner back to
877                 // worldspace and then to screenspace and make screen rect
878                 // initialize these variables just to avoid compiler warnings
879                 x1 = y1 = x2 = y2 = 0;
880                 for (i = 0;i < 8;i++)
881                 {
882                         v2[0] = (i & 1) ? smins[0] : smaxs[0];
883                         v2[1] = (i & 2) ? smins[1] : smaxs[1];
884                         v2[2] = (i & 4) ? smins[2] : smaxs[2];
885                         v[0] = v2[0] * vright[0] + v2[1] * vup[0] + v2[2] * vpn[0] + r_origin[0];
886                         v[1] = v2[0] * vright[1] + v2[1] * vup[1] + v2[2] * vpn[1] + r_origin[1];
887                         v[2] = v2[0] * vright[2] + v2[1] * vup[2] + v2[2] * vpn[2] + r_origin[2];
888                         v[3] = 1.0f;
889                         GL_TransformToScreen(v, v2);
890                         //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]);
891                         x = v2[0];
892                         y = v2[1];
893                         if (i)
894                         {
895                                 if (x1 > x) x1 = x;
896                                 if (x2 < x) x2 = x;
897                                 if (y1 > y) y1 = y;
898                                 if (y2 < y) y2 = y;
899                         }
900                         else
901                         {
902                                 x1 = x2 = x;
903                                 y1 = y2 = y;
904                         }
905                 }
906                 /*
907                 // this code doesn't handle boxes with any points behind view properly
908                 x1 = 1000;x2 = -1000;
909                 y1 = 1000;y2 = -1000;
910                 for (i = 0;i < 8;i++)
911                 {
912                         v[0] = (i & 1) ? mins[0] : maxs[0];
913                         v[1] = (i & 2) ? mins[1] : maxs[1];
914                         v[2] = (i & 4) ? mins[2] : maxs[2];
915                         v[3] = 1.0f;
916                         GL_TransformToScreen(v, v2);
917                         //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]);
918                         if (v2[2] > 0)
919                         {
920                                 x = v2[0];
921                                 y = v2[1];
922
923                                 if (x1 > x) x1 = x;
924                                 if (x2 < x) x2 = x;
925                                 if (y1 > y) y1 = y;
926                                 if (y2 < y) y2 = y;
927                         }
928                 }
929                 */
930         }
931         ix1 = x1 - 1.0f;
932         iy1 = y1 - 1.0f;
933         ix2 = x2 + 1.0f;
934         iy2 = y2 + 1.0f;
935         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
936         if (ix1 < r_refdef.x) ix1 = r_refdef.x;
937         if (iy1 < r_refdef.y) iy1 = r_refdef.y;
938         if (ix2 > r_refdef.x + r_refdef.width) ix2 = r_refdef.x + r_refdef.width;
939         if (iy2 > r_refdef.y + r_refdef.height) iy2 = r_refdef.y + r_refdef.height;
940         if (ix2 <= ix1 || iy2 <= iy1)
941                 return true;
942         // set up the scissor rectangle
943         qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);
944         qglEnable(GL_SCISSOR_TEST);
945         c_rt_scissored++;
946         return false;
947 }
948
949 // FIXME: this should be done in a vertex program when possible
950 // FIXME: if vertex program not available, this would really benefit from 3DNow! or SSE
951 void R_Shadow_TransformVertices(float *out, int numverts, const float *vertex, const matrix4x4_t *matrix)
952 {
953         do
954         {
955                 Matrix4x4_Transform(matrix, vertex, out);
956                 vertex += 4;
957                 out += 4;
958         }
959         while (--numverts);
960 }
961
962 void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(float *out, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin)
963 {
964         int i;
965         float lightdir[3];
966         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
967         {
968                 VectorSubtract(vertex, relativelightorigin, lightdir);
969                 // the cubemap normalizes this for us
970                 out[0] = DotProduct(svectors, lightdir);
971                 out[1] = DotProduct(tvectors, lightdir);
972                 out[2] = DotProduct(normals, lightdir);
973         }
974 }
975
976 void R_Shadow_GenTexCoords_Specular_NormalCubeMap(float *out, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin, const vec3_t relativeeyeorigin)
977 {
978         int i;
979         float lightdir[3], eyedir[3], halfdir[3];
980         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
981         {
982                 VectorSubtract(vertex, relativelightorigin, lightdir);
983                 VectorNormalizeFast(lightdir);
984                 VectorSubtract(vertex, relativeeyeorigin, eyedir);
985                 VectorNormalizeFast(eyedir);
986                 VectorAdd(lightdir, eyedir, halfdir);
987                 // the cubemap normalizes this for us
988                 out[0] = DotProduct(svectors, halfdir);
989                 out[1] = DotProduct(tvectors, halfdir);
990                 out[2] = DotProduct(normals, halfdir);
991         }
992 }
993
994 void R_Shadow_DiffuseLighting(int numverts, int numtriangles, const int *elements, const float *svectors, const float *tvectors, const float *normals, const float *texcoords, const float *relativelightorigin, float lightradius, const float *lightcolor, const matrix4x4_t *matrix_worldtofilter, const matrix4x4_t *matrix_worldtoattenuationxyz, const matrix4x4_t *matrix_worldtoattenuationz, rtexture_t *basetexture, rtexture_t *bumptexture, rtexture_t *lightcubemap)
995 {
996         int renders;
997         float color[3];
998         rmeshstate_t m;
999         memset(&m, 0, sizeof(m));
1000         if (!bumptexture)
1001                 bumptexture = r_shadow_blankbumptexture;
1002         // colorscale accounts for how much we multiply the brightness during combine
1003         // mult is how many times the final pass of the lighting will be
1004         // performed to get more brightness than otherwise possible
1005         // limit mult to 64 for sanity sake
1006         if (r_shadow_texture3d.integer && r_textureunits.integer >= 4)
1007         {
1008                 // 3/2 3D combine path
1009                 m.tex[0] = R_GetTexture(bumptexture);
1010                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1011                 m.tex3d[2] = R_GetTexture(r_shadow_attenuation3dtexture);
1012                 m.texcombinergb[0] = GL_REPLACE;
1013                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1014                 R_Mesh_TextureState(&m);
1015                 qglColorMask(0,0,0,1);
1016                 qglDisable(GL_BLEND);
1017                 GL_Color(1,1,1,1);
1018                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1019                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
1020                 R_Shadow_TransformVertices(varray_texcoord[2], numverts, varray_vertex, matrix_worldtoattenuationxyz);
1021                 R_Mesh_Draw(numverts, numtriangles, elements);
1022                 c_rt_lightmeshes++;
1023                 c_rt_lighttris += numtriangles;
1024
1025                 m.tex[0] = R_GetTexture(basetexture);
1026                 m.tex[1] = 0;
1027                 m.texcubemap[1] = R_GetTexture(lightcubemap);
1028                 m.tex3d[2] = 0;
1029                 m.texcombinergb[0] = GL_MODULATE;
1030                 m.texcombinergb[1] = GL_MODULATE;
1031                 R_Mesh_TextureState(&m);
1032                 qglColorMask(1,1,1,0);
1033                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1034                 qglEnable(GL_BLEND);
1035                 if (lightcubemap)
1036                         R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtofilter);
1037
1038                 VectorScale(lightcolor, r_colorscale * r_shadow_lightintensityscale.value, color);
1039                 for (renders = 0;renders < 64 && (color[0] > 0 || color[1] > 0 || color[2] > 0);renders++, color[0] = max(0, color[0] - 1.0f), color[1] = max(0, color[1] - 1.0f), color[2] = max(0, color[2] - 1.0f))
1040                 {
1041                         GL_Color(color[0], color[1], color[2], 1);
1042                         R_Mesh_Draw(numverts, numtriangles, elements);
1043                         c_rt_lightmeshes++;
1044                         c_rt_lighttris += numtriangles;
1045                 }
1046         }
1047         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && lightcubemap)
1048         {
1049                 // 1/2/2 3D combine path
1050                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1051                 R_Mesh_TextureState(&m);
1052                 qglColorMask(0,0,0,1);
1053                 qglDisable(GL_BLEND);
1054                 GL_Color(1,1,1,1);
1055                 R_Shadow_TransformVertices(varray_texcoord[0], numverts, varray_vertex, matrix_worldtoattenuationxyz);
1056                 R_Mesh_Draw(numverts, numtriangles, elements);
1057                 c_rt_lightmeshes++;
1058                 c_rt_lighttris += numtriangles;
1059
1060                 m.tex[0] = R_GetTexture(bumptexture);
1061                 m.tex3d[0] = 0;
1062                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1063                 m.texcombinergb[0] = GL_REPLACE;
1064                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1065                 R_Mesh_TextureState(&m);
1066                 qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
1067                 qglEnable(GL_BLEND);
1068                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1069                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
1070                 R_Mesh_Draw(numverts, numtriangles, elements);
1071                 c_rt_lightmeshes++;
1072                 c_rt_lighttris += numtriangles;
1073
1074                 m.tex[0] = R_GetTexture(basetexture);
1075                 m.texcubemap[1] = R_GetTexture(lightcubemap);
1076                 m.texcombinergb[0] = GL_MODULATE;
1077                 m.texcombinergb[1] = GL_MODULATE;
1078                 R_Mesh_TextureState(&m);
1079                 qglColorMask(1,1,1,0);
1080                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1081                 if (lightcubemap)
1082                         R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtofilter);
1083
1084                 VectorScale(lightcolor, r_colorscale * r_shadow_lightintensityscale.value, color);
1085                 for (renders = 0;renders < 64 && (color[0] > 0 || color[1] > 0 || color[2] > 0);renders++, color[0] = max(0, color[0] - 1.0f), color[1] = max(0, color[1] - 1.0f), color[2] = max(0, color[2] - 1.0f))
1086                 {
1087                         GL_Color(color[0], color[1], color[2], 1);
1088                         R_Mesh_Draw(numverts, numtriangles, elements);
1089                         c_rt_lightmeshes++;
1090                         c_rt_lighttris += numtriangles;
1091                 }
1092         }
1093         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && !lightcubemap)
1094         {
1095                 // 2/2 3D combine path
1096                 m.tex[0] = R_GetTexture(bumptexture);
1097                 m.tex3d[0] = 0;
1098                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1099                 m.texcombinergb[0] = GL_REPLACE;
1100                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1101                 R_Mesh_TextureState(&m);
1102                 GL_Color(1,1,1,1);
1103                 qglColorMask(0,0,0,1);
1104                 qglDisable(GL_BLEND);
1105                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1106                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
1107                 R_Mesh_Draw(numverts, numtriangles, elements);
1108                 c_rt_lightmeshes++;
1109                 c_rt_lighttris += numtriangles;
1110
1111                 m.tex[0] = R_GetTexture(basetexture);
1112                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
1113                 m.texcombinergb[0] = GL_MODULATE;
1114                 m.texcombinergb[1] = GL_MODULATE;
1115                 R_Mesh_TextureState(&m);
1116                 qglColorMask(1,1,1,0);
1117                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1118                 qglEnable(GL_BLEND);
1119                 R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtoattenuationxyz);
1120
1121                 VectorScale(lightcolor, r_colorscale * r_shadow_lightintensityscale.value, color);
1122                 for (renders = 0;renders < 64 && (color[0] > 0 || color[1] > 0 || color[2] > 0);renders++, color[0] = max(0, color[0] - 1.0f), color[1] = max(0, color[1] - 1.0f), color[2] = max(0, color[2] - 1.0f))
1123                 {
1124                         GL_Color(color[0], color[1], color[2], 1);
1125                         R_Mesh_Draw(numverts, numtriangles, elements);
1126                         c_rt_lightmeshes++;
1127                         c_rt_lighttris += numtriangles;
1128                 }
1129         }
1130         else if (r_textureunits.integer >= 4)
1131         {
1132                 // 4/2 2D combine path
1133                 m.tex[0] = R_GetTexture(bumptexture);
1134                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1135                 m.texcombinergb[0] = GL_REPLACE;
1136                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1137                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
1138                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
1139                 R_Mesh_TextureState(&m);
1140                 qglColorMask(0,0,0,1);
1141                 qglDisable(GL_BLEND);
1142                 GL_Color(1,1,1,1);
1143                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1144                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
1145                 R_Shadow_TransformVertices(varray_texcoord[2], numverts, varray_vertex, matrix_worldtoattenuationxyz);
1146                 R_Shadow_TransformVertices(varray_texcoord[3], numverts, varray_vertex, matrix_worldtoattenuationz);
1147                 R_Mesh_Draw(numverts, numtriangles, elements);
1148                 c_rt_lightmeshes++;
1149                 c_rt_lighttris += numtriangles;
1150
1151                 m.tex[0] = R_GetTexture(basetexture);
1152                 m.texcubemap[1] = R_GetTexture(lightcubemap);
1153                 m.texcombinergb[0] = GL_MODULATE;
1154                 m.texcombinergb[1] = GL_MODULATE;
1155                 m.tex[2] = 0;
1156                 m.tex[3] = 0;
1157                 R_Mesh_TextureState(&m);
1158                 qglColorMask(1,1,1,0);
1159                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1160                 qglEnable(GL_BLEND);
1161                 if (lightcubemap)
1162                         R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtofilter);
1163
1164                 VectorScale(lightcolor, r_colorscale * r_shadow_lightintensityscale.value, color);
1165                 for (renders = 0;renders < 64 && (color[0] > 0 || color[1] > 0 || color[2] > 0);renders++, color[0] = max(0, color[0] - 1.0f), color[1] = max(0, color[1] - 1.0f), color[2] = max(0, color[2] - 1.0f))
1166                 {
1167                         GL_Color(color[0], color[1], color[2], 1);
1168                         R_Mesh_Draw(numverts, numtriangles, elements);
1169                         c_rt_lightmeshes++;
1170                         c_rt_lighttris += numtriangles;
1171                 }
1172         }
1173         else
1174         {
1175                 // 2/2/2 2D combine path
1176                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1177                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1178                 R_Mesh_TextureState(&m);
1179                 qglColorMask(0,0,0,1);
1180                 qglDisable(GL_BLEND);
1181                 GL_Color(1,1,1,1);
1182                 R_Shadow_TransformVertices(varray_texcoord[0], numverts, varray_vertex, matrix_worldtoattenuationxyz);
1183                 R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtoattenuationz);
1184                 R_Mesh_Draw(numverts, numtriangles, elements);
1185                 c_rt_lightmeshes++;
1186                 c_rt_lighttris += numtriangles;
1187
1188                 m.tex[0] = R_GetTexture(bumptexture);
1189                 m.tex[1] = 0;
1190                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1191                 m.texcombinergb[0] = GL_REPLACE;
1192                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1193                 R_Mesh_TextureState(&m);
1194                 qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
1195                 qglEnable(GL_BLEND);
1196                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1197                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
1198                 R_Mesh_Draw(numverts, numtriangles, elements);
1199                 c_rt_lightmeshes++;
1200                 c_rt_lighttris += numtriangles;
1201
1202                 m.tex[0] = R_GetTexture(basetexture);
1203                 m.texcubemap[1] = R_GetTexture(lightcubemap);
1204                 m.texcombinergb[0] = GL_MODULATE;
1205                 m.texcombinergb[1] = GL_MODULATE;
1206                 R_Mesh_TextureState(&m);
1207                 qglColorMask(1,1,1,0);
1208                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1209                 if (lightcubemap)
1210                         R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtofilter);
1211
1212                 VectorScale(lightcolor, r_colorscale * r_shadow_lightintensityscale.value, color);
1213                 for (renders = 0;renders < 64 && (color[0] > 0 || color[1] > 0 || color[2] > 0);renders++, color[0] = max(0, color[0] - 1.0f), color[1] = max(0, color[1] - 1.0f), color[2] = max(0, color[2] - 1.0f))
1214                 {
1215                         GL_Color(color[0], color[1], color[2], 1);
1216                         R_Mesh_Draw(numverts, numtriangles, elements);
1217                         c_rt_lightmeshes++;
1218                         c_rt_lighttris += numtriangles;
1219                 }
1220         }
1221 }
1222
1223 void R_Shadow_SpecularLighting(int numverts, int numtriangles, const int *elements, const float *svectors, const float *tvectors, const float *normals, const float *texcoords, const float *relativelightorigin, const float *relativeeyeorigin, float lightradius, const float *lightcolor, const matrix4x4_t *matrix_worldtofilter, const matrix4x4_t *matrix_worldtoattenuationxyz, const matrix4x4_t *matrix_worldtoattenuationz, rtexture_t *glosstexture, rtexture_t *bumptexture, rtexture_t *lightcubemap)
1224 {
1225         int renders;
1226         float color[3];
1227         rmeshstate_t m;
1228         memset(&m, 0, sizeof(m));
1229         if (!bumptexture)
1230                 bumptexture = r_shadow_blankbumptexture;
1231         if (!glosstexture)
1232                 glosstexture = r_shadow_blankglosstexture;
1233         if (r_shadow_gloss.integer >= 2 || (r_shadow_gloss.integer >= 1 && glosstexture != r_shadow_blankglosstexture))
1234         {
1235                 if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && lightcubemap /*&& gl_support_blendsquare*/) // FIXME: detect blendsquare!
1236                 {
1237                         // 2/0/0/0/1/2 3D combine blendsquare path
1238                         m.tex[0] = R_GetTexture(bumptexture);
1239                         m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1240                         m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1241                         R_Mesh_TextureState(&m);
1242                         qglColorMask(0,0,0,1);
1243                         qglDisable(GL_BLEND);
1244                         GL_Color(1,1,1,1);
1245                         memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1246                         R_Shadow_GenTexCoords_Specular_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, relativeeyeorigin);
1247                         R_Mesh_Draw(numverts, numtriangles, elements);
1248                         c_rt_lightmeshes++;
1249                         c_rt_lighttris += numtriangles;
1250
1251                         m.tex[0] = 0;
1252                         m.texcubemap[1] = 0;
1253                         m.texcombinergb[1] = GL_MODULATE;
1254                         R_Mesh_TextureState(&m);
1255                         // square alpha in framebuffer a few times to make it shiny
1256                         qglBlendFunc(GL_ZERO, GL_DST_ALPHA);
1257                         qglEnable(GL_BLEND);
1258                         // these comments are a test run through this math for intensity 0.5
1259                         // 0.5 * 0.5 = 0.25
1260                         R_Mesh_Draw(numverts, numtriangles, elements);
1261                         c_rt_lightmeshes++;
1262                         c_rt_lighttris += numtriangles;
1263                         // 0.25 * 0.25 = 0.0625
1264                         R_Mesh_Draw(numverts, numtriangles, elements);
1265                         c_rt_lightmeshes++;
1266                         c_rt_lighttris += numtriangles;
1267                         // 0.0625 * 0.0625 = 0.00390625
1268                         R_Mesh_Draw(numverts, numtriangles, elements);
1269                         c_rt_lightmeshes++;
1270                         c_rt_lighttris += numtriangles;
1271
1272                         m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1273                         R_Mesh_TextureState(&m);
1274                         qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
1275                         R_Shadow_TransformVertices(varray_texcoord[0], numverts, varray_vertex, matrix_worldtoattenuationxyz);
1276                         R_Mesh_Draw(numverts, numtriangles, elements);
1277                         c_rt_lightmeshes++;
1278                         c_rt_lighttris += numtriangles;
1279
1280                         m.tex3d[0] = 0;
1281                         m.tex[0] = R_GetTexture(glosstexture);
1282                         m.texcubemap[1] = R_GetTexture(lightcubemap);
1283                         R_Mesh_TextureState(&m);
1284                         qglColorMask(1,1,1,0);
1285                         qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1286                         memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1287                         if (lightcubemap)
1288                                 R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtofilter);
1289
1290                         VectorScale(lightcolor, r_colorscale * r_shadow_lightintensityscale.value * 0.25f, color);
1291                         for (renders = 0;renders < 64 && (color[0] > 0 || color[1] > 0 || color[2] > 0);renders++, color[0] = max(0, color[0] - 1.0f), color[1] = max(0, color[1] - 1.0f), color[2] = max(0, color[2] - 1.0f))
1292                         {
1293                                 GL_Color(color[0], color[1], color[2], 1);
1294                                 R_Mesh_Draw(numverts, numtriangles, elements);
1295                                 c_rt_lightmeshes++;
1296                                 c_rt_lighttris += numtriangles;
1297                         }
1298                 }
1299                 else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && !lightcubemap /*&& gl_support_blendsquare*/) // FIXME: detect blendsquare!
1300                 {
1301                         // 2/0/0/0/2 3D combine blendsquare path
1302                         m.tex[0] = R_GetTexture(bumptexture);
1303                         m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1304                         m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1305                         R_Mesh_TextureState(&m);
1306                         qglColorMask(0,0,0,1);
1307                         qglDisable(GL_BLEND);
1308                         GL_Color(1,1,1,1);
1309                         memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1310                         R_Shadow_GenTexCoords_Specular_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, relativeeyeorigin);
1311                         R_Mesh_Draw(numverts, numtriangles, elements);
1312                         c_rt_lightmeshes++;
1313                         c_rt_lighttris += numtriangles;
1314
1315                         m.tex[0] = 0;
1316                         m.texcubemap[1] = 0;
1317                         m.texcombinergb[1] = GL_MODULATE;
1318                         R_Mesh_TextureState(&m);
1319                         // square alpha in framebuffer a few times to make it shiny
1320                         qglBlendFunc(GL_ZERO, GL_DST_ALPHA);
1321                         qglEnable(GL_BLEND);
1322                         // these comments are a test run through this math for intensity 0.5
1323                         // 0.5 * 0.5 = 0.25
1324                         R_Mesh_Draw(numverts, numtriangles, elements);
1325                         c_rt_lightmeshes++;
1326                         c_rt_lighttris += numtriangles;
1327                         // 0.25 * 0.25 = 0.0625
1328                         R_Mesh_Draw(numverts, numtriangles, elements);
1329                         c_rt_lightmeshes++;
1330                         c_rt_lighttris += numtriangles;
1331                         // 0.0625 * 0.0625 = 0.00390625
1332                         R_Mesh_Draw(numverts, numtriangles, elements);
1333                         c_rt_lightmeshes++;
1334                         c_rt_lighttris += numtriangles;
1335
1336                         m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1337                         m.tex[1] = R_GetTexture(glosstexture);
1338                         R_Mesh_TextureState(&m);
1339                         R_Shadow_TransformVertices(varray_texcoord[0], numverts, varray_vertex, matrix_worldtoattenuationxyz);
1340                         memcpy(varray_texcoord[1], texcoords, numverts * sizeof(float[4]));
1341                         qglColorMask(1,1,1,0);
1342                         qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1343                         R_Mesh_Draw(numverts, numtriangles, elements);
1344                         c_rt_lightmeshes++;
1345                         c_rt_lighttris += numtriangles;
1346
1347                         VectorScale(lightcolor, r_colorscale * r_shadow_lightintensityscale.value * 0.25f, color);
1348                         for (renders = 0;renders < 64 && (color[0] > 0 || color[1] > 0 || color[2] > 0);renders++, color[0] = max(0, color[0] - 1.0f), color[1] = max(0, color[1] - 1.0f), color[2] = max(0, color[2] - 1.0f))
1349                         {
1350                                 GL_Color(color[0], color[1], color[2], 1);
1351                                 R_Mesh_Draw(numverts, numtriangles, elements);
1352                                 c_rt_lightmeshes++;
1353                                 c_rt_lighttris += numtriangles;
1354                         }
1355                 }
1356                 else if (r_textureunits.integer >= 2 /*&& gl_support_blendsquare*/) // FIXME: detect blendsquare!
1357                 {
1358                         // 2/0/0/0/2/2 2D combine blendsquare path
1359                         m.tex[0] = R_GetTexture(bumptexture);
1360                         m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1361                         m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1362                         R_Mesh_TextureState(&m);
1363                         qglColorMask(0,0,0,1);
1364                         qglDisable(GL_BLEND);
1365                         GL_Color(1,1,1,1);
1366                         memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1367                         R_Shadow_GenTexCoords_Specular_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, relativeeyeorigin);
1368                         R_Mesh_Draw(numverts, numtriangles, elements);
1369                         c_rt_lightmeshes++;
1370                         c_rt_lighttris += numtriangles;
1371
1372                         m.tex[0] = 0;
1373                         m.texcubemap[1] = 0;
1374                         m.texcombinergb[1] = GL_MODULATE;
1375                         R_Mesh_TextureState(&m);
1376                         // square alpha in framebuffer a few times to make it shiny
1377                         qglBlendFunc(GL_ZERO, GL_DST_ALPHA);
1378                         qglEnable(GL_BLEND);
1379                         // these comments are a test run through this math for intensity 0.5
1380                         // 0.5 * 0.5 = 0.25
1381                         R_Mesh_Draw(numverts, numtriangles, elements);
1382                         c_rt_lightmeshes++;
1383                         c_rt_lighttris += numtriangles;
1384                         // 0.25 * 0.25 = 0.0625
1385                         R_Mesh_Draw(numverts, numtriangles, elements);
1386                         c_rt_lightmeshes++;
1387                         c_rt_lighttris += numtriangles;
1388                         // 0.0625 * 0.0625 = 0.00390625
1389                         R_Mesh_Draw(numverts, numtriangles, elements);
1390                         c_rt_lightmeshes++;
1391                         c_rt_lighttris += numtriangles;
1392
1393                         m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1394                         m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1395                         R_Mesh_TextureState(&m);
1396                         qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
1397                         R_Shadow_TransformVertices(varray_texcoord[0], numverts, varray_vertex, matrix_worldtoattenuationxyz);
1398                         R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtoattenuationz);
1399                         R_Mesh_Draw(numverts, numtriangles, elements);
1400                         c_rt_lightmeshes++;
1401                         c_rt_lighttris += numtriangles;
1402
1403                         m.tex[0] = R_GetTexture(glosstexture);
1404                         m.texcubemap[1] = R_GetTexture(lightcubemap);
1405                         R_Mesh_TextureState(&m);
1406                         qglColorMask(1,1,1,0);
1407                         qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1408                         memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1409                         if (lightcubemap)
1410                                 R_Shadow_TransformVertices(varray_texcoord[1], numverts, varray_vertex, matrix_worldtofilter);
1411
1412                         VectorScale(lightcolor, r_colorscale * r_shadow_lightintensityscale.value * 0.25f, color);
1413                         for (renders = 0;renders < 64 && (color[0] > 0 || color[1] > 0 || color[2] > 0);renders++, color[0] = max(0, color[0] - 1.0f), color[1] = max(0, color[1] - 1.0f), color[2] = max(0, color[2] - 1.0f))
1414                         {
1415                                 GL_Color(color[0], color[1], color[2], 1);
1416                                 R_Mesh_Draw(numverts, numtriangles, elements);
1417                                 c_rt_lightmeshes++;
1418                                 c_rt_lighttris += numtriangles;
1419                         }
1420                 }
1421         }
1422 }
1423
1424 void R_Shadow_DrawWorldLightShadowVolume(matrix4x4_t *matrix, worldlight_t *light)
1425 {
1426         R_Mesh_Matrix(matrix);
1427         R_Shadow_RenderShadowMeshVolume(light->shadowvolume);
1428 }
1429
1430 cvar_t r_editlights = {0, "r_editlights", "0"};
1431 cvar_t r_editlights_cursordistance = {0, "r_editlights_distance", "1024"};
1432 cvar_t r_editlights_cursorpushback = {0, "r_editlights_pushback", "0"};
1433 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_pushoff", "4"};
1434 cvar_t r_editlights_cursorgrid = {0, "r_editlights_grid", "4"};
1435 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "0.8"};
1436 cvar_t r_editlights_rtlightssizescale = {CVAR_SAVE, "r_editlights_rtlightssizescale", "0.7"};
1437 cvar_t r_editlights_rtlightscolorscale = {CVAR_SAVE, "r_editlights_rtlightscolorscale", "2"};
1438 worldlight_t *r_shadow_worldlightchain;
1439 worldlight_t *r_shadow_selectedlight;
1440 vec3_t r_editlights_cursorlocation;
1441
1442 static int castshadowcount = 1;
1443 void R_Shadow_NewWorldLight(vec3_t origin, float radius, vec3_t color, int style, const char *cubemapname, int castshadow)
1444 {
1445         int i, j, k, l, maxverts, *mark, tris;
1446         float *verts;
1447         worldlight_t *e;
1448         shadowmesh_t *mesh, *castmesh;
1449         mleaf_t *leaf;
1450         msurface_t *surf;
1451         qbyte *pvs;
1452         surfmesh_t *surfmesh;
1453
1454         if (radius < 15 || DotProduct(color, color) < 0.03)
1455         {
1456                 Con_Printf("R_Shadow_NewWorldLight: refusing to create a light too small/dim\n");
1457                 return;
1458         }
1459
1460         e = Mem_Alloc(r_shadow_mempool, sizeof(worldlight_t));
1461         VectorCopy(origin, e->origin);
1462         VectorCopy(color, e->light);
1463         e->lightradius = radius;
1464         e->style = style;
1465         if (e->style < 0 || e->style >= MAX_LIGHTSTYLES)
1466         {
1467                 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", e->style, MAX_LIGHTSTYLES);
1468                 e->style = 0;
1469         }
1470         e->castshadows = castshadow;
1471
1472         e->cullradius = e->lightradius;
1473         for (k = 0;k < 3;k++)
1474         {
1475                 e->mins[k] = e->origin[k] - e->lightradius;
1476                 e->maxs[k] = e->origin[k] + e->lightradius;
1477         }
1478
1479         e->next = r_shadow_worldlightchain;
1480         r_shadow_worldlightchain = e;
1481         if (cubemapname && cubemapname[0])
1482         {
1483                 e->cubemapname = Mem_Alloc(r_shadow_mempool, strlen(cubemapname) + 1);
1484                 strcpy(e->cubemapname, cubemapname);
1485                 // FIXME: add cubemap loading (and don't load a cubemap twice)
1486         }
1487         if (cl.worldmodel)
1488         {
1489                 castshadowcount++;
1490                 i = Mod_PointContents(e->origin, cl.worldmodel);
1491                 if (r_shadow_portallight.integer && i != CONTENTS_SOLID && i != CONTENTS_SKY)
1492                 {
1493                         qbyte *byteleafpvs;
1494                         qbyte *bytesurfacepvs;
1495
1496                         byteleafpvs = Mem_Alloc(tempmempool, cl.worldmodel->numleafs + 1);
1497                         bytesurfacepvs = Mem_Alloc(tempmempool, cl.worldmodel->numsurfaces);
1498
1499                         Portal_Visibility(cl.worldmodel, e->origin, byteleafpvs, bytesurfacepvs, NULL, 0, true, RadiusFromBoundsAndOrigin(e->mins, e->maxs, e->origin));
1500
1501                         for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1502                                 if (byteleafpvs[i+1] && BoxesOverlap(leaf->mins, leaf->maxs, e->mins, e->maxs))
1503                                         leaf->worldnodeframe = castshadowcount;
1504
1505                         for (i = 0, surf = cl.worldmodel->surfaces;i < cl.worldmodel->numsurfaces;i++, surf++)
1506                                 if (bytesurfacepvs[i] && BoxesOverlap(surf->poly_mins, surf->poly_maxs, e->mins, e->maxs))
1507                                         surf->castshadow = castshadowcount;
1508
1509                         Mem_Free(byteleafpvs);
1510                         Mem_Free(bytesurfacepvs);
1511                 }
1512                 else
1513                 {
1514                         leaf = Mod_PointInLeaf(origin, cl.worldmodel);
1515                         pvs = Mod_LeafPVS(leaf, cl.worldmodel);
1516                         for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1517                         {
1518                                 if (pvs[i >> 3] & (1 << (i & 7)) && BoxesOverlap(leaf->mins, leaf->maxs, e->mins, e->maxs))
1519                                 {
1520                                         leaf->worldnodeframe = castshadowcount;
1521                                         for (j = 0, mark = leaf->firstmarksurface;j < leaf->nummarksurfaces;j++, mark++)
1522                                         {
1523                                                 surf = cl.worldmodel->surfaces + *mark;
1524                                                 if (surf->castshadow != castshadowcount && BoxesOverlap(surf->poly_mins, surf->poly_maxs, e->mins, e->maxs))
1525                                                         surf->castshadow = castshadowcount;
1526                                         }
1527                                 }
1528                         }
1529                 }
1530
1531                 e->numleafs = 0;
1532                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1533                         if (leaf->worldnodeframe == castshadowcount)
1534                                 e->numleafs++;
1535                 e->numsurfaces = 0;
1536                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1537                         if (surf->castshadow == castshadowcount)
1538                                 e->numsurfaces++;
1539
1540                 if (e->numleafs)
1541                         e->leafs = Mem_Alloc(r_shadow_mempool, e->numleafs * sizeof(mleaf_t *));
1542                 if (e->numsurfaces)
1543                         e->surfaces = Mem_Alloc(r_shadow_mempool, e->numsurfaces * sizeof(msurface_t *));
1544                 e->numleafs = 0;
1545                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1546                         if (leaf->worldnodeframe == castshadowcount)
1547                                 e->leafs[e->numleafs++] = leaf;
1548                 e->numsurfaces = 0;
1549                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1550                         if (surf->castshadow == castshadowcount)
1551                                 e->surfaces[e->numsurfaces++] = surf;
1552
1553                 // find bounding box of lit leafs
1554                 VectorCopy(e->origin, e->mins);
1555                 VectorCopy(e->origin, e->maxs);
1556                 for (j = 0;j < e->numleafs;j++)
1557                 {
1558                         leaf = e->leafs[j];
1559                         for (k = 0;k < 3;k++)
1560                         {
1561                                 if (e->mins[k] > leaf->mins[k]) e->mins[k] = leaf->mins[k];
1562                                 if (e->maxs[k] < leaf->maxs[k]) e->maxs[k] = leaf->maxs[k];
1563                         }
1564                 }
1565
1566                 for (k = 0;k < 3;k++)
1567                 {
1568                         if (e->mins[k] < e->origin[k] - e->lightradius) e->mins[k] = e->origin[k] - e->lightradius;
1569                         if (e->maxs[k] > e->origin[k] + e->lightradius) e->maxs[k] = e->origin[k] + e->lightradius;
1570                 }
1571                 e->cullradius = RadiusFromBoundsAndOrigin(e->mins, e->maxs, e->origin);
1572
1573                 if (e->castshadows)
1574                 {
1575                         maxverts = 256;
1576                         verts = NULL;
1577                         castshadowcount++;
1578                         for (j = 0;j < e->numsurfaces;j++)
1579                         {
1580                                 surf = e->surfaces[j];
1581                                 if (surf->flags & SURF_SHADOWCAST)
1582                                 {
1583                                         surf->castshadow = castshadowcount;
1584                                         if (maxverts < surf->poly_numverts)
1585                                                 maxverts = surf->poly_numverts;
1586                                 }
1587                         }
1588                         e->shadowvolume = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1589                         // make a mesh to cast a shadow volume from
1590                         castmesh = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1591                         for (j = 0;j < e->numsurfaces;j++)
1592                                 if (e->surfaces[j]->castshadow == castshadowcount)
1593                                         for (surfmesh = e->surfaces[j]->mesh;surfmesh;surfmesh = surfmesh->chain)
1594                                                 Mod_ShadowMesh_AddMesh(r_shadow_mempool, castmesh, surfmesh->numverts, surfmesh->verts, surfmesh->numtriangles, surfmesh->index);
1595                         castmesh = Mod_ShadowMesh_Finish(r_shadow_mempool, castmesh);
1596
1597                         // cast shadow volume from castmesh
1598                         for (mesh = castmesh;mesh;mesh = mesh->next)
1599                         {
1600                                 R_Shadow_ResizeTriangleFacingLight(castmesh->numtriangles);
1601                                 R_Shadow_ResizeShadowElements(castmesh->numtriangles);
1602
1603                                 if (maxverts < castmesh->numverts * 2)
1604                                 {
1605                                         maxverts = castmesh->numverts * 2;
1606                                         if (verts)
1607                                                 Mem_Free(verts);
1608                                         verts = NULL;
1609                                 }
1610                                 if (verts == NULL && maxverts > 0)
1611                                         verts = Mem_Alloc(r_shadow_mempool, maxverts * sizeof(float[4]));
1612
1613                                 // now that we have the buffers big enough, construct shadow volume mesh
1614                                 memcpy(verts, castmesh->verts, castmesh->numverts * sizeof(float[4]));
1615                                 R_Shadow_ProjectVertices(verts, castmesh->numverts, e->origin, r_shadow_projectdistance.value);//, e->lightradius);
1616                                 R_Shadow_MakeTriangleShadowFlags(castmesh->elements, verts, castmesh->numtriangles, trianglefacinglight, e->origin, e->lightradius);
1617                                 tris = R_Shadow_BuildShadowVolumeTriangles(castmesh->elements, castmesh->neighbors, castmesh->numtriangles, castmesh->numverts, trianglefacinglight, shadowelements);
1618                                 // add the constructed shadow volume mesh
1619                                 Mod_ShadowMesh_AddMesh(r_shadow_mempool, e->shadowvolume, castmesh->numverts, verts, tris, shadowelements);
1620                         }
1621                         // we're done with castmesh now
1622                         Mod_ShadowMesh_Free(castmesh);
1623                         e->shadowvolume = Mod_ShadowMesh_Finish(r_shadow_mempool, e->shadowvolume);
1624                         for (l = 0, mesh = e->shadowvolume;mesh;mesh = mesh->next)
1625                                 l += mesh->numtriangles;
1626                         Con_Printf("static shadow volume built containing %i triangles\n", l);
1627                 }
1628         }
1629         Con_Printf("%f %f %f, %f %f %f, %f, %f, %d, %d\n", e->mins[0], e->mins[1], e->mins[2], e->maxs[0], e->maxs[1], e->maxs[2], e->cullradius, e->lightradius, e->numleafs, e->numsurfaces);
1630 }
1631
1632 void R_Shadow_FreeWorldLight(worldlight_t *light)
1633 {
1634         worldlight_t **lightpointer;
1635         for (lightpointer = &r_shadow_worldlightchain;*lightpointer && *lightpointer != light;lightpointer = &(*lightpointer)->next);
1636         if (*lightpointer != light)
1637                 Sys_Error("R_Shadow_FreeWorldLight: light not linked into chain\n");
1638         *lightpointer = light->next;
1639         if (light->cubemapname)
1640                 Mem_Free(light->cubemapname);
1641         if (light->shadowvolume)
1642                 Mod_ShadowMesh_Free(light->shadowvolume);
1643         if (light->surfaces)
1644                 Mem_Free(light->surfaces);
1645         if (light->leafs)
1646                 Mem_Free(light->leafs);
1647         Mem_Free(light);
1648 }
1649
1650 void R_Shadow_ClearWorldLights(void)
1651 {
1652         while (r_shadow_worldlightchain)
1653                 R_Shadow_FreeWorldLight(r_shadow_worldlightchain);
1654         r_shadow_selectedlight = NULL;
1655 }
1656
1657 void R_Shadow_SelectLight(worldlight_t *light)
1658 {
1659         if (r_shadow_selectedlight)
1660                 r_shadow_selectedlight->selected = false;
1661         r_shadow_selectedlight = light;
1662         if (r_shadow_selectedlight)
1663                 r_shadow_selectedlight->selected = true;
1664 }
1665
1666
1667 void R_DrawLightSprite(int texnum, const vec3_t origin, vec_t scale, float cr, float cg, float cb, float ca)
1668 {
1669         rmeshstate_t m;
1670         float diff[3];
1671
1672         if (fogenabled)
1673         {
1674                 VectorSubtract(origin, r_origin, diff);
1675                 ca *= 1 - exp(fogdensity/DotProduct(diff,diff));
1676         }
1677
1678         memset(&m, 0, sizeof(m));
1679         m.blendfunc1 = GL_SRC_ALPHA;
1680         m.blendfunc2 = GL_ONE;
1681         m.tex[0] = texnum;
1682         R_Mesh_Matrix(&r_identitymatrix);
1683         R_Mesh_State(&m);
1684
1685         GL_Color(cr * r_colorscale, cg * r_colorscale, cb * r_colorscale, ca);
1686         varray_texcoord[0][ 0] = 0;varray_texcoord[0][ 1] = 0;
1687         varray_texcoord[0][ 4] = 0;varray_texcoord[0][ 5] = 1;
1688         varray_texcoord[0][ 8] = 1;varray_texcoord[0][ 9] = 1;
1689         varray_texcoord[0][12] = 1;varray_texcoord[0][13] = 0;
1690         varray_vertex[0] = origin[0] - vright[0] * scale - vup[0] * scale;
1691         varray_vertex[1] = origin[1] - vright[1] * scale - vup[1] * scale;
1692         varray_vertex[2] = origin[2] - vright[2] * scale - vup[2] * scale;
1693         varray_vertex[4] = origin[0] - vright[0] * scale + vup[0] * scale;
1694         varray_vertex[5] = origin[1] - vright[1] * scale + vup[1] * scale;
1695         varray_vertex[6] = origin[2] - vright[2] * scale + vup[2] * scale;
1696         varray_vertex[8] = origin[0] + vright[0] * scale + vup[0] * scale;
1697         varray_vertex[9] = origin[1] + vright[1] * scale + vup[1] * scale;
1698         varray_vertex[10] = origin[2] + vright[2] * scale + vup[2] * scale;
1699         varray_vertex[12] = origin[0] + vright[0] * scale - vup[0] * scale;
1700         varray_vertex[13] = origin[1] + vright[1] * scale - vup[1] * scale;
1701         varray_vertex[14] = origin[2] + vright[2] * scale - vup[2] * scale;
1702         R_Mesh_Draw(4, 2, polygonelements);
1703 }
1704
1705 void R_Shadow_DrawCursorCallback(const void *calldata1, int calldata2)
1706 {
1707         cachepic_t *pic;
1708         pic = Draw_CachePic("gfx/crosshair1.tga");
1709         if (pic)
1710                 R_DrawLightSprite(R_GetTexture(pic->tex), r_editlights_cursorlocation, r_editlights_cursorgrid.value * 0.5f, 1, 1, 1, 0.5);
1711 }
1712
1713 void R_Shadow_DrawLightSpriteCallback(const void *calldata1, int calldata2)
1714 {
1715         float intensity;
1716         const worldlight_t *light;
1717         light = calldata1;
1718         intensity = 0.5;
1719         if (light->selected)
1720                 intensity = 0.75 + 0.25 * sin(realtime * M_PI * 4.0);
1721         if (light->shadowvolume)
1722                 R_DrawLightSprite(calldata2, light->origin, 8, intensity, intensity, intensity, 0.5);
1723         else
1724                 R_DrawLightSprite(calldata2, light->origin, 8, intensity * 0.5, intensity * 0.5, intensity * 0.5, 0.5);
1725 }
1726
1727 void R_Shadow_DrawLightSprites(void)
1728 {
1729         int i, texnums[5];
1730         cachepic_t *pic;
1731         worldlight_t *light;
1732
1733         for (i = 0;i < 5;i++)
1734         {
1735                 pic = Draw_CachePic(va("gfx/crosshair%i.tga", i + 1));
1736                 if (pic)
1737                         texnums[i] = R_GetTexture(pic->tex);
1738                 else
1739                         texnums[i] = 0;
1740         }
1741
1742         for (light = r_shadow_worldlightchain;light;light = light->next)
1743                 R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSpriteCallback, light, texnums[((int) light) % 5]);
1744         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursorCallback, NULL, 0);
1745 }
1746
1747 void R_Shadow_SelectLightInView(void)
1748 {
1749         float bestrating, rating, temp[3];
1750         worldlight_t *best, *light;
1751         best = NULL;
1752         bestrating = 0;
1753         for (light = r_shadow_worldlightchain;light;light = light->next)
1754         {
1755                 VectorSubtract(light->origin, r_refdef.vieworg, temp);
1756                 rating = (DotProduct(temp, vpn) / sqrt(DotProduct(temp, temp)));
1757                 if (rating >= 0.95)
1758                 {
1759                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
1760                         if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.vieworg, NULL, NULL, 0, true, NULL) == 1.0f)
1761                         {
1762                                 bestrating = rating;
1763                                 best = light;
1764                         }
1765                 }
1766         }
1767         R_Shadow_SelectLight(best);
1768 }
1769
1770 void R_Shadow_LoadWorldLights(void)
1771 {
1772         int n, a, style, shadow;
1773         char name[MAX_QPATH], cubemapname[MAX_QPATH], *lightsstring, *s, *t;
1774         float origin[3], radius, color[3];
1775         if (cl.worldmodel == NULL)
1776         {
1777                 Con_Printf("No map loaded.\n");
1778                 return;
1779         }
1780         COM_StripExtension(cl.worldmodel->name, name);
1781         strcat(name, ".rtlights");
1782         lightsstring = COM_LoadFile(name, false);
1783         if (lightsstring)
1784         {
1785                 s = lightsstring;
1786                 n = 0;
1787                 while (*s)
1788                 {
1789                         t = s;
1790                         while (*s && *s != '\n')
1791                                 s++;
1792                         if (!*s)
1793                                 break;
1794                         *s = 0;
1795                         shadow = true;
1796                         // check for modifier flags
1797                         if (*t == '!')
1798                         {
1799                                 shadow = false;
1800                                 t++;
1801                         }
1802                         a = sscanf(t, "%f %f %f %f %f %f %f %d %s", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, cubemapname);
1803                         if (a < 9)
1804                                 cubemapname[0] = 0;
1805                         *s = '\n';
1806                         if (a < 8)
1807                         {
1808                                 Con_Printf("found %d parameters on line %i, should be 8 or 9 parameters (origin[0] origin[1] origin[2] radius color[0] color[1] color[2] style cubemapname)\n", a, n + 1);
1809                                 break;
1810                         }
1811                         VectorScale(color, r_editlights_rtlightscolorscale.value, color);
1812                         radius *= r_editlights_rtlightssizescale.value;
1813                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname, shadow);
1814                         s++;
1815                         n++;
1816                 }
1817                 if (*s)
1818                         Con_Printf("invalid rtlights file \"%s\"\n", name);
1819                 Mem_Free(lightsstring);
1820         }
1821 }
1822
1823 void R_Shadow_SaveWorldLights(void)
1824 {
1825         worldlight_t *light;
1826         int bufchars, bufmaxchars;
1827         char *buf, *oldbuf;
1828         char name[MAX_QPATH];
1829         char line[1024];
1830         if (!r_shadow_worldlightchain)
1831                 return;
1832         if (cl.worldmodel == NULL)
1833         {
1834                 Con_Printf("No map loaded.\n");
1835                 return;
1836         }
1837         COM_StripExtension(cl.worldmodel->name, name);
1838         strcat(name, ".rtlights");
1839         bufchars = bufmaxchars = 0;
1840         buf = NULL;
1841         for (light = r_shadow_worldlightchain;light;light = light->next)
1842         {
1843                 sprintf(line, "%s%g %g %g %g %g %g %g %d %s\n", light->castshadows ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->lightradius / r_editlights_rtlightssizescale.value, light->light[0] / r_editlights_rtlightscolorscale.value, light->light[1] / r_editlights_rtlightscolorscale.value, light->light[2] / r_editlights_rtlightscolorscale.value, light->style, light->cubemapname ? light->cubemapname : "");
1844                 if (bufchars + strlen(line) > bufmaxchars)
1845                 {
1846                         bufmaxchars = bufchars + strlen(line) + 2048;
1847                         oldbuf = buf;
1848                         buf = Mem_Alloc(r_shadow_mempool, bufmaxchars);
1849                         if (oldbuf)
1850                         {
1851                                 if (bufchars)
1852                                         memcpy(buf, oldbuf, bufchars);
1853                                 Mem_Free(oldbuf);
1854                         }
1855                 }
1856                 if (strlen(line))
1857                 {
1858                         memcpy(buf + bufchars, line, strlen(line));
1859                         bufchars += strlen(line);
1860                 }
1861         }
1862         if (bufchars)
1863                 COM_WriteFile(name, buf, bufchars);
1864         if (buf)
1865                 Mem_Free(buf);
1866 }
1867
1868 void R_Shadow_LoadLightsFile(void)
1869 {
1870         int n, a, style;
1871         char name[MAX_QPATH], *lightsstring, *s, *t;
1872         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
1873         if (cl.worldmodel == NULL)
1874         {
1875                 Con_Printf("No map loaded.\n");
1876                 return;
1877         }
1878         COM_StripExtension(cl.worldmodel->name, name);
1879         strcat(name, ".lights");
1880         lightsstring = COM_LoadFile(name, false);
1881         if (lightsstring)
1882         {
1883                 s = lightsstring;
1884                 n = 0;
1885                 while (*s)
1886                 {
1887                         t = s;
1888                         while (*s && *s != '\n')
1889                                 s++;
1890                         if (!*s)
1891                                 break;
1892                         *s = 0;
1893                         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);
1894                         *s = '\n';
1895                         if (a < 14)
1896                         {
1897                                 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);
1898                                 break;
1899                         }
1900                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
1901                         radius = bound(15, radius, 4096);
1902                         VectorScale(color, (2.0f / (8388608.0f)), color);
1903                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL, true);
1904                         s++;
1905                         n++;
1906                 }
1907                 if (*s)
1908                         Con_Printf("invalid lights file \"%s\"\n", name);
1909                 Mem_Free(lightsstring);
1910         }
1911 }
1912
1913 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
1914 {
1915         int entnum, style, islight;
1916         char key[256], value[1024];
1917         float origin[3], radius, color[3], light, scale, originhack[3], overridecolor[3];
1918         const char *data;
1919
1920         if (cl.worldmodel == NULL)
1921         {
1922                 Con_Printf("No map loaded.\n");
1923                 return;
1924         }
1925         data = cl.worldmodel->entities;
1926         if (!data)
1927                 return;
1928         for (entnum = 0;COM_ParseToken(&data) && com_token[0] == '{';entnum++)
1929         {
1930                 light = 0;
1931                 origin[0] = origin[1] = origin[2] = 0;
1932                 originhack[0] = originhack[1] = originhack[2] = 0;
1933                 color[0] = color[1] = color[2] = 1;
1934                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
1935                 scale = 1;
1936                 style = 0;
1937                 islight = false;
1938                 while (1)
1939                 {
1940                         if (!COM_ParseToken(&data))
1941                                 break; // error
1942                         if (com_token[0] == '}')
1943                                 break; // end of entity
1944                         if (com_token[0] == '_')
1945                                 strcpy(key, com_token + 1);
1946                         else
1947                                 strcpy(key, com_token);
1948                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
1949                                 key[strlen(key)-1] = 0;
1950                         if (!COM_ParseToken(&data))
1951                                 break; // error
1952                         strcpy(value, com_token);
1953
1954                         // now that we have the key pair worked out...
1955                         if (!strcmp("light", key))
1956                                 light = atof(value);
1957                         else if (!strcmp("origin", key))
1958                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
1959                         else if (!strcmp("color", key))
1960                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
1961                         else if (!strcmp("wait", key))
1962                                 scale = atof(value);
1963                         else if (!strcmp("classname", key))
1964                         {
1965                                 if (!strncmp(value, "light", 5))
1966                                 {
1967                                         islight = true;
1968                                         if (!strcmp(value, "light_fluoro"))
1969                                         {
1970                                                 originhack[0] = 0;
1971                                                 originhack[1] = 0;
1972                                                 originhack[2] = 0;
1973                                                 overridecolor[0] = 1;
1974                                                 overridecolor[1] = 1;
1975                                                 overridecolor[2] = 1;
1976                                         }
1977                                         if (!strcmp(value, "light_fluorospark"))
1978                                         {
1979                                                 originhack[0] = 0;
1980                                                 originhack[1] = 0;
1981                                                 originhack[2] = 0;
1982                                                 overridecolor[0] = 1;
1983                                                 overridecolor[1] = 1;
1984                                                 overridecolor[2] = 1;
1985                                         }
1986                                         if (!strcmp(value, "light_globe"))
1987                                         {
1988                                                 originhack[0] = 0;
1989                                                 originhack[1] = 0;
1990                                                 originhack[2] = 0;
1991                                                 overridecolor[0] = 1;
1992                                                 overridecolor[1] = 0.8;
1993                                                 overridecolor[2] = 0.4;
1994                                         }
1995                                         if (!strcmp(value, "light_flame_large_yellow"))
1996                                         {
1997                                                 originhack[0] = 0;
1998                                                 originhack[1] = 0;
1999                                                 originhack[2] = 48;
2000                                                 overridecolor[0] = 1;
2001                                                 overridecolor[1] = 0.5;
2002                                                 overridecolor[2] = 0.1;
2003                                         }
2004                                         if (!strcmp(value, "light_flame_small_yellow"))
2005                                         {
2006                                                 originhack[0] = 0;
2007                                                 originhack[1] = 0;
2008                                                 originhack[2] = 40;
2009                                                 overridecolor[0] = 1;
2010                                                 overridecolor[1] = 0.5;
2011                                                 overridecolor[2] = 0.1;
2012                                         }
2013                                         if (!strcmp(value, "light_torch_small_white"))
2014                                         {
2015                                                 originhack[0] = 0;
2016                                                 originhack[1] = 0;
2017                                                 originhack[2] = 40;
2018                                                 overridecolor[0] = 1;
2019                                                 overridecolor[1] = 0.5;
2020                                                 overridecolor[2] = 0.1;
2021                                         }
2022                                         if (!strcmp(value, "light_torch_small_walltorch"))
2023                                         {
2024                                                 originhack[0] = 0;
2025                                                 originhack[1] = 0;
2026                                                 originhack[2] = 40;
2027                                                 overridecolor[0] = 1;
2028                                                 overridecolor[1] = 0.5;
2029                                                 overridecolor[2] = 0.1;
2030                                         }
2031                                 }
2032                         }
2033                         else if (!strcmp("style", key))
2034                                 style = atoi(value);
2035                 }
2036                 if (light <= 0 && islight)
2037                         light = 300;
2038                 radius = min(light * r_editlights_quakelightsizescale.value / scale, 1048576);
2039                 light = sqrt(bound(0, light, 1048576)) * (1.0f / 16.0f);
2040                 if (color[0] == 1 && color[1] == 1 && color[2] == 1)
2041                         VectorCopy(overridecolor, color);
2042                 VectorScale(color, light, color);
2043                 VectorAdd(origin, originhack, origin);
2044                 if (radius >= 15)
2045                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL, true);
2046         }
2047 }
2048
2049
2050 void R_Shadow_SetCursorLocationForView(void)
2051 {
2052         vec_t dist, push, frac;
2053         vec3_t dest, endpos, normal;
2054         VectorMA(r_refdef.vieworg, r_editlights_cursordistance.value, vpn, dest);
2055         frac = CL_TraceLine(r_refdef.vieworg, dest, endpos, normal, 0, true, NULL);
2056         if (frac < 1)
2057         {
2058                 dist = frac * r_editlights_cursordistance.value;
2059                 push = r_editlights_cursorpushback.value;
2060                 if (push > dist)
2061                         push = dist;
2062                 push = -push;
2063                 VectorMA(endpos, push, vpn, endpos);
2064                 VectorMA(endpos, r_editlights_cursorpushoff.value, normal, endpos);
2065         }
2066         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
2067         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
2068         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
2069 }
2070
2071 void R_Shadow_UpdateLightingMode(void)
2072 {
2073         r_shadow_lightingmode = 0;
2074         if (r_shadow_realtime.integer)
2075         {
2076                 if (r_shadow_worldlightchain)
2077                         r_shadow_lightingmode = 2;
2078                 else
2079                         r_shadow_lightingmode = 1;
2080         }
2081 }
2082
2083 void R_Shadow_UpdateWorldLightSelection(void)
2084 {
2085         R_Shadow_SetCursorLocationForView();
2086         if (r_editlights.integer)
2087         {
2088                 R_Shadow_SelectLightInView();
2089                 R_Shadow_DrawLightSprites();
2090         }
2091         else
2092                 R_Shadow_SelectLight(NULL);
2093 }
2094
2095 void R_Shadow_EditLights_Clear_f(void)
2096 {
2097         R_Shadow_ClearWorldLights();
2098 }
2099
2100 void R_Shadow_EditLights_Reload_f(void)
2101 {
2102         r_shadow_reloadlights = true;
2103 }
2104
2105 void R_Shadow_EditLights_Save_f(void)
2106 {
2107         if (cl.worldmodel)
2108                 R_Shadow_SaveWorldLights();
2109 }
2110
2111 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
2112 {
2113         R_Shadow_ClearWorldLights();
2114         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
2115 }
2116
2117 void R_Shadow_EditLights_ImportLightsFile_f(void)
2118 {
2119         R_Shadow_ClearWorldLights();
2120         R_Shadow_LoadLightsFile();
2121 }
2122
2123 void R_Shadow_EditLights_Spawn_f(void)
2124 {
2125         vec3_t color;
2126         if (!r_editlights.integer)
2127         {
2128                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
2129                 return;
2130         }
2131         if (Cmd_Argc() != 1)
2132         {
2133                 Con_Printf("r_editlights_spawn does not take parameters\n");
2134                 return;
2135         }
2136         color[0] = color[1] = color[2] = 1;
2137         R_Shadow_NewWorldLight(r_editlights_cursorlocation, 200, color, 0, NULL, true);
2138 }
2139
2140 void R_Shadow_EditLights_Edit_f(void)
2141 {
2142         vec3_t origin, color;
2143         vec_t radius;
2144         int style, shadows;
2145         char cubemapname[1024];
2146         if (!r_editlights.integer)
2147         {
2148                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
2149                 return;
2150         }
2151         if (!r_shadow_selectedlight)
2152         {
2153                 Con_Printf("No selected light.\n");
2154                 return;
2155         }
2156         VectorCopy(r_shadow_selectedlight->origin, origin);
2157         radius = r_shadow_selectedlight->lightradius;
2158         VectorCopy(r_shadow_selectedlight->light, color);
2159         style = r_shadow_selectedlight->style;
2160         if (r_shadow_selectedlight->cubemapname)
2161                 strcpy(cubemapname, r_shadow_selectedlight->cubemapname);
2162         else
2163                 cubemapname[0] = 0;
2164         shadows = r_shadow_selectedlight->castshadows;
2165         if (!strcmp(Cmd_Argv(1), "origin"))
2166         {
2167                 if (Cmd_Argc() != 5)
2168                 {
2169                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(0));
2170                         return;
2171                 }
2172                 origin[0] = atof(Cmd_Argv(2));
2173                 origin[1] = atof(Cmd_Argv(3));
2174                 origin[2] = atof(Cmd_Argv(4));
2175         }
2176         else if (!strcmp(Cmd_Argv(1), "originx"))
2177         {
2178                 if (Cmd_Argc() != 3)
2179                 {
2180                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2181                         return;
2182                 }
2183                 origin[0] = atof(Cmd_Argv(2));
2184         }
2185         else if (!strcmp(Cmd_Argv(1), "originy"))
2186         {
2187                 if (Cmd_Argc() != 3)
2188                 {
2189                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2190                         return;
2191                 }
2192                 origin[1] = atof(Cmd_Argv(2));
2193         }
2194         else if (!strcmp(Cmd_Argv(1), "originz"))
2195         {
2196                 if (Cmd_Argc() != 3)
2197                 {
2198                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2199                         return;
2200                 }
2201                 origin[2] = atof(Cmd_Argv(2));
2202         }
2203         else if (!strcmp(Cmd_Argv(1), "move"))
2204         {
2205                 if (Cmd_Argc() != 5)
2206                 {
2207                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(0));
2208                         return;
2209                 }
2210                 origin[0] += atof(Cmd_Argv(2));
2211                 origin[1] += atof(Cmd_Argv(3));
2212                 origin[2] += atof(Cmd_Argv(4));
2213         }
2214         else if (!strcmp(Cmd_Argv(1), "movex"))
2215         {
2216                 if (Cmd_Argc() != 3)
2217                 {
2218                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2219                         return;
2220                 }
2221                 origin[0] += atof(Cmd_Argv(2));
2222         }
2223         else if (!strcmp(Cmd_Argv(1), "movey"))
2224         {
2225                 if (Cmd_Argc() != 3)
2226                 {
2227                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2228                         return;
2229                 }
2230                 origin[1] += atof(Cmd_Argv(2));
2231         }
2232         else if (!strcmp(Cmd_Argv(1), "movez"))
2233         {
2234                 if (Cmd_Argc() != 3)
2235                 {
2236                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2237                         return;
2238                 }
2239                 origin[2] += atof(Cmd_Argv(2));
2240         }
2241         else if (!strcmp(Cmd_Argv(1), "color"))
2242         {
2243                 if (Cmd_Argc() != 5)
2244                 {
2245                         Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(0));
2246                         return;
2247                 }
2248                 color[0] = atof(Cmd_Argv(2));
2249                 color[1] = atof(Cmd_Argv(3));
2250                 color[2] = atof(Cmd_Argv(4));
2251         }
2252         else if (!strcmp(Cmd_Argv(1), "radius"))
2253         {
2254                 if (Cmd_Argc() != 3)
2255                 {
2256                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2257                         return;
2258                 }
2259                 radius = atof(Cmd_Argv(2));
2260         }
2261         else if (Cmd_Argc() == 3 && !strcmp(Cmd_Argv(1), "style"))
2262         {
2263                 if (Cmd_Argc() != 3)
2264                 {
2265                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2266                         return;
2267                 }
2268                 style = atoi(Cmd_Argv(2));
2269         }
2270         else if (Cmd_Argc() == 3 && !strcmp(Cmd_Argv(1), "cubemap"))
2271         {
2272                 if (Cmd_Argc() > 3)
2273                 {
2274                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2275                         return;
2276                 }
2277                 if (Cmd_Argc() == 3)
2278                         strcpy(cubemapname, Cmd_Argv(2));
2279                 else
2280                         cubemapname[0] = 0;
2281         }
2282         else if (Cmd_Argc() == 3 && !strcmp(Cmd_Argv(1), "shadows"))
2283         {
2284                 if (Cmd_Argc() != 3)
2285                 {
2286                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(0));
2287                         return;
2288                 }
2289                 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
2290         }
2291         else
2292         {
2293                 Con_Printf("usage: r_editlights_edit [property] [value]\n");
2294                 Con_Printf("Selected light's properties:\n");
2295                 Con_Printf("Origin: %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
2296                 Con_Printf("Radius: %f\n", r_shadow_selectedlight->lightradius);
2297                 Con_Printf("Color: %f %f %f\n", r_shadow_selectedlight->light[0], r_shadow_selectedlight->light[1], r_shadow_selectedlight->light[2]);
2298                 Con_Printf("Style: %i\n", r_shadow_selectedlight->style);
2299                 Con_Printf("Cubemap: %s\n", r_shadow_selectedlight->cubemapname);
2300                 Con_Printf("Shadows: %s\n", r_shadow_selectedlight->castshadows ? "yes" : "no");
2301                 return;
2302         }
2303         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
2304         r_shadow_selectedlight = NULL;
2305         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname, shadows);
2306 }
2307
2308 extern int con_vislines;
2309 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
2310 {
2311         float x, y;
2312         char temp[256];
2313         if (r_shadow_selectedlight == NULL)
2314                 return;
2315         x = 0;
2316         y = con_vislines;
2317         sprintf(temp, "Light properties");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
2318         sprintf(temp, "Origin %f %f %f", 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);y += 8;
2319         sprintf(temp, "Radius %f", r_shadow_selectedlight->lightradius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
2320         sprintf(temp, "Color %f %f %f", r_shadow_selectedlight->light[0], r_shadow_selectedlight->light[1], r_shadow_selectedlight->light[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
2321         sprintf(temp, "Style %i", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
2322         sprintf(temp, "Cubemap %s", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
2323         sprintf(temp, "Shadows %s", r_shadow_selectedlight->castshadows ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
2324 }
2325
2326 void R_Shadow_EditLights_ToggleShadow_f(void)
2327 {
2328         if (!r_editlights.integer)
2329         {
2330                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
2331                 return;
2332         }
2333         if (!r_shadow_selectedlight)
2334         {
2335                 Con_Printf("No selected light.\n");
2336                 return;
2337         }
2338         R_Shadow_NewWorldLight(r_shadow_selectedlight->origin, r_shadow_selectedlight->lightradius, r_shadow_selectedlight->light, r_shadow_selectedlight->style, r_shadow_selectedlight->cubemapname, !r_shadow_selectedlight->castshadows);
2339         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
2340         r_shadow_selectedlight = NULL;
2341 }
2342
2343 void R_Shadow_EditLights_Remove_f(void)
2344 {
2345         if (!r_editlights.integer)
2346         {
2347                 Con_Printf("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
2348                 return;
2349         }
2350         if (!r_shadow_selectedlight)
2351         {
2352                 Con_Printf("No selected light.\n");
2353                 return;
2354         }
2355         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
2356         r_shadow_selectedlight = NULL;
2357 }
2358
2359 void R_Shadow_EditLights_Init(void)
2360 {
2361         Cvar_RegisterVariable(&r_editlights);
2362         Cvar_RegisterVariable(&r_editlights_cursordistance);
2363         Cvar_RegisterVariable(&r_editlights_cursorpushback);
2364         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
2365         Cvar_RegisterVariable(&r_editlights_cursorgrid);
2366         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
2367         Cvar_RegisterVariable(&r_editlights_rtlightssizescale);
2368         Cvar_RegisterVariable(&r_editlights_rtlightscolorscale);
2369         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f);
2370         Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f);
2371         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f);
2372         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f);
2373         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f);
2374         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f);
2375         Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f);
2376         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f);
2377         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f);
2378 }