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