]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_rsurf.c
eliminated use of node bounding box when recursing collision traces and lights throug...
[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"};
29 cvar_t r_drawportals = {0, "r_drawportals", "0"};
30 cvar_t r_testvis = {0, "r_testvis", "0"};
31 cvar_t r_surfaceworldnode = {0, "r_surfaceworldnode", "0"};
32 cvar_t r_drawcollisionbrushes_polygonfactor = {0, "r_drawcollisionbrushes_polygonfactor", "-1"};
33 cvar_t r_drawcollisionbrushes_polygonoffset = {0, "r_drawcollisionbrushes_polygonoffset", "0"};
34 cvar_t r_q3bsp_renderskydepth = {0, "r_q3bsp_renderskydepth", "0"};
35
36 // flag arrays used for visibility checking on world model
37 // (all other entities have no per-surface/per-leaf visibility checks)
38 // TODO: dynamic resize according to r_refdef.worldmodel->brush.num_clusters
39 qbyte r_pvsbits[(32768+7)>>3];
40 // TODO: dynamic resize according to r_refdef.worldmodel->brush.num_leafs
41 qbyte r_worldleafvisible[32768];
42 // TODO: dynamic resize according to r_refdef.worldmodel->num_surfaces
43 qbyte r_worldsurfacevisible[262144];
44
45 /*
46 ===============
47 R_BuildLightMap
48
49 Combine and scale multiple lightmaps into the 8.8 format in blocklights
50 ===============
51 */
52 void R_BuildLightMap (const entity_render_t *ent, msurface_t *surface)
53 {
54         int smax, tmax, i, j, size, size3, maps, stride, l;
55         unsigned int *bl, scale;
56         qbyte *lightmap, *out, *stain;
57         static unsigned int intblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
58         static qbyte templight[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*4];
59
60         // update cached lighting info
61         surface->cached_dlight = 0;
62
63         smax = (surface->lightmapinfo->extents[0]>>4)+1;
64         tmax = (surface->lightmapinfo->extents[1]>>4)+1;
65         size = smax*tmax;
66         size3 = size*3;
67         lightmap = surface->lightmapinfo->samples;
68
69 // set to full bright if no light data
70         bl = intblocklights;
71         if (!ent->model->brushq1.lightdata)
72         {
73                 for (i = 0;i < size3;i++)
74                         bl[i] = 255*256;
75         }
76         else
77         {
78 // clear to no light
79                 memset(bl, 0, size*3*sizeof(unsigned int));
80
81 // add all the lightmaps
82                 if (lightmap)
83                 {
84                         bl = intblocklights;
85                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3)
86                                 for (scale = r_refdef.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size3;i++)
87                                         bl[i] += lightmap[i] * scale;
88                 }
89         }
90
91         stain = surface->lightmapinfo->stainsamples;
92         bl = intblocklights;
93         out = templight;
94         // the >> 16 shift adjusts down 8 bits to account for the stainmap
95         // scaling, and remaps the 0-65536 (2x overbright) to 0-256, it will
96         // be doubled during rendering to achieve 2x overbright
97         // (0 = 0.0, 128 = 1.0, 256 = 2.0)
98         if (ent->model->brushq1.lightmaprgba)
99         {
100                 stride = (surface->lightmapinfo->lightmaptexturestride - smax) * 4;
101                 for (i = 0;i < tmax;i++, out += stride)
102                 {
103                         for (j = 0;j < smax;j++)
104                         {
105                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
106                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
107                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
108                                 *out++ = 255;
109                         }
110                 }
111         }
112         else
113         {
114                 stride = (surface->lightmapinfo->lightmaptexturestride - smax) * 3;
115                 for (i = 0;i < tmax;i++, out += stride)
116                 {
117                         for (j = 0;j < smax;j++)
118                         {
119                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
120                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
121                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
122                         }
123                 }
124         }
125
126         R_UpdateTexture(surface->lightmaptexture, templight);
127 }
128
129 void R_StainNode (mnode_t *node, model_t *model, const vec3_t origin, float radius, const float fcolor[8])
130 {
131         float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
132         msurface_t *surface, *endsurface;
133         int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
134         qbyte *bl;
135         vec3_t impact;
136
137         maxdist = radius * radius;
138         invradius = 1.0f / radius;
139
140 loc0:
141         if (!node->plane)
142                 return;
143         ndist = PlaneDiff(origin, node->plane);
144         if (ndist > radius)
145         {
146                 node = node->children[0];
147                 goto loc0;
148         }
149         if (ndist < -radius)
150         {
151                 node = node->children[1];
152                 goto loc0;
153         }
154
155         dist2 = ndist * ndist;
156         maxdist3 = maxdist - dist2;
157
158         if (node->plane->type < 3)
159         {
160                 VectorCopy(origin, impact);
161                 impact[node->plane->type] -= ndist;
162         }
163         else
164         {
165                 impact[0] = origin[0] - node->plane->normal[0] * ndist;
166                 impact[1] = origin[1] - node->plane->normal[1] * ndist;
167                 impact[2] = origin[2] - node->plane->normal[2] * ndist;
168         }
169
170         for (surface = model->data_surfaces + node->firstsurface, endsurface = surface + node->numsurfaces;surface < endsurface;surface++)
171         {
172                 if (surface->lightmapinfo->stainsamples)
173                 {
174                         smax = (surface->lightmapinfo->extents[0] >> 4) + 1;
175                         tmax = (surface->lightmapinfo->extents[1] >> 4) + 1;
176
177                         impacts = DotProduct (impact, surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3] - surface->lightmapinfo->texturemins[0];
178                         impactt = DotProduct (impact, surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3] - surface->lightmapinfo->texturemins[1];
179
180                         s = bound(0, impacts, smax * 16) - impacts;
181                         t = bound(0, impactt, tmax * 16) - impactt;
182                         i = s * s + t * t + dist2;
183                         if (i > maxdist)
184                                 continue;
185
186                         // reduce calculations
187                         for (s = 0, i = impacts; s < smax; s++, i -= 16)
188                                 sdtable[s] = i * i + dist2;
189
190                         bl = surface->lightmapinfo->stainsamples;
191                         smax3 = smax * 3;
192                         stained = false;
193
194                         i = impactt;
195                         for (t = 0;t < tmax;t++, i -= 16)
196                         {
197                                 td = i * i;
198                                 // make sure some part of it is visible on this line
199                                 if (td < maxdist3)
200                                 {
201                                         maxdist2 = maxdist - td;
202                                         for (s = 0;s < smax;s++)
203                                         {
204                                                 if (sdtable[s] < maxdist2)
205                                                 {
206                                                         ratio = lhrandom(0.0f, 1.0f);
207                                                         a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
208                                                         if (a >= (1.0f / 64.0f))
209                                                         {
210                                                                 if (a > 1)
211                                                                         a = 1;
212                                                                 bl[0] = (qbyte) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
213                                                                 bl[1] = (qbyte) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
214                                                                 bl[2] = (qbyte) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
215                                                                 stained = true;
216                                                         }
217                                                 }
218                                                 bl += 3;
219                                         }
220                                 }
221                                 else // skip line
222                                         bl += smax3;
223                         }
224                         // force lightmap upload
225                         if (stained)
226                                 surface->cached_dlight = true;
227                 }
228         }
229
230         if (node->children[0]->plane)
231         {
232                 if (node->children[1]->plane)
233                 {
234                         R_StainNode(node->children[0], model, origin, radius, fcolor);
235                         node = node->children[1];
236                         goto loc0;
237                 }
238                 else
239                 {
240                         node = node->children[0];
241                         goto loc0;
242                 }
243         }
244         else if (node->children[1]->plane)
245         {
246                 node = node->children[1];
247                 goto loc0;
248         }
249 }
250
251 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)
252 {
253         int n;
254         float fcolor[8];
255         entity_render_t *ent;
256         model_t *model;
257         vec3_t org;
258         if (r_refdef.worldmodel == NULL || !r_refdef.worldmodel->brush.data_nodes || !r_refdef.worldmodel->brushq1.lightdata)
259                 return;
260         fcolor[0] = cr1;
261         fcolor[1] = cg1;
262         fcolor[2] = cb1;
263         fcolor[3] = ca1 * (1.0f / 64.0f);
264         fcolor[4] = cr2 - cr1;
265         fcolor[5] = cg2 - cg1;
266         fcolor[6] = cb2 - cb1;
267         fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
268
269         R_StainNode(r_refdef.worldmodel->brush.data_nodes + r_refdef.worldmodel->brushq1.hulls[0].firstclipnode, r_refdef.worldmodel, origin, radius, fcolor);
270
271         // look for embedded bmodels
272         for (n = 0;n < cl_num_brushmodel_entities;n++)
273         {
274                 ent = &cl_entities[cl_brushmodel_entities[n]].render;
275                 model = ent->model;
276                 if (model && model->name[0] == '*')
277                 {
278                         if (model->brush.data_nodes)
279                         {
280                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
281                                 R_StainNode(model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
282                         }
283                 }
284         }
285 }
286
287
288 /*
289 =============================================================
290
291         BRUSH MODELS
292
293 =============================================================
294 */
295
296 static void R_DrawPortal_Callback(const void *calldata1, int calldata2)
297 {
298         int i;
299         float *v;
300         rmeshstate_t m;
301         const mportal_t *portal = (mportal_t *)calldata1;
302         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
303         GL_DepthMask(false);
304         GL_DepthTest(true);
305         R_Mesh_Matrix(&r_identitymatrix);
306
307         memset(&m, 0, sizeof(m));
308         m.pointer_vertex = varray_vertex3f;
309         R_Mesh_State(&m);
310
311         i = calldata2;
312         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f),
313                          ((i & 0x0038) >> 3) * (1.0f / 7.0f),
314                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f),
315                          0.125f);
316         if (PlaneDiff(r_vieworigin, (&portal->plane)) < 0)
317         {
318                 for (i = portal->numpoints - 1, v = varray_vertex3f;i >= 0;i--, v += 3)
319                         VectorCopy(portal->points[i].position, v);
320         }
321         else
322                 for (i = 0, v = varray_vertex3f;i < portal->numpoints;i++, v += 3)
323                         VectorCopy(portal->points[i].position, v);
324         GL_LockArrays(0, portal->numpoints);
325         R_Mesh_Draw(0, portal->numpoints, portal->numpoints - 2, polygonelements);
326         GL_LockArrays(0, 0);
327 }
328
329 // LordHavoc: this is just a nice debugging tool, very slow
330 static void R_DrawPortals(void)
331 {
332         int i, leafnum;//, portalnum;
333         mportal_t *portal;
334         float center[3], f;
335         model_t *model = r_refdef.worldmodel;
336         if (model == NULL)
337                 return;
338         for (leafnum = 0;leafnum < r_refdef.worldmodel->brush.num_leafs;leafnum++)
339         {
340                 if (r_worldleafvisible[leafnum])
341                 {
342                         //for (portalnum = 0, portal = model->brush.data_portals;portalnum < model->brush.num_portals;portalnum++, portal++)
343                         for (portal = r_refdef.worldmodel->brush.data_leafs[leafnum].portals;portal;portal = portal->next)
344                         {
345                                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
346                                 if (!R_CullBox(portal->mins, portal->maxs))
347                                 {
348                                         VectorClear(center);
349                                         for (i = 0;i < portal->numpoints;i++)
350                                                 VectorAdd(center, portal->points[i].position, center);
351                                         f = ixtable[portal->numpoints];
352                                         VectorScale(center, f, center);
353                                         //R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, portal, portalnum);
354                                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, portal, leafnum);
355                                 }
356                         }
357                 }
358         }
359 }
360
361 static void R_DrawCollisionBrush(colbrushf_t *brush)
362 {
363         int i;
364         rmeshstate_t m;
365         memset(&m, 0, sizeof(m));
366         m.pointer_vertex = brush->points->v;
367         R_Mesh_State(&m);
368         i = (int)(((size_t)brush) / sizeof(colbrushf_t));
369         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
370         GL_LockArrays(0, brush->numpoints);
371         R_Mesh_Draw(0, brush->numpoints, brush->numtriangles, brush->elements);
372         GL_LockArrays(0, 0);
373 }
374
375 static void R_DrawCollisionSurface(entity_render_t *ent, msurface_t *surface)
376 {
377         int i;
378         rmeshstate_t m;
379         if (!surface->num_collisiontriangles)
380                 return;
381         memset(&m, 0, sizeof(m));
382         m.pointer_vertex = surface->data_collisionvertex3f;
383         R_Mesh_State(&m);
384         i = (int)(((size_t)surface) / sizeof(msurface_t));
385         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
386         GL_LockArrays(0, surface->num_collisionvertices);
387         R_Mesh_Draw(0, surface->num_collisionvertices, surface->num_collisiontriangles, surface->data_collisionelement3i);
388         GL_LockArrays(0, 0);
389 }
390
391 void R_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_vieworigin) : NULL;
403         // if possible fetch the visible cluster bits
404         if (model->brush.FatPVS)
405                 model->brush.FatPVS(model, r_vieworigin, 2, r_pvsbits, sizeof(r_pvsbits));
406
407         // clear the visible surface and leaf flags arrays
408         memset(r_worldsurfacevisible, 0, model->num_surfaces);
409         memset(r_worldleafvisible, 0, model->brush.num_leafs);
410
411         // if the user prefers surfaceworldnode (testing?) or the viewleaf could
412         // not be found, or the viewleaf is not part of the visible world
413         // (floating around in the void), use the pvs method
414         if (r_surfaceworldnode.integer || !viewleaf || viewleaf->clusterindex < 0)
415         {
416                 // pvs method:
417                 // similar to quake's RecursiveWorldNode but without cache misses
418                 for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
419                 {
420                         // if leaf is in current pvs and on the screen, mark its surfaces
421                         if (CHECKPVSBIT(r_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
422                         {
423                                 renderstats.world_leafs++;
424                                 r_worldleafvisible[j] = true;
425                                 if (leaf->numleafsurfaces)
426                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
427                                                 r_worldsurfacevisible[*mark] = true;
428                         }
429                 }
430         }
431         else
432         {
433                 int leafstackpos;
434                 mportal_t *p;
435                 mleaf_t *leafstack[8192];
436                 // portal method:
437                 // follows portals leading outward from viewleaf, does not venture
438                 // offscreen or into leafs that are not visible, faster than Quake's
439                 // RecursiveWorldNode and vastly better in unvised maps, often culls a
440                 // lot of surface that pvs alone would miss
441                 leafstack[0] = viewleaf;
442                 leafstackpos = 1;
443                 while (leafstackpos)
444                 {
445                         renderstats.world_leafs++;
446                         leaf = leafstack[--leafstackpos];
447                         r_worldleafvisible[leaf - model->brush.data_leafs] = true;
448                         // mark any surfaces bounding this leaf
449                         if (leaf->numleafsurfaces)
450                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
451                                         r_worldsurfacevisible[*mark] = true;
452                         // follow portals into other leafs
453                         // the checks are:
454                         // if viewer is behind portal (portal faces outward into the scene)
455                         // and the portal polygon's bounding box is on the screen
456                         // and the leaf has not been visited yet
457                         // and the leaf is visible in the pvs
458                         // (the first two checks won't cause as many cache misses as the leaf checks)
459                         for (p = leaf->portals;p;p = p->next)
460                         {
461                                 renderstats.world_portals++;
462                                 if (DotProduct(r_vieworigin, p->plane.normal) < (p->plane.dist + 1) && !R_CullBox(p->mins, p->maxs) && !r_worldleafvisible[p->past - model->brush.data_leafs] && CHECKPVSBIT(r_pvsbits, p->past->clusterindex))
463                                         leafstack[leafstackpos++] = p->past;
464                         }
465                 }
466         }
467
468         if (r_drawportals.integer)
469                 R_DrawPortals();
470 }
471
472 void R_Q1BSP_DrawSky(entity_render_t *ent)
473 {
474         if (ent->model == NULL)
475                 return;
476         if (r_drawcollisionbrushes.integer < 2)
477                 R_DrawSurfaces(ent, true);
478 }
479
480 void R_Q1BSP_Draw(entity_render_t *ent)
481 {
482         model_t *model = ent->model;
483         if (model == NULL)
484                 return;
485         if (r_drawcollisionbrushes.integer < 2)
486                 R_DrawSurfaces(ent, false);
487         if (r_drawcollisionbrushes.integer >= 1 && model->brush.num_brushes)
488         {
489                 int i;
490                 msurface_t *surface;
491                 q3mbrush_t *brush;
492                 R_Mesh_Matrix(&ent->matrix);
493                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
494                 GL_DepthMask(false);
495                 GL_DepthTest(true);
496                 qglPolygonOffset(r_drawcollisionbrushes_polygonfactor.value, r_drawcollisionbrushes_polygonoffset.value);
497                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
498                         if (brush->colbrushf && brush->colbrushf->numtriangles)
499                                 R_DrawCollisionBrush(brush->colbrushf);
500                 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
501                         if (surface->num_collisiontriangles)
502                                 R_DrawCollisionSurface(ent, surface);
503                 qglPolygonOffset(0, 0);
504         }
505 }
506
507 typedef struct r_q1bsp_getlightinfo_s
508 {
509         model_t *model;
510         vec3_t relativelightorigin;
511         float lightradius;
512         int *outleaflist;
513         qbyte *outleafpvs;
514         int outnumleafs;
515         int *outsurfacelist;
516         qbyte *outsurfacepvs;
517         int outnumsurfaces;
518         vec3_t outmins;
519         vec3_t outmaxs;
520         vec3_t lightmins;
521         vec3_t lightmaxs;
522         const qbyte *pvs;
523 }
524 r_q1bsp_getlightinfo_t;
525
526 void R_Q1BSP_RecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, mnode_t *node)
527 {
528         int sides;
529         mleaf_t *leaf;
530         for (;;)
531         {
532                 mplane_t *plane = node->plane;
533                 //if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
534                 //      return;
535                 if (!plane)
536                         break;
537                 if (plane->type < 3)
538                         sides = ((info->lightmaxs[plane->type] >= plane->dist) | ((info->lightmins[plane->type] < plane->dist) << 1));
539                 else
540                         sides = BoxOnPlaneSide(info->lightmins, info->lightmaxs, plane);
541                 if (sides == 3)
542                 {
543                         R_Q1BSP_RecursiveGetLightInfo(info, node->children[0]);
544                         node = node->children[1];
545                 }
546                 else
547                         node = node->children[sides - 1];
548         }
549         leaf = (mleaf_t *)node;
550         if (info->pvs == NULL || CHECKPVSBIT(info->pvs, leaf->clusterindex))
551         {
552                 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
553                 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
554                 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
555                 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
556                 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
557                 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
558                 if (info->outleafpvs)
559                 {
560                         int leafindex = leaf - info->model->brush.data_leafs;
561                         if (!CHECKPVSBIT(info->outleafpvs, leafindex))
562                         {
563                                 SETPVSBIT(info->outleafpvs, leafindex);
564                                 info->outleaflist[info->outnumleafs++] = leafindex;
565                         }
566                 }
567                 if (info->outsurfacepvs)
568                 {
569                         int leafsurfaceindex;
570                         for (leafsurfaceindex = 0;leafsurfaceindex < leaf->numleafsurfaces;leafsurfaceindex++)
571                         {
572                                 int surfaceindex = leaf->firstleafsurface[leafsurfaceindex];
573                                 if (!CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
574                                 {
575                                         msurface_t *surface = info->model->data_surfaces + surfaceindex;
576                                         if (BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
577                                         if ((surface->texture->currentmaterialflags & (MATERIALFLAG_WALL | MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT)) == MATERIALFLAG_WALL)
578                                         {
579                                                 int triangleindex, t;
580                                                 const int *e;
581                                                 const vec_t *v[3];
582                                                 for (triangleindex = 0, t = surface->num_firstshadowmeshtriangle, e = info->model->brush.shadowmesh->element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
583                                                 {
584                                                         v[0] = info->model->brush.shadowmesh->vertex3f + e[0] * 3;
585                                                         v[1] = info->model->brush.shadowmesh->vertex3f + e[1] * 3;
586                                                         v[2] = info->model->brush.shadowmesh->vertex3f + e[2] * 3;
587                                                         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])))
588                                                         {
589                                                                 SETPVSBIT(info->outsurfacepvs, surfaceindex);
590                                                                 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
591                                                                 break;
592                                                         }
593                                                 }
594                                         }
595                                 }
596                         }
597                 }
598         }
599 }
600
601 void R_Q1BSP_GetLightInfo(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, vec3_t outmins, vec3_t outmaxs, int *outleaflist, qbyte *outleafpvs, int *outnumleafspointer, int *outsurfacelist, qbyte *outsurfacepvs, int *outnumsurfacespointer)
602 {
603         r_q1bsp_getlightinfo_t info;
604         VectorCopy(relativelightorigin, info.relativelightorigin);
605         info.lightradius = lightradius;
606         info.lightmins[0] = info.relativelightorigin[0] - info.lightradius;
607         info.lightmins[1] = info.relativelightorigin[1] - info.lightradius;
608         info.lightmins[2] = info.relativelightorigin[2] - info.lightradius;
609         info.lightmaxs[0] = info.relativelightorigin[0] + info.lightradius;
610         info.lightmaxs[1] = info.relativelightorigin[1] + info.lightradius;
611         info.lightmaxs[2] = info.relativelightorigin[2] + info.lightradius;
612         if (ent->model == NULL)
613         {
614                 VectorCopy(info.lightmins, outmins);
615                 VectorCopy(info.lightmaxs, outmaxs);
616                 *outnumleafspointer = 0;
617                 *outnumsurfacespointer = 0;
618                 return;
619         }
620         info.model = ent->model;
621         info.outleaflist = outleaflist;
622         info.outleafpvs = outleafpvs;
623         info.outnumleafs = 0;
624         info.outsurfacelist = outsurfacelist;
625         info.outsurfacepvs = outsurfacepvs;
626         info.outnumsurfaces = 0;
627         VectorCopy(info.relativelightorigin, info.outmins);
628         VectorCopy(info.relativelightorigin, info.outmaxs);
629         memset(outleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
630         memset(outsurfacepvs, 0, (info.model->nummodelsurfaces + 7) >> 3);
631         if (info.model->brush.GetPVS)
632                 info.pvs = info.model->brush.GetPVS(info.model, info.relativelightorigin);
633         else
634                 info.pvs = NULL;
635         R_UpdateAllTextureInfo(ent);
636         if (r_shadow_compilingrtlight)
637         {
638                 // use portal recursion for exact light volume culling, and exact surface checking
639                 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);
640         }
641         else if (r_shadow_realtime_dlight_portalculling.integer)
642         {
643                 // use portal recursion for exact light volume culling, but not the expensive exact surface checking
644                 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);
645         }
646         else
647         {
648                 // use BSP recursion as lights are often small
649                 R_Q1BSP_RecursiveGetLightInfo(&info, info.model->brush.data_nodes);
650         }
651
652         // limit combined leaf box to light boundaries
653         outmins[0] = max(info.outmins[0] - 1, info.lightmins[0]);
654         outmins[1] = max(info.outmins[1] - 1, info.lightmins[1]);
655         outmins[2] = max(info.outmins[2] - 1, info.lightmins[2]);
656         outmaxs[0] = min(info.outmaxs[0] + 1, info.lightmaxs[0]);
657         outmaxs[1] = min(info.outmaxs[1] + 1, info.lightmaxs[1]);
658         outmaxs[2] = min(info.outmaxs[2] + 1, info.lightmaxs[2]);
659
660         *outnumleafspointer = info.outnumleafs;
661         *outnumsurfacespointer = info.outnumsurfaces;
662 }
663
664 void R_Q1BSP_CompileShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int numsurfaces, const int *surfacelist)
665 {
666         model_t *model = ent->model;
667         msurface_t *surface;
668         int surfacelistindex;
669         float projectdistance = lightradius + model->radius*2 + r_shadow_projectdistance.value;
670         texture_t *texture;
671         r_shadow_compilingrtlight->static_meshchain_shadow = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768, 32768, NULL, NULL, NULL, false, false, true);
672         R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
673         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
674         {
675                 surface = model->data_surfaces + surfacelist[surfacelistindex];
676                 texture = surface->texture;
677                 if ((texture->basematerialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) != MATERIALFLAG_WALL)
678                         continue;
679                 if (texture->textureflags & (Q3TEXTUREFLAG_TWOSIDED | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2))
680                         continue;
681                 R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, r_shadow_compilingrtlight->cullmins, r_shadow_compilingrtlight->cullmaxs, surface->mins, surface->maxs);
682         }
683         R_Shadow_VolumeFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, model->brush.shadowmesh->neighbor3i, relativelightorigin, lightradius + model->radius + projectdistance, numshadowmark, shadowmarklist);
684         r_shadow_compilingrtlight->static_meshchain_shadow = Mod_ShadowMesh_Finish(r_shadow_mempool, r_shadow_compilingrtlight->static_meshchain_shadow, false, false);
685 }
686
687 extern float *rsurface_vertex3f;
688 extern float *rsurface_svector3f;
689 extern float *rsurface_tvector3f;
690 extern float *rsurface_normal3f;
691 extern void RSurf_SetVertexPointer(const entity_render_t *ent, const texture_t *texture, const msurface_t *surface, const vec3_t modelorg);
692
693 void R_Q1BSP_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int numsurfaces, const int *surfacelist, const vec3_t lightmins, const vec3_t lightmaxs)
694 {
695         model_t *model = ent->model;
696         msurface_t *surface;
697         int surfacelistindex;
698         float projectdistance = lightradius + model->radius*2 + r_shadow_projectdistance.value;
699         vec3_t modelorg;
700         texture_t *texture;
701         // check the box in modelspace, it was already checked in worldspace
702         if (!BoxesOverlap(ent->model->normalmins, ent->model->normalmaxs, lightmins, lightmaxs))
703                 return;
704         if (r_drawcollisionbrushes.integer >= 2)
705                 return;
706         R_UpdateAllTextureInfo(ent);
707         if (model->brush.shadowmesh)
708         {
709                 R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
710                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
711                 {
712                         surface = model->data_surfaces + surfacelist[surfacelistindex];
713                         texture = surface->texture->currentframe;
714                         if ((texture->currentmaterialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) != MATERIALFLAG_WALL)
715                                 continue;
716                         if (texture->textureflags & (Q3TEXTUREFLAG_TWOSIDED | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2))
717                                 continue;
718                         R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, lightmins, lightmaxs, surface->mins, surface->maxs);
719                 }
720                 R_Shadow_VolumeFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, model->brush.shadowmesh->neighbor3i, relativelightorigin, lightradius + model->radius + projectdistance, numshadowmark, shadowmarklist);
721         }
722         else
723         {
724                 projectdistance = lightradius + ent->model->radius*2;
725                 Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
726                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
727                 {
728                         surface = model->data_surfaces + surfacelist[surfacelistindex];
729                         // FIXME: get current skin
730                         texture = surface->texture;//R_FetchAliasSkin(ent, surface->groupmesh);
731                         if (texture->currentmaterialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT) || !surface->num_triangles)
732                                 continue;
733                         RSurf_SetVertexPointer(ent, texture, surface, modelorg);
734                         // identify lit faces within the bounding box
735                         R_Shadow_PrepareShadowMark(surface->groupmesh->num_triangles);
736                         R_Shadow_MarkVolumeFromBox(surface->num_firsttriangle, surface->num_triangles, rsurface_vertex3f, surface->groupmesh->data_element3i, relativelightorigin, lightmins, lightmaxs, surface->mins, surface->maxs);
737                         R_Shadow_VolumeFromList(surface->groupmesh->num_vertices, surface->groupmesh->num_triangles, rsurface_vertex3f, surface->groupmesh->data_element3i, surface->groupmesh->data_neighbor3i, relativelightorigin, projectdistance, numshadowmark, shadowmarklist);
738                 }
739         }
740 }
741
742 #define RSURF_MAX_BATCHSURFACES 1024
743
744 void R_Q1BSP_DrawLight(entity_render_t *ent, float *lightcolorbase, float *lightcolorpants, float *lightcolorshirt, int numsurfaces, const int *surfacelist)
745 {
746         model_t *model = ent->model;
747         msurface_t *surface;
748         texture_t *texture;
749         int surfacelistindex, batchnumsurfaces;
750         msurface_t *batchsurfacelist[RSURF_MAX_BATCHSURFACES];
751         vec3_t modelorg;
752         texture_t *tex;
753         rtexture_t *basetexture = NULL;
754         rtexture_t *glosstexture = NULL;
755         float specularscale = 0;
756         qboolean skip;
757         if (r_drawcollisionbrushes.integer >= 2)
758                 return;
759         if (VectorLength2(lightcolorbase) + VectorLength2(lightcolorpants) + VectorLength2(lightcolorshirt) < 0.0001)
760                 return;
761         R_UpdateAllTextureInfo(ent);
762         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
763         tex = NULL;
764         texture = NULL;
765         skip = false;
766         batchnumsurfaces = 0;
767         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
768         {
769                 if ((ent == r_refdef.worldentity && !r_worldsurfacevisible[surfacelist[surfacelistindex]]))
770                         continue;
771                 surface = model->data_surfaces + surfacelist[surfacelistindex];
772                 renderstats.lights_lighttriangles += surface->num_triangles;
773                 if (tex != surface->texture)
774                 {
775                         if (batchnumsurfaces > 0)
776                         {
777                                 R_Shadow_RenderSurfacesLighting(ent, texture, batchnumsurfaces, batchsurfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, basetexture, texture->skin.pants, texture->skin.shirt, texture->skin.nmap, glosstexture, specularscale, modelorg);
778                                 batchnumsurfaces = 0;
779                         }
780                         tex = surface->texture;
781                         texture = surface->texture->currentframe;
782                         // FIXME: transparent surfaces need to be lit later
783                         skip = (texture->currentmaterialflags & (MATERIALFLAG_WALL | MATERIALFLAG_TRANSPARENT)) != MATERIALFLAG_WALL;
784                         if (skip)
785                                 continue;
786                         if (texture->textureflags & Q3TEXTUREFLAG_TWOSIDED)
787                                 qglDisable(GL_CULL_FACE);
788                         else
789                                 qglEnable(GL_CULL_FACE);
790                         glosstexture = r_texture_black;
791                         specularscale = 0;
792                         if (texture->skin.gloss)
793                         {
794                                 if (r_shadow_gloss.integer >= 1 && r_shadow_glossintensity.value > 0 && r_shadow_rtlight->specularscale > 0)
795                                 {
796                                         glosstexture = texture->skin.gloss;
797                                         specularscale = r_shadow_rtlight->specularscale * r_shadow_glossintensity.value;
798                                 }
799                         }
800                         else
801                         {
802                                 if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0 && r_shadow_glossintensity.value > 0 && r_shadow_rtlight->specularscale > 0)
803                                 {
804                                         glosstexture = r_texture_white;
805                                         specularscale = r_shadow_rtlight->specularscale * r_shadow_gloss2intensity.value;
806                                 }
807                         }
808                         basetexture = (ent->colormap < 0 && texture->skin.merged) ? texture->skin.merged : texture->skin.base;
809                         if ((r_shadow_rtlight->ambientscale + r_shadow_rtlight->diffusescale) * (VectorLength2(lightcolorbase) + VectorLength2(lightcolorpants) + VectorLength2(lightcolorshirt)) + specularscale * VectorLength2(lightcolorbase) < (1.0f / 1048576.0f))
810                                 skip = true;
811                 }
812                 if (!skip && surface->num_triangles)
813                 {
814                         if (batchnumsurfaces == RSURF_MAX_BATCHSURFACES)
815                         {
816                                 R_Shadow_RenderSurfacesLighting(ent, texture, batchnumsurfaces, batchsurfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, basetexture, texture->skin.pants, texture->skin.shirt, texture->skin.nmap, glosstexture, specularscale, modelorg);
817                                 batchnumsurfaces = 0;
818                         }
819                         batchsurfacelist[batchnumsurfaces++] = surface;
820                 }
821         }
822         if (batchnumsurfaces > 0)
823         {
824                 R_Shadow_RenderSurfacesLighting(ent, texture, batchnumsurfaces, batchsurfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, basetexture, texture->skin.pants, texture->skin.shirt, texture->skin.nmap, glosstexture, specularscale, modelorg);
825                 batchnumsurfaces = 0;
826         }
827         qglEnable(GL_CULL_FACE);
828 }
829
830 #if 0
831 static void gl_surf_start(void)
832 {
833 }
834
835 static void gl_surf_shutdown(void)
836 {
837 }
838
839 static void gl_surf_newmap(void)
840 {
841 }
842 #endif
843
844 void GL_Surf_Init(void)
845 {
846
847         Cvar_RegisterVariable(&r_ambient);
848         Cvar_RegisterVariable(&r_drawportals);
849         Cvar_RegisterVariable(&r_testvis);
850         Cvar_RegisterVariable(&r_surfaceworldnode);
851         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonfactor);
852         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonoffset);
853         Cvar_RegisterVariable(&r_q3bsp_renderskydepth);
854
855         //R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
856 }
857