minor update to texture flags and logic stuff
[divverent/darkplaces.git] / r_shadow.c
1
2 #include "quakedef.h"
3 #include "r_shadow.h"
4 #include "cl_collision.h"
5
6 extern void R_Shadow_EditLights_Init(void);
7
8 #define SHADOWSTAGE_NONE 0
9 #define SHADOWSTAGE_STENCIL 1
10 #define SHADOWSTAGE_LIGHT 2
11 #define SHADOWSTAGE_ERASESTENCIL 3
12
13 int r_shadowstage = SHADOWSTAGE_NONE;
14 int r_shadow_reloadlights = false;
15
16 int r_shadow_lightingmode = 0;
17
18 mempool_t *r_shadow_mempool;
19
20 int maxshadowelements;
21 int *shadowelements;
22 int maxtrianglefacinglight;
23 qbyte *trianglefacinglight;
24
25 rtexturepool_t *r_shadow_texturepool;
26 rtexture_t *r_shadow_normalsattenuationtexture;
27 rtexture_t *r_shadow_normalscubetexture;
28 rtexture_t *r_shadow_attenuation2dtexture;
29 rtexture_t *r_shadow_blankbumptexture;
30 rtexture_t *r_shadow_blankglosstexture;
31 rtexture_t *r_shadow_blankwhitetexture;
32
33 cvar_t r_shadow_lightattenuationscale = {0, "r_shadow_lightattenuationscale", "2"};
34 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1"};
35 cvar_t r_shadow_realtime = {0, "r_shadow_realtime", "0"};
36 cvar_t r_shadow_erasebydrawing = {0, "r_shadow_erasebydrawing", "0"};
37 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "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 = {0, "r_shadow_bumpscale", "4"};
42
43 void R_Shadow_ClearWorldLights(void);
44 void R_Shadow_SaveWorldLights(void);
45 void R_Shadow_LoadWorldLights(void);
46 void R_Shadow_LoadLightsFile(void);
47 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
48
49 void r_shadow_start(void)
50 {
51         // allocate vertex processing arrays
52         r_shadow_mempool = Mem_AllocPool("R_Shadow");
53         maxshadowelements = 0;
54         shadowelements = NULL;
55         maxtrianglefacinglight = 0;
56         trianglefacinglight = NULL;
57         r_shadow_normalsattenuationtexture = NULL;
58         r_shadow_normalscubetexture = NULL;
59         r_shadow_attenuation2dtexture = NULL;
60         r_shadow_blankbumptexture = NULL;
61         r_shadow_blankglosstexture = NULL;
62         r_shadow_blankwhitetexture = NULL;
63         r_shadow_texturepool = NULL;
64         R_Shadow_ClearWorldLights();
65         r_shadow_reloadlights = true;
66 }
67
68 void r_shadow_shutdown(void)
69 {
70         R_Shadow_ClearWorldLights();
71         r_shadow_reloadlights = true;
72         r_shadow_normalsattenuationtexture = NULL;
73         r_shadow_normalscubetexture = NULL;
74         r_shadow_attenuation2dtexture = NULL;
75         r_shadow_blankbumptexture = NULL;
76         r_shadow_blankglosstexture = NULL;
77         r_shadow_blankwhitetexture = NULL;
78         R_FreeTexturePool(&r_shadow_texturepool);
79         maxshadowelements = 0;
80         shadowelements = NULL;
81         maxtrianglefacinglight = 0;
82         trianglefacinglight = NULL;
83         Mem_FreePool(&r_shadow_mempool);
84 }
85
86 void r_shadow_newmap(void)
87 {
88         R_Shadow_ClearWorldLights();
89         r_shadow_reloadlights = true;
90 }
91
92 void R_Shadow_Init(void)
93 {
94         Cvar_RegisterVariable(&r_shadow_lightattenuationscale);
95         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
96         Cvar_RegisterVariable(&r_shadow_realtime);
97         Cvar_RegisterVariable(&r_shadow_texture3d);
98         Cvar_RegisterVariable(&r_shadow_gloss);
99         Cvar_RegisterVariable(&r_shadow_debuglight);
100         Cvar_RegisterVariable(&r_shadow_erasebydrawing);
101         Cvar_RegisterVariable(&r_shadow_scissor);
102         Cvar_RegisterVariable(&r_shadow_bumpscale);
103         R_Shadow_EditLights_Init();
104         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap);
105 }
106
107 void R_Shadow_ProjectVertices(const float *in, float *out, int numverts, const float *relativelightorigin, float projectdistance)
108 {
109         int i;
110         for (i = 0;i < numverts;i++, in += 4, out += 4)
111         {
112 #if 1
113                 out[0] = in[0] + 1000000.0f * (in[0] - relativelightorigin[0]);
114                 out[1] = in[1] + 1000000.0f * (in[1] - relativelightorigin[1]);
115                 out[2] = in[2] + 1000000.0f * (in[2] - relativelightorigin[2]);
116 #elif 0
117                 VectorSubtract(in, relativelightorigin, temp);
118                 f = lightradius / sqrt(DotProduct(temp,temp));
119                 if (f < 1)
120                         f = 1;
121                 VectorMA(relativelightorigin, f, temp, out);
122 #else
123                 VectorSubtract(in, relativelightorigin, temp);
124                 f = projectdistance / sqrt(DotProduct(temp,temp));
125                 VectorMA(in, f, temp, out);
126 #endif
127         }
128 }
129
130 void R_Shadow_MakeTriangleShadowFlags(const int *elements, const float *vertex, int numtris, qbyte *trianglefacinglight, const float *relativelightorigin, float lightradius)
131 {
132         int i;
133         const float *v0, *v1, *v2;
134         for (i = 0;i < numtris;i++, elements += 3)
135         {
136                 // calculate triangle facing flag
137                 v0 = vertex + elements[0] * 4;
138                 v1 = vertex + elements[1] * 4;
139                 v2 = vertex + elements[2] * 4;
140                 // we do not need to normalize the surface normal because both sides
141                 // of the comparison use it, therefore they are both multiplied the
142                 // same amount...  furthermore the subtract can be done on the
143                 // vectors, saving a little bit of math in the dotproducts
144 #if 0
145                 // fast version
146                 // subtracts v1 from v0 and v2, combined into a crossproduct,
147                 // combined with a dotproduct of the light location relative to the
148                 // first point of the triangle (any point works, since the triangle
149                 // is obviously flat), and finally a comparison to determine if the
150                 // light is infront of the triangle (the goal of this statement)
151                 trianglefacinglight[i] =
152                    (relativelightorigin[0] - v0[0]) * ((v0[1] - v1[1]) * (v2[2] - v1[2]) - (v0[2] - v1[2]) * (v2[1] - v1[1]))
153                  + (relativelightorigin[1] - v0[1]) * ((v0[2] - v1[2]) * (v2[0] - v1[0]) - (v0[0] - v1[0]) * (v2[2] - v1[2]))
154                  + (relativelightorigin[2] - v0[2]) * ((v0[0] - v1[0]) * (v2[1] - v1[1]) - (v0[1] - v1[1]) * (v2[0] - v1[0])) > 0;
155 #else
156                 // readable version
157                 {
158                 float dir0[3], dir1[3], temp[3], f;
159
160                 // calculate two mostly perpendicular edge directions
161                 VectorSubtract(v0, v1, dir0);
162                 VectorSubtract(v2, v1, dir1);
163
164                 // we have two edge directions, we can calculate a third vector from
165                 // them, which is the direction of the surface normal (it's magnitude
166                 // is not 1 however)
167                 CrossProduct(dir0, dir1, temp);
168
169                 // this is entirely unnecessary, but kept for clarity
170                 //VectorNormalize(temp);
171
172                 // compare distance of light along normal, with distance of any point
173                 // of the triangle along the same normal (the triangle is planar,
174                 // I.E. flat, so all points give the same answer)
175                 // the normal is not normalized because it is used on both sides of
176                 // the comparison, so it's magnitude does not matter
177                 //trianglefacinglight[i] = DotProduct(relativelightorigin, temp) >= DotProduct(v0, temp);
178                 f = DotProduct(relativelightorigin, temp) - DotProduct(v0, temp);
179                 trianglefacinglight[i] = f > 0 && f < lightradius * sqrt(DotProduct(temp, temp));
180                 }
181 #endif
182         }
183 }
184
185 int R_Shadow_BuildShadowVolumeTriangles(const int *elements, const int *neighbors, int numtris, int numverts, const qbyte *trianglefacinglight, int *out)
186 {
187         int i, tris;
188         // check each frontface for bordering backfaces,
189         // and cast shadow polygons from those edges,
190         // also create front and back caps for shadow volume
191         tris = 0;
192         for (i = 0;i < numtris;i++, elements += 3, neighbors += 3)
193         {
194                 if (trianglefacinglight[i])
195                 {
196                         // triangle is frontface and therefore casts shadow,
197                         // output front and back caps for shadow volume
198                         // front cap
199                         out[0] = elements[0];
200                         out[1] = elements[1];
201                         out[2] = elements[2];
202                         // rear cap (with flipped winding order)
203                         out[3] = elements[0] + numverts;
204                         out[4] = elements[2] + numverts;
205                         out[5] = elements[1] + numverts;
206                         out += 6;
207                         tris += 2;
208                         // check the edges
209                         if (neighbors[0] < 0 || !trianglefacinglight[neighbors[0]])
210                         {
211                                 out[0] = elements[1];
212                                 out[1] = elements[0];
213                                 out[2] = elements[0] + numverts;
214                                 out[3] = elements[1];
215                                 out[4] = elements[0] + numverts;
216                                 out[5] = elements[1] + numverts;
217                                 out += 6;
218                                 tris += 2;
219                         }
220                         if (neighbors[1] < 0 || !trianglefacinglight[neighbors[1]])
221                         {
222                                 out[0] = elements[2];
223                                 out[1] = elements[1];
224                                 out[2] = elements[1] + numverts;
225                                 out[3] = elements[2];
226                                 out[4] = elements[1] + numverts;
227                                 out[5] = elements[2] + numverts;
228                                 out += 6;
229                                 tris += 2;
230                         }
231                         if (neighbors[2] < 0 || !trianglefacinglight[neighbors[2]])
232                         {
233                                 out[0] = elements[0];
234                                 out[1] = elements[2];
235                                 out[2] = elements[2] + numverts;
236                                 out[3] = elements[0];
237                                 out[4] = elements[2] + numverts;
238                                 out[5] = elements[0] + numverts;
239                                 out += 6;
240                                 tris += 2;
241                         }
242                 }
243         }
244         return tris;
245 }
246
247 void R_Shadow_ResizeTriangleFacingLight(int numtris)
248 {
249         // make sure trianglefacinglight is big enough for this volume
250         if (maxtrianglefacinglight < numtris)
251         {
252                 maxtrianglefacinglight = numtris;
253                 if (trianglefacinglight)
254                         Mem_Free(trianglefacinglight);
255                 trianglefacinglight = Mem_Alloc(r_shadow_mempool, maxtrianglefacinglight);
256         }
257 }
258
259 void R_Shadow_ResizeShadowElements(int numtris)
260 {
261         // make sure shadowelements is big enough for this volume
262         if (maxshadowelements < numtris * 24)
263         {
264                 maxshadowelements = numtris * 24;
265                 if (shadowelements)
266                         Mem_Free(shadowelements);
267                 shadowelements = Mem_Alloc(r_shadow_mempool, maxshadowelements * sizeof(int));
268         }
269 }
270
271 void R_Shadow_Volume(int numverts, int numtris, int *elements, int *neighbors, vec3_t relativelightorigin, float lightradius, float projectdistance)
272 {
273         int tris;
274         if (projectdistance < 0.1)
275         {
276                 Con_Printf("R_Shadow_Volume: projectdistance %f\n");
277                 return;
278         }
279 // terminology:
280 //
281 // frontface:
282 // a triangle facing the light source
283 //
284 // backface:
285 // a triangle not facing the light source
286 //
287 // shadow volume:
288 // an extrusion of the frontfaces, beginning at the original geometry and
289 // ending further from the light source than the original geometry
290 // (presumably at least as far as the light's radius, if the light has a
291 // radius at all), capped at both front and back to avoid any problems
292 //
293 // description:
294 // draws the shadow volumes of the model.
295 // requirements:
296 // vertex locations must already be in varray_vertex before use.
297 // varray_vertex must have capacity for numverts * 2.
298
299         // make sure trianglefacinglight is big enough for this volume
300         if (maxtrianglefacinglight < numtris)
301                 R_Shadow_ResizeTriangleFacingLight(numtris);
302
303         // make sure shadowelements is big enough for this volume
304         if (maxshadowelements < numtris * 24)
305                 R_Shadow_ResizeShadowElements(numtris);
306
307         // generate projected vertices
308         // by clever use of elements we'll construct the whole shadow from
309         // the unprojected vertices and these projected vertices
310         R_Shadow_ProjectVertices(varray_vertex, varray_vertex + numverts * 4, numverts, relativelightorigin, projectdistance);
311
312         // check which triangles are facing the light
313         R_Shadow_MakeTriangleShadowFlags(elements, varray_vertex, numtris, trianglefacinglight, relativelightorigin, lightradius);
314
315         // output triangle elements
316         tris = R_Shadow_BuildShadowVolumeTriangles(elements, neighbors, numtris, numverts, trianglefacinglight, shadowelements);
317         R_Shadow_RenderVolume(numverts * 2, tris, shadowelements);
318 }
319
320 void R_Shadow_RenderVolume(int numverts, int numtris, int *elements)
321 {
322         if (!numverts || !numtris)
323                 return;
324         if (r_shadowstage == SHADOWSTAGE_STENCIL)
325         {
326                 // increment stencil if backface is behind depthbuffer
327                 qglCullFace(GL_BACK); // quake is backwards, this culls front faces
328                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
329                 R_Mesh_Draw(numverts, numtris, elements);
330                 // decrement stencil if frontface is behind depthbuffer
331                 qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
332                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
333         }
334         R_Mesh_Draw(numverts, numtris, elements);
335 }
336
337 void R_Shadow_RenderShadowMeshVolume(shadowmesh_t *firstmesh)
338 {
339         shadowmesh_t *mesh;
340         if (r_shadowstage == SHADOWSTAGE_STENCIL)
341         {
342                 // increment stencil if backface is behind depthbuffer
343                 qglCullFace(GL_BACK); // quake is backwards, this culls front faces
344                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
345                 for (mesh = firstmesh;mesh;mesh = mesh->next)
346                 {
347                         R_Mesh_ResizeCheck(mesh->numverts);
348                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
349                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->elements);
350                 }
351                 // decrement stencil if frontface is behind depthbuffer
352                 qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
353                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
354         }
355         for (mesh = firstmesh;mesh;mesh = mesh->next)
356         {
357                 R_Mesh_ResizeCheck(mesh->numverts);
358                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
359                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->elements);
360         }
361 }
362
363 float r_shadow_atten1;
364 #define ATTEN3DSIZE 64
365 static void R_Shadow_Make3DTextures(void)
366 {
367         int x, y, z;
368         float v[3], intensity, ilen, bordercolor[4];
369         qbyte *data;
370         data = Mem_Alloc(tempmempool, ATTEN3DSIZE * ATTEN3DSIZE * ATTEN3DSIZE * 4);
371         for (z = 0;z < ATTEN3DSIZE;z++)
372         {
373                 for (y = 0;y < ATTEN3DSIZE;y++)
374                 {
375                         for (x = 0;x < ATTEN3DSIZE;x++)
376                         {
377                                 v[0] = (x + 0.5f) * (2.0f / (float) ATTEN3DSIZE) - 1.0f;
378                                 v[1] = (y + 0.5f) * (2.0f / (float) ATTEN3DSIZE) - 1.0f;
379                                 v[2] = (z + 0.5f) * (2.0f / (float) ATTEN3DSIZE) - 1.0f;
380                                 intensity = 1.0f - sqrt(DotProduct(v, v));
381                                 if (intensity > 0)
382                                         intensity *= intensity;
383                                 ilen = 127.0f * bound(0, intensity * r_shadow_atten1, 1) / sqrt(DotProduct(v, v));
384                                 data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+0] = 128.0f + ilen * v[0];
385                                 data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+1] = 128.0f + ilen * v[1];
386                                 data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+2] = 128.0f + ilen * v[2];
387                                 data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+3] = 255;
388                         }
389                 }
390         }
391         r_shadow_normalsattenuationtexture = R_LoadTexture3D(r_shadow_texturepool, "normalsattenuation", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
392         Mem_Free(data);
393         bordercolor[0] = 0.5f;
394         bordercolor[1] = 0.5f;
395         bordercolor[2] = 0.5f;
396         bordercolor[3] = 1.0f;
397         qglTexParameterfv(GL_TEXTURE_3D, GL_TEXTURE_BORDER_COLOR, bordercolor);
398 }
399
400 static void R_Shadow_MakeTextures(void)
401 {
402         int x, y, d, side;
403         float v[3], s, t, intensity;
404         qbyte *data;
405         R_FreeTexturePool(&r_shadow_texturepool);
406         r_shadow_texturepool = R_AllocTexturePool();
407         r_shadow_atten1 = r_shadow_lightattenuationscale.value;
408         data = Mem_Alloc(tempmempool, 6*128*128*4);
409         data[0] = 128;
410         data[1] = 128;
411         data[2] = 255;
412         data[3] = 255;
413         r_shadow_blankbumptexture = R_LoadTexture2D(r_shadow_texturepool, "blankbump", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
414         data[0] = 255;
415         data[1] = 255;
416         data[2] = 255;
417         data[3] = 255;
418         r_shadow_blankglosstexture = R_LoadTexture2D(r_shadow_texturepool, "blankgloss", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
419         data[0] = 255;
420         data[1] = 255;
421         data[2] = 255;
422         data[3] = 255;
423         r_shadow_blankwhitetexture = R_LoadTexture2D(r_shadow_texturepool, "blankwhite", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
424         for (side = 0;side < 6;side++)
425         {
426                 for (y = 0;y < 128;y++)
427                 {
428                         for (x = 0;x < 128;x++)
429                         {
430                                 s = (x + 0.5f) * (2.0f / 128.0f) - 1.0f;
431                                 t = (y + 0.5f) * (2.0f / 128.0f) - 1.0f;
432                                 switch(side)
433                                 {
434                                 case 0:
435                                         v[0] = 1;
436                                         v[1] = -t;
437                                         v[2] = -s;
438                                         break;
439                                 case 1:
440                                         v[0] = -1;
441                                         v[1] = -t;
442                                         v[2] = s;
443                                         break;
444                                 case 2:
445                                         v[0] = s;
446                                         v[1] = 1;
447                                         v[2] = t;
448                                         break;
449                                 case 3:
450                                         v[0] = s;
451                                         v[1] = -1;
452                                         v[2] = -t;
453                                         break;
454                                 case 4:
455                                         v[0] = s;
456                                         v[1] = -t;
457                                         v[2] = 1;
458                                         break;
459                                 case 5:
460                                         v[0] = -s;
461                                         v[1] = -t;
462                                         v[2] = -1;
463                                         break;
464                                 }
465                                 intensity = 127.0f / sqrt(DotProduct(v, v));
466                                 data[((side*128+y)*128+x)*4+0] = 128.0f + intensity * v[0];
467                                 data[((side*128+y)*128+x)*4+1] = 128.0f + intensity * v[1];
468                                 data[((side*128+y)*128+x)*4+2] = 128.0f + intensity * v[2];
469                                 data[((side*128+y)*128+x)*4+3] = 255;
470                         }
471                 }
472         }
473         r_shadow_normalscubetexture = R_LoadTextureCubeMap(r_shadow_texturepool, "normalscube", 128, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
474         for (y = 0;y < 128;y++)
475         {
476                 for (x = 0;x < 128;x++)
477                 {
478                         v[0] = (x + 0.5f) * (2.0f / 128.0f) - 1.0f;
479                         v[1] = (y + 0.5f) * (2.0f / 128.0f) - 1.0f;
480                         v[2] = 0;
481                         intensity = 1.0f - sqrt(DotProduct(v, v));
482                         if (intensity > 0)
483                                 intensity *= intensity;
484                         intensity = bound(0, intensity * r_shadow_atten1 * 256.0f, 255.0f);
485                         d = bound(0, intensity, 255);
486                         data[((0*128+y)*128+x)*4+0] = d;
487                         data[((0*128+y)*128+x)*4+1] = d;
488                         data[((0*128+y)*128+x)*4+2] = d;
489                         data[((0*128+y)*128+x)*4+3] = d;
490                 }
491         }
492         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", 128, 128, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_MIPMAP, NULL);
493         Mem_Free(data);
494         if (r_shadow_texture3d.integer)
495                 R_Shadow_Make3DTextures();
496 }
497
498 void R_Shadow_Stage_Begin(void)
499 {
500         rmeshstate_t m;
501
502         if (r_shadow_texture3d.integer && !gl_texture3d)
503         {
504                 Con_Printf("3D texture support not detected, falling back on slower 2D + 1D + normalization lighting\n");
505                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
506         }
507         //cl.worldmodel->numlights = min(cl.worldmodel->numlights, 1);
508         if (!r_shadow_attenuation2dtexture
509          || (r_shadow_texture3d.integer && !r_shadow_normalsattenuationtexture)
510          || r_shadow_lightattenuationscale.value != r_shadow_atten1)
511                 R_Shadow_MakeTextures();
512         if (r_shadow_reloadlights && cl.worldmodel)
513         {
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
532 void R_Shadow_Stage_ShadowVolumes(void)
533 {
534         rmeshstate_t m;
535         memset(&m, 0, sizeof(m));
536         R_Mesh_TextureState(&m);
537         GL_Color(1, 1, 1, 1);
538         qglColorMask(0, 0, 0, 0);
539         qglDisable(GL_BLEND);
540         qglDepthMask(0);
541         qglDepthFunc(GL_LESS);
542         qglEnable(GL_STENCIL_TEST);
543         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
544         qglStencilFunc(GL_ALWAYS, 0, 0xFF);
545         qglEnable(GL_CULL_FACE);
546         qglEnable(GL_DEPTH_TEST);
547         r_shadowstage = SHADOWSTAGE_STENCIL;
548         if (!r_shadow_erasebydrawing.integer)
549                 qglClear(GL_STENCIL_BUFFER_BIT);
550 }
551
552 void R_Shadow_Stage_Light(void)
553 {
554         rmeshstate_t m;
555         memset(&m, 0, sizeof(m));
556         R_Mesh_TextureState(&m);
557         qglActiveTexture(GL_TEXTURE0_ARB);
558
559         qglEnable(GL_BLEND);
560         qglBlendFunc(GL_ONE, GL_ONE);
561         GL_Color(1, 1, 1, 1);
562         qglColorMask(1, 1, 1, 1);
563         qglDepthMask(0);
564         qglDepthFunc(GL_EQUAL);
565         qglEnable(GL_STENCIL_TEST);
566         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
567         // only draw light where this geometry was already rendered AND the
568         // stencil is 0 (non-zero means shadow)
569         qglStencilFunc(GL_EQUAL, 0, 0xFF);
570         qglEnable(GL_CULL_FACE);
571         qglEnable(GL_DEPTH_TEST);
572         r_shadowstage = SHADOWSTAGE_LIGHT;
573 }
574
575 int R_Shadow_Stage_EraseShadowVolumes(void)
576 {
577         if (r_shadow_erasebydrawing.integer)
578         {
579                 rmeshstate_t m;
580                 memset(&m, 0, sizeof(m));
581                 R_Mesh_TextureState(&m);
582                 GL_Color(1, 1, 1, 1);
583                 qglColorMask(0, 0, 0, 0);
584                 qglDisable(GL_BLEND);
585                 qglDepthMask(0);
586                 qglDepthFunc(GL_LESS);
587                 qglEnable(GL_STENCIL_TEST);
588                 qglStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
589                 qglStencilFunc(GL_ALWAYS, 0, 0xFF);
590                 qglDisable(GL_CULL_FACE);
591                 qglDisable(GL_DEPTH_TEST);
592                 r_shadowstage = SHADOWSTAGE_ERASESTENCIL;
593                 return true;
594         }
595         else
596                 return false;
597 }
598
599 void R_Shadow_Stage_End(void)
600 {
601         rmeshstate_t m;
602         // attempt to restore state to what Mesh_State thinks it is
603         qglDisable(GL_BLEND);
604         qglBlendFunc(GL_ONE, GL_ZERO);
605         qglDepthMask(1);
606         // now restore the rest of the state to normal
607         GL_Color(1, 1, 1, 1);
608         qglColorMask(1, 1, 1, 1);
609         qglDisable(GL_SCISSOR_TEST);
610         qglDepthFunc(GL_LEQUAL);
611         qglDisable(GL_STENCIL_TEST);
612         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
613         qglStencilFunc(GL_ALWAYS, 0, 0xFF);
614         qglEnable(GL_CULL_FACE);
615         qglEnable(GL_DEPTH_TEST);
616         // force mesh state to reset by using various combinations of features
617         memset(&m, 0, sizeof(m));
618         m.blendfunc1 = GL_SRC_ALPHA;
619         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
620         R_Mesh_State(&m);
621         m.blendfunc1 = GL_ONE;
622         m.blendfunc2 = GL_ZERO;
623         R_Mesh_State(&m);
624         r_shadowstage = SHADOWSTAGE_NONE;
625 }
626
627 int R_Shadow_ScissorForBBoxAndSphere(const float *mins, const float *maxs, const float *origin, float radius)
628 {
629         int i, ix1, iy1, ix2, iy2;
630         float x1, y1, x2, y2, x, y;
631         vec3_t smins, smaxs;
632         vec4_t v, v2;
633         if (!r_shadow_scissor.integer)
634                 return false;
635         // if view is inside the box, just say yes it's visible
636         if (r_origin[0] >= mins[0] && r_origin[0] <= maxs[0]
637          && r_origin[1] >= mins[1] && r_origin[1] <= maxs[1]
638          && r_origin[2] >= mins[2] && r_origin[2] <= maxs[2])
639         {
640                 qglDisable(GL_SCISSOR_TEST);
641                 return false;
642         }
643         VectorSubtract(r_origin, origin, v);
644         if (DotProduct(v, v) < radius * radius)
645         {
646                 qglDisable(GL_SCISSOR_TEST);
647                 return false;
648         }
649         // create viewspace bbox
650         for (i = 0;i < 8;i++)
651         {
652                 v[0] = ((i & 1) ? mins[0] : maxs[0]) - r_origin[0];
653                 v[1] = ((i & 2) ? mins[1] : maxs[1]) - r_origin[1];
654                 v[2] = ((i & 4) ? mins[2] : maxs[2]) - r_origin[2];
655                 v2[0] = DotProduct(v, vright);
656                 v2[1] = DotProduct(v, vup);
657                 v2[2] = DotProduct(v, vpn);
658                 if (i)
659                 {
660                         if (smins[0] > v2[0]) smins[0] = v2[0];
661                         if (smaxs[0] < v2[0]) smaxs[0] = v2[0];
662                         if (smins[1] > v2[1]) smins[1] = v2[1];
663                         if (smaxs[1] < v2[1]) smaxs[1] = v2[1];
664                         if (smins[2] > v2[2]) smins[2] = v2[2];
665                         if (smaxs[2] < v2[2]) smaxs[2] = v2[2];
666                 }
667                 else
668                 {
669                         smins[0] = smaxs[0] = v2[0];
670                         smins[1] = smaxs[1] = v2[1];
671                         smins[2] = smaxs[2] = v2[2];
672                 }
673         }
674         // now we have a bbox in viewspace
675         // clip it to the viewspace version of the sphere
676         v[0] = origin[0] - r_origin[0];
677         v[1] = origin[1] - r_origin[1];
678         v[2] = origin[2] - r_origin[2];
679         v2[0] = DotProduct(v, vright);
680         v2[1] = DotProduct(v, vup);
681         v2[2] = DotProduct(v, vpn);
682         if (smins[0] < v2[0] - radius) smins[0] = v2[0] - radius;
683         if (smaxs[0] < v2[0] - radius) smaxs[0] = v2[0] + radius;
684         if (smins[1] < v2[1] - radius) smins[1] = v2[1] - radius;
685         if (smaxs[1] < v2[1] - radius) smaxs[1] = v2[1] + radius;
686         if (smins[2] < v2[2] - radius) smins[2] = v2[2] - radius;
687         if (smaxs[2] < v2[2] - radius) smaxs[2] = v2[2] + radius;
688         // clip it to the view plane
689         if (smins[2] < 1)
690                 smins[2] = 1;
691         // return true if that culled the box
692         if (smins[2] >= smaxs[2])
693                 return true;
694         // ok some of it is infront of the view, transform each corner back to
695         // worldspace and then to screenspace and make screen rect
696         for (i = 0;i < 8;i++)
697         {
698                 v2[0] = (i & 1) ? smins[0] : smaxs[0];
699                 v2[1] = (i & 2) ? smins[1] : smaxs[1];
700                 v2[2] = (i & 4) ? smins[2] : smaxs[2];
701                 v[0] = v2[0] * vright[0] + v2[1] * vup[0] + v2[2] * vpn[0] + r_origin[0];
702                 v[1] = v2[0] * vright[1] + v2[1] * vup[1] + v2[2] * vpn[1] + r_origin[1];
703                 v[2] = v2[0] * vright[2] + v2[1] * vup[2] + v2[2] * vpn[2] + r_origin[2];
704                 v[3] = 1.0f;
705                 GL_TransformToScreen(v, v2);
706                 //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]);
707                 x = v2[0];
708                 y = v2[1];
709                 if (i)
710                 {
711                         if (x1 > x) x1 = x;
712                         if (x2 < x) x2 = x;
713                         if (y1 > y) y1 = y;
714                         if (y2 < y) y2 = y;
715                 }
716                 else
717                 {
718                         x1 = x2 = x;
719                         y1 = y2 = y;
720                 }
721         }
722         /*
723         // this code doesn't handle boxes with any points behind view properly
724         x1 = 1000;x2 = -1000;
725         y1 = 1000;y2 = -1000;
726         for (i = 0;i < 8;i++)
727         {
728                 v[0] = (i & 1) ? mins[0] : maxs[0];
729                 v[1] = (i & 2) ? mins[1] : maxs[1];
730                 v[2] = (i & 4) ? mins[2] : maxs[2];
731                 v[3] = 1.0f;
732                 GL_TransformToScreen(v, v2);
733                 //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]);
734                 if (v2[2] > 0)
735                 {
736                         x = v2[0];
737                         y = v2[1];
738
739                         if (x1 > x) x1 = x;
740                         if (x2 < x) x2 = x;
741                         if (y1 > y) y1 = y;
742                         if (y2 < y) y2 = y;
743                 }
744         }
745         */
746         ix1 = x1 - 1.0f;
747         iy1 = y1 - 1.0f;
748         ix2 = x2 + 1.0f;
749         iy2 = y2 + 1.0f;
750         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
751         if (ix1 < r_refdef.x) ix1 = r_refdef.x;
752         if (iy1 < r_refdef.y) iy1 = r_refdef.y;
753         if (ix2 > r_refdef.x + r_refdef.width) ix2 = r_refdef.x + r_refdef.width;
754         if (iy2 > r_refdef.y + r_refdef.height) iy2 = r_refdef.y + r_refdef.height;
755         if (ix2 <= ix1 || iy2 <= iy1)
756                 return true;
757         // set up the scissor rectangle
758         qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);
759         qglEnable(GL_SCISSOR_TEST);
760         return false;
761 }
762
763 void R_Shadow_GenTexCoords_Attenuation2D1D(float *out2d, float *out1d, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin, float lightradius)
764 {
765         int i;
766         float lightvec[3], iradius;
767         iradius = 0.5f / lightradius;
768         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out2d += 4, out1d += 4)
769         {
770                 VectorSubtract(vertex, relativelightorigin, lightvec);
771                 out2d[0] = 0.5f + DotProduct(svectors, lightvec) * iradius;
772                 out2d[1] = 0.5f + DotProduct(tvectors, lightvec) * iradius;
773                 out2d[2] = 0;
774                 out1d[0] = 0.5f + DotProduct(normals, lightvec) * iradius;
775                 out1d[1] = 0.5f;
776                 out1d[2] = 0;
777         }
778 }
779
780 void R_Shadow_GenTexCoords_Diffuse_Attenuation3D(float *out, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin, float lightradius)
781 {
782         int i;
783         float lightvec[3], iradius;
784         iradius = 0.5f / lightradius;
785         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
786         {
787                 VectorSubtract(vertex, relativelightorigin, lightvec);
788                 out[0] = 0.5f + DotProduct(svectors, lightvec) * iradius;
789                 out[1] = 0.5f + DotProduct(tvectors, lightvec) * iradius;
790                 out[2] = 0.5f + DotProduct(normals, lightvec) * iradius;
791         }
792 }
793
794 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)
795 {
796         int i;
797         float lightdir[3];
798         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
799         {
800                 VectorSubtract(vertex, relativelightorigin, lightdir);
801                 // the cubemap normalizes this for us
802                 out[0] = DotProduct(svectors, lightdir);
803                 out[1] = DotProduct(tvectors, lightdir);
804                 out[2] = DotProduct(normals, lightdir);
805         }
806 }
807
808 void R_Shadow_GenTexCoords_Specular_Attenuation3D(float *out, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin, const vec3_t relativeeyeorigin, float lightradius)
809 {
810         int i;
811         float lightdir[3], eyedir[3], halfdir[3], lightdirlen, iradius;
812         iradius = 0.5f / lightradius;
813         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
814         {
815                 VectorSubtract(vertex, relativelightorigin, lightdir);
816                 // this is used later to make the attenuation correct
817                 lightdirlen = sqrt(DotProduct(lightdir, lightdir)) * iradius;
818                 VectorNormalizeFast(lightdir);
819                 VectorSubtract(vertex, relativeeyeorigin, eyedir);
820                 VectorNormalizeFast(eyedir);
821                 VectorAdd(lightdir, eyedir, halfdir);
822                 VectorNormalizeFast(halfdir);
823                 out[0] = 0.5f + DotProduct(svectors, halfdir) * lightdirlen;
824                 out[1] = 0.5f + DotProduct(tvectors, halfdir) * lightdirlen;
825                 out[2] = 0.5f + DotProduct(normals, halfdir) * lightdirlen;
826         }
827 }
828
829 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)
830 {
831         int i;
832         float lightdir[3], eyedir[3], halfdir[3];
833         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
834         {
835                 VectorSubtract(vertex, relativelightorigin, lightdir);
836                 VectorNormalizeFast(lightdir);
837                 VectorSubtract(vertex, relativeeyeorigin, eyedir);
838                 VectorNormalizeFast(eyedir);
839                 VectorAdd(lightdir, eyedir, halfdir);
840                 // the cubemap normalizes this for us
841                 out[0] = DotProduct(svectors, halfdir);
842                 out[1] = DotProduct(tvectors, halfdir);
843                 out[2] = DotProduct(normals, halfdir);
844         }
845 }
846
847 void R_Shadow_GenTexCoords_LightCubeMap(float *out, int numverts, const float *vertex, const vec3_t relativelightorigin)
848 {
849         int i;
850         // FIXME: this needs to be written
851         // this code assumes the vertices are in worldspace (a false assumption)
852         for (i = 0;i < numverts;i++, vertex += 4, out += 4)
853                 VectorSubtract(vertex, relativelightorigin, out);
854 }
855
856 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, rtexture_t *basetexture, rtexture_t *bumptexture, rtexture_t *lightcubemap)
857 {
858         int renders, mult;
859         float scale, colorscale;
860         rmeshstate_t m;
861         memset(&m, 0, sizeof(m));
862         if (!bumptexture)
863                 bumptexture = r_shadow_blankbumptexture;
864         // colorscale accounts for how much we multiply the brightness during combine
865         // mult is how many times the final pass of the lighting will be
866         // performed to get more brightness than otherwise possible
867         // limit mult to 64 for sanity sake
868         if (r_shadow_texture3d.integer)
869         {
870                 if (r_textureunits.integer >= 4 && !lightcubemap)
871                 {
872                         // 4 texture 3D combine path, one pass, no light cubemap support
873                         m.tex[0] = R_GetTexture(bumptexture);
874                         m.tex3d[1] = R_GetTexture(r_shadow_normalsattenuationtexture);
875                         m.tex[2] = R_GetTexture(basetexture);
876                         m.tex[3] = R_GetTexture(r_shadow_blankwhitetexture);
877                         m.texcombinergb[0] = GL_REPLACE;
878                         m.texcombinergb[1] = GL_DOT3_RGB_ARB;
879                         m.texcombinergb[2] = GL_MODULATE;
880                         m.texcombinergb[3] = GL_MODULATE;
881                         R_Mesh_TextureState(&m);
882                         memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
883                         memcpy(varray_texcoord[2], texcoords, numverts * sizeof(float[4]));
884                         R_Shadow_GenTexCoords_Diffuse_Attenuation3D(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
885                         qglActiveTexture(GL_TEXTURE3_ARB);
886                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_PRIMARY_COLOR_ARB);
887                         colorscale = r_colorscale * r_shadow_lightintensityscale.value;
888                         for (mult = 1, scale = ixtable[mult];mult < 64 && (lightcolor[0] * scale * colorscale > 1 || lightcolor[1] * scale * colorscale > 1 || lightcolor[2] * scale * colorscale > 1);mult++, scale = ixtable[mult]);
889                         colorscale *= scale;
890                         GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
891                         for (renders = 0;renders < mult;renders++)
892                                 R_Mesh_Draw(numverts, numtriangles, elements);
893                         qglActiveTexture(GL_TEXTURE3_ARB);
894                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);
895                 }
896                 else
897                 {
898                         // 2 texture no3D combine path, two pass
899                         m.tex[0] = R_GetTexture(bumptexture);
900                         m.tex3d[1] = R_GetTexture(r_shadow_normalsattenuationtexture);
901                         m.texcombinergb[0] = GL_REPLACE;
902                         m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
903                         R_Mesh_TextureState(&m);
904                         qglColorMask(0,0,0,1);
905                         qglDisable(GL_BLEND);
906                         GL_Color(1,1,1,1);
907                         memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
908                         R_Shadow_GenTexCoords_Diffuse_Attenuation3D(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
909                         R_Mesh_Draw(numverts, numtriangles, elements);
910
911                         m.tex[0] = R_GetTexture(basetexture);
912                         m.tex3d[1] = 0;
913                         m.texcubemap[1] = R_GetTexture(lightcubemap);
914                         m.texcombinergb[0] = GL_MODULATE;
915                         m.texcombinergb[1] = GL_MODULATE;
916                         R_Mesh_TextureState(&m);
917                         qglColorMask(1,1,1,1);
918                         qglBlendFunc(GL_DST_ALPHA, GL_ONE);
919                         qglEnable(GL_BLEND);
920                         if (lightcubemap)
921                                 R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
922
923                         colorscale = r_colorscale * r_shadow_lightintensityscale.value;
924                         for (mult = 1, scale = ixtable[mult];mult < 64 && (lightcolor[0] * scale * colorscale > 1 || lightcolor[1] * scale * colorscale > 1 || lightcolor[2] * scale * colorscale > 1);mult++, scale = ixtable[mult]);
925                         colorscale *= scale;
926                         GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
927                         for (renders = 0;renders < mult;renders++)
928                                 R_Mesh_Draw(numverts, numtriangles, elements);
929                 }
930         }
931         else if (r_textureunits.integer >= 4)
932         {
933                 // 4 texture no3D combine path, two pass
934                 m.tex[0] = R_GetTexture(bumptexture);
935                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
936                 m.texcombinergb[0] = GL_REPLACE;
937                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
938                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
939                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
940                 R_Mesh_TextureState(&m);
941                 qglColorMask(0,0,0,1);
942                 qglDisable(GL_BLEND);
943                 GL_Color(1,1,1,1);
944                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
945                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
946                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[2], varray_texcoord[3], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
947                 R_Mesh_Draw(numverts, numtriangles, elements);
948
949                 m.tex[0] = R_GetTexture(basetexture);
950                 m.texcubemap[1] = R_GetTexture(lightcubemap);
951                 m.texcombinergb[0] = GL_MODULATE;
952                 m.texcombinergb[1] = GL_MODULATE;
953                 m.tex[2] = 0;
954                 m.tex[3] = 0;
955                 R_Mesh_TextureState(&m);
956                 qglColorMask(1,1,1,1);
957                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
958                 qglEnable(GL_BLEND);
959                 if (lightcubemap)
960                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
961
962                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
963                 for (mult = 1, scale = ixtable[mult];mult < 64 && (lightcolor[0] * scale * colorscale > 1 || lightcolor[1] * scale * colorscale > 1 || lightcolor[2] * scale * colorscale > 1);mult++, scale = ixtable[mult]);
964                 colorscale *= scale;
965                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
966                 for (renders = 0;renders < mult;renders++)
967                         R_Mesh_Draw(numverts, numtriangles, elements);
968         }
969         else
970         {
971                 // 2 texture no3D combine path, three pass
972                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
973                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
974                 R_Mesh_TextureState(&m);
975                 qglColorMask(0,0,0,1);
976                 qglDisable(GL_BLEND);
977                 GL_Color(1,1,1,1);
978                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[0], varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
979                 R_Mesh_Draw(numverts, numtriangles, elements);
980
981                 m.tex[0] = R_GetTexture(bumptexture);
982                 m.tex[1] = 0;
983                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
984                 m.texcombinergb[0] = GL_REPLACE;
985                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
986                 R_Mesh_TextureState(&m);
987                 qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
988                 qglEnable(GL_BLEND);
989                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
990                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
991                 R_Mesh_Draw(numverts, numtriangles, elements);
992
993                 m.tex[0] = R_GetTexture(basetexture);
994                 m.texcubemap[1] = R_GetTexture(lightcubemap);
995                 m.texcombinergb[0] = GL_MODULATE;
996                 m.texcombinergb[1] = GL_MODULATE;
997                 R_Mesh_TextureState(&m);
998                 qglColorMask(1,1,1,1);
999                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1000                 if (lightcubemap)
1001                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
1002
1003                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
1004                 for (mult = 1, scale = ixtable[mult];mult < 64 && (lightcolor[0] * scale * colorscale > 1 || lightcolor[1] * scale * colorscale > 1 || lightcolor[2] * scale * colorscale > 1);mult++, scale = ixtable[mult]);
1005                 colorscale *= scale;
1006                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
1007                 for (renders = 0;renders < mult;renders++)
1008                         R_Mesh_Draw(numverts, numtriangles, elements);
1009         }
1010 }
1011
1012 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, rtexture_t *glosstexture, rtexture_t *bumptexture, rtexture_t *lightcubemap)
1013 {
1014         int renders, mult;
1015         float scale, colorscale;
1016         rmeshstate_t m;
1017         memset(&m, 0, sizeof(m));
1018         if (!bumptexture)
1019                 bumptexture = r_shadow_blankbumptexture;
1020         if (!glosstexture)
1021                 glosstexture = r_shadow_blankglosstexture;
1022         if (r_shadow_gloss.integer >= 2 || (r_shadow_gloss.integer >= 1 && glosstexture != r_shadow_blankglosstexture))
1023         {
1024                 // 2 texture no3D combine path, five pass
1025                 memset(&m, 0, sizeof(m));
1026
1027                 m.tex[0] = R_GetTexture(bumptexture);
1028                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
1029                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1030                 R_Mesh_TextureState(&m);
1031                 qglColorMask(0,0,0,1);
1032                 qglDisable(GL_BLEND);
1033                 GL_Color(1,1,1,1);
1034                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1035                 R_Shadow_GenTexCoords_Specular_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, relativeeyeorigin);
1036                 R_Mesh_Draw(numverts, numtriangles, elements);
1037
1038                 m.tex[0] = 0;
1039                 m.texcubemap[1] = 0;
1040                 m.texcombinergb[1] = GL_MODULATE;
1041                 R_Mesh_TextureState(&m);
1042                 // square alpha in framebuffer a few times to make it shiny
1043                 qglBlendFunc(GL_ZERO, GL_DST_ALPHA);
1044                 qglEnable(GL_BLEND);
1045                 // these comments are a test run through this math for intensity 0.5
1046                 // 0.5 * 0.5 = 0.25
1047                 R_Mesh_Draw(numverts, numtriangles, elements);
1048                 // 0.25 * 0.25 = 0.0625
1049                 R_Mesh_Draw(numverts, numtriangles, elements);
1050                 // 0.0625 * 0.0625 = 0.00390625
1051                 R_Mesh_Draw(numverts, numtriangles, elements);
1052
1053                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1054                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1055                 R_Mesh_TextureState(&m);
1056                 qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
1057                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[0], varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
1058                 R_Mesh_Draw(numverts, numtriangles, elements);
1059
1060                 m.tex[0] = R_GetTexture(glosstexture);
1061                 m.texcubemap[1] = R_GetTexture(lightcubemap);
1062                 R_Mesh_TextureState(&m);
1063                 qglColorMask(1,1,1,1);
1064                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
1065                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
1066                 if (lightcubemap)
1067                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
1068
1069                 // the 0.25f makes specular lighting much dimmer than diffuse (intentionally)
1070                 colorscale = r_colorscale * 0.25f * r_shadow_lightintensityscale.value;
1071                 for (mult = 1, scale = ixtable[mult];mult < 64 && (lightcolor[0] * scale * colorscale > 1 || lightcolor[1] * scale * colorscale > 1 || lightcolor[2] * scale * colorscale > 1);mult++, scale = ixtable[mult]);
1072                 colorscale *= scale;
1073                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
1074                 for (renders = 0;renders < mult;renders++)
1075                         R_Mesh_Draw(numverts, numtriangles, elements);
1076         }
1077 }
1078
1079 #define PRECOMPUTEDSHADOWVOLUMES 1
1080 void R_Shadow_DrawWorldLightShadowVolume(matrix4x4_t *matrix, worldlight_t *light)
1081 {
1082 #if PRECOMPUTEDSHADOWVOLUMES
1083         R_Mesh_Matrix(matrix);
1084         R_Shadow_RenderShadowMeshVolume(light->shadowvolume);
1085 #else
1086         shadowmesh_t *mesh;
1087         R_Mesh_Matrix(matrix);
1088         for (mesh = light->shadowvolume;mesh;mesh = mesh->next)
1089         {
1090                 R_Mesh_ResizeCheck(mesh->numverts * 2);
1091                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1092                 R_Shadow_Volume(mesh->numverts, mesh->numtriangles, varray_vertex, mesh->elements, mesh->neighbors, light->origin, light->lightradius, light->lightradius);
1093         }
1094 #endif
1095 }
1096
1097 cvar_t r_editlights = {0, "r_editlights", "0"};
1098 cvar_t r_editlights_cursordistance = {0, "r_editlights_distance", "1024"};
1099 cvar_t r_editlights_cursorpushback = {0, "r_editlights_pushback", "0"};
1100 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_pushoff", "4"};
1101 cvar_t r_editlights_cursorgrid = {0, "r_editlights_grid", "4"};
1102 worldlight_t *r_shadow_worldlightchain;
1103 worldlight_t *r_shadow_selectedlight;
1104 vec3_t r_editlights_cursorlocation;
1105
1106 static int castshadowcount = 1;
1107 void R_Shadow_NewWorldLight(vec3_t origin, float radius, vec3_t color, int style, const char *cubemapname)
1108 {
1109         int i, j, k, l, maxverts, *mark;
1110         float *verts, *v, *v0, *v1, f, projectdistance, temp[3], temp2[3], temp3[3], radius2;
1111         worldlight_t *e;
1112         shadowmesh_t *mesh;
1113         mleaf_t *leaf;
1114         msurface_t *surf;
1115         qbyte *pvs;
1116
1117         e = Mem_Alloc(r_shadow_mempool, sizeof(worldlight_t));
1118         VectorCopy(origin, e->origin);
1119         VectorCopy(color, e->light);
1120         e->lightradius = radius;
1121         VectorCopy(origin, e->mins);
1122         VectorCopy(origin, e->maxs);
1123         e->cullradius = 0;
1124         e->style = style;
1125         e->next = r_shadow_worldlightchain;
1126         r_shadow_worldlightchain = e;
1127         if (cubemapname)
1128         {
1129                 e->cubemapname = Mem_Alloc(r_shadow_mempool, strlen(cubemapname) + 1);
1130                 strcpy(e->cubemapname, cubemapname);
1131                 // FIXME: add cubemap loading (and don't load a cubemap twice)
1132         }
1133         if (cl.worldmodel)
1134         {
1135                 castshadowcount++;
1136                 leaf = Mod_PointInLeaf(origin, cl.worldmodel);
1137                 pvs = Mod_LeafPVS(leaf, cl.worldmodel);
1138                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1139                 {
1140                         if (pvs[i >> 3] & (1 << (i & 7)))
1141                         {
1142                                 VectorCopy(origin, temp);
1143                                 if (temp[0] < leaf->mins[0]) temp[0] = leaf->mins[0];
1144                                 if (temp[0] > leaf->maxs[0]) temp[0] = leaf->maxs[0];
1145                                 if (temp[1] < leaf->mins[1]) temp[1] = leaf->mins[1];
1146                                 if (temp[1] > leaf->maxs[1]) temp[1] = leaf->maxs[1];
1147                                 if (temp[2] < leaf->mins[2]) temp[2] = leaf->mins[2];
1148                                 if (temp[2] > leaf->maxs[2]) temp[2] = leaf->maxs[2];
1149                                 VectorSubtract(temp, origin, temp);
1150                                 if (DotProduct(temp, temp) < e->lightradius * e->lightradius)
1151                                 {
1152                                         leaf->worldnodeframe = castshadowcount;
1153                                         for (j = 0, mark = leaf->firstmarksurface;j < leaf->nummarksurfaces;j++, mark++)
1154                                         {
1155                                                 surf = cl.worldmodel->surfaces + *mark;
1156                                                 if (surf->castshadow != castshadowcount)
1157                                                 {
1158                                                         f = DotProduct(e->origin, surf->plane->normal) - surf->plane->dist;
1159                                                         if (surf->flags & SURF_PLANEBACK)
1160                                                                 f = -f;
1161                                                         if (f > 0 && f < e->lightradius)
1162                                                         {
1163                                                                 VectorSubtract(e->origin, surf->poly_center, temp);
1164                                                                 if (DotProduct(temp, temp) - surf->poly_radius2 < e->lightradius * e->lightradius)
1165                                                                         surf->castshadow = castshadowcount;
1166                                                         }
1167                                                 }
1168                                         }
1169                                 }
1170                         }
1171                 }
1172
1173                 e->numleafs = 0;
1174                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1175                         if (leaf->worldnodeframe == castshadowcount)
1176                                 e->numleafs++;
1177                 e->numsurfaces = 0;
1178                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1179                         if (surf->castshadow == castshadowcount)
1180                                 e->numsurfaces++;
1181
1182                 if (e->numleafs)
1183                         e->leafs = Mem_Alloc(r_shadow_mempool, e->numleafs * sizeof(mleaf_t *));
1184                 if (e->numsurfaces)
1185                         e->surfaces = Mem_Alloc(r_shadow_mempool, e->numsurfaces * sizeof(msurface_t *));
1186                 e->numleafs = 0;
1187                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1188                         if (leaf->worldnodeframe == castshadowcount)
1189                                 e->leafs[e->numleafs++] = leaf;
1190                 e->numsurfaces = 0;
1191                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1192                         if (surf->castshadow == castshadowcount)
1193                                 e->surfaces[e->numsurfaces++] = surf;
1194                 // find bounding box and sphere of lit surfaces
1195                 // (these will be used for creating a shape to clip the light)
1196                 radius2 = 0;
1197                 VectorCopy(e->origin, e->mins);
1198                 VectorCopy(e->origin, e->maxs);
1199                 for (j = 0;j < e->numsurfaces;j++)
1200                 {
1201                         surf = e->surfaces[j];
1202                         for (k = 0, v = surf->poly_verts;k < surf->poly_numverts;k++, v += 3)
1203                         {
1204                                 if (e->mins[0] > v[0]) e->mins[0] = v[0];if (e->maxs[0] < v[0]) e->maxs[0] = v[0];
1205                                 if (e->mins[1] > v[1]) e->mins[1] = v[1];if (e->maxs[1] < v[1]) e->maxs[1] = v[1];
1206                                 if (e->mins[2] > v[2]) e->mins[2] = v[2];if (e->maxs[2] < v[2]) e->maxs[2] = v[2];
1207                                 VectorSubtract(v, e->origin, temp);
1208                                 f = DotProduct(temp, temp);
1209                                 if (radius2 < f)
1210                                         radius2 = f;
1211                         }
1212                 }
1213                 e->cullradius = sqrt(radius2);
1214                 if (e->cullradius > e->lightradius)
1215                         e->cullradius = e->lightradius;
1216                 if (e->mins[0] < e->origin[0] - e->lightradius) e->mins[0] = e->origin[0] - e->lightradius;
1217                 if (e->maxs[0] > e->origin[0] + e->lightradius) e->maxs[0] = e->origin[0] + e->lightradius;
1218                 if (e->mins[1] < e->origin[1] - e->lightradius) e->mins[1] = e->origin[1] - e->lightradius;
1219                 if (e->maxs[1] > e->origin[1] + e->lightradius) e->maxs[1] = e->origin[1] + e->lightradius;
1220                 if (e->mins[2] < e->origin[2] - e->lightradius) e->mins[2] = e->origin[2] - e->lightradius;
1221                 if (e->maxs[2] > e->origin[2] + e->lightradius) e->maxs[2] = e->origin[2] + e->lightradius;
1222                 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);
1223                 // clip shadow volumes against eachother to remove unnecessary
1224                 // polygons (and sections of polygons)
1225                 maxverts = 256;
1226                 verts = NULL;
1227                 castshadowcount++;
1228                 for (j = 0;j < e->numsurfaces;j++)
1229                 {
1230                         surf = e->surfaces[j];
1231                         if (surf->flags & SURF_SHADOWCAST)
1232                         {
1233                                 surf->castshadow = castshadowcount;
1234                                 if (maxverts < surf->poly_numverts)
1235                                         maxverts = surf->poly_numverts;
1236                         }
1237                 }
1238                 e->shadowvolume = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1239 #if !PRECOMPUTEDSHADOWVOLUMES
1240                 // make a mesh to cast a shadow volume from
1241                 for (j = 0;j < e->numsurfaces;j++)
1242                         if (e->surfaces[j]->castshadow == castshadowcount)
1243                                 Mod_ShadowMesh_AddPolygon(r_shadow_mempool, e->shadowvolume, e->surfaces[j]->poly_numverts, e->surfaces[j]->poly_verts);
1244 #else
1245 #if 1
1246                 {
1247                 int tris;
1248                 shadowmesh_t *castmesh, *mesh;
1249                 surfmesh_t *surfmesh;
1250                 // make a mesh to cast a shadow volume from
1251                 castmesh = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1252                 for (j = 0;j < e->numsurfaces;j++)
1253                         if (e->surfaces[j]->castshadow == castshadowcount)
1254                                 for (surfmesh = e->surfaces[j]->mesh;surfmesh;surfmesh = surfmesh->chain)
1255                                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, castmesh, surfmesh->numverts, surfmesh->verts, surfmesh->numtriangles, surfmesh->index);
1256                 castmesh = Mod_ShadowMesh_Finish(r_shadow_mempool, castmesh);
1257
1258                 // cast shadow volume from castmesh
1259                 for (mesh = castmesh;mesh;mesh = mesh->next)
1260                 {
1261                         R_Shadow_ResizeTriangleFacingLight(castmesh->numtriangles);
1262                         R_Shadow_ResizeShadowElements(castmesh->numtriangles);
1263
1264                         if (maxverts < castmesh->numverts * 2)
1265                         {
1266                                 maxverts = castmesh->numverts * 2;
1267                                 if (verts)
1268                                         Mem_Free(verts);
1269                                 verts = NULL;
1270                         }
1271                         if (verts == NULL && maxverts > 0)
1272                                 verts = Mem_Alloc(r_shadow_mempool, maxverts * sizeof(float[4]));
1273
1274                         // now that we have the buffers big enough, construct shadow volume mesh
1275                         memcpy(verts, castmesh->verts, castmesh->numverts * sizeof(float[4]));
1276                         R_Shadow_ProjectVertices(verts, verts + castmesh->numverts * 4, castmesh->numverts, e->origin, e->lightradius);
1277                         R_Shadow_MakeTriangleShadowFlags(castmesh->elements, verts, castmesh->numtriangles, trianglefacinglight, e->origin, e->lightradius);
1278                         tris = R_Shadow_BuildShadowVolumeTriangles(castmesh->elements, castmesh->neighbors, castmesh->numtriangles, castmesh->numverts, trianglefacinglight, shadowelements);
1279                         // add the constructed shadow volume mesh
1280                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, e->shadowvolume, castmesh->numverts, verts, tris, shadowelements);
1281                 }
1282                 // we're done with castmesh now
1283                 Mod_ShadowMesh_Free(castmesh);
1284                 }
1285 #else
1286                 // make a shadow volume mesh
1287                 if (verts == NULL && maxverts > 0)
1288                         verts = Mem_Alloc(r_shadow_mempool, maxverts * sizeof(float[4]));
1289                 for (j = 0;j < e->numsurfaces;j++)
1290                 {
1291                         surf = e->surfaces[j];
1292                         if (surf->castshadow != castshadowcount)
1293                                 continue;
1294                         projectdistance = 1000000.0f;//e->lightradius;
1295                         // copy the original polygon, for the front cap of the volume
1296                         for (k = 0, v0 = surf->poly_verts, v1 = verts;k < surf->poly_numverts;k++, v0 += 3, v1 += 3)
1297                                 VectorCopy(v0, v1);
1298                         Mod_ShadowMesh_AddPolygon(r_shadow_mempool, e->shadowvolume, surf->poly_numverts, verts);
1299                         // project the original polygon, reversed, for the back cap of the volume
1300                         for (k = 0, v0 = surf->poly_verts + (surf->poly_numverts - 1) * 3, v1 = verts;k < surf->poly_numverts;k++, v0 -= 3, v1 += 3)
1301                         {
1302                                 VectorSubtract(v0, e->origin, temp);
1303                                 //VectorNormalize(temp);
1304                                 VectorMA(v0, projectdistance, temp, v1);
1305                         }
1306                         Mod_ShadowMesh_AddPolygon(r_shadow_mempool, e->shadowvolume, surf->poly_numverts, verts);
1307                         // project the shadow volume sides
1308                         for (l = surf->poly_numverts - 1, k = 0, v0 = surf->poly_verts + (surf->poly_numverts - 1) * 3, v1 = surf->poly_verts;k < surf->poly_numverts;l = k, k++, v0 = v1, v1 += 3)
1309                         {
1310                                 if (surf->neighborsurfaces == NULL || surf->neighborsurfaces[l] == NULL || surf->neighborsurfaces[l]->castshadow != castshadowcount)
1311                                 {
1312                                         VectorCopy(v1, &verts[0]);
1313                                         VectorCopy(v0, &verts[3]);
1314                                         VectorCopy(v0, &verts[6]);
1315                                         VectorCopy(v1, &verts[9]);
1316                                         VectorSubtract(&verts[6], e->origin, temp);
1317                                         //VectorNormalize(temp);
1318                                         VectorMA(&verts[6], projectdistance, temp, &verts[6]);
1319                                         VectorSubtract(&verts[9], e->origin, temp);
1320                                         //VectorNormalize(temp);
1321                                         VectorMA(&verts[9], projectdistance, temp, &verts[9]);
1322
1323 #if 0
1324                                         VectorSubtract(&verts[0], &verts[3], temp);
1325                                         VectorSubtract(&verts[6], &verts[3], temp2);
1326                                         CrossProduct(temp, temp2, temp3);
1327                                         VectorNormalize(temp3);
1328                                         if (DotProduct(surf->poly_center, temp3) > DotProduct(&verts[0], temp3))
1329                                         {
1330                                                 VectorCopy(v0, &verts[0]);
1331                                                 VectorCopy(v1, &verts[3]);
1332                                                 VectorCopy(v1, &verts[6]);
1333                                                 VectorCopy(v0, &verts[9]);
1334                                                 VectorSubtract(&verts[6], e->origin, temp);
1335                                                 //VectorNormalize(temp);
1336                                                 VectorMA(&verts[6], projectdistance, temp, &verts[6]);
1337                                                 VectorSubtract(&verts[9], e->origin, temp);
1338                                                 //VectorNormalize(temp);
1339                                                 VectorMA(&verts[9], projectdistance, temp, &verts[9]);
1340                                                 Con_Printf("flipped shadow volume edge %8p %i\n", surf, l);
1341                                         }
1342 #endif
1343
1344                                         Mod_ShadowMesh_AddPolygon(r_shadow_mempool, e->shadowvolume, 4, verts);
1345                                 }
1346                         }
1347                 }
1348 #endif
1349 #endif
1350                 e->shadowvolume = Mod_ShadowMesh_Finish(r_shadow_mempool, e->shadowvolume);
1351                 for (l = 0, mesh = e->shadowvolume;mesh;mesh = mesh->next)
1352                         l += mesh->numtriangles;
1353                 Con_Printf("static shadow volume built containing %i triangles\n", l);
1354         }
1355 }
1356
1357 void R_Shadow_FreeWorldLight(worldlight_t *light)
1358 {
1359         worldlight_t **lightpointer;
1360         for (lightpointer = &r_shadow_worldlightchain;*lightpointer && *lightpointer != light;lightpointer = &(*lightpointer)->next);
1361         if (*lightpointer != light)
1362                 Sys_Error("R_Shadow_FreeWorldLight: light not linked into chain\n");
1363         *lightpointer = light->next;
1364         if (light->cubemapname)
1365                 Mem_Free(light->cubemapname);
1366         if (light->shadowvolume)
1367                 Mod_ShadowMesh_Free(light->shadowvolume);
1368         if (light->surfaces)
1369                 Mem_Free(light->surfaces);
1370         if (light->leafs)
1371                 Mem_Free(light->leafs);
1372         Mem_Free(light);
1373 }
1374
1375 void R_Shadow_ClearWorldLights(void)
1376 {
1377         while (r_shadow_worldlightchain)
1378                 R_Shadow_FreeWorldLight(r_shadow_worldlightchain);
1379         r_shadow_selectedlight = NULL;
1380 }
1381
1382 void R_Shadow_SelectLight(worldlight_t *light)
1383 {
1384         if (r_shadow_selectedlight)
1385                 r_shadow_selectedlight->selected = false;
1386         r_shadow_selectedlight = light;
1387         if (r_shadow_selectedlight)
1388                 r_shadow_selectedlight->selected = true;
1389 }
1390
1391 void R_Shadow_FreeSelectedWorldLight(void)
1392 {
1393         if (r_shadow_selectedlight)
1394         {
1395                 R_Shadow_FreeWorldLight(r_shadow_selectedlight);
1396                 r_shadow_selectedlight = NULL;
1397         }
1398 }
1399
1400 void R_Shadow_SelectLightInView(void)
1401 {
1402         float bestrating, rating, temp[3], dist;
1403         worldlight_t *best, *light;
1404         best = NULL;
1405         bestrating = 1e30;
1406         for (light = r_shadow_worldlightchain;light;light = light->next)
1407         {
1408                 VectorSubtract(light->origin, r_refdef.vieworg, temp);
1409                 dist = sqrt(DotProduct(temp, temp));
1410                 if (DotProduct(temp, vpn) >= 0.97 * dist && bestrating > dist && CL_TraceLine(light->origin, r_refdef.vieworg, NULL, NULL, 0, true, NULL) == 1.0f)
1411                 {
1412                         bestrating = dist;
1413                         best = light;
1414                 }
1415         }
1416         R_Shadow_SelectLight(best);
1417 }
1418
1419 void R_Shadow_LoadWorldLights(void)
1420 {
1421         int n, a, style;
1422         char name[MAX_QPATH], cubemapname[MAX_QPATH], *lightsstring, *s, *t;
1423         float origin[3], radius, color[3];
1424         COM_StripExtension(cl.worldmodel->name, name);
1425         strcat(name, ".rtlights");
1426         lightsstring = COM_LoadFile(name, false);
1427         if (lightsstring)
1428         {
1429                 s = lightsstring;
1430                 n = 0;
1431                 while (*s)
1432                 {
1433                         t = s;
1434                         while (*s && *s != '\n')
1435                                 s++;
1436                         if (!*s)
1437                                 break;
1438                         *s = 0;
1439                         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);
1440                         if (a < 9)
1441                                 cubemapname[0] = 0;
1442                         *s = '\n';
1443                         if (a < 8)
1444                         {
1445                                 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);
1446                                 break;
1447                         }
1448                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1449                         s++;
1450                         n++;
1451                 }
1452                 if (*s)
1453                         Con_Printf("invalid rtlights file \"%s\"\n", name);
1454                 Mem_Free(lightsstring);
1455         }
1456 }
1457
1458 void R_Shadow_SaveWorldLights(void)
1459 {
1460         worldlight_t *light;
1461         int bufchars, bufmaxchars;
1462         char *buf, *oldbuf;
1463         char name[MAX_QPATH];
1464         char line[1024];
1465         if (!r_shadow_worldlightchain)
1466                 return;
1467         COM_StripExtension(cl.worldmodel->name, name);
1468         strcat(name, ".rtlights");
1469         bufchars = bufmaxchars = 0;
1470         buf = NULL;
1471         for (light = r_shadow_worldlightchain;light;light = light->next)
1472         {
1473                 sprintf(line, "%g %g %g %g %g %g %g %d %s\n", light->origin[0], light->origin[1], light->origin[2], light->lightradius, light->light[0], light->light[1], light->light[2], light->style, light->cubemapname ? light->cubemapname : "");
1474                 if (bufchars + strlen(line) > bufmaxchars)
1475                 {
1476                         bufmaxchars = bufchars + strlen(line) + 2048;
1477                         oldbuf = buf;
1478                         buf = Mem_Alloc(r_shadow_mempool, bufmaxchars);
1479                         if (oldbuf)
1480                         {
1481                                 if (bufchars)
1482                                         memcpy(buf, oldbuf, bufchars);
1483                                 Mem_Free(oldbuf);
1484                         }
1485                 }
1486                 if (strlen(line))
1487                 {
1488                         memcpy(buf + bufchars, line, strlen(line));
1489                         bufchars += strlen(line);
1490                 }
1491         }
1492         if (bufchars)
1493                 COM_WriteFile(name, buf, bufchars);
1494         if (buf)
1495                 Mem_Free(buf);
1496 }
1497
1498 void R_Shadow_LoadLightsFile(void)
1499 {
1500         int n, a, style;
1501         char name[MAX_QPATH], cubemapname[MAX_QPATH], *lightsstring, *s, *t;
1502         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
1503         COM_StripExtension(cl.worldmodel->name, name);
1504         strcat(name, ".lights");
1505         lightsstring = COM_LoadFile(name, false);
1506         if (lightsstring)
1507         {
1508                 s = lightsstring;
1509                 n = 0;
1510                 while (*s)
1511                 {
1512                         t = s;
1513                         while (*s && *s != '\n')
1514                                 s++;
1515                         if (!*s)
1516                                 break;
1517                         *s = 0;
1518                         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);
1519                         *s = '\n';
1520                         if (a < 14)
1521                         {
1522                                 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);
1523                                 break;
1524                         }
1525                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
1526                         radius = bound(15, radius, 4096);
1527                         VectorScale(color, (1.0f / (8388608.0f)), color);
1528                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL);
1529                         s++;
1530                         n++;
1531                 }
1532                 if (*s)
1533                         Con_Printf("invalid lights file \"%s\"\n", name);
1534                 Mem_Free(lightsstring);
1535         }
1536 }
1537
1538 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
1539 {
1540         int entnum, style, islight;
1541         char key[256], value[1024];
1542         float origin[3], radius, color[3], light, scale, originhack[3], overridecolor[3];
1543         const char *data;
1544
1545         data = cl.worldmodel->entities;
1546         if (!data)
1547                 return;
1548         for (entnum = 0;COM_ParseToken(&data) && com_token[0] == '{';entnum++)
1549         {
1550                 light = 0;
1551                 origin[0] = origin[1] = origin[2] = 0;
1552                 originhack[0] = originhack[1] = originhack[2] = 0;
1553                 color[0] = color[1] = color[2] = 1;
1554                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
1555                 scale = 1;
1556                 style = 0;
1557                 islight = false;
1558                 while (1)
1559                 {
1560                         if (!COM_ParseToken(&data))
1561                                 break; // error
1562                         if (com_token[0] == '}')
1563                                 break; // end of entity
1564                         if (com_token[0] == '_')
1565                                 strcpy(key, com_token + 1);
1566                         else
1567                                 strcpy(key, com_token);
1568                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
1569                                 key[strlen(key)-1] = 0;
1570                         if (!COM_ParseToken(&data))
1571                                 break; // error
1572                         strcpy(value, com_token);
1573
1574                         // now that we have the key pair worked out...
1575                         if (!strcmp("light", key))
1576                                 light = atof(value);
1577                         else if (!strcmp("origin", key))
1578                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
1579                         else if (!strcmp("color", key))
1580                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
1581                         else if (!strcmp("wait", key))
1582                                 scale = atof(value);
1583                         else if (!strcmp("classname", key))
1584                         {
1585                                 if (!strncmp(value, "light", 5))
1586                                 {
1587                                         islight = true;
1588                                         if (!strcmp(value, "light_fluoro"))
1589                                         {
1590                                                 originhack[0] = 0;
1591                                                 originhack[1] = 0;
1592                                                 originhack[2] = 0;
1593                                                 overridecolor[0] = 1;
1594                                                 overridecolor[1] = 1;
1595                                                 overridecolor[2] = 1;
1596                                         }
1597                                         if (!strcmp(value, "light_fluorospark"))
1598                                         {
1599                                                 originhack[0] = 0;
1600                                                 originhack[1] = 0;
1601                                                 originhack[2] = 0;
1602                                                 overridecolor[0] = 1;
1603                                                 overridecolor[1] = 1;
1604                                                 overridecolor[2] = 1;
1605                                         }
1606                                         if (!strcmp(value, "light_globe"))
1607                                         {
1608                                                 originhack[0] = 0;
1609                                                 originhack[1] = 0;
1610                                                 originhack[2] = 0;
1611                                                 overridecolor[0] = 1;
1612                                                 overridecolor[1] = 0.8;
1613                                                 overridecolor[2] = 0.4;
1614                                         }
1615                                         if (!strcmp(value, "light_flame_large_yellow"))
1616                                         {
1617                                                 originhack[0] = 0;
1618                                                 originhack[1] = 0;
1619                                                 originhack[2] = 48;
1620                                                 overridecolor[0] = 1;
1621                                                 overridecolor[1] = 0.7;
1622                                                 overridecolor[2] = 0.2;
1623                                         }
1624                                         if (!strcmp(value, "light_flame_small_yellow"))
1625                                         {
1626                                                 originhack[0] = 0;
1627                                                 originhack[1] = 0;
1628                                                 originhack[2] = 40;
1629                                                 overridecolor[0] = 1;
1630                                                 overridecolor[1] = 0.7;
1631                                                 overridecolor[2] = 0.2;
1632                                         }
1633                                         if (!strcmp(value, "light_torch_small_white"))
1634                                         {
1635                                                 originhack[0] = 0;
1636                                                 originhack[1] = 0;
1637                                                 originhack[2] = 40;
1638                                                 overridecolor[0] = 1;
1639                                                 overridecolor[1] = 0.9;
1640                                                 overridecolor[2] = 0.7;
1641                                         }
1642                                         if (!strcmp(value, "light_torch_small_walltorch"))
1643                                         {
1644                                                 originhack[0] = 0;
1645                                                 originhack[1] = 0;
1646                                                 originhack[2] = 40;
1647                                                 overridecolor[0] = 1;
1648                                                 overridecolor[1] = 0.7;
1649                                                 overridecolor[2] = 0.2;
1650                                         }
1651                                 }
1652                         }
1653                         else if (!strcmp("style", key))
1654                                 style = atoi(value);
1655                 }
1656                 if (light <= 0 && islight)
1657                         light = 300;
1658                 radius = bound(0, light / scale, 1048576) + 15.0f;
1659                 light = bound(0, light, 1048576) * (1.0f / 256.0f);
1660                 if (color[0] == 1 && color[1] == 1 && color[2] == 1)
1661                         VectorCopy(overridecolor, color);
1662                 VectorScale(color, light, color);
1663                 VectorAdd(origin, originhack, origin);
1664                 if (radius >= 15)
1665                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL);
1666         }
1667 }
1668
1669
1670 void R_Shadow_SetCursorLocationForView(void)
1671 {
1672         vec_t dist, push, frac;
1673         vec3_t dest, endpos, normal;
1674         VectorMA(r_refdef.vieworg, r_editlights_cursordistance.value, vpn, dest);
1675         frac = CL_TraceLine(r_refdef.vieworg, dest, endpos, normal, 0, true, NULL);
1676         if (frac < 1)
1677         {
1678                 dist = frac * r_editlights_cursordistance.value;
1679                 push = r_editlights_cursorpushback.value;
1680                 if (push > dist)
1681                         push = dist;
1682                 push = -push;
1683                 VectorMA(endpos, push, vpn, endpos);
1684                 VectorMA(endpos, r_editlights_cursorpushoff.value, normal, endpos);
1685         }
1686         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1687         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1688         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1689 }
1690
1691 extern void R_DrawCrosshairSprite(rtexture_t *texture, vec3_t origin, vec_t scale, float cr, float cg, float cb, float ca);
1692 void R_Shadow_DrawCursorCallback(const void *calldata1, int calldata2)
1693 {
1694         cachepic_t *pic;
1695         pic = Draw_CachePic("gfx/crosshair1.tga");
1696         if (pic)
1697                 R_DrawCrosshairSprite(pic->tex, r_editlights_cursorlocation, r_editlights_cursorgrid.value * 0.5f, 1, 1, 1, 1);
1698 }
1699
1700 void R_Shadow_DrawCursor(void)
1701 {
1702         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursorCallback, NULL, 0);
1703 }
1704
1705 void R_Shadow_UpdateLightingMode(void)
1706 {
1707         r_shadow_lightingmode = 0;
1708         if (r_shadow_realtime.integer)
1709         {
1710                 if (r_shadow_worldlightchain)
1711                         r_shadow_lightingmode = 2;
1712                 else
1713                         r_shadow_lightingmode = 1;
1714         }
1715 }
1716
1717 void R_Shadow_UpdateWorldLightSelection(void)
1718 {
1719         if (r_editlights.integer)
1720         {
1721                 R_Shadow_SelectLightInView();
1722                 R_Shadow_SetCursorLocationForView();
1723                 R_Shadow_DrawCursor();
1724         }
1725         else
1726                 R_Shadow_SelectLight(NULL);
1727 }
1728
1729 void R_Shadow_EditLights_Clear_f(void)
1730 {
1731         R_Shadow_ClearWorldLights();
1732 }
1733
1734 void R_Shadow_EditLights_Reload_f(void)
1735 {
1736         if (cl.worldmodel)
1737         {
1738                 R_Shadow_ClearWorldLights();
1739                 R_Shadow_LoadWorldLights();
1740         }
1741 }
1742
1743 void R_Shadow_EditLights_Save_f(void)
1744 {
1745         if (cl.worldmodel)
1746                 R_Shadow_SaveWorldLights();
1747 }
1748
1749 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
1750 {
1751         R_Shadow_ClearWorldLights();
1752         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
1753 }
1754
1755 void R_Shadow_EditLights_ImportLightsFile_f(void)
1756 {
1757         R_Shadow_ClearWorldLights();
1758         R_Shadow_LoadLightsFile();
1759 }
1760
1761 void R_Shadow_EditLights_Spawn_f(void)
1762 {
1763         vec3_t origin, color;
1764         vec_t radius;
1765         int style;
1766         const char *cubemapname;
1767         if (!r_editlights.integer)
1768         {
1769                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
1770                 return;
1771         }
1772         if (Cmd_Argc() <= 7)
1773         {
1774                 radius = 200;
1775                 color[0] = color[1] = color[2] = 1;
1776                 style = 0;
1777                 cubemapname = NULL;
1778                 if (Cmd_Argc() >= 2)
1779                 {
1780                         radius = atof(Cmd_Argv(1));
1781                         if (Cmd_Argc() >= 3)
1782                         {
1783                                 color[0] = atof(Cmd_Argv(2));
1784                                 color[1] = color[0];
1785                                 color[2] = color[0];
1786                                 if (Cmd_Argc() >= 5)
1787                                 {
1788                                         color[1] = atof(Cmd_Argv(3));
1789                                         color[2] = atof(Cmd_Argv(4));
1790                                         if (Cmd_Argc() >= 6)
1791                                         {
1792                                                 style = atoi(Cmd_Argv(5));
1793                                                 if (Cmd_Argc() >= 7)
1794                                                         cubemapname = Cmd_Argv(6);
1795                                         }
1796                                 }
1797                         }
1798                 }
1799                 if (cubemapname && !cubemapname[0])
1800                         cubemapname = NULL;
1801                 if (radius >= 16 && color[0] >= 0 && color[1] >= 0 && color[2] >= 0 && style >= 0 && style < 256 && (color[0] >= 0.1 || color[1] >= 0.1 || color[2] >= 0.1))
1802                 {
1803                         VectorCopy(r_editlights_cursorlocation, origin);
1804                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1805                         return;
1806                 }
1807         }
1808         Con_Printf("usage: r_editlights_spawn radius red green blue [style [cubemap]]\n");
1809 }
1810
1811 void R_Shadow_EditLights_Edit_f(void)
1812 {
1813         vec3_t origin, color;
1814         vec_t radius;
1815         int style;
1816         const char *cubemapname;
1817         if (!r_editlights.integer)
1818         {
1819                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
1820                 return;
1821         }
1822         if (!r_shadow_selectedlight)
1823         {
1824                 Con_Printf("No selected light.\n");
1825                 return;
1826         }
1827         if (Cmd_Argc() <= 7)
1828         {
1829                 radius = 200;
1830                 color[0] = color[1] = color[2] = 1;
1831                 style = 0;
1832                 cubemapname = NULL;
1833                 if (Cmd_Argc() >= 2)
1834                 {
1835                         radius = atof(Cmd_Argv(1));
1836                         if (Cmd_Argc() >= 3)
1837                         {
1838                                 color[0] = atof(Cmd_Argv(2));
1839                                 color[1] = color[0];
1840                                 color[2] = color[0];
1841                                 if (Cmd_Argc() >= 5)
1842                                 {
1843                                         color[1] = atof(Cmd_Argv(3));
1844                                         color[2] = atof(Cmd_Argv(4));
1845                                         if (Cmd_Argc() >= 6)
1846                                         {
1847                                                 style = atoi(Cmd_Argv(5));
1848                                                 if (Cmd_Argc() >= 7)
1849                                                         cubemapname = Cmd_Argv(6);
1850                                         }
1851                                 }
1852                         }
1853                 }
1854                 if (cubemapname && !cubemapname[0])
1855                         cubemapname = NULL;
1856                 if (radius >= 16 && color[0] >= 0 && color[1] >= 0 && color[2] >= 0 && style >= 0 && style < 256 && (color[0] >= 0.1 || color[1] >= 0.1 || color[2] >= 0.1))
1857                 {
1858                         VectorCopy(r_shadow_selectedlight->origin, origin);
1859                         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
1860                         r_shadow_selectedlight = NULL;
1861                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1862                         return;
1863                 }
1864         }
1865         Con_Printf("usage: r_editlights_edit radius red green blue [style [cubemap]]\n");
1866 }
1867
1868 void R_Shadow_EditLights_Remove_f(void)
1869 {
1870         if (!r_editlights.integer)
1871         {
1872                 Con_Printf("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
1873                 return;
1874         }
1875         if (!r_shadow_selectedlight)
1876         {
1877                 Con_Printf("No selected light.\n");
1878                 return;
1879         }
1880         R_Shadow_FreeSelectedWorldLight();
1881 }
1882
1883 void R_Shadow_EditLights_Init(void)
1884 {
1885         Cvar_RegisterVariable(&r_editlights);
1886         Cvar_RegisterVariable(&r_editlights_cursordistance);
1887         Cvar_RegisterVariable(&r_editlights_cursorpushback);
1888         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
1889         Cvar_RegisterVariable(&r_editlights_cursorgrid);
1890         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f);
1891         Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f);
1892         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f);
1893         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f);
1894         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f);
1895         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f);
1896         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f);
1897         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f);
1898 }