fixed a crash with clusterindex -1 in GetPVS and FatPVS
[divverent/darkplaces.git] / gl_rsurf.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_surf.c: surface-related refresh code
21
22 #include "quakedef.h"
23 #include "r_shadow.h"
24
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_vertexsurfaces = {0, "r_vertexsurfaces", "0"};
34 cvar_t r_dlightmap = {CVAR_SAVE, "r_dlightmap", "1"};
35 cvar_t r_drawportals = {0, "r_drawportals", "0"};
36 cvar_t r_testvis = {0, "r_testvis", "0"};
37 cvar_t r_floatbuildlightmap = {0, "r_floatbuildlightmap", "0"};
38 cvar_t r_detailtextures = {CVAR_SAVE, "r_detailtextures", "1"};
39 cvar_t r_surfaceworldnode = {0, "r_surfaceworldnode", "1"};
40 cvar_t r_drawcollisionbrushes_polygonoffset = {0, "r_drawcollisionbrushes_polygonoffset", "-4"};
41
42 static int dlightdivtable[32768];
43
44 static int R_IntAddDynamicLights (const matrix4x4_t *matrix, msurface_t *surf)
45 {
46         int sdtable[256], lnum, td, maxdist, maxdist2, maxdist3, i, s, t, smax, tmax, smax3, red, green, blue, lit, dist2, impacts, impactt, subtract, k;
47         unsigned int *bl;
48         float dist, impact[3], local[3];
49
50         lit = false;
51
52         smax = (surf->extents[0] >> 4) + 1;
53         tmax = (surf->extents[1] >> 4) + 1;
54         smax3 = smax * 3;
55
56         for (lnum = 0; lnum < r_numdlights; lnum++)
57         {
58                 if (!(surf->dlightbits[lnum >> 5] & (1 << (lnum & 31))))
59                         continue;                                       // not lit by this light
60
61                 Matrix4x4_Transform(matrix, r_dlight[lnum].origin, local);
62                 dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
63
64                 // for comparisons to minimum acceptable light
65                 // compensate for LIGHTOFFSET
66                 maxdist = (int) r_dlight[lnum].cullradius2 + LIGHTOFFSET;
67
68                 dist2 = dist * dist;
69                 dist2 += LIGHTOFFSET;
70                 if (dist2 >= maxdist)
71                         continue;
72
73                 if (surf->plane->type < 3)
74                 {
75                         VectorCopy(local, impact);
76                         impact[surf->plane->type] -= dist;
77                 }
78                 else
79                 {
80                         impact[0] = local[0] - surf->plane->normal[0] * dist;
81                         impact[1] = local[1] - surf->plane->normal[1] * dist;
82                         impact[2] = local[2] - surf->plane->normal[2] * dist;
83                 }
84
85                 impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
86                 impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
87
88                 s = bound(0, impacts, smax * 16) - impacts;
89                 t = bound(0, impactt, tmax * 16) - impactt;
90                 i = s * s + t * t + dist2;
91                 if (i > maxdist)
92                         continue;
93
94                 // reduce calculations
95                 for (s = 0, i = impacts; s < smax; s++, i -= 16)
96                         sdtable[s] = i * i + dist2;
97
98                 maxdist3 = maxdist - dist2;
99
100                 // convert to 8.8 blocklights format
101                 red = r_dlight[lnum].light[0] * (1.0f / 128.0f);
102                 green = r_dlight[lnum].light[1] * (1.0f / 128.0f);
103                 blue = r_dlight[lnum].light[2] * (1.0f / 128.0f);
104                 subtract = (int) (r_dlight[lnum].subtract * 4194304.0f);
105                 bl = intblocklights;
106
107                 i = impactt;
108                 for (t = 0;t < tmax;t++, i -= 16)
109                 {
110                         td = i * i;
111                         // make sure some part of it is visible on this line
112                         if (td < maxdist3)
113                         {
114                                 maxdist2 = maxdist - td;
115                                 for (s = 0;s < smax;s++)
116                                 {
117                                         if (sdtable[s] < maxdist2)
118                                         {
119                                                 k = dlightdivtable[(sdtable[s] + td) >> 7] - subtract;
120                                                 if (k > 0)
121                                                 {
122                                                         bl[0] += (red   * k);
123                                                         bl[1] += (green * k);
124                                                         bl[2] += (blue  * k);
125                                                         lit = true;
126                                                 }
127                                         }
128                                         bl += 3;
129                                 }
130                         }
131                         else // skip line
132                                 bl += smax3;
133                 }
134         }
135         return lit;
136 }
137
138 static int R_FloatAddDynamicLights (const matrix4x4_t *matrix, msurface_t *surf)
139 {
140         int lnum, s, t, smax, tmax, smax3, lit, impacts, impactt;
141         float sdtable[256], *bl, k, dist, dist2, maxdist, maxdist2, maxdist3, td1, td, red, green, blue, impact[3], local[3], subtract;
142
143         lit = false;
144
145         smax = (surf->extents[0] >> 4) + 1;
146         tmax = (surf->extents[1] >> 4) + 1;
147         smax3 = smax * 3;
148
149         for (lnum = 0; lnum < r_numdlights; lnum++)
150         {
151                 if (!(surf->dlightbits[lnum >> 5] & (1 << (lnum & 31))))
152                         continue;                                       // not lit by this light
153
154                 Matrix4x4_Transform(matrix, r_dlight[lnum].origin, local);
155                 dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
156
157                 // for comparisons to minimum acceptable light
158                 // compensate for LIGHTOFFSET
159                 maxdist = (int) r_dlight[lnum].cullradius2 + LIGHTOFFSET;
160
161                 dist2 = dist * dist;
162                 dist2 += LIGHTOFFSET;
163                 if (dist2 >= maxdist)
164                         continue;
165
166                 if (surf->plane->type < 3)
167                 {
168                         VectorCopy(local, impact);
169                         impact[surf->plane->type] -= dist;
170                 }
171                 else
172                 {
173                         impact[0] = local[0] - surf->plane->normal[0] * dist;
174                         impact[1] = local[1] - surf->plane->normal[1] * dist;
175                         impact[2] = local[2] - surf->plane->normal[2] * dist;
176                 }
177
178                 impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
179                 impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
180
181                 td = bound(0, impacts, smax * 16) - impacts;
182                 td1 = bound(0, impactt, tmax * 16) - impactt;
183                 td = td * td + td1 * td1 + dist2;
184                 if (td > maxdist)
185                         continue;
186
187                 // reduce calculations
188                 for (s = 0, td1 = impacts; s < smax; s++, td1 -= 16.0f)
189                         sdtable[s] = td1 * td1 + dist2;
190
191                 maxdist3 = maxdist - dist2;
192
193                 // convert to 8.8 blocklights format
194                 red = r_dlight[lnum].light[0];
195                 green = r_dlight[lnum].light[1];
196                 blue = r_dlight[lnum].light[2];
197                 subtract = r_dlight[lnum].subtract * 32768.0f;
198                 bl = floatblocklights;
199
200                 td1 = impactt;
201                 for (t = 0;t < tmax;t++, td1 -= 16.0f)
202                 {
203                         td = td1 * td1;
204                         // make sure some part of it is visible on this line
205                         if (td < maxdist3)
206                         {
207                                 maxdist2 = maxdist - td;
208                                 for (s = 0;s < smax;s++)
209                                 {
210                                         if (sdtable[s] < maxdist2)
211                                         {
212                                                 k = (32768.0f / (sdtable[s] + td)) - subtract;
213                                                 bl[0] += red   * k;
214                                                 bl[1] += green * k;
215                                                 bl[2] += blue  * k;
216                                                 lit = true;
217                                         }
218                                         bl += 3;
219                                 }
220                         }
221                         else // skip line
222                                 bl += smax3;
223                 }
224         }
225         return lit;
226 }
227
228 /*
229 ===============
230 R_BuildLightMap
231
232 Combine and scale multiple lightmaps into the 8.8 format in blocklights
233 ===============
234 */
235 static void R_BuildLightMap (const entity_render_t *ent, msurface_t *surf)
236 {
237         if (!r_floatbuildlightmap.integer)
238         {
239                 int smax, tmax, i, j, size, size3, shift, maps, stride, l;
240                 unsigned int *bl, scale;
241                 qbyte *lightmap, *out, *stain;
242
243                 // update cached lighting info
244                 surf->cached_dlight = 0;
245
246                 smax = (surf->extents[0]>>4)+1;
247                 tmax = (surf->extents[1]>>4)+1;
248                 size = smax*tmax;
249                 size3 = size*3;
250                 lightmap = surf->samples;
251
252         // set to full bright if no light data
253                 bl = intblocklights;
254                 if ((ent->effects & EF_FULLBRIGHT) || !ent->model->brushq1.lightdata)
255                 {
256                         for (i = 0;i < size3;i++)
257                                 bl[i] = 255*256;
258                 }
259                 else
260                 {
261         // clear to no light
262                         j = r_ambient.value * 512.0f; // would be 128.0f logically, but using 512.0f to match winquake style
263                         if (j)
264                         {
265                                 for (i = 0;i < size3;i++)
266                                         *bl++ = j;
267                         }
268                         else
269                                 memset(bl, 0, size*3*sizeof(unsigned int));
270
271                         if (surf->dlightframe == r_framecount && r_dlightmap.integer)
272                         {
273                                 surf->cached_dlight = R_IntAddDynamicLights(&ent->inversematrix, surf);
274                                 if (surf->cached_dlight)
275                                         c_light_polys++;
276                         }
277
278         // add all the lightmaps
279                         if (lightmap)
280                         {
281                                 bl = intblocklights;
282                                 for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++, lightmap += size3)
283                                         for (scale = d_lightstylevalue[surf->styles[maps]], i = 0;i < size3;i++)
284                                                 bl[i] += lightmap[i] * scale;
285                         }
286                 }
287
288                 stain = surf->stainsamples;
289                 bl = intblocklights;
290                 out = templight;
291                 // deal with lightmap brightness scale
292                 shift = 7 + r_lightmapscalebit + 8;
293                 if (ent->model->brushq1.lightmaprgba)
294                 {
295                         stride = (surf->lightmaptexturestride - smax) * 4;
296                         for (i = 0;i < tmax;i++, out += stride)
297                         {
298                                 for (j = 0;j < smax;j++)
299                                 {
300                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
301                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
302                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
303                                         *out++ = 255;
304                                 }
305                         }
306                 }
307                 else
308                 {
309                         stride = (surf->lightmaptexturestride - smax) * 3;
310                         for (i = 0;i < tmax;i++, out += stride)
311                         {
312                                 for (j = 0;j < smax;j++)
313                                 {
314                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
315                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
316                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
317                                 }
318                         }
319                 }
320
321                 R_UpdateTexture(surf->lightmaptexture, templight);
322         }
323         else
324         {
325                 int smax, tmax, i, j, size, size3, maps, stride, l;
326                 float *bl, scale;
327                 qbyte *lightmap, *out, *stain;
328
329                 // update cached lighting info
330                 surf->cached_dlight = 0;
331
332                 smax = (surf->extents[0]>>4)+1;
333                 tmax = (surf->extents[1]>>4)+1;
334                 size = smax*tmax;
335                 size3 = size*3;
336                 lightmap = surf->samples;
337
338         // set to full bright if no light data
339                 bl = floatblocklights;
340                 if ((ent->effects & EF_FULLBRIGHT) || !ent->model->brushq1.lightdata)
341                         j = 255*256;
342                 else
343                         j = r_ambient.value * 512.0f; // would be 128.0f logically, but using 512.0f to match winquake style
344
345                 // clear to no light
346                 if (j)
347                 {
348                         for (i = 0;i < size3;i++)
349                                 *bl++ = j;
350                 }
351                 else
352                         memset(bl, 0, size*3*sizeof(float));
353
354                 if (surf->dlightframe == r_framecount && r_dlightmap.integer)
355                 {
356                         surf->cached_dlight = R_FloatAddDynamicLights(&ent->inversematrix, surf);
357                         if (surf->cached_dlight)
358                                 c_light_polys++;
359                 }
360
361                 // add all the lightmaps
362                 if (lightmap)
363                 {
364                         bl = floatblocklights;
365                         for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++, lightmap += size3)
366                                 for (scale = d_lightstylevalue[surf->styles[maps]], i = 0;i < size3;i++)
367                                         bl[i] += lightmap[i] * scale;
368                 }
369
370                 stain = surf->stainsamples;
371                 bl = floatblocklights;
372                 out = templight;
373                 // deal with lightmap brightness scale
374                 scale = 1.0f / (1 << (7 + r_lightmapscalebit + 8));
375                 if (ent->model->brushq1.lightmaprgba)
376                 {
377                         stride = (surf->lightmaptexturestride - smax) * 4;
378                         for (i = 0;i < tmax;i++, out += stride)
379                         {
380                                 for (j = 0;j < smax;j++)
381                                 {
382                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
383                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
384                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
385                                         *out++ = 255;
386                                 }
387                         }
388                 }
389                 else
390                 {
391                         stride = (surf->lightmaptexturestride - smax) * 3;
392                         for (i = 0;i < tmax;i++, out += stride)
393                         {
394                                 for (j = 0;j < smax;j++)
395                                 {
396                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
397                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
398                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
399                                 }
400                         }
401                 }
402
403                 R_UpdateTexture(surf->lightmaptexture, templight);
404         }
405 }
406
407 void R_StainNode (mnode_t *node, model_t *model, const vec3_t origin, float radius, const float fcolor[8])
408 {
409         float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
410         msurface_t *surf, *endsurf;
411         int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
412         qbyte *bl;
413         vec3_t impact;
414
415         maxdist = radius * radius;
416         invradius = 1.0f / radius;
417
418 loc0:
419         if (node->contents < 0)
420                 return;
421         ndist = PlaneDiff(origin, node->plane);
422         if (ndist > radius)
423         {
424                 node = node->children[0];
425                 goto loc0;
426         }
427         if (ndist < -radius)
428         {
429                 node = node->children[1];
430                 goto loc0;
431         }
432
433         dist2 = ndist * ndist;
434         maxdist3 = maxdist - dist2;
435
436         if (node->plane->type < 3)
437         {
438                 VectorCopy(origin, impact);
439                 impact[node->plane->type] -= ndist;
440         }
441         else
442         {
443                 impact[0] = origin[0] - node->plane->normal[0] * ndist;
444                 impact[1] = origin[1] - node->plane->normal[1] * ndist;
445                 impact[2] = origin[2] - node->plane->normal[2] * ndist;
446         }
447
448         for (surf = model->brushq1.surfaces + node->firstsurface, endsurf = surf + node->numsurfaces;surf < endsurf;surf++)
449         {
450                 if (surf->stainsamples)
451                 {
452                         smax = (surf->extents[0] >> 4) + 1;
453                         tmax = (surf->extents[1] >> 4) + 1;
454
455                         impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
456                         impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
457
458                         s = bound(0, impacts, smax * 16) - impacts;
459                         t = bound(0, impactt, tmax * 16) - impactt;
460                         i = s * s + t * t + dist2;
461                         if (i > maxdist)
462                                 continue;
463
464                         // reduce calculations
465                         for (s = 0, i = impacts; s < smax; s++, i -= 16)
466                                 sdtable[s] = i * i + dist2;
467
468                         bl = surf->stainsamples;
469                         smax3 = smax * 3;
470                         stained = false;
471
472                         i = impactt;
473                         for (t = 0;t < tmax;t++, i -= 16)
474                         {
475                                 td = i * i;
476                                 // make sure some part of it is visible on this line
477                                 if (td < maxdist3)
478                                 {
479                                         maxdist2 = maxdist - td;
480                                         for (s = 0;s < smax;s++)
481                                         {
482                                                 if (sdtable[s] < maxdist2)
483                                                 {
484                                                         ratio = lhrandom(0.0f, 1.0f);
485                                                         a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
486                                                         if (a >= (1.0f / 64.0f))
487                                                         {
488                                                                 if (a > 1)
489                                                                         a = 1;
490                                                                 bl[0] = (qbyte) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
491                                                                 bl[1] = (qbyte) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
492                                                                 bl[2] = (qbyte) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
493                                                                 stained = true;
494                                                         }
495                                                 }
496                                                 bl += 3;
497                                         }
498                                 }
499                                 else // skip line
500                                         bl += smax3;
501                         }
502                         // force lightmap upload
503                         if (stained)
504                                 surf->cached_dlight = true;
505                 }
506         }
507
508         if (node->children[0]->contents >= 0)
509         {
510                 if (node->children[1]->contents >= 0)
511                 {
512                         R_StainNode(node->children[0], model, origin, radius, fcolor);
513                         node = node->children[1];
514                         goto loc0;
515                 }
516                 else
517                 {
518                         node = node->children[0];
519                         goto loc0;
520                 }
521         }
522         else if (node->children[1]->contents >= 0)
523         {
524                 node = node->children[1];
525                 goto loc0;
526         }
527 }
528
529 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)
530 {
531         int n;
532         float fcolor[8];
533         entity_render_t *ent;
534         model_t *model;
535         vec3_t org;
536         if (cl.worldmodel == NULL || !cl.worldmodel->brushq1.nodes)
537                 return;
538         fcolor[0] = cr1;
539         fcolor[1] = cg1;
540         fcolor[2] = cb1;
541         fcolor[3] = ca1 * (1.0f / 64.0f);
542         fcolor[4] = cr2 - cr1;
543         fcolor[5] = cg2 - cg1;
544         fcolor[6] = cb2 - cb1;
545         fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
546
547         R_StainNode(cl.worldmodel->brushq1.nodes + cl.worldmodel->brushq1.hulls[0].firstclipnode, cl.worldmodel, origin, radius, fcolor);
548
549         // look for embedded bmodels
550         for (n = 0;n < cl_num_brushmodel_entities;n++)
551         {
552                 ent = cl_brushmodel_entities[n];
553                 model = ent->model;
554                 if (model && model->name[0] == '*')
555                 {
556                         Mod_CheckLoaded(model);
557                         if (model->brushq1.nodes)
558                         {
559                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
560                                 R_StainNode(model->brushq1.nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
561                         }
562                 }
563         }
564 }
565
566
567 /*
568 =============================================================
569
570         BRUSH MODELS
571
572 =============================================================
573 */
574
575 static void RSurf_AddLightmapToVertexColors_Color4f(const int *lightmapoffsets, float *c, int numverts, const qbyte *samples, int size3, const qbyte *styles)
576 {
577         int i;
578         float scale;
579         const qbyte *lm;
580         if (styles[0] != 255)
581         {
582                 for (i = 0;i < numverts;i++, c += 4)
583                 {
584                         lm = samples + lightmapoffsets[i];
585                         scale = d_lightstylevalue[styles[0]] * (1.0f / 32768.0f);
586                         VectorMA(c, scale, lm, c);
587                         if (styles[1] != 255)
588                         {
589                                 lm += size3;
590                                 scale = d_lightstylevalue[styles[1]] * (1.0f / 32768.0f);
591                                 VectorMA(c, scale, lm, c);
592                                 if (styles[2] != 255)
593                                 {
594                                         lm += size3;
595                                         scale = d_lightstylevalue[styles[2]] * (1.0f / 32768.0f);
596                                         VectorMA(c, scale, lm, c);
597                                         if (styles[3] != 255)
598                                         {
599                                                 lm += size3;
600                                                 scale = d_lightstylevalue[styles[3]] * (1.0f / 32768.0f);
601                                                 VectorMA(c, scale, lm, c);
602                                         }
603                                 }
604                         }
605                 }
606         }
607 }
608
609 static void RSurf_FogColors_Vertex3f_Color4f(const float *v, float *c, float colorscale, int numverts, const float *modelorg)
610 {
611         int i;
612         float diff[3], f;
613         if (fogenabled)
614         {
615                 for (i = 0;i < numverts;i++, v += 3, c += 4)
616                 {
617                         VectorSubtract(v, modelorg, diff);
618                         f = colorscale * (1 - exp(fogdensity/DotProduct(diff, diff)));
619                         VectorScale(c, f, c);
620                 }
621         }
622         else if (colorscale != 1)
623                 for (i = 0;i < numverts;i++, c += 4)
624                         VectorScale(c, colorscale, c);
625 }
626
627 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)
628 {
629         int i;
630         float diff[3], f;
631         r *= colorscale;
632         g *= colorscale;
633         b *= colorscale;
634         if (fogenabled)
635         {
636                 for (i = 0;i < numverts;i++, v += 3, c += 4)
637                 {
638                         VectorSubtract(v, modelorg, diff);
639                         f = 1 - exp(fogdensity/DotProduct(diff, diff));
640                         c[0] = r * f;
641                         c[1] = g * f;
642                         c[2] = b * f;
643                         c[3] = a;
644                 }
645         }
646         else
647         {
648                 for (i = 0;i < numverts;i++, c += 4)
649                 {
650                         c[0] = r;
651                         c[1] = g;
652                         c[2] = b;
653                         c[3] = a;
654                 }
655         }
656 }
657
658 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)
659 {
660         int i;
661         float diff[3], f;
662         r *= colorscale;
663         g *= colorscale;
664         b *= colorscale;
665         for (i = 0;i < numverts;i++, v += 3, c += 4)
666         {
667                 VectorSubtract(v, modelorg, diff);
668                 f = exp(fogdensity/DotProduct(diff, diff));
669                 c[0] = r;
670                 c[1] = g;
671                 c[2] = b;
672                 c[3] = a * f;
673         }
674 }
675
676 static int RSurf_LightSeparate_Vertex3f_Color4f(const matrix4x4_t *matrix, const int *dlightbits, int numverts, const float *vert, float *color, float scale)
677 {
678         float f;
679         const float *v;
680         float *c;
681         int i, l, lit = false;
682         const rdlight_t *rd;
683         vec3_t lightorigin;
684         for (l = 0;l < r_numdlights;l++)
685         {
686                 if (dlightbits[l >> 5] & (1 << (l & 31)))
687                 {
688                         rd = &r_dlight[l];
689                         Matrix4x4_Transform(matrix, rd->origin, lightorigin);
690                         for (i = 0, v = vert, c = color;i < numverts;i++, v += 3, c += 4)
691                         {
692                                 f = VectorDistance2(v, lightorigin) + LIGHTOFFSET;
693                                 if (f < rd->cullradius2)
694                                 {
695                                         f = ((1.0f / f) - rd->subtract) * scale;
696                                         VectorMA(c, f, rd->light, c);
697                                         lit = true;
698                                 }
699                         }
700                 }
701         }
702         return lit;
703 }
704
705 // note: this untransforms lights to do the checking
706 static int RSurf_LightCheck(const matrix4x4_t *matrix, const int *dlightbits, const surfmesh_t *mesh)
707 {
708         int i, l;
709         const rdlight_t *rd;
710         vec3_t lightorigin;
711         const float *v;
712         for (l = 0;l < r_numdlights;l++)
713         {
714                 if (dlightbits[l >> 5] & (1 << (l & 31)))
715                 {
716                         rd = &r_dlight[l];
717                         Matrix4x4_Transform(matrix, rd->origin, lightorigin);
718                         for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
719                                 if (VectorDistance2(v, lightorigin) < rd->cullradius2)
720                                         return true;
721                 }
722         }
723         return false;
724 }
725
726 static void RSurfShader_Sky(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
727 {
728         const msurface_t *surf;
729         const surfmesh_t *mesh;
730         rmeshstate_t m;
731
732         // LordHavoc: HalfLife maps have freaky skypolys...
733         if (ent->model->brush.ishlbsp)
734                 return;
735
736         if (skyrendernow)
737         {
738                 skyrendernow = false;
739                 if (skyrendermasked)
740                         R_Sky();
741         }
742
743         R_Mesh_Matrix(&ent->matrix);
744
745         GL_Color(fogcolor[0] * r_colorscale, fogcolor[1] * r_colorscale, fogcolor[2] * r_colorscale, 1);
746         if (skyrendermasked)
747         {
748                 // depth-only (masking)
749                 qglColorMask(0,0,0,0);
750                 // just to make sure that braindead drivers don't draw anything
751                 // despite that colormask...
752                 GL_BlendFunc(GL_ZERO, GL_ONE);
753         }
754         else
755         {
756                 // fog sky
757                 GL_BlendFunc(GL_ONE, GL_ZERO);
758         }
759         GL_DepthMask(true);
760         GL_DepthTest(true);
761
762         memset(&m, 0, sizeof(m));
763         R_Mesh_State_Texture(&m);
764
765         while((surf = *surfchain++) != NULL)
766         {
767                 if (surf->visframe == r_framecount)
768                 {
769                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
770                         {
771                                 GL_VertexPointer(mesh->vertex3f);
772                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
773                         }
774                 }
775         }
776         qglColorMask(1,1,1,1);
777 }
778
779 static void RSurfShader_Water_Callback(const void *calldata1, int calldata2)
780 {
781         const entity_render_t *ent = calldata1;
782         const msurface_t *surf = ent->model->brushq1.surfaces + calldata2;
783         float f, colorscale;
784         const surfmesh_t *mesh;
785         rmeshstate_t m;
786         float alpha;
787         float modelorg[3];
788         texture_t *texture;
789         matrix4x4_t tempmatrix;
790
791         if (r_waterscroll.value)
792         {
793                 // scrolling in texture matrix
794                 Matrix4x4_CreateTranslate(&tempmatrix, sin(cl.time) * 0.025 * r_waterscroll.value, sin(cl.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
795                 R_Mesh_TextureMatrix(0, &tempmatrix);
796         }
797
798         R_Mesh_Matrix(&ent->matrix);
799         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
800
801         memset(&m, 0, sizeof(m));
802         texture = surf->texinfo->texture->currentframe;
803         alpha = texture->currentalpha;
804         if (texture->rendertype == SURFRENDER_ADD)
805         {
806                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
807                 GL_DepthMask(false);
808         }
809         else if (texture->rendertype == SURFRENDER_ALPHA)
810         {
811                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
812                 GL_DepthMask(false);
813         }
814         else
815         {
816                 GL_BlendFunc(GL_ONE, GL_ZERO);
817                 GL_DepthMask(true);
818         }
819         m.tex[0] = R_GetTexture(texture->skin.base);
820         colorscale = r_colorscale;
821         if (gl_combine.integer)
822         {
823                 m.texrgbscale[0] = 4;
824                 colorscale *= 0.25f;
825         }
826         GL_DepthTest(true);
827         GL_ColorPointer(varray_color4f);
828         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
829         {
830                 GL_VertexPointer(mesh->vertex3f);
831                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
832                 R_Mesh_State_Texture(&m);
833                 f = surf->flags & SURF_DRAWFULLBRIGHT ? 1.0f : ((surf->flags & SURF_LIGHTMAP) ? 0 : 0.5f);
834                 R_FillColors(varray_color4f, mesh->numverts, f, f, f, alpha);
835                 if (!(surf->flags & SURF_DRAWFULLBRIGHT || ent->effects & EF_FULLBRIGHT))
836                 {
837                         if (surf->dlightframe == r_framecount)
838                                 RSurf_LightSeparate_Vertex3f_Color4f(&ent->inversematrix, surf->dlightbits, mesh->numverts, mesh->vertex3f, varray_color4f, 1);
839                         if (surf->flags & SURF_LIGHTMAP)
840                                 RSurf_AddLightmapToVertexColors_Color4f(mesh->lightmapoffsets, varray_color4f, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
841                 }
842                 RSurf_FogColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, colorscale, mesh->numverts, modelorg);
843                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
844         }
845
846         if (fogenabled)
847         {
848                 memset(&m, 0, sizeof(m));
849                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
850                 GL_DepthMask(false);
851                 GL_DepthTest(true);
852                 m.tex[0] = R_GetTexture(texture->skin.fog);
853                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
854                 {
855                         GL_VertexPointer(mesh->vertex3f);
856                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
857                         GL_ColorPointer(varray_color4f);
858                         R_Mesh_State_Texture(&m);
859                         RSurf_FogPassColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], alpha, r_colorscale, mesh->numverts, modelorg);
860                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
861                 }
862         }
863
864         if (r_waterscroll.value)
865         {
866                 Matrix4x4_CreateIdentity(&tempmatrix);
867                 R_Mesh_TextureMatrix(0, &tempmatrix);
868         }
869 }
870
871 static void RSurfShader_Water(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
872 {
873         const msurface_t *surf;
874         msurface_t **chain;
875         vec3_t center;
876         if (texture->rendertype != SURFRENDER_OPAQUE)
877         {
878                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
879                 {
880                         if (surf->visframe == r_framecount)
881                         {
882                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
883                                 R_MeshQueue_AddTransparent(center, RSurfShader_Water_Callback, ent, surf - ent->model->brushq1.surfaces);
884                         }
885                 }
886         }
887         else
888                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
889                         if (surf->visframe == r_framecount)
890                                 RSurfShader_Water_Callback(ent, surf - ent->model->brushq1.surfaces);
891 }
892
893 static void RSurfShader_Wall_Pass_BaseVertex(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
894 {
895         float base, colorscale;
896         const surfmesh_t *mesh;
897         rmeshstate_t m;
898         float modelorg[3];
899         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
900         memset(&m, 0, sizeof(m));
901         if (rendertype == SURFRENDER_ADD)
902         {
903                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
904                 GL_DepthMask(false);
905         }
906         else if (rendertype == SURFRENDER_ALPHA)
907         {
908                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
909                 GL_DepthMask(false);
910         }
911         else
912         {
913                 GL_BlendFunc(GL_ONE, GL_ZERO);
914                 GL_DepthMask(true);
915         }
916         m.tex[0] = R_GetTexture(texture->skin.base);
917         colorscale = r_colorscale;
918         if (gl_combine.integer)
919         {
920                 m.texrgbscale[0] = 4;
921                 colorscale *= 0.25f;
922         }
923         base = ent->effects & EF_FULLBRIGHT ? 2.0f : r_ambient.value * (1.0f / 64.0f);
924         GL_DepthTest(true);
925         GL_ColorPointer(varray_color4f);
926         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
927         {
928                 GL_VertexPointer(mesh->vertex3f);
929                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
930                 R_Mesh_State_Texture(&m);
931                 R_FillColors(varray_color4f, mesh->numverts, base, base, base, currentalpha);
932                 if (!(ent->effects & EF_FULLBRIGHT))
933                 {
934                         if (surf->dlightframe == r_framecount)
935                                 RSurf_LightSeparate_Vertex3f_Color4f(&ent->inversematrix, surf->dlightbits, mesh->numverts, mesh->vertex3f, varray_color4f, 1);
936                         if (surf->flags & SURF_LIGHTMAP)
937                                 RSurf_AddLightmapToVertexColors_Color4f(mesh->lightmapoffsets, varray_color4f, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
938                 }
939                 RSurf_FogColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, colorscale, mesh->numverts, modelorg);
940                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
941         }
942 }
943
944 static void RSurfShader_Wall_Pass_Glow(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
945 {
946         const surfmesh_t *mesh;
947         rmeshstate_t m;
948         float modelorg[3];
949         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
950         memset(&m, 0, sizeof(m));
951         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
952         GL_DepthMask(false);
953         GL_DepthTest(true);
954         m.tex[0] = R_GetTexture(texture->skin.glow);
955         GL_ColorPointer(varray_color4f);
956         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
957         {
958                 GL_VertexPointer(mesh->vertex3f);
959                 if (m.tex[0])
960                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
961                 R_Mesh_State_Texture(&m);
962                 RSurf_FoggedColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, 1, 1, 1, currentalpha, r_colorscale, mesh->numverts, modelorg);
963                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
964         }
965 }
966
967 static void RSurfShader_Wall_Pass_Fog(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
968 {
969         const surfmesh_t *mesh;
970         rmeshstate_t m;
971         float modelorg[3];
972         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
973         memset(&m, 0, sizeof(m));
974         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
975         GL_DepthMask(false);
976         GL_DepthTest(true);
977         m.tex[0] = R_GetTexture(texture->skin.fog);
978         GL_ColorPointer(varray_color4f);
979         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
980         {
981                 GL_VertexPointer(mesh->vertex3f);
982                 if (m.tex[0])
983                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
984                 R_Mesh_State_Texture(&m);
985                 RSurf_FogPassColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], currentalpha, r_colorscale, mesh->numverts, modelorg);
986                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
987         }
988 }
989
990 static void RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
991 {
992         const msurface_t *surf;
993         const surfmesh_t *mesh;
994         rmeshstate_t m;
995         int lightmaptexturenum;
996         float cl;
997         memset(&m, 0, sizeof(m));
998         GL_BlendFunc(GL_ONE, GL_ZERO);
999         GL_DepthMask(true);
1000         GL_DepthTest(true);
1001         m.tex[0] = R_GetTexture(texture->skin.base);
1002         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1003         m.tex[2] = R_GetTexture(texture->skin.detail);
1004         m.texrgbscale[0] = 1;
1005         m.texrgbscale[1] = 4;
1006         m.texrgbscale[2] = 2;
1007         cl = (float) (1 << r_lightmapscalebit) * r_colorscale;
1008         GL_Color(cl, cl, cl, 1);
1009
1010         while((surf = *surfchain++) != NULL)
1011         {
1012                 if (surf->visframe == r_framecount)
1013                 {
1014                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1015                         //if (m.tex[1] != lightmaptexturenum)
1016                         //{
1017                                 m.tex[1] = lightmaptexturenum;
1018                         //      R_Mesh_State_Texture(&m);
1019                         //}
1020                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1021                         {
1022                                 GL_VertexPointer(mesh->vertex3f);
1023                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1024                                 m.pointer_texcoord[1] = mesh->texcoordlightmap2f;
1025                                 m.pointer_texcoord[2] = mesh->texcoorddetail2f;
1026                                 R_Mesh_State_Texture(&m);
1027                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1028                         }
1029                 }
1030         }
1031 }
1032
1033 static void RSurfShader_OpaqueWall_Pass_BaseDoubleTex(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1034 {
1035         const msurface_t *surf;
1036         const surfmesh_t *mesh;
1037         rmeshstate_t m;
1038         int lightmaptexturenum;
1039         memset(&m, 0, sizeof(m));
1040         GL_BlendFunc(GL_ONE, GL_ZERO);
1041         GL_DepthMask(true);
1042         GL_DepthTest(true);
1043         m.tex[0] = R_GetTexture(texture->skin.base);
1044         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1045         if (gl_combine.integer)
1046                 m.texrgbscale[1] = 4;
1047         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1048         while((surf = *surfchain++) != NULL)
1049         {
1050                 if (surf->visframe == r_framecount)
1051                 {
1052                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1053                         //if (m.tex[1] != lightmaptexturenum)
1054                         //{
1055                                 m.tex[1] = lightmaptexturenum;
1056                         //      R_Mesh_State_Texture(&m);
1057                         //}
1058                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1059                         {
1060                                 GL_VertexPointer(mesh->vertex3f);
1061                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1062                                 m.pointer_texcoord[1] = mesh->texcoordlightmap2f;
1063                                 R_Mesh_State_Texture(&m);
1064                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1065                         }
1066                 }
1067         }
1068 }
1069
1070 static void RSurfShader_OpaqueWall_Pass_BaseTexture(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1071 {
1072         const msurface_t *surf;
1073         const surfmesh_t *mesh;
1074         rmeshstate_t m;
1075         memset(&m, 0, sizeof(m));
1076         GL_DepthMask(true);
1077         GL_DepthTest(true);
1078         GL_BlendFunc(GL_ONE, GL_ZERO);
1079         m.tex[0] = R_GetTexture(texture->skin.base);
1080         GL_Color(1, 1, 1, 1);
1081         while((surf = *surfchain++) != NULL)
1082         {
1083                 if (surf->visframe == r_framecount)
1084                 {
1085                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1086                         {
1087                                 GL_VertexPointer(mesh->vertex3f);
1088                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1089                                 R_Mesh_State_Texture(&m);
1090                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1091                         }
1092                 }
1093         }
1094 }
1095
1096 static void RSurfShader_OpaqueWall_Pass_BaseLightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1097 {
1098         const msurface_t *surf;
1099         const surfmesh_t *mesh;
1100         rmeshstate_t m;
1101         int lightmaptexturenum;
1102         memset(&m, 0, sizeof(m));
1103         GL_BlendFunc(GL_ZERO, GL_SRC_COLOR);
1104         GL_DepthMask(false);
1105         GL_DepthTest(true);
1106         m.tex[0] = R_GetTexture((**surfchain).lightmaptexture);
1107         if (gl_combine.integer)
1108                 m.texrgbscale[0] = 4;
1109         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1110         while((surf = *surfchain++) != NULL)
1111         {
1112                 if (surf->visframe == r_framecount)
1113                 {
1114                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1115                         //if (m.tex[0] != lightmaptexturenum)
1116                         //{
1117                                 m.tex[0] = lightmaptexturenum;
1118                         //      R_Mesh_State_Texture(&m);
1119                         //}
1120                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1121                         {
1122                                 GL_VertexPointer(mesh->vertex3f);
1123                                 m.pointer_texcoord[0] = mesh->texcoordlightmap2f;
1124                                 R_Mesh_State_Texture(&m);
1125                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1126                         }
1127                 }
1128         }
1129 }
1130
1131 static void RSurfShader_OpaqueWall_Pass_Light(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1132 {
1133         const msurface_t *surf;
1134         const surfmesh_t *mesh;
1135         float colorscale;
1136         rmeshstate_t m;
1137
1138         memset(&m, 0, sizeof(m));
1139         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1140         GL_DepthMask(false);
1141         GL_DepthTest(true);
1142         m.tex[0] = R_GetTexture(texture->skin.base);
1143         colorscale = r_colorscale;
1144         if (gl_combine.integer)
1145         {
1146                 m.texrgbscale[0] = 4;
1147                 colorscale *= 0.25f;
1148         }
1149         GL_ColorPointer(varray_color4f);
1150         while((surf = *surfchain++) != NULL)
1151         {
1152                 if (surf->visframe == r_framecount && surf->dlightframe == r_framecount)
1153                 {
1154                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1155                         {
1156                                 if (RSurf_LightCheck(&ent->inversematrix, surf->dlightbits, mesh))
1157                                 {
1158                                         GL_VertexPointer(mesh->vertex3f);
1159                                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1160                                         R_FillColors(varray_color4f, mesh->numverts, 0, 0, 0, 1);
1161                                         R_Mesh_State_Texture(&m);
1162                                         RSurf_LightSeparate_Vertex3f_Color4f(&ent->inversematrix, surf->dlightbits, mesh->numverts, mesh->vertex3f, varray_color4f, colorscale);
1163                                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1164                                 }
1165                         }
1166                 }
1167         }
1168 }
1169
1170 static void RSurfShader_OpaqueWall_Pass_Fog(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1171 {
1172         const msurface_t *surf;
1173         const surfmesh_t *mesh;
1174         rmeshstate_t m;
1175         float modelorg[3];
1176         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1177         memset(&m, 0, sizeof(m));
1178         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1179         GL_DepthMask(false);
1180         GL_DepthTest(true);
1181         GL_ColorPointer(varray_color4f);
1182         while((surf = *surfchain++) != NULL)
1183         {
1184                 if (surf->visframe == r_framecount)
1185                 {
1186                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1187                         {
1188                                 GL_VertexPointer(mesh->vertex3f);
1189                                 if (m.tex[0])
1190                                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1191                                 R_Mesh_State_Texture(&m);
1192                                 RSurf_FogPassColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], 1, r_colorscale, mesh->numverts, modelorg);
1193                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1194                         }
1195                 }
1196         }
1197 }
1198
1199 static void RSurfShader_OpaqueWall_Pass_BaseDetail(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1200 {
1201         const msurface_t *surf;
1202         const surfmesh_t *mesh;
1203         rmeshstate_t m;
1204         memset(&m, 0, sizeof(m));
1205         GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
1206         GL_DepthMask(false);
1207         GL_DepthTest(true);
1208         m.tex[0] = R_GetTexture(texture->skin.detail);
1209         GL_Color(1, 1, 1, 1);
1210         while((surf = *surfchain++) != NULL)
1211         {
1212                 if (surf->visframe == r_framecount)
1213                 {
1214                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1215                         {
1216                                 GL_VertexPointer(mesh->vertex3f);
1217                                 m.pointer_texcoord[0] = mesh->texcoorddetail2f;
1218                                 R_Mesh_State_Texture(&m);
1219                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1220                         }
1221                 }
1222         }
1223 }
1224
1225 static void RSurfShader_OpaqueWall_Pass_Glow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1226 {
1227         const msurface_t *surf;
1228         const surfmesh_t *mesh;
1229         rmeshstate_t m;
1230         memset(&m, 0, sizeof(m));
1231         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1232         GL_DepthMask(false);
1233         GL_DepthTest(true);
1234         m.tex[0] = R_GetTexture(texture->skin.glow);
1235         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1236         while((surf = *surfchain++) != NULL)
1237         {
1238                 if (surf->visframe == r_framecount)
1239                 {
1240                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1241                         {
1242                                 GL_VertexPointer(mesh->vertex3f);
1243                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1244                                 R_Mesh_State_Texture(&m);
1245                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1246                         }
1247                 }
1248         }
1249 }
1250
1251 static void RSurfShader_OpaqueWall_Pass_OpaqueGlow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1252 {
1253         const msurface_t *surf;
1254         const surfmesh_t *mesh;
1255         rmeshstate_t m;
1256         memset(&m, 0, sizeof(m));
1257         GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1258         GL_DepthMask(true);
1259         m.tex[0] = R_GetTexture(texture->skin.glow);
1260         if (m.tex[0])
1261                 GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1262         else
1263                 GL_Color(0, 0, 0, 1);
1264         while((surf = *surfchain++) != NULL)
1265         {
1266                 if (surf->visframe == r_framecount)
1267                 {
1268                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1269                         {
1270                                 GL_VertexPointer(mesh->vertex3f);
1271                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1272                                 R_Mesh_State_Texture(&m);
1273                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1274                         }
1275                 }
1276         }
1277 }
1278
1279 static void RSurfShader_Wall_Vertex_Callback(const void *calldata1, int calldata2)
1280 {
1281         const entity_render_t *ent = calldata1;
1282         const msurface_t *surf = ent->model->brushq1.surfaces + calldata2;
1283         int rendertype;
1284         float currentalpha;
1285         texture_t *texture;
1286         R_Mesh_Matrix(&ent->matrix);
1287
1288         texture = surf->texinfo->texture;
1289         if (texture->animated)
1290                 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];
1291
1292         currentalpha = ent->alpha;
1293         if (texture->flags & SURF_WATERALPHA)
1294                 currentalpha *= r_wateralpha.value;
1295         if (ent->effects & EF_ADDITIVE)
1296                 rendertype = SURFRENDER_ADD;
1297         else if (currentalpha < 1 || texture->skin.fog != NULL)
1298                 rendertype = SURFRENDER_ALPHA;
1299         else
1300                 rendertype = SURFRENDER_OPAQUE;
1301
1302         RSurfShader_Wall_Pass_BaseVertex(ent, surf, texture, rendertype, currentalpha);
1303         if (texture->skin.glow)
1304                 RSurfShader_Wall_Pass_Glow(ent, surf, texture, rendertype, currentalpha);
1305         if (fogenabled)
1306                 RSurfShader_Wall_Pass_Fog(ent, surf, texture, rendertype, currentalpha);
1307 }
1308
1309 static void RSurfShader_Wall_Lightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1310 {
1311         const msurface_t *surf;
1312         msurface_t **chain;
1313         vec3_t center;
1314         if (texture->rendertype != SURFRENDER_OPAQUE)
1315         {
1316                 // transparent vertex shaded from lightmap
1317                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
1318                 {
1319                         if (surf->visframe == r_framecount)
1320                         {
1321                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
1322                                 R_MeshQueue_AddTransparent(center, RSurfShader_Wall_Vertex_Callback, ent, surf - ent->model->brushq1.surfaces);
1323                         }
1324                 }
1325         }
1326         else if (r_shadow_realtime_world.integer)
1327         {
1328                 // opaque base lighting
1329                 RSurfShader_OpaqueWall_Pass_OpaqueGlow(ent, texture, surfchain);
1330                 if (fogenabled)
1331                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1332         }
1333         else if (r_vertexsurfaces.integer)
1334         {
1335                 // opaque vertex shaded from lightmap
1336                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
1337                         if (surf->visframe == r_framecount)
1338                                 RSurfShader_Wall_Pass_BaseVertex(ent, surf, texture, texture->rendertype, texture->currentalpha);
1339                 if (texture->skin.glow)
1340                         for (chain = surfchain;(surf = *chain) != NULL;chain++)
1341                                 if (surf->visframe == r_framecount)
1342                                         RSurfShader_Wall_Pass_Glow(ent, surf, texture, texture->rendertype, texture->currentalpha);
1343                 if (fogenabled)
1344                         for (chain = surfchain;(surf = *chain) != NULL;chain++)
1345                                 if (surf->visframe == r_framecount)
1346                                         RSurfShader_Wall_Pass_Fog(ent, surf, texture, texture->rendertype, texture->currentalpha);
1347         }
1348         else
1349         {
1350                 // opaque lightmapped
1351                 if (r_textureunits.integer >= 2)
1352                 {
1353                         if (r_textureunits.integer >= 3 && gl_combine.integer && r_detailtextures.integer)
1354                                 RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(ent, texture, surfchain);
1355                         else
1356                         {
1357                                 RSurfShader_OpaqueWall_Pass_BaseDoubleTex(ent, texture, surfchain);
1358                                 if (r_detailtextures.integer)
1359                                         RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1360                         }
1361                 }
1362                 else
1363                 {
1364                         RSurfShader_OpaqueWall_Pass_BaseTexture(ent, texture, surfchain);
1365                         RSurfShader_OpaqueWall_Pass_BaseLightmap(ent, texture, surfchain);
1366                         if (r_detailtextures.integer)
1367                                 RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1368                 }
1369                 if (!r_dlightmap.integer && !(ent->effects & EF_FULLBRIGHT))
1370                         RSurfShader_OpaqueWall_Pass_Light(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 }
1377
1378 Cshader_t Cshader_wall_lightmap = {{NULL, RSurfShader_Wall_Lightmap}, SHADERFLAGS_NEEDLIGHTMAP};
1379 Cshader_t Cshader_water = {{NULL, RSurfShader_Water}, 0};
1380 Cshader_t Cshader_sky = {{RSurfShader_Sky, NULL}, 0};
1381
1382 int Cshader_count = 3;
1383 Cshader_t *Cshaders[3] =
1384 {
1385         &Cshader_wall_lightmap,
1386         &Cshader_water,
1387         &Cshader_sky
1388 };
1389
1390 void R_UpdateTextureInfo(entity_render_t *ent)
1391 {
1392         int i, texframe, alttextures;
1393         texture_t *t;
1394
1395         if (!ent->model)
1396                 return;
1397
1398         alttextures = ent->frame != 0;
1399         texframe = (int)(cl.time * 5.0f);
1400         for (i = 0;i < ent->model->brushq1.numtextures;i++)
1401         {
1402                 t = ent->model->brushq1.textures + i;
1403                 t->currentalpha = ent->alpha;
1404                 if (t->flags & SURF_WATERALPHA)
1405                         t->currentalpha *= r_wateralpha.value;
1406                 if (ent->effects & EF_ADDITIVE)
1407                         t->rendertype = SURFRENDER_ADD;
1408                 else if (t->currentalpha < 1 || t->skin.fog != NULL)
1409                         t->rendertype = SURFRENDER_ALPHA;
1410                 else
1411                         t->rendertype = SURFRENDER_OPAQUE;
1412                 // we don't need to set currentframe if t->animated is false because
1413                 // it was already set up by the texture loader for non-animating
1414                 if (t->animated)
1415                         t->currentframe = t->anim_frames[alttextures][(t->anim_total[alttextures] >= 2) ? (texframe % t->anim_total[alttextures]) : 0];
1416         }
1417 }
1418
1419 void R_PrepareSurfaces(entity_render_t *ent)
1420 {
1421         int i, numsurfaces, *surfacevisframes;
1422         model_t *model;
1423         msurface_t *surf, *surfaces, **surfchain;
1424         vec3_t modelorg;
1425
1426         if (!ent->model)
1427                 return;
1428
1429         model = ent->model;
1430         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1431         numsurfaces = model->brushq1.nummodelsurfaces;
1432         surfaces = model->brushq1.surfaces + model->brushq1.firstmodelsurface;
1433         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1434
1435         R_UpdateTextureInfo(ent);
1436
1437         if (r_dynamic.integer && !r_shadow_realtime_dlight.integer)
1438                 R_MarkLights(ent);
1439
1440         if (model->brushq1.light_ambient != r_ambient.value || model->brushq1.light_scalebit != r_lightmapscalebit)
1441         {
1442                 model->brushq1.light_ambient = r_ambient.value;
1443                 model->brushq1.light_scalebit = r_lightmapscalebit;
1444                 for (i = 0;i < model->brushq1.nummodelsurfaces;i++)
1445                         model->brushq1.surfaces[i + model->brushq1.firstmodelsurface].cached_dlight = true;
1446         }
1447         else
1448         {
1449                 for (i = 0;i < model->brushq1.light_styles;i++)
1450                 {
1451                         if (model->brushq1.light_stylevalue[i] != d_lightstylevalue[model->brushq1.light_style[i]])
1452                         {
1453                                 model->brushq1.light_stylevalue[i] = d_lightstylevalue[model->brushq1.light_style[i]];
1454                                 for (surfchain = model->brushq1.light_styleupdatechains[i];*surfchain;surfchain++)
1455                                         (**surfchain).cached_dlight = true;
1456                         }
1457                 }
1458         }
1459
1460         for (i = 0, surf = surfaces;i < numsurfaces;i++, surf++)
1461         {
1462                 if (surfacevisframes[i] == r_framecount)
1463                 {
1464 #if !WORLDNODECULLBACKFACES
1465                         // mark any backface surfaces as not visible
1466                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1467                         {
1468                                 if (!(surf->flags & SURF_PLANEBACK))
1469                                         surfacevisframes[i] = -1;
1470                         }
1471                         else
1472                         {
1473                                 if ((surf->flags & SURF_PLANEBACK))
1474                                         surfacevisframes[i] = -1;
1475                         }
1476                         if (surfacevisframes[i] == r_framecount)
1477 #endif
1478                         {
1479                                 c_faces++;
1480                                 surf->visframe = r_framecount;
1481                                 if (surf->cached_dlight && surf->lightmaptexture != NULL && !r_vertexsurfaces.integer)
1482                                         R_BuildLightMap(ent, surf);
1483                         }
1484                 }
1485         }
1486 }
1487
1488 void R_DrawSurfaces(entity_render_t *ent, int type, msurface_t ***chains)
1489 {
1490         int i;
1491         texture_t *t;
1492         if (ent->model == NULL)
1493                 return;
1494         R_Mesh_Matrix(&ent->matrix);
1495         for (i = 0, t = ent->model->brushq1.textures;i < ent->model->brushq1.numtextures;i++, t++)
1496                 if (t->shader->shaderfunc[type] && t->currentframe && chains[i] != NULL)
1497                         t->shader->shaderfunc[type](ent, t->currentframe, chains[i]);
1498 }
1499
1500 static void R_DrawPortal_Callback(const void *calldata1, int calldata2)
1501 {
1502         int i;
1503         float *v;
1504         rmeshstate_t m;
1505         const entity_render_t *ent = calldata1;
1506         const mportal_t *portal = ent->model->brushq1.portals + calldata2;
1507         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1508         GL_DepthMask(false);
1509         GL_DepthTest(true);
1510         R_Mesh_Matrix(&ent->matrix);
1511         GL_VertexPointer(varray_vertex3f);
1512
1513         memset(&m, 0, sizeof(m));
1514         R_Mesh_State_Texture(&m);
1515
1516         i = portal - ent->model->brushq1.portals;
1517         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_colorscale,
1518                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_colorscale,
1519                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_colorscale,
1520                          0.125f);
1521         if (PlaneDiff(r_origin, (&portal->plane)) > 0)
1522         {
1523                 for (i = portal->numpoints - 1, v = varray_vertex3f;i >= 0;i--, v += 3)
1524                         VectorCopy(portal->points[i].position, v);
1525         }
1526         else
1527                 for (i = 0, v = varray_vertex3f;i < portal->numpoints;i++, v += 3)
1528                         VectorCopy(portal->points[i].position, v);
1529         R_Mesh_Draw(portal->numpoints, portal->numpoints - 2, polygonelements);
1530 }
1531
1532 // LordHavoc: this is just a nice debugging tool, very slow
1533 static void R_DrawPortals(entity_render_t *ent)
1534 {
1535         int i;
1536         mportal_t *portal, *endportal;
1537         float temp[3], center[3], f;
1538         if (ent->model == NULL)
1539                 return;
1540         for (portal = ent->model->brushq1.portals, endportal = portal + ent->model->brushq1.numportals;portal < endportal;portal++)
1541         {
1542                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
1543                 {
1544                         VectorClear(temp);
1545                         for (i = 0;i < portal->numpoints;i++)
1546                                 VectorAdd(temp, portal->points[i].position, temp);
1547                         f = ixtable[portal->numpoints];
1548                         VectorScale(temp, f, temp);
1549                         Matrix4x4_Transform(&ent->matrix, temp, center);
1550                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, ent, portal - ent->model->brushq1.portals);
1551                 }
1552         }
1553 }
1554
1555 void R_PrepareBrushModel(entity_render_t *ent)
1556 {
1557         int i, numsurfaces, *surfacevisframes, *surfacepvsframes;
1558         msurface_t *surf;
1559         model_t *model;
1560 #if WORLDNODECULLBACKFACES
1561         vec3_t modelorg;
1562 #endif
1563
1564         // because bmodels can be reused, we have to decide which things to render
1565         // from scratch every time
1566         model = ent->model;
1567         if (model == NULL)
1568                 return;
1569 #if WORLDNODECULLBACKFACES
1570         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1571 #endif
1572         numsurfaces = model->brushq1.nummodelsurfaces;
1573         surf = model->brushq1.surfaces + model->brushq1.firstmodelsurface;
1574         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1575         surfacepvsframes = model->brushq1.surfacepvsframes + model->brushq1.firstmodelsurface;
1576         for (i = 0;i < numsurfaces;i++, surf++)
1577         {
1578 #if WORLDNODECULLBACKFACES
1579                 // mark any backface surfaces as not visible
1580                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1581                 {
1582                         if ((surf->flags & SURF_PLANEBACK))
1583                                 surfacevisframes[i] = r_framecount;
1584                 }
1585                 else if (!(surf->flags & SURF_PLANEBACK))
1586                         surfacevisframes[i] = r_framecount;
1587 #else
1588                 surfacevisframes[i] = r_framecount;
1589 #endif
1590                 surf->dlightframe = -1;
1591         }
1592         R_PrepareSurfaces(ent);
1593 }
1594
1595 void R_SurfaceWorldNode (entity_render_t *ent)
1596 {
1597         int i, *surfacevisframes, *surfacepvsframes, surfnum;
1598         msurface_t *surf;
1599         mleaf_t *leaf;
1600         model_t *model;
1601         vec3_t modelorg;
1602
1603         // equivilant to quake's RecursiveWorldNode but faster and more effective
1604         model = ent->model;
1605         if (model == NULL)
1606                 return;
1607         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1608         surfacepvsframes = model->brushq1.surfacepvsframes + model->brushq1.firstmodelsurface;
1609         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1610
1611         for (leaf = model->brushq1.pvsleafchain;leaf;leaf = leaf->pvschain)
1612         {
1613                 if (!R_CullBox (leaf->mins, leaf->maxs))
1614                 {
1615                         c_leafs++;
1616                         leaf->visframe = r_framecount;
1617                 }
1618         }
1619
1620         for (i = 0;i < model->brushq1.pvssurflistlength;i++)
1621         {
1622                 surfnum = model->brushq1.pvssurflist[i];
1623                 surf = model->brushq1.surfaces + surfnum;
1624 #if WORLDNODECULLBACKFACES
1625                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1626                 {
1627                         if ((surf->flags & SURF_PLANEBACK) && !R_CullBox (surf->poly_mins, surf->poly_maxs))
1628                                 surfacevisframes[surfnum] = r_framecount;
1629                 }
1630                 else
1631                 {
1632                         if (!(surf->flags & SURF_PLANEBACK) && !R_CullBox (surf->poly_mins, surf->poly_maxs))
1633                                 surfacevisframes[surfnum] = r_framecount;
1634                 }
1635 #else
1636                 if (!R_CullBox (surf->poly_mins, surf->poly_maxs))
1637                         surfacevisframes[surfnum] = r_framecount;
1638 #endif
1639         }
1640 }
1641
1642 static void R_PortalWorldNode(entity_render_t *ent, mleaf_t *viewleaf)
1643 {
1644         int c, leafstackpos, *mark, *surfacevisframes, bitnum;
1645 #if WORLDNODECULLBACKFACES
1646         int n;
1647         msurface_t *surf;
1648 #endif
1649         mleaf_t *leaf, *leafstack[8192];
1650         mportal_t *p;
1651         vec3_t modelorg;
1652         msurface_t *surfaces;
1653         if (ent->model == NULL)
1654                 return;
1655         // LordHavoc: portal-passage worldnode with PVS;
1656         // follows portals leading outward from viewleaf, does not venture
1657         // offscreen or into leafs that are not visible, faster than Quake's
1658         // RecursiveWorldNode
1659         surfaces = ent->model->brushq1.surfaces;
1660         surfacevisframes = ent->model->brushq1.surfacevisframes;
1661         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1662         viewleaf->worldnodeframe = r_framecount;
1663         leafstack[0] = viewleaf;
1664         leafstackpos = 1;
1665         while (leafstackpos)
1666         {
1667                 c_leafs++;
1668                 leaf = leafstack[--leafstackpos];
1669                 leaf->visframe = r_framecount;
1670                 // draw any surfaces bounding this leaf
1671                 if (leaf->nummarksurfaces)
1672                 {
1673                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1674                         {
1675 #if WORLDNODECULLBACKFACES
1676                                 n = *mark++;
1677                                 if (surfacevisframes[n] != r_framecount)
1678                                 {
1679                                         surf = surfaces + n;
1680                                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1681                                         {
1682                                                 if ((surf->flags & SURF_PLANEBACK))
1683                                                         surfacevisframes[n] = r_framecount;
1684                                         }
1685                                         else
1686                                         {
1687                                                 if (!(surf->flags & SURF_PLANEBACK))
1688                                                         surfacevisframes[n] = r_framecount;
1689                                         }
1690                                 }
1691 #else
1692                                 surfacevisframes[*mark++] = r_framecount;
1693 #endif
1694                         }
1695                 }
1696                 // follow portals into other leafs
1697                 for (p = leaf->portals;p;p = p->next)
1698                 {
1699                         // LordHavoc: this DotProduct hurts less than a cache miss
1700                         // (which is more likely to happen if backflowing through leafs)
1701                         if (DotProduct(modelorg, p->plane.normal) < (p->plane.dist + 1))
1702                         {
1703                                 leaf = p->past;
1704                                 if (leaf->worldnodeframe != r_framecount)
1705                                 {
1706                                         leaf->worldnodeframe = r_framecount;
1707                                         // FIXME: R_CullBox is absolute, should be done relative
1708                                         bitnum = (leaf - ent->model->brushq1.leafs) - 1;
1709                                         if ((r_pvsbits[bitnum >> 3] & (1 << (bitnum & 7))) && !R_CullBox(leaf->mins, leaf->maxs))
1710                                                 leafstack[leafstackpos++] = leaf;
1711                                 }
1712                         }
1713                 }
1714         }
1715 }
1716
1717 void R_PVSUpdate (entity_render_t *ent, mleaf_t *viewleaf)
1718 {
1719         int j, c, *surfacepvsframes, *mark;
1720         mleaf_t *leaf;
1721         model_t *model;
1722
1723         model = ent->model;
1724         if (model && (model->brushq1.pvsviewleaf != viewleaf || model->brushq1.pvsviewleafnovis != r_novis.integer))
1725         {
1726                 model->brushq1.pvsframecount++;
1727                 model->brushq1.pvsviewleaf = viewleaf;
1728                 model->brushq1.pvsviewleafnovis = r_novis.integer;
1729                 model->brushq1.pvsleafchain = NULL;
1730                 model->brushq1.pvssurflistlength = 0;
1731                 if (viewleaf)
1732                 {
1733                         surfacepvsframes = model->brushq1.surfacepvsframes;
1734                         for (j = 0;j < model->brushq1.visleafs;j++)
1735                         {
1736                                 if (r_pvsbits[j >> 3] & (1 << (j & 7)))
1737                                 {
1738                                         leaf = model->brushq1.leafs + j + 1;
1739                                         leaf->pvsframe = model->brushq1.pvsframecount;
1740                                         leaf->pvschain = model->brushq1.pvsleafchain;
1741                                         model->brushq1.pvsleafchain = leaf;
1742                                         // mark surfaces bounding this leaf as visible
1743                                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--, mark++)
1744                                                 surfacepvsframes[*mark] = model->brushq1.pvsframecount;
1745                                 }
1746                         }
1747                         model->brushq1.BuildPVSTextureChains(model);
1748                 }
1749         }
1750 }
1751
1752 void R_WorldVisibility(entity_render_t *ent)
1753 {
1754         vec3_t modelorg;
1755         mleaf_t *viewleaf;
1756
1757         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1758         viewleaf = (ent->model && ent->model->brushq1.PointInLeaf) ? ent->model->brushq1.PointInLeaf(ent->model, modelorg) : NULL;
1759         R_PVSUpdate(ent, viewleaf);
1760
1761         if (!viewleaf)
1762                 return;
1763
1764         if (r_surfaceworldnode.integer || viewleaf->contents == CONTENTS_SOLID)
1765                 R_SurfaceWorldNode (ent);
1766         else
1767                 R_PortalWorldNode (ent, viewleaf);
1768 }
1769
1770 void R_DrawWorld(entity_render_t *ent)
1771 {
1772         if (ent->model == NULL)
1773                 return;
1774         if (!ent->model->brushq1.numleafs && ent->model->Draw)
1775                 ent->model->Draw(ent);
1776         else
1777         {
1778                 R_PrepareSurfaces(ent);
1779                 R_DrawSurfaces(ent, SHADERSTAGE_SKY, ent->model->brushq1.pvstexturechains);
1780                 R_DrawSurfaces(ent, SHADERSTAGE_NORMAL, ent->model->brushq1.pvstexturechains);
1781                 if (r_drawportals.integer)
1782                         R_DrawPortals(ent);
1783         }
1784 }
1785
1786 void R_Model_Brush_DrawSky(entity_render_t *ent)
1787 {
1788         if (ent->model == NULL)
1789                 return;
1790         if (ent != &cl_entities[0].render)
1791                 R_PrepareBrushModel(ent);
1792         R_DrawSurfaces(ent, SHADERSTAGE_SKY, ent->model->brushq1.pvstexturechains);
1793 }
1794
1795 void R_Model_Brush_Draw(entity_render_t *ent)
1796 {
1797         if (ent->model == NULL)
1798                 return;
1799         c_bmodels++;
1800         if (ent != &cl_entities[0].render)
1801                 R_PrepareBrushModel(ent);
1802         R_DrawSurfaces(ent, SHADERSTAGE_NORMAL, ent->model->brushq1.pvstexturechains);
1803 }
1804
1805 void R_Model_Brush_DrawShadowVolume (entity_render_t *ent, vec3_t relativelightorigin, float lightradius)
1806 {
1807         int i;
1808         msurface_t *surf;
1809         float projectdistance, f, temp[3], lightradius2;
1810         surfmesh_t *mesh;
1811         if (ent->model == NULL)
1812                 return;
1813         R_Mesh_Matrix(&ent->matrix);
1814         lightradius2 = lightradius * lightradius;
1815         R_UpdateTextureInfo(ent);
1816         projectdistance = 1000000000.0f;//lightradius + ent->model->radius;
1817         for (i = 0, surf = ent->model->brushq1.surfaces + ent->model->brushq1.firstmodelsurface;i < ent->model->brushq1.nummodelsurfaces;i++, surf++)
1818         {
1819                 if (surf->texinfo->texture->rendertype == SURFRENDER_OPAQUE && surf->flags & SURF_SHADOWCAST)
1820                 {
1821                         f = PlaneDiff(relativelightorigin, surf->plane);
1822                         if (surf->flags & SURF_PLANEBACK)
1823                                 f = -f;
1824                         // draw shadows only for frontfaces and only if they are close
1825                         if (f >= 0.1 && f < lightradius)
1826                         {
1827                                 temp[0] = bound(surf->poly_mins[0], relativelightorigin[0], surf->poly_maxs[0]) - relativelightorigin[0];
1828                                 temp[1] = bound(surf->poly_mins[1], relativelightorigin[1], surf->poly_maxs[1]) - relativelightorigin[1];
1829                                 temp[2] = bound(surf->poly_mins[2], relativelightorigin[2], surf->poly_maxs[2]) - relativelightorigin[2];
1830                                 if (DotProduct(temp, temp) < lightradius2)
1831                                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1832                                                 R_Shadow_Volume(mesh->numverts, mesh->numtriangles, mesh->vertex3f, mesh->element3i, mesh->neighbor3i, relativelightorigin, lightradius, projectdistance);
1833                         }
1834                 }
1835         }
1836 }
1837
1838 void R_Model_Brush_DrawLightForSurfaceList(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor, msurface_t **surflist, int numsurfaces, const matrix4x4_t *matrix_modeltofilter, const matrix4x4_t *matrix_modeltoattenuationxyz, const matrix4x4_t *matrix_modeltoattenuationz)
1839 {
1840         int surfnum;
1841         msurface_t *surf;
1842         texture_t *t;
1843         surfmesh_t *mesh;
1844         if (ent->model == NULL)
1845                 return;
1846         R_Mesh_Matrix(&ent->matrix);
1847         R_UpdateTextureInfo(ent);
1848         for (surfnum = 0;surfnum < numsurfaces;surfnum++)
1849         {
1850                 surf = surflist[surfnum];
1851                 if (surf->visframe == r_framecount)
1852                 {
1853                         t = surf->texinfo->texture->currentframe;
1854                         if (t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1855                         {
1856                                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1857                                 {
1858                                         R_Shadow_DiffuseLighting(mesh->numverts, mesh->numtriangles, mesh->element3i, mesh->vertex3f, mesh->svector3f, mesh->tvector3f, mesh->normal3f, mesh->texcoordtexture2f, relativelightorigin, lightradius, lightcolor, matrix_modeltofilter, matrix_modeltoattenuationxyz, matrix_modeltoattenuationz, t->skin.base, t->skin.nmap, NULL);
1859                                         R_Shadow_SpecularLighting(mesh->numverts, mesh->numtriangles, mesh->element3i, mesh->vertex3f, mesh->svector3f, mesh->tvector3f, mesh->normal3f, mesh->texcoordtexture2f, relativelightorigin, relativeeyeorigin, lightradius, lightcolor, matrix_modeltofilter, matrix_modeltoattenuationxyz, matrix_modeltoattenuationz, t->skin.gloss, t->skin.nmap, NULL);
1860                                 }
1861                         }
1862                 }
1863         }
1864 }
1865
1866 void R_Model_Brush_DrawLight(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor, const matrix4x4_t *matrix_modeltofilter, const matrix4x4_t *matrix_modeltoattenuationxyz, const matrix4x4_t *matrix_modeltoattenuationz)
1867 {
1868         int surfnum;
1869         msurface_t *surf;
1870         texture_t *t;
1871         float f, lightmins[3], lightmaxs[3];
1872         surfmesh_t *mesh;
1873         if (ent->model == NULL)
1874                 return;
1875         R_Mesh_Matrix(&ent->matrix);
1876         lightmins[0] = relativelightorigin[0] - lightradius;
1877         lightmins[1] = relativelightorigin[1] - lightradius;
1878         lightmins[2] = relativelightorigin[2] - lightradius;
1879         lightmaxs[0] = relativelightorigin[0] + lightradius;
1880         lightmaxs[1] = relativelightorigin[1] + lightradius;
1881         lightmaxs[2] = relativelightorigin[2] + lightradius;
1882         R_UpdateTextureInfo(ent);
1883         for (surfnum = 0, surf = ent->model->brushq1.surfaces + ent->model->brushq1.firstmodelsurface;surfnum < ent->model->brushq1.nummodelsurfaces;surfnum++, surf++)
1884         {
1885                 if ((ent != &cl_entities[0].render || surf->visframe == r_framecount) && BoxesOverlap(surf->poly_mins, surf->poly_maxs, lightmins, lightmaxs))
1886                 {
1887                         f = PlaneDiff(relativelightorigin, surf->plane);
1888                         if (surf->flags & SURF_PLANEBACK)
1889                                 f = -f;
1890                         if (f >= -0.1 && f < lightradius)
1891                         {
1892                                 t = surf->texinfo->texture->currentframe;
1893                                 if (t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1894                                 {
1895                                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1896                                         {
1897                                                 R_Shadow_DiffuseLighting(mesh->numverts, mesh->numtriangles, mesh->element3i, mesh->vertex3f, mesh->svector3f, mesh->tvector3f, mesh->normal3f, mesh->texcoordtexture2f, relativelightorigin, lightradius, lightcolor, matrix_modeltofilter, matrix_modeltoattenuationxyz, matrix_modeltoattenuationz, t->skin.base, t->skin.nmap, NULL);
1898                                                 R_Shadow_SpecularLighting(mesh->numverts, mesh->numtriangles, mesh->element3i, mesh->vertex3f, mesh->svector3f, mesh->tvector3f, mesh->normal3f, mesh->texcoordtexture2f, relativelightorigin, relativeeyeorigin, lightradius, lightcolor, matrix_modeltofilter, matrix_modeltoattenuationxyz, matrix_modeltoattenuationz, t->skin.gloss, t->skin.nmap, NULL);
1899                                         }
1900                                 }
1901                         }
1902                 }
1903         }
1904 }
1905
1906 void R_DrawCollisionBrush(colbrushf_t *brush)
1907 {
1908         int i;
1909         i = ((int)brush) / sizeof(colbrushf_t);
1910         GL_Color((i & 31) * (1.0f / 32.0f) * r_colorscale, ((i >> 5) & 31) * (1.0f / 32.0f) * r_colorscale, ((i >> 10) & 31) * (1.0f / 32.0f) * r_colorscale, 0.2f);
1911         GL_VertexPointer(brush->points->v);
1912         R_Mesh_Draw(brush->numpoints, brush->numtriangles, brush->elements);
1913 }
1914
1915 void R_Q3BSP_DrawFace(entity_render_t *ent, q3mface_t *face)
1916 {
1917         rmeshstate_t m;
1918         if ((face->texture->renderflags & Q3MTEXTURERENDERFLAGS_NODRAW) || !face->numtriangles || R_CullBox(face->mins, face->maxs))
1919                 return;
1920         memset(&m, 0, sizeof(m));
1921         GL_BlendFunc(GL_ONE, GL_ZERO);
1922         GL_DepthMask(true);
1923         GL_DepthTest(true);
1924         m.tex[0] = R_GetTexture(face->texture->skin.base);
1925         m.pointer_texcoord[0] = face->data_texcoordtexture2f;
1926         if (face->lightmaptexture)
1927         {
1928                 m.tex[1] = R_GetTexture(face->lightmaptexture);
1929                 m.pointer_texcoord[1] = face->data_texcoordlightmap2f;
1930                 m.texrgbscale[1] = 2;
1931                 GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1932         }
1933         else
1934         {
1935                 m.texrgbscale[0] = 2;
1936                 GL_ColorPointer(face->data_color4f);
1937         }
1938         R_Mesh_State_Texture(&m);
1939         GL_VertexPointer(face->data_vertex3f);
1940         R_Mesh_Draw(face->numvertices, face->numtriangles, face->data_element3i);
1941 }
1942
1943 /*
1944 void R_Q3BSP_DrawSky(entity_render_t *ent)
1945 {
1946 }
1947 */
1948
1949 void R_Q3BSP_RecursiveWorldNode(entity_render_t *ent, q3mnode_t *node, const vec3_t modelorg, qbyte *pvs, int markframe)
1950 {
1951         int i;
1952         q3mleaf_t *leaf;
1953         q3mface_t *face;
1954         while (node->isnode)
1955         {
1956                 if (R_CullBox(node->mins, node->maxs))
1957                         return;
1958                 R_Q3BSP_RecursiveWorldNode(ent, node->children[0], modelorg, pvs, markframe);
1959                 node = node->children[1];
1960         }
1961         if (R_CullBox(node->mins, node->maxs))
1962                 return;
1963         leaf = (q3mleaf_t *)node;
1964         if (pvs[leaf->clusterindex >> 3] & (1 << (leaf->clusterindex & 7)))
1965         {
1966                 for (i = 0;i < leaf->numleaffaces;i++)
1967                 {
1968                         face = leaf->firstleafface[i];
1969                         if (face->markframe != markframe)
1970                         {
1971                                 face->markframe = markframe;
1972                                 R_Q3BSP_DrawFace(ent, face);
1973                         }
1974                 }
1975         }
1976 }
1977
1978
1979
1980 void R_Q3BSP_Draw(entity_render_t *ent)
1981 {
1982         int i;
1983         q3mface_t *face;
1984         vec3_t modelorg;
1985         model_t *model;
1986         qbyte *pvs;
1987         static int markframe = 0;
1988         qglEnable(GL_POLYGON_OFFSET_FILL);
1989         R_Mesh_Matrix(&ent->matrix);
1990         model = ent->model;
1991         if (r_drawcollisionbrushes.integer < 2)
1992         {
1993                 qglPolygonOffset(1.0f, 0);
1994                 Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1995                 if (ent == &cl_entities[0].render && model->brushq3.num_pvsclusters && !r_novis.integer && (pvs = model->brush.GetPVS(model, modelorg)))
1996                         R_Q3BSP_RecursiveWorldNode(ent, model->brushq3.data_nodes, modelorg, pvs, ++markframe);
1997                 else
1998                         for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
1999                                 R_Q3BSP_DrawFace(ent, face);
2000         }
2001         if (r_drawcollisionbrushes.integer >= 1)
2002         {
2003                 rmeshstate_t m;
2004                 memset(&m, 0, sizeof(m));
2005                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2006                 GL_DepthMask(false);
2007                 GL_DepthTest(true);
2008                 R_Mesh_State_Texture(&m);
2009                 qglPolygonOffset(1.0f, r_drawcollisionbrushes_polygonoffset.value);
2010                 for (i = 0;i < model->brushq3.data_thismodel->numbrushes;i++)
2011                         if (model->brushq3.data_thismodel->firstbrush[i].colbrushf && model->brushq3.data_thismodel->firstbrush[i].colbrushf->numtriangles)
2012                                 R_DrawCollisionBrush(model->brushq3.data_thismodel->firstbrush[i].colbrushf);
2013         }
2014         qglDisable(GL_POLYGON_OFFSET_FILL);
2015 }
2016
2017 /*
2018 void R_Q3BSP_DrawFakeShadow(entity_render_t *ent)
2019 {
2020 }
2021 */
2022
2023 /*
2024 void R_Q3BSP_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius)
2025 {
2026 }
2027 */
2028
2029 void R_Q3BSP_DrawLight(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor, const matrix4x4_t *matrix_modeltofilter, const matrix4x4_t *matrix_modeltoattenuationxyz, const matrix4x4_t *matrix_modeltoattenuationz)
2030 {
2031 }
2032
2033 static void gl_surf_start(void)
2034 {
2035 }
2036
2037 static void gl_surf_shutdown(void)
2038 {
2039 }
2040
2041 static void gl_surf_newmap(void)
2042 {
2043 }
2044
2045 void GL_Surf_Init(void)
2046 {
2047         int i;
2048         dlightdivtable[0] = 4194304;
2049         for (i = 1;i < 32768;i++)
2050                 dlightdivtable[i] = 4194304 / (i << 7);
2051
2052         Cvar_RegisterVariable(&r_ambient);
2053         Cvar_RegisterVariable(&r_vertexsurfaces);
2054         Cvar_RegisterVariable(&r_dlightmap);
2055         Cvar_RegisterVariable(&r_drawportals);
2056         Cvar_RegisterVariable(&r_testvis);
2057         Cvar_RegisterVariable(&r_floatbuildlightmap);
2058         Cvar_RegisterVariable(&r_detailtextures);
2059         Cvar_RegisterVariable(&r_surfaceworldnode);
2060         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonoffset);
2061
2062         R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
2063 }
2064