]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_rsurf.c
r_dlightmap 0 mode removed (vertex dlights on lightmapped walls)
[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 // note: this untransforms lights to do the checking
704 static int RSurf_LightCheck(const matrix4x4_t *matrix, const int *dlightbits, const surfmesh_t *mesh)
705 {
706         int i, l;
707         const rdlight_t *rd;
708         vec3_t lightorigin;
709         const float *v;
710         for (l = 0;l < r_numdlights;l++)
711         {
712                 if (dlightbits[l >> 5] & (1 << (l & 31)))
713                 {
714                         rd = &r_dlight[l];
715                         Matrix4x4_Transform(matrix, rd->origin, lightorigin);
716                         for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
717                                 if (VectorDistance2(v, lightorigin) < rd->cullradius2)
718                                         return true;
719                 }
720         }
721         return false;
722 }
723
724 static void RSurfShader_Sky(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
725 {
726         const msurface_t *surf;
727         const surfmesh_t *mesh;
728         rmeshstate_t m;
729
730         // LordHavoc: HalfLife maps have freaky skypolys...
731         if (ent->model->brush.ishlbsp)
732                 return;
733
734         if (skyrendernow)
735         {
736                 skyrendernow = false;
737                 if (skyrendermasked)
738                         R_Sky();
739         }
740
741         R_Mesh_Matrix(&ent->matrix);
742
743         GL_Color(fogcolor[0], fogcolor[1], fogcolor[2], 1);
744         if (skyrendermasked)
745         {
746                 // depth-only (masking)
747                 qglColorMask(0,0,0,0);
748                 // just to make sure that braindead drivers don't draw anything
749                 // despite that colormask...
750                 GL_BlendFunc(GL_ZERO, GL_ONE);
751         }
752         else
753         {
754                 // fog sky
755                 GL_BlendFunc(GL_ONE, GL_ZERO);
756         }
757         GL_DepthMask(true);
758         GL_DepthTest(true);
759
760         memset(&m, 0, sizeof(m));
761         R_Mesh_State_Texture(&m);
762
763         while((surf = *surfchain++) != NULL)
764         {
765                 if (surf->visframe == r_framecount)
766                 {
767                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
768                         {
769                                 GL_VertexPointer(mesh->vertex3f);
770                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
771                         }
772                 }
773         }
774         qglColorMask(1,1,1,1);
775 }
776
777 static void RSurfShader_Water_Callback(const void *calldata1, int calldata2)
778 {
779         const entity_render_t *ent = calldata1;
780         const msurface_t *surf = ent->model->brushq1.surfaces + calldata2;
781         float colorscale;
782         const surfmesh_t *mesh;
783         rmeshstate_t m;
784         float alpha;
785         float modelorg[3];
786         texture_t *texture;
787         matrix4x4_t tempmatrix;
788         float   args[4] = {0.05f,0,0,0.04f};
789
790         if (r_waterscroll.value)
791         {
792                 // scrolling in texture matrix
793                 Matrix4x4_CreateTranslate(&tempmatrix, sin(cl.time) * 0.025 * r_waterscroll.value, sin(cl.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
794                 if (gl_textureshader && r_watershader.integer)
795                 {
796                         R_Mesh_TextureMatrix(1, &tempmatrix);
797                         Matrix4x4_CreateTranslate(&tempmatrix, -sin(cl.time) * 0.025 * r_waterscroll.value, -sin(cl.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
798                 }
799                 R_Mesh_TextureMatrix(0, &tempmatrix);
800         }
801
802         R_Mesh_Matrix(&ent->matrix);
803         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
804
805         memset(&m, 0, sizeof(m));
806         texture = surf->texinfo->texture->currentframe;
807         alpha = texture->currentalpha;
808         if (texture->rendertype == SURFRENDER_ADD)
809         {
810                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
811                 GL_DepthMask(false);
812         }
813         else if (texture->rendertype == SURFRENDER_ALPHA)
814         {
815                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
816                 GL_DepthMask(false);
817         }
818         else
819         {
820                 GL_BlendFunc(GL_ONE, GL_ZERO);
821                 GL_DepthMask(true);
822         }
823         if (gl_textureshader && r_watershader.integer)
824         {
825                 m.tex[0] = R_GetTexture(mod_shared_distorttexture);
826                 m.tex[1] = R_GetTexture(texture->skin.base);
827         }
828         else
829                 m.tex[0] = R_GetTexture(texture->skin.base);
830         colorscale = 1;
831         if (gl_combine.integer)
832         {
833                 m.texrgbscale[0] = 4;
834                 colorscale *= 0.25f;
835         }
836         GL_DepthTest(true);
837         if (fogenabled)
838                 GL_ColorPointer(varray_color4f);
839         else
840                 GL_Color(1, 1, 1, alpha);
841         if (gl_textureshader && r_watershader.integer)
842         {
843                 GL_ActiveTexture (0);
844                 qglTexEnvi (GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_2D);
845                 GL_ActiveTexture (1);
846                 qglTexEnvi (GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_2D);
847                 qglTexEnvi (GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_OFFSET_TEXTURE_2D_NV);
848                 qglTexEnvi (GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB);
849                 qglTexEnvfv (GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_MATRIX_NV, &args[0]);
850                 qglEnable (GL_TEXTURE_SHADER_NV);
851         }
852         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
853         {
854                 GL_VertexPointer(mesh->vertex3f);
855                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
856                 m.pointer_texcoord[1] = mesh->texcoordtexture2f;
857                 m.texcombinergb[1] = GL_REPLACE;
858                 R_Mesh_State_Texture(&m);
859                 if (fogenabled)
860                 {
861                         R_FillColors(varray_color4f, mesh->numverts, 1, 1, 1, alpha);
862                         RSurf_FogColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, colorscale, mesh->numverts, modelorg);
863                 }
864                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
865         }
866         if (gl_textureshader && r_watershader.integer)
867         {
868                 qglDisable (GL_TEXTURE_SHADER_NV);
869                 GL_ActiveTexture (0);
870         }
871
872         if (fogenabled)
873         {
874                 memset(&m, 0, sizeof(m));
875                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
876                 GL_DepthMask(false);
877                 GL_DepthTest(true);
878                 m.tex[0] = R_GetTexture(texture->skin.fog);
879                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
880                 {
881                         GL_VertexPointer(mesh->vertex3f);
882                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
883                         GL_ColorPointer(varray_color4f);
884                         R_Mesh_State_Texture(&m);
885                         RSurf_FogPassColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], alpha, 1, mesh->numverts, modelorg);
886                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
887                 }
888         }
889
890         if (r_waterscroll.value)
891         {
892                 Matrix4x4_CreateIdentity(&tempmatrix);
893                 R_Mesh_TextureMatrix(0, &tempmatrix);
894                 R_Mesh_TextureMatrix(1, &tempmatrix);
895         }
896 }
897
898 static void RSurfShader_Water(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
899 {
900         const msurface_t *surf;
901         msurface_t **chain;
902         vec3_t center;
903         if (texture->rendertype != SURFRENDER_OPAQUE)
904         {
905                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
906                 {
907                         if (surf->visframe == r_framecount)
908                         {
909                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
910                                 R_MeshQueue_AddTransparent(center, RSurfShader_Water_Callback, ent, surf - ent->model->brushq1.surfaces);
911                         }
912                 }
913         }
914         else
915                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
916                         if (surf->visframe == r_framecount)
917                                 RSurfShader_Water_Callback(ent, surf - ent->model->brushq1.surfaces);
918 }
919
920 static void RSurfShader_Wall_Pass_BaseVertex(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
921 {
922         float base, colorscale;
923         const surfmesh_t *mesh;
924         rmeshstate_t m;
925         float modelorg[3];
926         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
927         memset(&m, 0, sizeof(m));
928         if (rendertype == SURFRENDER_ADD)
929         {
930                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
931                 GL_DepthMask(false);
932         }
933         else if (rendertype == SURFRENDER_ALPHA)
934         {
935                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
936                 GL_DepthMask(false);
937         }
938         else
939         {
940                 GL_BlendFunc(GL_ONE, GL_ZERO);
941                 GL_DepthMask(true);
942         }
943         m.tex[0] = R_GetTexture(texture->skin.base);
944         colorscale = 1;
945         if (gl_combine.integer)
946         {
947                 m.texrgbscale[0] = 4;
948                 colorscale *= 0.25f;
949         }
950         base = ent->effects & EF_FULLBRIGHT ? 2.0f : r_ambient.value * (1.0f / 64.0f);
951         GL_DepthTest(true);
952         GL_ColorPointer(varray_color4f);
953         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
954         {
955                 GL_VertexPointer(mesh->vertex3f);
956                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
957                 R_Mesh_State_Texture(&m);
958                 R_FillColors(varray_color4f, mesh->numverts, base, base, base, currentalpha);
959                 if (!(ent->effects & EF_FULLBRIGHT))
960                 {
961                         if (surf->dlightframe == r_framecount)
962                                 RSurf_LightSeparate_Vertex3f_Color4f(&ent->inversematrix, surf->dlightbits, mesh->numverts, mesh->vertex3f, varray_color4f, 1);
963                         if (surf->flags & SURF_LIGHTMAP)
964                                 RSurf_AddLightmapToVertexColors_Color4f(mesh->lightmapoffsets, varray_color4f, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
965                 }
966                 RSurf_FogColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, colorscale, mesh->numverts, modelorg);
967                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
968         }
969 }
970
971 static void RSurfShader_Wall_Pass_Glow(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
972 {
973         const surfmesh_t *mesh;
974         rmeshstate_t m;
975         float modelorg[3];
976         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
977         memset(&m, 0, sizeof(m));
978         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
979         GL_DepthMask(false);
980         GL_DepthTest(true);
981         m.tex[0] = R_GetTexture(texture->skin.glow);
982         GL_ColorPointer(varray_color4f);
983         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
984         {
985                 GL_VertexPointer(mesh->vertex3f);
986                 if (m.tex[0])
987                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
988                 R_Mesh_State_Texture(&m);
989                 RSurf_FoggedColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, 1, 1, 1, currentalpha, 1, mesh->numverts, modelorg);
990                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
991         }
992 }
993
994 static void RSurfShader_Wall_Pass_Fog(const entity_render_t *ent, const msurface_t *surf, const texture_t *texture, int rendertype, float currentalpha)
995 {
996         const surfmesh_t *mesh;
997         rmeshstate_t m;
998         float modelorg[3];
999         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1000         memset(&m, 0, sizeof(m));
1001         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1002         GL_DepthMask(false);
1003         GL_DepthTest(true);
1004         m.tex[0] = R_GetTexture(texture->skin.fog);
1005         GL_ColorPointer(varray_color4f);
1006         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1007         {
1008                 GL_VertexPointer(mesh->vertex3f);
1009                 if (m.tex[0])
1010                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1011                 R_Mesh_State_Texture(&m);
1012                 RSurf_FogPassColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], currentalpha, 1, mesh->numverts, modelorg);
1013                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1014         }
1015 }
1016
1017 static void RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1018 {
1019         const msurface_t *surf;
1020         const surfmesh_t *mesh;
1021         rmeshstate_t m;
1022         int lightmaptexturenum;
1023         float cl;
1024         memset(&m, 0, sizeof(m));
1025         GL_BlendFunc(GL_ONE, GL_ZERO);
1026         GL_DepthMask(true);
1027         GL_DepthTest(true);
1028         m.tex[0] = R_GetTexture(texture->skin.base);
1029         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1030         m.tex[2] = R_GetTexture(texture->skin.detail);
1031         m.texrgbscale[0] = 1;
1032         m.texrgbscale[1] = 4;
1033         m.texrgbscale[2] = 2;
1034         cl = (float) (1 << r_lightmapscalebit);
1035         GL_Color(cl, cl, cl, 1);
1036
1037         while((surf = *surfchain++) != NULL)
1038         {
1039                 if (surf->visframe == r_framecount)
1040                 {
1041                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1042                         //if (m.tex[1] != lightmaptexturenum)
1043                         //{
1044                                 m.tex[1] = lightmaptexturenum;
1045                         //      R_Mesh_State_Texture(&m);
1046                         //}
1047                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1048                         {
1049                                 GL_VertexPointer(mesh->vertex3f);
1050                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1051                                 m.pointer_texcoord[1] = mesh->texcoordlightmap2f;
1052                                 m.pointer_texcoord[2] = mesh->texcoorddetail2f;
1053                                 R_Mesh_State_Texture(&m);
1054                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1055                         }
1056                 }
1057         }
1058 }
1059
1060 static void RSurfShader_OpaqueWall_Pass_BaseDoubleTex(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1061 {
1062         const msurface_t *surf;
1063         const surfmesh_t *mesh;
1064         rmeshstate_t m;
1065         int lightmaptexturenum;
1066         memset(&m, 0, sizeof(m));
1067         GL_BlendFunc(GL_ONE, GL_ZERO);
1068         GL_DepthMask(true);
1069         GL_DepthTest(true);
1070         m.tex[0] = R_GetTexture(texture->skin.base);
1071         m.tex[1] = R_GetTexture((**surfchain).lightmaptexture);
1072         if (gl_combine.integer)
1073                 m.texrgbscale[1] = 4;
1074         GL_Color(1, 1, 1, 1);
1075         while((surf = *surfchain++) != NULL)
1076         {
1077                 if (surf->visframe == r_framecount)
1078                 {
1079                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1080                         //if (m.tex[1] != lightmaptexturenum)
1081                         //{
1082                                 m.tex[1] = lightmaptexturenum;
1083                         //      R_Mesh_State_Texture(&m);
1084                         //}
1085                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1086                         {
1087                                 GL_VertexPointer(mesh->vertex3f);
1088                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1089                                 m.pointer_texcoord[1] = mesh->texcoordlightmap2f;
1090                                 R_Mesh_State_Texture(&m);
1091                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1092                         }
1093                 }
1094         }
1095 }
1096
1097 static void RSurfShader_OpaqueWall_Pass_BaseTexture(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1098 {
1099         const msurface_t *surf;
1100         const surfmesh_t *mesh;
1101         rmeshstate_t m;
1102         memset(&m, 0, sizeof(m));
1103         GL_DepthMask(true);
1104         GL_DepthTest(true);
1105         GL_BlendFunc(GL_ONE, GL_ZERO);
1106         m.tex[0] = R_GetTexture(texture->skin.base);
1107         GL_Color(1, 1, 1, 1);
1108         while((surf = *surfchain++) != NULL)
1109         {
1110                 if (surf->visframe == r_framecount)
1111                 {
1112                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1113                         {
1114                                 GL_VertexPointer(mesh->vertex3f);
1115                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1116                                 R_Mesh_State_Texture(&m);
1117                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1118                         }
1119                 }
1120         }
1121 }
1122
1123 static void RSurfShader_OpaqueWall_Pass_BaseLightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1124 {
1125         const msurface_t *surf;
1126         const surfmesh_t *mesh;
1127         rmeshstate_t m;
1128         int lightmaptexturenum;
1129         memset(&m, 0, sizeof(m));
1130         GL_BlendFunc(GL_ZERO, GL_SRC_COLOR);
1131         GL_DepthMask(false);
1132         GL_DepthTest(true);
1133         m.tex[0] = R_GetTexture((**surfchain).lightmaptexture);
1134         if (gl_combine.integer)
1135                 m.texrgbscale[0] = 4;
1136         GL_Color(1, 1, 1, 1);
1137         while((surf = *surfchain++) != NULL)
1138         {
1139                 if (surf->visframe == r_framecount)
1140                 {
1141                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1142                         //if (m.tex[0] != lightmaptexturenum)
1143                         //{
1144                                 m.tex[0] = lightmaptexturenum;
1145                         //      R_Mesh_State_Texture(&m);
1146                         //}
1147                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1148                         {
1149                                 GL_VertexPointer(mesh->vertex3f);
1150                                 m.pointer_texcoord[0] = mesh->texcoordlightmap2f;
1151                                 R_Mesh_State_Texture(&m);
1152                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1153                         }
1154                 }
1155         }
1156 }
1157
1158 static void RSurfShader_OpaqueWall_Pass_Fog(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1159 {
1160         const msurface_t *surf;
1161         const surfmesh_t *mesh;
1162         rmeshstate_t m;
1163         float modelorg[3];
1164         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1165         memset(&m, 0, sizeof(m));
1166         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1167         GL_DepthMask(false);
1168         GL_DepthTest(true);
1169         GL_ColorPointer(varray_color4f);
1170         while((surf = *surfchain++) != NULL)
1171         {
1172                 if (surf->visframe == r_framecount)
1173                 {
1174                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1175                         {
1176                                 GL_VertexPointer(mesh->vertex3f);
1177                                 if (m.tex[0])
1178                                         m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1179                                 R_Mesh_State_Texture(&m);
1180                                 RSurf_FogPassColors_Vertex3f_Color4f(mesh->vertex3f, varray_color4f, fogcolor[0], fogcolor[1], fogcolor[2], 1, 1, mesh->numverts, modelorg);
1181                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1182                         }
1183                 }
1184         }
1185 }
1186
1187 static void RSurfShader_OpaqueWall_Pass_BaseDetail(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1188 {
1189         const msurface_t *surf;
1190         const surfmesh_t *mesh;
1191         rmeshstate_t m;
1192         memset(&m, 0, sizeof(m));
1193         GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
1194         GL_DepthMask(false);
1195         GL_DepthTest(true);
1196         m.tex[0] = R_GetTexture(texture->skin.detail);
1197         GL_Color(1, 1, 1, 1);
1198         while((surf = *surfchain++) != NULL)
1199         {
1200                 if (surf->visframe == r_framecount)
1201                 {
1202                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1203                         {
1204                                 GL_VertexPointer(mesh->vertex3f);
1205                                 m.pointer_texcoord[0] = mesh->texcoorddetail2f;
1206                                 R_Mesh_State_Texture(&m);
1207                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1208                         }
1209                 }
1210         }
1211 }
1212
1213 static void RSurfShader_OpaqueWall_Pass_Glow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1214 {
1215         const msurface_t *surf;
1216         const surfmesh_t *mesh;
1217         rmeshstate_t m;
1218         memset(&m, 0, sizeof(m));
1219         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1220         GL_DepthMask(false);
1221         GL_DepthTest(true);
1222         m.tex[0] = R_GetTexture(texture->skin.glow);
1223         GL_Color(1, 1, 1, 1);
1224         while((surf = *surfchain++) != NULL)
1225         {
1226                 if (surf->visframe == r_framecount)
1227                 {
1228                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1229                         {
1230                                 GL_VertexPointer(mesh->vertex3f);
1231                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1232                                 R_Mesh_State_Texture(&m);
1233                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1234                         }
1235                 }
1236         }
1237 }
1238
1239 static void RSurfShader_OpaqueWall_Pass_OpaqueGlow(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1240 {
1241         const msurface_t *surf;
1242         const surfmesh_t *mesh;
1243         rmeshstate_t m;
1244         memset(&m, 0, sizeof(m));
1245         GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1246         GL_DepthMask(true);
1247         m.tex[0] = R_GetTexture(texture->skin.glow);
1248         if (m.tex[0])
1249                 GL_Color(1, 1, 1, 1);
1250         else
1251                 GL_Color(0, 0, 0, 1);
1252         while((surf = *surfchain++) != NULL)
1253         {
1254                 if (surf->visframe == r_framecount)
1255                 {
1256                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1257                         {
1258                                 GL_VertexPointer(mesh->vertex3f);
1259                                 m.pointer_texcoord[0] = mesh->texcoordtexture2f;
1260                                 R_Mesh_State_Texture(&m);
1261                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->element3i);
1262                         }
1263                 }
1264         }
1265 }
1266
1267 static void RSurfShader_Wall_Vertex_Callback(const void *calldata1, int calldata2)
1268 {
1269         const entity_render_t *ent = calldata1;
1270         const msurface_t *surf = ent->model->brushq1.surfaces + calldata2;
1271         int rendertype;
1272         float currentalpha;
1273         texture_t *texture;
1274         R_Mesh_Matrix(&ent->matrix);
1275
1276         texture = surf->texinfo->texture;
1277         if (texture->animated)
1278                 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];
1279
1280         currentalpha = ent->alpha;
1281         if (ent->effects & EF_ADDITIVE)
1282                 rendertype = SURFRENDER_ADD;
1283         else if (currentalpha < 1 || texture->skin.fog != NULL)
1284                 rendertype = SURFRENDER_ALPHA;
1285         else
1286                 rendertype = SURFRENDER_OPAQUE;
1287
1288         RSurfShader_Wall_Pass_BaseVertex(ent, surf, texture, rendertype, currentalpha);
1289         if (texture->skin.glow)
1290                 RSurfShader_Wall_Pass_Glow(ent, surf, texture, rendertype, currentalpha);
1291         if (fogenabled)
1292                 RSurfShader_Wall_Pass_Fog(ent, surf, texture, rendertype, currentalpha);
1293 }
1294
1295 static void RSurfShader_Wall_Lightmap(const entity_render_t *ent, const texture_t *texture, msurface_t **surfchain)
1296 {
1297         const msurface_t *surf;
1298         msurface_t **chain;
1299         vec3_t center;
1300         if (texture->rendertype != SURFRENDER_OPAQUE)
1301         {
1302                 // transparent vertex shaded from lightmap
1303                 for (chain = surfchain;(surf = *chain) != NULL;chain++)
1304                 {
1305                         if (surf->visframe == r_framecount)
1306                         {
1307                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
1308                                 R_MeshQueue_AddTransparent(center, RSurfShader_Wall_Vertex_Callback, ent, surf - ent->model->brushq1.surfaces);
1309                         }
1310                 }
1311         }
1312         else if (r_shadow_realtime_world.integer)
1313         {
1314                 // opaque base lighting
1315                 RSurfShader_OpaqueWall_Pass_OpaqueGlow(ent, texture, surfchain);
1316                 if (fogenabled)
1317                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1318         }
1319         else
1320         {
1321                 // opaque lightmapped
1322                 if (r_textureunits.integer >= 3 && gl_combine.integer && r_detailtextures.integer)
1323                         RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(ent, texture, surfchain);
1324                 else if (r_textureunits.integer >= 2)
1325                 {
1326                         RSurfShader_OpaqueWall_Pass_BaseDoubleTex(ent, texture, surfchain);
1327                         if (r_detailtextures.integer)
1328                                 RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1329                 }
1330                 else
1331                 {
1332                         RSurfShader_OpaqueWall_Pass_BaseTexture(ent, texture, surfchain);
1333                         RSurfShader_OpaqueWall_Pass_BaseLightmap(ent, texture, surfchain);
1334                         if (r_detailtextures.integer)
1335                                 RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, surfchain);
1336                 }
1337                 if (texture->skin.glow)
1338                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture, surfchain);
1339                 if (fogenabled)
1340                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, surfchain);
1341         }
1342 }
1343
1344 Cshader_t Cshader_wall_lightmap = {{NULL, RSurfShader_Wall_Lightmap}, SHADERFLAGS_NEEDLIGHTMAP};
1345 Cshader_t Cshader_water = {{NULL, RSurfShader_Water}, 0};
1346 Cshader_t Cshader_sky = {{RSurfShader_Sky, NULL}, 0};
1347
1348 int Cshader_count = 3;
1349 Cshader_t *Cshaders[3] =
1350 {
1351         &Cshader_wall_lightmap,
1352         &Cshader_water,
1353         &Cshader_sky
1354 };
1355
1356 void R_UpdateTextureInfo(entity_render_t *ent)
1357 {
1358         int i, texframe, alttextures;
1359         texture_t *t;
1360
1361         if (!ent->model)
1362                 return;
1363
1364         alttextures = ent->frame != 0;
1365         texframe = (int)(cl.time * 5.0f);
1366         for (i = 0;i < ent->model->brushq1.numtextures;i++)
1367         {
1368                 t = ent->model->brushq1.textures + i;
1369                 t->currentalpha = ent->alpha;
1370                 if (t->flags & SURF_WATERALPHA)
1371                         t->currentalpha *= r_wateralpha.value;
1372                 if (ent->effects & EF_ADDITIVE)
1373                         t->rendertype = SURFRENDER_ADD;
1374                 else if (t->currentalpha < 1 || t->skin.fog != NULL)
1375                         t->rendertype = SURFRENDER_ALPHA;
1376                 else
1377                         t->rendertype = SURFRENDER_OPAQUE;
1378                 // we don't need to set currentframe if t->animated is false because
1379                 // it was already set up by the texture loader for non-animating
1380                 if (t->animated)
1381                         t->currentframe = t->anim_frames[alttextures][(t->anim_total[alttextures] >= 2) ? (texframe % t->anim_total[alttextures]) : 0];
1382         }
1383 }
1384
1385 void R_PrepareSurfaces(entity_render_t *ent)
1386 {
1387         int i, numsurfaces, *surfacevisframes;
1388         model_t *model;
1389         msurface_t *surf, *surfaces, **surfchain;
1390         vec3_t modelorg;
1391
1392         if (!ent->model)
1393                 return;
1394
1395         model = ent->model;
1396         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1397         numsurfaces = model->brushq1.nummodelsurfaces;
1398         surfaces = model->brushq1.surfaces + model->brushq1.firstmodelsurface;
1399         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1400
1401         R_UpdateTextureInfo(ent);
1402
1403         if (r_dynamic.integer && !r_shadow_realtime_dlight.integer)
1404                 R_MarkLights(ent);
1405
1406         if (model->brushq1.light_ambient != r_ambient.value || model->brushq1.light_scalebit != r_lightmapscalebit)
1407         {
1408                 model->brushq1.light_ambient = r_ambient.value;
1409                 model->brushq1.light_scalebit = r_lightmapscalebit;
1410                 for (i = 0;i < model->brushq1.nummodelsurfaces;i++)
1411                         model->brushq1.surfaces[i + model->brushq1.firstmodelsurface].cached_dlight = true;
1412         }
1413         else
1414         {
1415                 for (i = 0;i < model->brushq1.light_styles;i++)
1416                 {
1417                         if (model->brushq1.light_stylevalue[i] != d_lightstylevalue[model->brushq1.light_style[i]])
1418                         {
1419                                 model->brushq1.light_stylevalue[i] = d_lightstylevalue[model->brushq1.light_style[i]];
1420                                 for (surfchain = model->brushq1.light_styleupdatechains[i];*surfchain;surfchain++)
1421                                         (**surfchain).cached_dlight = true;
1422                         }
1423                 }
1424         }
1425
1426         for (i = 0, surf = surfaces;i < numsurfaces;i++, surf++)
1427         {
1428                 if (surfacevisframes[i] == r_framecount)
1429                 {
1430 #if !WORLDNODECULLBACKFACES
1431                         // mark any backface surfaces as not visible
1432                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1433                         {
1434                                 if (!(surf->flags & SURF_PLANEBACK))
1435                                         surfacevisframes[i] = -1;
1436                         }
1437                         else
1438                         {
1439                                 if ((surf->flags & SURF_PLANEBACK))
1440                                         surfacevisframes[i] = -1;
1441                         }
1442                         if (surfacevisframes[i] == r_framecount)
1443 #endif
1444                         {
1445                                 c_faces++;
1446                                 surf->visframe = r_framecount;
1447                                 if (surf->cached_dlight && surf->lightmaptexture != NULL)
1448                                         R_BuildLightMap(ent, surf);
1449                         }
1450                 }
1451         }
1452 }
1453
1454 void R_DrawSurfaces(entity_render_t *ent, int type, msurface_t ***chains)
1455 {
1456         int i;
1457         texture_t *t;
1458         if (ent->model == NULL)
1459                 return;
1460         R_Mesh_Matrix(&ent->matrix);
1461         for (i = 0, t = ent->model->brushq1.textures;i < ent->model->brushq1.numtextures;i++, t++)
1462                 if (t->shader->shaderfunc[type] && t->currentframe && chains[i] != NULL)
1463                         t->shader->shaderfunc[type](ent, t->currentframe, chains[i]);
1464 }
1465
1466 static void R_DrawPortal_Callback(const void *calldata1, int calldata2)
1467 {
1468         int i;
1469         float *v;
1470         rmeshstate_t m;
1471         const entity_render_t *ent = calldata1;
1472         const mportal_t *portal = ent->model->brushq1.portals + calldata2;
1473         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1474         GL_DepthMask(false);
1475         GL_DepthTest(true);
1476         R_Mesh_Matrix(&ent->matrix);
1477         GL_VertexPointer(varray_vertex3f);
1478
1479         memset(&m, 0, sizeof(m));
1480         R_Mesh_State_Texture(&m);
1481
1482         i = portal - ent->model->brushq1.portals;
1483         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f),
1484                          ((i & 0x0038) >> 3) * (1.0f / 7.0f),
1485                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f),
1486                          0.125f);
1487         if (PlaneDiff(r_origin, (&portal->plane)) < 0)
1488         {
1489                 for (i = portal->numpoints - 1, v = varray_vertex3f;i >= 0;i--, v += 3)
1490                         VectorCopy(portal->points[i].position, v);
1491         }
1492         else
1493                 for (i = 0, v = varray_vertex3f;i < portal->numpoints;i++, v += 3)
1494                         VectorCopy(portal->points[i].position, v);
1495         R_Mesh_Draw(portal->numpoints, portal->numpoints - 2, polygonelements);
1496 }
1497
1498 // LordHavoc: this is just a nice debugging tool, very slow
1499 static void R_DrawPortals(entity_render_t *ent)
1500 {
1501         int i;
1502         mportal_t *portal, *endportal;
1503         float temp[3], center[3], f;
1504         if (ent->model == NULL)
1505                 return;
1506         for (portal = ent->model->brushq1.portals, endportal = portal + ent->model->brushq1.numportals;portal < endportal;portal++)
1507         {
1508                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
1509                 {
1510                         VectorClear(temp);
1511                         for (i = 0;i < portal->numpoints;i++)
1512                                 VectorAdd(temp, portal->points[i].position, temp);
1513                         f = ixtable[portal->numpoints];
1514                         VectorScale(temp, f, temp);
1515                         Matrix4x4_Transform(&ent->matrix, temp, center);
1516                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, ent, portal - ent->model->brushq1.portals);
1517                 }
1518         }
1519 }
1520
1521 void R_PrepareBrushModel(entity_render_t *ent)
1522 {
1523         int i, numsurfaces, *surfacevisframes, *surfacepvsframes;
1524         msurface_t *surf;
1525         model_t *model;
1526 #if WORLDNODECULLBACKFACES
1527         vec3_t modelorg;
1528 #endif
1529
1530         // because bmodels can be reused, we have to decide which things to render
1531         // from scratch every time
1532         model = ent->model;
1533         if (model == NULL)
1534                 return;
1535 #if WORLDNODECULLBACKFACES
1536         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1537 #endif
1538         numsurfaces = model->brushq1.nummodelsurfaces;
1539         surf = model->brushq1.surfaces + model->brushq1.firstmodelsurface;
1540         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1541         surfacepvsframes = model->brushq1.surfacepvsframes + model->brushq1.firstmodelsurface;
1542         for (i = 0;i < numsurfaces;i++, surf++)
1543         {
1544 #if WORLDNODECULLBACKFACES
1545                 // mark any backface surfaces as not visible
1546                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1547                 {
1548                         if ((surf->flags & SURF_PLANEBACK))
1549                                 surfacevisframes[i] = r_framecount;
1550                 }
1551                 else if (!(surf->flags & SURF_PLANEBACK))
1552                         surfacevisframes[i] = r_framecount;
1553 #else
1554                 surfacevisframes[i] = r_framecount;
1555 #endif
1556                 surf->dlightframe = -1;
1557         }
1558         R_PrepareSurfaces(ent);
1559 }
1560
1561 void R_SurfaceWorldNode (entity_render_t *ent)
1562 {
1563         int i, *surfacevisframes, *surfacepvsframes, surfnum;
1564         msurface_t *surf;
1565         mleaf_t *leaf;
1566         model_t *model;
1567         vec3_t modelorg;
1568
1569         // equivilant to quake's RecursiveWorldNode but faster and more effective
1570         model = ent->model;
1571         if (model == NULL)
1572                 return;
1573         surfacevisframes = model->brushq1.surfacevisframes + model->brushq1.firstmodelsurface;
1574         surfacepvsframes = model->brushq1.surfacepvsframes + model->brushq1.firstmodelsurface;
1575         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1576
1577         for (leaf = model->brushq1.pvsleafchain;leaf;leaf = leaf->pvschain)
1578         {
1579                 if (!R_CullBox (leaf->mins, leaf->maxs))
1580                 {
1581                         c_leafs++;
1582                         leaf->visframe = r_framecount;
1583                 }
1584         }
1585
1586         for (i = 0;i < model->brushq1.pvssurflistlength;i++)
1587         {
1588                 surfnum = model->brushq1.pvssurflist[i];
1589                 surf = model->brushq1.surfaces + surfnum;
1590 #if WORLDNODECULLBACKFACES
1591                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1592                 {
1593                         if ((surf->flags & SURF_PLANEBACK) && !R_CullBox (surf->poly_mins, surf->poly_maxs))
1594                                 surfacevisframes[surfnum] = r_framecount;
1595                 }
1596                 else
1597                 {
1598                         if (!(surf->flags & SURF_PLANEBACK) && !R_CullBox (surf->poly_mins, surf->poly_maxs))
1599                                 surfacevisframes[surfnum] = r_framecount;
1600                 }
1601 #else
1602                 if (!R_CullBox (surf->poly_mins, surf->poly_maxs))
1603                         surfacevisframes[surfnum] = r_framecount;
1604 #endif
1605         }
1606 }
1607
1608 static void R_PortalWorldNode(entity_render_t *ent, mleaf_t *viewleaf)
1609 {
1610         int c, leafstackpos, *mark, *surfacevisframes, bitnum;
1611 #if WORLDNODECULLBACKFACES
1612         int n;
1613         msurface_t *surf;
1614 #endif
1615         mleaf_t *leaf, *leafstack[8192];
1616         mportal_t *p;
1617         vec3_t modelorg;
1618         msurface_t *surfaces;
1619         if (ent->model == NULL)
1620                 return;
1621         // LordHavoc: portal-passage worldnode with PVS;
1622         // follows portals leading outward from viewleaf, does not venture
1623         // offscreen or into leafs that are not visible, faster than Quake's
1624         // RecursiveWorldNode
1625         surfaces = ent->model->brushq1.surfaces;
1626         surfacevisframes = ent->model->brushq1.surfacevisframes;
1627         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1628         viewleaf->worldnodeframe = r_framecount;
1629         leafstack[0] = viewleaf;
1630         leafstackpos = 1;
1631         while (leafstackpos)
1632         {
1633                 c_leafs++;
1634                 leaf = leafstack[--leafstackpos];
1635                 leaf->visframe = r_framecount;
1636                 // draw any surfaces bounding this leaf
1637                 if (leaf->nummarksurfaces)
1638                 {
1639                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1640                         {
1641 #if WORLDNODECULLBACKFACES
1642                                 n = *mark++;
1643                                 if (surfacevisframes[n] != r_framecount)
1644                                 {
1645                                         surf = surfaces + n;
1646                                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1647                                         {
1648                                                 if ((surf->flags & SURF_PLANEBACK))
1649                                                         surfacevisframes[n] = r_framecount;
1650                                         }
1651                                         else
1652                                         {
1653                                                 if (!(surf->flags & SURF_PLANEBACK))
1654                                                         surfacevisframes[n] = r_framecount;
1655                                         }
1656                                 }
1657 #else
1658                                 surfacevisframes[*mark++] = r_framecount;
1659 #endif
1660                         }
1661                 }
1662                 // follow portals into other leafs
1663                 for (p = leaf->portals;p;p = p->next)
1664                 {
1665                         // LordHavoc: this DotProduct hurts less than a cache miss
1666                         // (which is more likely to happen if backflowing through leafs)
1667                         if (DotProduct(modelorg, p->plane.normal) < (p->plane.dist + 1))
1668                         {
1669                                 leaf = p->past;
1670                                 if (leaf->worldnodeframe != r_framecount)
1671                                 {
1672                                         leaf->worldnodeframe = r_framecount;
1673                                         // FIXME: R_CullBox is absolute, should be done relative
1674                                         bitnum = (leaf - ent->model->brushq1.leafs) - 1;
1675                                         if ((r_pvsbits[bitnum >> 3] & (1 << (bitnum & 7))) && !R_CullBox(leaf->mins, leaf->maxs))
1676                                                 leafstack[leafstackpos++] = leaf;
1677                                 }
1678                         }
1679                 }
1680         }
1681 }
1682
1683 void R_PVSUpdate (entity_render_t *ent, mleaf_t *viewleaf)
1684 {
1685         int j, c, *surfacepvsframes, *mark;
1686         mleaf_t *leaf;
1687         model_t *model;
1688
1689         model = ent->model;
1690         if (model && (model->brushq1.pvsviewleaf != viewleaf || model->brushq1.pvsviewleafnovis != r_novis.integer))
1691         {
1692                 model->brushq1.pvsframecount++;
1693                 model->brushq1.pvsviewleaf = viewleaf;
1694                 model->brushq1.pvsviewleafnovis = r_novis.integer;
1695                 model->brushq1.pvsleafchain = NULL;
1696                 model->brushq1.pvssurflistlength = 0;
1697                 if (viewleaf)
1698                 {
1699                         surfacepvsframes = model->brushq1.surfacepvsframes;
1700                         for (j = 0;j < model->brushq1.visleafs;j++)
1701                         {
1702                                 if (r_pvsbits[j >> 3] & (1 << (j & 7)))
1703                                 {
1704                                         leaf = model->brushq1.leafs + j + 1;
1705                                         leaf->pvsframe = model->brushq1.pvsframecount;
1706                                         leaf->pvschain = model->brushq1.pvsleafchain;
1707                                         model->brushq1.pvsleafchain = leaf;
1708                                         // mark surfaces bounding this leaf as visible
1709                                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--, mark++)
1710                                                 surfacepvsframes[*mark] = model->brushq1.pvsframecount;
1711                                 }
1712                         }
1713                         model->brushq1.BuildPVSTextureChains(model);
1714                 }
1715         }
1716 }
1717
1718 void R_WorldVisibility(entity_render_t *ent)
1719 {
1720         vec3_t modelorg;
1721         mleaf_t *viewleaf;
1722
1723         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1724         viewleaf = (ent->model && ent->model->brushq1.PointInLeaf) ? ent->model->brushq1.PointInLeaf(ent->model, modelorg) : NULL;
1725         R_PVSUpdate(ent, viewleaf);
1726
1727         if (!viewleaf)
1728                 return;
1729
1730         if (r_surfaceworldnode.integer || viewleaf->contents == CONTENTS_SOLID)
1731                 R_SurfaceWorldNode (ent);
1732         else
1733                 R_PortalWorldNode (ent, viewleaf);
1734 }
1735
1736 void R_DrawWorld(entity_render_t *ent)
1737 {
1738         if (ent->model == NULL)
1739                 return;
1740         if (!ent->model->brushq1.numleafs && ent->model->Draw)
1741                 ent->model->Draw(ent);
1742         else
1743         {
1744                 R_PrepareSurfaces(ent);
1745                 R_DrawSurfaces(ent, SHADERSTAGE_SKY, ent->model->brushq1.pvstexturechains);
1746                 R_DrawSurfaces(ent, SHADERSTAGE_NORMAL, ent->model->brushq1.pvstexturechains);
1747                 if (r_drawportals.integer)
1748                         R_DrawPortals(ent);
1749         }
1750 }
1751
1752 void R_Model_Brush_DrawSky(entity_render_t *ent)
1753 {
1754         if (ent->model == NULL)
1755                 return;
1756         if (ent != &cl_entities[0].render)
1757                 R_PrepareBrushModel(ent);
1758         R_DrawSurfaces(ent, SHADERSTAGE_SKY, ent->model->brushq1.pvstexturechains);
1759 }
1760
1761 void R_Model_Brush_Draw(entity_render_t *ent)
1762 {
1763         if (ent->model == NULL)
1764                 return;
1765         c_bmodels++;
1766         if (ent != &cl_entities[0].render)
1767                 R_PrepareBrushModel(ent);
1768         R_DrawSurfaces(ent, SHADERSTAGE_NORMAL, ent->model->brushq1.pvstexturechains);
1769 }
1770
1771 void R_Model_Brush_DrawShadowVolume (entity_render_t *ent, vec3_t relativelightorigin, float lightradius)
1772 {
1773         int i;
1774         msurface_t *surf;
1775         float projectdistance, f, temp[3], lightradius2;
1776         surfmesh_t *mesh;
1777         if (ent->model == NULL)
1778                 return;
1779         R_Mesh_Matrix(&ent->matrix);
1780         lightradius2 = lightradius * lightradius;
1781         R_UpdateTextureInfo(ent);
1782         projectdistance = 1000000000.0f;//lightradius + ent->model->radius;
1783         for (i = 0, surf = ent->model->brushq1.surfaces + ent->model->brushq1.firstmodelsurface;i < ent->model->brushq1.nummodelsurfaces;i++, surf++)
1784         {
1785                 if (surf->texinfo->texture->rendertype == SURFRENDER_OPAQUE && surf->flags & SURF_SHADOWCAST)
1786                 {
1787                         f = PlaneDiff(relativelightorigin, surf->plane);
1788                         if (surf->flags & SURF_PLANEBACK)
1789                                 f = -f;
1790                         // draw shadows only for frontfaces and only if they are close
1791                         if (f >= 0.1 && f < lightradius)
1792                         {
1793                                 temp[0] = bound(surf->poly_mins[0], relativelightorigin[0], surf->poly_maxs[0]) - relativelightorigin[0];
1794                                 temp[1] = bound(surf->poly_mins[1], relativelightorigin[1], surf->poly_maxs[1]) - relativelightorigin[1];
1795                                 temp[2] = bound(surf->poly_mins[2], relativelightorigin[2], surf->poly_maxs[2]) - relativelightorigin[2];
1796                                 if (DotProduct(temp, temp) < lightradius2)
1797                                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1798                                                 R_Shadow_Volume(mesh->numverts, mesh->numtriangles, mesh->vertex3f, mesh->element3i, mesh->neighbor3i, relativelightorigin, lightradius, projectdistance);
1799                         }
1800                 }
1801         }
1802 }
1803
1804 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)
1805 {
1806         int surfnum;
1807         msurface_t *surf;
1808         texture_t *t;
1809         surfmesh_t *mesh;
1810         if (ent->model == NULL)
1811                 return;
1812         R_Mesh_Matrix(&ent->matrix);
1813         R_UpdateTextureInfo(ent);
1814         for (surfnum = 0;surfnum < numsurfaces;surfnum++)
1815         {
1816                 surf = surflist[surfnum];
1817                 if (surf->visframe == r_framecount)
1818                 {
1819                         t = surf->texinfo->texture->currentframe;
1820                         if (t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1821                         {
1822                                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1823                                 {
1824                                         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);
1825                                         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);
1826                                 }
1827                         }
1828                 }
1829         }
1830 }
1831
1832 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)
1833 {
1834         int surfnum;
1835         msurface_t *surf;
1836         texture_t *t;
1837         float f, lightmins[3], lightmaxs[3];
1838         surfmesh_t *mesh;
1839         if (ent->model == NULL)
1840                 return;
1841         R_Mesh_Matrix(&ent->matrix);
1842         lightmins[0] = relativelightorigin[0] - lightradius;
1843         lightmins[1] = relativelightorigin[1] - lightradius;
1844         lightmins[2] = relativelightorigin[2] - lightradius;
1845         lightmaxs[0] = relativelightorigin[0] + lightradius;
1846         lightmaxs[1] = relativelightorigin[1] + lightradius;
1847         lightmaxs[2] = relativelightorigin[2] + lightradius;
1848         R_UpdateTextureInfo(ent);
1849         for (surfnum = 0, surf = ent->model->brushq1.surfaces + ent->model->brushq1.firstmodelsurface;surfnum < ent->model->brushq1.nummodelsurfaces;surfnum++, surf++)
1850         {
1851                 if ((ent != &cl_entities[0].render || surf->visframe == r_framecount) && BoxesOverlap(surf->poly_mins, surf->poly_maxs, lightmins, lightmaxs))
1852                 {
1853                         f = PlaneDiff(relativelightorigin, surf->plane);
1854                         if (surf->flags & SURF_PLANEBACK)
1855                                 f = -f;
1856                         if (f >= -0.1 && f < lightradius)
1857                         {
1858                                 t = surf->texinfo->texture->currentframe;
1859                                 if (t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1860                                 {
1861                                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1862                                         {
1863                                                 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);
1864                                                 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);
1865                                         }
1866                                 }
1867                         }
1868                 }
1869         }
1870 }
1871
1872 void R_DrawCollisionBrush(colbrushf_t *brush)
1873 {
1874         int i;
1875         i = ((int)brush) / sizeof(colbrushf_t);
1876         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
1877         GL_VertexPointer(brush->points->v);
1878         R_Mesh_Draw(brush->numpoints, brush->numtriangles, brush->elements);
1879 }
1880
1881 void R_Q3BSP_DrawFace(entity_render_t *ent, q3mface_t *face)
1882 {
1883         rmeshstate_t m;
1884         if (!face->numtriangles)
1885                 return;
1886         if (face->texture->renderflags)
1887         {
1888                 if (face->texture->renderflags & Q3MTEXTURERENDERFLAGS_SKY)
1889                 {
1890                         if (skyrendernow)
1891                         {
1892                                 skyrendernow = false;
1893                                 if (skyrendermasked)
1894                                         R_Sky();
1895                         }
1896
1897                         R_Mesh_Matrix(&ent->matrix);
1898
1899                         GL_Color(fogcolor[0], fogcolor[1], fogcolor[2], 1);
1900                         if (skyrendermasked)
1901                         {
1902                                 // depth-only (masking)
1903                                 qglColorMask(0,0,0,0);
1904                                 // just to make sure that braindead drivers don't draw anything
1905                                 // despite that colormask...
1906                                 GL_BlendFunc(GL_ZERO, GL_ONE);
1907                         }
1908                         else
1909                         {
1910                                 // fog sky
1911                                 GL_BlendFunc(GL_ONE, GL_ZERO);
1912                         }
1913                         GL_DepthMask(true);
1914                         GL_DepthTest(true);
1915
1916                         memset(&m, 0, sizeof(m));
1917                         R_Mesh_State_Texture(&m);
1918
1919                         GL_VertexPointer(face->data_vertex3f);
1920                         R_Mesh_Draw(face->numvertices, face->numtriangles, face->data_element3i);
1921                         qglColorMask(1,1,1,1);
1922                         return;
1923                 }
1924                 if (face->texture->renderflags & Q3MTEXTURERENDERFLAGS_NODRAW)
1925                         return;
1926         }
1927         R_Mesh_Matrix(&ent->matrix);
1928         face->visframe = r_framecount;
1929         memset(&m, 0, sizeof(m));
1930         GL_BlendFunc(GL_ONE, GL_ZERO);
1931         GL_DepthMask(true);
1932         GL_DepthTest(true);
1933         m.tex[0] = R_GetTexture(face->texture->skin.base);
1934         m.pointer_texcoord[0] = face->data_texcoordtexture2f;
1935         if (face->lightmaptexture)
1936         {
1937                 m.tex[1] = R_GetTexture(face->lightmaptexture);
1938                 m.pointer_texcoord[1] = face->data_texcoordlightmap2f;
1939                 m.texrgbscale[1] = 2;
1940                 GL_Color(1, 1, 1, 1);
1941         }
1942         else
1943         {
1944                 m.texrgbscale[0] = 2;
1945                 GL_ColorPointer(face->data_color4f);
1946         }
1947         R_Mesh_State_Texture(&m);
1948         GL_VertexPointer(face->data_vertex3f);
1949         R_Mesh_Draw(face->numvertices, face->numtriangles, face->data_element3i);
1950 }
1951
1952 /*
1953 void R_Q3BSP_DrawSky(entity_render_t *ent)
1954 {
1955 }
1956 */
1957
1958 void R_Q3BSP_RecursiveWorldNode(entity_render_t *ent, q3mnode_t *node, const vec3_t modelorg, qbyte *pvs, int markframe)
1959 {
1960         int i;
1961         q3mleaf_t *leaf;
1962         q3mface_t *face;
1963         while (node->isnode)
1964         {
1965                 if (R_CullBox(node->mins, node->maxs))
1966                         return;
1967                 R_Q3BSP_RecursiveWorldNode(ent, node->children[0], modelorg, pvs, markframe);
1968                 node = node->children[1];
1969         }
1970         if (R_CullBox(node->mins, node->maxs))
1971                 return;
1972         leaf = (q3mleaf_t *)node;
1973         if (pvs[leaf->clusterindex >> 3] & (1 << (leaf->clusterindex & 7)))
1974         {
1975                 for (i = 0;i < leaf->numleaffaces;i++)
1976                 {
1977                         face = leaf->firstleafface[i];
1978                         if (face->markframe != markframe)
1979                         {
1980                                 face->markframe = markframe;
1981                                 if (!R_CullBox(face->mins, face->maxs))
1982                                         R_Q3BSP_DrawFace(ent, face);
1983                         }
1984                 }
1985         }
1986 }
1987
1988
1989
1990 void R_Q3BSP_Draw(entity_render_t *ent)
1991 {
1992         int i;
1993         q3mface_t *face;
1994         vec3_t modelorg;
1995         model_t *model;
1996         qbyte *pvs;
1997         static int markframe = 0;
1998         R_Mesh_Matrix(&ent->matrix);
1999         model = ent->model;
2000         if (r_drawcollisionbrushes.integer < 2)
2001         {
2002                 Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
2003                 if (ent == &cl_entities[0].render && model->brushq3.num_pvsclusters && !r_novis.integer && (pvs = model->brush.GetPVS(model, modelorg)))
2004                         R_Q3BSP_RecursiveWorldNode(ent, model->brushq3.data_nodes, modelorg, pvs, ++markframe);
2005                 else
2006                         for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
2007                                 R_Q3BSP_DrawFace(ent, face);
2008         }
2009         if (r_drawcollisionbrushes.integer >= 1)
2010         {
2011                 rmeshstate_t m;
2012                 memset(&m, 0, sizeof(m));
2013                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2014                 GL_DepthMask(false);
2015                 GL_DepthTest(true);
2016                 R_Mesh_State_Texture(&m);
2017                 for (i = 0;i < model->brushq3.data_thismodel->numbrushes;i++)
2018                         if (model->brushq3.data_thismodel->firstbrush[i].colbrushf && model->brushq3.data_thismodel->firstbrush[i].colbrushf->numtriangles)
2019                                 R_DrawCollisionBrush(model->brushq3.data_thismodel->firstbrush[i].colbrushf);
2020         }
2021 }
2022
2023 void R_Q3BSP_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius)
2024 {
2025         int i;
2026         q3mface_t *face;
2027         vec3_t modelorg, lightmins, lightmaxs;
2028         model_t *model;
2029         float projectdistance;
2030         projectdistance = 1000000000.0f;//lightradius + ent->model->radius;
2031         if (r_drawcollisionbrushes.integer < 2)
2032         {
2033                 model = ent->model;
2034                 R_Mesh_Matrix(&ent->matrix);
2035                 Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
2036                 lightmins[0] = relativelightorigin[0] - lightradius;
2037                 lightmins[1] = relativelightorigin[1] - lightradius;
2038                 lightmins[2] = relativelightorigin[2] - lightradius;
2039                 lightmaxs[0] = relativelightorigin[0] + lightradius;
2040                 lightmaxs[1] = relativelightorigin[1] + lightradius;
2041                 lightmaxs[2] = relativelightorigin[2] + lightradius;
2042                 //if (ent == &cl_entities[0].render && model->brushq3.num_pvsclusters && !r_novis.integer && (pvs = model->brush.GetPVS(model, modelorg)))
2043                 //      R_Q3BSP_RecursiveWorldNode(ent, model->brushq3.data_nodes, modelorg, pvs, ++markframe);
2044                 //else
2045                         for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
2046                                 if (BoxesOverlap(lightmins, lightmaxs, face->mins, face->maxs))
2047                                         R_Shadow_Volume(face->numvertices, face->numtriangles, face->data_vertex3f, face->data_element3i, face->data_neighbor3i, relativelightorigin, lightradius, projectdistance);
2048         }
2049 }
2050
2051 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)
2052 {
2053         if ((face->texture->renderflags & Q3MTEXTURERENDERFLAGS_NODRAW) || !face->numtriangles)
2054                 return;
2055         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);
2056         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);
2057 }
2058
2059 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)
2060 {
2061         int i;
2062         q3mface_t *face;
2063         vec3_t modelorg, lightmins, lightmaxs;
2064         model_t *model;
2065         //qbyte *pvs;
2066         //static int markframe = 0;
2067         if (r_drawcollisionbrushes.integer < 2)
2068         {
2069                 model = ent->model;
2070                 R_Mesh_Matrix(&ent->matrix);
2071                 Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
2072                 lightmins[0] = relativelightorigin[0] - lightradius;
2073                 lightmins[1] = relativelightorigin[1] - lightradius;
2074                 lightmins[2] = relativelightorigin[2] - lightradius;
2075                 lightmaxs[0] = relativelightorigin[0] + lightradius;
2076                 lightmaxs[1] = relativelightorigin[1] + lightradius;
2077                 lightmaxs[2] = relativelightorigin[2] + lightradius;
2078                 //if (ent == &cl_entities[0].render && model->brushq3.num_pvsclusters && !r_novis.integer && (pvs = model->brush.GetPVS(model, modelorg)))
2079                 //      R_Q3BSP_RecursiveWorldNode(ent, model->brushq3.data_nodes, modelorg, pvs, ++markframe);
2080                 //else
2081                         for (i = 0, face = model->brushq3.data_thismodel->firstface;i < model->brushq3.data_thismodel->numfaces;i++, face++)
2082                                 if ((ent != &cl_entities[0].render || face->visframe == r_framecount) && BoxesOverlap(lightmins, lightmaxs, face->mins, face->maxs))
2083                                         R_Q3BSP_DrawFaceLight(ent, face, relativelightorigin, relativeeyeorigin, lightradius, lightcolor, matrix_modeltofilter, matrix_modeltoattenuationxyz, matrix_modeltoattenuationz);
2084         }
2085 }
2086
2087 static void gl_surf_start(void)
2088 {
2089 }
2090
2091 static void gl_surf_shutdown(void)
2092 {
2093 }
2094
2095 static void gl_surf_newmap(void)
2096 {
2097 }
2098
2099 void GL_Surf_Init(void)
2100 {
2101         int i;
2102         dlightdivtable[0] = 4194304;
2103         for (i = 1;i < 32768;i++)
2104                 dlightdivtable[i] = 4194304 / (i << 7);
2105
2106         Cvar_RegisterVariable(&r_ambient);
2107         Cvar_RegisterVariable(&r_drawportals);
2108         Cvar_RegisterVariable(&r_testvis);
2109         Cvar_RegisterVariable(&r_floatbuildlightmap);
2110         Cvar_RegisterVariable(&r_detailtextures);
2111         Cvar_RegisterVariable(&r_surfaceworldnode);
2112         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonoffset);
2113
2114         R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
2115 }
2116