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