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