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