82b82b5f6f050de59d044422d08c7743d985ed7b
[divverent/darkplaces.git] / gl_rsurf.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_surf.c: surface-related refresh code
21
22 #include "quakedef.h"
23 #include "r_shadow.h"
24 #include "portals.h"
25
26 #define MAX_LIGHTMAP_SIZE 256
27
28 cvar_t r_ambient = {0, "r_ambient", "0", "brighter world cheat (not allowed in multiplayer), value is 0-128"};
29 cvar_t r_lockpvs = {0, "r_lockpvs", "0", "disables pvs switching, allows you to walk around and inspect what is visible from a given location in the map (anything not visible from your current location will not be drawn)"};
30 cvar_t r_lockvisibility = {0, "r_lockvisibility", "0", "disables visibility updates, allows you to walk around and inspect what is visible from a given viewpoint in the map (anything offscreen at the moment this is enabled will not be drawn)"};
31 cvar_t r_useportalculling = {0, "r_useportalculling", "1", "use advanced portal culling visibility method to improve performance over just Potentially Visible Set, provides an even more significant speed improvement in unvised maps"};
32 cvar_t r_q3bsp_renderskydepth = {0, "r_q3bsp_renderskydepth", "0", "draws sky depth masking in q3 maps (as in q1 maps), this means for example that sky polygons can hide other things"};
33
34 /*
35 ===============
36 R_BuildLightMap
37
38 Combine and scale multiple lightmaps into the 8.8 format in blocklights
39 ===============
40 */
41 void R_BuildLightMap (const entity_render_t *ent, msurface_t *surface)
42 {
43         int smax, tmax, i, size, size3, maps, l;
44         int *bl, scale;
45         unsigned char *lightmap, *out, *stain;
46         model_t *model = ent->model;
47         static int intblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
48         static unsigned char templight[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*4];
49
50         // update cached lighting info
51         surface->cached_dlight = 0;
52
53         smax = (surface->lightmapinfo->extents[0]>>4)+1;
54         tmax = (surface->lightmapinfo->extents[1]>>4)+1;
55         size = smax*tmax;
56         size3 = size*3;
57         lightmap = surface->lightmapinfo->samples;
58
59 // set to full bright if no light data
60         bl = intblocklights;
61         if (!model->brushq1.lightdata)
62         {
63                 for (i = 0;i < size3;i++)
64                         bl[i] = 255*256;
65         }
66         else
67         {
68 // clear to no light
69                 memset(bl, 0, size3*sizeof(*bl));
70
71 // add all the lightmaps
72                 if (lightmap)
73                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3)
74                                 for (scale = r_refdef.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size3;i++)
75                                         bl[i] += lightmap[i] * scale;
76         }
77
78         stain = surface->lightmapinfo->stainsamples;
79         bl = intblocklights;
80         out = templight;
81         // the >> 16 shift adjusts down 8 bits to account for the stainmap
82         // scaling, and remaps the 0-65536 (2x overbright) to 0-256, it will
83         // be doubled during rendering to achieve 2x overbright
84         // (0 = 0.0, 128 = 1.0, 256 = 2.0)
85         if (model->brushq1.lightmaprgba)
86         {
87                 for (i = 0;i < size;i++)
88                 {
89                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
90                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
91                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
92                         *out++ = 255;
93                 }
94         }
95         else
96         {
97                 for (i = 0;i < size;i++)
98                 {
99                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
100                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
101                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
102                 }
103         }
104
105         R_UpdateTexture(surface->lightmaptexture, templight, surface->lightmapinfo->lightmaporigin[0], surface->lightmapinfo->lightmaporigin[1], smax, tmax);
106
107         // update the surface's deluxemap if it has one
108         if (surface->deluxemaptexture != r_texture_blanknormalmap)
109         {
110                 vec3_t n;
111                 unsigned char *normalmap = surface->lightmapinfo->nmapsamples;
112                 lightmap = surface->lightmapinfo->samples;
113                 // clear to no normalmap
114                 bl = intblocklights;
115                 memset(bl, 0, size3*sizeof(*bl));
116                 // add all the normalmaps
117                 if (lightmap && normalmap)
118                 {
119                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3, normalmap += size3)
120                         {
121                                 for (scale = r_refdef.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size;i++)
122                                 {
123                                         // add the normalmap with weighting proportional to the style's lightmap intensity
124                                         l = (int)(VectorLength(lightmap + i*3) * scale);
125                                         bl[i*3+0] += ((int)normalmap[i*3+0] - 128) * l;
126                                         bl[i*3+1] += ((int)normalmap[i*3+1] - 128) * l;
127                                         bl[i*3+2] += ((int)normalmap[i*3+2] - 128) * l;
128                                 }
129                         }
130                 }
131                 bl = intblocklights;
132                 out = templight;
133                 // we simply renormalize the weighted normals to get a valid deluxemap
134                 if (model->brushq1.lightmaprgba)
135                 {
136                         for (i = 0;i < size;i++, bl += 3)
137                         {
138                                 VectorCopy(bl, n);
139                                 VectorNormalize(n);
140                                 l = (int)(n[0] * 128 + 128);*out++ = bound(0, l, 255);
141                                 l = (int)(n[1] * 128 + 128);*out++ = bound(0, l, 255);
142                                 l = (int)(n[2] * 128 + 128);*out++ = bound(0, l, 255);
143                                 *out++ = 255;
144                         }
145                 }
146                 else
147                 {
148                         for (i = 0;i < size;i++, bl += 3)
149                         {
150                                 VectorCopy(bl, n);
151                                 VectorNormalize(n);
152                                 l = (int)(n[0] * 128 + 128);*out++ = bound(0, l, 255);
153                                 l = (int)(n[1] * 128 + 128);*out++ = bound(0, l, 255);
154                                 l = (int)(n[2] * 128 + 128);*out++ = bound(0, l, 255);
155                         }
156                 }
157                 R_UpdateTexture(surface->deluxemaptexture, templight, surface->lightmapinfo->lightmaporigin[0], surface->lightmapinfo->lightmaporigin[1], smax, tmax);
158         }
159 }
160
161 void R_StainNode (mnode_t *node, model_t *model, const vec3_t origin, float radius, const float fcolor[8])
162 {
163         float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
164         msurface_t *surface, *endsurface;
165         int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
166         unsigned char *bl;
167         vec3_t impact;
168
169         maxdist = radius * radius;
170         invradius = 1.0f / radius;
171
172 loc0:
173         if (!node->plane)
174                 return;
175         ndist = PlaneDiff(origin, node->plane);
176         if (ndist > radius)
177         {
178                 node = node->children[0];
179                 goto loc0;
180         }
181         if (ndist < -radius)
182         {
183                 node = node->children[1];
184                 goto loc0;
185         }
186
187         dist2 = ndist * ndist;
188         maxdist3 = maxdist - dist2;
189
190         if (node->plane->type < 3)
191         {
192                 VectorCopy(origin, impact);
193                 impact[node->plane->type] -= ndist;
194         }
195         else
196         {
197                 impact[0] = origin[0] - node->plane->normal[0] * ndist;
198                 impact[1] = origin[1] - node->plane->normal[1] * ndist;
199                 impact[2] = origin[2] - node->plane->normal[2] * ndist;
200         }
201
202         for (surface = model->data_surfaces + node->firstsurface, endsurface = surface + node->numsurfaces;surface < endsurface;surface++)
203         {
204                 if (surface->lightmapinfo->stainsamples)
205                 {
206                         smax = (surface->lightmapinfo->extents[0] >> 4) + 1;
207                         tmax = (surface->lightmapinfo->extents[1] >> 4) + 1;
208
209                         impacts = (int)(DotProduct (impact, surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3] - surface->lightmapinfo->texturemins[0]);
210                         impactt = (int)(DotProduct (impact, surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3] - surface->lightmapinfo->texturemins[1]);
211
212                         s = bound(0, impacts, smax * 16) - impacts;
213                         t = bound(0, impactt, tmax * 16) - impactt;
214                         i = (int)(s * s + t * t + dist2);
215                         if (i > maxdist)
216                                 continue;
217
218                         // reduce calculations
219                         for (s = 0, i = impacts; s < smax; s++, i -= 16)
220                                 sdtable[s] = i * i + dist2;
221
222                         bl = surface->lightmapinfo->stainsamples;
223                         smax3 = smax * 3;
224                         stained = false;
225
226                         i = impactt;
227                         for (t = 0;t < tmax;t++, i -= 16)
228                         {
229                                 td = i * i;
230                                 // make sure some part of it is visible on this line
231                                 if (td < maxdist3)
232                                 {
233                                         maxdist2 = maxdist - td;
234                                         for (s = 0;s < smax;s++)
235                                         {
236                                                 if (sdtable[s] < maxdist2)
237                                                 {
238                                                         ratio = lhrandom(0.0f, 1.0f);
239                                                         a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
240                                                         if (a >= (1.0f / 64.0f))
241                                                         {
242                                                                 if (a > 1)
243                                                                         a = 1;
244                                                                 bl[0] = (unsigned char) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
245                                                                 bl[1] = (unsigned char) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
246                                                                 bl[2] = (unsigned char) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
247                                                                 stained = true;
248                                                         }
249                                                 }
250                                                 bl += 3;
251                                         }
252                                 }
253                                 else // skip line
254                                         bl += smax3;
255                         }
256                         // force lightmap upload
257                         if (stained)
258                                 surface->cached_dlight = true;
259                 }
260         }
261
262         if (node->children[0]->plane)
263         {
264                 if (node->children[1]->plane)
265                 {
266                         R_StainNode(node->children[0], model, origin, radius, fcolor);
267                         node = node->children[1];
268                         goto loc0;
269                 }
270                 else
271                 {
272                         node = node->children[0];
273                         goto loc0;
274                 }
275         }
276         else if (node->children[1]->plane)
277         {
278                 node = node->children[1];
279                 goto loc0;
280         }
281 }
282
283 void R_Stain (const vec3_t origin, float radius, int cr1, int cg1, int cb1, int ca1, int cr2, int cg2, int cb2, int ca2)
284 {
285         int n;
286         float fcolor[8];
287         entity_render_t *ent;
288         model_t *model;
289         vec3_t org;
290         if (r_refdef.worldmodel == NULL || !r_refdef.worldmodel->brush.data_nodes || !r_refdef.worldmodel->brushq1.lightdata)
291                 return;
292         fcolor[0] = cr1;
293         fcolor[1] = cg1;
294         fcolor[2] = cb1;
295         fcolor[3] = ca1 * (1.0f / 64.0f);
296         fcolor[4] = cr2 - cr1;
297         fcolor[5] = cg2 - cg1;
298         fcolor[6] = cb2 - cb1;
299         fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
300
301         R_StainNode(r_refdef.worldmodel->brush.data_nodes + r_refdef.worldmodel->brushq1.hulls[0].firstclipnode, r_refdef.worldmodel, origin, radius, fcolor);
302
303         // look for embedded bmodels
304         for (n = 0;n < cl.num_brushmodel_entities;n++)
305         {
306                 ent = &cl.entities[cl.brushmodel_entities[n]].render;
307                 model = ent->model;
308                 if (model && model->name[0] == '*')
309                 {
310                         if (model->brush.data_nodes)
311                         {
312                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
313                                 R_StainNode(model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
314                         }
315                 }
316         }
317 }
318
319
320 /*
321 =============================================================
322
323         BRUSH MODELS
324
325 =============================================================
326 */
327
328 static void R_DrawPortal_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
329 {
330         // due to the hacky nature of this function's parameters, this is never
331         // called with a batch, so numsurfaces is always 1, and the surfacelist
332         // contains only a leaf number for coloring purposes
333         const mportal_t *portal = (mportal_t *)ent;
334         int i, numpoints;
335         float *v;
336         float vertex3f[POLYGONELEMENTS_MAXPOINTS*3];
337         CHECKGLERROR
338         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
339         GL_DepthMask(false);
340         GL_DepthTest(true);
341         GL_CullFace(GL_NONE);
342         R_Mesh_Matrix(&identitymatrix);
343
344         numpoints = min(portal->numpoints, POLYGONELEMENTS_MAXPOINTS);
345
346         R_Mesh_VertexPointer(vertex3f);
347         R_Mesh_ColorPointer(NULL);
348         R_Mesh_ResetTextureState();
349
350         i = surfacelist[0];
351         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_view.colorscale,
352                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_view.colorscale,
353                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_view.colorscale,
354                          0.125f);
355         for (i = 0, v = vertex3f;i < numpoints;i++, v += 3)
356                 VectorCopy(portal->points[i].position, v);
357         R_Mesh_Draw(0, numpoints, numpoints - 2, polygonelements);
358 }
359
360 // LordHavoc: this is just a nice debugging tool, very slow
361 void R_DrawPortals(void)
362 {
363         int i, leafnum;
364         mportal_t *portal;
365         float center[3], f;
366         model_t *model = r_refdef.worldmodel;
367         if (model == NULL)
368                 return;
369         for (leafnum = 0;leafnum < r_refdef.worldmodel->brush.num_leafs;leafnum++)
370         {
371                 if (r_viewcache.world_leafvisible[leafnum])
372                 {
373                         //for (portalnum = 0, portal = model->brush.data_portals;portalnum < model->brush.num_portals;portalnum++, portal++)
374                         for (portal = r_refdef.worldmodel->brush.data_leafs[leafnum].portals;portal;portal = portal->next)
375                         {
376                                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
377                                 if (!R_CullBox(portal->mins, portal->maxs))
378                                 {
379                                         VectorClear(center);
380                                         for (i = 0;i < portal->numpoints;i++)
381                                                 VectorAdd(center, portal->points[i].position, center);
382                                         f = ixtable[portal->numpoints];
383                                         VectorScale(center, f, center);
384                                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, (entity_render_t *)portal, leafnum, r_shadow_rtlight);
385                                 }
386                         }
387                 }
388         }
389 }
390
391 void R_View_WorldVisibility(void)
392 {
393         int i, j, *mark;
394         mleaf_t *leaf;
395         mleaf_t *viewleaf;
396         model_t *model = r_refdef.worldmodel;
397
398         if (!model)
399                 return;
400
401         // if possible find the leaf the view origin is in
402         viewleaf = model->brush.PointInLeaf ? model->brush.PointInLeaf(model, r_view.origin) : NULL;
403         // if possible fetch the visible cluster bits
404         if (!r_lockpvs.integer && model->brush.FatPVS)
405                 model->brush.FatPVS(model, r_view.origin, 2, r_viewcache.world_pvsbits, sizeof(r_viewcache.world_pvsbits));
406
407         if (!r_lockvisibility.integer)
408         {
409                 // clear the visible surface and leaf flags arrays
410                 memset(r_viewcache.world_surfacevisible, 0, model->num_surfaces);
411                 memset(r_viewcache.world_leafvisible, 0, model->brush.num_leafs);
412
413                 r_viewcache.world_novis = false;
414
415                 // if floating around in the void (no pvs data available, and no
416                 // portals available), simply use all on-screen leafs.
417                 if (!viewleaf || viewleaf->clusterindex < 0)
418                 {
419                         // no visibility method: (used when floating around in the void)
420                         // simply cull each leaf to the frustum (view pyramid)
421                         // similar to quake's RecursiveWorldNode but without cache misses
422                         r_viewcache.world_novis = true;
423                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
424                         {
425                                 // if leaf is in current pvs and on the screen, mark its surfaces
426                                 if (!R_CullBox(leaf->mins, leaf->maxs))
427                                 {
428                                         r_refdef.stats.world_leafs++;
429                                         r_viewcache.world_leafvisible[j] = true;
430                                         if (leaf->numleafsurfaces)
431                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
432                                                         r_viewcache.world_surfacevisible[*mark] = true;
433                                 }
434                         }
435                 }
436                 // if the user prefers to disable portal culling (testing?), simply
437                 // use all on-screen leafs that are in the pvs.
438                 else if (!r_useportalculling.integer)
439                 {
440                         // pvs method:
441                         // simply check if each leaf is in the Potentially Visible Set,
442                         // and cull to frustum (view pyramid)
443                         // similar to quake's RecursiveWorldNode but without cache misses
444                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
445                         {
446                                 // if leaf is in current pvs and on the screen, mark its surfaces
447                                 if (CHECKPVSBIT(r_viewcache.world_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
448                                 {
449                                         r_refdef.stats.world_leafs++;
450                                         r_viewcache.world_leafvisible[j] = true;
451                                         if (leaf->numleafsurfaces)
452                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
453                                                         r_viewcache.world_surfacevisible[*mark] = true;
454                                 }
455                         }
456                 }
457                 // otherwise use a recursive portal flow, culling each portal to
458                 // frustum and checking if the leaf the portal leads to is in the pvs
459                 else
460                 {
461                         int leafstackpos;
462                         mportal_t *p;
463                         mleaf_t *leafstack[8192];
464                         // simple-frustum portal method:
465                         // follows portals leading outward from viewleaf, does not venture
466                         // offscreen or into leafs that are not visible, faster than
467                         // Quake's RecursiveWorldNode and vastly better in unvised maps,
468                         // often culls some surfaces that pvs alone would miss
469                         // (such as a room in pvs that is hidden behind a wall, but the
470                         //  passage leading to the room is off-screen)
471                         leafstack[0] = viewleaf;
472                         leafstackpos = 1;
473                         while (leafstackpos)
474                         {
475                                 r_refdef.stats.world_leafs++;
476                                 leaf = leafstack[--leafstackpos];
477                                 r_viewcache.world_leafvisible[leaf - model->brush.data_leafs] = true;
478                                 // mark any surfaces bounding this leaf
479                                 if (leaf->numleafsurfaces)
480                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
481                                                 r_viewcache.world_surfacevisible[*mark] = true;
482                                 // follow portals into other leafs
483                                 // the checks are:
484                                 // if viewer is behind portal (portal faces outward into the scene)
485                                 // and the portal polygon's bounding box is on the screen
486                                 // and the leaf has not been visited yet
487                                 // and the leaf is visible in the pvs
488                                 // (the first two checks won't cause as many cache misses as the leaf checks)
489                                 for (p = leaf->portals;p;p = p->next)
490                                 {
491                                         r_refdef.stats.world_portals++;
492                                         if (DotProduct(r_view.origin, p->plane.normal) < (p->plane.dist + 1) && !R_CullBox(p->mins, p->maxs) && !r_viewcache.world_leafvisible[p->past - model->brush.data_leafs] && CHECKPVSBIT(r_viewcache.world_pvsbits, p->past->clusterindex))
493                                                 leafstack[leafstackpos++] = p->past;
494                                 }
495                         }
496                 }
497         }
498 }
499
500 void R_Q1BSP_DrawSky(entity_render_t *ent)
501 {
502         if (ent->model == NULL)
503                 return;
504         R_DrawSurfaces(ent, true);
505 }
506
507 void R_Q1BSP_Draw(entity_render_t *ent)
508 {
509         model_t *model = ent->model;
510         if (model == NULL)
511                 return;
512         R_DrawSurfaces(ent, false);
513 }
514
515 typedef struct r_q1bsp_getlightinfo_s
516 {
517         model_t *model;
518         vec3_t relativelightorigin;
519         float lightradius;
520         int *outleaflist;
521         unsigned char *outleafpvs;
522         int outnumleafs;
523         int *outsurfacelist;
524         unsigned char *outsurfacepvs;
525         int outnumsurfaces;
526         vec3_t outmins;
527         vec3_t outmaxs;
528         vec3_t lightmins;
529         vec3_t lightmaxs;
530         const unsigned char *pvs;
531 }
532 r_q1bsp_getlightinfo_t;
533
534 void R_Q1BSP_RecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, mnode_t *node)
535 {
536         int sides;
537         mleaf_t *leaf;
538         for (;;)
539         {
540                 mplane_t *plane = node->plane;
541                 //if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
542                 //      return;
543                 if (!plane)
544                         break;
545                 if (plane->type < 3)
546                         sides = ((info->lightmaxs[plane->type] >= plane->dist) | ((info->lightmins[plane->type] < plane->dist) << 1));
547                 else
548                         sides = BoxOnPlaneSide(info->lightmins, info->lightmaxs, plane);
549                 if (sides == 3)
550                 {
551                         R_Q1BSP_RecursiveGetLightInfo(info, node->children[0]);
552                         node = node->children[1];
553                 }
554                 else if (sides == 0)
555                         return; // ERROR: NAN bounding box!
556                 else
557                         node = node->children[sides - 1];
558         }
559         leaf = (mleaf_t *)node;
560         if (info->pvs == NULL || CHECKPVSBIT(info->pvs, leaf->clusterindex))
561         {
562                 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
563                 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
564                 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
565                 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
566                 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
567                 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
568                 if (info->outleafpvs)
569                 {
570                         int leafindex = leaf - info->model->brush.data_leafs;
571                         if (!CHECKPVSBIT(info->outleafpvs, leafindex))
572                         {
573                                 SETPVSBIT(info->outleafpvs, leafindex);
574                                 info->outleaflist[info->outnumleafs++] = leafindex;
575                         }
576                 }
577                 if (info->outsurfacepvs)
578                 {
579                         int leafsurfaceindex;
580                         for (leafsurfaceindex = 0;leafsurfaceindex < leaf->numleafsurfaces;leafsurfaceindex++)
581                         {
582                                 int surfaceindex = leaf->firstleafsurface[leafsurfaceindex];
583                                 if (!CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
584                                 {
585                                         msurface_t *surface = info->model->data_surfaces + surfaceindex;
586                                         if (BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
587                                         {
588                                                 int triangleindex, t;
589                                                 const int *e;
590                                                 const vec_t *v[3];
591                                                 for (triangleindex = 0, t = surface->num_firstshadowmeshtriangle, e = info->model->brush.shadowmesh->element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
592                                                 {
593                                                         v[0] = info->model->brush.shadowmesh->vertex3f + e[0] * 3;
594                                                         v[1] = info->model->brush.shadowmesh->vertex3f + e[1] * 3;
595                                                         v[2] = info->model->brush.shadowmesh->vertex3f + e[2] * 3;
596                                                         if (PointInfrontOfTriangle(info->relativelightorigin, v[0], v[1], v[2]) && info->lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0])) && info->lightmins[0] < max(v[0][0], max(v[1][0], v[2][0])) && info->lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1])) && info->lightmins[1] < max(v[0][1], max(v[1][1], v[2][1])) && info->lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2])) && info->lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
597                                                         {
598                                                                 SETPVSBIT(info->outsurfacepvs, surfaceindex);
599                                                                 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
600                                                                 break;
601                                                         }
602                                                 }
603                                         }
604                                 }
605                         }
606                 }
607         }
608 }
609
610 void R_Q1BSP_GetLightInfo(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, vec3_t outmins, vec3_t outmaxs, int *outleaflist, unsigned char *outleafpvs, int *outnumleafspointer, int *outsurfacelist, unsigned char *outsurfacepvs, int *outnumsurfacespointer)
611 {
612         r_q1bsp_getlightinfo_t info;
613         VectorCopy(relativelightorigin, info.relativelightorigin);
614         info.lightradius = lightradius;
615         info.lightmins[0] = info.relativelightorigin[0] - info.lightradius;
616         info.lightmins[1] = info.relativelightorigin[1] - info.lightradius;
617         info.lightmins[2] = info.relativelightorigin[2] - info.lightradius;
618         info.lightmaxs[0] = info.relativelightorigin[0] + info.lightradius;
619         info.lightmaxs[1] = info.relativelightorigin[1] + info.lightradius;
620         info.lightmaxs[2] = info.relativelightorigin[2] + info.lightradius;
621         if (ent->model == NULL)
622         {
623                 VectorCopy(info.lightmins, outmins);
624                 VectorCopy(info.lightmaxs, outmaxs);
625                 *outnumleafspointer = 0;
626                 *outnumsurfacespointer = 0;
627                 return;
628         }
629         info.model = ent->model;
630         info.outleaflist = outleaflist;
631         info.outleafpvs = outleafpvs;
632         info.outnumleafs = 0;
633         info.outsurfacelist = outsurfacelist;
634         info.outsurfacepvs = outsurfacepvs;
635         info.outnumsurfaces = 0;
636         VectorCopy(info.relativelightorigin, info.outmins);
637         VectorCopy(info.relativelightorigin, info.outmaxs);
638         memset(outleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
639         memset(outsurfacepvs, 0, (info.model->nummodelsurfaces + 7) >> 3);
640         if (info.model->brush.GetPVS)
641                 info.pvs = info.model->brush.GetPVS(info.model, info.relativelightorigin);
642         else
643                 info.pvs = NULL;
644         R_UpdateAllTextureInfo(ent);
645         if (r_shadow_compilingrtlight)
646         {
647                 // use portal recursion for exact light volume culling, and exact surface checking
648                 Portal_Visibility(info.model, info.relativelightorigin, info.outleaflist, info.outleafpvs, &info.outnumleafs, info.outsurfacelist, info.outsurfacepvs, &info.outnumsurfaces, NULL, 0, true, info.lightmins, info.lightmaxs, info.outmins, info.outmaxs);
649         }
650         else if (r_shadow_realtime_dlight_portalculling.integer)
651         {
652                 // use portal recursion for exact light volume culling, but not the expensive exact surface checking
653                 Portal_Visibility(info.model, info.relativelightorigin, info.outleaflist, info.outleafpvs, &info.outnumleafs, info.outsurfacelist, info.outsurfacepvs, &info.outnumsurfaces, NULL, 0, r_shadow_realtime_dlight_portalculling.integer >= 2, info.lightmins, info.lightmaxs, info.outmins, info.outmaxs);
654         }
655         else
656         {
657                 // use BSP recursion as lights are often small
658                 R_Q1BSP_RecursiveGetLightInfo(&info, info.model->brush.data_nodes);
659         }
660
661         // limit combined leaf box to light boundaries
662         outmins[0] = max(info.outmins[0] - 1, info.lightmins[0]);
663         outmins[1] = max(info.outmins[1] - 1, info.lightmins[1]);
664         outmins[2] = max(info.outmins[2] - 1, info.lightmins[2]);
665         outmaxs[0] = min(info.outmaxs[0] + 1, info.lightmaxs[0]);
666         outmaxs[1] = min(info.outmaxs[1] + 1, info.lightmaxs[1]);
667         outmaxs[2] = min(info.outmaxs[2] + 1, info.lightmaxs[2]);
668
669         *outnumleafspointer = info.outnumleafs;
670         *outnumsurfacespointer = info.outnumsurfaces;
671 }
672
673 void R_Q1BSP_CompileShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativelightdirection, float lightradius, int numsurfaces, const int *surfacelist)
674 {
675         model_t *model = ent->model;
676         msurface_t *surface;
677         int surfacelistindex;
678         float projectdistance = relativelightdirection ? lightradius : lightradius + model->radius*2 + r_shadow_projectdistance.value;
679         texture_t *texture;
680         r_shadow_compilingrtlight->static_meshchain_shadow = Mod_ShadowMesh_Begin(r_main_mempool, 32768, 32768, NULL, NULL, NULL, false, false, true);
681         R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
682         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
683         {
684                 surface = model->data_surfaces + surfacelist[surfacelistindex];
685                 texture = surface->texture;
686                 if ((texture->basematerialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) != MATERIALFLAG_WALL)
687                         continue;
688                 if ((texture->textureflags & (Q3TEXTUREFLAG_TWOSIDED | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2)) || (ent->flags & RENDER_NOCULLFACE))
689                         continue;
690                 R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, relativelightdirection, r_shadow_compilingrtlight->cullmins, r_shadow_compilingrtlight->cullmaxs, surface->mins, surface->maxs);
691         }
692         R_Shadow_VolumeFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, model->brush.shadowmesh->neighbor3i, relativelightorigin, relativelightdirection, projectdistance, numshadowmark, shadowmarklist);
693         r_shadow_compilingrtlight->static_meshchain_shadow = Mod_ShadowMesh_Finish(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow, false, false);
694 }
695
696 void R_Q1BSP_DrawShadowVolume_Batch(const vec3_t relativelightorigin, const vec3_t relativelightdirection, const vec3_t lightmins, const vec3_t lightmaxs, int texturenumsurfaces, msurface_t **texturesurfacelist)
697 {
698         int texturesurfaceindex;
699         RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
700         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
701         {
702                 msurface_t *surface = texturesurfacelist[texturesurfaceindex];
703                 R_Shadow_MarkVolumeFromBox(surface->num_firsttriangle, surface->num_triangles, rsurface_vertex3f, rsurface_model->surfmesh.data_element3i, relativelightorigin, relativelightdirection, lightmins, lightmaxs, surface->mins, surface->maxs);
704         }
705 }
706
707 void R_Q1BSP_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativelightdirection, float lightradius, int modelnumsurfaces, const int *modelsurfacelist, const vec3_t lightmins, const vec3_t lightmaxs)
708 {
709         model_t *model = ent->model;
710         msurface_t *surface;
711         int modelsurfacelistindex;
712         int f = 0;
713         float projectdistance = relativelightdirection ? lightradius : lightradius + model->radius*2 + r_shadow_projectdistance.value;
714         texture_t *t = NULL;
715         const int maxsurfacelist = 1024;
716         int numsurfacelist = 0;
717         msurface_t *surfacelist[1024];
718         // check the box in modelspace, it was already checked in worldspace
719         if (!BoxesOverlap(model->normalmins, model->normalmaxs, lightmins, lightmaxs))
720                 return;
721         R_UpdateAllTextureInfo(ent);
722         if (model->brush.shadowmesh)
723         {
724                 R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
725                 for (modelsurfacelistindex = 0;modelsurfacelistindex < modelnumsurfaces;modelsurfacelistindex++)
726                 {
727                         surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
728                         t = surface->texture->currentframe;
729                         if ((t->currentmaterialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) != MATERIALFLAG_WALL)
730                                 continue;
731                         if ((t->textureflags & (Q3TEXTUREFLAG_TWOSIDED | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2)) || (ent->flags & RENDER_NOCULLFACE))
732                                 continue;
733                         R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, relativelightdirection, lightmins, lightmaxs, surface->mins, surface->maxs);
734                 }
735                 R_Shadow_VolumeFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, model->brush.shadowmesh->neighbor3i, relativelightorigin, relativelightdirection, projectdistance, numshadowmark, shadowmarklist);
736         }
737         else
738         {
739                 projectdistance = lightradius + model->radius*2;
740                 RSurf_ActiveEntity(ent, false, false);
741                 R_Shadow_PrepareShadowMark(model->surfmesh.num_triangles);
742                 // identify lit faces within the bounding box
743                 for (modelsurfacelistindex = 0;modelsurfacelistindex < modelnumsurfaces;modelsurfacelistindex++)
744                 {
745                         surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
746                         if (t != surface->texture || numsurfacelist >= maxsurfacelist)
747                         {
748                                 if (numsurfacelist)
749                                 {
750                                         R_Q1BSP_DrawShadowVolume_Batch(relativelightorigin, relativelightdirection, lightmins, lightmaxs, numsurfacelist, surfacelist);
751                                         numsurfacelist = 0;
752                                 }
753                                 t = surface->texture;
754                                 rsurface_texture = t->currentframe;
755                                 f = (rsurface_texture->currentmaterialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) == MATERIALFLAG_WALL;
756                         }
757                         if (f && surface->num_triangles)
758                                 surfacelist[numsurfacelist++] = surface;
759                 }
760                 if (numsurfacelist)
761                         R_Q1BSP_DrawShadowVolume_Batch(relativelightorigin, relativelightdirection, lightmins, lightmaxs, numsurfacelist, surfacelist);
762                 R_Shadow_VolumeFromList(model->surfmesh.num_vertices, model->surfmesh.num_triangles, rsurface_vertex3f, model->surfmesh.data_element3i, model->surfmesh.data_neighbor3i, relativelightorigin, relativelightdirection, projectdistance, numshadowmark, shadowmarklist);
763         }
764 }
765
766 #define BATCHSIZE 256
767
768 static void R_Q1BSP_DrawLight_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
769 {
770         int surfacelistindex, batchcount;
771         texture_t *t;
772         msurface_t *batchsurfaces[BATCHSIZE];
773         // note: in practice this never actually batches, oh well
774         R_Shadow_RenderMode_Begin();
775         R_Shadow_RenderMode_ActiveLight((rtlight_t *)rtlight);
776         R_Shadow_RenderMode_Lighting(false, true);
777         R_Shadow_SetupEntityLight(ent);
778         t = NULL;
779         batchcount = 0;
780         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
781         {
782                 msurface_t *surface = ent->model->data_surfaces + surfacelist[surfacelistindex];
783                 if (t != surface->texture)
784                 {
785                         if (batchcount > 0)
786                                 R_Shadow_RenderSurfacesLighting(batchcount, batchsurfaces);
787                         batchcount = 0;
788                         t = surface->texture;
789                         R_UpdateTextureInfo(ent, t);
790                         rsurface_texture = t->currentframe;
791                 }
792                 batchsurfaces[batchcount++] = surface;
793         }
794         if (batchcount > 0)
795                 R_Shadow_RenderSurfacesLighting(batchcount, batchsurfaces);
796         R_Shadow_RenderMode_End();
797 }
798
799 static void R_Q1BSP_DrawLight_TransparentBatch(int batchnumsurfaces, msurface_t **batchsurfacelist)
800 {
801         int batchsurfaceindex;
802         msurface_t *batchsurface;
803         vec3_t tempcenter, center;
804         for (batchsurfaceindex = 0;batchsurfaceindex < batchnumsurfaces;batchsurfaceindex++)
805         {
806                 batchsurface = batchsurfacelist[batchsurfaceindex];
807                 tempcenter[0] = (batchsurface->mins[0] + batchsurface->maxs[0]) * 0.5f;
808                 tempcenter[1] = (batchsurface->mins[1] + batchsurface->maxs[1]) * 0.5f;
809                 tempcenter[2] = (batchsurface->mins[2] + batchsurface->maxs[2]) * 0.5f;
810                 Matrix4x4_Transform(&rsurface_entity->matrix, tempcenter, center);
811                 R_MeshQueue_AddTransparent(rsurface_texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_view.origin : center, R_Q1BSP_DrawLight_TransparentCallback, rsurface_entity, batchsurface - rsurface_model->data_surfaces, r_shadow_rtlight);
812         }
813 }
814
815 #define RSURF_MAX_BATCHSURFACES 1024
816
817 void R_Q1BSP_DrawLight(entity_render_t *ent, int numsurfaces, const int *surfacelist)
818 {
819         model_t *model = ent->model;
820         msurface_t *surface;
821         int surfacelistindex, batchnumsurfaces;
822         msurface_t *batchsurfacelist[RSURF_MAX_BATCHSURFACES];
823         texture_t *tex;
824         qboolean skip;
825         CHECKGLERROR
826         RSurf_ActiveEntity(ent, true, true);
827         R_UpdateAllTextureInfo(ent);
828         tex = NULL;
829         rsurface_texture = NULL;
830         skip = false;
831         batchnumsurfaces = 0;
832         CHECKGLERROR
833         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
834         {
835                 if ((ent == r_refdef.worldentity && !r_viewcache.world_surfacevisible[surfacelist[surfacelistindex]]))
836                         continue;
837                 surface = model->data_surfaces + surfacelist[surfacelistindex];
838                 r_refdef.stats.lights_lighttriangles += surface->num_triangles;
839                 if (tex != surface->texture)
840                 {
841                         if (batchnumsurfaces > 0)
842                         {
843                                 if (rsurface_texture->currentmaterialflags & MATERIALFLAG_BLENDED)
844                                         R_Q1BSP_DrawLight_TransparentBatch(batchnumsurfaces, batchsurfacelist);
845                                 else
846                                         R_Shadow_RenderSurfacesLighting(batchnumsurfaces, batchsurfacelist);
847                                 batchnumsurfaces = 0;
848                         }
849                         tex = surface->texture;
850                         rsurface_texture = surface->texture->currentframe;
851                         skip = (rsurface_texture->currentmaterialflags & MATERIALFLAG_SKY) != 0;
852                         if (skip)
853                                 continue;
854                 }
855                 if (!skip && surface->num_triangles)
856                 {
857                         if (batchnumsurfaces == RSURF_MAX_BATCHSURFACES)
858                         {
859                                 if (rsurface_texture->currentmaterialflags & MATERIALFLAG_BLENDED)
860                                         R_Q1BSP_DrawLight_TransparentBatch(batchnumsurfaces, batchsurfacelist);
861                                 else
862                                         R_Shadow_RenderSurfacesLighting(batchnumsurfaces, batchsurfacelist);
863                                 batchnumsurfaces = 0;
864                         }
865                         batchsurfacelist[batchnumsurfaces++] = surface;
866                 }
867         }
868         if (batchnumsurfaces > 0)
869         {
870                 if (rsurface_texture->currentmaterialflags & MATERIALFLAG_BLENDED)
871                         R_Q1BSP_DrawLight_TransparentBatch(batchnumsurfaces, batchsurfacelist);
872                 else
873                         R_Shadow_RenderSurfacesLighting(batchnumsurfaces, batchsurfacelist);
874                 batchnumsurfaces = 0;
875         }
876 }
877
878 //Made by [515]
879 void R_ReplaceWorldTexture (void)
880 {
881         model_t         *m;
882         texture_t       *t;
883         int                     i;
884         const char      *r, *newt;
885         m = r_refdef.worldmodel;
886
887         if(Cmd_Argc() < 2)
888         {
889                 Con_Print("r_replacemaptexture <texname> <newtexname> - replaces texture\n");
890                 Con_Print("r_replacemaptexture <texname> - switch back to default texture\n");
891                 return;
892         }
893         if(!cl.islocalgame || !cl.worldmodel)
894         {
895                 Con_Print("This command works only in singleplayer\n");
896                 return;
897         }
898         r = Cmd_Argv(1);
899         newt = Cmd_Argv(2);
900         if(!newt[0])
901                 newt = r;
902         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
903         {
904                 if(t->width && !strcasecmp(t->name, r))
905                 {
906                         if(Mod_LoadSkinFrame(&t->skinframes[0], (char*)newt, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, r_fullbrights.integer))
907                         {
908                                 Con_Printf("%s replaced with %s\n", r, newt);
909                                 return;
910                         }
911                         else
912                         {
913                                 Con_Printf("%s was not found\n", newt);
914                                 Mod_LoadSkinFrame(&t->skinframes[0], (char*)r, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, r_fullbrights.integer);//back to default
915                                 return;
916                         }
917                 }
918         }
919 }
920
921 //Made by [515]
922 void R_ListWorldTextures (void)
923 {
924         model_t         *m;
925         texture_t       *t;
926         int                     i;
927         m = r_refdef.worldmodel;
928
929         Con_Print("Worldmodel textures :\n");
930         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
931                 if (t->numskinframes)
932                         Con_Printf("%s\n", t->name);
933 }
934
935 #if 0
936 static void gl_surf_start(void)
937 {
938 }
939
940 static void gl_surf_shutdown(void)
941 {
942 }
943
944 static void gl_surf_newmap(void)
945 {
946 }
947 #endif
948
949 void GL_Surf_Init(void)
950 {
951
952         Cvar_RegisterVariable(&r_ambient);
953         Cvar_RegisterVariable(&r_lockpvs);
954         Cvar_RegisterVariable(&r_lockvisibility);
955         Cvar_RegisterVariable(&r_useportalculling);
956         Cvar_RegisterVariable(&r_q3bsp_renderskydepth);
957
958         Cmd_AddCommand ("r_replacemaptexture", R_ReplaceWorldTexture, "override a map texture for testing purposes");   // By [515]
959         Cmd_AddCommand ("r_listmaptextures", R_ListWorldTextures, "list all textures used by the current map"); // By [515]
960
961         //R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
962 }
963