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