fixed bumpmapping! now looks correct
[divverent/darkplaces.git] / gl_rsurf.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_surf.c: surface-related refresh code
21
22 #include "quakedef.h"
23 #include "r_shadow.h"
24
25 #define MAX_LIGHTMAP_SIZE 256
26
27 static unsigned int intblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
28 static float floatblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
29
30 static qbyte templight[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*4];
31
32 cvar_t r_ambient = {0, "r_ambient", "0"};
33 cvar_t r_vertexsurfaces = {0, "r_vertexsurfaces", "0"};
34 cvar_t r_dlightmap = {CVAR_SAVE, "r_dlightmap", "1"};
35 cvar_t r_drawportals = {0, "r_drawportals", "0"};
36 cvar_t r_testvis = {0, "r_testvis", "0"};
37 cvar_t r_floatbuildlightmap = {0, "r_floatbuildlightmap", "0"};
38 cvar_t r_detailtextures = {CVAR_SAVE, "r_detailtextures", "1"};
39 cvar_t r_surfaceworldnode = {0, "r_surfaceworldnode", "1"};
40
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         int i;
790         const entity_render_t *ent = calldata1;
791         const msurface_t *surf = ent->model->surfaces + calldata2;
792         float f, colorscale, scroll[2], *v;
793         const surfmesh_t *mesh;
794         rmeshstate_t m;
795         float alpha;
796         float modelorg[3];
797         texture_t *texture;
798         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
799
800         R_Mesh_Matrix(&ent->matrix);
801
802         memset(&m, 0, sizeof(m));
803         texture = surf->texinfo->texture->currentframe;
804         alpha = texture->currentalpha;
805         if (texture->rendertype == SURFRENDER_ADD)
806         {
807                 m.blendfunc1 = GL_SRC_ALPHA;
808                 m.blendfunc2 = GL_ONE;
809         }
810         else if (texture->rendertype == SURFRENDER_ALPHA)
811         {
812                 m.blendfunc1 = GL_SRC_ALPHA;
813                 m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
814         }
815         else
816         {
817                 m.blendfunc1 = GL_ONE;
818                 m.blendfunc2 = GL_ZERO;
819         }
820         m.tex[0] = R_GetTexture(texture->skin.base);
821         colorscale = r_colorscale;
822         if (gl_combine.integer)
823         {
824                 m.texrgbscale[0] = 4;
825                 colorscale *= 0.25f;
826         }
827         R_Mesh_State(&m);
828         GL_UseColorArray();
829         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
830         {
831                 R_Mesh_ResizeCheck(mesh->numverts);
832                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
833                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
834                 scroll[0] = sin(cl.time) * 0.125f;
835                 scroll[1] = sin(cl.time * 0.8f) * 0.125f;
836                 for (i = 0, v = varray_texcoord[0];i < mesh->numverts;i++, v += 4)
837                 {
838                         v[0] += scroll[0];
839                         v[1] += scroll[1];
840                 }
841                 f = surf->flags & SURF_DRAWFULLBRIGHT ? 1.0f : ((surf->flags & SURF_LIGHTMAP) ? 0 : 0.5f);
842                 R_FillColors(varray_color, mesh->numverts, f, f, f, alpha);
843                 if (!(surf->flags & SURF_DRAWFULLBRIGHT || ent->effects & EF_FULLBRIGHT))
844                 {
845                         if (surf->dlightframe == r_framecount)
846                                 RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
847                         if (surf->flags & SURF_LIGHTMAP)
848                                 RSurf_AddLightmapToVertexColors(mesh->lightmapoffsets, varray_color, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
849                 }
850                 RSurf_FogColors(varray_vertex, varray_color, colorscale, mesh->numverts, modelorg);
851                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
852         }
853
854         if (fogenabled)
855         {
856                 memset(&m, 0, sizeof(m));
857                 m.blendfunc1 = GL_SRC_ALPHA;
858                 m.blendfunc2 = GL_ONE;
859                 m.tex[0] = R_GetTexture(texture->skin.fog);
860                 R_Mesh_State(&m);
861                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
862                 {
863                         R_Mesh_ResizeCheck(mesh->numverts);
864                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
865                         if (m.tex[0])
866                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
867                         RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], alpha, r_colorscale, mesh->numverts, modelorg);
868                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
869                 }
870         }
871 }
872
873 static void RSurfShader_Water(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
874 {
875         const msurface_t *surf;
876         msurface_t **chain;
877         vec3_t center;
878         if (texture->rendertype != SURFRENDER_OPAQUE)
879         {
880                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
881                 {
882                         if (surf->visframe == r_framecount)
883                         {
884                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
885                                 R_MeshQueue_AddTransparent(center, RSurfShader_Water_Callback, ent, surf - ent->model->surfaces);
886                         }
887                 }
888         }
889         else
890                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
891                         if (surf->visframe == r_framecount)
892                                 RSurfShader_Water_Callback(ent, surf - ent->model->surfaces);
893 }
894
895 static void RSurfShader_Wall_Pass_BaseVertex(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
896 {
897         float base, colorscale;
898         const surfmesh_t *mesh;
899         rmeshstate_t m;
900         float modelorg[3];
901         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
902         memset(&m, 0, sizeof(m));
903         if (rendertype == SURFRENDER_ADD)
904         {
905                 m.blendfunc1 = GL_SRC_ALPHA;
906                 m.blendfunc2 = GL_ONE;
907         }
908         else if (rendertype == SURFRENDER_ALPHA)
909         {
910                 m.blendfunc1 = GL_SRC_ALPHA;
911                 m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
912         }
913         else
914         {
915                 m.blendfunc1 = GL_ONE;
916                 m.blendfunc2 = GL_ZERO;
917         }
918         m.tex[0] = R_GetTexture(texture->skin.base);
919         colorscale = r_colorscale;
920         if (gl_combine.integer)
921         {
922                 m.texrgbscale[0] = 4;
923                 colorscale *= 0.25f;
924         }
925         base = ent->effects & EF_FULLBRIGHT ? 2.0f : r_ambient.value * (1.0f / 64.0f);
926         R_Mesh_State(&m);
927         GL_UseColorArray();
928         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
929         {
930                 R_Mesh_ResizeCheck(mesh->numverts);
931                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
932                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
933                 R_FillColors(varray_color, mesh->numverts, base, base, base, currentalpha);
934                 if (!(ent->effects & EF_FULLBRIGHT))
935                 {
936                         if (surf->dlightframe == r_framecount)
937                                 RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
938                         if (surf->flags & SURF_LIGHTMAP)
939                                 RSurf_AddLightmapToVertexColors(mesh->lightmapoffsets, varray_color, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
940                 }
941                 RSurf_FogColors(varray_vertex, varray_color, colorscale, mesh->numverts, modelorg);
942                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
943         }
944 }
945
946 static void RSurfShader_Wall_Pass_Glow(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
947 {
948         const surfmesh_t *mesh;
949         rmeshstate_t m;
950         float modelorg[3];
951         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
952         memset(&m, 0, sizeof(m));
953         m.blendfunc1 = GL_SRC_ALPHA;
954         m.blendfunc2 = GL_ONE;
955         m.tex[0] = R_GetTexture(texture->skin.glow);
956         R_Mesh_State(&m);
957         GL_UseColorArray();
958         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
959         {
960                 R_Mesh_ResizeCheck(mesh->numverts);
961                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
962                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
963                 RSurf_FoggedColors(varray_vertex, varray_color, 1, 1, 1, currentalpha, r_colorscale, mesh->numverts, modelorg);
964                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
965         }
966 }
967
968 static void RSurfShader_Wall_Pass_Fog(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
969 {
970         const surfmesh_t *mesh;
971         rmeshstate_t m;
972         float modelorg[3];
973         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
974         memset(&m, 0, sizeof(m));
975         m.blendfunc1 = GL_SRC_ALPHA;
976         m.blendfunc2 = GL_ONE;
977         m.tex[0] = R_GetTexture(texture->skin.fog);
978         R_Mesh_State(&m);
979         GL_UseColorArray();
980         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
981         {
982                 R_Mesh_ResizeCheck(mesh->numverts);
983                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
984                 if (m.tex[0])
985                         memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
986                 RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], currentalpha, r_colorscale, mesh->numverts, modelorg);
987                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
988         }
989 }
990
991 static void RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
992 {
993         const msurface_t *surf;
994         const surfmesh_t *mesh;
995         rmeshstate_t m;
996         int lightmaptexturenum;
997         float cl;
998         memset(&m, 0, sizeof(m));
999         m.blendfunc1 = GL_ONE;
1000         m.blendfunc2 = GL_ZERO;
1001         m.tex[0] = R_GetTexture(texture->skin.base);
1002         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1003         m.tex[2] = R_GetTexture(texture->skin.detail);
1004         m.texrgbscale[0] = 1;
1005         m.texrgbscale[1] = 4;
1006         m.texrgbscale[2] = 2;
1007         R_Mesh_State(&m);
1008         cl = (float) (1 << r_lightmapscalebit) * r_colorscale;
1009         GL_Color(cl, cl, cl, 1);
1010         while((surf = *surfchain++) != NULL)
1011         {
1012                 if (surf->visframe == r_framecount)
1013                 {
1014                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1015                         if (m.tex[1] != lightmaptexturenum)
1016                         {
1017                                 m.tex[1] = lightmaptexturenum;
1018                                 R_Mesh_State(&m);
1019                         }
1020                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1021                         {
1022                                 R_Mesh_ResizeCheck(mesh->numverts);
1023                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1024                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1025                                 memcpy(varray_texcoord[1], mesh->uvw, mesh->numverts * sizeof(float[4]));
1026                                 memcpy(varray_texcoord[2], mesh->abc, mesh->numverts * sizeof(float[4]));
1027                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1028                         }
1029                 }
1030         }
1031 }
1032
1033 static void RSurfShader_OpaqueWall_Pass_BaseDoubleTex(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1034 {
1035         const msurface_t *surf;
1036         const surfmesh_t *mesh;
1037         rmeshstate_t m;
1038         int lightmaptexturenum;
1039         memset(&m, 0, sizeof(m));
1040         m.blendfunc1 = GL_ONE;
1041         m.blendfunc2 = GL_ZERO;
1042         m.tex[0] = R_GetTexture(texture->skin.base);
1043         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1044         if (gl_combine.integer)
1045                 m.texrgbscale[1] = 4;
1046         R_Mesh_State(&m);
1047         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1048         while((surf = *surfchain++) != NULL)
1049         {
1050                 if (surf->visframe == r_framecount)
1051                 {
1052                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1053                         if (m.tex[1] != lightmaptexturenum)
1054                         {
1055                                 m.tex[1] = lightmaptexturenum;
1056                                 R_Mesh_State(&m);
1057                         }
1058                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1059                         {
1060                                 R_Mesh_ResizeCheck(mesh->numverts);
1061                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1062                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1063                                 memcpy(varray_texcoord[1], mesh->uvw, mesh->numverts * sizeof(float[4]));
1064                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1065                         }
1066                 }
1067         }
1068 }
1069
1070 static void RSurfShader_OpaqueWall_Pass_BaseTexture(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1071 {
1072         const msurface_t *surf;
1073         const surfmesh_t *mesh;
1074         rmeshstate_t m;
1075         memset(&m, 0, sizeof(m));
1076         m.blendfunc1 = GL_ONE;
1077         m.blendfunc2 = GL_ZERO;
1078         m.tex[0] = R_GetTexture(texture->skin.base);
1079         R_Mesh_State(&m);
1080         GL_Color(1, 1, 1, 1);
1081         while((surf = *surfchain++) != NULL)
1082         {
1083                 if (surf->visframe == r_framecount)
1084                 {
1085                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1086                         {
1087                                 R_Mesh_ResizeCheck(mesh->numverts);
1088                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1089                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1090                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1091                         }
1092                 }
1093         }
1094 }
1095
1096 static void RSurfShader_OpaqueWall_Pass_BaseLightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1097 {
1098         const msurface_t *surf;
1099         const surfmesh_t *mesh;
1100         rmeshstate_t m;
1101         int lightmaptexturenum;
1102         memset(&m, 0, sizeof(m));
1103         m.blendfunc1 = GL_ZERO;
1104         m.blendfunc2 = GL_SRC_COLOR;
1105         m.tex[0] = R_GetTexture((**surfchain).lightmaptexture);
1106         if (gl_combine.integer)
1107                 m.texrgbscale[0] = 4;
1108         R_Mesh_State(&m);
1109         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1110         while((surf = *surfchain++) != NULL)
1111         {
1112                 if (surf->visframe == r_framecount)
1113                 {
1114                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1115                         if (m.tex[0] != lightmaptexturenum)
1116                         {
1117                                 m.tex[0] = lightmaptexturenum;
1118                                 R_Mesh_State(&m);
1119                         }
1120                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1121                         {
1122                                 R_Mesh_ResizeCheck(mesh->numverts);
1123                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1124                                 memcpy(varray_texcoord[0], mesh->uvw, mesh->numverts * sizeof(float[4]));
1125                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1126                         }
1127                 }
1128         }
1129 }
1130
1131 static void RSurfShader_OpaqueWall_Pass_Light(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1132 {
1133         const msurface_t *surf;
1134         const surfmesh_t *mesh;
1135         float colorscale;
1136         rmeshstate_t m;
1137
1138         memset(&m, 0, sizeof(m));
1139         m.blendfunc1 = GL_SRC_ALPHA;
1140         m.blendfunc2 = GL_ONE;
1141         m.tex[0] = R_GetTexture(texture->skin.base);
1142         colorscale = r_colorscale;
1143         if (gl_combine.integer)
1144         {
1145                 m.texrgbscale[0] = 4;
1146                 colorscale *= 0.25f;
1147         }
1148         R_Mesh_State(&m);
1149         GL_UseColorArray();
1150         while((surf = *surfchain++) != NULL)
1151         {
1152                 if (surf->visframe == r_framecount && surf->dlightframe == r_framecount)
1153                 {
1154                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1155                         {
1156                                 if (RSurf_LightCheck(&ent->inversematrix, surf->dlightbits, mesh))
1157                                 {
1158                                         R_Mesh_ResizeCheck(mesh->numverts);
1159                                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1160                                         memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1161                                         R_FillColors(varray_color, mesh->numverts, 0, 0, 0, 1);
1162                                         RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
1163                                         RSurf_ScaleColors(varray_color, colorscale, mesh->numverts);
1164                                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1165                                 }
1166                         }
1167                 }
1168         }
1169 }
1170
1171 static void RSurfShader_OpaqueWall_Pass_Fog(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1172 {
1173         const msurface_t *surf;
1174         const surfmesh_t *mesh;
1175         rmeshstate_t m;
1176         float modelorg[3];
1177         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1178         memset(&m, 0, sizeof(m));
1179         m.blendfunc1 = GL_SRC_ALPHA;
1180         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
1181         R_Mesh_State(&m);
1182         GL_UseColorArray();
1183         while((surf = *surfchain++) != NULL)
1184         {
1185                 if (surf->visframe == r_framecount)
1186                 {
1187                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1188                         {
1189                                 R_Mesh_ResizeCheck(mesh->numverts);
1190                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1191                                 if (m.tex[0])
1192                                         memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1193                                 RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], 1, r_colorscale, mesh->numverts, modelorg);
1194                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1195                         }
1196                 }
1197         }
1198 }
1199
1200 static void RSurfShader_OpaqueWall_Pass_BaseDetail(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1201 {
1202         const msurface_t *surf;
1203         const surfmesh_t *mesh;
1204         rmeshstate_t m;
1205         memset(&m, 0, sizeof(m));
1206         m.blendfunc1 = GL_DST_COLOR;
1207         m.blendfunc2 = GL_SRC_COLOR;
1208         m.tex[0] = R_GetTexture(texture->skin.detail);
1209         R_Mesh_State(&m);
1210         GL_Color(1, 1, 1, 1);
1211         while((surf = *surfchain++) != NULL)
1212         {
1213                 if (surf->visframe == r_framecount)
1214                 {
1215                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1216                         {
1217                                 R_Mesh_ResizeCheck(mesh->numverts);
1218                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1219                                 memcpy(varray_texcoord[0], mesh->abc, mesh->numverts * sizeof(float[4]));
1220                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1221                         }
1222                 }
1223         }
1224 }
1225
1226 static void RSurfShader_OpaqueWall_Pass_Glow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1227 {
1228         const msurface_t *surf;
1229         const surfmesh_t *mesh;
1230         rmeshstate_t m;
1231         memset(&m, 0, sizeof(m));
1232         m.blendfunc1 = GL_SRC_ALPHA;
1233         m.blendfunc2 = GL_ONE;
1234         m.tex[0] = R_GetTexture(texture->skin.glow);
1235         R_Mesh_State(&m);
1236         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1237         while((surf = *surfchain++) != NULL)
1238         {
1239                 if (surf->visframe == r_framecount)
1240                 {
1241                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1242                         {
1243                                 R_Mesh_ResizeCheck(mesh->numverts);
1244                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1245                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1246                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1247                         }
1248                 }
1249         }
1250 }
1251
1252 static void RSurfShader_OpaqueWall_Pass_OpaqueGlow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1253 {
1254         const msurface_t *surf;
1255         const surfmesh_t *mesh;
1256         rmeshstate_t m;
1257         memset(&m, 0, sizeof(m));
1258         m.blendfunc1 = GL_SRC_ALPHA;
1259         m.blendfunc2 = GL_ZERO;
1260         m.tex[0] = R_GetTexture(texture->skin.glow);
1261         R_Mesh_State(&m);
1262         if (m.tex[0])
1263                 GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1264         else
1265                 GL_Color(0, 0, 0, 1);
1266         while((surf = *surfchain++) != NULL)
1267         {
1268                 if (surf->visframe == r_framecount)
1269                 {
1270                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1271                         {
1272                                 R_Mesh_ResizeCheck(mesh->numverts);
1273                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1274                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1275                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1276                         }
1277                 }
1278         }
1279 }
1280
1281 static void RSurfShader_Wall_Vertex_Callback(const void *calldata1, int calldata2)
1282 {
1283         const entity_render_t *ent = calldata1;
1284         const msurface_t *surf = ent->model->surfaces + calldata2;
1285         int rendertype;
1286         float currentalpha;
1287         texture_t *texture;
1288         R_Mesh_Matrix(&ent->matrix);
1289
1290         texture = surf->texinfo->texture;
1291         if (texture->animated)
1292                 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];
1293
1294         currentalpha = ent->alpha;
1295         if (texture->flags & SURF_WATERALPHA)
1296                 currentalpha *= r_wateralpha.value;
1297         if (ent->effects & EF_ADDITIVE)
1298                 rendertype = SURFRENDER_ADD;
1299         else if (currentalpha < 1 || texture->skin.fog != NULL)
1300                 rendertype = SURFRENDER_ALPHA;
1301         else
1302                 rendertype = SURFRENDER_OPAQUE;
1303
1304         RSurfShader_Wall_Pass_BaseVertex(ent, surf, texture, rendertype, currentalpha);
1305         if (texture->skin.glow)
1306                 RSurfShader_Wall_Pass_Glow(ent, surf, texture, rendertype, currentalpha);
1307         if (fogenabled)
1308                 RSurfShader_Wall_Pass_Fog(ent, surf, texture, rendertype, currentalpha);
1309 }
1310
1311 static void RSurfShader_Wall_Lightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1312 {
1313         const msurface_t *surf;
1314         msurface_t **chain;
1315         vec3_t center;
1316         if (texture->rendertype != SURFRENDER_OPAQUE)
1317         {
1318                 // transparent vertex shaded from lightmap
1319                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
1320                 {
1321                         if (surf->visframe == r_framecount)
1322                         {
1323                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
1324                                 R_MeshQueue_AddTransparent(center, RSurfShader_Wall_Vertex_Callback, ent, surf - ent->model->surfaces);
1325                         }
1326                 }
1327         }
1328         else if (r_shadow_lightingmode >= 2)
1329         {
1330                 // opaque base lighting
1331                 RSurfShader_OpaqueWall_Pass_OpaqueGlow(ent, texture, surfchain);
1332                 if (fogenabled)
1333                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1334         }
1335         else if (r_vertexsurfaces.integer)
1336         {
1337                 // opaque vertex shaded from lightmap
1338                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
1339                         if (surf->visframe == r_framecount)
1340                                 RSurfShader_Wall_Pass_BaseVertex(ent, surf, texture, texture->rendertype, texture->currentalpha);
1341                 if (texture->skin.glow)
1342                         for (chain = surfchain;(surf = *chain) != NULL;chain++)
1343                                 if (surf->visframe == r_framecount)
1344                                         RSurfShader_Wall_Pass_Glow(ent, surf, texture, texture->rendertype, texture->currentalpha);
1345                 if (fogenabled)
1346                         for (chain = surfchain;(surf = *chain) != NULL;chain++)
1347                                 if (surf->visframe == r_framecount)
1348                                         RSurfShader_Wall_Pass_Fog(ent, surf, texture, texture->rendertype, texture->currentalpha);
1349         }
1350         else
1351         {
1352                 // opaque lightmapped
1353                 if (r_textureunits.integer >= 2)
1354                 {
1355                         if (r_textureunits.integer >= 3 && gl_combine.integer && r_detailtextures.integer)
1356                                 RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(ent, texture, surfchain);
1357                         else
1358                         {
1359                                 RSurfShader_OpaqueWall_Pass_BaseDoubleTex(ent, texture, surfchain);
1360                                 if (r_detailtextures.integer)
1361                                         RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1362                         }
1363                 }
1364                 else
1365                 {
1366                         RSurfShader_OpaqueWall_Pass_BaseTexture(ent, texture, surfchain);
1367                         RSurfShader_OpaqueWall_Pass_BaseLightmap(ent, texture, surfchain);
1368                         if (r_detailtextures.integer)
1369                                 RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1370                 }
1371                 if (!r_dlightmap.integer && !(ent->effects & EF_FULLBRIGHT))
1372                         RSurfShader_OpaqueWall_Pass_Light(ent, texture, surfchain);
1373                 if (texture->skin.glow)
1374                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture, surfchain);
1375                 if (fogenabled)
1376                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1377         }
1378 }
1379
1380 Cshader_t Cshader_wall_lightmap = {{NULL, RSurfShader_Wall_Lightmap}, SHADERFLAGS_NEEDLIGHTMAP};
1381 Cshader_t Cshader_water = {{NULL, RSurfShader_Water}, 0};
1382 Cshader_t Cshader_sky = {{RSurfShader_Sky, NULL}, 0};
1383
1384 int Cshader_count = 3;
1385 Cshader_t *Cshaders[3] =
1386 {
1387         &Cshader_wall_lightmap,
1388         &Cshader_water,
1389         &Cshader_sky
1390 };
1391
1392 void R_UpdateTextureInfo(entity_render_t *ent)
1393 {
1394         int i, texframe, alttextures;
1395         texture_t *t;
1396
1397         if (!ent->model)
1398                 return;
1399
1400         alttextures = ent->frame != 0;
1401         texframe = (int)(cl.time * 5.0f);
1402         for (i = 0;i < ent->model->numtextures;i++)
1403         {
1404                 t = ent->model->textures + i;
1405                 t->currentalpha = ent->alpha;
1406                 if (t->flags & SURF_WATERALPHA)
1407                         t->currentalpha *= r_wateralpha.value;
1408                 if (ent->effects & EF_ADDITIVE)
1409                         t->rendertype = SURFRENDER_ADD;
1410                 else if (t->currentalpha < 1 || t->skin.fog != NULL)
1411                         t->rendertype = SURFRENDER_ALPHA;
1412                 else
1413                         t->rendertype = SURFRENDER_OPAQUE;
1414                 // we don't need to set currentframe if t->animated is false because
1415                 // it was already set up by the texture loader for non-animating
1416                 if (t->animated)
1417                         t->currentframe = t->anim_frames[alttextures][(t->anim_total[alttextures] >= 2) ? (texframe % t->anim_total[alttextures]) : 0];
1418         }
1419 }
1420
1421 void R_PrepareSurfaces(entity_render_t *ent)
1422 {
1423         int i, numsurfaces, *surfacevisframes;
1424         model_t *model;
1425         msurface_t *surf, *surfaces, **surfchain;
1426         vec3_t modelorg;
1427
1428         if (!ent->model)
1429                 return;
1430
1431         model = ent->model;
1432         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1433         numsurfaces = model->nummodelsurfaces;
1434         surfaces = model->surfaces + model->firstmodelsurface;
1435         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1436
1437         R_UpdateTextureInfo(ent);
1438
1439         if (r_dynamic.integer && r_shadow_lightingmode < 1)
1440                 R_MarkLights(ent);
1441
1442         if (model->light_ambient != r_ambient.value || model->light_scalebit != r_lightmapscalebit)
1443         {
1444                 model->light_ambient = r_ambient.value;
1445                 model->light_scalebit = r_lightmapscalebit;
1446                 for (i = 0;i < model->nummodelsurfaces;i++)
1447                         model->surfaces[i + model->firstmodelsurface].cached_dlight = true;
1448         }
1449         else
1450         {
1451                 for (i = 0;i < model->light_styles;i++)
1452                 {
1453                         if (model->light_stylevalue[i] != d_lightstylevalue[model->light_style[i]])
1454                         {
1455                                 model->light_stylevalue[i] = d_lightstylevalue[model->light_style[i]];
1456                                 for (surfchain = model->light_styleupdatechains[i];*surfchain;surfchain++)
1457                                         (**surfchain).cached_dlight = true;
1458                         }
1459                 }
1460         }
1461
1462         for (i = 0, surf = surfaces;i < numsurfaces;i++, surf++)
1463         {
1464                 if (surfacevisframes[i] == r_framecount)
1465                 {
1466 #if !WORLDNODECULLBACKFACES
1467                         // mark any backface surfaces as not visible
1468                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1469                         {
1470                                 if (!(surf->flags & SURF_PLANEBACK))
1471                                         surfacevisframes[i] = -1;
1472                         }
1473                         else
1474                         {
1475                                 if ((surf->flags & SURF_PLANEBACK))
1476                                         surfacevisframes[i] = -1;
1477                         }
1478                         if (surfacevisframes[i] == r_framecount)
1479 #endif
1480                         {
1481                                 c_faces++;
1482                                 surf->visframe = r_framecount;
1483                                 if (surf->cached_dlight && surf->lightmaptexture != NULL && !r_vertexsurfaces.integer)
1484                                         R_BuildLightMap(ent, surf);
1485                         }
1486                 }
1487         }
1488 }
1489
1490 void R_DrawSurfaces(entity_render_t *ent, int type, msurface_t ***chains)
1491 {
1492         int i;
1493         texture_t *t;
1494         R_Mesh_Matrix(&ent->matrix);
1495         for (i = 0, t = ent->model->textures;i < ent->model->numtextures;i++, t++)
1496                 if (t->shader->shaderfunc[type] && t->currentframe && chains[i] != NULL)
1497                         t->shader->shaderfunc[type](ent, t->currentframe, chains[i]);
1498 }
1499
1500 static void R_DrawPortal_Callback(const void *calldata1, int calldata2)
1501 {
1502         int i;
1503         float *v;
1504         rmeshstate_t m;
1505         const entity_render_t *ent = calldata1;
1506         const mportal_t *portal = ent->model->portals + calldata2;
1507         memset(&m, 0, sizeof(m));
1508         m.blendfunc1 = GL_SRC_ALPHA;
1509         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
1510         R_Mesh_Matrix(&ent->matrix);
1511         R_Mesh_State(&m);
1512         R_Mesh_ResizeCheck(portal->numpoints);
1513         i = portal - ent->model->portals;
1514         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_colorscale,
1515                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_colorscale,
1516                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_colorscale,
1517                          0.125f);
1518         if (PlaneDiff(r_origin, (&portal->plane)) > 0)
1519         {
1520                 for (i = portal->numpoints - 1, v = varray_vertex;i >= 0;i--, v += 4)
1521                         VectorCopy(portal->points[i].position, v);
1522         }
1523         else
1524                 for (i = 0, v = varray_vertex;i < portal->numpoints;i++, v += 4)
1525                         VectorCopy(portal->points[i].position, v);
1526         R_Mesh_Draw(portal->numpoints, portal->numpoints - 2, polygonelements);
1527 }
1528
1529 static void R_DrawPortals(entity_render_t *ent)
1530 {
1531         int i;
1532         mportal_t *portal, *endportal;
1533         float temp[3], center[3], f;
1534         for (portal = ent->model->portals, endportal = portal + ent->model->numportals;portal < endportal;portal++)
1535         {
1536                 if ((portal->here->pvsframe == ent->model->pvsframecount || portal->past->pvsframe == ent->model->pvsframecount) && portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
1537                 {
1538                         VectorClear(temp);
1539                         for (i = 0;i < portal->numpoints;i++)
1540                                 VectorAdd(temp, portal->points[i].position, temp);
1541                         f = ixtable[portal->numpoints];
1542                         VectorScale(temp, f, temp);
1543                         Matrix4x4_Transform(&ent->matrix, temp, center);
1544                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, ent, portal - ent->model->portals);
1545                 }
1546         }
1547 }
1548
1549 void R_PrepareBrushModel(entity_render_t *ent)
1550 {
1551         int i, numsurfaces, *surfacevisframes, *surfacepvsframes;
1552         msurface_t *surf;
1553         model_t *model;
1554 #if WORLDNODECULLBACKFACES
1555         vec3_t modelorg;
1556 #endif
1557
1558         // because bmodels can be reused, we have to decide which things to render
1559         // from scratch every time
1560         model = ent->model;
1561 #if WORLDNODECULLBACKFACES
1562         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1563 #endif
1564         numsurfaces = model->nummodelsurfaces;
1565         surf = model->surfaces + model->firstmodelsurface;
1566         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1567         surfacepvsframes = model->surfacepvsframes + model->firstmodelsurface;
1568         for (i = 0;i < numsurfaces;i++, surf++)
1569         {
1570 #if WORLDNODECULLBACKFACES
1571                 // mark any backface surfaces as not visible
1572                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1573                 {
1574                         if ((surf->flags & SURF_PLANEBACK))
1575                                 surfacevisframes[i] = r_framecount;
1576                 }
1577                 else if (!(surf->flags & SURF_PLANEBACK))
1578                         surfacevisframes[i] = r_framecount;
1579 #else
1580                 surfacevisframes[i] = r_framecount;
1581 #endif
1582                 surf->dlightframe = -1;
1583         }
1584         R_PrepareSurfaces(ent);
1585 }
1586
1587 void R_SurfaceWorldNode (entity_render_t *ent)
1588 {
1589         int i, *surfacevisframes, *surfacepvsframes, surfnum;
1590         msurface_t *surf;
1591         mleaf_t *leaf;
1592         model_t *model;
1593         vec3_t modelorg;
1594
1595         model = ent->model;
1596         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1597         surfacepvsframes = model->surfacepvsframes + model->firstmodelsurface;
1598         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1599
1600         for (leaf = model->pvsleafchain;leaf;leaf = leaf->pvschain)
1601         {
1602                 if (!R_CullBox (leaf->mins, leaf->maxs))
1603                 {
1604                         c_leafs++;
1605                         leaf->visframe = r_framecount;
1606                 }
1607         }
1608
1609         for (i = 0;i < model->pvssurflistlength;i++)
1610         {
1611                 surfnum = model->pvssurflist[i];
1612                 surf = model->surfaces + surfnum;
1613 #if WORLDNODECULLBACKFACES
1614                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1615                 {
1616                         if ((surf->flags & SURF_PLANEBACK) && !R_CullBox (surf->poly_mins, surf->poly_maxs))
1617                                 surfacevisframes[surfnum] = r_framecount;
1618                 }
1619                 else
1620                 {
1621                         if (!(surf->flags & SURF_PLANEBACK) && !R_CullBox (surf->poly_mins, surf->poly_maxs))
1622                                 surfacevisframes[surfnum] = r_framecount;
1623                 }
1624 #else
1625                 if (!R_CullBox (surf->poly_mins, surf->poly_maxs))
1626                         surfacevisframes[surfnum] = r_framecount;
1627 #endif
1628         }
1629 }
1630
1631 static void R_PortalWorldNode(entity_render_t *ent, mleaf_t *viewleaf)
1632 {
1633         int c, leafstackpos, *mark, *surfacevisframes;
1634 #if WORLDNODECULLBACKFACES
1635         int n;
1636         msurface_t *surf;
1637 #endif
1638         mleaf_t *leaf, *leafstack[8192];
1639         mportal_t *p;
1640         vec3_t modelorg;
1641         msurface_t *surfaces;
1642         // LordHavoc: portal-passage worldnode with PVS;
1643         // follows portals leading outward from viewleaf, does not venture
1644         // offscreen or into leafs that are not visible, faster than Quake's
1645         // RecursiveWorldNode
1646         surfaces = ent->model->surfaces;
1647         surfacevisframes = ent->model->surfacevisframes;
1648         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1649         viewleaf->worldnodeframe = r_framecount;
1650         leafstack[0] = viewleaf;
1651         leafstackpos = 1;
1652         while (leafstackpos)
1653         {
1654                 c_leafs++;
1655                 leaf = leafstack[--leafstackpos];
1656                 leaf->visframe = r_framecount;
1657                 // draw any surfaces bounding this leaf
1658                 if (leaf->nummarksurfaces)
1659                 {
1660                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1661                         {
1662 #if WORLDNODECULLBACKFACES
1663                                 n = *mark++;
1664                                 if (surfacevisframes[n] != r_framecount)
1665                                 {
1666                                         surf = surfaces + n;
1667                                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1668                                         {
1669                                                 if ((surf->flags & SURF_PLANEBACK))
1670                                                         surfacevisframes[n] = r_framecount;
1671                                         }
1672                                         else
1673                                         {
1674                                                 if (!(surf->flags & SURF_PLANEBACK))
1675                                                         surfacevisframes[n] = r_framecount;
1676                                         }
1677                                 }
1678 #else
1679                                 surfacevisframes[*mark++] = r_framecount;
1680 #endif
1681                         }
1682                 }
1683                 // follow portals into other leafs
1684                 for (p = leaf->portals;p;p = p->next)
1685                 {
1686                         // LordHavoc: this DotProduct hurts less than a cache miss
1687                         // (which is more likely to happen if backflowing through leafs)
1688                         if (DotProduct(modelorg, p->plane.normal) < (p->plane.dist + 1))
1689                         {
1690                                 leaf = p->past;
1691                                 if (leaf->worldnodeframe != r_framecount)
1692                                 {
1693                                         leaf->worldnodeframe = r_framecount;
1694                                         // FIXME: R_CullBox is absolute, should be done relative
1695                                         if (leaf->pvsframe == ent->model->pvsframecount && !R_CullBox(leaf->mins, leaf->maxs))
1696                                                 leafstack[leafstackpos++] = leaf;
1697                                 }
1698                         }
1699                 }
1700         }
1701         if (r_drawportals.integer)
1702                 R_DrawPortals(ent);
1703 }
1704
1705 void R_PVSUpdate (entity_render_t *ent, mleaf_t *viewleaf)
1706 {
1707         int i, j, l, c, bits, *surfacepvsframes, *mark;
1708         mleaf_t *leaf;
1709         qbyte *vis;
1710         model_t *model;
1711
1712         model = ent->model;
1713         if (model && (model->pvsviewleaf != viewleaf || model->pvsviewleafnovis != r_novis.integer))
1714         {
1715                 model->pvsframecount++;
1716                 model->pvsviewleaf = viewleaf;
1717                 model->pvsviewleafnovis = r_novis.integer;
1718                 model->pvsleafchain = NULL;
1719                 model->pvssurflistlength = 0;
1720                 if (viewleaf)
1721                 {
1722                         surfacepvsframes = model->surfacepvsframes;
1723                         vis = Mod_LeafPVS (viewleaf, model);
1724                         for (j = 0;j < model->numleafs;j += 8)
1725                         {
1726                                 bits = *vis++;
1727                                 if (bits)
1728                                 {
1729                                         l = model->numleafs - j;
1730                                         if (l > 8)
1731                                                 l = 8;
1732                                         for (i = 0;i < l;i++)
1733                                         {
1734                                                 if (bits & (1 << i))
1735                                                 {
1736                                                         leaf = &model->leafs[j + i + 1];
1737                                                         leaf->pvschain = model->pvsleafchain;
1738                                                         model->pvsleafchain = leaf;
1739                                                         leaf->pvsframe = model->pvsframecount;
1740                                                         // mark surfaces bounding this leaf as visible
1741                                                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--, mark++)
1742                                                                 surfacepvsframes[*mark] = model->pvsframecount;
1743                                                 }
1744                                         }
1745                                 }
1746                         }
1747                         Mod_BuildPVSTextureChains(model);
1748                 }
1749         }
1750 }
1751
1752 void R_WorldVisibility (entity_render_t *ent)
1753 {
1754         vec3_t modelorg;
1755         mleaf_t *viewleaf;
1756
1757         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1758         viewleaf = Mod_PointInLeaf (modelorg, ent->model);
1759         R_PVSUpdate(ent, viewleaf);
1760
1761         if (!viewleaf)
1762                 return;
1763
1764         if (r_surfaceworldnode.integer || viewleaf->contents == CONTENTS_SOLID)
1765                 R_SurfaceWorldNode (ent);
1766         else
1767                 R_PortalWorldNode (ent, viewleaf);
1768 }
1769
1770 void R_DrawWorld (entity_render_t *ent)
1771 {
1772         R_PrepareSurfaces(ent);
1773         R_DrawSurfaces(ent, SHADERSTAGE_SKY, ent->model->pvstexturechains);
1774         R_DrawSurfaces(ent, SHADERSTAGE_NORMAL, ent->model->pvstexturechains);
1775 }
1776
1777 void R_Model_Brush_DrawSky (entity_render_t *ent)
1778 {
1779         if (ent != &cl_entities[0].render)
1780                 R_PrepareBrushModel(ent);
1781         R_DrawSurfaces(ent, SHADERSTAGE_SKY, ent->model->pvstexturechains);
1782 }
1783
1784 void R_Model_Brush_Draw (entity_render_t *ent)
1785 {
1786         c_bmodels++;
1787         if (ent != &cl_entities[0].render)
1788                 R_PrepareBrushModel(ent);
1789         R_DrawSurfaces(ent, SHADERSTAGE_NORMAL, ent->model->pvstexturechains);
1790 }
1791
1792 void R_Model_Brush_DrawShadowVolume (entity_render_t *ent, vec3_t relativelightorigin, float lightradius)
1793 {
1794         int i;
1795         msurface_t *surf;
1796         float projectdistance, f, temp[3], lightradius2;
1797         surfmesh_t *mesh;
1798         R_Mesh_Matrix(&ent->matrix);
1799         lightradius2 = lightradius * lightradius;
1800         R_UpdateTextureInfo(ent);
1801         projectdistance = 1000000000.0f;//lightradius + ent->model->radius;
1802         for (i = 0, surf = ent->model->surfaces + ent->model->firstmodelsurface;i < ent->model->nummodelsurfaces;i++, surf++)
1803         {
1804                 if (surf->texinfo->texture->rendertype == SURFRENDER_OPAQUE && surf->flags & SURF_SHADOWCAST)
1805                 {
1806                         f = PlaneDiff(relativelightorigin, surf->plane);
1807                         if (surf->flags & SURF_PLANEBACK)
1808                                 f = -f;
1809                         // draw shadows only for frontfaces and only if they are close
1810                         if (f >= 0.1 && f < lightradius)
1811                         {
1812                                 temp[0] = bound(surf->poly_mins[0], relativelightorigin[0], surf->poly_maxs[0]) - relativelightorigin[0];
1813                                 temp[1] = bound(surf->poly_mins[1], relativelightorigin[1], surf->poly_maxs[1]) - relativelightorigin[1];
1814                                 temp[2] = bound(surf->poly_mins[2], relativelightorigin[2], surf->poly_maxs[2]) - relativelightorigin[2];
1815                                 if (DotProduct(temp, temp) < lightradius2)
1816                                 {
1817                                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1818                                         {
1819                                                 R_Mesh_ResizeCheck(mesh->numverts * 2);
1820                                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1821                                                 R_Shadow_Volume(mesh->numverts, mesh->numtriangles, mesh->index, mesh->triangleneighbors, relativelightorigin, lightradius, projectdistance);
1822                                         }
1823                                 }
1824                         }
1825                 }
1826         }
1827 }
1828
1829 void R_Model_Brush_DrawLightForSurfaceList(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor, msurface_t **surflist, int numsurfaces)
1830 {
1831         int surfnum;
1832         msurface_t *surf;
1833         texture_t *t;
1834         surfmesh_t *mesh;
1835         R_Mesh_Matrix(&ent->matrix);
1836         R_UpdateTextureInfo(ent);
1837         for (surfnum = 0;surfnum < numsurfaces;surfnum++)
1838         {
1839                 surf = surflist[surfnum];
1840                 if (surf->visframe == r_framecount)
1841                 {
1842                         t = surf->texinfo->texture->currentframe;
1843                         if (t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1844                         {
1845                                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1846                                 {
1847                                         R_Mesh_ResizeCheck(mesh->numverts);
1848                                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1849                                         R_Shadow_DiffuseLighting(mesh->numverts, mesh->numtriangles, mesh->index, mesh->svectors, mesh->tvectors, mesh->normals, mesh->str, relativelightorigin, lightradius, lightcolor, t->skin.base, t->skin.nmap, NULL);
1850                                         R_Shadow_SpecularLighting(mesh->numverts, mesh->numtriangles, mesh->index, mesh->svectors, mesh->tvectors, mesh->normals, mesh->str, relativelightorigin, relativeeyeorigin, lightradius, lightcolor, t->skin.gloss, t->skin.nmap, NULL);
1851                                 }
1852                         }
1853                 }
1854         }
1855 }
1856
1857 void R_Model_Brush_DrawLight(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float *lightcolor)
1858 {
1859         int surfnum;
1860         msurface_t *surf;
1861         texture_t *t;
1862         float f, lightradius2, temp[3];
1863         surfmesh_t *mesh;
1864         R_Mesh_Matrix(&ent->matrix);
1865         lightradius2 = lightradius * lightradius;
1866         R_UpdateTextureInfo(ent);
1867         if (ent != &cl_entities[0].render)
1868         {
1869                 // bmodel, cull crudely to view and light
1870                 for (surfnum = 0, surf = ent->model->surfaces + ent->model->firstmodelsurface;surfnum < ent->model->nummodelsurfaces;surfnum++, surf++)
1871                 {
1872                         temp[0] = bound(surf->poly_mins[0], relativelightorigin[0], surf->poly_maxs[0]) - relativelightorigin[0];
1873                         temp[1] = bound(surf->poly_mins[1], relativelightorigin[1], surf->poly_maxs[1]) - relativelightorigin[1];
1874                         temp[2] = bound(surf->poly_mins[2], relativelightorigin[2], surf->poly_maxs[2]) - relativelightorigin[2];
1875                         if (DotProduct(temp, temp) < lightradius2)
1876                         {
1877                                 f = PlaneDiff(relativelightorigin, surf->plane);
1878                                 if (surf->flags & SURF_PLANEBACK)
1879                                         f = -f;
1880                                 if (f >= -0.1 && f < lightradius)
1881                                 {
1882                                         f = PlaneDiff(relativeeyeorigin, surf->plane);
1883                                         if (surf->flags & SURF_PLANEBACK)
1884                                                 f = -f;
1885                                         if (f > 0)
1886                                         {
1887                                                 t = surf->texinfo->texture->currentframe;
1888                                                 if (t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1889                                                 {
1890                                                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1891                                                         {
1892                                                                 R_Mesh_ResizeCheck(mesh->numverts);
1893                                                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1894                                                                 R_Shadow_DiffuseLighting(mesh->numverts, mesh->numtriangles, mesh->index, mesh->svectors, mesh->tvectors, mesh->normals, mesh->str, relativelightorigin, lightradius, lightcolor, t->skin.base, t->skin.nmap, NULL);
1895                                                                 R_Shadow_SpecularLighting(mesh->numverts, mesh->numtriangles, mesh->index, mesh->svectors, mesh->tvectors, mesh->normals, mesh->str, relativelightorigin, relativeeyeorigin, lightradius, lightcolor, t->skin.gloss, t->skin.nmap, NULL);
1896                                                         }
1897                                                 }
1898                                         }
1899                                 }
1900                         }
1901                 }
1902         }
1903         else
1904         {
1905                 // world, already culled to view, just cull to light
1906                 for (surfnum = 0, surf = ent->model->surfaces + ent->model->firstmodelsurface;surfnum < ent->model->nummodelsurfaces;surfnum++, surf++)
1907                 {
1908                         if (surf->visframe == r_framecount)
1909                         {
1910                                 temp[0] = bound(surf->poly_mins[0], relativelightorigin[0], surf->poly_maxs[0]) - relativelightorigin[0];
1911                                 temp[1] = bound(surf->poly_mins[1], relativelightorigin[1], surf->poly_maxs[1]) - relativelightorigin[1];
1912                                 temp[2] = bound(surf->poly_mins[2], relativelightorigin[2], surf->poly_maxs[2]) - relativelightorigin[2];
1913                                 if (DotProduct(temp, temp) < lightradius2)
1914                                 {
1915                                         f = PlaneDiff(relativelightorigin, surf->plane);
1916                                         if (surf->flags & SURF_PLANEBACK)
1917                                                 f = -f;
1918                                         if (f >= -0.1 && f < lightradius)
1919                                         {
1920                                                 t = surf->texinfo->texture->currentframe;
1921                                                 if (t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1922                                                 {
1923                                                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1924                                                         {
1925                                                                 R_Mesh_ResizeCheck(mesh->numverts);
1926                                                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1927                                                                 R_Shadow_DiffuseLighting(mesh->numverts, mesh->numtriangles, mesh->index, mesh->svectors, mesh->tvectors, mesh->normals, mesh->str, relativelightorigin, lightradius, lightcolor, t->skin.base, t->skin.nmap, NULL);
1928                                                                 R_Shadow_SpecularLighting(mesh->numverts, mesh->numtriangles, mesh->index, mesh->svectors, mesh->tvectors, mesh->normals, mesh->str, relativelightorigin, relativeeyeorigin, lightradius, lightcolor, t->skin.gloss, t->skin.nmap, NULL);
1929                                                         }
1930                                                 }
1931                                         }
1932                                 }
1933                         }
1934                 }
1935         }
1936 }
1937
1938 static void gl_surf_start(void)
1939 {
1940 }
1941
1942 static void gl_surf_shutdown(void)
1943 {
1944 }
1945
1946 static void gl_surf_newmap(void)
1947 {
1948 }
1949
1950 void GL_Surf_Init(void)
1951 {
1952         int i;
1953         dlightdivtable[0] = 4194304;
1954         for (i = 1;i < 32768;i++)
1955                 dlightdivtable[i] = 4194304 / (i << 7);
1956
1957         Cvar_RegisterVariable(&r_ambient);
1958         Cvar_RegisterVariable(&r_vertexsurfaces);
1959         Cvar_RegisterVariable(&r_dlightmap);
1960         Cvar_RegisterVariable(&r_drawportals);
1961         Cvar_RegisterVariable(&r_testvis);
1962         Cvar_RegisterVariable(&r_floatbuildlightmap);
1963         Cvar_RegisterVariable(&r_detailtextures);
1964         Cvar_RegisterVariable(&r_surfaceworldnode);
1965
1966         R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
1967 }
1968