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