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