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