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