merged static and dynamic rtlight handling almost entirely (even uses DrawShadowVolum...
[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
25 #define MAX_LIGHTMAP_SIZE 256
26
27 static unsigned int intblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
28 static float floatblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
29
30 static qbyte templight[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*4];
31
32 cvar_t r_ambient = {0, "r_ambient", "0"};
33 cvar_t r_drawportals = {0, "r_drawportals", "0"};
34 cvar_t r_testvis = {0, "r_testvis", "0"};
35 cvar_t r_floatbuildlightmap = {0, "r_floatbuildlightmap", "0"};
36 cvar_t r_detailtextures = {CVAR_SAVE, "r_detailtextures", "1"};
37 cvar_t r_surfaceworldnode = {0, "r_surfaceworldnode", "1"};
38 cvar_t r_drawcollisionbrushes_polygonfactor = {0, "r_drawcollisionbrushes_polygonfactor", "-1"};
39 cvar_t r_drawcollisionbrushes_polygonoffset = {0, "r_drawcollisionbrushes_polygonoffset", "0"};
40 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0"};
41
42 /*
43 // FIXME: these arrays are huge!
44 int r_q1bsp_maxmarkleafs;
45 int r_q1bsp_nummarkleafs;
46 mleaf_t *r_q1bsp_maxleaflist[65536];
47 int r_q1bsp_maxmarksurfaces;
48 int r_q1bsp_nummarksurfaces;
49 msurface_t *r_q1bsp_maxsurfacelist[65536];
50
51 // FIXME: these arrays are huge!
52 int r_q3bsp_maxmarkleafs;
53 int r_q3bsp_nummarkleafs;
54 q3mleaf_t *r_q3bsp_maxleaflist[65536];
55 int r_q3bsp_maxmarksurfaces;
56 int r_q3bsp_nummarksurfaces;
57 q3mface_t *r_q3bsp_maxsurfacelist[65536];
58 */
59
60 static int dlightdivtable[32768];
61
62 static int R_IntAddDynamicLights (const matrix4x4_t *matrix, msurface_t *surf)
63 {
64         int sdtable[256], lnum, td, maxdist, maxdist2, maxdist3, i, s, t, smax, tmax, smax3, red, green, blue, lit, dist2, impacts, impactt, subtract, k;
65         unsigned int *bl;
66         float dist, impact[3], local[3];
67         dlight_t *light;
68
69         lit = false;
70
71         smax = (surf->extents[0] >> 4) + 1;
72         tmax = (surf->extents[1] >> 4) + 1;
73         smax3 = smax * 3;
74
75         for (lnum = 0, light = r_dlight;lnum < r_numdlights;lnum++, light++)
76         {
77                 if (!(surf->dlightbits[lnum >> 5] & (1 << (lnum & 31))))
78                         continue;                                       // not lit by this light
79
80                 Matrix4x4_Transform(matrix, light->origin, local);
81                 dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
82
83                 // for comparisons to minimum acceptable light
84                 // compensate for LIGHTOFFSET
85                 maxdist = (int) light->rtlight.lightmap_cullradius2 + LIGHTOFFSET;
86
87                 dist2 = dist * dist;
88                 dist2 += LIGHTOFFSET;
89                 if (dist2 >= maxdist)
90                         continue;
91
92                 if (surf->plane->type < 3)
93                 {
94                         VectorCopy(local, impact);
95                         impact[surf->plane->type] -= dist;
96                 }
97                 else
98                 {
99                         impact[0] = local[0] - surf->plane->normal[0] * dist;
100                         impact[1] = local[1] - surf->plane->normal[1] * dist;
101                         impact[2] = local[2] - surf->plane->normal[2] * dist;
102                 }
103
104                 impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
105                 impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
106
107                 s = bound(0, impacts, smax * 16) - impacts;
108                 t = bound(0, impactt, tmax * 16) - impactt;
109                 i = s * s + t * t + dist2;
110                 if (i > maxdist)
111                         continue;
112
113                 // reduce calculations
114                 for (s = 0, i = impacts; s < smax; s++, i -= 16)
115                         sdtable[s] = i * i + dist2;
116
117                 maxdist3 = maxdist - dist2;
118
119                 // convert to 8.8 blocklights format
120                 red = light->rtlight.lightmap_light[0] * (1.0f / 128.0f);
121                 green = light->rtlight.lightmap_light[1] * (1.0f / 128.0f);
122                 blue = light->rtlight.lightmap_light[2] * (1.0f / 128.0f);
123                 subtract = (int) (light->rtlight.lightmap_subtract * 4194304.0f);
124                 bl = intblocklights;
125
126                 i = impactt;
127                 for (t = 0;t < tmax;t++, i -= 16)
128                 {
129                         td = i * i;
130                         // make sure some part of it is visible on this line
131                         if (td < maxdist3)
132                         {
133                                 maxdist2 = maxdist - td;
134                                 for (s = 0;s < smax;s++)
135                                 {
136                                         if (sdtable[s] < maxdist2)
137                                         {
138                                                 k = dlightdivtable[(sdtable[s] + td) >> 7] - subtract;
139                                                 if (k > 0)
140                                                 {
141                                                         bl[0] += (red   * k);
142                                                         bl[1] += (green * k);
143                                                         bl[2] += (blue  * k);
144                                                         lit = true;
145                                                 }
146                                         }
147                                         bl += 3;
148                                 }
149                         }
150                         else // skip line
151                                 bl += smax3;
152                 }
153         }
154         return lit;
155 }
156
157 static int R_FloatAddDynamicLights (const matrix4x4_t *matrix, msurface_t *surf)
158 {
159         int lnum, s, t, smax, tmax, smax3, lit, impacts, impactt;
160         float sdtable[256], *bl, k, dist, dist2, maxdist, maxdist2, maxdist3, td1, td, red, green, blue, impact[3], local[3], subtract;
161         dlight_t *light;
162
163         lit = false;
164
165         smax = (surf->extents[0] >> 4) + 1;
166         tmax = (surf->extents[1] >> 4) + 1;
167         smax3 = smax * 3;
168
169         for (lnum = 0, light = r_dlight;lnum < r_numdlights;lnum++, light++)
170         {
171                 if (!(surf->dlightbits[lnum >> 5] & (1 << (lnum & 31))))
172                         continue;                                       // not lit by this light
173
174                 Matrix4x4_Transform(matrix, light->origin, local);
175                 dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
176
177                 // for comparisons to minimum acceptable light
178                 // compensate for LIGHTOFFSET
179                 maxdist = (int) light->rtlight.lightmap_cullradius2 + LIGHTOFFSET;
180
181                 dist2 = dist * dist;
182                 dist2 += LIGHTOFFSET;
183                 if (dist2 >= maxdist)
184                         continue;
185
186                 if (surf->plane->type < 3)
187                 {
188                         VectorCopy(local, impact);
189                         impact[surf->plane->type] -= dist;
190                 }
191                 else
192                 {
193                         impact[0] = local[0] - surf->plane->normal[0] * dist;
194                         impact[1] = local[1] - surf->plane->normal[1] * dist;
195                         impact[2] = local[2] - surf->plane->normal[2] * dist;
196                 }
197
198                 impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
199                 impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
200
201                 td = bound(0, impacts, smax * 16) - impacts;
202                 td1 = bound(0, impactt, tmax * 16) - impactt;
203                 td = td * td + td1 * td1 + dist2;
204                 if (td > maxdist)
205                         continue;
206
207                 // reduce calculations
208                 for (s = 0, td1 = impacts; s < smax; s++, td1 -= 16.0f)
209                         sdtable[s] = td1 * td1 + dist2;
210
211                 maxdist3 = maxdist - dist2;
212
213                 // convert to 8.8 blocklights format
214                 red = light->rtlight.lightmap_light[0];
215                 green = light->rtlight.lightmap_light[1];
216                 blue = light->rtlight.lightmap_light[2];
217                 subtract = light->rtlight.lightmap_subtract * 32768.0f;
218                 bl = floatblocklights;
219
220                 td1 = impactt;
221                 for (t = 0;t < tmax;t++, td1 -= 16.0f)
222                 {
223                         td = td1 * td1;
224                         // make sure some part of it is visible on this line
225                         if (td < maxdist3)
226                         {
227                                 maxdist2 = maxdist - td;
228                                 for (s = 0;s < smax;s++)
229                                 {
230                                         if (sdtable[s] < maxdist2)
231                                         {
232                                                 k = (32768.0f / (sdtable[s] + td)) - subtract;
233                                                 bl[0] += red   * k;
234                                                 bl[1] += green * k;
235                                                 bl[2] += blue  * k;
236                                                 lit = true;
237                                         }
238                                         bl += 3;
239                                 }
240                         }
241                         else // skip line
242                                 bl += smax3;
243                 }
244         }
245         return lit;
246 }
247
248 /*
249 ===============
250 R_BuildLightMap
251
252 Combine and scale multiple lightmaps into the 8.8 format in blocklights
253 ===============
254 */
255 static void R_BuildLightMap (const entity_render_t *ent, msurface_t *surf)
256 {
257         if (!r_floatbuildlightmap.integer)
258         {
259                 int smax, tmax, i, j, size, size3, maps, stride, l;
260                 unsigned int *bl, scale;
261                 qbyte *lightmap, *out, *stain;
262
263                 // update cached lighting info
264                 surf->cached_dlight = 0;
265
266                 smax = (surf->extents[0]>>4)+1;
267                 tmax = (surf->extents[1]>>4)+1;
268                 size = smax*tmax;
269                 size3 = size*3;
270                 lightmap = surf->samples;
271
272         // set to full bright if no light data
273                 bl = intblocklights;
274                 if (!ent->model->brushq1.lightdata)
275                 {
276                         for (i = 0;i < size3;i++)
277                                 bl[i] = 255*256;
278                 }
279                 else
280                 {
281         // clear to no light
282                         j = r_ambient.value * 512.0f; // would be 128.0f logically, but using 512.0f to match winquake style
283                         if (j)
284                         {
285                                 for (i = 0;i < size3;i++)
286                                         *bl++ = j;
287                         }
288                         else
289                                 memset(bl, 0, size*3*sizeof(unsigned int));
290
291                         if (surf->dlightframe == r_framecount)
292                         {
293                                 surf->cached_dlight = R_IntAddDynamicLights(&ent->inversematrix, surf);
294                                 if (surf->cached_dlight)
295                                         c_light_polys++;
296                         }
297
298         // add all the lightmaps
299                         if (lightmap)
300                         {
301                                 bl = intblocklights;
302                                 for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++, lightmap += size3)
303                                         for (scale = d_lightstylevalue[surf->styles[maps]], i = 0;i < size3;i++)
304                                                 bl[i] += lightmap[i] * scale;
305                         }
306                 }
307
308                 stain = surf->stainsamples;
309                 bl = intblocklights;
310                 out = templight;
311                 // the >> 16 shift adjusts down 8 bits to account for the stainmap
312                 // scaling, and remaps the 0-65536 (2x overbright) to 0-256, it will
313                 // be doubled during rendering to achieve 2x overbright
314                 // (0 = 0.0, 128 = 1.0, 256 = 2.0)
315                 if (ent->model->brushq1.lightmaprgba)
316                 {
317                         stride = (surf->lightmaptexturestride - smax) * 4;
318                         for (i = 0;i < tmax;i++, out += stride)
319                         {
320                                 for (j = 0;j < smax;j++)
321                                 {
322                                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
323                                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
324                                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
325                                         *out++ = 255;
326                                 }
327                         }
328                 }
329                 else
330                 {
331                         stride = (surf->lightmaptexturestride - smax) * 3;
332                         for (i = 0;i < tmax;i++, out += stride)
333                         {
334                                 for (j = 0;j < smax;j++)
335                                 {
336                                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
337                                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
338                                         l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
339                                 }
340                         }
341                 }
342
343                 R_UpdateTexture(surf->lightmaptexture, templight);
344         }
345         else
346         {
347                 int smax, tmax, i, j, size, size3, maps, stride, l;
348                 float *bl, scale;
349                 qbyte *lightmap, *out, *stain;
350
351                 // update cached lighting info
352                 surf->cached_dlight = 0;
353
354                 smax = (surf->extents[0]>>4)+1;
355                 tmax = (surf->extents[1]>>4)+1;
356                 size = smax*tmax;
357                 size3 = size*3;
358                 lightmap = surf->samples;
359
360         // set to full bright if no light data
361                 bl = floatblocklights;
362                 if (!ent->model->brushq1.lightdata)
363                         j = 255*256;
364                 else
365                         j = r_ambient.value * 512.0f; // would be 128.0f logically, but using 512.0f to match winquake style
366
367                 // clear to no light
368                 if (j)
369                 {
370                         for (i = 0;i < size3;i++)
371                                 *bl++ = j;
372                 }
373                 else
374                         memset(bl, 0, size*3*sizeof(float));
375
376                 if (surf->dlightframe == r_framecount)
377                 {
378                         surf->cached_dlight = R_FloatAddDynamicLights(&ent->inversematrix, surf);
379                         if (surf->cached_dlight)
380                                 c_light_polys++;
381                 }
382
383                 // add all the lightmaps
384                 if (lightmap)
385                 {
386                         bl = floatblocklights;
387                         for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++, lightmap += size3)
388                                 for (scale = d_lightstylevalue[surf->styles[maps]], i = 0;i < size3;i++)
389                                         bl[i] += lightmap[i] * scale;
390                 }
391
392                 stain = surf->stainsamples;
393                 bl = floatblocklights;
394                 out = templight;
395                 // this scaling adjusts down 8 bits to account for the stainmap
396                 // scaling, and remaps the 0.0-2.0 (2x overbright) to 0-256, it will
397                 // be doubled during rendering to achieve 2x overbright
398                 // (0 = 0.0, 128 = 1.0, 256 = 2.0)
399                 scale = 1.0f / (1 << 16);
400                 if (ent->model->brushq1.lightmaprgba)
401                 {
402                         stride = (surf->lightmaptexturestride - smax) * 4;
403                         for (i = 0;i < tmax;i++, out += stride)
404                         {
405                                 for (j = 0;j < smax;j++)
406                                 {
407                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
408                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
409                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
410                                         *out++ = 255;
411                                 }
412                         }
413                 }
414                 else
415                 {
416                         stride = (surf->lightmaptexturestride - smax) * 3;
417                         for (i = 0;i < tmax;i++, out += stride)
418                         {
419                                 for (j = 0;j < smax;j++)
420                                 {
421                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
422                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
423                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
424                                 }
425                         }
426                 }
427
428                 R_UpdateTexture(surf->lightmaptexture, templight);
429         }
430 }
431
432 void R_StainNode (mnode_t *node, model_t *model, const vec3_t origin, float radius, const float fcolor[8])
433 {
434         float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
435         msurface_t *surf, *endsurf;
436         int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
437         qbyte *bl;
438         vec3_t impact;
439
440         maxdist = radius * radius;
441         invradius = 1.0f / radius;
442
443 loc0:
444         if (node->contents < 0)
445                 return;
446         ndist = PlaneDiff(origin, node->plane);
447         if (ndist > radius)
448         {
449                 node = node->children[0];
450                 goto loc0;
451         }
452         if (ndist < -radius)
453         {
454                 node = node->children[1];
455                 goto loc0;
456         }
457
458         dist2 = ndist * ndist;
459         maxdist3 = maxdist - dist2;
460
461         if (node->plane->type < 3)
462         {
463                 VectorCopy(origin, impact);
464                 impact[node->plane->type] -= ndist;
465         }
466         else
467         {
468                 impact[0] = origin[0] - node->plane->normal[0] * ndist;
469                 impact[1] = origin[1] - node->plane->normal[1] * ndist;
470                 impact[2] = origin[2] - node->plane->normal[2] * ndist;
471         }
472
473         for (surf = model->brushq1.surfaces + node->firstsurface, endsurf = surf + node->numsurfaces;surf < endsurf;surf++)
474         {
475                 if (surf->stainsamples)
476                 {
477                         smax = (surf->extents[0] >> 4) + 1;
478                         tmax = (surf->extents[1] >> 4) + 1;
479
480                         impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
481                         impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
482
483                         s = bound(0, impacts, smax * 16) - impacts;
484                         t = bound(0, impactt, tmax * 16) - impactt;
485                         i = s * s + t * t + dist2;
486                         if (i > maxdist)
487                                 continue;
488
489                         // reduce calculations
490                         for (s = 0, i = impacts; s < smax; s++, i -= 16)
491                                 sdtable[s] = i * i + dist2;
492
493                         bl = surf->stainsamples;
494                         smax3 = smax * 3;
495                         stained = false;
496
497                         i = impactt;
498                         for (t = 0;t < tmax;t++, i -= 16)
499                         {
500                                 td = i * i;
501                                 // make sure some part of it is visible on this line
502                                 if (td < maxdist3)
503                                 {
504                                         maxdist2 = maxdist - td;
505                                         for (s = 0;s < smax;s++)
506                                         {
507                                                 if (sdtable[s] < maxdist2)
508                                                 {
509                                                         ratio = lhrandom(0.0f, 1.0f);
510                                                         a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
511                                                         if (a >= (1.0f / 64.0f))
512                                                         {
513                                                                 if (a > 1)
514                                                                         a = 1;
515                                                                 bl[0] = (qbyte) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
516                                                                 bl[1] = (qbyte) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
517                                                                 bl[2] = (qbyte) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
518                                                                 stained = true;
519                                                         }
520                                                 }
521                                                 bl += 3;
522                                         }
523                                 }
524                                 else // skip line
525                                         bl += smax3;
526                         }
527                         // force lightmap upload
528                         if (stained)
529                                 surf->cached_dlight = true;
530                 }
531         }
532
533         if (node->children[0]->contents >= 0)
534         {
535                 if (node->children[1]->contents >= 0)
536                 {
537                         R_StainNode(node->children[0], model, origin, radius, fcolor);
538                         node = node->children[1];
539                         goto loc0;
540                 }
541                 else
542                 {
543                         node = node->children[0];
544                         goto loc0;
545                 }
546         }
547         else if (node->children[1]->contents >= 0)
548         {
549                 node = node->children[1];
550                 goto loc0;
551         }
552 }
553
554 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)
555 {
556         int n;
557         float fcolor[8];
558         entity_render_t *ent;
559         model_t *model;
560         vec3_t org;
561         if (cl.worldmodel == NULL || !cl.worldmodel->brushq1.nodes)
562                 return;
563         fcolor[0] = cr1;
564         fcolor[1] = cg1;
565         fcolor[2] = cb1;
566         fcolor[3] = ca1 * (1.0f / 64.0f);
567         fcolor[4] = cr2 - cr1;
568         fcolor[5] = cg2 - cg1;
569         fcolor[6] = cb2 - cb1;
570         fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
571
572         R_StainNode(cl.worldmodel->brushq1.nodes + cl.worldmodel->brushq1.hulls[0].firstclipnode, cl.worldmodel, origin, radius, fcolor);
573
574         // look for embedded bmodels
575         for (n = 0;n < cl_num_brushmodel_entities;n++)
576         {
577                 ent = cl_brushmodel_entities[n];
578                 model = ent->model;
579                 if (model && model->name[0] == '*')
580                 {
581                         Mod_CheckLoaded(model);
582                         if (model->brushq1.nodes)
583                         {
584                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
585                                 R_StainNode(model->brushq1.nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
586                         }
587                 }
588         }
589 }
590
591
592 /*
593 =============================================================
594
595         BRUSH MODELS
596
597 =============================================================
598 */
599
600 static void RSurf_AddLightmapToVertexColors_Color4f(const int *lightmapoffsets, float *c, int numverts, const qbyte *samples, int size3, const qbyte *styles)
601 {
602         int i;
603         float scale;
604         const qbyte *lm;
605         if (styles[0] != 255)
606         {
607                 for (i = 0;i < numverts;i++, c += 4)
608                 {
609                         lm = samples + lightmapoffsets[i];
610                         scale = d_lightstylevalue[styles[0]] * (1.0f / 32768.0f);
611                         VectorMA(c, scale, lm, c);
612                         if (styles[1] != 255)
613                         {
614                                 lm += size3;
615                                 scale = d_lightstylevalue[styles[1]] * (1.0f / 32768.0f);
616                                 VectorMA(c, scale, lm, c);
617                                 if (styles[2] != 255)
618                                 {
619                                         lm += size3;
620                                         scale = d_lightstylevalue[styles[2]] * (1.0f / 32768.0f);
621                                         VectorMA(c, scale, lm, c);
622                                         if (styles[3] != 255)
623                                         {
624                                                 lm += size3;
625                                                 scale = d_lightstylevalue[styles[3]] * (1.0f / 32768.0f);
626                                                 VectorMA(c, scale, lm, c);
627                                         }
628                                 }
629                         }
630                 }
631         }
632 }
633
634 static void RSurf_FogColors_Vertex3f_Color4f(const float *v, float *c, float colorscale, int numverts, const float *modelorg)
635 {
636         int i;
637         float diff[3], f;
638         if (fogenabled)
639         {
640                 for (i = 0;i < numverts;i++, v += 3, c += 4)
641                 {
642                         VectorSubtract(v, modelorg, diff);
643                         f = colorscale * (1 - exp(fogdensity/DotProduct(diff, diff)));
644                         VectorScale(c, f, c);
645                 }
646         }
647         else if (colorscale != 1)
648                 for (i = 0;i < numverts;i++, c += 4)
649                         VectorScale(c, colorscale, c);
650 }
651
652 static void RSurf_FoggedColors_Vertex3f_Color4f(const float *v, float *c, float r, float g, float b, float a, float colorscale, int numverts, const float *modelorg)
653 {
654         int i;
655         float diff[3], f;
656         r *= colorscale;
657         g *= colorscale;
658         b *= colorscale;
659         if (fogenabled)
660         {
661                 for (i = 0;i < numverts;i++, v += 3, c += 4)
662                 {
663                         VectorSubtract(v, modelorg, diff);
664                         f = 1 - exp(fogdensity/DotProduct(diff, diff));
665                         c[0] = r * f;
666                         c[1] = g * f;
667                         c[2] = b * f;
668                         c[3] = a;
669                 }
670         }
671         else
672         {
673                 for (i = 0;i < numverts;i++, c += 4)
674                 {
675                         c[0] = r;
676                         c[1] = g;
677                         c[2] = b;
678                         c[3] = a;
679                 }
680         }
681 }
682
683 static void RSurf_FogPassColors_Vertex3f_Color4f(const float *v, float *c, float r, float g, float b, float a, float colorscale, int numverts, const float *modelorg)
684 {
685         int i;
686         float diff[3], f;
687         r *= colorscale;
688         g *= colorscale;
689         b *= colorscale;
690         for (i = 0;i < numverts;i++, v += 3, c += 4)
691         {
692                 VectorSubtract(v, modelorg, diff);
693                 f = exp(fogdensity/DotProduct(diff, diff));
694                 c[0] = r;
695                 c[1] = g;
696                 c[2] = b;
697                 c[3] = a * f;
698         }
699 }
700
701 static int RSurf_LightSeparate_Vertex3f_Color4f(const matrix4x4_t *matrix, const int *dlightbits, int numverts, const float *vert, float *color, float scale)
702 {
703         float f;
704         const float *v;
705         float *c;
706         int i, l, lit = false;
707         const dlight_t *light;
708         vec3_t lightorigin;
709         for (l = 0;l < r_numdlights;l++)
710         {
711                 if (dlightbits[l >> 5] & (1 << (l & 31)))
712                 {
713                         light = &r_dlight[l];
714                         Matrix4x4_Transform(matrix, light->origin, lightorigin);
715                         for (i = 0, v = vert, c = color;i < numverts;i++, v += 3, c += 4)
716                         {
717                                 f = VectorDistance2(v, lightorigin) + LIGHTOFFSET;
718                                 if (f < light->rtlight.lightmap_cullradius2)
719                                 {
720                                         f = ((1.0f / f) - light->rtlight.lightmap_subtract) * scale;
721                                         VectorMA(c, f, light->rtlight.lightmap_light, c);
722                                         lit = true;
723                                 }
724                         }
725                 }
726         }
727         return lit;
728 }
729
730 static void RSurfShader_Sky(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
731 {
732         const msurface_t *surf;
733         rmeshstate_t m;
734
735         // LordHavoc: HalfLife maps have freaky skypolys...
736         if (ent->model->brush.ishlbsp)
737                 return;
738
739         if (skyrendernow)
740         {
741                 skyrendernow = false;
742                 if (skyrendermasked)
743                         R_Sky();
744         }
745
746         R_Mesh_Matrix(&ent->matrix);
747
748         GL_Color(fogcolor[0], fogcolor[1], fogcolor[2], 1);
749         if (skyrendermasked)
750         {
751                 // depth-only (masking)
752                 GL_ColorMask(0,0,0,0);
753                 // just to make sure that braindead drivers don't draw anything
754                 // despite that colormask...
755                 GL_BlendFunc(GL_ZERO, GL_ONE);
756         }
757         else
758         {
759                 // fog sky
760                 GL_BlendFunc(GL_ONE, GL_ZERO);
761         }
762         GL_DepthMask(true);
763         GL_DepthTest(true);
764
765         memset(&m, 0, sizeof(m));
766         while((surf = *surfchain++) != NULL)
767         {
768                 if (surf->visframe == r_framecount)
769                 {
770                         m.pointer_vertex = surf->mesh.data_vertex3f;
771                         R_Mesh_State(&m);
772                         GL_LockArrays(0, surf->mesh.num_vertices);
773                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
774                         GL_LockArrays(0, 0);
775                 }
776         }
777         GL_ColorMask(1,1,1,1);
778 }
779
780 static void RSurfShader_Water_Callback(const void *calldata1, int calldata2)
781 {
782         const entity_render_t *ent = calldata1;
783         const msurface_t *surf = ent->model->brushq1.surfaces + calldata2;
784         rmeshstate_t m;
785         float alpha;
786         float modelorg[3];
787         texture_t *texture;
788         float args[4] = {0.05f,0,0,0.04f};
789
790         R_Mesh_Matrix(&ent->matrix);
791         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
792
793         texture = surf->texinfo->texture->currentframe;
794         alpha = texture->currentalpha;
795         if (texture->rendertype == SURFRENDER_ADD)
796         {
797                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
798                 GL_DepthMask(false);
799         }
800         else if (texture->rendertype == SURFRENDER_ALPHA)
801         {
802                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
803                 GL_DepthMask(false);
804         }
805         else
806         {
807                 GL_BlendFunc(GL_ONE, GL_ZERO);
808                 GL_DepthMask(true);
809         }
810         GL_DepthTest(true);
811         GL_Color(1, 1, 1, alpha);
812         memset(&m, 0, sizeof(m));
813         m.pointer_vertex = surf->mesh.data_vertex3f;
814         if (gl_textureshader && r_watershader.value && !fogenabled)
815         {
816                 m.tex[0] = R_GetTexture(mod_shared_distorttexture[(int)(cl.time * 16)&63]);
817                 m.tex[1] = R_GetTexture(texture->skin.base);
818                 m.texcombinergb[0] = GL_REPLACE;
819                 m.texcombinergb[1] = GL_REPLACE;
820                 m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
821                 m.pointer_texcoord[1] = surf->mesh.data_texcoordtexture2f;
822                 Matrix4x4_CreateFromQuakeEntity(&m.texmatrix[0], 0, 0, 0, 0, 0, 0, r_watershader.value);
823                 Matrix4x4_CreateTranslate(&m.texmatrix[1], sin(cl.time) * 0.025 * r_waterscroll.value, sin(cl.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
824                 R_Mesh_State(&m);
825
826                 GL_ActiveTexture(0);
827                 qglTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_2D);
828                 GL_ActiveTexture(1);
829                 qglTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_OFFSET_TEXTURE_2D_NV);
830                 qglTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB);
831                 qglTexEnvfv(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_MATRIX_NV, &args[0]);
832                 qglEnable(GL_TEXTURE_SHADER_NV);
833
834                 GL_LockArrays(0, surf->mesh.num_vertices);
835                 R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
836                 GL_LockArrays(0, 0);
837
838                 qglDisable(GL_TEXTURE_SHADER_NV);
839                 qglTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_2D);
840                 GL_ActiveTexture(0);
841         }
842         else
843         {
844                 if (fogenabled)
845                 {
846                         R_FillColors(varray_color4f, surf->mesh.num_vertices, 1, 1, 1, alpha);
847                         RSurf_FogColors_Vertex3f_Color4f(surf->mesh.data_vertex3f, varray_color4f, 1, surf->mesh.num_vertices, modelorg);
848                         m.pointer_color = varray_color4f;
849                 }
850                 m.tex[0] = R_GetTexture(texture->skin.base);
851                 m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
852                 if (r_waterscroll.value)
853                 {
854                         // scrolling in texture matrix
855                         Matrix4x4_CreateTranslate(&m.texmatrix[0], sin(cl.time) * 0.025 * r_waterscroll.value, sin(cl.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
856                 }
857                 R_Mesh_State(&m);
858
859                 GL_LockArrays(0, surf->mesh.num_vertices);
860                 R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
861                 GL_LockArrays(0, 0);
862
863                 if (fogenabled && texture->rendertype != SURFRENDER_ADD)
864                 {
865                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
866                         GL_DepthMask(false);
867                         RSurf_FogPassColors_Vertex3f_Color4f(surf->mesh.data_vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], alpha, 1, surf->mesh.num_vertices, modelorg);
868                         m.tex[0] = R_GetTexture(texture->skin.fog);
869                         R_Mesh_State(&m);
870                         GL_LockArrays(0, surf->mesh.num_vertices);
871                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
872                         GL_LockArrays(0, 0);
873                 }
874         }
875 }
876
877 static void RSurfShader_Water(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
878 {
879         const msurface_t *surf;
880         msurface_t **chain;
881         vec3_t center;
882         if (texture->rendertype != SURFRENDER_OPAQUE)
883         {
884                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
885                 {
886                         if (surf->visframe == r_framecount)
887                         {
888                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
889                                 R_MeshQueue_AddTransparent(center, RSurfShader_Water_Callback, ent, surf - ent->model->brushq1.surfaces);
890                         }
891                 }
892         }
893         else
894                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
895                         if (surf->visframe == r_framecount)
896                                 RSurfShader_Water_Callback(ent, surf - ent->model->brushq1.surfaces);
897 }
898
899 static void RSurfShader_Wall_Pass_BaseVertex(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
900 {
901         float base, colorscale;
902         rmeshstate_t m;
903         float modelorg[3];
904         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
905         memset(&m, 0, sizeof(m));
906         if (rendertype == SURFRENDER_ADD)
907         {
908                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
909                 GL_DepthMask(false);
910         }
911         else if (rendertype == SURFRENDER_ALPHA)
912         {
913                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
914                 GL_DepthMask(false);
915         }
916         else
917         {
918                 GL_BlendFunc(GL_ONE, GL_ZERO);
919                 GL_DepthMask(true);
920         }
921         m.tex[0] = R_GetTexture(texture->skin.base);
922         colorscale = 1;
923         if (gl_combine.integer)
924         {
925                 m.texrgbscale[0] = 4;
926                 colorscale *= 0.25f;
927         }
928         base = ent->effects & EF_FULLBRIGHT ? 2.0f : r_ambient.value * (1.0f / 64.0f);
929         GL_DepthTest(true);
930
931         m.pointer_color = varray_color4f;
932         m.pointer_vertex = surf->mesh.data_vertex3f;
933         m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
934         R_Mesh_State(&m);
935         R_FillColors(varray_color4f, surf->mesh.num_vertices, base, base, base, currentalpha);
936         if (!(ent->effects & EF_FULLBRIGHT))
937         {
938                 if (surf->dlightframe == r_framecount)
939                         RSurf_LightSeparate_Vertex3f_Color4f(&ent->inversematrix, surf->dlightbits, surf->mesh.num_vertices, surf->mesh.data_vertex3f, varray_color4f, 1);
940                 if (surf->flags & SURF_LIGHTMAP)
941                         RSurf_AddLightmapToVertexColors_Color4f(surf->mesh.data_lightmapoffsets, varray_color4f,surf->mesh.num_vertices, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
942         }
943         RSurf_FogColors_Vertex3f_Color4f(surf->mesh.data_vertex3f, varray_color4f, colorscale, surf->mesh.num_vertices, modelorg);
944         GL_LockArrays(0, surf->mesh.num_vertices);
945         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
946         GL_LockArrays(0, 0);
947 }
948
949 static void RSurfShader_Wall_Pass_Glow(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
950 {
951         rmeshstate_t m;
952         float modelorg[3];
953         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
954         memset(&m, 0, sizeof(m));
955         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
956         GL_DepthMask(false);
957         GL_DepthTest(true);
958         m.pointer_color = varray_color4f;
959         m.tex[0] = R_GetTexture(texture->skin.glow);
960
961         m.pointer_vertex = surf->mesh.data_vertex3f;
962         if (m.tex[0])
963                 m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
964         R_Mesh_State(&m);
965         RSurf_FoggedColors_Vertex3f_Color4f(surf->mesh.data_vertex3f, varray_color4f, 1, 1, 1, currentalpha, 1, surf->mesh.num_vertices, modelorg);
966         GL_LockArrays(0, surf->mesh.num_vertices);
967         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
968         GL_LockArrays(0, 0);
969 }
970
971 static void RSurfShader_Wall_Pass_Fog(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
972 {
973         rmeshstate_t m;
974         float modelorg[3];
975         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
976         memset(&m, 0, sizeof(m));
977         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
978         GL_DepthMask(false);
979         GL_DepthTest(true);
980         m.pointer_color = varray_color4f;
981         m.tex[0] = R_GetTexture(texture->skin.fog);
982
983         m.pointer_vertex = surf->mesh.data_vertex3f;
984         if (m.tex[0])
985                 m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
986         R_Mesh_State(&m);
987         RSurf_FogPassColors_Vertex3f_Color4f(surf->mesh.data_vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], currentalpha, 1, surf->mesh.num_vertices, modelorg);
988         GL_LockArrays(0, surf->mesh.num_vertices);
989         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
990         GL_LockArrays(0, 0);
991 }
992
993 static void RSurfShader_OpaqueWall_Pass_BaseCombine_TextureLightmapDetailGlow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
994 {
995         const msurface_t *surf;
996         rmeshstate_t m;
997         int lightmaptexturenum;
998         memset(&m, 0, sizeof(m));
999         GL_BlendFunc(GL_ONE, GL_ZERO);
1000         GL_DepthMask(true);
1001         GL_DepthTest(true);
1002         m.tex[0] = R_GetTexture(texture->skin.base);
1003         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1004         m.texrgbscale[1] = 2;
1005         m.tex[2] = R_GetTexture(texture->skin.detail);
1006         m.texrgbscale[2] = 2;
1007         if (texture->skin.glow)
1008         {
1009                 m.tex[3] = R_GetTexture(texture->skin.glow);
1010                 m.texcombinergb[3] = GL_ADD;
1011         }
1012         if (r_shadow_realtime_world.integer)
1013                 GL_Color(r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, 1);
1014         else
1015                 GL_Color(1, 1, 1, 1);
1016
1017         while((surf = *surfchain++) != NULL)
1018         {
1019                 if (surf->visframe == r_framecount)
1020                 {
1021                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1022                         m.tex[1] = lightmaptexturenum;
1023                         m.pointer_vertex = surf->mesh.data_vertex3f;
1024                         m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
1025                         m.pointer_texcoord[1] = surf->mesh.data_texcoordlightmap2f;
1026                         m.pointer_texcoord[2] = surf->mesh.data_texcoorddetail2f;
1027                         m.pointer_texcoord[3] = surf->mesh.data_texcoordtexture2f;
1028                         R_Mesh_State(&m);
1029                         GL_LockArrays(0, surf->mesh.num_vertices);
1030                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1031                         GL_LockArrays(0, 0);
1032                 }
1033         }
1034 }
1035
1036 static void RSurfShader_OpaqueWall_Pass_BaseCombine_TextureLightmapDetail(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1037 {
1038         const msurface_t *surf;
1039         rmeshstate_t m;
1040         int lightmaptexturenum;
1041         memset(&m, 0, sizeof(m));
1042         GL_BlendFunc(GL_ONE, GL_ZERO);
1043         GL_DepthMask(true);
1044         GL_DepthTest(true);
1045         m.tex[0] = R_GetTexture(texture->skin.base);
1046         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1047         m.texrgbscale[1] = 2;
1048         m.tex[2] = R_GetTexture(texture->skin.detail);
1049         m.texrgbscale[2] = 2;
1050         if (r_shadow_realtime_world.integer)
1051                 GL_Color(r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, 1);
1052         else
1053                 GL_Color(1, 1, 1, 1);
1054
1055         while((surf = *surfchain++) != NULL)
1056         {
1057                 if (surf->visframe == r_framecount)
1058                 {
1059                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1060                         m.tex[1] = lightmaptexturenum;
1061                         m.pointer_vertex = surf->mesh.data_vertex3f;
1062                         m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
1063                         m.pointer_texcoord[1] = surf->mesh.data_texcoordlightmap2f;
1064                         m.pointer_texcoord[2] = surf->mesh.data_texcoorddetail2f;
1065                         R_Mesh_State(&m);
1066                         GL_LockArrays(0, surf->mesh.num_vertices);
1067                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1068                         GL_LockArrays(0, 0);
1069                 }
1070         }
1071 }
1072
1073 static void RSurfShader_OpaqueWall_Pass_BaseCombine_TextureLightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1074 {
1075         const msurface_t *surf;
1076         rmeshstate_t m;
1077         int lightmaptexturenum;
1078         memset(&m, 0, sizeof(m));
1079         GL_BlendFunc(GL_ONE, GL_ZERO);
1080         GL_DepthMask(true);
1081         GL_DepthTest(true);
1082         m.tex[0] = R_GetTexture(texture->skin.base);
1083         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1084         m.texrgbscale[1] = 2;
1085         if (r_shadow_realtime_world.integer)
1086                 GL_Color(r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, 1);
1087         else
1088                 GL_Color(1, 1, 1, 1);
1089         while((surf = *surfchain++) != NULL)
1090         {
1091                 if (surf->visframe == r_framecount)
1092                 {
1093                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1094                         m.tex[1] = lightmaptexturenum;
1095                         m.pointer_vertex = surf->mesh.data_vertex3f;
1096                         m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
1097                         m.pointer_texcoord[1] = surf->mesh.data_texcoordlightmap2f;
1098                         R_Mesh_State(&m);
1099                         GL_LockArrays(0, surf->mesh.num_vertices);
1100                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1101                         GL_LockArrays(0, 0);
1102                 }
1103         }
1104 }
1105
1106 static void RSurfShader_OpaqueWall_Pass_BaseTexture(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1107 {
1108         const msurface_t *surf;
1109         rmeshstate_t m;
1110         memset(&m, 0, sizeof(m));
1111         GL_DepthMask(true);
1112         GL_DepthTest(true);
1113         GL_BlendFunc(GL_ONE, GL_ZERO);
1114         m.tex[0] = R_GetTexture(texture->skin.base);
1115         if (r_shadow_realtime_world.integer)
1116                 GL_Color(r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, 1);
1117         else
1118                 GL_Color(1, 1, 1, 1);
1119         while((surf = *surfchain++) != NULL)
1120         {
1121                 if (surf->visframe == r_framecount)
1122                 {
1123                         m.pointer_vertex = surf->mesh.data_vertex3f;
1124                         m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
1125                         R_Mesh_State(&m);
1126                         GL_LockArrays(0, surf->mesh.num_vertices);
1127                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1128                         GL_LockArrays(0, 0);
1129                 }
1130         }
1131 }
1132
1133 static void RSurfShader_OpaqueWall_Pass_BaseLightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1134 {
1135         const msurface_t *surf;
1136         rmeshstate_t m;
1137         int lightmaptexturenum;
1138         memset(&m, 0, sizeof(m));
1139         GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
1140         GL_DepthMask(false);
1141         GL_DepthTest(true);
1142         m.tex[0] = R_GetTexture((**surfchain).lightmaptexture);
1143         GL_Color(1, 1, 1, 1);
1144         while((surf = *surfchain++) != NULL)
1145         {
1146                 if (surf->visframe == r_framecount)
1147                 {
1148                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1149                         m.tex[0] = lightmaptexturenum;
1150                         m.pointer_vertex = surf->mesh.data_vertex3f;
1151                         m.pointer_texcoord[0] = surf->mesh.data_texcoordlightmap2f;
1152                         R_Mesh_State(&m);
1153                         GL_LockArrays(0, surf->mesh.num_vertices);
1154                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1155                         GL_LockArrays(0, 0);
1156                 }
1157         }
1158 }
1159
1160 static void RSurfShader_OpaqueWall_Pass_Fog(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1161 {
1162         const msurface_t *surf;
1163         rmeshstate_t m;
1164         float modelorg[3];
1165         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
1166         memset(&m, 0, sizeof(m));
1167         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1168         GL_DepthMask(false);
1169         GL_DepthTest(true);
1170         m.pointer_color = varray_color4f;
1171         while((surf = *surfchain++) != NULL)
1172         {
1173                 if (surf->visframe == r_framecount)
1174                 {
1175                         m.pointer_vertex = surf->mesh.data_vertex3f;
1176                         if (m.tex[0])
1177                                 m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
1178                         R_Mesh_State(&m);
1179                         RSurf_FogPassColors_Vertex3f_Color4f(surf->mesh.data_vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], 1, 1, surf->mesh.num_vertices, modelorg);
1180                         GL_LockArrays(0, surf->mesh.num_vertices);
1181                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1182                         GL_LockArrays(0, 0);
1183                 }
1184         }
1185 }
1186
1187 static void RSurfShader_OpaqueWall_Pass_BaseDetail(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1188 {
1189         const msurface_t *surf;
1190         rmeshstate_t m;
1191         memset(&m, 0, sizeof(m));
1192         GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
1193         GL_DepthMask(false);
1194         GL_DepthTest(true);
1195         m.tex[0] = R_GetTexture(texture->skin.detail);
1196         GL_Color(1, 1, 1, 1);
1197         while((surf = *surfchain++) != NULL)
1198         {
1199                 if (surf->visframe == r_framecount)
1200                 {
1201                         m.pointer_vertex = surf->mesh.data_vertex3f;
1202                         m.pointer_texcoord[0] = surf->mesh.data_texcoorddetail2f;
1203                         R_Mesh_State(&m);
1204                         GL_LockArrays(0, surf->mesh.num_vertices);
1205                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1206                         GL_LockArrays(0, 0);
1207                 }
1208         }
1209 }
1210
1211 static void RSurfShader_OpaqueWall_Pass_Glow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1212 {
1213         const msurface_t *surf;
1214         rmeshstate_t m;
1215         memset(&m, 0, sizeof(m));
1216         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1217         GL_DepthMask(false);
1218         GL_DepthTest(true);
1219         m.tex[0] = R_GetTexture(texture->skin.glow);
1220         GL_Color(1, 1, 1, 1);
1221         while((surf = *surfchain++) != NULL)
1222         {
1223                 if (surf->visframe == r_framecount)
1224                 {
1225                         m.pointer_vertex = surf->mesh.data_vertex3f;
1226                         m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
1227                         R_Mesh_State(&m);
1228                         GL_LockArrays(0, surf->mesh.num_vertices);
1229                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1230                         GL_LockArrays(0, 0);
1231                 }
1232         }
1233 }
1234
1235 /*
1236 static void RSurfShader_OpaqueWall_Pass_OpaqueGlow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1237 {
1238         const msurface_t *surf;
1239         rmeshstate_t m;
1240         memset(&m, 0, sizeof(m));
1241         GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1242         GL_DepthMask(true);
1243         m.tex[0] = R_GetTexture(texture->skin.glow);
1244         if (m.tex[0])
1245                 GL_Color(1, 1, 1, 1);
1246         else
1247                 GL_Color(0, 0, 0, 1);
1248         while((surf = *surfchain++) != NULL)
1249         {
1250                 if (surf->visframe == r_framecount)
1251                 {
1252                         m.pointer_vertex = surf->mesh.data_vertex3f;
1253                         m.pointer_texcoord[0] = surf->mesh.data_texcoordtexture2f;
1254                         R_Mesh_State(&m);
1255                         GL_LockArrays(0, surf->mesh.num_vertices);
1256                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1257                         GL_LockArrays(0, 0);
1258                 }
1259         }
1260 }
1261 */
1262
1263 static void RSurfShader_OpaqueWall_Pass_BaseLightmapOnly(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1264 {
1265         const msurface_t *surf;
1266         rmeshstate_t m;
1267         int lightmaptexturenum;
1268         memset(&m, 0, sizeof(m));
1269         GL_BlendFunc(GL_ONE, GL_ZERO);
1270         GL_DepthMask(true);
1271         GL_DepthTest(true);
1272         m.tex[0] = R_GetTexture((**surfchain).lightmaptexture);
1273         if (r_shadow_realtime_world.integer)
1274                 GL_Color(r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, 1);
1275         else
1276                 GL_Color(1, 1, 1, 1);
1277         while((surf = *surfchain++) != NULL)
1278         {
1279                 if (surf->visframe == r_framecount)
1280                 {
1281                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1282                         m.tex[0] = lightmaptexturenum;
1283                         m.pointer_vertex = surf->mesh.data_vertex3f;
1284                         m.pointer_texcoord[0] = surf->mesh.data_texcoordlightmap2f;
1285                         R_Mesh_State(&m);
1286                         GL_LockArrays(0, surf->mesh.num_vertices);
1287                         R_Mesh_Draw(surf->mesh.num_vertices, surf->mesh.num_triangles, surf->mesh.data_element3i);
1288                         GL_LockArrays(0, 0);
1289                 }
1290         }
1291 }
1292
1293 static void RSurfShader_Wall_Vertex_Callback(const void *calldata1, int calldata2)
1294 {
1295         const entity_render_t *ent = calldata1;
1296         const msurface_t *surf = ent->model->brushq1.surfaces + calldata2;
1297         int rendertype;
1298         float currentalpha;
1299         texture_t *texture;
1300         R_Mesh_Matrix(&ent->matrix);
1301
1302         texture = surf->texinfo->texture;
1303         if (texture->animated)
1304                 texture = texture->anim_frames[ent->frame != 0][(texture->anim_total[ent->frame != 0] >= 2) ? ((int) (cl.time * 5.0f) % texture->anim_total[ent->frame != 0]) : 0];
1305
1306         currentalpha = ent->alpha;
1307         if (ent->effects & EF_ADDITIVE)
1308                 rendertype = SURFRENDER_ADD;
1309         else if (currentalpha < 1 || texture->skin.fog != NULL)
1310                 rendertype = SURFRENDER_ALPHA;
1311         else
1312                 rendertype = SURFRENDER_OPAQUE;
1313
1314         RSurfShader_Wall_Pass_BaseVertex(ent, surf, texture, rendertype, currentalpha);
1315         if (texture->skin.glow)
1316                 RSurfShader_Wall_Pass_Glow(ent, surf, texture, rendertype, currentalpha);
1317         if (fogenabled)
1318                 RSurfShader_Wall_Pass_Fog(ent, surf, texture, rendertype, currentalpha);
1319 }
1320
1321 static void RSurfShader_Wall_Lightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1322 {
1323         const msurface_t *surf;
1324         msurface_t **chain;
1325         vec3_t center;
1326         if (texture->rendertype != SURFRENDER_OPAQUE)
1327         {
1328                 // transparent vertex shaded from lightmap
1329                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
1330                 {
1331                         if (surf->visframe == r_framecount)
1332                         {
1333                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
1334                                 R_MeshQueue_AddTransparent(center, RSurfShader_Wall_Vertex_Callback, ent, surf - ent->model->brushq1.surfaces);
1335                         }
1336                 }
1337         }
1338         else if (ent->effects & EF_FULLBRIGHT)
1339         {
1340                 RSurfShader_OpaqueWall_Pass_BaseTexture(ent, texture, surfchain);
1341                 if (r_detailtextures.integer)
1342                         RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1343                 if (texture->skin.glow)
1344                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture, surfchain);
1345                 if (fogenabled)
1346                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1347         }
1348         /*
1349         // opaque base lighting
1350         else if (r_shadow_realtime_world.integer && r_shadow_realtime_world_lightmaps.value <= 0)
1351         {
1352                 if (r_ambient.value > 0)
1353                 {
1354                 }
1355                 else
1356                         RSurfShader_OpaqueWall_Pass_OpaqueGlow(ent, texture, surfchain);
1357                 if (fogenabled)
1358                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1359         }
1360         */
1361         // opaque lightmapped
1362         else if (r_textureunits.integer >= 4 && gl_combine.integer && r_detailtextures.integer && !gl_lightmaps.integer)
1363         {
1364                 RSurfShader_OpaqueWall_Pass_BaseCombine_TextureLightmapDetailGlow(ent, texture, surfchain);
1365                 if (fogenabled)
1366                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1367         }
1368         else if (r_textureunits.integer >= 3 && gl_combine.integer && r_detailtextures.integer && !gl_lightmaps.integer)
1369         {
1370                 RSurfShader_OpaqueWall_Pass_BaseCombine_TextureLightmapDetail(ent, texture, surfchain);
1371                 if (texture->skin.glow)
1372                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture, surfchain);
1373                 if (fogenabled)
1374                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1375         }
1376         else if (r_textureunits.integer >= 2 && gl_combine.integer && !gl_lightmaps.integer)
1377         {
1378                 RSurfShader_OpaqueWall_Pass_BaseCombine_TextureLightmap(ent, texture, surfchain);
1379                 if (r_detailtextures.integer)
1380                         RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1381                 if (texture->skin.glow)
1382                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture, surfchain);
1383                 if (fogenabled)
1384                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1385         }
1386         else if (!gl_lightmaps.integer)
1387         {
1388                 RSurfShader_OpaqueWall_Pass_BaseTexture(ent, texture, surfchain);
1389                 RSurfShader_OpaqueWall_Pass_BaseLightmap(ent, texture, surfchain);
1390                 if (r_detailtextures.integer)
1391                         RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1392                 if (texture->skin.glow)
1393                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture, surfchain);
1394                 if (fogenabled)
1395                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1396         }
1397         else
1398         {
1399                 RSurfShader_OpaqueWall_Pass_BaseLightmapOnly(ent, texture, surfchain);
1400                 if (fogenabled)
1401                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1402         }
1403 }
1404
1405 Cshader_t Cshader_wall_lightmap = {{NULL, RSurfShader_Wall_Lightmap}, SHADERFLAGS_NEEDLIGHTMAP};
1406 Cshader_t Cshader_water = {{NULL, RSurfShader_Water}, 0};
1407 Cshader_t Cshader_sky = {{RSurfShader_Sky, NULL}, 0};
1408
1409 int Cshader_count = 3;
1410 Cshader_t *Cshaders[3] =
1411 {
1412         &Cshader_wall_lightmap,
1413         &Cshader_water,
1414         &Cshader_sky
1415 };
1416
1417 void R_UpdateTextureInfo(entity_render_t *ent)
1418 {
1419         int i, texframe, alttextures;
1420         texture_t *t;
1421
1422         if (!ent->model)
1423                 return;
1424
1425         alttextures = ent->frame != 0;
1426         texframe = (int)(cl.time * 5.0f);
1427         for (i = 0;i < ent->model->brushq1.numtextures;i++)
1428         {
1429                 t = ent->model->brushq1.textures + i;
1430                 t->currentalpha = ent->alpha;
1431                 if (t->flags & SURF_WATERALPHA)
1432                         t->currentalpha *= r_wateralpha.value;
1433                 if (ent->effects & EF_ADDITIVE)
1434                         t->rendertype = SURFRENDER_ADD;
1435                 else if (t->currentalpha < 1 || t->skin.fog != NULL)
1436                         t->rendertype = SURFRENDER_ALPHA;
1437                 else
1438                         t->rendertype = SURFRENDER_OPAQUE;
1439                 // we don't need to set currentframe if t->animated is false because
1440                 // it was already set up by the texture loader for non-animating
1441                 if (t->animated)
1442                         t->currentframe = t->anim_frames[alttextures][(t->anim_total[alttextures] >= 2) ? (texframe % t->anim_total[alttextures]) : 0];
1443         }
1444 }
1445
1446 void R_PrepareSurfaces(entity_render_t *ent)
1447 {
1448         int i, numsurfaces, *surfacevisframes;
1449         model_t *model;
1450         msurface_t *surf, *surfaces, **surfchain;
1451         vec3_t modelorg;
1452
1453         if (!ent->model)
1454                 return;
1455
1456         model = ent->model;
1457         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
1458         numsurfaces = model->brushq1.nummodelsurfaces;
1459         surfaces = model->brushq1.surfaces + model->brushq1.firstmodelsurface;
1460         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1461
1462         R_UpdateTextureInfo(ent);
1463
1464         if (r_dynamic.integer && !r_shadow_realtime_dlight.integer)
1465                 R_MarkLights(ent);
1466
1467         if (model->brushq1.light_ambient != r_ambient.value)
1468         {
1469                 model->brushq1.light_ambient = r_ambient.value;
1470                 for (i = 0;i < model->brushq1.nummodelsurfaces;i++)
1471                         model->brushq1.surfaces[i + model->brushq1.firstmodelsurface].cached_dlight = true;
1472         }
1473         else
1474         {
1475                 for (i = 0;i < model->brushq1.light_styles;i++)
1476                 {
1477                         if (model->brushq1.light_stylevalue[i] != d_lightstylevalue[model->brushq1.light_style[i]])
1478                         {
1479                                 model->brushq1.light_stylevalue[i] = d_lightstylevalue[model->brushq1.light_style[i]];
1480                                 for (surfchain = model->brushq1.light_styleupdatechains[i];*surfchain;surfchain++)
1481                                         (**surfchain).cached_dlight = true;
1482                         }
1483                 }
1484         }
1485
1486         for (i = 0, surf = surfaces;i < numsurfaces;i++, surf++)
1487         {
1488                 if (surfacevisframes[i] == r_framecount)
1489                 {
1490 #if !WORLDNODECULLBACKFACES
1491                         // mark any backface surfaces as not visible
1492                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1493                         {
1494                                 if (!(surf->flags & SURF_PLANEBACK))
1495                                         surfacevisframes[i] = -1;
1496                         }
1497                         else
1498                         {
1499                                 if ((surf->flags & SURF_PLANEBACK))
1500                                         surfacevisframes[i] = -1;
1501                         }
1502                         if (surfacevisframes[i] == r_framecount)
1503 #endif
1504                         {
1505                                 c_faces++;
1506                                 surf->visframe = r_framecount;
1507                                 if (surf->cached_dlight && surf->lightmaptexture != NULL)
1508                                         R_BuildLightMap(ent, surf);
1509                         }
1510                 }
1511         }
1512 }
1513
1514 void R_DrawSurfaces(entity_render_t *ent, int type, msurface_t ***chains)
1515 {
1516         int i;
1517         texture_t *t;
1518         if (ent->model == NULL)
1519                 return;
1520         R_Mesh_Matrix(&ent->matrix);
1521         for (i = 0, t = ent->model->brushq1.textures;i < ent->model->brushq1.numtextures;i++, t++)
1522                 if (t->shader->shaderfunc[type] && t->currentframe && chains[i] != NULL)
1523                         t->shader->shaderfunc[type](ent, t->currentframe, chains[i]);
1524 }
1525
1526 static void R_DrawPortal_Callback(const void *calldata1, int calldata2)
1527 {
1528         int i;
1529         float *v;
1530         rmeshstate_t m;
1531         const entity_render_t *ent = calldata1;
1532         const mportal_t *portal = ent->model->brushq1.portals + calldata2;
1533         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1534         GL_DepthMask(false);
1535         GL_DepthTest(true);
1536         R_Mesh_Matrix(&ent->matrix);
1537
1538         memset(&m, 0, sizeof(m));
1539         m.pointer_vertex = varray_vertex3f;
1540         R_Mesh_State(&m);
1541
1542         i = portal - ent->model->brushq1.portals;
1543         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f),
1544                          ((i & 0x0038) >> 3) * (1.0f / 7.0f),
1545                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f),
1546                          0.125f);
1547         if (PlaneDiff(r_vieworigin, (&portal->plane)) < 0)
1548         {
1549                 for (i = portal->numpoints - 1, v = varray_vertex3f;i >= 0;i--, v += 3)
1550                         VectorCopy(portal->points[i].position, v);
1551         }
1552         else
1553                 for (i = 0, v = varray_vertex3f;i < portal->numpoints;i++, v += 3)
1554                         VectorCopy(portal->points[i].position, v);
1555         GL_LockArrays(0, portal->numpoints);
1556         R_Mesh_Draw(portal->numpoints, portal->numpoints - 2, polygonelements);
1557         GL_LockArrays(0, 0);
1558 }
1559
1560 // LordHavoc: this is just a nice debugging tool, very slow
1561 static void R_DrawPortals(entity_render_t *ent)
1562 {
1563         int i;
1564         mportal_t *portal, *endportal;
1565         float temp[3], center[3], f;
1566         if (ent->model == NULL)
1567                 return;
1568         for (portal = ent->model->brushq1.portals, endportal = portal + ent->model->brushq1.numportals;portal < endportal;portal++)
1569         {
1570                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
1571                 {
1572                         VectorClear(temp);
1573                         for (i = 0;i < portal->numpoints;i++)
1574                                 VectorAdd(temp, portal->points[i].position, temp);
1575                         f = ixtable[portal->numpoints];
1576                         VectorScale(temp, f, temp);
1577                         Matrix4x4_Transform(&ent->matrix, temp, center);
1578                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, ent, portal - ent->model->brushq1.portals);
1579                 }
1580         }
1581 }
1582
1583 void R_PrepareBrushModel(entity_render_t *ent)
1584 {
1585         int i, numsurfaces, *surfacevisframes, *surfacepvsframes;
1586         msurface_t *surf;
1587         model_t *model;
1588 #if WORLDNODECULLBACKFACES
1589         vec3_t modelorg;
1590 #endif
1591
1592         // because bmodels can be reused, we have to decide which things to render
1593         // from scratch every time
1594         model = ent->model;
1595         if (model == NULL)
1596                 return;
1597 #if WORLDNODECULLBACKFACES
1598         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
1599 #endif
1600         numsurfaces = model->brushq1.nummodelsurfaces;
1601         surf = model->brushq1.surfaces + model->brushq1.firstmodelsurface;
1602         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1603         surfacepvsframes = model->brushq1.surfacepvsframes + model->brushq1.firstmodelsurface;
1604         for (i = 0;i < numsurfaces;i++, surf++)
1605         {
1606 #if WORLDNODECULLBACKFACES
1607                 // mark any backface surfaces as not visible
1608                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1609                 {
1610                         if ((surf->flags & SURF_PLANEBACK))
1611                                 surfacevisframes[i] = r_framecount;
1612                 }
1613                 else if (!(surf->flags & SURF_PLANEBACK))
1614                         surfacevisframes[i] = r_framecount;
1615 #else
1616                 surfacevisframes[i] = r_framecount;
1617 #endif
1618                 surf->dlightframe = -1;
1619         }
1620         R_PrepareSurfaces(ent);
1621 }
1622
1623 void R_SurfaceWorldNode (entity_render_t *ent)
1624 {
1625         int i, *surfacevisframes, *surfacepvsframes, surfnum;
1626         msurface_t *surf;
1627         mleaf_t *leaf;
1628         model_t *model;
1629         vec3_t modelorg;
1630
1631         // equivilant to quake's RecursiveWorldNode but faster and more effective
1632         model = ent->model;
1633         if (model == NULL)
1634                 return;
1635         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1636         surfacepvsframes = model->brushq1.surfacepvsframes + model->brushq1.firstmodelsurface;
1637         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
1638
1639         for (leaf = model->brushq1.pvsleafchain;leaf;leaf = leaf->pvschain)
1640         {
1641                 if (!R_CullBox (leaf->mins, leaf->maxs))
1642                 {
1643                         c_leafs++;
1644                         leaf->visframe = r_framecount;
1645                 }
1646         }
1647
1648         for (i = 0;i < model->brushq1.pvssurflistlength;i++)
1649         {
1650                 surfnum = model->brushq1.pvssurflist[i];
1651                 surf = model->brushq1.surfaces + surfnum;
1652 #if WORLDNODECULLBACKFACES
1653                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1654                 {
1655                         if ((surf->flags & SURF_PLANEBACK) && !R_CullBox (surf->poly_mins, surf->poly_maxs))
1656                                 surfacevisframes[surfnum] = r_framecount;
1657                 }
1658                 else
1659                 {
1660                         if (!(surf->flags & SURF_PLANEBACK) && !R_CullBox (surf->poly_mins, surf->poly_maxs))
1661                                 surfacevisframes[surfnum] = r_framecount;
1662                 }
1663 #else
1664                 if (!R_CullBox (surf->poly_mins, surf->poly_maxs))
1665                         surfacevisframes[surfnum] = r_framecount;
1666 #endif
1667         }
1668 }
1669
1670 static void R_PortalWorldNode(entity_render_t *ent, mleaf_t *viewleaf)
1671 {
1672         int c, leafstackpos, *mark, *surfacevisframes;
1673 #if WORLDNODECULLBACKFACES
1674         int n;
1675         msurface_t *surf;
1676 #endif
1677         mleaf_t *leaf, *leafstack[8192];
1678         mportal_t *p;
1679         vec3_t modelorg;
1680         msurface_t *surfaces;
1681         if (ent->model == NULL)
1682                 return;
1683         // LordHavoc: portal-passage worldnode with PVS;
1684         // follows portals leading outward from viewleaf, does not venture
1685         // offscreen or into leafs that are not visible, faster than Quake's
1686         // RecursiveWorldNode
1687         surfaces = ent->model->brushq1.surfaces;
1688         surfacevisframes = ent->model->brushq1.surfacevisframes;
1689         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
1690         viewleaf->worldnodeframe = r_framecount;
1691         leafstack[0] = viewleaf;
1692         leafstackpos = 1;
1693         while (leafstackpos)
1694         {
1695                 c_leafs++;
1696                 leaf = leafstack[--leafstackpos];
1697                 leaf->visframe = r_framecount;
1698                 // draw any surfaces bounding this leaf
1699                 if (leaf->nummarksurfaces)
1700                 {
1701                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1702                         {
1703 #if WORLDNODECULLBACKFACES
1704                                 n = *mark++;
1705                                 if (surfacevisframes[n] != r_framecount)
1706                                 {
1707                                         surf = surfaces + n;
1708                                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1709                                         {
1710                                                 if ((surf->flags & SURF_PLANEBACK))
1711                                                         surfacevisframes[n] = r_framecount;
1712                                         }
1713                                         else
1714                                         {
1715                                                 if (!(surf->flags & SURF_PLANEBACK))
1716                                                         surfacevisframes[n] = r_framecount;
1717                                         }
1718                                 }
1719 #else
1720                                 surfacevisframes[*mark++] = r_framecount;
1721 #endif
1722                         }
1723                 }
1724                 // follow portals into other leafs
1725                 for (p = leaf->portals;p;p = p->next)
1726                 {
1727                         // LordHavoc: this DotProduct hurts less than a cache miss
1728                         // (which is more likely to happen if backflowing through leafs)
1729                         if (DotProduct(modelorg, p->plane.normal) < (p->plane.dist + 1))
1730                         {
1731                                 leaf = p->past;
1732                                 if (leaf->worldnodeframe != r_framecount)
1733                                 {
1734                                         leaf->worldnodeframe = r_framecount;
1735                                         // FIXME: R_CullBox is absolute, should be done relative
1736                                         if (CHECKPVSBIT(r_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
1737                                                 leafstack[leafstackpos++] = leaf;
1738                                 }
1739                         }
1740                 }
1741         }
1742 }
1743
1744 void R_PVSUpdate (entity_render_t *ent, mleaf_t *viewleaf)
1745 {
1746         int j, c, *surfacepvsframes, *mark;
1747         mleaf_t *leaf;
1748         model_t *model;
1749
1750         model = ent->model;
1751         if (model && (model->brushq1.pvsviewleaf != viewleaf || model->brushq1.pvsviewleafnovis != r_novis.integer))
1752         {
1753                 model->brushq1.pvsframecount++;
1754                 model->brushq1.pvsviewleaf = viewleaf;
1755                 model->brushq1.pvsviewleafnovis = r_novis.integer;
1756                 model->brushq1.pvsleafchain = NULL;
1757                 model->brushq1.pvssurflistlength = 0;
1758                 if (viewleaf)
1759                 {
1760                         surfacepvsframes = model->brushq1.surfacepvsframes;
1761                         for (j = 0, leaf = model->brushq1.data_leafs;j < model->brushq1.num_leafs;j++, leaf++)
1762                         {
1763                                 if (CHECKPVSBIT(r_pvsbits, leaf->clusterindex))
1764                                 {
1765                                         leaf->pvsframe = model->brushq1.pvsframecount;
1766                                         leaf->pvschain = model->brushq1.pvsleafchain;
1767                                         model->brushq1.pvsleafchain = leaf;
1768                                         // mark surfaces bounding this leaf as visible
1769                                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--, mark++)
1770                                                 surfacepvsframes[*mark] = model->brushq1.pvsframecount;
1771                                 }
1772                         }
1773                         model->brushq1.BuildPVSTextureChains(model);
1774                 }
1775         }
1776 }
1777
1778 void R_WorldVisibility(entity_render_t *ent)
1779 {
1780         vec3_t modelorg;
1781         mleaf_t *viewleaf;
1782
1783         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
1784         viewleaf = (ent->model && ent->model->brushq1.PointInLeaf) ? ent->model->brushq1.PointInLeaf(ent->model, modelorg) : NULL;
1785         R_PVSUpdate(ent, viewleaf);
1786
1787         if (!viewleaf)
1788                 return;
1789
1790         if (r_surfaceworldnode.integer || viewleaf->contents == CONTENTS_SOLID)
1791                 R_SurfaceWorldNode (ent);
1792         else
1793                 R_PortalWorldNode (ent, viewleaf);
1794 }
1795
1796 void R_DrawWorld(entity_render_t *ent)
1797 {
1798         if (ent->model == NULL)
1799                 return;
1800         if (!ent->model->brushq1.num_leafs)
1801         {
1802                 if (ent->model->DrawSky)
1803                         ent->model->DrawSky(ent);
1804                 if (ent->model->Draw)
1805                         ent->model->Draw(ent);
1806         }
1807         else
1808         {
1809                 R_PrepareSurfaces(ent);
1810                 R_DrawSurfaces(ent, SHADERSTAGE_SKY, ent->model->brushq1.pvstexturechains);
1811                 R_DrawSurfaces(ent, SHADERSTAGE_NORMAL, ent->model->brushq1.pvstexturechains);
1812                 if (r_drawportals.integer)
1813                         R_DrawPortals(ent);
1814         }
1815 }
1816
1817 void R_Model_Brush_DrawSky(entity_render_t *ent)
1818 {
1819         if (ent->model == NULL)
1820                 return;
1821         if (ent != &cl_entities[0].render)
1822                 R_PrepareBrushModel(ent);
1823         R_DrawSurfaces(ent, SHADERSTAGE_SKY, ent->model->brushq1.pvstexturechains);
1824 }
1825
1826 void R_Model_Brush_Draw(entity_render_t *ent)
1827 {
1828         if (ent->model == NULL)
1829                 return;
1830         c_bmodels++;
1831         if (ent != &cl_entities[0].render)
1832                 R_PrepareBrushModel(ent);
1833         R_DrawSurfaces(ent, SHADERSTAGE_NORMAL, ent->model->brushq1.pvstexturechains);
1834 }
1835
1836 void R_Model_Brush_GetLightInfo(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, vec3_t outmins, vec3_t outmaxs, int *outclusterlist, qbyte *outclusterpvs, int *outnumclusterspointer, int *outsurfacelist, qbyte *outsurfacepvs, int *outnumsurfacespointer)
1837 {
1838         model_t *model = ent->model;
1839         vec3_t lightmins, lightmaxs;
1840         int t, leafindex, marksurfaceindex, surfaceindex, triangleindex, outnumclusters = 0, outnumsurfaces = 0;
1841         const int *e;
1842         const float *v[3];
1843         msurface_t *surface;
1844         mleaf_t *leaf;
1845         const qbyte *pvs;
1846         lightmins[0] = relativelightorigin[0] - lightradius;
1847         lightmins[1] = relativelightorigin[1] - lightradius;
1848         lightmins[2] = relativelightorigin[2] - lightradius;
1849         lightmaxs[0] = relativelightorigin[0] + lightradius;
1850         lightmaxs[1] = relativelightorigin[1] + lightradius;
1851         lightmaxs[2] = relativelightorigin[2] + lightradius;
1852         *outnumclusterspointer = 0;
1853         *outnumsurfacespointer = 0;
1854         memset(outclusterpvs, 0, model->brush.num_pvsclusterbytes);
1855         memset(outsurfacepvs, 0, (model->numsurfaces + 7) >> 3);
1856         if (model == NULL)
1857         {
1858                 VectorCopy(lightmins, outmins);
1859                 VectorCopy(lightmaxs, outmaxs);
1860                 return;
1861         }
1862         VectorCopy(relativelightorigin, outmins);
1863         VectorCopy(relativelightorigin, outmaxs);
1864         if (model->brush.GetPVS)
1865                 pvs = model->brush.GetPVS(model, relativelightorigin);
1866         else
1867                 pvs = NULL;
1868         // FIXME: use BSP recursion as lights are often small
1869         for (leafindex = 0, leaf = model->brushq1.data_leafs;leafindex < model->brushq1.num_leafs;leafindex++, leaf++)
1870         {
1871                 if (BoxesOverlap(lightmins, lightmaxs, leaf->mins, leaf->maxs) && (pvs == NULL || CHECKPVSBIT(pvs, leaf->clusterindex)))
1872                 {
1873                         outmins[0] = min(outmins[0], leaf->mins[0]);
1874                         outmins[1] = min(outmins[1], leaf->mins[1]);
1875                         outmins[2] = min(outmins[2], leaf->mins[2]);
1876                         outmaxs[0] = max(outmaxs[0], leaf->maxs[0]);
1877                         outmaxs[1] = max(outmaxs[1], leaf->maxs[1]);
1878                         outmaxs[2] = max(outmaxs[2], leaf->maxs[2]);
1879                         if (!CHECKPVSBIT(outclusterpvs, leaf->clusterindex))
1880                         {
1881                                 SETPVSBIT(outclusterpvs, leaf->clusterindex);
1882                                 outclusterlist[outnumclusters++] = leaf->clusterindex;
1883                         }
1884                         for (marksurfaceindex = 0;marksurfaceindex < leaf->nummarksurfaces;marksurfaceindex++)
1885                         {
1886                                 surfaceindex = leaf->firstmarksurface[marksurfaceindex];
1887                                 if (!CHECKPVSBIT(outsurfacepvs, surfaceindex))
1888                                 {
1889                                         surface = model->brushq1.surfaces + surfaceindex;
1890                                         if (BoxesOverlap(lightmins, lightmaxs, surface->poly_mins, surface->poly_maxs))
1891                                         {
1892                                                 for (triangleindex = 0, t = surface->num_firstshadowmeshtriangle, e = model->brush.shadowmesh->element3i + t * 3;triangleindex < surface->mesh.num_triangles;triangleindex++, t++, e += 3)
1893                                                 {
1894                                                         v[0] = model->brush.shadowmesh->vertex3f + e[0] * 3;
1895                                                         v[1] = model->brush.shadowmesh->vertex3f + e[1] * 3;
1896                                                         v[2] = model->brush.shadowmesh->vertex3f + e[2] * 3;
1897                                                         if (PointInfrontOfTriangle(relativelightorigin, v[0], v[1], v[2]) && lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0])) && lightmins[0] < max(v[0][0], max(v[1][0], v[2][0])) && lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1])) && lightmins[1] < max(v[0][1], max(v[1][1], v[2][1])) && lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2])) && lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
1898                                                         {
1899                                                                 SETPVSBIT(outsurfacepvs, surfaceindex);
1900                                                                 outsurfacelist[outnumsurfaces++] = surfaceindex;
1901                                                                 break;
1902                                                         }
1903                                                 }
1904                                         }
1905                                 }
1906                         }
1907                 }
1908         }
1909
1910         // limit combined leaf box to light boundaries
1911         outmins[0] = max(outmins[0], lightmins[0]);
1912         outmins[1] = max(outmins[1], lightmins[1]);
1913         outmins[2] = max(outmins[2], lightmins[2]);
1914         outmaxs[0] = min(outmaxs[0], lightmaxs[0]);
1915         outmaxs[1] = min(outmaxs[1], lightmaxs[1]);
1916         outmaxs[2] = min(outmaxs[2], lightmaxs[2]);
1917
1918         *outnumclusterspointer = outnumclusters;
1919         *outnumsurfacespointer = outnumsurfaces;
1920 }
1921
1922 void R_Model_Brush_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int numsurfaces, const int *surfacelist)
1923 {
1924         model_t *model = ent->model;
1925         vec3_t lightmins, lightmaxs;
1926         msurface_t *surface;
1927         int surfacelistindex, j, t;
1928         const int *e;
1929         const float *v[3];
1930         if (r_drawcollisionbrushes.integer < 2)
1931         {
1932                 lightmins[0] = relativelightorigin[0] - lightradius;
1933                 lightmins[1] = relativelightorigin[1] - lightradius;
1934                 lightmins[2] = relativelightorigin[2] - lightradius;
1935                 lightmaxs[0] = relativelightorigin[0] + lightradius;
1936                 lightmaxs[1] = relativelightorigin[1] + lightradius;
1937                 lightmaxs[2] = relativelightorigin[2] + lightradius;
1938                 R_Mesh_Matrix(&ent->matrix);
1939                 R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
1940                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1941                 {
1942                         surface = model->brushq1.surfaces + surfacelist[surfacelistindex];
1943                         for (j = 0, t = surface->num_firstshadowmeshtriangle, e = model->brush.shadowmesh->element3i + t * 3;j < surface->mesh.num_triangles;j++, t++, e += 3)
1944                         {
1945                                 v[0] = model->brush.shadowmesh->vertex3f + e[0] * 3;
1946                                 v[1] = model->brush.shadowmesh->vertex3f + e[1] * 3;
1947                                 v[2] = model->brush.shadowmesh->vertex3f + e[2] * 3;
1948                                 if (PointInfrontOfTriangle(relativelightorigin, v[0], v[1], v[2]) && lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0])) && lightmins[0] < max(v[0][0], max(v[1][0], v[2][0])) && lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1])) && lightmins[1] < max(v[0][1], max(v[1][1], v[2][1])) && lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2])) && lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
1949                                         shadowmarklist[numshadowmark++] = t;
1950                         }
1951                 }
1952                 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, numshadowmark, shadowmarklist);
1953         }
1954 }
1955
1956 void R_Model_Brush_DrawLight(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor, const matrix4x4_t *matrix_modeltolight, const matrix4x4_t *matrix_modeltoattenuationxyz, const matrix4x4_t *matrix_modeltoattenuationz, rtexture_t *lightcubemap, int numsurfaces, const int *surfacelist)
1957 {
1958         model_t *model = ent->model;
1959         vec3_t lightmins, lightmaxs, modelorg;
1960         msurface_t *surface;
1961         texture_t *t;
1962         int surfacelistindex;
1963         if (r_drawcollisionbrushes.integer < 2)
1964         {
1965                 lightmins[0] = relativelightorigin[0] - lightradius;
1966                 lightmins[1] = relativelightorigin[1] - lightradius;
1967                 lightmins[2] = relativelightorigin[2] - lightradius;
1968                 lightmaxs[0] = relativelightorigin[0] + lightradius;
1969                 lightmaxs[1] = relativelightorigin[1] + lightradius;
1970                 lightmaxs[2] = relativelightorigin[2] + lightradius;
1971                 R_Mesh_Matrix(&ent->matrix);
1972                 Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
1973                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1974                 {
1975                         surface = model->brushq1.surfaces + surfacelist[surfacelistindex];
1976                         if (r_shadow_compilingrtlight)
1977                         {
1978                                 // if compiling an rtlight, capture the mesh
1979                                 Mod_ShadowMesh_AddMesh(r_shadow_mempool, r_shadow_compilingrtlight->static_meshchain_light, surface->texinfo->texture->skin.base, surface->texinfo->texture->skin.gloss, surface->texinfo->texture->skin.nmap, surface->mesh.data_vertex3f, surface->mesh.data_svector3f, surface->mesh.data_tvector3f, surface->mesh.data_normal3f, surface->mesh.data_texcoordtexture2f, surface->mesh.num_triangles, surface->mesh.data_element3i);
1980                         }
1981                         else if (ent != &cl_entities[0].render || surface->visframe == r_framecount)
1982                         {
1983                                 t = surface->texinfo->texture->currentframe;
1984                                 if (t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1985                                                 R_Shadow_RenderLighting(surface->mesh.num_vertices, surface->mesh.num_triangles, surface->mesh.data_element3i, surface->mesh.data_vertex3f, surface->mesh.data_svector3f, surface->mesh.data_tvector3f, surface->mesh.data_normal3f, surface->mesh.data_texcoordtexture2f, relativelightorigin, relativeeyeorigin, lightcolor, matrix_modeltolight, matrix_modeltoattenuationxyz, matrix_modeltoattenuationz, t->skin.base, t->skin.nmap, t->skin.gloss, lightcubemap, LIGHTING_DIFFUSE | LIGHTING_SPECULAR);
1986                         }
1987                 }
1988         }
1989 }
1990
1991 void R_DrawCollisionBrush(colbrushf_t *brush)
1992 {
1993         int i;
1994         rmeshstate_t m;
1995         memset(&m, 0, sizeof(m));
1996         m.pointer_vertex = brush->points->v;
1997         R_Mesh_State(&m);
1998         i = ((int)brush) / sizeof(colbrushf_t);
1999         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
2000         GL_LockArrays(0, brush->numpoints);
2001         R_Mesh_Draw(brush->numpoints, brush->numtriangles, brush->elements);
2002         GL_LockArrays(0, 0);
2003 }
2004
2005 void R_Q3BSP_DrawCollisionFace(entity_render_t *ent, q3mface_t *face)
2006 {
2007         int i;
2008         rmeshstate_t m;
2009         if (!face->num_collisiontriangles)
2010                 return;
2011         memset(&m, 0, sizeof(m));
2012         m.pointer_vertex = face->data_collisionvertex3f;
2013         R_Mesh_State(&m);
2014         i = ((int)face) / sizeof(q3mface_t);
2015         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
2016         GL_LockArrays(0, face->num_collisionvertices);
2017         R_Mesh_Draw(face->num_collisionvertices, face->num_collisiontriangles, face->data_collisionelement3i);
2018         GL_LockArrays(0, 0);
2019 }
2020
2021 void R_Q3BSP_DrawSkyFace(entity_render_t *ent, q3mface_t *face)
2022 {
2023         rmeshstate_t m;
2024         if (!face->num_triangles)
2025                 return;
2026         c_faces++;
2027         if (skyrendernow)
2028         {
2029                 skyrendernow = false;
2030                 if (skyrendermasked)
2031                         R_Sky();
2032         }
2033
2034         R_Mesh_Matrix(&ent->matrix);
2035
2036         GL_Color(fogcolor[0], fogcolor[1], fogcolor[2], 1);
2037         if (skyrendermasked)
2038         {
2039                 // depth-only (masking)
2040                 GL_ColorMask(0,0,0,0);
2041                 // just to make sure that braindead drivers don't draw anything
2042                 // despite that colormask...
2043                 GL_BlendFunc(GL_ZERO, GL_ONE);
2044         }
2045         else
2046         {
2047                 // fog sky
2048                 GL_BlendFunc(GL_ONE, GL_ZERO);
2049         }
2050         GL_DepthMask(true);
2051         GL_DepthTest(true);
2052
2053         memset(&m, 0, sizeof(m));
2054         m.pointer_vertex = face->data_vertex3f;
2055         R_Mesh_State(&m);
2056
2057         GL_LockArrays(0, face->num_vertices);
2058         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2059         GL_LockArrays(0, 0);
2060         GL_ColorMask(1,1,1,1);
2061 }
2062
2063 void R_Q3BSP_DrawFace_OpaqueWall_Pass_OpaqueGlow(entity_render_t *ent, q3mface_t *face)
2064 {
2065         rmeshstate_t m;
2066         memset(&m, 0, sizeof(m));
2067         GL_BlendFunc(GL_ONE, GL_ZERO);
2068         GL_DepthMask(true);
2069         GL_DepthTest(true);
2070         if (face->texture->skin.glow)
2071         {
2072                 m.tex[0] = R_GetTexture(face->texture->skin.glow);
2073                 m.pointer_texcoord[0] = face->data_texcoordtexture2f;
2074                 GL_Color(1, 1, 1, 1);
2075         }
2076         else
2077                 GL_Color(0, 0, 0, 1);
2078         m.pointer_vertex = face->data_vertex3f;
2079         R_Mesh_State(&m);
2080         GL_LockArrays(0, face->num_vertices);
2081         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2082         GL_LockArrays(0, 0);
2083 }
2084
2085 void R_Q3BSP_DrawFace_OpaqueWall_Pass_TextureLightmapCombine(entity_render_t *ent, q3mface_t *face)
2086 {
2087         rmeshstate_t m;
2088         memset(&m, 0, sizeof(m));
2089         GL_BlendFunc(GL_ONE, GL_ZERO);
2090         GL_DepthMask(true);
2091         GL_DepthTest(true);
2092         m.tex[0] = R_GetTexture(face->texture->skin.base);
2093         m.pointer_texcoord[0] = face->data_texcoordtexture2f;
2094         m.tex[1] = R_GetTexture(face->lightmaptexture);
2095         m.pointer_texcoord[1] = face->data_texcoordlightmap2f;
2096         m.texrgbscale[1] = 2;
2097         GL_Color(1, 1, 1, 1);
2098         m.pointer_vertex = face->data_vertex3f;
2099         R_Mesh_State(&m);
2100         GL_LockArrays(0, face->num_vertices);
2101         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2102         GL_LockArrays(0, 0);
2103 }
2104
2105 void R_Q3BSP_DrawFace_OpaqueWall_Pass_Texture(entity_render_t *ent, q3mface_t *face)
2106 {
2107         rmeshstate_t m;
2108         memset(&m, 0, sizeof(m));
2109         GL_BlendFunc(GL_ONE, GL_ZERO);
2110         GL_DepthMask(true);
2111         GL_DepthTest(true);
2112         m.tex[0] = R_GetTexture(face->texture->skin.base);
2113         m.pointer_texcoord[0] = face->data_texcoordtexture2f;
2114         GL_Color(1, 1, 1, 1);
2115         m.pointer_vertex = face->data_vertex3f;
2116         R_Mesh_State(&m);
2117         GL_LockArrays(0, face->num_vertices);
2118         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2119         GL_LockArrays(0, 0);
2120 }
2121
2122 void R_Q3BSP_DrawFace_OpaqueWall_Pass_Lightmap(entity_render_t *ent, q3mface_t *face)
2123 {
2124         rmeshstate_t m;
2125         memset(&m, 0, sizeof(m));
2126         GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
2127         GL_DepthMask(false);
2128         GL_DepthTest(true);
2129         m.tex[0] = R_GetTexture(face->lightmaptexture);
2130         m.pointer_texcoord[0] = face->data_texcoordlightmap2f;
2131         GL_Color(1, 1, 1, 1);
2132         m.pointer_vertex = face->data_vertex3f;
2133         R_Mesh_State(&m);
2134         GL_LockArrays(0, face->num_vertices);
2135         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2136         GL_LockArrays(0, 0);
2137 }
2138
2139 void R_Q3BSP_DrawFace_OpaqueWall_Pass_LightmapOnly(entity_render_t *ent, q3mface_t *face)
2140 {
2141         rmeshstate_t m;
2142         memset(&m, 0, sizeof(m));
2143         GL_BlendFunc(GL_ONE, GL_ZERO);
2144         GL_DepthMask(true);
2145         GL_DepthTest(true);
2146         m.tex[0] = R_GetTexture(face->lightmaptexture);
2147         m.pointer_texcoord[0] = face->data_texcoordlightmap2f;
2148         if (r_shadow_realtime_world.integer)
2149                 GL_Color(r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, r_shadow_realtime_world_lightmaps.value, 1);
2150         else
2151                 GL_Color(1, 1, 1, 1);
2152         m.pointer_vertex = face->data_vertex3f;
2153         R_Mesh_State(&m);
2154         GL_LockArrays(0, face->num_vertices);
2155         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2156         GL_LockArrays(0, 0);
2157 }
2158
2159 void R_Q3BSP_DrawFace_OpaqueWall_Pass_Glow(entity_render_t *ent, q3mface_t *face)
2160 {
2161         rmeshstate_t m;
2162         memset(&m, 0, sizeof(m));
2163         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2164         GL_DepthMask(false);
2165         GL_DepthTest(true);
2166         if (face->texture->skin.glow)
2167         {
2168                 m.tex[0] = R_GetTexture(face->texture->skin.glow);
2169                 m.pointer_texcoord[0] = face->data_texcoordtexture2f;
2170                 GL_Color(1, 1, 1, 1);
2171         }
2172         else
2173                 GL_Color(0, 0, 0, 1);
2174         m.pointer_vertex = face->data_vertex3f;
2175         R_Mesh_State(&m);
2176         GL_LockArrays(0, face->num_vertices);
2177         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2178         GL_LockArrays(0, 0);
2179 }
2180
2181 void R_Q3BSP_DrawFace_OpaqueWall_Pass_TextureVertex(entity_render_t *ent, q3mface_t *face)
2182 {
2183         int i;
2184         float mul;
2185         rmeshstate_t m;
2186         memset(&m, 0, sizeof(m));
2187         GL_BlendFunc(GL_ONE, GL_ZERO);
2188         GL_DepthMask(true);
2189         GL_DepthTest(true);
2190         m.tex[0] = R_GetTexture(face->texture->skin.base);
2191         m.pointer_texcoord[0] = face->data_texcoordtexture2f;
2192         mul = 2.0f;
2193         if (r_shadow_realtime_world.integer && r_shadow_realtime_world_lightmaps.value != 1)
2194                 mul *= r_shadow_realtime_world_lightmaps.value;
2195         if (mul == 2 && gl_combine.integer)
2196         {
2197                 m.texrgbscale[0] = 2;
2198                 m.pointer_color = face->data_color4f;
2199         }
2200         else if (mul == 1)
2201                 m.pointer_color = face->data_color4f;
2202         else
2203         {
2204                 for (i = 0;i < face->num_vertices;i++)
2205                 {
2206                         varray_color4f[i*4+0] = face->data_color4f[i*4+0] * mul;
2207                         varray_color4f[i*4+1] = face->data_color4f[i*4+1] * mul;
2208                         varray_color4f[i*4+2] = face->data_color4f[i*4+2] * mul;
2209                         varray_color4f[i*4+3] = face->data_color4f[i*4+3];
2210                 }
2211                 m.pointer_color = varray_color4f;
2212         }
2213         m.pointer_vertex = face->data_vertex3f;
2214         R_Mesh_State(&m);
2215         GL_LockArrays(0, face->num_vertices);
2216         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2217         GL_LockArrays(0, 0);
2218 }
2219
2220 void R_Q3BSP_DrawFace_OpaqueWall_Pass_VertexOnly(entity_render_t *ent, q3mface_t *face)
2221 {
2222         int i;
2223         float mul;
2224         rmeshstate_t m;
2225         memset(&m, 0, sizeof(m));
2226         GL_BlendFunc(GL_ONE, GL_ZERO);
2227         GL_DepthMask(true);
2228         GL_DepthTest(true);
2229         mul = 2.0f;
2230         if (r_shadow_realtime_world.integer && r_shadow_realtime_world_lightmaps.value != 1)
2231                 mul *= r_shadow_realtime_world_lightmaps.value;
2232         if (mul == 1)
2233                 m.pointer_color = face->data_color4f;
2234         else
2235         {
2236                 for (i = 0;i < face->num_vertices;i++)
2237                 {
2238                         varray_color4f[i*4+0] = face->data_color4f[i*4+0] * 2.0f;
2239                         varray_color4f[i*4+1] = face->data_color4f[i*4+1] * 2.0f;
2240                         varray_color4f[i*4+2] = face->data_color4f[i*4+2] * 2.0f;
2241                         varray_color4f[i*4+3] = face->data_color4f[i*4+3];
2242                 }
2243                 m.pointer_color = varray_color4f;
2244         }
2245         m.pointer_vertex = face->data_vertex3f;
2246         R_Mesh_State(&m);
2247         GL_LockArrays(0, face->num_vertices);
2248         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2249         GL_LockArrays(0, 0);
2250 }
2251
2252 void R_Q3BSP_DrawFace_OpaqueWall_Pass_AddTextureAmbient(entity_render_t *ent, q3mface_t *face)
2253 {
2254         rmeshstate_t m;
2255         memset(&m, 0, sizeof(m));
2256         GL_BlendFunc(GL_ONE, GL_ONE);
2257         GL_DepthMask(true);
2258         GL_DepthTest(true);
2259         m.tex[0] = R_GetTexture(face->texture->skin.base);
2260         m.pointer_texcoord[0] = face->data_texcoordtexture2f;
2261         GL_Color(r_ambient.value * (1.0f / 128.0f), r_ambient.value * (1.0f / 128.0f), r_ambient.value * (1.0f / 128.0f), 1);
2262         m.pointer_vertex = face->data_vertex3f;
2263         R_Mesh_State(&m);
2264         GL_LockArrays(0, face->num_vertices);
2265         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2266         GL_LockArrays(0, 0);
2267 }
2268
2269 void R_Q3BSP_DrawFace_TransparentCallback(const void *voident, int facenumber)
2270 {
2271         const entity_render_t *ent = voident;
2272         q3mface_t *face = ent->model->brushq3.data_faces + facenumber;
2273         rmeshstate_t m;
2274         R_Mesh_Matrix(&ent->matrix);
2275         memset(&m, 0, sizeof(m));
2276         if (ent->effects & EF_ADDITIVE)
2277                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2278         else
2279                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2280         GL_DepthMask(false);
2281         GL_DepthTest(true);
2282         m.tex[0] = R_GetTexture(face->texture->skin.base);
2283         m.pointer_texcoord[0] = face->data_texcoordtexture2f;
2284         // LordHavoc: quake3 was not able to do this; lit transparent surfaces
2285         if (gl_combine.integer)
2286         {
2287                 m.texrgbscale[0] = 2;
2288                 if (r_textureunits.integer >= 2)
2289                 {
2290                         m.tex[1] = R_GetTexture(face->lightmaptexture);
2291                         m.pointer_texcoord[1] = face->data_texcoordlightmap2f;
2292                         GL_Color(1, 1, 1, ent->alpha);
2293                 }
2294                 else
2295                 {
2296                         if (ent->alpha == 1)
2297                                 m.pointer_color = face->data_color4f;
2298                         else
2299                         {
2300                                 int i;
2301                                 for (i = 0;i < face->num_vertices;i++)
2302                                 {
2303                                         varray_color4f[i*4+0] = face->data_color4f[i*4+0];
2304                                         varray_color4f[i*4+1] = face->data_color4f[i*4+1];
2305                                         varray_color4f[i*4+2] = face->data_color4f[i*4+2];
2306                                         varray_color4f[i*4+3] = face->data_color4f[i*4+3] * ent->alpha;
2307                                 }
2308                                 m.pointer_color = varray_color4f;
2309                         }
2310                 }
2311         }
2312         else
2313         {
2314                 int i;
2315                 for (i = 0;i < face->num_vertices;i++)
2316                 {
2317                         varray_color4f[i*4+0] = face->data_color4f[i*4+0] * 2.0f;
2318                         varray_color4f[i*4+1] = face->data_color4f[i*4+1] * 2.0f;
2319                         varray_color4f[i*4+2] = face->data_color4f[i*4+2] * 2.0f;
2320                         varray_color4f[i*4+3] = face->data_color4f[i*4+3] * ent->alpha;
2321                 }
2322                 m.pointer_color = varray_color4f;
2323         }
2324         m.pointer_vertex = face->data_vertex3f;
2325         R_Mesh_State(&m);
2326         qglDisable(GL_CULL_FACE);
2327         GL_LockArrays(0, face->num_vertices);
2328         R_Mesh_Draw(face->num_vertices, face->num_triangles, face->data_element3i);
2329         GL_LockArrays(0, 0);
2330         qglEnable(GL_CULL_FACE);
2331 }
2332
2333 void R_Q3BSP_DrawFace(entity_render_t *ent, q3mface_t *face)
2334 {
2335         if (!face->num_triangles)
2336                 return;
2337         if (face->texture->surfaceparms)
2338         {
2339                 if (face->texture->surfaceflags & (Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NODRAW))
2340                         return;
2341         }
2342         c_faces++;
2343         if ((face->texture->surfaceparms & Q3SURFACEPARM_TRANS) || ent->alpha < 1 || (ent->effects & EF_ADDITIVE))
2344         {
2345                 vec3_t facecenter, center;
2346                 facecenter[0] = (face->mins[0] + face->maxs[0]) * 0.5f;
2347                 facecenter[1] = (face->mins[1] + face->maxs[1]) * 0.5f;
2348                 facecenter[2] = (face->mins[2] + face->maxs[2]) * 0.5f;
2349                 Matrix4x4_Transform(&ent->matrix, facecenter, center);
2350                 R_MeshQueue_AddTransparent(center, R_Q3BSP_DrawFace_TransparentCallback, ent, face - ent->model->brushq3.data_faces);
2351                 return;
2352         }
2353         R_Mesh_Matrix(&ent->matrix);
2354         if (r_shadow_realtime_world.integer && r_shadow_realtime_world_lightmaps.value <= 0)
2355                 R_Q3BSP_DrawFace_OpaqueWall_Pass_OpaqueGlow(ent, face);
2356         else if ((ent->effects & EF_FULLBRIGHT) || r_fullbright.integer)
2357         {
2358                 R_Q3BSP_DrawFace_OpaqueWall_Pass_Texture(ent, face);
2359                 if (face->texture->skin.glow)
2360                         R_Q3BSP_DrawFace_OpaqueWall_Pass_Glow(ent, face);
2361         }
2362         else if (face->lightmaptexture)
2363         {
2364                 if (gl_lightmaps.integer)
2365                         R_Q3BSP_DrawFace_OpaqueWall_Pass_LightmapOnly(ent, face);
2366                 else
2367                 {
2368                         if (r_textureunits.integer >= 2 && gl_combine.integer)
2369                                 R_Q3BSP_DrawFace_OpaqueWall_Pass_TextureLightmapCombine(ent, face);
2370                         else
2371                         {
2372                                 R_Q3BSP_DrawFace_OpaqueWall_Pass_Texture(ent, face);
2373                                 R_Q3BSP_DrawFace_OpaqueWall_Pass_Lightmap(ent, face);
2374                         }
2375                         if (face->texture->skin.glow)
2376                                 R_Q3BSP_DrawFace_OpaqueWall_Pass_Glow(ent, face);
2377                 }
2378         }
2379         else
2380         {
2381                 if (gl_lightmaps.integer)
2382                         R_Q3BSP_DrawFace_OpaqueWall_Pass_VertexOnly(ent, face);
2383                 else
2384                 {
2385                         R_Q3BSP_DrawFace_OpaqueWall_Pass_TextureVertex(ent, face);
2386                         if (face->texture->skin.glow)
2387                                 R_Q3BSP_DrawFace_OpaqueWall_Pass_Glow(ent, face);
2388                 }
2389         }
2390         if (r_ambient.value)
2391                 R_Q3BSP_DrawFace_OpaqueWall_Pass_AddTextureAmbient(ent, face);
2392 }
2393
2394 void R_Q3BSP_RecursiveWorldNode(q3mnode_t *node)
2395 {
2396         int i;
2397         q3mleaf_t *leaf;
2398         for (;;)
2399         {
2400                 if (R_CullBox(node->mins, node->maxs))
2401                         return;
2402                 if (!node->plane)
2403                         break;
2404                 c_nodes++;
2405                 R_Q3BSP_RecursiveWorldNode(node->children[0]);
2406                 node = node->children[1];
2407         }
2408         leaf = (q3mleaf_t *)node;
2409         if (CHECKPVSBIT(r_pvsbits, leaf->clusterindex))
2410         {
2411                 c_leafs++;
2412                 for (i = 0;i < leaf->numleaffaces;i++)
2413                         leaf->firstleafface[i]->visframe = r_framecount;
2414         }
2415 }
2416
2417 // FIXME: num_leafs needs to be recalculated at load time to include only
2418 // node-referenced leafs, as some maps are incorrectly compiled with leafs for
2419 // the submodels (which would render the submodels occasionally, as part of
2420 // the world - not good)
2421 void R_Q3BSP_MarkLeafPVS(void)
2422 {
2423         int i, j;
2424         q3mleaf_t *leaf;
2425         for (j = 0, leaf = cl.worldmodel->brushq3.data_leafs;j < cl.worldmodel->brushq3.num_leafs;j++, leaf++)
2426         {
2427                 if (CHECKPVSBIT(r_pvsbits, leaf->clusterindex))
2428                 {
2429                         c_leafs++;
2430                         for (i = 0;i < leaf->numleaffaces;i++)
2431                                 leaf->firstleafface[i]->visframe = r_framecount;
2432                 }
2433         }
2434 }
2435
2436 static int r_q3bsp_framecount = -1;
2437
2438 void R_Q3BSP_DrawSky(entity_render_t *ent)
2439 {
2440         int i;
2441         q3mface_t *face;
2442         vec3_t modelorg;
2443         model_t *model;
2444         R_Mesh_Matrix(&ent->matrix);
2445         model = ent->model;
2446         if (r_drawcollisionbrushes.integer < 2)
2447         {
2448                 Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
2449                 if (ent == &cl_entities[0].render)
2450                 {
2451                         if (r_q3bsp_framecount != r_framecount)
2452                         {
2453                                 r_q3bsp_framecount = r_framecount;
2454                                 R_Q3BSP_RecursiveWorldNode(model->brushq3.data_nodes);
2455                                 //R_Q3BSP_MarkLeafPVS();
2456                         }
2457                         for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
2458                                 if (face->visframe == r_framecount && (face->texture->surfaceflags & Q3SURFACEFLAG_SKY) && !R_CullBox(face->mins, face->maxs))
2459                                         R_Q3BSP_DrawSkyFace(ent, face);
2460                 }
2461                 else
2462                         for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
2463                                 if ((face->texture->surfaceflags & Q3SURFACEFLAG_SKY))
2464                                         R_Q3BSP_DrawSkyFace(ent, face);
2465         }
2466 }
2467
2468 void R_Q3BSP_Draw(entity_render_t *ent)
2469 {
2470         int i;
2471         q3mface_t *face;
2472         vec3_t modelorg;
2473         model_t *model;
2474         qbyte *pvs;
2475         R_Mesh_Matrix(&ent->matrix);
2476         model = ent->model;
2477         if (r_drawcollisionbrushes.integer < 2)
2478         {
2479                 Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
2480                 if (ent == &cl_entities[0].render)
2481                 {
2482                         if (model->brush.num_pvsclusters && !r_novis.integer && (pvs = model->brush.GetPVS(model, modelorg)))
2483                         if (r_q3bsp_framecount != r_framecount)
2484                         {
2485                                 r_q3bsp_framecount = r_framecount;
2486                                 R_Q3BSP_RecursiveWorldNode(model->brushq3.data_nodes);
2487                                 //R_Q3BSP_MarkLeafPVS();
2488                         }
2489                         for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
2490                                 if (face->visframe == r_framecount && !R_CullBox(face->mins, face->maxs))
2491                                         R_Q3BSP_DrawFace(ent, face);
2492                 }
2493                 else
2494                         for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
2495                                 R_Q3BSP_DrawFace(ent, face);
2496         }
2497         if (r_drawcollisionbrushes.integer >= 1)
2498         {
2499                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2500                 GL_DepthMask(false);
2501                 GL_DepthTest(true);
2502                 qglPolygonOffset(r_drawcollisionbrushes_polygonfactor.value, r_drawcollisionbrushes_polygonoffset.value);
2503                 for (i = 0;i < model->brushq3.data_thismodel->numbrushes;i++)
2504                         if (model->brushq3.data_thismodel->firstbrush[i].colbrushf && model->brushq3.data_thismodel->firstbrush[i].colbrushf->numtriangles)
2505                                 R_DrawCollisionBrush(model->brushq3.data_thismodel->firstbrush[i].colbrushf);
2506                 for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
2507                         if (face->num_collisiontriangles)
2508                                 R_Q3BSP_DrawCollisionFace(ent, face);
2509                 qglPolygonOffset(0, 0);
2510         }
2511 }
2512
2513 void R_Q3BSP_GetLightInfo(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, vec3_t outmins, vec3_t outmaxs, int *outclusterlist, qbyte *outclusterpvs, int *outnumclusterspointer, int *outsurfacelist, qbyte *outsurfacepvs, int *outnumsurfacespointer)
2514 {
2515         model_t *model = ent->model;
2516         vec3_t lightmins, lightmaxs;
2517         int t, leafindex, marksurfaceindex, surfaceindex, triangleindex, outnumclusters = 0, outnumsurfaces = 0;
2518         const int *e;
2519         const float *v[3];
2520         q3mface_t *surface;
2521         q3mleaf_t *leaf;
2522         const qbyte *pvs;
2523         lightmins[0] = relativelightorigin[0] - lightradius;
2524         lightmins[1] = relativelightorigin[1] - lightradius;
2525         lightmins[2] = relativelightorigin[2] - lightradius;
2526         lightmaxs[0] = relativelightorigin[0] + lightradius;
2527         lightmaxs[1] = relativelightorigin[1] + lightradius;
2528         lightmaxs[2] = relativelightorigin[2] + lightradius;
2529         *outnumclusterspointer = 0;
2530         *outnumsurfacespointer = 0;
2531         memset(outclusterpvs, 0, model->brush.num_pvsclusterbytes);
2532         memset(outsurfacepvs, 0, (model->numsurfaces + 7) >> 3);
2533         if (model == NULL)
2534         {
2535                 VectorCopy(lightmins, outmins);
2536                 VectorCopy(lightmaxs, outmaxs);
2537                 return;
2538         }
2539         VectorCopy(relativelightorigin, outmins);
2540         VectorCopy(relativelightorigin, outmaxs);
2541         if (model->brush.GetPVS)
2542                 pvs = model->brush.GetPVS(model, relativelightorigin);
2543         else
2544                 pvs = NULL;
2545         // FIXME: use BSP recursion as lights are often small
2546         for (leafindex = 0, leaf = model->brushq3.data_leafs;leafindex < model->brushq3.num_leafs;leafindex++, leaf++)
2547         {
2548                 if (BoxesOverlap(lightmins, lightmaxs, leaf->mins, leaf->maxs) && (pvs == NULL || CHECKPVSBIT(pvs, leaf->clusterindex)))
2549                 {
2550                         outmins[0] = min(outmins[0], leaf->mins[0]);
2551                         outmins[1] = min(outmins[1], leaf->mins[1]);
2552                         outmins[2] = min(outmins[2], leaf->mins[2]);
2553                         outmaxs[0] = max(outmaxs[0], leaf->maxs[0]);
2554                         outmaxs[1] = max(outmaxs[1], leaf->maxs[1]);
2555                         outmaxs[2] = max(outmaxs[2], leaf->maxs[2]);
2556                         if (!CHECKPVSBIT(outclusterpvs, leaf->clusterindex))
2557                         {
2558                                 SETPVSBIT(outclusterpvs, leaf->clusterindex);
2559                                 outclusterlist[outnumclusters++] = leaf->clusterindex;
2560                         }
2561                         for (marksurfaceindex = 0;marksurfaceindex < leaf->numleaffaces;marksurfaceindex++)
2562                         {
2563                                 surface = leaf->firstleafface[marksurfaceindex];
2564                                 surfaceindex = surface - model->brushq3.data_faces;
2565                                 if (!CHECKPVSBIT(outsurfacepvs, surfaceindex))
2566                                 {
2567                                         if (BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
2568                                         {
2569                                                 for (triangleindex = 0, t = surface->num_firstshadowmeshtriangle, e = model->brush.shadowmesh->element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
2570                                                 {
2571                                                         v[0] = model->brush.shadowmesh->vertex3f + e[0] * 3;
2572                                                         v[1] = model->brush.shadowmesh->vertex3f + e[1] * 3;
2573                                                         v[2] = model->brush.shadowmesh->vertex3f + e[2] * 3;
2574                                                         if (PointInfrontOfTriangle(relativelightorigin, v[0], v[1], v[2]) && lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0])) && lightmins[0] < max(v[0][0], max(v[1][0], v[2][0])) && lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1])) && lightmins[1] < max(v[0][1], max(v[1][1], v[2][1])) && lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2])) && lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
2575                                                         {
2576                                                                 SETPVSBIT(outsurfacepvs, surfaceindex);
2577                                                                 outsurfacelist[outnumsurfaces++] = surfaceindex;
2578                                                                 break;
2579                                                         }
2580                                                 }
2581                                         }
2582                                 }
2583                         }
2584                 }
2585         }
2586
2587         // limit combined leaf box to light boundaries
2588         outmins[0] = max(outmins[0], lightmins[0]);
2589         outmins[1] = max(outmins[1], lightmins[1]);
2590         outmins[2] = max(outmins[2], lightmins[2]);
2591         outmaxs[0] = min(outmaxs[0], lightmaxs[0]);
2592         outmaxs[1] = min(outmaxs[1], lightmaxs[1]);
2593         outmaxs[2] = min(outmaxs[2], lightmaxs[2]);
2594
2595         *outnumclusterspointer = outnumclusters;
2596         *outnumsurfacespointer = outnumsurfaces;
2597 }
2598
2599 void R_Q3BSP_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int numsurfaces, const int *surfacelist)
2600 {
2601         model_t *model = ent->model;
2602         vec3_t lightmins, lightmaxs;
2603         q3mface_t *surface;
2604         int surfacelistindex, j, t;
2605         const int *e;
2606         const float *v[3];
2607         if (r_drawcollisionbrushes.integer < 2)
2608         {
2609                 lightmins[0] = relativelightorigin[0] - lightradius;
2610                 lightmins[1] = relativelightorigin[1] - lightradius;
2611                 lightmins[2] = relativelightorigin[2] - lightradius;
2612                 lightmaxs[0] = relativelightorigin[0] + lightradius;
2613                 lightmaxs[1] = relativelightorigin[1] + lightradius;
2614                 lightmaxs[2] = relativelightorigin[2] + lightradius;
2615                 R_Mesh_Matrix(&ent->matrix);
2616                 R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
2617                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
2618                 {
2619                         surface = model->brushq3.data_faces + surfacelist[surfacelistindex];
2620                         // FIXME: check some manner of face->rendermode here?
2621                         if (!(surface->texture->surfaceflags & Q3SURFACEFLAG_NODRAW) && surface->num_triangles && !surface->texture->skin.fog)
2622                         {
2623                                 for (j = 0, t = surface->num_firstshadowmeshtriangle, e = model->brush.shadowmesh->element3i + t * 3;j < surface->num_triangles;j++, t++, e += 3)
2624                                 {
2625                                         v[0] = model->brush.shadowmesh->vertex3f + e[0] * 3;
2626                                         v[1] = model->brush.shadowmesh->vertex3f + e[1] * 3;
2627                                         v[2] = model->brush.shadowmesh->vertex3f + e[2] * 3;
2628                                         if (PointInfrontOfTriangle(relativelightorigin, v[0], v[1], v[2]) && lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0])) && lightmins[0] < max(v[0][0], max(v[1][0], v[2][0])) && lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1])) && lightmins[1] < max(v[0][1], max(v[1][1], v[2][1])) && lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2])) && lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
2629                                                 shadowmarklist[numshadowmark++] = t;
2630                                 }
2631                         }
2632                 }
2633                 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, numshadowmark, shadowmarklist);
2634         }
2635 }
2636
2637 void R_Q3BSP_DrawLight(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor, const matrix4x4_t *matrix_modeltolight, const matrix4x4_t *matrix_modeltoattenuationxyz, const matrix4x4_t *matrix_modeltoattenuationz, rtexture_t *lightcubemap, int numsurfaces, const int *surfacelist)
2638 {
2639         model_t *model = ent->model;
2640         vec3_t lightmins, lightmaxs, modelorg;
2641         q3mface_t *surface;
2642         int surfacelistindex;
2643         if (r_drawcollisionbrushes.integer < 2)
2644         {
2645                 lightmins[0] = relativelightorigin[0] - lightradius;
2646                 lightmins[1] = relativelightorigin[1] - lightradius;
2647                 lightmins[2] = relativelightorigin[2] - lightradius;
2648                 lightmaxs[0] = relativelightorigin[0] + lightradius;
2649                 lightmaxs[1] = relativelightorigin[1] + lightradius;
2650                 lightmaxs[2] = relativelightorigin[2] + lightradius;
2651                 R_Mesh_Matrix(&ent->matrix);
2652                 Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
2653                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
2654                 {
2655                         surface = model->brushq3.data_faces + surfacelist[surfacelistindex];
2656                         if (r_shadow_compilingrtlight)
2657                         {
2658                                 // if compiling an rtlight, capture the mesh
2659                                 Mod_ShadowMesh_AddMesh(r_shadow_mempool, r_shadow_compilingrtlight->static_meshchain_light, surface->texture->skin.base, surface->texture->skin.gloss, surface->texture->skin.nmap, surface->data_vertex3f, surface->data_svector3f, surface->data_tvector3f, surface->data_normal3f, surface->data_texcoordtexture2f, surface->num_triangles, surface->data_element3i);
2660                         }
2661                         else if ((ent != &cl_entities[0].render || surface->visframe == r_framecount) && !(surface->texture->surfaceflags & Q3SURFACEFLAG_NODRAW) && surface->num_triangles)
2662                                 R_Shadow_RenderLighting(surface->num_vertices, surface->num_triangles, surface->data_element3i, surface->data_vertex3f, surface->data_svector3f, surface->data_tvector3f, surface->data_normal3f, surface->data_texcoordtexture2f, relativelightorigin, relativeeyeorigin, lightcolor, matrix_modeltolight, matrix_modeltoattenuationxyz, matrix_modeltoattenuationz, surface->texture->skin.base, surface->texture->skin.nmap, surface->texture->skin.gloss, lightcubemap, LIGHTING_DIFFUSE | LIGHTING_SPECULAR);
2663                 }
2664         }
2665 }
2666
2667 static void gl_surf_start(void)
2668 {
2669 }
2670
2671 static void gl_surf_shutdown(void)
2672 {
2673 }
2674
2675 static void gl_surf_newmap(void)
2676 {
2677 }
2678
2679 void GL_Surf_Init(void)
2680 {
2681         int i;
2682         dlightdivtable[0] = 4194304;
2683         for (i = 1;i < 32768;i++)
2684                 dlightdivtable[i] = 4194304 / (i << 7);
2685
2686         Cvar_RegisterVariable(&r_ambient);
2687         Cvar_RegisterVariable(&r_drawportals);
2688         Cvar_RegisterVariable(&r_testvis);
2689         Cvar_RegisterVariable(&r_floatbuildlightmap);
2690         Cvar_RegisterVariable(&r_detailtextures);
2691         Cvar_RegisterVariable(&r_surfaceworldnode);
2692         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonfactor);
2693         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonoffset);
2694         Cvar_RegisterVariable(&gl_lightmaps);
2695
2696         R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
2697 }
2698