a big change with a little description...
[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
24 int             lightmap_textures;
25
26 // LordHavoc: skinny but tall lightmaps for quicker subimage uploads
27 #define BLOCK_WIDTH             256
28 #define BLOCK_HEIGHT    256
29 // LordHavoc: increased lightmap limit from 64 to 1024
30 #define MAX_LIGHTMAPS   1024
31 #define LIGHTMAPSIZE    (BLOCK_WIDTH*BLOCK_HEIGHT*4)
32
33 int                     active_lightmaps;
34
35 short allocated[MAX_LIGHTMAPS][BLOCK_WIDTH];
36
37 byte *lightmaps[MAX_LIGHTMAPS];
38 short lightmapupdate[MAX_LIGHTMAPS][2];
39
40 signed int blocklights[BLOCK_WIDTH*BLOCK_HEIGHT*3]; // LordHavoc: *3 for colored lighting
41
42 int lightmapalign, lightmapalignmask; // LordHavoc: NVIDIA's broken subimage fix, see BuildLightmaps for notes
43 cvar_t gl_lightmapalign = {"gl_lightmapalign", "4"};
44 cvar_t gl_lightmaprgba = {"gl_lightmaprgba", "1"};
45 cvar_t gl_nosubimagefragments = {"gl_nosubimagefragments", "0"};
46 cvar_t gl_nosubimage = {"gl_nosubimage", "0"};
47 cvar_t r_ambient = {"r_ambient", "0"};
48 cvar_t gl_vertex = {"gl_vertex", "0"};
49 cvar_t gl_texsort = {"gl_texsort", "1"};
50 cvar_t r_newworldnode = {"r_newworldnode", "0"};
51 cvar_t r_oldclip = {"r_oldclip", "1"};
52 cvar_t r_dlightmap = {"r_dlightmap", "1"};
53
54 qboolean lightmaprgba, nosubimagefragments, nosubimage, skyisvisible;
55 int lightmapbytes;
56
57 void gl_surf_start()
58 {
59 }
60
61 void gl_surf_shutdown()
62 {
63 }
64
65 void gl_surf_newmap()
66 {
67 }
68
69 void GL_Surf_Init()
70 {
71         int i;
72         for (i = 0;i < MAX_LIGHTMAPS;i++)
73                 lightmaps[i] = NULL;
74         Cvar_RegisterVariable(&gl_lightmapalign);
75         Cvar_RegisterVariable(&gl_lightmaprgba);
76         Cvar_RegisterVariable(&gl_nosubimagefragments);
77         Cvar_RegisterVariable(&gl_nosubimage);
78         Cvar_RegisterVariable(&r_ambient);
79         Cvar_RegisterVariable(&gl_vertex);
80         Cvar_RegisterVariable(&gl_texsort);
81         Cvar_RegisterVariable(&r_newworldnode);
82         Cvar_RegisterVariable(&r_oldclip);
83         Cvar_RegisterVariable(&r_dlightmap);
84
85         R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
86 }
87
88 int         dlightdivtable[32768];
89
90 /*
91         R_AddDynamicLights
92 */
93 int R_AddDynamicLights (msurface_t *surf)
94 {
95         int         sdtable[18], lnum, td, maxdist, maxdist2, maxdist3, i, s, t, smax, tmax, red, green, blue, lit, dist2, impacts, impactt;
96         unsigned int *bl;
97         float       dist;
98         vec3_t      impact, local;
99
100         // LordHavoc: use 64bit integer...  shame it's not very standardized...
101 #if _MSC_VER || __BORLANDC__
102         __int64     k;
103 #else
104         long long   k;
105 #endif
106
107         lit = false;
108
109         if (!dlightdivtable[1])
110         {
111                 dlightdivtable[0] = 4194304;
112                 for (s = 1; s < 32768; s++)
113                         dlightdivtable[s] = 4194304 / (s << 7);
114         }
115
116         smax = (surf->extents[0] >> 4) + 1;
117         tmax = (surf->extents[1] >> 4) + 1;
118
119         for (lnum = 0; lnum < MAX_DLIGHTS; lnum++)
120         {
121                 if (!(surf->dlightbits[lnum >> 5] & (1 << (lnum & 31))))
122                         continue;                                       // not lit by this light
123
124                 VectorSubtract (cl_dlights[lnum].origin, currententity->render.origin, local);
125                 dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
126
127                 // for comparisons to minimum acceptable light
128                 maxdist = (int) ((cl_dlights[lnum].radius * cl_dlights[lnum].radius));
129
130                 // clamp radius to avoid exceeding 32768 entry division table
131                 if (maxdist > 4194304)
132                         maxdist = 4194304;
133
134                 dist2 = dist * dist;
135                 if (dist2 >= maxdist)
136                         continue;
137
138                 impact[0] = cl_dlights[lnum].origin[0] - surf->plane->normal[0] * dist;
139                 impact[1] = cl_dlights[lnum].origin[1] - surf->plane->normal[1] * dist;
140                 impact[2] = cl_dlights[lnum].origin[2] - surf->plane->normal[2] * dist;
141
142                 impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
143                 impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
144
145                 s = bound(0, impacts, smax * 16) - impacts;
146                 t = bound(0, impactt, tmax * 16) - impactt;
147                 i = s * s + t * t + dist2;
148                 if (i > maxdist)
149                         continue;
150
151                 // reduce calculations
152                 for (s = 0, i = impacts; s < smax; s++, i -= 16)
153                         sdtable[s] = i * i + dist2 + LIGHTOFFSET;
154
155                 maxdist3 = maxdist - (int) (dist * dist);
156
157                 // convert to 8.8 blocklights format and scale up by radius
158                 red = cl_dlights[lnum].color[0] * maxdist;
159                 green = cl_dlights[lnum].color[1] * maxdist;
160                 blue = cl_dlights[lnum].color[2] * maxdist;
161                 bl = blocklights;
162
163                 i = impactt;
164                 for (t = 0; t < tmax; t++, i -= 16)
165                 {
166                         td = i * i;
167                         // make sure some part of it is visible on this line
168                         if (td < maxdist3)
169                         {
170                                 maxdist2 = maxdist - td;
171                                 for (s = 0; s < smax; s++)
172                                 {
173                                         if (sdtable[s] < maxdist2)
174                                         {
175                                                 k = dlightdivtable[(sdtable[s] + td) >> 7];
176                                                 bl[0] += (red   * k) >> 9;
177                                                 bl[1] += (green * k) >> 9;
178                                                 bl[2] += (blue  * k) >> 9;
179                                                 lit = true;
180                                         }
181                                         bl += 3;
182                                 }
183                         }
184                         else // skip line
185                                 bl += smax * 3;
186                 }
187         }
188         return lit;
189 }
190
191
192 void R_ConvertLightmap (int *in, byte *out, int width, int height, int stride)
193 {
194         int i, j;
195         stride -= (width*lightmapbytes);
196         if (lighthalf)
197         {
198                 // LordHavoc: I shift down by 8 unlike GLQuake's 7,
199                 // the image is brightened as a processing pass
200                 if (lightmaprgba)
201                 {
202                         for (i = 0;i < height;i++, out += stride)
203                         {
204                                 for (j = 0;j < width;j++, in += 3, out += 4)
205                                 {
206                                         out[0] = min(in[0] >> 8, 255);
207                                         out[1] = min(in[1] >> 8, 255);
208                                         out[2] = min(in[2] >> 8, 255);
209                                         out[3] = 255;
210                                 }
211                         }
212                 }
213                 else
214                 {
215                         for (i = 0;i < height;i++, out += stride)
216                         {
217                                 for (j = 0;j < width;j++, in += 3, out += 3)
218                                 {
219                                         out[0] = min(in[0] >> 8, 255);
220                                         out[1] = min(in[1] >> 8, 255);
221                                         out[2] = min(in[2] >> 8, 255);
222                                 }
223                         }
224                 }
225         }
226         else
227         {
228                 if (lightmaprgba)
229                 {
230                         for (i = 0;i < height;i++, out += stride)
231                         {
232                                 for (j = 0;j < width;j++, in += 3, out += 4)
233                                 {
234                                         out[0] = min(in[0] >> 7, 255);
235                                         out[1] = min(in[1] >> 7, 255);
236                                         out[2] = min(in[2] >> 7, 255);
237                                         out[3] = 255;
238                                 }
239                         }
240                 }
241                 else
242                 {
243                         for (i = 0;i < height;i++, out += stride)
244                         {
245                                 for (j = 0;j < width;j++, in += 3, out += 3)
246                                 {
247                                         out[0] = min(in[0] >> 7, 255);
248                                         out[1] = min(in[1] >> 7, 255);
249                                         out[2] = min(in[2] >> 7, 255);
250                                 }
251                         }
252                 }
253         }
254 }
255
256 /*
257 ===============
258 R_BuildLightMap
259
260 Combine and scale multiple lightmaps into the 8.8 format in blocklights
261 ===============
262 */
263 void R_BuildLightMap (msurface_t *surf, byte *dest, int stride)
264 {
265         int                     smax, tmax;
266         int                     i, j, size, size3;
267         byte            *lightmap;
268         int                     scale;
269         int                     maps;
270         int                     *bl;
271
272         surf->cached_dlight = 0;
273         surf->cached_lighthalf = lighthalf;
274         surf->cached_ambient = r_ambient.value;
275
276         smax = (surf->extents[0]>>4)+1;
277         tmax = (surf->extents[1]>>4)+1;
278         size = smax*tmax;
279         size3 = size*3;
280         lightmap = surf->samples;
281
282 // set to full bright if no light data
283         if ((currententity && (currententity->render.effects & EF_FULLBRIGHT)) || !cl.worldmodel->lightdata)
284         {
285                 bl = blocklights;
286                 for (i=0 ; i<size ; i++)
287                 {
288                         *bl++ = 255*256;
289                         *bl++ = 255*256;
290                         *bl++ = 255*256;
291                 }
292         }
293         else
294         {
295 // clear to no light
296                 j = r_ambient.value * 512.0f; // would be 256.0f logically, but using 512.0f to match winquake style
297                 if (j)
298                 {
299                         bl = blocklights;
300                         for (i = 0;i < size3;i++)
301                                 *bl++ = j;
302                 }
303                 else
304                         memset(&blocklights[0], 0, size*3*sizeof(int));
305
306 // add all the lightmaps
307                 if (lightmap)
308                 {
309                         for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++)
310                         {
311                                 scale = d_lightstylevalue[surf->styles[maps]];
312                                 surf->cached_light[maps] = scale;       // 8.8 fraction
313                                 bl = blocklights;
314                                 for (i = 0;i < size3;i++)
315                                         *bl++ += *lightmap++ * scale;
316                         }
317                 }
318                 if (r_dlightmap.value && surf->dlightframe == r_dlightframecount)
319                         if ((surf->cached_dlight = R_AddDynamicLights(surf)))
320                                 c_light_polys++;
321         }
322         R_ConvertLightmap(blocklights, dest, smax, tmax, stride);
323 }
324
325 byte templight[BLOCK_WIDTH*BLOCK_HEIGHT*4];
326
327 void R_UpdateLightmap(msurface_t *s, int lnum)
328 {
329         int smax, tmax;
330         // upload the new lightmap texture fragment
331         if(r_upload.value)
332                 glBindTexture(GL_TEXTURE_2D, lightmap_textures + lnum);
333         if (nosubimage || nosubimagefragments)
334         {
335                 if (lightmapupdate[lnum][0] > s->light_t)
336                         lightmapupdate[lnum][0] = s->light_t;
337                 if (lightmapupdate[lnum][1] < (s->light_t + ((s->extents[1]>>4)+1)))
338                         lightmapupdate[lnum][1] = (s->light_t + ((s->extents[1]>>4)+1));
339                 if (lightmaprgba)
340                         R_BuildLightMap (s, lightmaps[s->lightmaptexturenum] + (s->light_t * BLOCK_WIDTH + s->light_s) * 4, BLOCK_WIDTH * 4);
341                 else
342                         R_BuildLightMap (s, lightmaps[s->lightmaptexturenum] + (s->light_t * BLOCK_WIDTH + s->light_s) * 3, BLOCK_WIDTH * 3);
343         }
344         else
345         {
346                 smax = ((s->extents[0]>>4)+lightmapalign) & lightmapalignmask;
347                 tmax = (s->extents[1]>>4)+1;
348                 if (lightmaprgba)
349                 {
350                         R_BuildLightMap (s, templight, smax * 4);
351                         if(r_upload.value)
352                                 glTexSubImage2D(GL_TEXTURE_2D, 0, s->light_s, s->light_t, smax, tmax, GL_RGBA, GL_UNSIGNED_BYTE, templight);
353                 }
354                 else
355                 {
356                         R_BuildLightMap (s, templight, smax * 3);
357                         if(r_upload.value)
358                                 glTexSubImage2D(GL_TEXTURE_2D, 0, s->light_s, s->light_t, smax, tmax, GL_RGB , GL_UNSIGNED_BYTE, templight);
359                 }
360         }
361 }
362
363
364 /*
365 ===============
366 R_TextureAnimation
367
368 Returns the proper texture for a given time and base texture
369 ===============
370 */
371 texture_t *R_TextureAnimation (texture_t *base)
372 {
373         texture_t *original;
374         int             relative;
375         int             count;
376
377         if (currententity->render.frame)
378         {
379                 if (base->alternate_anims)
380                         base = base->alternate_anims;
381         }
382         
383         if (!base->anim_total)
384                 return base;
385
386         original = base;
387
388         relative = (int)(cl.time*10) % base->anim_total;
389
390         count = 0;      
391         while (base->anim_min > relative || base->anim_max <= relative)
392         {
393                 base = base->anim_next;
394                 if (!base)
395                 {
396                         Con_Printf("R_TextureAnimation: broken cycle");
397                         return original;
398                 }
399                 if (++count > 100)
400                 {
401                         Con_Printf("R_TextureAnimation: infinite cycle");
402                         return original;
403                 }
404         }
405
406         return base;
407 }
408
409
410 /*
411 =============================================================
412
413         BRUSH MODELS
414
415 =============================================================
416 */
417
418
419 extern  int             solidskytexture;
420 extern  int             alphaskytexture;
421 extern  float   speedscale;             // for top sky and bottom sky
422
423 extern char skyname[];
424
425 float   turbsin[256] =
426 {
427         #include "gl_warp_sin.h"
428 };
429 #define TURBSCALE (256.0 / (2 * M_PI))
430
431
432 void UploadLightmaps()
433 {
434         int i;
435         if (nosubimage || nosubimagefragments)
436         {
437                 for (i = 0;i < MAX_LIGHTMAPS;i++)
438                 {
439                         if (lightmapupdate[i][0] < lightmapupdate[i][1])
440                         {
441                                 if(r_upload.value)
442                                 {
443                                         glBindTexture(GL_TEXTURE_2D, lightmap_textures + i);
444                                         if (nosubimage)
445                                         {
446                                                 if (lightmaprgba)
447                                                         glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i]);
448                                                 else
449                                                         glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i]);
450                                         }
451                                         else
452                                         {
453                                                 if (lightmaprgba)
454                                                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, lightmapupdate[i][0], BLOCK_WIDTH, lightmapupdate[i][1] - lightmapupdate[i][0], GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i] + (BLOCK_WIDTH * 4 * lightmapupdate[i][0]));
455                                                 else
456                                                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, lightmapupdate[i][0], BLOCK_WIDTH, lightmapupdate[i][1] - lightmapupdate[i][0], GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i] + (BLOCK_WIDTH * 3 * lightmapupdate[i][0]));
457                                         }
458                                 }
459                         }
460                         lightmapupdate[i][0] = BLOCK_HEIGHT;
461                         lightmapupdate[i][1] = 0;
462                 }
463         }
464 }
465
466 float   wvert[1024*6]; // used by the following functions
467
468 void RSurf_DrawSky(msurface_t *s, int transform)
469 {
470         glpoly_t *p;
471         int i;
472         float *v;
473         for (p=s->polys ; p ; p=p->next)
474         {
475                 if (currentskypoly < MAX_SKYPOLYS && currentskyvert + p->numverts <= MAX_SKYVERTS)
476                 {
477                         skypoly[currentskypoly].firstvert = currentskyvert;
478                         skypoly[currentskypoly++].verts = p->numverts;
479                         if (transform)
480                         {
481                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
482                                 {
483                                         softwaretransform(v, skyvert[currentskyvert].v);
484                                         currentskyvert++;
485                                 }
486                         }
487                         else
488                         {
489                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
490                                 {
491                                         VectorCopy(v, skyvert[currentskyvert].v);
492                                         currentskyvert++;
493                                 }
494                         }
495                 }
496         }
497 }
498
499 int RSurf_Light(int *dlightbits, glpoly_t *polys)
500 {
501         float           cr, cg, cb, radius, radius2, f, *v, *wv;
502         int                     i, a, b, lit = false;
503         unsigned int c, d;
504         dlight_t        *light;
505         vec_t           *lightorigin;
506         glpoly_t        *p;
507         for (a = 0;a < 8;a++)
508         {
509                 if ((c = dlightbits[a]))
510                 {
511                         for (b = 0, d = 1;c;b++, d <<= 1)
512                         {
513                                 if (c & d)
514                                 {
515                                         c -= d;
516                                         light = &cl_dlights[a * 32 + b];
517                                         lightorigin = light->origin;
518                                         cr = light->color[0];
519                                         cg = light->color[1];
520                                         cb = light->color[2];
521                                         radius = light->radius*light->radius;
522                                         radius2 = radius * 256.0f;
523                                         wv = wvert;
524                                         for (p = polys;p;p = p->next)
525                                         {
526                                                 for (i = 0, v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
527                                                 {
528                                                         f = VectorDistance2(wv, lightorigin);
529                                                         if (f < radius)
530                                                         {
531                                                                 f = radius2 / (f + LIGHTOFFSET);
532                                                                 wv[3] += cr * f;
533                                                                 wv[4] += cg * f;
534                                                                 wv[5] += cb * f;
535                                                                 lit = true;
536                                                         }
537                                                         wv += 6;
538                                                 }
539                                         }
540                                 }
541                         }
542                 }
543         }
544         return lit;
545 }
546
547 void RSurf_DrawWater(msurface_t *s, texture_t *t, int transform, int alpha)
548 {
549         int             i;
550         float   os = turbsin[(int)(realtime * TURBSCALE) & 255], ot = turbsin[(int)(cl.time * TURBSCALE + 96.0) & 255];
551         glpoly_t *p;
552         float   *v;
553         // FIXME: make fog texture if water texture is transparent?
554
555         if (s->dlightframe != r_dlightframecount)
556         {
557                 vec3_t temp;
558                 // LordHavoc: fast path for no vertex lighting cases
559                 if (transform)
560                 {
561                         if (r_waterripple.value)
562                         {
563                                 for (p=s->polys ; p ; p=p->next)
564                                 {
565                                         transpolybegin(R_GetTexture(t->texture), R_GetTexture(t->glowtexture), 0, TPOLYTYPE_ALPHA);
566                                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
567                                         {
568                                                 softwaretransform(v, temp);
569                                                 transpolyvert(temp[0], temp[1], temp[2] + r_waterripple.value * turbsin[(int)((temp[0]*(1.0f/32.0f)+cl.time) * TURBSCALE) & 255] * turbsin[(int)((temp[1]*(1.0f/32.0f)+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f), (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), 128, 128, 128, alpha);
570                                         }
571                                         transpolyend();
572                                 }
573                         }
574                         else
575                         {
576                                 for (p=s->polys ; p ; p=p->next)
577                                 {
578                                         transpolybegin(R_GetTexture(t->texture), R_GetTexture(t->glowtexture), 0, TPOLYTYPE_ALPHA);
579                                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
580                                         {
581                                                 softwaretransform(v, temp);
582                                                 transpolyvert(temp[0], temp[1], temp[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), 128, 128, 128, alpha);
583                                         }
584                                         transpolyend();
585                                 }
586                         }
587                 }
588                 else
589                 {
590                         if (r_waterripple.value)
591                         {
592                                 for (p=s->polys ; p ; p=p->next)
593                                 {
594                                         transpolybegin(R_GetTexture(t->texture), R_GetTexture(t->glowtexture), 0, TPOLYTYPE_ALPHA);
595                                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
596                                                 transpolyvert(v[0], v[1], v[2] + r_waterripple.value * turbsin[(int)((v[0]*(1.0f/32.0f)+cl.time) * TURBSCALE) & 255] * turbsin[(int)((v[1]*(1.0f/32.0f)+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f), (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), 128, 128, 128, alpha);
597                                         transpolyend();
598                                 }
599                         }
600                         else
601                         {
602                                 for (p=s->polys ; p ; p=p->next)
603                                 {
604                                         transpolybegin(R_GetTexture(t->texture), R_GetTexture(t->glowtexture), 0, TPOLYTYPE_ALPHA);
605                                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
606                                                 transpolyvert(v[0], v[1], v[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), 128, 128, 128, alpha);
607                                         transpolyend();
608                                 }
609                         }
610                 }
611         }
612         else
613         {
614                 float *wv;
615                 wv = wvert;
616                 for (p = s->polys;p;p = p->next)
617                 {
618                         for (i = 0, v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
619                         {
620                                 if (transform)
621                                         softwaretransform(v, wv);
622                                 else
623                                         VectorCopy(v, wv);
624                                 if (r_waterripple.value)
625                                         wv[2] += r_waterripple.value * turbsin[(int)((wv[0]*(1.0f/32.0f)+cl.time) * TURBSCALE) & 255] * turbsin[(int)((wv[1]*(1.0f/32.0f)+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f);
626                                 wv[3] = wv[4] = wv[5] = 128.0f;
627                                 wv += 6;
628                         }
629                 }
630                 if (s->dlightframe == r_dlightframecount)
631                         RSurf_Light(s->dlightbits, s->polys);
632                 wv = wvert;
633                 for (p=s->polys ; p ; p=p->next)
634                 {
635                         transpolybegin(R_GetTexture(t->texture), R_GetTexture(t->glowtexture), 0, TPOLYTYPE_ALPHA);
636                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE, wv += 6)
637                                 transpolyvert(wv[0], wv[1], wv[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), wv[3], wv[4], wv[5], alpha);
638                         transpolyend();
639                 }
640         }
641 }
642
643 void RSurf_DrawWall(msurface_t *s, texture_t *t, int transform)
644 {
645         int             i, lit = false, polys = 0, verts = 0;
646         float   *v;
647         glpoly_t *p;
648         wallpoly_t *wp;
649         wallvert_t *out;
650         wallvertcolor_t *outcolor;
651         // check for lightmap modification
652         if (s->cached_dlight
653          || (r_dynamic.value && r_dlightmap.value && s->dlightframe == r_dlightframecount)
654          || r_ambient.value != s->cached_ambient
655          || lighthalf != s->cached_lighthalf
656          || (r_dynamic.value
657          && ((s->styles[0] != 255 && d_lightstylevalue[s->styles[0]] != s->cached_light[0])
658          || (s->styles[1] != 255 && d_lightstylevalue[s->styles[1]] != s->cached_light[1])
659          || (s->styles[2] != 255 && d_lightstylevalue[s->styles[2]] != s->cached_light[2])
660          || (s->styles[3] != 255 && d_lightstylevalue[s->styles[3]] != s->cached_light[3]))))
661                 R_UpdateLightmap(s, s->lightmaptexturenum);
662         if (r_dlightmap.value || s->dlightframe != r_dlightframecount)
663         {
664                 // LordHavoc: fast path version for no vertex lighting cases
665                 wp = &wallpoly[currentwallpoly];
666                 out = &wallvert[currentwallvert];
667                 for (p = s->polys;p;p = p->next)
668                 {
669                         if ((currentwallpoly >= MAX_WALLPOLYS) || (currentwallvert+p->numverts > MAX_WALLVERTS))
670                                 return;
671                         wp->texnum = (unsigned short) R_GetTexture(t->texture);
672                         wp->lighttexnum = (unsigned short) (lightmap_textures + s->lightmaptexturenum);
673                         wp->glowtexnum = (unsigned short) R_GetTexture(t->glowtexture);
674                         wp->firstvert = currentwallvert;
675                         wp->numverts = p->numverts;
676                         wp->lit = lit;
677                         wp++;
678                         currentwallpoly++;
679                         currentwallvert += p->numverts;
680                         v = p->verts[0];
681                         if (transform)
682                         {
683                                 for (i = 0;i < p->numverts;i++, v += VERTEXSIZE, out++)
684                                 {
685                                         softwaretransform(v, out->vert);
686                                         out->vert[3] = v[3];
687                                         out->vert[4] = v[4];
688                                         out->vert[5] = v[5];
689                                         out->vert[6] = v[6];
690                                 }
691                         }
692                         else
693                         {
694                                 /*
695                                 for (i = 0;i < p->numverts;i++, v += VERTEXSIZE, out++)
696                                 {
697                                         VectorCopy(v, out->vert);
698                                         out->vert[3] = v[3];
699                                         out->vert[4] = v[4];
700                                         out->vert[5] = v[5];
701                                         out->vert[6] = v[6];
702                                 }
703                                 */
704                                 memcpy(out, v, sizeof(vec_t) * VERTEXSIZE * p->numverts);
705                                 out += p->numverts;
706                         }
707                 }
708         }
709         else
710         {
711                 float *wv;
712                 wv = wvert;
713                 for (p = s->polys;p;p = p->next)
714                 {
715                         for (i = 0, v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
716                         {
717                                 if (transform)
718                                         softwaretransform(v, wv);
719                                 else
720                                         VectorCopy(v, wv);
721                                 wv[3] = wv[4] = wv[5] = 0.0f;
722                                 wv += 6;
723                         }
724                         verts += p->numverts;
725                         polys++;
726                 }
727                 if ((currentwallpoly + polys > MAX_WALLPOLYS) || (currentwallvert+verts > MAX_WALLVERTS))
728                         return;
729                 if ((!r_dlightmap.value) && s->dlightframe == r_dlightframecount)
730                         lit = RSurf_Light(s->dlightbits, s->polys);
731                 wv = wvert;
732                 wp = &wallpoly[currentwallpoly];
733                 out = &wallvert[currentwallvert];
734                 outcolor = &wallvertcolor[currentwallvert];
735                 currentwallpoly += polys;
736                 for (p = s->polys;p;p = p->next)
737                 {
738                         v = p->verts[0];
739                         wp->texnum = (unsigned short) R_GetTexture(t->texture);
740                         wp->lighttexnum = (unsigned short) (lightmap_textures + s->lightmaptexturenum);
741                         wp->glowtexnum = (unsigned short) R_GetTexture(t->glowtexture);
742                         wp->firstvert = currentwallvert;
743                         wp->numverts = p->numverts;
744                         wp->lit = lit;
745                         wp++;
746                         currentwallvert += p->numverts;
747                         for (i = 0;i < p->numverts;i++, v += VERTEXSIZE, wv += 6, out++, outcolor++)
748                         {
749                                 if (lit)
750                                 {
751                                         if (lighthalf)
752                                         {
753                                                 outcolor->r = (byte) (bound(0, (int) wv[3] >> 1, 255));
754                                                 outcolor->g = (byte) (bound(0, (int) wv[4] >> 1, 255));
755                                                 outcolor->b = (byte) (bound(0, (int) wv[5] >> 1, 255));
756                                                 outcolor->a = 255;
757                                         }
758                                         else
759                                         {
760                                                 outcolor->r = (byte) (bound(0, (int) wv[3], 255));
761                                                 outcolor->g = (byte) (bound(0, (int) wv[4], 255));
762                                                 outcolor->b = (byte) (bound(0, (int) wv[5], 255));
763                                                 outcolor->a = 255;
764                                         }
765                                 }
766                                 out->vert[0] = wv[0];
767                                 out->vert[1] = wv[1];
768                                 out->vert[2] = wv[2];
769                                 out->vert[3] = v[3];
770                                 out->vert[4] = v[4];
771                                 out->vert[5] = v[5];
772                                 out->vert[6] = v[6];
773                         }
774                 }
775         }
776 }
777
778 // LordHavoc: transparent brush models
779 extern float modelalpha;
780
781 void RSurf_DrawWallVertex(msurface_t *s, texture_t *t, int transform, int isbmodel)
782 {
783         int i, alpha, size3;
784         float *v, *wv, scale;
785         glpoly_t *p;
786         byte *lm;
787         alpha = (int) (modelalpha * 255.0f);
788         size3 = ((s->extents[0]>>4)+1)*((s->extents[1]>>4)+1)*3; // *3 for colored lighting
789         wv = wvert;
790         for (p = s->polys;p;p = p->next)
791         {
792                 for (i = 0, v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
793                 {
794                         if (transform)
795                                 softwaretransform(v, wv);
796                         else
797                                 VectorCopy(v, wv);
798                         wv[3] = wv[4] = wv[5] = r_ambient.value * 2.0f;
799                         if (s->styles[0] != 255)
800                         {
801                                 lm = (byte *)((long) s->samples + (int) v[7]);
802                                 scale = d_lightstylevalue[s->styles[0]] * (1.0f / 128.0f);wv[3] += lm[size3*0+0] * scale;wv[4] += lm[size3*0+1] * scale;wv[5] += lm[size3*0+2] * scale;
803                                 if (s->styles[1] != 255)
804                                 {
805                                         scale = d_lightstylevalue[s->styles[1]] * (1.0f / 128.0f);wv[3] += lm[size3*1+0] * scale;wv[4] += lm[size3*1+1] * scale;wv[5] += lm[size3*1+2] * scale;
806                                         if (s->styles[2] != 255)
807                                         {
808                                                 scale = d_lightstylevalue[s->styles[2]] * (1.0f / 128.0f);wv[3] += lm[size3*2+0] * scale;wv[4] += lm[size3*2+1] * scale;wv[5] += lm[size3*2+2] * scale;
809                                                 if (s->styles[3] != 255)
810                                                 {
811                                                         scale = d_lightstylevalue[s->styles[3]] * (1.0f / 128.0f);wv[3] += lm[size3*3+0] * scale;wv[4] += lm[size3*3+1] * scale;wv[5] += lm[size3*3+2] * scale;
812                                                 }
813                                         }
814                                 }
815                         }
816                         wv += 6;
817                 }
818         }
819         if (s->dlightframe == r_dlightframecount)
820                 RSurf_Light(s->dlightbits, s->polys);
821         wv = wvert;
822         if (isbmodel && (currententity->render.colormod[0] != 1 || currententity->render.colormod[1] != 1 || currententity->render.colormod[2] != 1))
823         {
824                 for (p = s->polys;p;p = p->next)
825                 {
826                         v = p->verts[0];
827                         transpolybegin(R_GetTexture(t->texture), R_GetTexture(t->glowtexture), 0, currententity->render.effects & EF_ADDITIVE ? TPOLYTYPE_ADD : TPOLYTYPE_ALPHA);
828                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE, wv += 6)
829                                 transpolyvert(wv[0], wv[1], wv[2], v[3], v[4], wv[3] * currententity->render.colormod[0], wv[4] * currententity->render.colormod[1], wv[5] * currententity->render.colormod[2], alpha);
830                         transpolyend();
831                 }
832         }
833         else
834         {
835                 for (p = s->polys;p;p = p->next)
836                 {
837                         v = p->verts[0];
838                         transpolybegin(R_GetTexture(t->texture), R_GetTexture(t->glowtexture), 0, currententity->render.effects & EF_ADDITIVE ? TPOLYTYPE_ADD : TPOLYTYPE_ALPHA);
839                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE, wv += 6)
840                                 transpolyvert(wv[0], wv[1], wv[2], v[3], v[4], wv[3], wv[4], wv[5], alpha);
841                         transpolyend();
842                 }
843         }
844 }
845
846 /*
847 ================
848 DrawTextureChains
849 ================
850 */
851 extern qboolean hlbsp;
852 extern char skyname[];
853 void R_DrawSurf(msurface_t *s, int isbmodel, int vertexlit)
854 {
855         texture_t *t;
856         if (s->flags & SURF_DRAWSKY)
857         {
858                 skyisvisible = true;
859                 if (!hlbsp) // LordHavoc: HalfLife maps have freaky skypolys...
860                         RSurf_DrawSky(s, false);
861                 return;
862         }
863         t = R_TextureAnimation (s->texinfo->texture);
864         if (s->flags & SURF_DRAWTURB)
865         {
866                 RSurf_DrawWater(s, t, false, s->flags & SURF_DRAWNOALPHA ? 255 : r_wateralpha.value*255.0f);
867                 return;
868         }
869         if (vertexlit)
870                 RSurf_DrawWallVertex(s, t, false, false);
871         else
872                 RSurf_DrawWall(s, t, false);
873 }
874
875 void DrawTextureChains (void)
876 {
877         int                     n;
878         msurface_t      *s;
879         texture_t       *t;
880
881         for (n = 0;n < cl.worldmodel->numtextures;n++)
882         {
883                 if (!cl.worldmodel->textures[n] || !(s = cl.worldmodel->textures[n]->texturechain))
884                         continue;
885                 cl.worldmodel->textures[n]->texturechain = NULL;
886 //              for (;s;s = s->texturechain)
887 //                      R_DrawSurf(s, false, gl_vertex.value);
888                 // LordHavoc: decide the render type only once, because the surface properties were determined by texture anyway
889                 // sky
890                 if (s->flags & SURF_DRAWSKY)
891                 {
892                         skyisvisible = true;
893                         if (!hlbsp) // LordHavoc: HalfLife maps have freaky skypolys...
894                                 for (;s;s = s->texturechain)
895                                         RSurf_DrawSky(s, false);
896                         continue;
897                 }
898                 t = R_TextureAnimation (cl.worldmodel->textures[n]);
899                 // subdivided water surface warp
900                 if (s->flags & SURF_DRAWTURB)
901                 {
902                         int alpha = s->flags & SURF_DRAWNOALPHA ? 255 : r_wateralpha.value*255.0f;
903                         for (;s;s = s->texturechain)
904                                 RSurf_DrawWater(s, t, false, alpha);
905                         continue;
906                 }
907                 if (gl_vertex.value)
908                         for (;s;s = s->texturechain)
909                                 RSurf_DrawWallVertex(s, t, false, false);
910                 else
911                         for (;s;s = s->texturechain)
912                                 RSurf_DrawWall(s, t, false);
913         }
914 }
915
916 void R_NoVisMarkLights (vec3_t lightorigin, dlight_t *light, int bit, int bitindex, model_t *model);
917
918 /*
919 =================
920 R_DrawBrushModel
921 =================
922 */
923 void R_DrawBrushModel (entity_t *e)
924 {
925         int                     i;
926         vec3_t          mins, maxs;
927         msurface_t      *s;
928         model_t         *clmodel;
929         int     rotated, vertexlit = false;
930         texture_t       *t;
931         vec3_t          org;
932
933         currententity = e;
934
935         clmodel = e->render.model;
936
937         if (e->render.angles[0] || e->render.angles[1] || e->render.angles[2])
938         {
939                 rotated = true;
940                 for (i=0 ; i<3 ; i++)
941                 {
942                         mins[i] = e->render.origin[i] - clmodel->radius;
943                         maxs[i] = e->render.origin[i] + clmodel->radius;
944                 }
945         }
946         else
947         {
948                 rotated = false;
949                 VectorAdd (e->render.origin, clmodel->mins, mins);
950                 VectorAdd (e->render.origin, clmodel->maxs, maxs);
951         }
952
953         if (R_CullBox (mins, maxs))
954                 return;
955
956         c_bmodels++;
957
958         VectorSubtract (r_refdef.vieworg, e->render.origin, modelorg);
959         if (rotated)
960         {
961                 vec3_t  temp;
962                 vec3_t  forward, right, up;
963
964                 VectorCopy (modelorg, temp);
965                 AngleVectors (e->render.angles, forward, right, up);
966                 modelorg[0] = DotProduct (temp, forward);
967                 modelorg[1] = -DotProduct (temp, right);
968                 modelorg[2] = DotProduct (temp, up);
969         }
970
971         s = &clmodel->surfaces[clmodel->firstmodelsurface];
972
973 // calculate dynamic lighting for bmodel if it's not an
974 // instanced model
975         for (i = 0;i < MAX_DLIGHTS;i++)
976         {
977                 if (!cl_dlights[i].radius)
978                         continue;
979
980                 VectorSubtract(cl_dlights[i].origin, currententity->render.origin, org);
981                 R_NoVisMarkLights (org, &cl_dlights[i], 1<<(i&31), i >> 5, clmodel);
982         }
983         vertexlit = modelalpha != 1 || clmodel->firstmodelsurface == 0 || (currententity->render.effects & EF_FULLBRIGHT) || currententity->render.colormod[0] != 1 || currententity->render.colormod[2] != 1 || currententity->render.colormod[2] != 1;
984
985 e->render.angles[0] = -e->render.angles[0];     // stupid quake bug
986         softwaretransformforentity (e);
987 e->render.angles[0] = -e->render.angles[0];     // stupid quake bug
988
989         // draw texture
990         for (i = 0;i < clmodel->nummodelsurfaces;i++, s++)
991         {
992                 if (((s->flags & SURF_PLANEBACK) == 0) == (PlaneDiff(modelorg, s->plane) >= 0))
993                 {
994 //                      R_DrawSurf(s, true, vertexlit || s->texinfo->texture->transparent);
995                         if (s->flags & SURF_DRAWSKY)
996                         {
997                                 RSurf_DrawSky(s, true);
998                                 continue;
999                         }
1000                         t = R_TextureAnimation (s->texinfo->texture);
1001                         if (s->flags & SURF_DRAWTURB)
1002                         {
1003                                 RSurf_DrawWater(s, t, true, s->flags & SURF_DRAWNOALPHA ? 255 : r_wateralpha.value*255.0f);
1004                                 continue;
1005                         }
1006                         if (vertexlit || s->texinfo->texture->transparent)
1007                                 RSurf_DrawWallVertex(s, t, true, true);
1008                         else
1009                                 RSurf_DrawWall(s, t, true);
1010                 }
1011         }
1012         UploadLightmaps();
1013 }
1014
1015 /*
1016 =============================================================
1017
1018         WORLD MODEL
1019
1020 =============================================================
1021 */
1022
1023 void R_StoreEfrags (efrag_t **ppefrag);
1024
1025 void R_NewWorldNode ()
1026 {
1027         int l, texsort = gl_texsort.value, vertex = gl_vertex.value;
1028         mleaf_t *leaf;
1029         msurface_t *surf, **mark, **endmark;
1030
1031         for (l = 0, leaf = cl.worldmodel->leafs;l < cl.worldmodel->numleafs;l++, leaf++)
1032         {
1033                 if ((leaf->visframe == r_visframecount) && (leaf->efrags || leaf->nummarksurfaces))
1034                 {
1035                         if (R_CullBox(leaf->minmaxs, leaf->minmaxs+3))
1036                                 continue;
1037
1038                         c_leafs++;
1039
1040                         // deal with model fragments in this leaf
1041                         if (leaf->efrags)
1042                                 R_StoreEfrags (&leaf->efrags);
1043
1044                         if (leaf->nummarksurfaces)
1045                         {
1046                                 mark = leaf->firstmarksurface;
1047                                 endmark = mark + leaf->nummarksurfaces;
1048                                 do
1049                                 {
1050                                         surf = *mark++;
1051                                         // make sure surfaces are only processed once
1052                                         if (surf->worldnodeframe == r_framecount)
1053                                                 continue;
1054                                         surf->worldnodeframe = r_framecount;
1055                                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1056                                         {
1057                                                 if ( (surf->flags & SURF_PLANEBACK))
1058                                                 {
1059                                                         surf->visframe = r_framecount;
1060                                                         c_faces++;
1061                                                         if (texsort)
1062                                                         {
1063                                                                 surf->texturechain = surf->texinfo->texture->texturechain;
1064                                                                 surf->texinfo->texture->texturechain = surf;
1065                                                         }
1066                                                         else
1067                                                                 R_DrawSurf(surf, false, vertex);
1068                                                 }
1069                                         }
1070                                         else
1071                                         {
1072                                                 if (!(surf->flags & SURF_PLANEBACK))
1073                                                 {
1074                                                         surf->visframe = r_framecount;
1075                                                         c_faces++;
1076                                                         if (texsort)
1077                                                         {
1078                                                                 surf->texturechain = surf->texinfo->texture->texturechain;
1079                                                                 surf->texinfo->texture->texturechain = surf;
1080                                                         }
1081                                                         else
1082                                                                 R_DrawSurf(surf, false, vertex);
1083                                                 }
1084                                         }
1085                                 }
1086                                 while (mark < endmark);
1087                         }
1088                 }
1089         }
1090 }
1091
1092 struct nodestack_s
1093 {
1094         int side;
1095         mnode_t *node;
1096         int noclipping;
1097 } nodestack[8192];
1098
1099 /*
1100 ================
1101 R_WorldNode
1102 ================
1103 */
1104 void R_WorldNode ()
1105 {
1106         int side, texsort = gl_texsort.value, vertex = gl_vertex.value, ca, cb, cc, cd, noclipping = false, oldclip = r_oldclip.value;
1107         struct nodestack_s *nstack;
1108         mnode_t *node;
1109         mleaf_t *pleaf;
1110         msurface_t *surf, *endsurf, **mark, **endmark;
1111         nstack = nodestack;
1112
1113         if (!(node = cl.worldmodel->nodes))
1114                 return;
1115
1116         while(1)
1117         {
1118                 if (oldclip)
1119                 {
1120                         if (R_CullBox(node->minmaxs, node->minmaxs+3))
1121                         {
1122 backupstack:
1123                                 if (nstack <= nodestack)
1124                                         break;
1125                                 nstack--;
1126                                 node = nstack->node;
1127                                 side = nstack->side;
1128                                 noclipping = nstack->noclipping;
1129                                 goto loc0;
1130                         }
1131                 }
1132                 else
1133                 if (!noclipping)
1134                 {
1135                         ca = frustum[0].BoxOnPlaneSideFunc(node->minmaxs, node->minmaxs+3, &frustum[0]);if (ca == 2) goto backupstack; // completely clipped away
1136                         cb = frustum[1].BoxOnPlaneSideFunc(node->minmaxs, node->minmaxs+3, &frustum[1]);if (cb == 2) goto backupstack; // completely clipped away
1137                         cc = frustum[2].BoxOnPlaneSideFunc(node->minmaxs, node->minmaxs+3, &frustum[2]);if (cc == 2) goto backupstack; // completely clipped away
1138                         cd = frustum[3].BoxOnPlaneSideFunc(node->minmaxs, node->minmaxs+3, &frustum[3]);if (cd == 2) goto backupstack; // completely clipped away
1139                         if (ca == 0 && cb == 0 && cc == 0 && cd == 0)
1140                                 noclipping = true; // not clipped at all, no need to clip any children of this node
1141                         // partially clipped node
1142                 }
1143         // if a leaf node, draw stuff
1144                 if (node->contents < 0)
1145                 {
1146                         if (node->contents != CONTENTS_SOLID)
1147                         {
1148                                 pleaf = (mleaf_t *)node;
1149
1150                                 c_leafs++;
1151                                 if (pleaf->nummarksurfaces)
1152                                 {
1153                                         mark = pleaf->firstmarksurface;
1154                                         endmark = mark + pleaf->nummarksurfaces;
1155                                         do
1156                                         {
1157                                                 (*mark)->visframe = r_framecount;
1158                                                 mark++;
1159                                         }
1160                                         while (mark < endmark);
1161                                 }
1162
1163                                 // deal with model fragments in this leaf
1164                                 if (pleaf->efrags)
1165                                         R_StoreEfrags (&pleaf->efrags);
1166                         }
1167
1168                         if (nstack <= nodestack)
1169                                 break;
1170                         nstack--;
1171                         node = nstack->node;
1172                         side = nstack->side;
1173                         noclipping = nstack->noclipping;
1174                         goto loc0;
1175                 }
1176
1177                 c_nodes++;
1178
1179                 // node is just a decision point, so go down the apropriate sides
1180
1181                 // find which side of the node we are on
1182                 side = PlaneDist(modelorg, node->plane) < node->plane->dist;
1183
1184                 // recurse down the children, front side first
1185                 if (node->children[side]->visframe == r_visframecount)
1186                 {
1187                         nstack->node = node;
1188                         nstack->side = !side; // go down back side when we come back up
1189                         nstack->noclipping = noclipping;
1190                         nstack++;
1191                         node = node->children[side];
1192                         continue;
1193                 }
1194                 side = !side;
1195 loc0:
1196
1197         // draw stuff
1198                 if (node->numsurfaces)
1199                 {
1200                         surf = cl.worldmodel->surfaces + node->firstsurface;
1201                         endsurf = surf + node->numsurfaces;
1202
1203                         if (texsort)
1204                         {
1205                                 if (side)
1206                                 {
1207                                         do
1208                                         {
1209                                                 if (surf->visframe == r_framecount && !(surf->flags & SURF_PLANEBACK))
1210                                                 {
1211                                                         c_faces++;
1212                                                         surf->texturechain = surf->texinfo->texture->texturechain;
1213                                                         surf->texinfo->texture->texturechain = surf;
1214                                                 }
1215                                                 else
1216                                                         surf->visframe = -1; // LordHavoc: mark as not visible, so lighting will not touch it
1217                                                 surf++;
1218                                         }
1219                                         while (surf < endsurf);
1220                                 }
1221                                 else
1222                                 {
1223                                         do
1224                                         {
1225                                                 if (surf->visframe == r_framecount && (surf->flags & SURF_PLANEBACK))
1226                                                 {
1227                                                         c_faces++;
1228                                                         surf->texturechain = surf->texinfo->texture->texturechain;
1229                                                         surf->texinfo->texture->texturechain = surf;
1230                                                 }
1231                                                 else
1232                                                         surf->visframe = -1; // LordHavoc: mark as not visible, so lighting will not touch it
1233                                                 surf++;
1234                                         }
1235                                         while (surf < endsurf);
1236                                 }
1237                         }
1238                         else
1239                         {
1240                                 if (side)
1241                                 {
1242                                         do
1243                                         {
1244                                                 if (surf->visframe == r_framecount && !(surf->flags & SURF_PLANEBACK))
1245                                                 {
1246                                                         c_faces++;
1247                                                         R_DrawSurf(surf, false, vertex);
1248                                                 }
1249                                                 else
1250                                                         surf->visframe = -1; // LordHavoc: mark as not visible, so lighting will not touch it
1251                                                 surf++;
1252                                         }
1253                                         while (surf < endsurf);
1254                                 }
1255                                 else
1256                                 {
1257                                         do
1258                                         {
1259                                                 if (surf->visframe == r_framecount && (surf->flags & SURF_PLANEBACK))
1260                                                 {
1261                                                         c_faces++;
1262                                                         R_DrawSurf(surf, false, vertex);
1263                                                 }
1264                                                 else
1265                                                         surf->visframe = -1; // LordHavoc: mark as not visible, so lighting will not touch it
1266                                                 surf++;
1267                                         }
1268                                         while (surf < endsurf);
1269                                 }
1270                         }
1271                 }
1272
1273         // recurse down the back side
1274                 if (node->children[side]->visframe == r_visframecount)
1275                 {
1276                         node = node->children[side];
1277                         continue;
1278                 }
1279
1280                 if (nstack <= nodestack)
1281                         break;
1282                 nstack--;
1283                 node = nstack->node;
1284                 side = nstack->side;
1285                 noclipping = nstack->noclipping;
1286                 goto loc0;
1287         }
1288 }
1289
1290
1291 /*
1292 =============
1293 R_DrawWorld
1294 =============
1295 */
1296 void R_DrawWorld (void)
1297 {
1298         entity_t        ent;
1299
1300         memset (&ent, 0, sizeof(ent));
1301         ent.render.model = cl.worldmodel;
1302         ent.render.colormod[0] = ent.render.colormod[1] = ent.render.colormod[2] = 1;
1303         modelalpha = ent.render.alpha = 1;
1304         ent.render.scale = 1;
1305
1306         VectorCopy (r_refdef.vieworg, modelorg);
1307
1308         currententity = &ent;
1309
1310         softwaretransformidentity(); // LordHavoc: clear transform
1311
1312         if (cl.worldmodel)
1313         {
1314                 if (r_newworldnode.value)
1315                         R_NewWorldNode ();
1316                 else
1317                         R_WorldNode ();
1318         }
1319
1320         R_PushDlights (); // now mark the lit surfaces
1321
1322         DrawTextureChains ();
1323 }
1324
1325
1326 /*
1327 ===============
1328 R_MarkLeaves
1329 ===============
1330 */
1331 void R_MarkLeaves (void)
1332 {
1333         byte    *vis;
1334         mnode_t *node;
1335         int             i;
1336
1337         if (r_oldviewleaf == r_viewleaf && !r_novis.value)
1338                 return;
1339         
1340         r_visframecount++;
1341         r_oldviewleaf = r_viewleaf;
1342
1343         if (r_novis.value)
1344         {
1345                 for (i=0 ; i<cl.worldmodel->numleafs ; i++)
1346                 {
1347                         node = (mnode_t *)&cl.worldmodel->leafs[i+1];
1348                         do
1349                         {
1350                                 if (node->visframe == r_visframecount)
1351                                         break;
1352                                 node->visframe = r_visframecount;
1353                                 node = node->parent;
1354                         } while (node);
1355                 }
1356         }
1357         else
1358         {
1359                 vis = Mod_LeafPVS (r_viewleaf, cl.worldmodel);
1360                 
1361                 for (i=0 ; i<cl.worldmodel->numleafs ; i++)
1362                 {
1363                         if (vis[i>>3] & (1<<(i&7)))
1364                         {
1365                                 node = (mnode_t *)&cl.worldmodel->leafs[i+1];
1366                                 do
1367                                 {
1368                                         if (node->visframe == r_visframecount)
1369                                                 break;
1370                                         node->visframe = r_visframecount;
1371                                         node = node->parent;
1372                                 } while (node);
1373                         }
1374                 }
1375         }
1376 }
1377
1378
1379
1380 /*
1381 =============================================================================
1382
1383   LIGHTMAP ALLOCATION
1384
1385 =============================================================================
1386 */
1387
1388 // returns a texture number and the position inside it
1389 int AllocBlock (int w, int h, short *x, short *y)
1390 {
1391         int             i, j;
1392         int             best, best2;
1393         int             texnum;
1394
1395         for (texnum=0 ; texnum<MAX_LIGHTMAPS ; texnum++)
1396         {
1397                 best = BLOCK_HEIGHT;
1398
1399                 for (i=0 ; i<BLOCK_WIDTH-w ; i+=lightmapalign) // LordHavoc: NVIDIA has broken subimage, so align the lightmaps
1400                 {
1401                         best2 = 0;
1402
1403                         for (j=0 ; j<w ; j++)
1404                         {
1405                                 if (allocated[texnum][i+j] >= best)
1406                                         break;
1407                                 if (allocated[texnum][i+j] > best2)
1408                                         best2 = allocated[texnum][i+j];
1409                         }
1410                         if (j == w)
1411                         {       // this is a valid spot
1412                                 *x = i;
1413                                 *y = best = best2;
1414                         }
1415                 }
1416
1417                 if (best + h > BLOCK_HEIGHT)
1418                         continue;
1419
1420                 if (nosubimagefragments || nosubimage)
1421                 {
1422                         if (!lightmaps[texnum])
1423                         {
1424                                 lightmaps[texnum] = qmalloc(BLOCK_WIDTH*BLOCK_HEIGHT*4);
1425                                 memset(lightmaps[texnum], 0, BLOCK_WIDTH*BLOCK_HEIGHT*4);
1426                         }
1427                 }
1428                 // LordHavoc: clear texture to blank image, fragments are uploaded using subimage
1429                 else if (!allocated[texnum][0])
1430                 {
1431                         byte blank[BLOCK_WIDTH*BLOCK_HEIGHT*4];
1432                         memset(blank, 0, sizeof(blank));
1433                         if(r_upload.value)
1434                         {
1435                                 glBindTexture(GL_TEXTURE_2D, lightmap_textures + texnum);
1436                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1437                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1438                                 if (lightmaprgba)
1439                                         glTexImage2D (GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, blank);
1440                                 else
1441                                         glTexImage2D (GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, blank);
1442                         }
1443                 }
1444
1445                 for (i=0 ; i<w ; i++)
1446                         allocated[texnum][*x + i] = best + h;
1447
1448                 return texnum;
1449         }
1450
1451         Host_Error ("AllocBlock: full, unable to find room for %i by %i lightmap", w, h);
1452         return 0;
1453 }
1454
1455
1456 mvertex_t       *r_pcurrentvertbase;
1457 model_t         *currentmodel;
1458
1459 int     nColinElim;
1460
1461 /*
1462 ================
1463 BuildSurfaceDisplayList
1464 ================
1465 */
1466 void BuildSurfaceDisplayList (msurface_t *fa)
1467 {
1468         int                     i, j, lindex, lnumverts;
1469         medge_t         *pedges, *r_pedge;
1470         int                     vertpage;
1471         float           *vec;
1472         float           s, t;
1473         glpoly_t        *poly;
1474
1475 // reconstruct the polygon
1476         pedges = currentmodel->edges;
1477         lnumverts = fa->numedges;
1478         vertpage = 0;
1479
1480         //
1481         // draw texture
1482         //
1483         poly = Hunk_AllocName (sizeof(glpoly_t) + (lnumverts-4) * VERTEXSIZE*sizeof(float), "surfaces");
1484         poly->next = fa->polys;
1485         poly->flags = fa->flags;
1486         fa->polys = poly;
1487         poly->numverts = lnumverts;
1488
1489         for (i=0 ; i<lnumverts ; i++)
1490         {
1491                 lindex = currentmodel->surfedges[fa->firstedge + i];
1492
1493                 if (lindex > 0)
1494                 {
1495                         r_pedge = &pedges[lindex];
1496                         vec = r_pcurrentvertbase[r_pedge->v[0]].position;
1497                 }
1498                 else
1499                 {
1500                         r_pedge = &pedges[-lindex];
1501                         vec = r_pcurrentvertbase[r_pedge->v[1]].position;
1502                 }
1503                 s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3];
1504                 t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3];
1505
1506                 VectorCopy (vec, poly->verts[i]);
1507                 poly->verts[i][3] = s / fa->texinfo->texture->width;
1508                 poly->verts[i][4] = t / fa->texinfo->texture->height;
1509
1510                 //
1511                 // lightmap texture coordinates
1512                 //
1513                 s -= fa->texturemins[0];
1514                 t -= fa->texturemins[1];
1515                 s += 8;
1516                 t += 8;
1517                 // LordHavoc: calc lightmap data offset
1518                 j = (bound(0l, (int)t>>4, fa->extents[1]>>4) * ((fa->extents[0]>>4)+1) + bound(0l, (int)s>>4, fa->extents[0]>>4)) * 3;
1519                 poly->verts[i][7] = j;
1520                 s += fa->light_s*16;
1521                 s /= BLOCK_WIDTH*16; //fa->texinfo->texture->width;
1522
1523                 t += fa->light_t*16;
1524                 t /= BLOCK_HEIGHT*16; //fa->texinfo->texture->height;
1525
1526                 poly->verts[i][5] = s;
1527                 poly->verts[i][6] = t;
1528         }
1529
1530         //
1531         // remove co-linear points - Ed
1532         //
1533         /*
1534         if (!gl_keeptjunctions.value)
1535         {
1536                 for (i = 0 ; i < lnumverts ; ++i)
1537                 {
1538                         vec3_t v1, v2;
1539                         float *prev, *this, *next;
1540
1541                         prev = poly->verts[(i + lnumverts - 1) % lnumverts];
1542                         this = poly->verts[i];
1543                         next = poly->verts[(i + 1) % lnumverts];
1544
1545                         VectorSubtract( this, prev, v1 );
1546                         VectorNormalize( v1 );
1547                         VectorSubtract( next, prev, v2 );
1548                         VectorNormalize( v2 );
1549
1550                         // skip co-linear points
1551                         #define COLINEAR_EPSILON 0.001
1552                         if ((fabs( v1[0] - v2[0] ) <= COLINEAR_EPSILON) &&
1553                                 (fabs( v1[1] - v2[1] ) <= COLINEAR_EPSILON) && 
1554                                 (fabs( v1[2] - v2[2] ) <= COLINEAR_EPSILON))
1555                         {
1556                                 int j;
1557                                 for (j = i + 1; j < lnumverts; ++j)
1558                                 {
1559                                         int k;
1560                                         for (k = 0; k < VERTEXSIZE; ++k)
1561                                                 poly->verts[j - 1][k] = poly->verts[j][k];
1562                                 }
1563                                 --lnumverts;
1564                                 ++nColinElim;
1565                                 // retry next vertex next time, which is now current vertex
1566                                 --i;
1567                         }
1568                 }
1569         }
1570         */
1571         poly->numverts = lnumverts;
1572 }
1573
1574 /*
1575 ========================
1576 GL_CreateSurfaceLightmap
1577 ========================
1578 */
1579 void GL_CreateSurfaceLightmap (msurface_t *surf)
1580 {
1581         int             smax, tmax;
1582
1583         if (surf->flags & (SURF_DRAWSKY|SURF_DRAWTURB))
1584                 return;
1585
1586         smax = (surf->extents[0]>>4)+1;
1587         tmax = (surf->extents[1]>>4)+1;
1588
1589         surf->lightmaptexturenum = AllocBlock (smax, tmax, &surf->light_s, &surf->light_t);
1590         if (nosubimage || nosubimagefragments)
1591                 return;
1592         glBindTexture(GL_TEXTURE_2D, lightmap_textures + surf->lightmaptexturenum);
1593         smax = ((surf->extents[0]>>4)+lightmapalign) & lightmapalignmask;
1594         if (lightmaprgba)
1595         {
1596                 R_BuildLightMap (surf, templight, smax * 4);
1597                 if(r_upload.value)
1598                         glTexSubImage2D(GL_TEXTURE_2D, 0, surf->light_s, surf->light_t, smax, tmax, GL_RGBA, GL_UNSIGNED_BYTE, templight);
1599         }
1600         else
1601         {
1602                 R_BuildLightMap (surf, templight, smax * 3);
1603                 if(r_upload.value)
1604                         glTexSubImage2D(GL_TEXTURE_2D, 0, surf->light_s, surf->light_t, smax, tmax, GL_RGB , GL_UNSIGNED_BYTE, templight);
1605         }
1606 }
1607
1608
1609 /*
1610 ==================
1611 GL_BuildLightmaps
1612
1613 Builds the lightmap texture
1614 with all the surfaces from all brush models
1615 ==================
1616 */
1617 void GL_BuildLightmaps (void)
1618 {
1619         int             i, j;
1620         model_t *m;
1621
1622         memset (allocated, 0, sizeof(allocated));
1623
1624         r_framecount = 1;               // no dlightcache
1625
1626         if (gl_nosubimagefragments.value)
1627                 nosubimagefragments = 1;
1628         else
1629                 nosubimagefragments = 0;
1630
1631         if (gl_nosubimage.value)
1632                 nosubimage = 1;
1633         else
1634                 nosubimage = 0;
1635
1636         if (gl_lightmaprgba.value)
1637         {
1638                 lightmaprgba = true;
1639                 lightmapbytes = 4;
1640         }
1641         else
1642         {
1643                 lightmaprgba = false;
1644                 lightmapbytes = 3;
1645         }
1646
1647         // LordHavoc: NVIDIA seems to have a broken glTexSubImage2D,
1648         //            it needs to be aligned on 4 pixel boundaries...
1649         //            so I implemented an adjustable lightmap alignment
1650         if (gl_lightmapalign.value < 1)
1651                 gl_lightmapalign.value = 1;
1652         if (gl_lightmapalign.value > 16)
1653                 gl_lightmapalign.value = 16;
1654         lightmapalign = 1;
1655         while (lightmapalign < gl_lightmapalign.value)
1656                 lightmapalign <<= 1;
1657         gl_lightmapalign.value = lightmapalign;
1658         lightmapalignmask = ~(lightmapalign - 1);
1659         if (nosubimagefragments || nosubimage)
1660         {
1661                 lightmapalign = 1;
1662                 lightmapalignmask = ~0;
1663         }
1664
1665         if (!lightmap_textures)
1666                 lightmap_textures = R_GetTextureSlots(MAX_LIGHTMAPS);
1667
1668         for (j=1 ; j<MAX_MODELS ; j++)
1669         {
1670                 m = cl.model_precache[j];
1671                 if (!m)
1672                         break;
1673                 if (m->name[0] == '*')
1674                         continue;
1675                 r_pcurrentvertbase = m->vertexes;
1676                 currentmodel = m;
1677                 for (i=0 ; i<m->numsurfaces ; i++)
1678                 {
1679                         if ( m->surfaces[i].flags & SURF_DRAWTURB )
1680                                 continue;
1681                         if ( m->surfaces[i].flags & SURF_DRAWSKY )
1682                                 continue;
1683                         GL_CreateSurfaceLightmap (m->surfaces + i);
1684                         BuildSurfaceDisplayList (m->surfaces + i);
1685                 }
1686         }
1687
1688         if (nosubimage || nosubimagefragments)
1689         {
1690                 if(r_upload.value)
1691                         if (gl_mtexable)
1692                                 qglSelectTexture(gl_mtex_enum+1);
1693                 for (i = 0;i < MAX_LIGHTMAPS;i++)
1694                 {
1695                         if (!allocated[i][0])
1696                                 break;
1697                         lightmapupdate[i][0] = BLOCK_HEIGHT;
1698                         lightmapupdate[i][1] = 0;
1699                         if(r_upload.value)
1700                         {
1701                                 glBindTexture(GL_TEXTURE_2D, lightmap_textures + i);
1702                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1703                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1704                                 if (lightmaprgba)
1705                                         glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i]);
1706                                 else
1707                                         glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i]);
1708                         }
1709                 }
1710                 if(r_upload.value)
1711                         if (gl_mtexable)
1712                                 qglSelectTexture(gl_mtex_enum+0);
1713         }
1714 }
1715