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