2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // r_surf.c: surface-related refresh code
28 cvar_t r_ambient = {0, "r_ambient", "0", "brightens map, 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", "2", "improve framerate with r_novis 1 by using portal culling - still not as good as compiled visibility data in the map, but it helps (a value of 2 forces use of this even with vis data, which improves framerates in maps without too much complexity, but hurts in extremely complex maps, which is why 2 is not the default mode)"};
32 cvar_t r_usesurfaceculling = {0, "r_usesurfaceculling", "1", "skip off-screen surfaces (1 = cull surfaces if the map is likely to benefit, 2 = always cull surfaces)"};
33 cvar_t r_vis_trace = {0, "r_vis_trace", "0", "test if each portal or leaf is visible using tracelines"};
34 cvar_t r_vis_trace_samples = {0, "r_vis_trace_samples", "1", "use this many randomly positioned tracelines each frame to refresh the visible timer"};
35 cvar_t r_vis_trace_delay = {0, "r_vis_trace_delay", "1", "keep a portal visible for this many seconds"};
36 cvar_t r_vis_trace_eyejitter = {0, "r_vis_trace_eyejitter", "8", "use a random offset of this much on the start of each traceline"};
37 cvar_t r_vis_trace_enlarge = {0, "r_vis_trace_enlarge", "0", "make portal bounds bigger for tests by (1+this)*size"};
38 cvar_t r_vis_trace_expand = {0, "r_vis_trace_expand", "0", "make portal bounds bigger for tests by this many units"};
39 cvar_t r_vis_trace_pad = {0, "r_vis_trace_pad", "8", "accept traces that hit within this many units of the portal"};
40 cvar_t r_vis_trace_surfaces = {0, "r_vis_trace_surfaces", "0", "also use tracelines to cull surfaces"};
41 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"};
47 Combine and scale multiple lightmaps into the 8.8 format in blocklights
50 void R_BuildLightMap (const entity_render_t *ent, msurface_t *surface)
52 int smax, tmax, i, size, size3, maps, l;
54 unsigned char *lightmap, *out, *stain;
55 dp_model_t *model = ent->model;
57 unsigned char *templight;
59 smax = (surface->lightmapinfo->extents[0]>>4)+1;
60 tmax = (surface->lightmapinfo->extents[1]>>4)+1;
64 r_refdef.stats[r_stat_lightmapupdatepixels] += size;
65 r_refdef.stats[r_stat_lightmapupdates]++;
67 if (cl.buildlightmapmemorysize < size*sizeof(int[3]))
69 cl.buildlightmapmemorysize = size*sizeof(int[3]);
70 if (cl.buildlightmapmemory)
71 Mem_Free(cl.buildlightmapmemory);
72 cl.buildlightmapmemory = (unsigned char *) Mem_Alloc(cls.levelmempool, cl.buildlightmapmemorysize);
75 // these both point at the same buffer, templight is only used for final
76 // processing and can replace the intblocklights data as it goes
77 intblocklights = (int *)cl.buildlightmapmemory;
78 templight = (unsigned char *)cl.buildlightmapmemory;
80 // update cached lighting info
81 model->brushq1.lightmapupdateflags[surface - model->data_surfaces] = false;
83 lightmap = surface->lightmapinfo->samples;
85 // set to full bright if no light data
87 if (!model->brushq1.lightdata)
89 for (i = 0;i < size3;i++)
95 memset(bl, 0, size3*sizeof(*bl));
97 // add all the lightmaps
99 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3)
100 for (scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size3;i++)
101 bl[i] += lightmap[i] * scale;
104 stain = surface->lightmapinfo->stainsamples;
107 // the >> 16 shift adjusts down 8 bits to account for the stainmap
108 // scaling, and remaps the 0-65536 (2x overbright) to 0-256, it will
109 // be doubled during rendering to achieve 2x overbright
110 // (0 = 0.0, 128 = 1.0, 256 = 2.0)
113 for (i = 0;i < size;i++, bl += 3, stain += 3, out += 4)
115 l = (bl[0] * stain[0]) >> 16;out[2] = min(l, 255);
116 l = (bl[1] * stain[1]) >> 16;out[1] = min(l, 255);
117 l = (bl[2] * stain[2]) >> 16;out[0] = min(l, 255);
123 for (i = 0;i < size;i++, bl += 3, out += 4)
125 l = bl[0] >> 8;out[2] = min(l, 255);
126 l = bl[1] >> 8;out[1] = min(l, 255);
127 l = bl[2] >> 8;out[0] = min(l, 255);
132 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
133 Image_MakesRGBColorsFromLinear_Lightmap(templight, templight, size);
134 R_UpdateTexture(surface->lightmaptexture, templight, surface->lightmapinfo->lightmaporigin[0], surface->lightmapinfo->lightmaporigin[1], 0, smax, tmax, 1);
136 // update the surface's deluxemap if it has one
137 if (surface->deluxemaptexture != r_texture_blanknormalmap)
140 unsigned char *normalmap = surface->lightmapinfo->nmapsamples;
141 lightmap = surface->lightmapinfo->samples;
142 // clear to no normalmap
144 memset(bl, 0, size3*sizeof(*bl));
145 // add all the normalmaps
146 if (lightmap && normalmap)
148 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3, normalmap += size3)
150 for (scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size;i++)
152 // add the normalmap with weighting proportional to the style's lightmap intensity
153 l = (int)(VectorLength(lightmap + i*3) * scale);
154 bl[i*3+0] += ((int)normalmap[i*3+0] - 128) * l;
155 bl[i*3+1] += ((int)normalmap[i*3+1] - 128) * l;
156 bl[i*3+2] += ((int)normalmap[i*3+2] - 128) * l;
162 // we simply renormalize the weighted normals to get a valid deluxemap
163 for (i = 0;i < size;i++, bl += 3, out += 4)
167 l = (int)(n[0] * 128 + 128);out[2] = bound(0, l, 255);
168 l = (int)(n[1] * 128 + 128);out[1] = bound(0, l, 255);
169 l = (int)(n[2] * 128 + 128);out[0] = bound(0, l, 255);
172 R_UpdateTexture(surface->deluxemaptexture, templight, surface->lightmapinfo->lightmaporigin[0], surface->lightmapinfo->lightmaporigin[1], 0, smax, tmax, 1);
176 static void R_StainNode (mnode_t *node, dp_model_t *model, const vec3_t origin, float radius, const float fcolor[8])
178 float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
179 msurface_t *surface, *endsurface;
180 int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
184 maxdist = radius * radius;
185 invradius = 1.0f / radius;
190 ndist = PlaneDiff(origin, node->plane);
193 node = node->children[0];
198 node = node->children[1];
202 dist2 = ndist * ndist;
203 maxdist3 = maxdist - dist2;
205 if (node->plane->type < 3)
207 VectorCopy(origin, impact);
208 impact[node->plane->type] -= ndist;
212 impact[0] = origin[0] - node->plane->normal[0] * ndist;
213 impact[1] = origin[1] - node->plane->normal[1] * ndist;
214 impact[2] = origin[2] - node->plane->normal[2] * ndist;
217 for (surface = model->data_surfaces + node->firstsurface, endsurface = surface + node->numsurfaces;surface < endsurface;surface++)
219 if (surface->lightmapinfo->stainsamples)
221 smax = (surface->lightmapinfo->extents[0] >> 4) + 1;
222 tmax = (surface->lightmapinfo->extents[1] >> 4) + 1;
224 impacts = (int)(DotProduct (impact, surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3] - surface->lightmapinfo->texturemins[0]);
225 impactt = (int)(DotProduct (impact, surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3] - surface->lightmapinfo->texturemins[1]);
227 s = bound(0, impacts, smax * 16) - impacts;
228 t = bound(0, impactt, tmax * 16) - impactt;
229 i = (int)(s * s + t * t + dist2);
230 if ((i > maxdist) || (smax > (int)(sizeof(sdtable)/sizeof(sdtable[0])))) // smax overflow fix from Andreas Dehmel
233 // reduce calculations
234 for (s = 0, i = impacts; s < smax; s++, i -= 16)
235 sdtable[s] = i * i + dist2;
237 bl = surface->lightmapinfo->stainsamples;
242 for (t = 0;t < tmax;t++, i -= 16)
245 // make sure some part of it is visible on this line
248 maxdist2 = maxdist - td;
249 for (s = 0;s < smax;s++)
251 if (sdtable[s] < maxdist2)
253 ratio = lhrandom(0.0f, 1.0f);
254 a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
255 if (a >= (1.0f / 64.0f))
259 bl[0] = (unsigned char) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
260 bl[1] = (unsigned char) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
261 bl[2] = (unsigned char) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
271 // force lightmap upload
273 model->brushq1.lightmapupdateflags[surface - model->data_surfaces] = true;
277 if (node->children[0]->plane)
279 if (node->children[1]->plane)
281 R_StainNode(node->children[0], model, origin, radius, fcolor);
282 node = node->children[1];
287 node = node->children[0];
291 else if (node->children[1]->plane)
293 node = node->children[1];
298 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)
302 entity_render_t *ent;
305 if (r_refdef.scene.worldmodel == NULL || !r_refdef.scene.worldmodel->brush.data_nodes || !r_refdef.scene.worldmodel->brushq1.lightdata)
310 fcolor[3] = ca1 * (1.0f / 64.0f);
311 fcolor[4] = cr2 - cr1;
312 fcolor[5] = cg2 - cg1;
313 fcolor[6] = cb2 - cb1;
314 fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
316 R_StainNode(r_refdef.scene.worldmodel->brush.data_nodes + r_refdef.scene.worldmodel->brushq1.hulls[0].firstclipnode, r_refdef.scene.worldmodel, origin, radius, fcolor);
318 // look for embedded bmodels
319 for (n = 0;n < cl.num_brushmodel_entities;n++)
321 ent = &cl.entities[cl.brushmodel_entities[n]].render;
323 if (model && model->name[0] == '*')
325 if (model->brush.data_nodes)
327 Matrix4x4_Transform(&ent->inversematrix, origin, org);
328 R_StainNode(model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
336 =============================================================
340 =============================================================
343 static void R_DrawPortal_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
345 // due to the hacky nature of this function's parameters, this is never
346 // called with a batch, so numsurfaces is always 1, and the surfacelist
347 // contains only a leaf number for coloring purposes
348 const mportal_t *portal = (mportal_t *)ent;
352 float vertex3f[POLYGONELEMENTS_MAXPOINTS*3];
354 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
357 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
359 GL_CullFace(GL_NONE);
360 R_EntityMatrix(&identitymatrix);
362 numpoints = min(portal->numpoints, POLYGONELEMENTS_MAXPOINTS);
364 // R_Mesh_ResetTextureState();
366 isvis = (portal->here->clusterindex >= 0 && portal->past->clusterindex >= 0 && portal->here->clusterindex != portal->past->clusterindex);
368 i = surfacelist[0] >> 1;
369 GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
370 ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
371 ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
372 isvis ? 0.125f : 0.03125f);
373 for (i = 0, v = vertex3f;i < numpoints;i++, v += 3)
374 VectorCopy(portal->points[i].position, v);
375 R_Mesh_PrepareVertices_Generic_Arrays(numpoints, vertex3f, NULL, NULL);
376 R_SetupShader_Generic_NoTexture(false, false);
377 R_Mesh_Draw(0, numpoints, 0, numpoints - 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
380 // LadyHavoc: this is just a nice debugging tool, very slow
381 void R_DrawPortals(void)
386 dp_model_t *model = r_refdef.scene.worldmodel;
389 for (leafnum = 0;leafnum < r_refdef.scene.worldmodel->brush.num_leafs;leafnum++)
391 if (r_refdef.viewcache.world_leafvisible[leafnum])
393 //for (portalnum = 0, portal = model->brush.data_portals;portalnum < model->brush.num_portals;portalnum++, portal++)
394 for (portal = r_refdef.scene.worldmodel->brush.data_leafs[leafnum].portals;portal;portal = portal->next)
396 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
397 if (!R_CullBox(portal->mins, portal->maxs))
400 for (i = 0;i < portal->numpoints;i++)
401 VectorAdd(center, portal->points[i].position, center);
402 f = ixtable[portal->numpoints];
403 VectorScale(center, f, center);
404 R_MeshQueue_AddTransparent(TRANSPARENTSORT_DISTANCE, center, R_DrawPortal_Callback, (entity_render_t *)portal, leafnum, rsurface.rtlight);
411 static void R_View_WorldVisibility_CullSurfaces(void)
414 int surfaceindexstart;
416 unsigned char *surfacevisible;
417 msurface_t *surfaces;
418 dp_model_t *model = r_refdef.scene.worldmodel;
421 if (r_trippy.integer)
423 if (r_usesurfaceculling.integer < 1)
425 surfaceindexstart = model->firstmodelsurface;
426 surfaceindexend = surfaceindexstart + model->nummodelsurfaces;
427 surfaces = model->data_surfaces;
428 surfacevisible = r_refdef.viewcache.world_surfacevisible;
429 for (surfaceindex = surfaceindexstart; surfaceindex < surfaceindexend; surfaceindex++)
431 if (surfacevisible[surfaceindex])
433 if (R_CullBox(surfaces[surfaceindex].mins, surfaces[surfaceindex].maxs)
434 || (r_vis_trace_surfaces.integer && !R_CanSeeBox(r_vis_trace_samples.integer, r_vis_trace_eyejitter.value, r_vis_trace_enlarge.value, r_vis_trace_expand.value, r_vis_trace_pad.value, r_refdef.view.origin, surfaces[surfaceindex].mins, surfaces[surfaceindex].maxs)))
435 surfacevisible[surfaceindex] = 0;
440 void R_View_WorldVisibility(qboolean forcenovis)
445 dp_model_t *model = r_refdef.scene.worldmodel;
450 if (r_refdef.view.usecustompvs)
452 // clear the visible surface and leaf flags arrays
453 memset(r_refdef.viewcache.world_surfacevisible, 0, model->num_surfaces);
454 memset(r_refdef.viewcache.world_leafvisible, 0, model->brush.num_leafs);
455 r_refdef.viewcache.world_novis = false;
457 // simply cull each marked leaf to the frustum (view pyramid)
458 for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
460 // if leaf is in current pvs and on the screen, mark its surfaces
461 if (CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
463 r_refdef.stats[r_stat_world_leafs]++;
464 r_refdef.viewcache.world_leafvisible[j] = true;
465 if (leaf->numleafsurfaces)
466 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
467 r_refdef.viewcache.world_surfacevisible[*mark] = true;
470 R_View_WorldVisibility_CullSurfaces();
474 // if possible find the leaf the view origin is in
475 viewleaf = model->brush.PointInLeaf ? model->brush.PointInLeaf(model, r_refdef.view.origin) : NULL;
476 // if possible fetch the visible cluster bits
477 if (!r_lockpvs.integer && model->brush.FatPVS)
478 model->brush.FatPVS(model, r_refdef.view.origin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
480 if (!r_lockvisibility.integer)
482 // clear the visible surface and leaf flags arrays
483 memset(r_refdef.viewcache.world_surfacevisible, 0, model->num_surfaces);
484 memset(r_refdef.viewcache.world_leafvisible, 0, model->brush.num_leafs);
486 r_refdef.viewcache.world_novis = false;
488 // if floating around in the void (no pvs data available, and no
489 // portals available), simply use all on-screen leafs.
490 if (!viewleaf || viewleaf->clusterindex < 0 || forcenovis || !r_refdef.view.usevieworiginculling)
492 // no visibility method: (used when floating around in the void)
493 // simply cull each leaf to the frustum (view pyramid)
494 // similar to quake's RecursiveWorldNode but without cache misses
495 r_refdef.viewcache.world_novis = true;
496 for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
498 if (leaf->clusterindex < 0)
500 // if leaf is in current pvs and on the screen, mark its surfaces
501 if (!R_CullBox(leaf->mins, leaf->maxs))
503 r_refdef.stats[r_stat_world_leafs]++;
504 r_refdef.viewcache.world_leafvisible[j] = true;
505 if (leaf->numleafsurfaces)
506 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
507 r_refdef.viewcache.world_surfacevisible[*mark] = true;
511 // just check if each leaf in the PVS is on screen
512 // (unless portal culling is enabled)
513 else if (!model->brush.data_portals || r_useportalculling.integer < 1 || (r_useportalculling.integer < 2 && !r_novis.integer))
516 // simply check if each leaf is in the Potentially Visible Set,
517 // and cull to frustum (view pyramid)
518 // similar to quake's RecursiveWorldNode but without cache misses
519 for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
521 if (leaf->clusterindex < 0)
523 // if leaf is in current pvs and on the screen, mark its surfaces
524 if (CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
526 r_refdef.stats[r_stat_world_leafs]++;
527 r_refdef.viewcache.world_leafvisible[j] = true;
528 if (leaf->numleafsurfaces)
529 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
530 r_refdef.viewcache.world_surfacevisible[*mark] = true;
534 // if desired use a recursive portal flow, culling each portal to
535 // frustum and checking if the leaf the portal leads to is in the pvs
540 mleaf_t *leafstack[8192];
541 vec3_t cullmins, cullmaxs;
542 float cullbias = r_nearclip.value * 2.0f; // the nearclip plane can easily end up culling portals in certain perfectly-aligned views, causing view blackouts
543 // simple-frustum portal method:
544 // follows portals leading outward from viewleaf, does not venture
545 // offscreen or into leafs that are not visible, faster than
546 // Quake's RecursiveWorldNode and vastly better in unvised maps,
547 // often culls some surfaces that pvs alone would miss
548 // (such as a room in pvs that is hidden behind a wall, but the
549 // passage leading to the room is off-screen)
550 leafstack[0] = viewleaf;
554 leaf = leafstack[--leafstackpos];
555 if (r_refdef.viewcache.world_leafvisible[leaf - model->brush.data_leafs])
557 if (leaf->clusterindex < 0)
559 r_refdef.stats[r_stat_world_leafs]++;
560 r_refdef.viewcache.world_leafvisible[leaf - model->brush.data_leafs] = true;
561 // mark any surfaces bounding this leaf
562 if (leaf->numleafsurfaces)
563 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
564 r_refdef.viewcache.world_surfacevisible[*mark] = true;
565 // follow portals into other leafs
567 // the leaf has not been visited yet
568 // and the leaf is visible in the pvs
569 // the portal polygon's bounding box is on the screen
570 for (p = leaf->portals;p;p = p->next)
572 r_refdef.stats[r_stat_world_portals]++;
573 if (r_refdef.viewcache.world_leafvisible[p->past - model->brush.data_leafs])
575 if (!CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, p->past->clusterindex))
577 cullmins[0] = p->mins[0] - cullbias;
578 cullmins[1] = p->mins[1] - cullbias;
579 cullmins[2] = p->mins[2] - cullbias;
580 cullmaxs[0] = p->maxs[0] + cullbias;
581 cullmaxs[1] = p->maxs[1] + cullbias;
582 cullmaxs[2] = p->maxs[2] + cullbias;
583 if (R_CullBox(cullmins, cullmaxs))
585 if (r_vis_trace.integer)
587 if (p->tracetime != realtime && R_CanSeeBox(r_vis_trace_samples.value, r_vis_trace_eyejitter.value, r_vis_trace_enlarge.value, r_vis_trace_expand.value, r_vis_trace_pad.value, r_refdef.view.origin, cullmins, cullmaxs))
588 p->tracetime = realtime;
589 if (realtime - p->tracetime > r_vis_trace_delay.value)
592 if (leafstackpos >= (int)(sizeof(leafstack) / sizeof(leafstack[0])))
594 leafstack[leafstackpos++] = p->past;
600 R_View_WorldVisibility_CullSurfaces();
603 void R_Q1BSP_DrawSky(entity_render_t *ent)
605 if (ent->model == NULL)
607 R_DrawModelSurfaces(ent, true, true, false, false, false, false);
610 void R_Q1BSP_DrawAddWaterPlanes(entity_render_t *ent)
612 int i, j, n, flagsmask;
613 dp_model_t *model = ent->model;
614 msurface_t *surfaces;
618 RSurf_ActiveModelEntity(ent, true, false, false);
620 surfaces = model->data_surfaces;
621 flagsmask = MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA;
623 // add visible surfaces to draw list
624 if (ent == r_refdef.scene.worldentity)
626 for (i = 0;i < model->nummodelsurfaces;i++)
628 j = model->sortedmodelsurfaces[i];
629 if (r_refdef.viewcache.world_surfacevisible[j])
630 if (surfaces[j].texture->basematerialflags & flagsmask)
631 R_Water_AddWaterPlane(surfaces + j, 0);
636 if(ent->entitynumber >= MAX_EDICTS) // && CL_VM_TransformView(ent->entitynumber - MAX_EDICTS, NULL, NULL, NULL))
637 n = ent->entitynumber;
640 for (i = 0;i < model->nummodelsurfaces;i++)
642 j = model->sortedmodelsurfaces[i];
643 if (surfaces[j].texture->basematerialflags & flagsmask)
644 R_Water_AddWaterPlane(surfaces + j, n);
647 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveModelEntity
650 void R_Q1BSP_Draw(entity_render_t *ent)
652 dp_model_t *model = ent->model;
655 R_DrawModelSurfaces(ent, false, true, false, false, false, false);
658 void R_Q1BSP_DrawDepth(entity_render_t *ent)
660 dp_model_t *model = ent->model;
661 if (model == NULL || model->surfmesh.isanimated)
663 GL_ColorMask(0,0,0,0);
666 GL_BlendFunc(GL_ONE, GL_ZERO);
668 // R_Mesh_ResetTextureState();
669 R_DrawModelSurfaces(ent, false, false, true, false, false, false);
670 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
673 void R_Q1BSP_DrawDebug(entity_render_t *ent)
675 if (ent->model == NULL)
677 R_DrawModelSurfaces(ent, false, false, false, true, false, false);
680 void R_Q1BSP_DrawPrepass(entity_render_t *ent)
682 dp_model_t *model = ent->model;
685 R_DrawModelSurfaces(ent, false, true, false, false, true, false);
688 typedef struct r_q1bsp_getlightinfo_s
691 vec3_t relativelightorigin;
694 unsigned char *outleafpvs;
696 unsigned char *visitingleafpvs;
698 unsigned char *outsurfacepvs;
699 unsigned char *tempsurfacepvs;
700 unsigned char *outshadowtrispvs;
701 unsigned char *outlighttrispvs;
707 const unsigned char *pvs;
708 qboolean svbsp_active;
709 qboolean svbsp_insertoccluder;
710 qboolean noocclusion; // avoids PVS culling
711 qboolean frontsidecasting; // casts shadows from surfaces facing the light (otherwise ones facing away)
712 int numfrustumplanes;
713 const mplane_t *frustumplanes;
715 r_q1bsp_getlightinfo_t;
717 #define GETLIGHTINFO_MAXNODESTACK 4096
719 static void R_Q1BSP_RecursiveGetLightInfo_BSP(r_q1bsp_getlightinfo_t *info, qboolean skipsurfaces)
722 mnode_t *nodestack[GETLIGHTINFO_MAXNODESTACK];
723 int nodestackpos = 0;
730 const msurface_t *surface;
731 const msurface_t *surfaces = info->model->data_surfaces;
733 int leafsurfaceindex;
735 int triangleindex, t;
736 int currentmaterialflags;
742 qboolean noocclusion = info->noocclusion;
743 qboolean frontsidecasting = info->frontsidecasting;
744 qboolean svbspactive = info->svbsp_active;
745 qboolean svbspinsertoccluder = info->svbsp_insertoccluder;
746 const int *leafsurfaceindices;
750 static float points[128][3];
751 // push the root node onto our nodestack
752 nodestack[nodestackpos++] = info->model->brush.data_nodes;
753 // we'll be done when the nodestack is empty
756 // get a node from the stack to process
757 node = nodestack[--nodestackpos];
758 // is it a node or a leaf?
764 if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
768 if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(node->mins, node->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
771 // axial planes can be processed much more quickly
775 if (info->lightmins[plane->type] > plane->dist)
776 nodestack[nodestackpos++] = node->children[0];
777 else if (info->lightmaxs[plane->type] < plane->dist)
778 nodestack[nodestackpos++] = node->children[1];
781 // recurse front side first because the svbsp building prefers it
782 if (info->relativelightorigin[plane->type] >= plane->dist)
784 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
785 nodestack[nodestackpos++] = node->children[0];
786 nodestack[nodestackpos++] = node->children[1];
790 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
791 nodestack[nodestackpos++] = node->children[1];
792 nodestack[nodestackpos++] = node->children[0];
799 sides = BoxOnPlaneSide(info->lightmins, info->lightmaxs, plane);
803 continue; // ERROR: NAN bounding box!
805 nodestack[nodestackpos++] = node->children[0];
808 nodestack[nodestackpos++] = node->children[1];
811 // recurse front side first because the svbsp building prefers it
812 if (PlaneDist(info->relativelightorigin, plane) >= 0)
814 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
815 nodestack[nodestackpos++] = node->children[0];
816 nodestack[nodestackpos++] = node->children[1];
820 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
821 nodestack[nodestackpos++] = node->children[1];
822 nodestack[nodestackpos++] = node->children[0];
831 leaf = (mleaf_t *)node;
833 if (!info->noocclusion && info->pvs != NULL && !CHECKPVSBIT(info->pvs, leaf->clusterindex))
837 if (!BoxesOverlap(info->lightmins, info->lightmaxs, leaf->mins, leaf->maxs))
841 if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(leaf->mins, leaf->maxs, info->numfrustumplanes, info->frustumplanes))
847 // we can occlusion test the leaf by checking if all of its portals
848 // are occluded (unless the light is in this leaf - but that was
849 // already handled by the caller)
850 for (portal = leaf->portals;portal;portal = portal->next)
852 for (i = 0;i < portal->numpoints;i++)
853 VectorCopy(portal->points[i].position, points[i]);
854 if (SVBSP_AddPolygon(&r_svbsp, portal->numpoints, points[0], false, NULL, NULL, 0) & 2)
857 if (leaf->portals && portal == NULL)
858 continue; // no portals of this leaf visible
861 // add this leaf to the reduced light bounds
862 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
863 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
864 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
865 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
866 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
867 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
869 // mark this leaf as being visible to the light
870 if (info->outleafpvs)
872 int leafindex = leaf - info->model->brush.data_leafs;
873 if (!CHECKPVSBIT(info->outleafpvs, leafindex))
875 SETPVSBIT(info->outleafpvs, leafindex);
876 info->outleaflist[info->outnumleafs++] = leafindex;
880 // when using BIH, we skip the surfaces here
884 // iterate the surfaces linked by this leaf and check their triangles
885 leafsurfaceindices = leaf->firstleafsurface;
886 numleafsurfaces = leaf->numleafsurfaces;
887 if (svbspinsertoccluder)
889 for (leafsurfaceindex = 0;leafsurfaceindex < numleafsurfaces;leafsurfaceindex++)
891 surfaceindex = leafsurfaceindices[leafsurfaceindex];
892 if (CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
894 SETPVSBIT(info->outsurfacepvs, surfaceindex);
895 surface = surfaces + surfaceindex;
896 if (!BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
898 currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
899 castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
902 insidebox = BoxInsideBox(surface->mins, surface->maxs, info->lightmins, info->lightmaxs);
903 for (triangleindex = 0, t = surface->num_firsttriangle, e = info->model->surfmesh.data_element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
905 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
906 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
907 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
908 VectorCopy(v[0], v2[0]);
909 VectorCopy(v[1], v2[1]);
910 VectorCopy(v[2], v2[2]);
911 if (insidebox || TriangleBBoxOverlapsBox(v2[0], v2[1], v2[2], info->lightmins, info->lightmaxs))
912 SVBSP_AddPolygon(&r_svbsp, 3, v2[0], true, NULL, NULL, 0);
918 for (leafsurfaceindex = 0;leafsurfaceindex < numleafsurfaces;leafsurfaceindex++)
920 surfaceindex = leafsurfaceindices[leafsurfaceindex];
921 if (CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
923 SETPVSBIT(info->outsurfacepvs, surfaceindex);
924 surface = surfaces + surfaceindex;
925 if (!BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
928 currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
929 castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
930 insidebox = BoxInsideBox(surface->mins, surface->maxs, info->lightmins, info->lightmaxs);
931 for (triangleindex = 0, t = surface->num_firsttriangle, e = info->model->surfmesh.data_element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
933 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
934 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
935 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
936 VectorCopy(v[0], v2[0]);
937 VectorCopy(v[1], v2[1]);
938 VectorCopy(v[2], v2[2]);
939 if (!insidebox && !TriangleBBoxOverlapsBox(v2[0], v2[1], v2[2], info->lightmins, info->lightmaxs))
941 if (svbspactive && !(SVBSP_AddPolygon(&r_svbsp, 3, v2[0], false, NULL, NULL, 0) & 2))
943 // we don't omit triangles from lighting even if they are
944 // backfacing, because when using shadowmapping they are often
945 // not fully occluded on the horizon of an edge
946 SETPVSBIT(info->outlighttrispvs, t);
950 if (noocclusion || (currentmaterialflags & MATERIALFLAG_NOCULLFACE))
952 // if the material is double sided we
953 // can't cull by direction
954 SETPVSBIT(info->outshadowtrispvs, t);
956 else if (frontsidecasting)
958 // front side casting occludes backfaces,
959 // so they are completely useless as both
960 // casters and lit polygons
961 if (PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
962 SETPVSBIT(info->outshadowtrispvs, t);
966 // back side casting does not occlude
967 // anything so we can't cull lit polygons
968 if (!PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
969 SETPVSBIT(info->outshadowtrispvs, t);
974 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
981 static void R_Q1BSP_RecursiveGetLightInfo_BIH(r_q1bsp_getlightinfo_t *info, const bih_t *bih)
990 int currentmaterialflags;
992 qboolean noocclusion = info->noocclusion;
993 qboolean frontsidecasting = info->frontsidecasting;
998 int nodestack[GETLIGHTINFO_MAXNODESTACK];
999 int nodestackpos = 0;
1000 // note: because the BSP leafs are not in the BIH tree, the _BSP function
1001 // must be called to mark leafs visible for entity culling...
1002 // we start at the root node
1003 nodestack[nodestackpos++] = bih->rootnode;
1004 // we'll be done when the stack is empty
1005 while (nodestackpos)
1007 // pop one off the stack to process
1008 nodenum = nodestack[--nodestackpos];
1010 node = bih->nodes + nodenum;
1011 if (node->type == BIH_UNORDERED)
1013 for (nodeleafindex = 0;nodeleafindex < BIH_MAXUNORDEREDCHILDREN && node->children[nodeleafindex] >= 0;nodeleafindex++)
1015 leaf = bih->leafs + node->children[nodeleafindex];
1016 if (leaf->type != BIH_RENDERTRIANGLE)
1019 if (!BoxesOverlap(info->lightmins, info->lightmaxs, leaf->mins, leaf->maxs))
1023 if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(leaf->mins, leaf->maxs, info->numfrustumplanes, info->frustumplanes))
1026 surfaceindex = leaf->surfaceindex;
1027 surface = info->model->data_surfaces + surfaceindex;
1028 currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
1029 castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
1030 t = leaf->itemindex;
1031 e = info->model->surfmesh.data_element3i + t * 3;
1032 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
1033 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
1034 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
1035 VectorCopy(v[0], v2[0]);
1036 VectorCopy(v[1], v2[1]);
1037 VectorCopy(v[2], v2[2]);
1038 if (info->svbsp_insertoccluder)
1041 SVBSP_AddPolygon(&r_svbsp, 3, v2[0], true, NULL, NULL, 0);
1044 if (info->svbsp_active && !(SVBSP_AddPolygon(&r_svbsp, 3, v2[0], false, NULL, NULL, 0) & 2))
1046 // we don't occlude triangles from lighting even
1047 // if they are backfacing, because when using
1048 // shadowmapping they are often not fully occluded
1049 // on the horizon of an edge
1050 SETPVSBIT(info->outlighttrispvs, t);
1053 if (noocclusion || (currentmaterialflags & MATERIALFLAG_NOCULLFACE))
1055 // if the material is double sided we
1056 // can't cull by direction
1057 SETPVSBIT(info->outshadowtrispvs, t);
1059 else if (frontsidecasting)
1061 // front side casting occludes backfaces,
1062 // so they are completely useless as both
1063 // casters and lit polygons
1064 if (PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
1065 SETPVSBIT(info->outshadowtrispvs, t);
1069 // back side casting does not occlude
1070 // anything so we can't cull lit polygons
1071 if (!PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
1072 SETPVSBIT(info->outshadowtrispvs, t);
1075 if (!CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
1077 SETPVSBIT(info->outsurfacepvs, surfaceindex);
1078 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
1084 axis = node->type - BIH_SPLITX;
1086 if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
1090 if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(node->mins, node->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
1093 if (info->lightmins[axis] <= node->backmax)
1095 if (info->lightmaxs[axis] >= node->frontmin && nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
1096 nodestack[nodestackpos++] = node->front;
1097 nodestack[nodestackpos++] = node->back;
1100 else if (info->lightmaxs[axis] >= node->frontmin)
1102 nodestack[nodestackpos++] = node->front;
1106 continue; // light falls between children, nothing here
1111 static void R_Q1BSP_CallRecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, qboolean use_svbsp)
1113 extern cvar_t r_shadow_usebihculling;
1117 VectorCopy(info->relativelightorigin, origin);
1118 r_svbsp.maxnodes = max(r_svbsp.maxnodes, 1<<12);
1119 r_svbsp.nodes = (svbsp_node_t*) R_FrameData_Alloc(r_svbsp.maxnodes * sizeof(svbsp_node_t));
1120 info->svbsp_active = true;
1121 info->svbsp_insertoccluder = true;
1124 SVBSP_Init(&r_svbsp, origin, r_svbsp.maxnodes, r_svbsp.nodes);
1125 R_Q1BSP_RecursiveGetLightInfo_BSP(info, false);
1126 // if that failed, retry with more nodes
1127 if (r_svbsp.ranoutofnodes)
1129 // an upper limit is imposed
1130 if (r_svbsp.maxnodes >= 2<<22)
1132 r_svbsp.maxnodes *= 2;
1133 r_svbsp.nodes = (svbsp_node_t*) R_FrameData_Alloc(r_svbsp.maxnodes * sizeof(svbsp_node_t));
1134 //Mem_Free(r_svbsp.nodes);
1135 //r_svbsp.nodes = (svbsp_node_t*) Mem_Alloc(tempmempool, r_svbsp.maxnodes * sizeof(svbsp_node_t));
1140 // now clear the visibility arrays because we need to redo it
1141 info->outnumleafs = 0;
1142 info->outnumsurfaces = 0;
1143 memset(info->outleafpvs, 0, (info->model->brush.num_leafs + 7) >> 3);
1144 memset(info->outsurfacepvs, 0, (info->model->nummodelsurfaces + 7) >> 3);
1145 memset(info->outshadowtrispvs, 0, (info->model->surfmesh.num_triangles + 7) >> 3);
1146 memset(info->outlighttrispvs, 0, (info->model->surfmesh.num_triangles + 7) >> 3);
1149 info->svbsp_active = false;
1151 // we HAVE to mark the leaf the light is in as lit, because portals are
1152 // irrelevant to a leaf that the light source is inside of
1153 // (and they are all facing away, too)
1155 mnode_t *node = info->model->brush.data_nodes;
1158 node = node->children[(node->plane->type < 3 ? info->relativelightorigin[node->plane->type] : DotProduct(info->relativelightorigin,node->plane->normal)) < node->plane->dist];
1159 leaf = (mleaf_t *)node;
1160 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
1161 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
1162 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
1163 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
1164 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
1165 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
1166 if (info->outleafpvs)
1168 int leafindex = leaf - info->model->brush.data_leafs;
1169 if (!CHECKPVSBIT(info->outleafpvs, leafindex))
1171 SETPVSBIT(info->outleafpvs, leafindex);
1172 info->outleaflist[info->outnumleafs++] = leafindex;
1177 info->svbsp_insertoccluder = false;
1178 // use BIH culling on single leaf maps (generally this only happens if running a model as a map), otherwise use BSP culling to make use of vis data
1179 if (r_shadow_usebihculling.integer > 0 && (r_shadow_usebihculling.integer == 2 || info->model->brush.num_leafs == 1) && info->model->render_bih.leafs != NULL)
1181 R_Q1BSP_RecursiveGetLightInfo_BSP(info, true);
1182 R_Q1BSP_RecursiveGetLightInfo_BIH(info, &info->model->render_bih);
1185 R_Q1BSP_RecursiveGetLightInfo_BSP(info, false);
1186 // we're using temporary framedata memory, so this pointer will be invalid soon, clear it
1187 r_svbsp.nodes = NULL;
1188 if (developer_extra.integer && use_svbsp)
1190 Con_DPrintf("GetLightInfo: svbsp built with %i nodes, polygon stats:\n", r_svbsp.numnodes);
1191 Con_DPrintf("occluders: %i accepted, %i rejected, %i fragments accepted, %i fragments rejected.\n", r_svbsp.stat_occluders_accepted, r_svbsp.stat_occluders_rejected, r_svbsp.stat_occluders_fragments_accepted, r_svbsp.stat_occluders_fragments_rejected);
1192 Con_DPrintf("queries : %i accepted, %i rejected, %i fragments accepted, %i fragments rejected.\n", r_svbsp.stat_queries_accepted, r_svbsp.stat_queries_rejected, r_svbsp.stat_queries_fragments_accepted, r_svbsp.stat_queries_fragments_rejected);
1196 static msurface_t *r_q1bsp_getlightinfo_surfaces;
1198 static int R_Q1BSP_GetLightInfo_comparefunc(const void *ap, const void *bp)
1202 const msurface_t *as = r_q1bsp_getlightinfo_surfaces + a;
1203 const msurface_t *bs = r_q1bsp_getlightinfo_surfaces + b;
1204 if (as->texture < bs->texture)
1206 if (as->texture > bs->texture)
1211 extern cvar_t r_shadow_sortsurfaces;
1213 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, unsigned char *outshadowtrispvs, unsigned char *outlighttrispvs, unsigned char *visitingleafpvs, int numfrustumplanes, const mplane_t *frustumplanes, qboolean noocclusion)
1215 r_q1bsp_getlightinfo_t info;
1216 info.frontsidecasting = r_shadow_frontsidecasting.integer != 0;
1217 info.noocclusion = noocclusion || !info.frontsidecasting;
1218 VectorCopy(relativelightorigin, info.relativelightorigin);
1219 info.lightradius = lightradius;
1220 info.lightmins[0] = info.relativelightorigin[0] - info.lightradius;
1221 info.lightmins[1] = info.relativelightorigin[1] - info.lightradius;
1222 info.lightmins[2] = info.relativelightorigin[2] - info.lightradius;
1223 info.lightmaxs[0] = info.relativelightorigin[0] + info.lightradius;
1224 info.lightmaxs[1] = info.relativelightorigin[1] + info.lightradius;
1225 info.lightmaxs[2] = info.relativelightorigin[2] + info.lightradius;
1226 if (ent->model == NULL)
1228 VectorCopy(info.lightmins, outmins);
1229 VectorCopy(info.lightmaxs, outmaxs);
1230 *outnumleafspointer = 0;
1231 *outnumsurfacespointer = 0;
1234 info.model = ent->model;
1235 info.outleaflist = outleaflist;
1236 info.outleafpvs = outleafpvs;
1237 info.outnumleafs = 0;
1238 info.visitingleafpvs = visitingleafpvs;
1239 info.outsurfacelist = outsurfacelist;
1240 info.outsurfacepvs = outsurfacepvs;
1241 info.outshadowtrispvs = outshadowtrispvs;
1242 info.outlighttrispvs = outlighttrispvs;
1243 info.outnumsurfaces = 0;
1244 info.numfrustumplanes = numfrustumplanes;
1245 info.frustumplanes = frustumplanes;
1246 VectorCopy(info.relativelightorigin, info.outmins);
1247 VectorCopy(info.relativelightorigin, info.outmaxs);
1248 memset(visitingleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
1249 memset(outleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
1250 memset(outsurfacepvs, 0, (info.model->nummodelsurfaces + 7) >> 3);
1251 memset(outshadowtrispvs, 0, (info.model->surfmesh.num_triangles + 7) >> 3);
1252 memset(outlighttrispvs, 0, (info.model->surfmesh.num_triangles + 7) >> 3);
1253 if (info.model->brush.GetPVS && !info.noocclusion)
1254 info.pvs = info.model->brush.GetPVS(info.model, info.relativelightorigin);
1257 RSurf_ActiveModelEntity(r_refdef.scene.worldentity, false, false, false);
1259 if (!info.noocclusion && r_shadow_compilingrtlight && r_shadow_realtime_world_compileportalculling.integer && info.model->brush.data_portals)
1261 // use portal recursion for exact light volume culling, and exact surface checking
1262 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, info.outshadowtrispvs, info.outlighttrispvs, info.visitingleafpvs);
1264 else if (!info.noocclusion && r_shadow_realtime_dlight_portalculling.integer && info.model->brush.data_portals)
1266 // use portal recursion for exact light volume culling, but not the expensive exact surface checking
1267 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, info.outshadowtrispvs, info.outlighttrispvs, info.visitingleafpvs);
1271 // recurse the bsp tree, checking leafs and surfaces for visibility
1272 // optionally using svbsp for exact culling of compiled lights
1273 // (or if the user enables dlight svbsp culling, which is mostly for
1274 // debugging not actual use)
1275 R_Q1BSP_CallRecursiveGetLightInfo(&info, !info.noocclusion && (r_shadow_compilingrtlight ? r_shadow_realtime_world_compilesvbsp.integer : r_shadow_realtime_dlight_svbspculling.integer) != 0);
1278 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveModelEntity
1280 // limit combined leaf box to light boundaries
1281 outmins[0] = max(info.outmins[0] - 1, info.lightmins[0]);
1282 outmins[1] = max(info.outmins[1] - 1, info.lightmins[1]);
1283 outmins[2] = max(info.outmins[2] - 1, info.lightmins[2]);
1284 outmaxs[0] = min(info.outmaxs[0] + 1, info.lightmaxs[0]);
1285 outmaxs[1] = min(info.outmaxs[1] + 1, info.lightmaxs[1]);
1286 outmaxs[2] = min(info.outmaxs[2] + 1, info.lightmaxs[2]);
1288 *outnumleafspointer = info.outnumleafs;
1289 *outnumsurfacespointer = info.outnumsurfaces;
1291 // now sort surfaces by texture for faster rendering
1292 r_q1bsp_getlightinfo_surfaces = info.model->data_surfaces;
1293 if (r_shadow_sortsurfaces.integer)
1294 qsort(info.outsurfacelist, info.outnumsurfaces, sizeof(*info.outsurfacelist), R_Q1BSP_GetLightInfo_comparefunc);
1297 void R_Q1BSP_CompileShadowMap(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativelightdirection, float lightradius, int numsurfaces, const int *surfacelist)
1299 dp_model_t *model = ent->model;
1300 msurface_t *surface;
1301 int surfacelistindex;
1302 int sidetotals[6] = { 0, 0, 0, 0, 0, 0 }, sidemasks = 0;
1304 // FIXME: the sidetotals code incorrectly assumes that static_meshchain is
1305 // a single mesh - to prevent that from crashing (sideoffsets, sidetotals
1306 // exceeding the number of triangles in a single mesh) we have to make sure
1307 // that we make only a single mesh - so over-estimate the size of the mesh
1308 // to match the model.
1309 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap = Mod_ShadowMesh_Begin(r_main_mempool, model->surfmesh.num_vertices, model->surfmesh.num_triangles);
1310 R_Shadow_PrepareShadowSides(model->surfmesh.num_triangles);
1311 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1313 surface = model->data_surfaces + surfacelist[surfacelistindex];
1314 sidemasks |= R_Shadow_ChooseSidesFromBox(surface->num_firsttriangle, surface->num_triangles, model->surfmesh.data_vertex3f, model->surfmesh.data_element3i, &r_shadow_compilingrtlight->matrix_worldtolight, relativelightorigin, relativelightdirection, r_shadow_compilingrtlight->cullmins, r_shadow_compilingrtlight->cullmaxs, surface->mins, surface->maxs, surface->texture->basematerialflags & MATERIALFLAG_NOSHADOW ? NULL : sidetotals);
1316 R_Shadow_ShadowMapFromList(model->surfmesh.num_vertices, model->surfmesh.num_triangles, model->surfmesh.data_vertex3f, model->surfmesh.data_element3i, numshadowsides, sidetotals, shadowsides, shadowsideslist);
1317 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap = Mod_ShadowMesh_Finish(r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, true);
1318 r_shadow_compilingrtlight->static_shadowmap_receivers &= sidemasks;
1321 r_shadow_compilingrtlight->static_shadowmap_casters &= ~(1 << i);
1324 #define RSURF_MAX_BATCHSURFACES 8192
1326 static const msurface_t *batchsurfacelist[RSURF_MAX_BATCHSURFACES];
1328 void R_Q1BSP_DrawShadowMap(int side, entity_render_t *ent, const vec3_t relativelightorigin, const vec3_t relativelightdirection, float lightradius, int modelnumsurfaces, const int *modelsurfacelist, const unsigned char *surfacesides, const vec3_t lightmins, const vec3_t lightmaxs)
1330 dp_model_t *model = ent->model;
1331 const msurface_t *surface;
1332 int modelsurfacelistindex, batchnumsurfaces;
1333 // check the box in modelspace, it was already checked in worldspace
1334 if (!BoxesOverlap(model->normalmins, model->normalmaxs, lightmins, lightmaxs))
1336 R_FrameData_SetMark();
1337 // identify lit faces within the bounding box
1338 for (modelsurfacelistindex = 0;modelsurfacelistindex < modelnumsurfaces;modelsurfacelistindex++)
1340 surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1341 if (surfacesides && !(surfacesides[modelsurfacelistindex] && (1 << side)))
1343 rsurface.texture = R_GetCurrentTexture(surface->texture);
1344 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_NOSHADOW)
1346 if (!BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
1348 r_refdef.stats[r_stat_lights_dynamicshadowtriangles] += surface->num_triangles;
1349 r_refdef.stats[r_stat_lights_shadowtriangles] += surface->num_triangles;
1350 batchsurfacelist[0] = surface;
1351 batchnumsurfaces = 1;
1352 while(++modelsurfacelistindex < modelnumsurfaces && batchnumsurfaces < RSURF_MAX_BATCHSURFACES)
1354 surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1355 if (surfacesides && !(surfacesides[modelsurfacelistindex] & (1 << side)))
1357 if (surface->texture != batchsurfacelist[0]->texture)
1359 if (!BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
1361 r_refdef.stats[r_stat_lights_dynamicshadowtriangles] += surface->num_triangles;
1362 r_refdef.stats[r_stat_lights_shadowtriangles] += surface->num_triangles;
1363 batchsurfacelist[batchnumsurfaces++] = surface;
1365 --modelsurfacelistindex;
1366 GL_CullFace(rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE ? GL_NONE : r_refdef.view.cullface_back);
1367 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ALLOWMULTIDRAW, batchnumsurfaces, batchsurfacelist);
1368 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
1371 R_FrameData_ReturnToMark();
1374 #define BATCHSIZE 1024
1376 static void R_Q1BSP_DrawLight_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
1378 int i, j, endsurface;
1380 const msurface_t *surface;
1381 R_FrameData_SetMark();
1382 // note: in practice this never actually receives batches
1383 R_Shadow_RenderMode_Begin();
1384 R_Shadow_RenderMode_ActiveLight(rtlight);
1385 R_Shadow_RenderMode_Lighting(true, rtlight->shadowmapatlassidesize != 0, (ent->flags & RENDER_NOSELFSHADOW) != 0);
1386 R_Shadow_SetupEntityLight(ent);
1387 for (i = 0;i < numsurfaces;i = j)
1390 surface = rsurface.modelsurfaces + surfacelist[i];
1391 t = surface->texture;
1392 rsurface.texture = R_GetCurrentTexture(t);
1393 endsurface = min(j + BATCHSIZE, numsurfaces);
1394 for (j = i;j < endsurface;j++)
1396 surface = rsurface.modelsurfaces + surfacelist[j];
1397 if (t != surface->texture)
1399 R_Shadow_RenderLighting(1, &surface);
1402 R_Shadow_RenderMode_End();
1403 R_FrameData_ReturnToMark();
1406 extern qboolean r_shadow_usingdeferredprepass;
1407 void R_Q1BSP_DrawLight(entity_render_t *ent, int numsurfaces, const int *surfacelist, const unsigned char *lighttrispvs)
1409 dp_model_t *model = ent->model;
1410 const msurface_t *surface;
1411 int i, k, kend, l, endsurface, batchnumsurfaces, texturenumsurfaces;
1412 const msurface_t **texturesurfacelist;
1415 R_FrameData_SetMark();
1416 // this is a double loop because non-visible surface skipping has to be
1417 // fast, and even if this is not the world model (and hence no visibility
1418 // checking) the input surface list and batch buffer are different formats
1419 // so some processing is necessary. (luckily models have few surfaces)
1420 for (i = 0;i < numsurfaces;)
1422 batchnumsurfaces = 0;
1423 endsurface = min(i + RSURF_MAX_BATCHSURFACES, numsurfaces);
1424 if (ent == r_refdef.scene.worldentity)
1426 for (;i < endsurface;i++)
1427 if (r_refdef.viewcache.world_surfacevisible[surfacelist[i]])
1428 batchsurfacelist[batchnumsurfaces++] = model->data_surfaces + surfacelist[i];
1432 for (;i < endsurface;i++)
1433 batchsurfacelist[batchnumsurfaces++] = model->data_surfaces + surfacelist[i];
1435 if (!batchnumsurfaces)
1437 for (k = 0;k < batchnumsurfaces;k = kend)
1439 surface = batchsurfacelist[k];
1440 tex = surface->texture;
1441 rsurface.texture = R_GetCurrentTexture(tex);
1442 // gather surfaces into a batch range
1443 for (kend = k;kend < batchnumsurfaces && tex == batchsurfacelist[kend]->texture;kend++)
1445 // now figure out what to do with this particular range of surfaces
1446 // VorteX: added MATERIALFLAG_NORTLIGHT
1447 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WALL | MATERIALFLAG_NORTLIGHT)) != MATERIALFLAG_WALL)
1449 if (r_fb.water.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
1451 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
1453 vec3_t tempcenter, center;
1454 for (l = k;l < kend;l++)
1456 surface = batchsurfacelist[l];
1457 if (r_transparent_sortsurfacesbynearest.integer)
1459 tempcenter[0] = bound(surface->mins[0], rsurface.localvieworigin[0], surface->maxs[0]);
1460 tempcenter[1] = bound(surface->mins[1], rsurface.localvieworigin[1], surface->maxs[1]);
1461 tempcenter[2] = bound(surface->mins[2], rsurface.localvieworigin[2], surface->maxs[2]);
1465 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
1466 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
1467 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
1469 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
1470 if (ent->transparent_offset) // transparent offset
1472 center[0] += r_refdef.view.forward[0]*ent->transparent_offset;
1473 center[1] += r_refdef.view.forward[1]*ent->transparent_offset;
1474 center[2] += r_refdef.view.forward[2]*ent->transparent_offset;
1476 R_MeshQueue_AddTransparent((rsurface.entity->flags & RENDER_WORLDOBJECT) ? TRANSPARENTSORT_SKY : ((rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) ? TRANSPARENTSORT_HUD : rsurface.texture->transparentsort), center, R_Q1BSP_DrawLight_TransparentCallback, ent, surface - rsurface.modelsurfaces, rsurface.rtlight);
1480 if (r_shadow_usingdeferredprepass)
1482 texturenumsurfaces = kend - k;
1483 texturesurfacelist = batchsurfacelist + k;
1484 R_Shadow_RenderLighting(texturenumsurfaces, texturesurfacelist);
1487 R_FrameData_ReturnToMark();
1491 static void R_ReplaceWorldTexture (void)
1496 const char *r, *newt;
1497 skinframe_t *skinframe;
1498 if (!r_refdef.scene.worldmodel)
1500 Con_Printf("There is no worldmodel\n");
1503 m = r_refdef.scene.worldmodel;
1507 Con_Print("r_replacemaptexture <texname> <newtexname> - replaces texture\n");
1508 Con_Print("r_replacemaptexture <texname> - switch back to default texture\n");
1511 if(!cl.islocalgame || !cl.worldmodel)
1513 Con_Print("This command works only in singleplayer\n");
1520 for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
1522 if(/*t->width && !strcasecmp(t->name, r)*/ matchpattern( t->name, r, true ) )
1524 if ((skinframe = R_SkinFrame_LoadExternal(newt, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PICMIP, true, false)))
1526 // t->skinframes[0] = skinframe;
1527 t->currentskinframe = skinframe;
1528 Con_Printf("%s replaced with %s\n", r, newt);
1532 Con_Printf("%s was not found\n", newt);
1540 static void R_ListWorldTextures (void)
1545 if (!r_refdef.scene.worldmodel)
1547 Con_Printf("There is no worldmodel\n");
1550 m = r_refdef.scene.worldmodel;
1552 Con_Print("Worldmodel textures :\n");
1553 for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
1554 if (t->name[0] && strcasecmp(t->name, "NO TEXTURE FOUND"))
1555 Con_Printf("%s\n", t->name);
1559 static void gl_surf_start(void)
1563 static void gl_surf_shutdown(void)
1567 static void gl_surf_newmap(void)
1572 void GL_Surf_Init(void)
1575 Cvar_RegisterVariable(&r_ambient);
1576 Cvar_RegisterVariable(&r_lockpvs);
1577 Cvar_RegisterVariable(&r_lockvisibility);
1578 Cvar_RegisterVariable(&r_useportalculling);
1579 Cvar_RegisterVariable(&r_usesurfaceculling);
1580 Cvar_RegisterVariable(&r_vis_trace);
1581 Cvar_RegisterVariable(&r_vis_trace_samples);
1582 Cvar_RegisterVariable(&r_vis_trace_delay);
1583 Cvar_RegisterVariable(&r_vis_trace_eyejitter);
1584 Cvar_RegisterVariable(&r_vis_trace_enlarge);
1585 Cvar_RegisterVariable(&r_vis_trace_expand);
1586 Cvar_RegisterVariable(&r_vis_trace_pad);
1587 Cvar_RegisterVariable(&r_vis_trace_surfaces);
1588 Cvar_RegisterVariable(&r_q3bsp_renderskydepth);
1590 Cmd_AddCommand ("r_replacemaptexture", R_ReplaceWorldTexture, "override a map texture for testing purposes");
1591 Cmd_AddCommand ("r_listmaptextures", R_ListWorldTextures, "list all textures used by the current map");
1593 //R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);