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