Debian Codegraph @

code/renderergl2/tr_bsp.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22 // tr_map.c
23
24 #include "tr_local.h"
25
26 #define JSON_IMPLEMENTATION
27 #include "../qcommon/json.h"
28 #undef JSON_IMPLEMENTATION
29
30 /*
31
32 Loads and prepares a map file for scene rendering.
33
34 A single entry point:
35
36 void RE_LoadWorldMap( const char *name );
37
38 */
39
40 static world_t s_worldData;
41 static byte *fileBase;
42
43 int c_subdivisions;
44 int c_gridVerts;
45
46 //===============================================================================
47
48 static void HSVtoRGB( float h, float s, float v, float rgb[3] )
49 {
50 int i;
51 float f;
52 float p, q, t;
53
54 h *= 5;
55
56 i = floor( h );
57 f = h - i;
58
59 p = v * ( 1 - s );
60 q = v * ( 1 - s * f );
61 t = v * ( 1 - s * ( 1 - f ) );
62
63 switch ( i )
64 {
65 case 0:
66 rgb[0] = v;
67 rgb[1] = t;
68 rgb[2] = p;
69 break;
70 case 1:
71 rgb[0] = q;
72 rgb[1] = v;
73 rgb[2] = p;
74 break;
75 case 2:
76 rgb[0] = p;
77 rgb[1] = v;
78 rgb[2] = t;
79 break;
80 case 3:
81 rgb[0] = p;
82 rgb[1] = q;
83 rgb[2] = v;
84 break;
85 case 4:
86 rgb[0] = t;
87 rgb[1] = p;
88 rgb[2] = v;
89 break;
90 case 5:
91 rgb[0] = v;
92 rgb[1] = p;
93 rgb[2] = q;
94 break;
95 }
96 }
97
98 /*
99 ===============
100 R_ColorShiftLightingBytes
101
102 ===============
103 */
104 static void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) {
105 int shift, r, g, b;
106
107 // shift the color data based on overbright range
108 shift = r_mapOverBrightBits->integer - tr.overbrightBits;
109
110 // shift the data based on overbright range
111 r = in[0] << shift;
112 g = in[1] << shift;
113 b = in[2] << shift;
114
115 // normalize by color instead of saturating to white
116 if ( ( r | g | b ) > 255 ) {
117 int max;
118
119 max = r > g ? r : g;
120 max = max > b ? max : b;
121 r = r * 255 / max;
122 g = g * 255 / max;
123 b = b * 255 / max;
124 }
125
126 out[0] = r;
127 out[1] = g;
128 out[2] = b;
129 out[3] = in[3];
130 }
131
132
133 /*
134 ===============
135 R_ColorShiftLightingFloats
136
137 ===============
138 */
139 static void R_ColorShiftLightingFloats(float in[4], float out[4])
140 {
141 float r, g, b;
142 float scale = (1 << (r_mapOverBrightBits->integer - tr.overbrightBits)) / 255.0f;
143
144 r = in[0] * scale;
145 g = in[1] * scale;
146 b = in[2] * scale;
147
148 // normalize by color instead of saturating to white
149 if ( r > 1 || g > 1 || b > 1 ) {
150 float max;
151
152 max = r > g ? r : g;
153 max = max > b ? max : b;
154 r = r / max;
155 g = g / max;
156 b = b / max;
157 }
158
159 out[0] = r;
160 out[1] = g;
161 out[2] = b;
162 out[3] = in[3];
163 }
164
165 // Modified from http://graphicrants.blogspot.jp/2009/04/rgbm-color-encoding.html
166 void ColorToRGBM(const vec3_t color, unsigned char rgbm[4])
167 {
168 vec3_t sample;
169 float maxComponent;
170
171 VectorCopy(color, sample);
172
173 maxComponent = MAX(sample[0], sample[1]);
174 maxComponent = MAX(maxComponent, sample[2]);
175 maxComponent = CLAMP(maxComponent, 1.0f/255.0f, 1.0f);
176
177 rgbm[3] = (unsigned char) ceil(maxComponent * 255.0f);
178 maxComponent = 255.0f / rgbm[3];
179
180 VectorScale(sample, maxComponent, sample);
181
182 rgbm[0] = (unsigned char) (sample[0] * 255);
183 rgbm[1] = (unsigned char) (sample[1] * 255);
184 rgbm[2] = (unsigned char) (sample[2] * 255);
185 }
186
187 void ColorToRGB16(const vec3_t color, uint16_t rgb16[3])
188 {
189 rgb16[0] = color[0] * 65535.0f + 0.5f;
190 rgb16[1] = color[1] * 65535.0f + 0.5f;
191 rgb16[2] = color[2] * 65535.0f + 0.5f;
192 }
193
194
195 /*
196 ===============
197 R_LoadLightmaps
198
199 ===============
200 */
201 #define DEFAULT_LIGHTMAP_SIZE 128
202 static void R_LoadLightmaps( lump_t *l, lump_t *surfs ) {
203 imgFlags_t imgFlags = IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE;
204 byte *buf, *buf_p;
205 dsurface_t *surf;
206 int len;
207 byte *image;
208 int i, j, numLightmaps, textureInternalFormat = 0;
209 int numLightmapsPerPage = 16;
210 float maxIntensity = 0;
211
212 len = l->filelen;
213 if ( !len ) {
214 return;
215 }
216 buf = fileBase + l->fileofs;
217
218 // we are about to upload textures
219 R_IssuePendingRenderCommands();
220
221 tr.lightmapSize = DEFAULT_LIGHTMAP_SIZE;
222 numLightmaps = len / (tr.lightmapSize * tr.lightmapSize * 3);
223
224 // check for deluxe mapping
225 if (numLightmaps <= 1)
226 {
227 tr.worldDeluxeMapping = qfalse;
228 }
229 else
230 {
231 tr.worldDeluxeMapping = qtrue;
232 for( i = 0, surf = (dsurface_t *)(fileBase + surfs->fileofs);
233 i < surfs->filelen / sizeof(dsurface_t); i++, surf++ ) {
234 int lightmapNum = LittleLong( surf->lightmapNum );
235
236 if ( lightmapNum >= 0 && (lightmapNum & 1) != 0 ) {
237 tr.worldDeluxeMapping = qfalse;
238 break;
239 }
240 }
241 }
242
243 image = ri.Malloc(tr.lightmapSize * tr.lightmapSize * 4 * 2);
244
245 if (tr.worldDeluxeMapping)
246 numLightmaps >>= 1;
247
248 // Use fat lightmaps of an appropriate size.
249 if (r_mergeLightmaps->integer)
250 {
251 int maxLightmapsPerAxis = glConfig.maxTextureSize / tr.lightmapSize;
252 int lightmapCols = 4, lightmapRows = 4;
253
254 // Increase width at first, then height.
255 while (lightmapCols * lightmapRows < numLightmaps && lightmapCols != maxLightmapsPerAxis)
256 lightmapCols <<= 1;
257
258 while (lightmapCols * lightmapRows < numLightmaps && lightmapRows != maxLightmapsPerAxis)
259 lightmapRows <<= 1;
260
261 tr.fatLightmapCols = lightmapCols;
262 tr.fatLightmapRows = lightmapRows;
263 numLightmapsPerPage = lightmapCols * lightmapRows;
264
265 tr.numLightmaps = (numLightmaps + (numLightmapsPerPage - 1)) / numLightmapsPerPage;
266 }
267 else
268 {
269 tr.numLightmaps = numLightmaps;
270 }
271
272 tr.lightmaps = ri.Hunk_Alloc( tr.numLightmaps * sizeof(image_t *), h_low );
273
274 if (tr.worldDeluxeMapping)
275 tr.deluxemaps = ri.Hunk_Alloc( tr.numLightmaps * sizeof(image_t *), h_low );
276
277 textureInternalFormat = GL_RGBA8;
278 if (r_hdr->integer && !qglesMajorVersion)
279 {
280 // Check for the first hdr lightmap, if it exists, use GL_RGBA16 for textures.
281 char filename[MAX_QPATH];
282
283 Com_sprintf(filename, sizeof(filename), "maps/%s/lm_0000.hdr", s_worldData.baseName);
284 if (ri.FS_FileExists(filename))
285 textureInternalFormat = GL_RGBA16;
286 }
287
288 if (r_mergeLightmaps->integer)
289 {
290 int width = tr.fatLightmapCols * tr.lightmapSize;
291 int height = tr.fatLightmapRows * tr.lightmapSize;
292
293 for (i = 0; i < tr.numLightmaps; i++)
294 {
295 tr.lightmaps[i] = R_CreateImage(va("_fatlightmap%d", i), NULL, width, height, IMGTYPE_COLORALPHA, imgFlags, textureInternalFormat);
296
297 if (tr.worldDeluxeMapping)
298 tr.deluxemaps[i] = R_CreateImage(va("_fatdeluxemap%d", i), NULL, width, height, IMGTYPE_DELUXE, imgFlags, 0);
299 }
300 }
301
302 for(i = 0; i < numLightmaps; i++)
303 {
304 int xoff = 0, yoff = 0;
305 int lightmapnum = i;
306 // expand the 24 bit on-disk to 32 bit
307
308 if (r_mergeLightmaps->integer)
309 {
310 int lightmaponpage = i % numLightmapsPerPage;
311 xoff = (lightmaponpage % tr.fatLightmapCols) * tr.lightmapSize;
312 yoff = (lightmaponpage / tr.fatLightmapCols) * tr.lightmapSize;
313
314 lightmapnum /= numLightmapsPerPage;
315 }
316
317 // if (tr.worldLightmapping)
318 {
319 char filename[MAX_QPATH];
320 byte *hdrLightmap = NULL;
321 int size = 0;
322
323 // look for hdr lightmaps
324 if (textureInternalFormat == GL_RGBA16)
325 {
326 Com_sprintf( filename, sizeof( filename ), "maps/%s/lm_%04d.hdr", s_worldData.baseName, i * (tr.worldDeluxeMapping ? 2 : 1) );
327 //ri.Printf(PRINT_ALL, "looking for %s\n", filename);
328
329 size = ri.FS_ReadFile(filename, (void **)&hdrLightmap);
330 }
331
332 if (hdrLightmap)
333 {
334 byte *p = hdrLightmap, *end = hdrLightmap + size;
335 //ri.Printf(PRINT_ALL, "found!\n");
336
337 /* FIXME: don't just skip over this header and actually parse it */
338 while (p < end && !(*p == '\n' && *(p+1) == '\n'))
339 p++;
340
341 p += 2;
342
343 while (p < end && !(*p == '\n'))
344 p++;
345
346 p++;
347
348 if (p >= end)
349 ri.Error(ERR_DROP, "Bad header for %s!", filename);
350
351 buf_p = p;
352
353 #if 0 // HDRFILE_RGBE
354 if ((int)(end - hdrLightmap) != tr.lightmapSize * tr.lightmapSize * 4)
355 ri.Error(ERR_DROP, "Bad size for %s (%i)!", filename, size);
356 #else // HDRFILE_FLOAT
357 if ((int)(end - hdrLightmap) != tr.lightmapSize * tr.lightmapSize * 12)
358 ri.Error(ERR_DROP, "Bad size for %s (%i)!", filename, size);
359 #endif
360 }
361 else
362 {
363 int imgOffset = tr.worldDeluxeMapping ? i * 2 : i;
364 buf_p = buf + imgOffset * tr.lightmapSize * tr.lightmapSize * 3;
365 }
366
367 for ( j = 0 ; j < tr.lightmapSize * tr.lightmapSize; j++ )
368 {
369 if (hdrLightmap)
370 {
371 vec4_t color;
372
373 #if 0 // HDRFILE_RGBE
374 float exponent = exp2(buf_p[j*4+3] - 128);
375
376 color[0] = buf_p[j*4+0] * exponent;
377 color[1] = buf_p[j*4+1] * exponent;
378 color[2] = buf_p[j*4+2] * exponent;
379 #else // HDRFILE_FLOAT
380 memcpy(color, &buf_p[j*12], 12);
381
382 color[0] = LittleFloat(color[0]);
383 color[1] = LittleFloat(color[1]);
384 color[2] = LittleFloat(color[2]);
385 #endif
386 color[3] = 1.0f;
387
388 R_ColorShiftLightingFloats(color, color);
389
390 ColorToRGB16(color, (uint16_t *)(&image[j * 8]));
391 ((uint16_t *)(&image[j * 8]))[3] = 65535;
392 }
393 else if (textureInternalFormat == GL_RGBA16)
394 {
395 vec4_t color;
396
397 //hack: convert LDR lightmap to HDR one
398 color[0] = MAX(buf_p[j*3+0], 0.499f);
399 color[1] = MAX(buf_p[j*3+1], 0.499f);
400 color[2] = MAX(buf_p[j*3+2], 0.499f);
401
402 // if under an arbitrary value (say 12) grey it out
403 // this prevents weird splotches in dimly lit areas
404 if (color[0] + color[1] + color[2] < 12.0f)
405 {
406 float avg = (color[0] + color[1] + color[2]) * 0.3333f;
407 color[0] = avg;
408 color[1] = avg;
409 color[2] = avg;
410 }
411 color[3] = 1.0f;
412
413 R_ColorShiftLightingFloats(color, color);
414
415 ColorToRGB16(color, (uint16_t *)(&image[j * 8]));
416 ((uint16_t *)(&image[j * 8]))[3] = 65535;
417 }
418 else
419 {
420 if ( r_lightmap->integer == 2 )
421 { // color code by intensity as development tool (FIXME: check range)
422 float r = buf_p[j*3+0];
423 float g = buf_p[j*3+1];
424 float b = buf_p[j*3+2];
425 float intensity;
426 float out[3] = {0.0, 0.0, 0.0};
427
428 intensity = 0.33f * r + 0.685f * g + 0.063f * b;
429
430 if ( intensity > 255 )
431 intensity = 1.0f;
432 else
433 intensity /= 255.0f;
434
435 if ( intensity > maxIntensity )
436 maxIntensity = intensity;
437
438 HSVtoRGB( intensity, 1.00, 0.50, out );
439
440 image[j*4+0] = out[0] * 255;
441 image[j*4+1] = out[1] * 255;
442 image[j*4+2] = out[2] * 255;
443 image[j*4+3] = 255;
444 }
445 else
446 {
447 R_ColorShiftLightingBytes( &buf_p[j*3], &image[j*4] );
448 image[j*4+3] = 255;
449 }
450 }
451 }
452
453 if (r_mergeLightmaps->integer)
454 R_UpdateSubImage(tr.lightmaps[lightmapnum], image, xoff, yoff, tr.lightmapSize, tr.lightmapSize, textureInternalFormat);
455 else
456 tr.lightmaps[i] = R_CreateImage(va("*lightmap%d", i), image, tr.lightmapSize, tr.lightmapSize, IMGTYPE_COLORALPHA, imgFlags, textureInternalFormat );
457
458 if (hdrLightmap)
459 ri.FS_FreeFile(hdrLightmap);
460 }
461
462 if (tr.worldDeluxeMapping)
463 {
464 buf_p = buf + (i * 2 + 1) * tr.lightmapSize * tr.lightmapSize * 3;
465
466 for ( j = 0 ; j < tr.lightmapSize * tr.lightmapSize; j++ ) {
467 image[j*4+0] = buf_p[j*3+0];
468 image[j*4+1] = buf_p[j*3+1];
469 image[j*4+2] = buf_p[j*3+2];
470
471 // make 0,0,0 into 127,127,127
472 if ((image[j*4+0] == 0) && (image[j*4+1] == 0) && (image[j*4+2] == 0))
473 {
474 image[j*4+0] =
475 image[j*4+1] =
476 image[j*4+2] = 127;
477 }
478
479 image[j*4+3] = 255;
480 }
481
482 if (r_mergeLightmaps->integer)
483 R_UpdateSubImage(tr.deluxemaps[lightmapnum], image, xoff, yoff, tr.lightmapSize, tr.lightmapSize, GL_RGBA8 );
484 else
485 tr.deluxemaps[i] = R_CreateImage(va("*deluxemap%d", i), image, tr.lightmapSize, tr.lightmapSize, IMGTYPE_DELUXE, imgFlags, 0 );
486 }
487 }
488
489 if ( r_lightmap->integer == 2 ) {
490 ri.Printf( PRINT_ALL, "Brightest lightmap value: %d\n", ( int ) ( maxIntensity * 255 ) );
491 }
492
493 ri.Free(image);
494 }
495
496
497 // If FatPackU() or FatPackV() changes, update FixFatLightmapTexCoords()
498 static float FatPackU(float input, int lightmapnum)
499 {
500 if (lightmapnum < 0)
501 return input;
502
503 if (tr.worldDeluxeMapping)
504 lightmapnum >>= 1;
505
506 if (tr.fatLightmapCols > 0)
507 {
508 lightmapnum %= (tr.fatLightmapCols * tr.fatLightmapRows);
509 return (input + (lightmapnum % tr.fatLightmapCols)) / (float)(tr.fatLightmapCols);
510 }
511
512 return input;
513 }
514
515 static float FatPackV(float input, int lightmapnum)
516 {
517 if (lightmapnum < 0)
518 return input;
519
520 if (tr.worldDeluxeMapping)
521 lightmapnum >>= 1;
522
523 if (tr.fatLightmapCols > 0)
524 {
525 lightmapnum %= (tr.fatLightmapCols * tr.fatLightmapRows);
526 return (input + (lightmapnum / tr.fatLightmapCols)) / (float)(tr.fatLightmapRows);
527 }
528
529 return input;
530 }
531
532
533 static int FatLightmap(int lightmapnum)
534 {
535 if (lightmapnum < 0)
536 return lightmapnum;
537
538 if (tr.worldDeluxeMapping)
539 lightmapnum >>= 1;
540
541 if (tr.fatLightmapCols > 0)
542 return lightmapnum / (tr.fatLightmapCols * tr.fatLightmapRows);
543
544 return lightmapnum;
545 }
546
547 /*
548 =================
549 RE_SetWorldVisData
550
551 This is called by the clipmodel subsystem so we can share the 1.8 megs of
552 space in big maps...
553 =================
554 */
555 void RE_SetWorldVisData( const byte *vis ) {
556 tr.externalVisData = vis;
557 }
558
559
560 /*
561 =================
562 R_LoadVisibility
563 =================
564 */
565 static void R_LoadVisibility( lump_t *l ) {
566 int len;
567 byte *buf;
568
569 len = l->filelen;
570 if ( !len ) {
571 return;
572 }
573 buf = fileBase + l->fileofs;
574
575 s_worldData.numClusters = LittleLong( ((int *)buf)[0] );
576 s_worldData.clusterBytes = LittleLong( ((int *)buf)[1] );
577
578 // CM_Load should have given us the vis data to share, so
579 // we don't need to allocate another copy
580 if ( tr.externalVisData ) {
581 s_worldData.vis = tr.externalVisData;
582 } else {
583 byte *dest;
584
585 dest = ri.Hunk_Alloc( len - 8, h_low );
586 Com_Memcpy( dest, buf + 8, len - 8 );
587 s_worldData.vis = dest;
588 }
589 }
590
591 //===============================================================================
592
593
594 /*
595 ===============
596 ShaderForShaderNum
597 ===============
598 */
599 static shader_t *ShaderForShaderNum( int shaderNum, int lightmapNum ) {
600 shader_t *shader;
601 dshader_t *dsh;
602
603 int _shaderNum = LittleLong( shaderNum );
604 if ( _shaderNum < 0 || _shaderNum >= s_worldData.numShaders ) {
605 ri.Error( ERR_DROP, "ShaderForShaderNum: bad num %i", _shaderNum );
606 }
607 dsh = &s_worldData.shaders[ _shaderNum ];
608
609 if ( r_vertexLight->integer || glConfig.hardwareType == GLHW_PERMEDIA2 ) {
610 lightmapNum = LIGHTMAP_BY_VERTEX;
611 }
612
613 if ( r_fullbright->integer ) {
614 lightmapNum = LIGHTMAP_WHITEIMAGE;
615 }
616
617 shader = R_FindShaderEx( dsh->shader, FatLightmap( lightmapNum ), qtrue, lightmapNum );
618
619 // if the shader had errors, just use default shader
620 if ( shader->defaultShader ) {
621 return tr.defaultShader;
622 }
623
624 return shader;
625 }
626
627 void LoadDrawVertToSrfVert(srfVert_t *s, drawVert_t *d, int realLightmapNum, float hdrVertColors[3], vec3_t *bounds)
628 {
629 vec4_t v;
630
631 s->xyz[0] = LittleFloat(d->xyz[0]);
632 s->xyz[1] = LittleFloat(d->xyz[1]);
633 s->xyz[2] = LittleFloat(d->xyz[2]);
634
635 if (bounds)
636 AddPointToBounds(s->xyz, bounds[0], bounds[1]);
637
638 s->st[0] = LittleFloat(d->st[0]);
639 s->st[1] = LittleFloat(d->st[1]);
640
641 if (realLightmapNum >= 0)
642 {
643 s->lightmap[0] = FatPackU(LittleFloat(d->lightmap[0]), realLightmapNum);
644 s->lightmap[1] = FatPackV(LittleFloat(d->lightmap[1]), realLightmapNum);
645 }
646 else
647 {
648 s->lightmap[0] = LittleFloat(d->lightmap[0]);
649 s->lightmap[1] = LittleFloat(d->lightmap[1]);
650 }
651
652 v[0] = LittleFloat(d->normal[0]);
653 v[1] = LittleFloat(d->normal[1]);
654 v[2] = LittleFloat(d->normal[2]);
655
656 R_VaoPackNormal(s->normal, v);
657
658 if (hdrVertColors)
659 {
660 v[0] = hdrVertColors[0];
661 v[1] = hdrVertColors[1];
662 v[2] = hdrVertColors[2];
663 }
664 else
665 {
666 //hack: convert LDR vertex colors to HDR
667 if (r_hdr->integer)
668 {
669 v[0] = MAX(d->color[0], 0.499f);
670 v[1] = MAX(d->color[1], 0.499f);
671 v[2] = MAX(d->color[2], 0.499f);
672 }
673 else
674 {
675 v[0] = d->color[0];
676 v[1] = d->color[1];
677 v[2] = d->color[2];
678 }
679
680 }
681 v[3] = d->color[3] / 255.0f;
682
683 R_ColorShiftLightingFloats(v, v);
684 R_VaoPackColor(s->color, v);
685 }
686
687
688 /*
689 ===============
690 ParseFace
691 ===============
692 */
693 static void ParseFace( dsurface_t *ds, drawVert_t *verts, float *hdrVertColors, msurface_t *surf, int *indexes ) {
694 int i, j;
695 srfBspSurface_t *cv;
696 glIndex_t *tri;
697 int numVerts, numIndexes, badTriangles;
698 int realLightmapNum;
699
700 realLightmapNum = LittleLong( ds->lightmapNum );
701
702 // get fog volume
703 surf->fogIndex = LittleLong( ds->fogNum ) + 1;
704
705 // get shader value
706 surf->shader = ShaderForShaderNum( ds->shaderNum, realLightmapNum );
707 if ( r_singleShader->integer && !surf->shader->isSky ) {
708 surf->shader = tr.defaultShader;
709 }
710
711 numVerts = LittleLong(ds->numVerts);
712 if (numVerts > MAX_FACE_POINTS) {
713 ri.Printf( PRINT_WARNING, "WARNING: MAX_FACE_POINTS exceeded: %i\n", numVerts);
714 numVerts = MAX_FACE_POINTS;
715 surf->shader = tr.defaultShader;
716 }
717
718 numIndexes = LittleLong(ds->numIndexes);
719
720 //cv = ri.Hunk_Alloc(sizeof(*cv), h_low);
721 cv = (void *)surf->data;
722 cv->surfaceType = SF_FACE;
723
724 cv->numIndexes = numIndexes;
725 cv->indexes = ri.Hunk_Alloc(numIndexes * sizeof(cv->indexes[0]), h_low);
726
727 cv->numVerts = numVerts;
728 cv->verts = ri.Hunk_Alloc(numVerts * sizeof(cv->verts[0]), h_low);
729
730 // copy vertexes
731 surf->cullinfo.type = CULLINFO_PLANE | CULLINFO_BOX;
732 ClearBounds(surf->cullinfo.bounds[0], surf->cullinfo.bounds[1]);
733 verts += LittleLong(ds->firstVert);
734 for(i = 0; i < numVerts; i++)
735 LoadDrawVertToSrfVert(&cv->verts[i], &verts[i], realLightmapNum, hdrVertColors ? hdrVertColors + (ds->firstVert + i) * 3 : NULL, surf->cullinfo.bounds);
736
737 // copy triangles
738 badTriangles = 0;
739 indexes += LittleLong(ds->firstIndex);
740 for(i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3)
741 {
742 for(j = 0; j < 3; j++)
743 {
744 tri[j] = LittleLong(indexes[i + j]);
745
746 if(tri[j] >= numVerts)
747 {
748 ri.Error(ERR_DROP, "Bad index in face surface");
749 }
750 }
751
752 if ((tri[0] == tri[1]) || (tri[1] == tri[2]) || (tri[0] == tri[2]))
753 {
754 tri -= 3;
755 badTriangles++;
756 }
757 }
758
759 if (badTriangles)
760 {
761 ri.Printf(PRINT_WARNING, "Face has bad triangles, originally shader %s %d tris %d verts, now %d tris\n", surf->shader->name, numIndexes / 3, numVerts, numIndexes / 3 - badTriangles);
762 cv->numIndexes -= badTriangles * 3;
763 }
764
765 // take the plane information from the lightmap vector
766 for ( i = 0 ; i < 3 ; i++ ) {
767 cv->cullPlane.normal[i] = LittleFloat( ds->lightmapVecs[2][i] );
768 }
769 cv->cullPlane.dist = DotProduct( cv->verts[0].xyz, cv->cullPlane.normal );
770 SetPlaneSignbits( &cv->cullPlane );
771 cv->cullPlane.type = PlaneTypeForNormal( cv->cullPlane.normal );
772 surf->cullinfo.plane = cv->cullPlane;
773
774 surf->data = (surfaceType_t *)cv;
775
776 // Calculate tangent spaces
777 {
778 srfVert_t *dv[3];
779
780 for(i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3)
781 {
782 dv[0] = &cv->verts[tri[0]];
783 dv[1] = &cv->verts[tri[1]];
784 dv[2] = &cv->verts[tri[2]];
785
786 R_CalcTangentVectors(dv);
787 }
788 }
789 }
790
791
792 /*
793 ===============
794 ParseMesh
795 ===============
796 */
797 static void ParseMesh ( dsurface_t *ds, drawVert_t *verts, float *hdrVertColors, msurface_t *surf ) {
798 srfBspSurface_t *grid = (srfBspSurface_t *)surf->data;
799 int i;
800 int width, height, numPoints;
801 srfVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE];
802 vec3_t bounds[2];
803 vec3_t tmpVec;
804 static surfaceType_t skipData = SF_SKIP;
805 int realLightmapNum;
806
807 realLightmapNum = LittleLong( ds->lightmapNum );
808
809 // get fog volume
810 surf->fogIndex = LittleLong( ds->fogNum ) + 1;
811
812 // get shader value
813 surf->shader = ShaderForShaderNum( ds->shaderNum, realLightmapNum );
814 if ( r_singleShader->integer && !surf->shader->isSky ) {
815 surf->shader = tr.defaultShader;
816 }
817
818 // we may have a nodraw surface, because they might still need to
819 // be around for movement clipping
820 if ( s_worldData.shaders[ LittleLong( ds->shaderNum ) ].surfaceFlags & SURF_NODRAW ) {
821 surf->data = &skipData;
822 return;
823 }
824
825 width = LittleLong( ds->patchWidth );
826 height = LittleLong( ds->patchHeight );
827
828 if(width < 0 || width > MAX_PATCH_SIZE || height < 0 || height > MAX_PATCH_SIZE)
829 ri.Error(ERR_DROP, "ParseMesh: bad size");
830
831 verts += LittleLong( ds->firstVert );
832 numPoints = width * height;
833 for(i = 0; i < numPoints; i++)
834 LoadDrawVertToSrfVert(&points[i], &verts[i], realLightmapNum, hdrVertColors ? hdrVertColors + (ds->firstVert + i) * 3 : NULL, NULL);
835
836 // pre-tesseleate
837 R_SubdividePatchToGrid( grid, width, height, points );
838
839 // copy the level of detail origin, which is the center
840 // of the group of all curves that must subdivide the same
841 // to avoid cracking
842 for ( i = 0 ; i < 3 ; i++ ) {
843 bounds[0][i] = LittleFloat( ds->lightmapVecs[0][i] );
844 bounds[1][i] = LittleFloat( ds->lightmapVecs[1][i] );
845 }
846 VectorAdd( bounds[0], bounds[1], bounds[1] );
847 VectorScale( bounds[1], 0.5f, grid->lodOrigin );
848 VectorSubtract( bounds[0], grid->lodOrigin, tmpVec );
849 grid->lodRadius = VectorLength( tmpVec );
850
851 surf->cullinfo.type = CULLINFO_BOX | CULLINFO_SPHERE;
852 VectorCopy(grid->cullBounds[0], surf->cullinfo.bounds[0]);
853 VectorCopy(grid->cullBounds[1], surf->cullinfo.bounds[1]);
854 VectorCopy(grid->cullOrigin, surf->cullinfo.localOrigin);
855 surf->cullinfo.radius = grid->cullRadius;
856 }
857
858 /*
859 ===============
860 ParseTriSurf
861 ===============
862 */
863 static void ParseTriSurf( dsurface_t *ds, drawVert_t *verts, float *hdrVertColors, msurface_t *surf, int *indexes ) {
864 srfBspSurface_t *cv;
865 glIndex_t *tri;
866 int i, j;
867 int numVerts, numIndexes, badTriangles;
868
869 // get fog volume
870 surf->fogIndex = LittleLong( ds->fogNum ) + 1;
871
872 // get shader
873 surf->shader = ShaderForShaderNum( ds->shaderNum, LIGHTMAP_BY_VERTEX );
874 if ( r_singleShader->integer && !surf->shader->isSky ) {
875 surf->shader = tr.defaultShader;
876 }
877
878 numVerts = LittleLong(ds->numVerts);
879 numIndexes = LittleLong(ds->numIndexes);
880
881 //cv = ri.Hunk_Alloc(sizeof(*cv), h_low);
882 cv = (void *)surf->data;
883 cv->surfaceType = SF_TRIANGLES;
884
885 cv->numIndexes = numIndexes;
886 cv->indexes = ri.Hunk_Alloc(numIndexes * sizeof(cv->indexes[0]), h_low);
887
888 cv->numVerts = numVerts;
889 cv->verts = ri.Hunk_Alloc(numVerts * sizeof(cv->verts[0]), h_low);
890
891 surf->data = (surfaceType_t *) cv;
892
893 // copy vertexes
894 surf->cullinfo.type = CULLINFO_BOX;
895 ClearBounds(surf->cullinfo.bounds[0], surf->cullinfo.bounds[1]);
896 verts += LittleLong(ds->firstVert);
897 for(i = 0; i < numVerts; i++)
898 LoadDrawVertToSrfVert(&cv->verts[i], &verts[i], -1, hdrVertColors ? hdrVertColors + (ds->firstVert + i) * 3 : NULL, surf->cullinfo.bounds);
899
900 // copy triangles
901 badTriangles = 0;
902 indexes += LittleLong(ds->firstIndex);
903 for(i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3)
904 {
905 for(j = 0; j < 3; j++)
906 {
907 tri[j] = LittleLong(indexes[i + j]);
908
909 if(tri[j] >= numVerts)
910 {
911 ri.Error(ERR_DROP, "Bad index in face surface");
912 }
913 }
914
915 if ((tri[0] == tri[1]) || (tri[1] == tri[2]) || (tri[0] == tri[2]))
916 {
917 tri -= 3;
918 badTriangles++;
919 }
920 }
921
922 if (badTriangles)
923 {
924 ri.Printf(PRINT_WARNING, "Trisurf has bad triangles, originally shader %s %d tris %d verts, now %d tris\n", surf->shader->name, numIndexes / 3, numVerts, numIndexes / 3 - badTriangles);
925 cv->numIndexes -= badTriangles * 3;
926 }
927
928 // Calculate tangent spaces
929 {
930 srfVert_t *dv[3];
931
932 for(i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3)
933 {
934 dv[0] = &cv->verts[tri[0]];
935 dv[1] = &cv->verts[tri[1]];
936 dv[2] = &cv->verts[tri[2]];
937
938 R_CalcTangentVectors(dv);
939 }
940 }
941 }
942
943 /*
944 ===============
945 ParseFlare
946 ===============
947 */
948 static void ParseFlare( dsurface_t *ds, drawVert_t *verts, msurface_t *surf, int *indexes ) {
949 srfFlare_t *flare;
950 int i;
951
952 // get fog volume
953 surf->fogIndex = LittleLong( ds->fogNum ) + 1;
954
955 // get shader
956 surf->shader = ShaderForShaderNum( ds->shaderNum, LIGHTMAP_BY_VERTEX );
957 if ( r_singleShader->integer && !surf->shader->isSky ) {
958 surf->shader = tr.defaultShader;
959 }
960
961 //flare = ri.Hunk_Alloc( sizeof( *flare ), h_low );
962 flare = (void *)surf->data;
963 flare->surfaceType = SF_FLARE;
964
965 surf->data = (surfaceType_t *)flare;
966
967 for ( i = 0 ; i < 3 ; i++ ) {
968 flare->origin[i] = LittleFloat( ds->lightmapOrigin[i] );
969 flare->color[i] = LittleFloat( ds->lightmapVecs[0][i] );
970 flare->normal[i] = LittleFloat( ds->lightmapVecs[2][i] );
971 }
972
973 surf->cullinfo.type = CULLINFO_NONE;
974 }
975
976
977 /*
978 =================
979 R_MergedWidthPoints
980
981 returns true if there are grid points merged on a width edge
982 =================
983 */
984 int R_MergedWidthPoints(srfBspSurface_t *grid, int offset) {
985 int i, j;
986
987 for (i = 1; i < grid->width-1; i++) {
988 for (j = i + 1; j < grid->width-1; j++) {
989 if ( fabs(grid->verts[i + offset].xyz[0] - grid->verts[j + offset].xyz[0]) > .1) continue;
990 if ( fabs(grid->verts[i + offset].xyz[1] - grid->verts[j + offset].xyz[1]) > .1) continue;
991 if ( fabs(grid->verts[i + offset].xyz[2] - grid->verts[j + offset].xyz[2]) > .1) continue;
992 return qtrue;
993 }
994 }
995 return qfalse;
996 }
997
998 /*
999 =================
1000 R_MergedHeightPoints
1001
1002 returns true if there are grid points merged on a height edge
1003 =================
1004 */
1005 int R_MergedHeightPoints(srfBspSurface_t *grid, int offset) {
1006 int i, j;
1007
1008 for (i = 1; i < grid->height-1; i++) {
1009 for (j = i + 1; j < grid->height-1; j++) {
1010 if ( fabs(grid->verts[grid->width * i + offset].xyz[0] - grid->verts[grid->width * j + offset].xyz[0]) > .1) continue;
1011 if ( fabs(grid->verts[grid->width * i + offset].xyz[1] - grid->verts[grid->width * j + offset].xyz[1]) > .1) continue;
1012 if ( fabs(grid->verts[grid->width * i + offset].xyz[2] - grid->verts[grid->width * j + offset].xyz[2]) > .1) continue;
1013 return qtrue;
1014 }
1015 }
1016 return qfalse;
1017 }
1018
1019 /*
1020 =================
1021 R_FixSharedVertexLodError_r
1022
1023 NOTE: never sync LoD through grid edges with merged points!
1024
1025 FIXME: write generalized version that also avoids cracks between a patch and one that meets half way?
1026 =================
1027 */
1028 void R_FixSharedVertexLodError_r( int start, srfBspSurface_t *grid1 ) {
1029 int j, k, l, m, n, offset1, offset2, touch;
1030 srfBspSurface_t *grid2;
1031
1032 for ( j = start; j < s_worldData.numsurfaces; j++ ) {
1033 //
1034 grid2 = (srfBspSurface_t *) s_worldData.surfaces[j].data;
1035 // if this surface is not a grid
1036 if ( grid2->surfaceType != SF_GRID ) continue;
1037 // if the LOD errors are already fixed for this patch
1038 if ( grid2->lodFixed == 2 ) continue;
1039 // grids in the same LOD group should have the exact same lod radius
1040 if ( grid1->lodRadius != grid2->lodRadius ) continue;
1041 // grids in the same LOD group should have the exact same lod origin
1042 if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue;
1043 if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue;
1044 if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue;
1045 //
1046 touch = qfalse;
1047 for (n = 0; n < 2; n++) {
1048 //
1049 if (n) offset1 = (grid1->height-1) * grid1->width;
1050 else offset1 = 0;
1051 if (R_MergedWidthPoints(grid1, offset1)) continue;
1052 for (k = 1; k < grid1->width-1; k++) {
1053 for (m = 0; m < 2; m++) {
1054
1055 if (m) offset2 = (grid2->height-1) * grid2->width;
1056 else offset2 = 0;
1057 if (R_MergedWidthPoints(grid2, offset2)) continue;
1058 for ( l = 1; l < grid2->width-1; l++) {
1059 //
1060 if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue;
1061 if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue;
1062 if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue;
1063 // ok the points are equal and should have the same lod error
1064 grid2->widthLodError[l] = grid1->widthLodError[k];
1065 touch = qtrue;
1066 }
1067 }
1068 for (m = 0; m < 2; m++) {
1069
1070 if (m) offset2 = grid2->width-1;
1071 else offset2 = 0;
1072 if (R_MergedHeightPoints(grid2, offset2)) continue;
1073 for ( l = 1; l < grid2->height-1; l++) {
1074 //
1075 if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue;
1076 if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue;
1077 if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue;
1078 // ok the points are equal and should have the same lod error
1079 grid2->heightLodError[l] = grid1->widthLodError[k];
1080 touch = qtrue;
1081 }
1082 }
1083 }
1084 }
1085 for (n = 0; n < 2; n++) {
1086 //
1087 if (n) offset1 = grid1->width-1;
1088 else offset1 = 0;
1089 if (R_MergedHeightPoints(grid1, offset1)) continue;
1090 for (k = 1; k < grid1->height-1; k++) {
1091 for (m = 0; m < 2; m++) {
1092
1093 if (m) offset2 = (grid2->height-1) * grid2->width;
1094 else offset2 = 0;
1095 if (R_MergedWidthPoints(grid2, offset2)) continue;
1096 for ( l = 1; l < grid2->width-1; l++) {
1097 //
1098 if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue;
1099 if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue;
1100 if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue;
1101 // ok the points are equal and should have the same lod error
1102 grid2->widthLodError[l] = grid1->heightLodError[k];
1103 touch = qtrue;
1104 }
1105 }
1106 for (m = 0; m < 2; m++) {
1107
1108 if (m) offset2 = grid2->width-1;
1109 else offset2 = 0;
1110 if (R_MergedHeightPoints(grid2, offset2)) continue;
1111 for ( l = 1; l < grid2->height-1; l++) {
1112 //
1113 if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue;
1114 if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue;
1115 if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue;
1116 // ok the points are equal and should have the same lod error
1117 grid2->heightLodError[l] = grid1->heightLodError[k];
1118 touch = qtrue;
1119 }
1120 }
1121 }
1122 }
1123 if (touch) {
1124 grid2->lodFixed = 2;
1125 R_FixSharedVertexLodError_r ( start, grid2 );
1126 //NOTE: this would be correct but makes things really slow
1127 //grid2->lodFixed = 1;
1128 }
1129 }
1130 }
1131
1132 /*
1133 =================
1134 R_FixSharedVertexLodError
1135
1136 This function assumes that all patches in one group are nicely stitched together for the highest LoD.
1137 If this is not the case this function will still do its job but won't fix the highest LoD cracks.
1138 =================
1139 */
1140 void R_FixSharedVertexLodError( void ) {
1141 int i;
1142 srfBspSurface_t *grid1;
1143
1144 for ( i = 0; i < s_worldData.numsurfaces; i++ ) {
1145 //
1146 grid1 = (srfBspSurface_t *) s_worldData.surfaces[i].data;
1147 // if this surface is not a grid
1148 if ( grid1->surfaceType != SF_GRID )
1149 continue;
1150 //
1151 if ( grid1->lodFixed )
1152 continue;
1153 //
1154 grid1->lodFixed = 2;
1155 // recursively fix other patches in the same LOD group
1156 R_FixSharedVertexLodError_r( i + 1, grid1);
1157 }
1158 }
1159
1160
1161 /*
1162 ===============
1163 R_StitchPatches
1164 ===============
1165 */
1166 int R_StitchPatches( int grid1num, int grid2num ) {
1167 float *v1, *v2;
1168 srfBspSurface_t *grid1, *grid2;
1169 int k, l, m, n, offset1, offset2, row, column;
1170
1171 grid1 = (srfBspSurface_t *) s_worldData.surfaces[grid1num].data;
1172 grid2 = (srfBspSurface_t *) s_worldData.surfaces[grid2num].data;
1173 for (n = 0; n < 2; n++) {
1174 //
1175 if (n) offset1 = (grid1->height-1) * grid1->width;
1176 else offset1 = 0;
1177 if (R_MergedWidthPoints(grid1, offset1))
1178 continue;
1179 for (k = 0; k < grid1->width-2; k += 2) {
1180
1181 for (m = 0; m < 2; m++) {
1182
1183 if ( grid2->width >= MAX_GRID_SIZE )
1184 break;
1185 if (m) offset2 = (grid2->height-1) * grid2->width;
1186 else offset2 = 0;
1187 for ( l = 0; l < grid2->width-1; l++) {
1188 //
1189 v1 = grid1->verts[k + offset1].xyz;
1190 v2 = grid2->verts[l + offset2].xyz;
1191 if ( fabs(v1[0] - v2[0]) > .1)
1192 continue;
1193 if ( fabs(v1[1] - v2[1]) > .1)
1194 continue;
1195 if ( fabs(v1[2] - v2[2]) > .1)
1196 continue;
1197
1198 v1 = grid1->verts[k + 2 + offset1].xyz;
1199 v2 = grid2->verts[l + 1 + offset2].xyz;
1200 if ( fabs(v1[0] - v2[0]) > .1)
1201 continue;
1202 if ( fabs(v1[1] - v2[1]) > .1)
1203 continue;
1204 if ( fabs(v1[2] - v2[2]) > .1)
1205 continue;
1206 //
1207 v1 = grid2->verts[l + offset2].xyz;
1208 v2 = grid2->verts[l + 1 + offset2].xyz;
1209 if ( fabs(v1[0] - v2[0]) < .01 &&
1210 fabs(v1[1] - v2[1]) < .01 &&
1211 fabs(v1[2] - v2[2]) < .01)
1212 continue;
1213 //
1214 //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
1215 // insert column into grid2 right after after column l
1216 if (m) row = grid2->height-1;
1217 else row = 0;
1218 R_GridInsertColumn( grid2, l+1, row,
1219 grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]);
1220 grid2->lodStitched = qfalse;
1221 s_worldData.surfaces[grid2num].data = (void *) grid2;
1222 return qtrue;
1223 }
1224 }
1225 for (m = 0; m < 2; m++) {
1226
1227 if (grid2->height >= MAX_GRID_SIZE)
1228 break;
1229 if (m) offset2 = grid2->width-1;
1230 else offset2 = 0;
1231 for ( l = 0; l < grid2->height-1; l++) {
1232 //
1233 v1 = grid1->verts[k + offset1].xyz;
1234 v2 = grid2->verts[grid2->width * l + offset2].xyz;
1235 if ( fabs(v1[0] - v2[0]) > .1)
1236 continue;
1237 if ( fabs(v1[1] - v2[1]) > .1)
1238 continue;
1239 if ( fabs(v1[2] - v2[2]) > .1)
1240 continue;
1241
1242 v1 = grid1->verts[k + 2 + offset1].xyz;
1243 v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
1244 if ( fabs(v1[0] - v2[0]) > .1)
1245 continue;
1246 if ( fabs(v1[1] - v2[1]) > .1)
1247 continue;
1248 if ( fabs(v1[2] - v2[2]) > .1)
1249 continue;
1250 //
1251 v1 = grid2->verts[grid2->width * l + offset2].xyz;
1252 v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
1253 if ( fabs(v1[0] - v2[0]) < .01 &&
1254 fabs(v1[1] - v2[1]) < .01 &&
1255 fabs(v1[2] - v2[2]) < .01)
1256 continue;
1257 //
1258 //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
1259 // insert row into grid2 right after after row l
1260 if (m) column = grid2->width-1;
1261 else column = 0;
1262 R_GridInsertRow( grid2, l+1, column,
1263 grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]);
1264 grid2->lodStitched = qfalse;
1265 s_worldData.surfaces[grid2num].data = (void *) grid2;
1266 return qtrue;
1267 }
1268 }
1269 }
1270 }
1271 for (n = 0; n < 2; n++) {
1272 //
1273 if (n) offset1 = grid1->width-1;
1274 else offset1 = 0;
1275 if (R_MergedHeightPoints(grid1, offset1))
1276 continue;
1277 for (k = 0; k < grid1->height-2; k += 2) {
1278 for (m = 0; m < 2; m++) {
1279
1280 if ( grid2->width >= MAX_GRID_SIZE )
1281 break;
1282 if (m) offset2 = (grid2->height-1) * grid2->width;
1283 else offset2 = 0;
1284 for ( l = 0; l < grid2->width-1; l++) {
1285 //
1286 v1 = grid1->verts[grid1->width * k + offset1].xyz;
1287 v2 = grid2->verts[l + offset2].xyz;
1288 if ( fabs(v1[0] - v2[0]) > .1)
1289 continue;
1290 if ( fabs(v1[1] - v2[1]) > .1)
1291 continue;
1292 if ( fabs(v1[2] - v2[2]) > .1)
1293 continue;
1294
1295 v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz;
1296 v2 = grid2->verts[l + 1 + offset2].xyz;
1297 if ( fabs(v1[0] - v2[0]) > .1)
1298 continue;
1299 if ( fabs(v1[1] - v2[1]) > .1)
1300 continue;
1301 if ( fabs(v1[2] - v2[2]) > .1)
1302 continue;
1303 //
1304 v1 = grid2->verts[l + offset2].xyz;
1305 v2 = grid2->verts[(l + 1) + offset2].xyz;
1306 if ( fabs(v1[0] - v2[0]) < .01 &&
1307 fabs(v1[1] - v2[1]) < .01 &&
1308 fabs(v1[2] - v2[2]) < .01)
1309 continue;
1310 //
1311 //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
1312 // insert column into grid2 right after after column l
1313 if (m) row = grid2->height-1;
1314 else row = 0;
1315 R_GridInsertColumn( grid2, l+1, row,
1316 grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]);
1317 grid2->lodStitched = qfalse;
1318 s_worldData.surfaces[grid2num].data = (void *) grid2;
1319 return qtrue;
1320 }
1321 }
1322 for (m = 0; m < 2; m++) {
1323
1324 if (grid2->height >= MAX_GRID_SIZE)
1325 break;
1326 if (m) offset2 = grid2->width-1;
1327 else offset2 = 0;
1328 for ( l = 0; l < grid2->height-1; l++) {
1329 //
1330 v1 = grid1->verts[grid1->width * k + offset1].xyz;
1331 v2 = grid2->verts[grid2->width * l + offset2].xyz;
1332 if ( fabs(v1[0] - v2[0]) > .1)
1333 continue;
1334 if ( fabs(v1[1] - v2[1]) > .1)
1335 continue;
1336 if ( fabs(v1[2] - v2[2]) > .1)
1337 continue;
1338
1339 v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz;
1340 v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
1341 if ( fabs(v1[0] - v2[0]) > .1)
1342 continue;
1343 if ( fabs(v1[1] - v2[1]) > .1)
1344 continue;
1345 if ( fabs(v1[2] - v2[2]) > .1)
1346 continue;
1347 //
1348 v1 = grid2->verts[grid2->width * l + offset2].xyz;
1349 v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
1350 if ( fabs(v1[0] - v2[0]) < .01 &&
1351 fabs(v1[1] - v2[1]) < .01 &&
1352 fabs(v1[2] - v2[2]) < .01)
1353 continue;
1354 //
1355 //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
1356 // insert row into grid2 right after after row l
1357 if (m) column = grid2->width-1;
1358 else column = 0;
1359 R_GridInsertRow( grid2, l+1, column,
1360 grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]);
1361 grid2->lodStitched = qfalse;
1362 s_worldData.surfaces[grid2num].data = (void *) grid2;
1363 return qtrue;
1364 }
1365 }
1366 }
1367 }
1368 for (n = 0; n < 2; n++) {
1369 //
1370 if (n) offset1 = (grid1->height-1) * grid1->width;
1371 else offset1 = 0;
1372 if (R_MergedWidthPoints(grid1, offset1))
1373 continue;
1374 for (k = grid1->width-1; k > 1; k -= 2) {
1375
1376 for (m = 0; m < 2; m++) {
1377
1378 if ( !grid2 || grid2->width >= MAX_GRID_SIZE )
1379 break;
1380 if (m) offset2 = (grid2->height-1) * grid2->width;
1381 else offset2 = 0;
1382 for ( l = 0; l < grid2->width-1; l++) {
1383 //
1384 v1 = grid1->verts[k + offset1].xyz;
1385 v2 = grid2->verts[l + offset2].xyz;
1386 if ( fabs(v1[0] - v2[0]) > .1)
1387 continue;
1388 if ( fabs(v1[1] - v2[1]) > .1)
1389 continue;
1390 if ( fabs(v1[2] - v2[2]) > .1)
1391 continue;
1392
1393 v1 = grid1->verts[k - 2 + offset1].xyz;
1394 v2 = grid2->verts[l + 1 + offset2].xyz;
1395 if ( fabs(v1[0] - v2[0]) > .1)
1396 continue;
1397 if ( fabs(v1[1] - v2[1]) > .1)
1398 continue;
1399 if ( fabs(v1[2] - v2[2]) > .1)
1400 continue;
1401 //
1402 v1 = grid2->verts[l + offset2].xyz;
1403 v2 = grid2->verts[(l + 1) + offset2].xyz;
1404 if ( fabs(v1[0] - v2[0]) < .01 &&
1405 fabs(v1[1] - v2[1]) < .01 &&
1406 fabs(v1[2] - v2[2]) < .01)
1407 continue;
1408 //
1409 //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
1410 // insert column into grid2 right after after column l
1411 if (m) row = grid2->height-1;
1412 else row = 0;
1413 R_GridInsertColumn( grid2, l+1, row,
1414 grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]);
1415 grid2->lodStitched = qfalse;
1416 s_worldData.surfaces[grid2num].data = (void *) grid2;
1417 return qtrue;
1418 }
1419 }
1420 for (m = 0; m < 2; m++) {
1421
1422 if (!grid2 || grid2->height >= MAX_GRID_SIZE)
1423 break;
1424 if (m) offset2 = grid2->width-1;
1425 else offset2 = 0;
1426 for ( l = 0; l < grid2->height-1; l++) {
1427 //
1428 v1 = grid1->verts[k + offset1].xyz;
1429 v2 = grid2->verts[grid2->width * l + offset2].xyz;
1430 if ( fabs(v1[0] - v2[0]) > .1)
1431 continue;
1432 if ( fabs(v1[1] - v2[1]) > .1)
1433 continue;
1434 if ( fabs(v1[2] - v2[2]) > .1)
1435 continue;
1436
1437 v1 = grid1->verts[k - 2 + offset1].xyz;
1438 v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
1439 if ( fabs(v1[0] - v2[0]) > .1)
1440 continue;
1441 if ( fabs(v1[1] - v2[1]) > .1)
1442 continue;
1443 if ( fabs(v1[2] - v2[2]) > .1)
1444 continue;
1445 //
1446 v1 = grid2->verts[grid2->width * l + offset2].xyz;
1447 v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
1448 if ( fabs(v1[0] - v2[0]) < .01 &&
1449 fabs(v1[1] - v2[1]) < .01 &&
1450 fabs(v1[2] - v2[2]) < .01)
1451 continue;
1452 //
1453 //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
1454 // insert row into grid2 right after after row l
1455 if (m) column = grid2->width-1;
1456 else column = 0;
1457 R_GridInsertRow( grid2, l+1, column,
1458 grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]);
1459 if (!grid2)
1460 break;
1461 grid2->lodStitched = qfalse;
1462 s_worldData.surfaces[grid2num].data = (void *) grid2;
1463 return qtrue;
1464 }
1465 }
1466 }
1467 }
1468 for (n = 0; n < 2; n++) {
1469 //
1470 if (n) offset1 = grid1->width-1;
1471 else offset1 = 0;
1472 if (R_MergedHeightPoints(grid1, offset1))
1473 continue;
1474 for (k = grid1->height-1; k > 1; k -= 2) {
1475 for (m = 0; m < 2; m++) {
1476
1477 if (!grid2 || grid2->width >= MAX_GRID_SIZE )
1478 break;
1479 if (m) offset2 = (grid2->height-1) * grid2->width;
1480 else offset2 = 0;
1481 for ( l = 0; l < grid2->width-1; l++) {
1482 //
1483 v1 = grid1->verts[grid1->width * k + offset1].xyz;
1484 v2 = grid2->verts[l + offset2].xyz;
1485 if ( fabs(v1[0] - v2[0]) > .1)
1486 continue;
1487 if ( fabs(v1[1] - v2[1]) > .1)
1488 continue;
1489 if ( fabs(v1[2] - v2[2]) > .1)
1490 continue;
1491
1492 v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz;
1493 v2 = grid2->verts[l + 1 + offset2].xyz;
1494 if ( fabs(v1[0] - v2[0]) > .1)
1495 continue;
1496 if ( fabs(v1[1] - v2[1]) > .1)
1497 continue;
1498 if ( fabs(v1[2] - v2[2]) > .1)
1499 continue;
1500 //
1501 v1 = grid2->verts[l + offset2].xyz;
1502 v2 = grid2->verts[(l + 1) + offset2].xyz;
1503 if ( fabs(v1[0] - v2[0]) < .01 &&
1504 fabs(v1[1] - v2[1]) < .01 &&
1505 fabs(v1[2] - v2[2]) < .01)
1506 continue;
1507 //
1508 //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
1509 // insert column into grid2 right after after column l
1510 if (m) row = grid2->height-1;
1511 else row = 0;
1512 R_GridInsertColumn( grid2, l+1, row,
1513 grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]);
1514 grid2->lodStitched = qfalse;
1515 s_worldData.surfaces[grid2num].data = (void *) grid2;
1516 return qtrue;
1517 }
1518 }
1519 for (m = 0; m < 2; m++) {
1520
1521 if (!grid2 || grid2->height >= MAX_GRID_SIZE)
1522 break;
1523 if (m) offset2 = grid2->width-1;
1524 else offset2 = 0;
1525 for ( l = 0; l < grid2->height-1; l++) {
1526 //
1527 v1 = grid1->verts[grid1->width * k + offset1].xyz;
1528 v2 = grid2->verts[grid2->width * l + offset2].xyz;
1529 if ( fabs(v1[0] - v2[0]) > .1)
1530 continue;
1531 if ( fabs(v1[1] - v2[1]) > .1)
1532 continue;
1533 if ( fabs(v1[2] - v2[2]) > .1)
1534 continue;
1535
1536 v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz;
1537 v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
1538 if ( fabs(v1[0] - v2[0]) > .1)
1539 continue;
1540 if ( fabs(v1[1] - v2[1]) > .1)
1541 continue;
1542 if ( fabs(v1[2] - v2[2]) > .1)
1543 continue;
1544 //
1545 v1 = grid2->verts[grid2->width * l + offset2].xyz;
1546 v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
1547 if ( fabs(v1[0] - v2[0]) < .01 &&
1548 fabs(v1[1] - v2[1]) < .01 &&
1549 fabs(v1[2] - v2[2]) < .01)
1550 continue;
1551 //
1552 //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
1553 // insert row into grid2 right after after row l
1554 if (m) column = grid2->width-1;
1555 else column = 0;
1556 R_GridInsertRow( grid2, l+1, column,
1557 grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]);
1558 grid2->lodStitched = qfalse;
1559 s_worldData.surfaces[grid2num].data = (void *) grid2;
1560 return qtrue;
1561 }
1562 }
1563 }
1564 }
1565 return qfalse;
1566 }
1567
1568 /*
1569 ===============
1570 R_TryStitchPatch
1571
1572 This function will try to stitch patches in the same LoD group together for the highest LoD.
1573
1574 Only single missing vertice cracks will be fixed.
1575
1576 Vertices will be joined at the patch side a crack is first found, at the other side
1577 of the patch (on the same row or column) the vertices will not be joined and cracks
1578 might still appear at that side.
1579 ===============
1580 */
1581 int R_TryStitchingPatch( int grid1num ) {
1582 int j, numstitches;
1583 srfBspSurface_t *grid1, *grid2;
1584
1585 numstitches = 0;
1586 grid1 = (srfBspSurface_t *) s_worldData.surfaces[grid1num].data;
1587 for ( j = 0; j < s_worldData.numsurfaces; j++ ) {
1588 //
1589 grid2 = (srfBspSurface_t *) s_worldData.surfaces[j].data;
1590 // if this surface is not a grid
1591 if ( grid2->surfaceType != SF_GRID ) continue;
1592 // grids in the same LOD group should have the exact same lod radius
1593 if ( grid1->lodRadius != grid2->lodRadius ) continue;
1594 // grids in the same LOD group should have the exact same lod origin
1595 if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue;
1596 if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue;
1597 if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue;
1598 //
1599 while (R_StitchPatches(grid1num, j))
1600 {
1601 numstitches++;
1602 }
1603 }
1604 return numstitches;
1605 }
1606
1607 /*
1608 ===============
1609 R_StitchAllPatches
1610 ===============
1611 */
1612 void R_StitchAllPatches( void ) {
1613 int i, stitched, numstitches;
1614 srfBspSurface_t *grid1;
1615
1616 numstitches = 0;
1617 do
1618 {
1619 stitched = qfalse;
1620 for ( i = 0; i < s_worldData.numsurfaces; i++ ) {
1621 //
1622 grid1 = (srfBspSurface_t *) s_worldData.surfaces[i].data;
1623 // if this surface is not a grid
1624 if ( grid1->surfaceType != SF_GRID )
1625 continue;
1626 //
1627 if ( grid1->lodStitched )
1628 continue;
1629 //
1630 grid1->lodStitched = qtrue;
1631 stitched = qtrue;
1632 //
1633 numstitches += R_TryStitchingPatch( i );
1634 }
1635 }
1636 while (stitched);
1637 ri.Printf( PRINT_ALL, "stitched %d LoD cracks\n", numstitches );
1638 }
1639
1640 /*
1641 ===============
1642 R_MovePatchSurfacesToHunk
1643 ===============
1644 */
1645 void R_MovePatchSurfacesToHunk(void) {
1646 int i;
1647 srfBspSurface_t *grid;
1648
1649 for ( i = 0; i < s_worldData.numsurfaces; i++ ) {
1650 void *copyFrom;
1651 //
1652 grid = (srfBspSurface_t *) s_worldData.surfaces[i].data;
1653 // if this surface is not a grid
1654 if ( grid->surfaceType != SF_GRID )
1655 continue;
1656 //
1657
1658 copyFrom = grid->widthLodError;
1659 grid->widthLodError = ri.Hunk_Alloc( grid->width * 4, h_low );
1660 Com_Memcpy(grid->widthLodError, copyFrom, grid->width * 4);
1661 ri.Free(copyFrom);
1662
1663 copyFrom = grid->heightLodError;
1664 grid->heightLodError = ri.Hunk_Alloc(grid->height * 4, h_low);
1665 Com_Memcpy(grid->heightLodError, copyFrom, grid->height * 4);
1666 ri.Free(copyFrom);
1667
1668 copyFrom = grid->indexes;
1669 grid->indexes = ri.Hunk_Alloc(grid->numIndexes * sizeof(glIndex_t), h_low);
1670 Com_Memcpy(grid->indexes, copyFrom, grid->numIndexes * sizeof(glIndex_t));
1671 ri.Free(copyFrom);
1672
1673 copyFrom = grid->verts;
1674 grid->verts = ri.Hunk_Alloc(grid->numVerts * sizeof(srfVert_t), h_low);
1675 Com_Memcpy(grid->verts, copyFrom, grid->numVerts * sizeof(srfVert_t));
1676 ri.Free(copyFrom);
1677 }
1678 }
1679
1680
1681 /*
1682 ===============
1683 R_LoadSurfaces
1684 ===============
1685 */
1686 static void R_LoadSurfaces( lump_t *surfs, lump_t *verts, lump_t *indexLump ) {
1687 dsurface_t *in;
1688 msurface_t *out;
1689 drawVert_t *dv;
1690 int *indexes;
1691 int count;
1692 int numFaces, numMeshes, numTriSurfs, numFlares;
1693 int i;
1694 float *hdrVertColors = NULL;
1695
1696 numFaces = 0;
1697 numMeshes = 0;
1698 numTriSurfs = 0;
1699 numFlares = 0;
1700
1701 if (surfs->filelen % sizeof(*in))
1702 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
1703 count = surfs->filelen / sizeof(*in);
1704
1705 dv = (void *)(fileBase + verts->fileofs);
1706 if (verts->filelen % sizeof(*dv))
1707 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
1708
1709 indexes = (void *)(fileBase + indexLump->fileofs);
1710 if ( indexLump->filelen % sizeof(*indexes))
1711 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
1712
1713 out = ri.Hunk_Alloc ( count * sizeof(*out), h_low );
1714
1715 s_worldData.surfaces = out;
1716 s_worldData.numsurfaces = count;
1717 s_worldData.surfacesViewCount = ri.Hunk_Alloc ( count * sizeof(*s_worldData.surfacesViewCount), h_low );
1718 s_worldData.surfacesDlightBits = ri.Hunk_Alloc ( count * sizeof(*s_worldData.surfacesDlightBits), h_low );
1719 s_worldData.surfacesPshadowBits = ri.Hunk_Alloc ( count * sizeof(*s_worldData.surfacesPshadowBits), h_low );
1720
1721 // load hdr vertex colors
1722 if (r_hdr->integer)
1723 {
1724 char filename[MAX_QPATH];
1725 int size;
1726
1727 Com_sprintf( filename, sizeof( filename ), "maps/%s/vertlight.raw", s_worldData.baseName);
1728 //ri.Printf(PRINT_ALL, "looking for %s\n", filename);
1729
1730 size = ri.FS_ReadFile(filename, (void **)&hdrVertColors);
1731
1732 if (hdrVertColors)
1733 {
1734 //ri.Printf(PRINT_ALL, "Found!\n");
1735 if (size != sizeof(float) * 3 * (verts->filelen / sizeof(*dv)))
1736 ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, (int)((sizeof(float)) * 3 * (verts->filelen / sizeof(*dv))));
1737 }
1738 }
1739
1740
1741 // Two passes, allocate surfaces first, then load them full of data
1742 // This ensures surfaces are close together to reduce L2 cache misses when using VAOs,
1743 // which don't actually use the verts and indexes
1744 in = (void *)(fileBase + surfs->fileofs);
1745 out = s_worldData.surfaces;
1746 for ( i = 0 ; i < count ; i++, in++, out++ ) {
1747 switch ( LittleLong( in->surfaceType ) ) {
1748 case MST_PATCH:
1749 out->data = ri.Hunk_Alloc( sizeof(srfBspSurface_t), h_low);
1750 break;
1751 case MST_TRIANGLE_SOUP:
1752 out->data = ri.Hunk_Alloc( sizeof(srfBspSurface_t), h_low);
1753 break;
1754 case MST_PLANAR:
1755 out->data = ri.Hunk_Alloc( sizeof(srfBspSurface_t), h_low);
1756 break;
1757 case MST_FLARE:
1758 out->data = ri.Hunk_Alloc( sizeof(srfFlare_t), h_low);
1759 break;
1760 default:
1761 break;
1762 }
1763 }
1764
1765 in = (void *)(fileBase + surfs->fileofs);
1766 out = s_worldData.surfaces;
1767 for ( i = 0 ; i < count ; i++, in++, out++ ) {
1768 switch ( LittleLong( in->surfaceType ) ) {
1769 case MST_PATCH:
1770 ParseMesh ( in, dv, hdrVertColors, out );
1771 numMeshes++;
1772 break;
1773 case MST_TRIANGLE_SOUP:
1774 ParseTriSurf( in, dv, hdrVertColors, out, indexes );
1775 numTriSurfs++;
1776 break;
1777 case MST_PLANAR:
1778 ParseFace( in, dv, hdrVertColors, out, indexes );
1779 numFaces++;
1780 break;
1781 case MST_FLARE:
1782 ParseFlare( in, dv, out, indexes );
1783 numFlares++;
1784 break;
1785 default:
1786 ri.Error( ERR_DROP, "Bad surfaceType" );
1787 }
1788 }
1789
1790 if (hdrVertColors)
1791 {
1792 ri.FS_FreeFile(hdrVertColors);
1793 }
1794
1795 #ifdef PATCH_STITCHING
1796 R_StitchAllPatches();
1797 #endif
1798
1799 R_FixSharedVertexLodError();
1800
1801 #ifdef PATCH_STITCHING
1802 R_MovePatchSurfacesToHunk();
1803 #endif
1804
1805 ri.Printf( PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n",
1806 numFaces, numMeshes, numTriSurfs, numFlares );
1807 }
1808
1809
1810
1811 /*
1812 =================
1813 R_LoadSubmodels
1814 =================
1815 */
1816 static void R_LoadSubmodels( lump_t *l ) {
1817 dmodel_t *in;
1818 bmodel_t *out;
1819 int i, j, count;
1820
1821 in = (void *)(fileBase + l->fileofs);
1822 if (l->filelen % sizeof(*in))
1823 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
1824 count = l->filelen / sizeof(*in);
1825
1826 s_worldData.numBModels = count;
1827 s_worldData.bmodels = out = ri.Hunk_Alloc( count * sizeof(*out), h_low );
1828
1829 for ( i=0 ; i<count ; i++, in++, out++ ) {
1830 model_t *model;
1831
1832 model = R_AllocModel();
1833
1834 assert( model != NULL ); // this should never happen
1835 if ( model == NULL ) {
1836 ri.Error(ERR_DROP, "R_LoadSubmodels: R_AllocModel() failed");
1837 }
1838
1839 model->type = MOD_BRUSH;
1840 model->bmodel = out;
1841 Com_sprintf( model->name, sizeof( model->name ), "*%d", i );
1842
1843 for (j=0 ; j<3 ; j++) {
1844 out->bounds[0][j] = LittleFloat (in->mins[j]);
1845 out->bounds[1][j] = LittleFloat (in->maxs[j]);
1846 }
1847
1848 out->firstSurface = LittleLong( in->firstSurface );
1849 out->numSurfaces = LittleLong( in->numSurfaces );
1850
1851 if(i == 0)
1852 {
1853 // Add this for limiting VAO surface creation
1854 s_worldData.numWorldSurfaces = out->numSurfaces;
1855 }
1856 }
1857 }
1858
1859
1860
1861 //==================================================================
1862
1863 /*
1864 =================
1865 R_SetParent
1866 =================
1867 */
1868 static void R_SetParent (mnode_t *node, mnode_t *parent)
1869 {
1870 node->parent = parent;
1871 if (node->contents != -1)
1872 return;
1873 R_SetParent (node->children[0], node);
1874 R_SetParent (node->children[1], node);
1875 }
1876
1877 /*
1878 =================
1879 R_LoadNodesAndLeafs
1880 =================
1881 */
1882 static void R_LoadNodesAndLeafs (lump_t *nodeLump, lump_t *leafLump) {
1883 int i, j, p;
1884 dnode_t *in;
1885 dleaf_t *inLeaf;
1886 mnode_t *out;
1887 int numNodes, numLeafs;
1888
1889 in = (void *)(fileBase + nodeLump->fileofs);
1890 if (nodeLump->filelen % sizeof(dnode_t) ||
1891 leafLump->filelen % sizeof(dleaf_t) ) {
1892 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
1893 }
1894 numNodes = nodeLump->filelen / sizeof(dnode_t);
1895 numLeafs = leafLump->filelen / sizeof(dleaf_t);
1896
1897 out = ri.Hunk_Alloc ( (numNodes + numLeafs) * sizeof(*out), h_low);
1898
1899 s_worldData.nodes = out;
1900 s_worldData.numnodes = numNodes + numLeafs;
1901 s_worldData.numDecisionNodes = numNodes;
1902
1903 // load nodes
1904 for ( i=0 ; i<numNodes; i++, in++, out++)
1905 {
1906 for (j=0 ; j<3 ; j++)
1907 {
1908 out->mins[j] = LittleLong (in->mins[j]);
1909 out->maxs[j] = LittleLong (in->maxs[j]);
1910 }
1911
1912 p = LittleLong(in->planeNum);
1913 out->plane = s_worldData.planes + p;
1914
1915 out->contents = CONTENTS_NODE; // differentiate from leafs
1916
1917 for (j=0 ; j<2 ; j++)
1918 {
1919 p = LittleLong (in->children[j]);
1920 if (p >= 0)
1921 out->children[j] = s_worldData.nodes + p;
1922 else
1923 out->children[j] = s_worldData.nodes + numNodes + (-1 - p);
1924 }
1925 }
1926
1927 // load leafs
1928 inLeaf = (void *)(fileBase + leafLump->fileofs);
1929 for ( i=0 ; i<numLeafs ; i++, inLeaf++, out++)
1930 {
1931 for (j=0 ; j<3 ; j++)
1932 {
1933 out->mins[j] = LittleLong (inLeaf->mins[j]);
1934 out->maxs[j] = LittleLong (inLeaf->maxs[j]);
1935 }
1936
1937 out->cluster = LittleLong(inLeaf->cluster);
1938 out->area = LittleLong(inLeaf->area);
1939
1940 if ( out->cluster >= s_worldData.numClusters ) {
1941 s_worldData.numClusters = out->cluster + 1;
1942 }
1943
1944 out->firstmarksurface = LittleLong(inLeaf->firstLeafSurface);
1945 out->nummarksurfaces = LittleLong(inLeaf->numLeafSurfaces);
1946 }
1947
1948 // chain descendants
1949 R_SetParent (s_worldData.nodes, NULL);
1950 }
1951
1952 //=============================================================================
1953
1954 /*
1955 =================
1956 R_LoadShaders
1957 =================
1958 */
1959 static void R_LoadShaders( lump_t *l ) {
1960 int i, count;
1961 dshader_t *in, *out;
1962
1963 in = (void *)(fileBase + l->fileofs);
1964 if (l->filelen % sizeof(*in))
1965 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
1966 count = l->filelen / sizeof(*in);
1967 out = ri.Hunk_Alloc ( count*sizeof(*out), h_low );
1968
1969 s_worldData.shaders = out;
1970 s_worldData.numShaders = count;
1971
1972 Com_Memcpy( out, in, count*sizeof(*out) );
1973
1974 for ( i=0 ; i<count ; i++ ) {
1975 out[i].surfaceFlags = LittleLong( out[i].surfaceFlags );
1976 out[i].contentFlags = LittleLong( out[i].contentFlags );
1977 }
1978 }
1979
1980
1981 /*
1982 =================
1983 R_LoadMarksurfaces
1984 =================
1985 */
1986 static void R_LoadMarksurfaces (lump_t *l)
1987 {
1988 int i, j, count;
1989 int *in;
1990 int *out;
1991
1992 in = (void *)(fileBase + l->fileofs);
1993 if (l->filelen % sizeof(*in))
1994 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
1995 count = l->filelen / sizeof(*in);
1996 out = ri.Hunk_Alloc ( count*sizeof(*out), h_low);
1997
1998 s_worldData.marksurfaces = out;
1999 s_worldData.nummarksurfaces = count;
2000
2001 for ( i=0 ; i<count ; i++)
2002 {
2003 j = LittleLong(in[i]);
2004 out[i] = j;
2005 }
2006 }
2007
2008
2009 /*
2010 =================
2011 R_LoadPlanes
2012 =================
2013 */
2014 static void R_LoadPlanes( lump_t *l ) {
2015 int i, j;
2016 cplane_t *out;
2017 dplane_t *in;
2018 int count;
2019 int bits;
2020
2021 in = (void *)(fileBase + l->fileofs);
2022 if (l->filelen % sizeof(*in))
2023 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
2024 count = l->filelen / sizeof(*in);
2025 out = ri.Hunk_Alloc ( count*2*sizeof(*out), h_low);
2026
2027 s_worldData.planes = out;
2028 s_worldData.numplanes = count;
2029
2030 for ( i=0 ; i<count ; i++, in++, out++) {
2031 bits = 0;
2032 for (j=0 ; j<3 ; j++) {
2033 out->normal[j] = LittleFloat (in->normal[j]);
2034 if (out->normal[j] < 0) {
2035 bits |= 1<<j;
2036 }
2037 }
2038
2039 out->dist = LittleFloat (in->dist);
2040 out->type = PlaneTypeForNormal( out->normal );
2041 out->signbits = bits;
2042 }
2043 }
2044
2045 /*
2046 =================
2047 R_LoadFogs
2048
2049 =================
2050 */
2051 static void R_LoadFogs( lump_t *l, lump_t *brushesLump, lump_t *sidesLump ) {
2052 int i;
2053 fog_t *out;
2054 dfog_t *fogs;
2055 dbrush_t *brushes, *brush;
2056 dbrushside_t *sides;
2057 int count, brushesCount, sidesCount;
2058 int sideNum;
2059 int planeNum;
2060 shader_t *shader;
2061 float d;
2062 int firstSide;
2063
2064 fogs = (void *)(fileBase + l->fileofs);
2065 if (l->filelen % sizeof(*fogs)) {
2066 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
2067 }
2068 count = l->filelen / sizeof(*fogs);
2069
2070 // create fog strucutres for them
2071 s_worldData.numfogs = count + 1;
2072 s_worldData.fogs = ri.Hunk_Alloc ( s_worldData.numfogs*sizeof(*out), h_low);
2073 out = s_worldData.fogs + 1;
2074
2075 if ( !count ) {
2076 return;
2077 }
2078
2079 brushes = (void *)(fileBase + brushesLump->fileofs);
2080 if (brushesLump->filelen % sizeof(*brushes)) {
2081 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
2082 }
2083 brushesCount = brushesLump->filelen / sizeof(*brushes);
2084
2085 sides = (void *)(fileBase + sidesLump->fileofs);
2086 if (sidesLump->filelen % sizeof(*sides)) {
2087 ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
2088 }
2089 sidesCount = sidesLump->filelen / sizeof(*sides);
2090
2091 for ( i=0 ; i<count ; i++, fogs++) {
2092 out->originalBrushNumber = LittleLong( fogs->brushNum );
2093
2094 if ( (unsigned)out->originalBrushNumber >= brushesCount ) {
2095 ri.Error( ERR_DROP, "fog brushNumber out of range" );
2096 }
2097 brush = brushes + out->originalBrushNumber;
2098
2099 firstSide = LittleLong( brush->firstSide );
2100
2101 if ( (unsigned)firstSide > sidesCount - 6 ) {
2102 ri.Error( ERR_DROP, "fog brush sideNumber out of range" );
2103 }
2104
2105 // brushes are always sorted with the axial sides first
2106 sideNum = firstSide + 0;
2107 planeNum = LittleLong( sides[ sideNum ].planeNum );
2108 out->bounds[0][0] = -s_worldData.planes[ planeNum ].dist;
2109
2110 sideNum = firstSide + 1;
2111 planeNum = LittleLong( sides[ sideNum ].planeNum );
2112 out->bounds[1][0] = s_worldData.planes[ planeNum ].dist;
2113
2114 sideNum = firstSide + 2;
2115 planeNum = LittleLong( sides[ sideNum ].planeNum );
2116 out->bounds[0][1] = -s_worldData.planes[ planeNum ].dist;
2117
2118 sideNum = firstSide + 3;
2119 planeNum = LittleLong( sides[ sideNum ].planeNum );
2120 out->bounds[1][1] = s_worldData.planes[ planeNum ].dist;
2121
2122 sideNum = firstSide + 4;
2123 planeNum = LittleLong( sides[ sideNum ].planeNum );
2124 out->bounds[0][2] = -s_worldData.planes[ planeNum ].dist;
2125
2126 sideNum = firstSide + 5;
2127 planeNum = LittleLong( sides[ sideNum ].planeNum );
2128 out->bounds[1][2] = s_worldData.planes[ planeNum ].dist;
2129
2130 // get information from the shader for fog parameters
2131 shader = R_FindShader( fogs->shader, LIGHTMAP_NONE, qtrue );
2132
2133 out->parms = shader->fogParms;
2134
2135 out->colorInt = ColorBytes4 ( shader->fogParms.color[0],
2136 shader->fogParms.color[1],
2137 shader->fogParms.color[2], 1.0 );
2138
2139 d = shader->fogParms.depthForOpaque < 1 ? 1 : shader->fogParms.depthForOpaque;
2140 out->tcScale = 1.0f / ( d * 8 );
2141
2142 // set the gradient vector
2143 sideNum = LittleLong( fogs->visibleSide );
2144
2145 if ( sideNum == -1 ) {
2146 out->hasSurface = qfalse;
2147 } else {
2148 out->hasSurface = qtrue;
2149 planeNum = LittleLong( sides[ firstSide + sideNum ].planeNum );
2150 VectorSubtract( vec3_origin, s_worldData.planes[ planeNum ].normal, out->surface );
2151 out->surface[3] = -s_worldData.planes[ planeNum ].dist;
2152 }
2153
2154 out++;
2155 }
2156
2157 }
2158
2159
2160 /*
2161 ================
2162 R_LoadLightGrid
2163
2164 ================
2165 */
2166 void R_LoadLightGrid( lump_t *l ) {
2167 int i;
2168 vec3_t maxs;
2169 int numGridPoints;
2170 world_t *w;
2171 float *wMins, *wMaxs;
2172
2173 w = &s_worldData;
2174
2175 w->lightGridInverseSize[0] = 1.0f / w->lightGridSize[0];
2176 w->lightGridInverseSize[1] = 1.0f / w->lightGridSize[1];
2177 w->lightGridInverseSize[2] = 1.0f / w->lightGridSize[2];
2178
2179 wMins = w->bmodels[0].bounds[0];
2180 wMaxs = w->bmodels[0].bounds[1];
2181
2182 for ( i = 0 ; i < 3 ; i++ ) {
2183 w->lightGridOrigin[i] = w->lightGridSize[i] * ceil( wMins[i] / w->lightGridSize[i] );
2184 maxs[i] = w->lightGridSize[i] * floor( wMaxs[i] / w->lightGridSize[i] );
2185 w->lightGridBounds[i] = (maxs[i] - w->lightGridOrigin[i])/w->lightGridSize[i] + 1;
2186 }
2187
2188 numGridPoints = w->lightGridBounds[0] * w->lightGridBounds[1] * w->lightGridBounds[2];
2189
2190 if ( l->filelen != numGridPoints * 8 ) {
2191 ri.Printf( PRINT_WARNING, "WARNING: light grid mismatch\n" );
2192 w->lightGridData = NULL;
2193 return;
2194 }
2195
2196 w->lightGridData = ri.Hunk_Alloc( l->filelen, h_low );
2197 Com_Memcpy( w->lightGridData, (void *)(fileBase + l->fileofs), l->filelen );
2198
2199 // deal with overbright bits
2200 for ( i = 0 ; i < numGridPoints ; i++ ) {
2201 R_ColorShiftLightingBytes( &w->lightGridData[i*8], &w->lightGridData[i*8] );
2202 R_ColorShiftLightingBytes( &w->lightGridData[i*8+3], &w->lightGridData[i*8+3] );
2203 }
2204
2205 // load hdr lightgrid
2206 if (r_hdr->integer)
2207 {
2208 char filename[MAX_QPATH];
2209 float *hdrLightGrid;
2210 int size;
2211
2212 Com_sprintf( filename, sizeof( filename ), "maps/%s/lightgrid.raw", s_worldData.baseName);
2213 //ri.Printf(PRINT_ALL, "looking for %s\n", filename);
2214
2215 size = ri.FS_ReadFile(filename, (void **)&hdrLightGrid);
2216
2217 if (hdrLightGrid)
2218 {
2219 //ri.Printf(PRINT_ALL, "found!\n");
2220
2221 if (size != sizeof(float) * 6 * numGridPoints)
2222 ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, (int)(sizeof(float)) * 6 * numGridPoints);
2223
2224 w->lightGrid16 = ri.Hunk_Alloc(sizeof(w->lightGrid16) * 6 * numGridPoints, h_low);
2225
2226 for (i = 0; i < numGridPoints ; i++)
2227 {
2228 vec4_t c;
2229
2230 c[0] = hdrLightGrid[i * 6];
2231 c[1] = hdrLightGrid[i * 6 + 1];
2232 c[2] = hdrLightGrid[i * 6 + 2];
2233 c[3] = 1.0f;
2234
2235 R_ColorShiftLightingFloats(c, c);
2236 ColorToRGB16(c, &w->lightGrid16[i * 6]);
2237
2238 c[0] = hdrLightGrid[i * 6 + 3];
2239 c[1] = hdrLightGrid[i * 6 + 4];
2240 c[2] = hdrLightGrid[i * 6 + 5];
2241 c[3] = 1.0f;
2242
2243 R_ColorShiftLightingFloats(c, c);
2244 ColorToRGB16(c, &w->lightGrid16[i * 6 + 3]);
2245 }
2246 }
2247 else if (0)
2248 {
2249 // promote 8-bit lightgrid to 16-bit
2250 w->lightGrid16 = ri.Hunk_Alloc(sizeof(w->lightGrid16) * 6 * numGridPoints, h_low);
2251
2252 for (i = 0; i < numGridPoints; i++)
2253 {
2254 w->lightGrid16[i * 6] = w->lightGridData[i * 8] * 257;
2255 w->lightGrid16[i * 6 + 1] = w->lightGridData[i * 8 + 1] * 257;
2256 w->lightGrid16[i * 6 + 2] = w->lightGridData[i * 8 + 2] * 257;
2257 w->lightGrid16[i * 6 + 3] = w->lightGridData[i * 8 + 3] * 257;
2258 w->lightGrid16[i * 6 + 4] = w->lightGridData[i * 8 + 4] * 257;
2259 w->lightGrid16[i * 6 + 5] = w->lightGridData[i * 8 + 5] * 257;
2260 }
2261 }
2262
2263 if (hdrLightGrid)
2264 ri.FS_FreeFile(hdrLightGrid);
2265 }
2266 }
2267
2268 /*
2269 ================
2270 R_LoadEntities
2271 ================
2272 */
2273 void R_LoadEntities( lump_t *l ) {
2274 char *p, *token, *s;
2275 char keyname[MAX_TOKEN_CHARS];
2276 char value[MAX_TOKEN_CHARS];
2277 world_t *w;
2278
2279 w = &s_worldData;
2280 w->lightGridSize[0] = 64;
2281 w->lightGridSize[1] = 64;
2282 w->lightGridSize[2] = 128;
2283
2284 p = (char *)(fileBase + l->fileofs);
2285
2286 // store for reference by the cgame
2287 w->entityString = ri.Hunk_Alloc( l->filelen + 1, h_low );
2288 strcpy( w->entityString, p );
2289 w->entityParsePoint = w->entityString;
2290
2291 token = COM_ParseExt( &p, qtrue );
2292 if (!*token || *token != '{') {
2293 return;
2294 }
2295
2296 // only parse the world spawn
2297 while ( 1 ) {
2298 // parse key
2299 token = COM_ParseExt( &p, qtrue );
2300
2301 if ( !*token || *token == '}' ) {
2302 break;
2303 }
2304 Q_strncpyz(keyname, token, sizeof(keyname));
2305
2306 // parse value
2307 token = COM_ParseExt( &p, qtrue );
2308
2309 if ( !*token || *token == '}' ) {
2310 break;
2311 }
2312 Q_strncpyz(value, token, sizeof(value));
2313
2314 // check for remapping of shaders for vertex lighting
2315 s = "vertexremapshader";
2316 if (!Q_strncmp(keyname, s, strlen(s)) ) {
2317 s = strchr(value, ';');
2318 if (!s) {
2319 ri.Printf( PRINT_WARNING, "WARNING: no semi colon in vertexshaderremap '%s'\n", value );
2320 break;
2321 }
2322 *s++ = 0;
2323 if (r_vertexLight->integer) {
2324 R_RemapShader(value, s, "0");
2325 }
2326 continue;
2327 }
2328 // check for remapping of shaders
2329 s = "remapshader";
2330 if (!Q_strncmp(keyname, s, strlen(s)) ) {
2331 s = strchr(value, ';');
2332 if (!s) {
2333 ri.Printf( PRINT_WARNING, "WARNING: no semi colon in shaderremap '%s'\n", value );
2334 break;
2335 }
2336 *s++ = 0;
2337 R_RemapShader(value, s, "0");
2338 continue;
2339 }
2340 // check for a different grid size
2341 if (!Q_stricmp(keyname, "gridsize")) {
2342 sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2] );
2343 continue;
2344 }
2345
2346 // check for auto exposure
2347 if (!Q_stricmp(keyname, "autoExposureMinMax")) {
2348 sscanf(value, "%f %f", &tr.autoExposureMinMax[0], &tr.autoExposureMinMax[1]);
2349 continue;
2350 }
2351 }
2352 }
2353
2354 /*
2355 =================
2356 R_GetEntityToken
2357 =================
2358 */
2359 qboolean R_GetEntityToken( char *buffer, int size ) {
2360 const char *s;
2361
2362 s = COM_Parse( &s_worldData.entityParsePoint );
2363 Q_strncpyz( buffer, s, size );
2364 if ( !s_worldData.entityParsePoint && !s[0] ) {
2365 s_worldData.entityParsePoint = s_worldData.entityString;
2366 return qfalse;
2367 } else {
2368 return qtrue;
2369 }
2370 }
2371
2372 #ifndef MAX_SPAWN_VARS
2373 #define MAX_SPAWN_VARS 64
2374 #endif
2375
2376 // derived from G_ParseSpawnVars() in g_spawn.c
2377 qboolean R_ParseSpawnVars( char *spawnVarChars, int maxSpawnVarChars, int *numSpawnVars, char *spawnVars[MAX_SPAWN_VARS][2] )
2378 {
2379 char keyname[MAX_TOKEN_CHARS];
2380 char com_token[MAX_TOKEN_CHARS];
2381 int numSpawnVarChars = 0;
2382
2383 *numSpawnVars = 0;
2384
2385 // parse the opening brace
2386 if ( !R_GetEntityToken( com_token, sizeof( com_token ) ) ) {
2387 // end of spawn string
2388 return qfalse;
2389 }
2390 if ( com_token[0] != '{' ) {
2391 ri.Printf( PRINT_ALL, "R_ParseSpawnVars: found %s when expecting {\n",com_token );
2392 return qfalse;
2393 }
2394
2395 // go through all the key / value pairs
2396 while ( 1 ) {
2397 int keyLength, tokenLength;
2398
2399 // parse key
2400 if ( !R_GetEntityToken( keyname, sizeof( keyname ) ) ) {
2401 ri.Printf( PRINT_ALL, "R_ParseSpawnVars: EOF without closing brace\n" );
2402 return qfalse;
2403 }
2404
2405 if ( keyname[0] == '}' ) {
2406 break;
2407 }
2408
2409 // parse value
2410 if ( !R_GetEntityToken( com_token, sizeof( com_token ) ) ) {
2411 ri.Printf( PRINT_ALL, "R_ParseSpawnVars: EOF without closing brace\n" );
2412 return qfalse;
2413 }
2414
2415 if ( com_token[0] == '}' ) {
2416 ri.Printf( PRINT_ALL, "R_ParseSpawnVars: closing brace without data\n" );
2417 return qfalse;
2418 }
2419
2420 if ( *numSpawnVars == MAX_SPAWN_VARS ) {
2421 ri.Printf( PRINT_ALL, "R_ParseSpawnVars: MAX_SPAWN_VARS\n" );
2422 return qfalse;
2423 }
2424
2425 keyLength = strlen(keyname) + 1;
2426 tokenLength = strlen(com_token) + 1;
2427
2428 if (numSpawnVarChars + keyLength + tokenLength > maxSpawnVarChars)
2429 {
2430 ri.Printf( PRINT_ALL, "R_ParseSpawnVars: MAX_SPAWN_VAR_CHARS\n" );
2431 return qfalse;
2432 }
2433
2434 strcpy(spawnVarChars + numSpawnVarChars, keyname);
2435 spawnVars[ *numSpawnVars ][0] = spawnVarChars + numSpawnVarChars;
2436 numSpawnVarChars += keyLength;
2437
2438 strcpy(spawnVarChars + numSpawnVarChars, com_token);
2439 spawnVars[ *numSpawnVars ][1] = spawnVarChars + numSpawnVarChars;
2440 numSpawnVarChars += tokenLength;
2441
2442 (*numSpawnVars)++;
2443 }
2444
2445 return qtrue;
2446 }
2447
2448 void R_LoadEnvironmentJson(const char *baseName)
2449 {
2450 char filename[MAX_QPATH];
2451
2452 union {
2453 char *c;
2454 void *v;
2455 } buffer;
2456 char *bufferEnd;
2457
2458 const char *cubemapArrayJson;
2459 int filelen, i;
2460
2461 Com_sprintf(filename, MAX_QPATH, "cubemaps/%s/env.json", baseName);
2462
2463 filelen = ri.FS_ReadFile(filename, &buffer.v);
2464 if (!buffer.c)
2465 return;
2466 bufferEnd = buffer.c + filelen;
2467
2468 if (JSON_ValueGetType(buffer.c, bufferEnd) != JSONTYPE_OBJECT)
2469 {
2470 ri.Printf(PRINT_ALL, "Bad %s: does not start with a object\n", filename);
2471 ri.FS_FreeFile(buffer.v);
2472 return;
2473 }
2474
2475 cubemapArrayJson = JSON_ObjectGetNamedValue(buffer.c, bufferEnd, "Cubemaps");
2476 if (!cubemapArrayJson)
2477 {
2478 ri.Printf(PRINT_ALL, "Bad %s: no Cubemaps\n", filename);
2479 ri.FS_FreeFile(buffer.v);
2480 return;
2481 }
2482
2483 if (JSON_ValueGetType(cubemapArrayJson, bufferEnd) != JSONTYPE_ARRAY)
2484 {
2485 ri.Printf(PRINT_ALL, "Bad %s: Cubemaps not an array\n", filename);
2486 ri.FS_FreeFile(buffer.v);
2487 return;
2488 }
2489
2490 tr.numCubemaps = JSON_ArrayGetIndex(cubemapArrayJson, bufferEnd, NULL, 0);
2491 tr.cubemaps = ri.Hunk_Alloc(tr.numCubemaps * sizeof(*tr.cubemaps), h_low);
2492 memset(tr.cubemaps, 0, tr.numCubemaps * sizeof(*tr.cubemaps));
2493
2494 for (i = 0; i < tr.numCubemaps; i++)
2495 {
2496 cubemap_t *cubemap = &tr.cubemaps[i];
2497 const char *cubemapJson, *keyValueJson, *indexes[3];
2498 int j;
2499
2500 cubemapJson = JSON_ArrayGetValue(cubemapArrayJson, bufferEnd, i);
2501
2502 keyValueJson = JSON_ObjectGetNamedValue(cubemapJson, bufferEnd, "Name");
2503 if (!JSON_ValueGetString(keyValueJson, bufferEnd, cubemap->name, MAX_QPATH))
2504 cubemap->name[0] = '\0';
2505
2506 keyValueJson = JSON_ObjectGetNamedValue(cubemapJson, bufferEnd, "Position");
2507 JSON_ArrayGetIndex(keyValueJson, bufferEnd, indexes, 3);
2508 for (j = 0; j < 3; j++)
2509 cubemap->origin[j] = JSON_ValueGetFloat(indexes[j], bufferEnd);
2510
2511 cubemap->parallaxRadius = 1000.0f;
2512 keyValueJson = JSON_ObjectGetNamedValue(cubemapJson, bufferEnd, "Radius");
2513 if (keyValueJson)
2514 cubemap->parallaxRadius = JSON_ValueGetFloat(keyValueJson, bufferEnd);
2515 }
2516
2517 ri.FS_FreeFile(buffer.v);
2518 }
2519
2520 void R_LoadCubemapEntities(char *cubemapEntityName)
2521 {
2522 char spawnVarChars[2048];
2523 int numSpawnVars;
2524 char *spawnVars[MAX_SPAWN_VARS][2];
2525 int numCubemaps = 0;
2526
2527 // count cubemaps
2528 numCubemaps = 0;
2529 while(R_ParseSpawnVars(spawnVarChars, sizeof(spawnVarChars), &numSpawnVars, spawnVars))
2530 {
2531 int i;
2532
2533 for (i = 0; i < numSpawnVars; i++)
2534 {
2535 if (!Q_stricmp(spawnVars[i][0], "classname") && !Q_stricmp(spawnVars[i][1], cubemapEntityName))
2536 numCubemaps++;
2537 }
2538 }
2539
2540 if (!numCubemaps)
2541 return;
2542
2543 tr.numCubemaps = numCubemaps;
2544 tr.cubemaps = ri.Hunk_Alloc(tr.numCubemaps * sizeof(*tr.cubemaps), h_low);
2545 memset(tr.cubemaps, 0, tr.numCubemaps * sizeof(*tr.cubemaps));
2546
2547 numCubemaps = 0;
2548 while(R_ParseSpawnVars(spawnVarChars, sizeof(spawnVarChars), &numSpawnVars, spawnVars))
2549 {
2550 int i;
2551 char name[MAX_QPATH];
2552 qboolean isCubemap = qfalse;
2553 qboolean originSet = qfalse;
2554 vec3_t origin;
2555 float parallaxRadius = 1000.0f;
2556
2557 name[0] = '\0';
2558 for (i = 0; i < numSpawnVars; i++)
2559 {
2560 if (!Q_stricmp(spawnVars[i][0], "classname") && !Q_stricmp(spawnVars[i][1], cubemapEntityName))
2561 isCubemap = qtrue;
2562
2563 if (!Q_stricmp(spawnVars[i][0], "name"))
2564 Q_strncpyz(name, spawnVars[i][1], MAX_QPATH);
2565
2566 if (!Q_stricmp(spawnVars[i][0], "origin"))
2567 {
2568 sscanf(spawnVars[i][1], "%f %f %f", &origin[0], &origin[1], &origin[2]);
2569 originSet = qtrue;
2570 }
2571 else if (!Q_stricmp(spawnVars[i][0], "radius"))
2572 {
2573 sscanf(spawnVars[i][1], "%f", &parallaxRadius);
2574 }
2575 }
2576
2577 if (isCubemap && originSet)
2578 {
2579 cubemap_t *cubemap = &tr.cubemaps[numCubemaps];
2580 Q_strncpyz(cubemap->name, name, MAX_QPATH);
2581 VectorCopy(origin, cubemap->origin);
2582 cubemap->parallaxRadius = parallaxRadius;
2583 numCubemaps++;
2584 }
2585 }
2586 }
2587
2588 void R_AssignCubemapsToWorldSurfaces(void)
2589 {
2590 world_t *w;
2591 int i;
2592
2593 w = &s_worldData;
2594
2595 for (i = 0; i < w->numsurfaces; i++)
2596 {
2597 msurface_t *surf = &w->surfaces[i];
2598 vec3_t surfOrigin;
2599
2600 if (surf->cullinfo.type & CULLINFO_SPHERE)
2601 {
2602 VectorCopy(surf->cullinfo.localOrigin, surfOrigin);
2603 }
2604 else if (surf->cullinfo.type & CULLINFO_BOX)
2605 {
2606 surfOrigin[0] = (surf->cullinfo.bounds[0][0] + surf->cullinfo.bounds[1][0]) * 0.5f;
2607 surfOrigin[1] = (surf->cullinfo.bounds[0][1] + surf->cullinfo.bounds[1][1]) * 0.5f;
2608 surfOrigin[2] = (surf->cullinfo.bounds[0][2] + surf->cullinfo.bounds[1][2]) * 0.5f;
2609 }
2610 else
2611 {
2612 //ri.Printf(PRINT_ALL, "surface %d has no cubemap\n", i);
2613 continue;
2614 }
2615
2616 surf->cubemapIndex = R_CubemapForPoint(surfOrigin);
2617 //ri.Printf(PRINT_ALL, "surface %d has cubemap %d\n", i, surf->cubemapIndex);
2618 }
2619 }
2620
2621
2622 void R_LoadCubemaps(void)
2623 {
2624 int i;
2625 imgFlags_t flags = IMGFLAG_CLAMPTOEDGE | IMGFLAG_MIPMAP | IMGFLAG_NOLIGHTSCALE | IMGFLAG_CUBEMAP;
2626
2627 for (i = 0; i < tr.numCubemaps; i++)
2628 {
2629 char filename[MAX_QPATH];
2630 cubemap_t *cubemap = &tr.cubemaps[i];
2631
2632 Com_sprintf(filename, MAX_QPATH, "cubemaps/%s/%03d.dds", tr.world->baseName, i);
2633
2634 cubemap->image = R_FindImageFile(filename, IMGTYPE_COLORALPHA, flags);
2635 }
2636 }
2637
2638
2639 void R_RenderMissingCubemaps(void)
2640 {
2641 int i, j;
2642 imgFlags_t flags = IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGFLAG_MIPMAP | IMGFLAG_NOLIGHTSCALE | IMGFLAG_CUBEMAP;
2643
2644 for (i = 0; i < tr.numCubemaps; i++)
2645 {
2646 if (!tr.cubemaps[i].image)
2647 {
2648 tr.cubemaps[i].image = R_CreateImage(va("*cubeMap%d", i), NULL, r_cubemapSize->integer, r_cubemapSize->integer, IMGTYPE_COLORALPHA, flags, GL_RGBA8);
2649
2650 for (j = 0; j < 6; j++)
2651 {
2652 RE_ClearScene();
2653 R_RenderCubemapSide(i, j, qfalse);
2654 R_IssuePendingRenderCommands();
2655 R_InitNextFrame();
2656 }
2657 }
2658 }
2659 }
2660
2661
2662 void R_CalcVertexLightDirs( void )
2663 {
2664 int i, k;
2665 msurface_t *surface;
2666
2667 for(k = 0, surface = &s_worldData.surfaces[0]; k < s_worldData.numsurfaces /* s_worldData.numWorldSurfaces */; k++, surface++)
2668 {
2669 srfBspSurface_t *bspSurf = (srfBspSurface_t *) surface->data;
2670
2671 switch(bspSurf->surfaceType)
2672 {
2673 case SF_FACE:
2674 case SF_GRID:
2675 case SF_TRIANGLES:
2676 for(i = 0; i < bspSurf->numVerts; i++)
2677 {
2678 vec3_t lightDir;
2679 vec3_t normal;
2680
2681 R_VaoUnpackNormal(normal, bspSurf->verts[i].normal);
2682 R_LightDirForPoint( bspSurf->verts[i].xyz, lightDir, normal, &s_worldData );
2683 R_VaoPackNormal(bspSurf->verts[i].lightdir, lightDir);
2684 }
2685
2686 break;
2687
2688 default:
2689 break;
2690 }
2691 }
2692 }
2693
2694
2695 /*
2696 =================
2697 RE_LoadWorldMap
2698
2699 Called directly from cgame
2700 =================
2701 */
2702 void RE_LoadWorldMap( const char *name ) {
2703 int i;
2704 dheader_t *header;
2705 union {
2706 byte *b;
2707 void *v;
2708 } buffer;
2709 byte *startMarker;
2710
2711 if ( tr.worldMapLoaded ) {
2712 ri.Error( ERR_DROP, "ERROR: attempted to redundantly load world map" );
2713 }
2714
2715 // set default map light scale
2716 tr.sunShadowScale = 0.5f;
2717
2718 // set default sun direction to be used if it isn't
2719 // overridden by a shader
2720 tr.sunDirection[0] = 0.45f;
2721 tr.sunDirection[1] = 0.3f;
2722 tr.sunDirection[2] = 0.9f;
2723
2724 VectorNormalize( tr.sunDirection );
2725
2726 // set default autoexposure settings
2727 tr.autoExposureMinMax[0] = -2.0f;
2728 tr.autoExposureMinMax[1] = 2.0f;
2729
2730 // set default tone mapping settings
2731 tr.toneMinAvgMaxLevel[0] = -8.0f;
2732 tr.toneMinAvgMaxLevel[1] = -2.0f;
2733 tr.toneMinAvgMaxLevel[2] = 0.0f;
2734
2735 // reset last cascade sun direction so last shadow cascade is rerendered
2736 VectorClear(tr.lastCascadeSunDirection);
2737
2738 tr.worldMapLoaded = qtrue;
2739
2740 // load it
2741 ri.FS_ReadFile( name, &buffer.v );
2742 if ( !buffer.b ) {
2743 ri.Error (ERR_DROP, "RE_LoadWorldMap: %s not found", name);
2744 }
2745
2746 // clear tr.world so if the level fails to load, the next
2747 // try will not look at the partially loaded version
2748 tr.world = NULL;
2749
2750 Com_Memset( &s_worldData, 0, sizeof( s_worldData ) );
2751 Q_strncpyz( s_worldData.name, name, sizeof( s_worldData.name ) );
2752
2753 Q_strncpyz( s_worldData.baseName, COM_SkipPath( s_worldData.name ), sizeof( s_worldData.name ) );
2754 COM_StripExtension(s_worldData.baseName, s_worldData.baseName, sizeof(s_worldData.baseName));
2755
2756 startMarker = ri.Hunk_Alloc(0, h_low);
2757 c_gridVerts = 0;
2758
2759 header = (dheader_t *)buffer.b;
2760 fileBase = (byte *)header;
2761
2762 i = LittleLong (header->version);
2763 if ( i != BSP_VERSION ) {
2764 ri.Error (ERR_DROP, "RE_LoadWorldMap: %s has wrong version number (%i should be %i)",
2765 name, i, BSP_VERSION);
2766 }
2767
2768 // swap all the lumps
2769 for (i=0 ; i<sizeof(dheader_t)/4 ; i++) {
2770 ((int *)header)[i] = LittleLong ( ((int *)header)[i]);
2771 }
2772
2773 // load into heap
2774 R_LoadEntities( &header->lumps[LUMP_ENTITIES] );
2775 R_LoadShaders( &header->lumps[LUMP_SHADERS] );
2776 R_LoadLightmaps( &header->lumps[LUMP_LIGHTMAPS], &header->lumps[LUMP_SURFACES] );
2777 R_LoadPlanes (&header->lumps[LUMP_PLANES]);
2778 R_LoadFogs( &header->lumps[LUMP_FOGS], &header->lumps[LUMP_BRUSHES], &header->lumps[LUMP_BRUSHSIDES] );
2779 R_LoadSurfaces( &header->lumps[LUMP_SURFACES], &header->lumps[LUMP_DRAWVERTS], &header->lumps[LUMP_DRAWINDEXES] );
2780 R_LoadMarksurfaces (&header->lumps[LUMP_LEAFSURFACES]);
2781 R_LoadNodesAndLeafs (&header->lumps[LUMP_NODES], &header->lumps[LUMP_LEAFS]);
2782 R_LoadSubmodels (&header->lumps[LUMP_MODELS]);
2783 R_LoadVisibility( &header->lumps[LUMP_VISIBILITY] );
2784 R_LoadLightGrid( &header->lumps[LUMP_LIGHTGRID] );
2785
2786 // determine vertex light directions
2787 R_CalcVertexLightDirs();
2788
2789 // determine which parts of the map are in sunlight
2790 if (0)
2791 {
2792 world_t *w;
2793 uint8_t *primaryLightGrid, *data;
2794 int lightGridSize;
2795 int j;
2796
2797 w = &s_worldData;
2798
2799 lightGridSize = w->lightGridBounds[0] * w->lightGridBounds[1] * w->lightGridBounds[2];
2800 primaryLightGrid = ri.Malloc(lightGridSize * sizeof(*primaryLightGrid));
2801
2802 memset(primaryLightGrid, 0, lightGridSize * sizeof(*primaryLightGrid));
2803
2804 data = w->lightGridData;
2805 for (j = 0; j < lightGridSize; j++, data += 8)
2806 {
2807 int lat, lng;
2808 vec3_t gridLightDir, gridLightCol;
2809
2810 // skip samples in wall
2811 if (!(data[0]+data[1]+data[2]+data[3]+data[4]+data[5]) )
2812 continue;
2813
2814 gridLightCol[0] = ByteToFloat(data[3]);
2815 gridLightCol[1] = ByteToFloat(data[4]);
2816 gridLightCol[2] = ByteToFloat(data[5]);
2817 (void)gridLightCol; // Suppress unused-but-set-variable warning
2818
2819 lat = data[7];
2820 lng = data[6];
2821 lat *= (FUNCTABLE_SIZE/256);
2822 lng *= (FUNCTABLE_SIZE/256);
2823
2824 // decode X as cos( lat ) * sin( long )
2825 // decode Y as sin( lat ) * sin( long )
2826 // decode Z as cos( long )
2827
2828 gridLightDir[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng];
2829 gridLightDir[1] = tr.sinTable[lat] * tr.sinTable[lng];
2830 gridLightDir[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK];
2831
2832 // FIXME: magic number for determining if light direction is close enough to sunlight
2833 if (DotProduct(gridLightDir, tr.sunDirection) > 0.75f)
2834 {
2835 primaryLightGrid[j] = 1;
2836 }
2837 else
2838 {
2839 primaryLightGrid[j] = 255;
2840 }
2841 }
2842
2843 if (0)
2844 {
2845 int k;
2846 byte *buf = ri.Malloc(w->lightGridBounds[0] * w->lightGridBounds[1] * 3 + 18);
2847 byte *out;
2848 uint8_t *in;
2849 char fileName[MAX_QPATH];
2850
2851 Com_Memset (buf, 0, 18);
2852 buf[2] = 2; // uncompressed type
2853 buf[12] = w->lightGridBounds[0] & 255;
2854 buf[13] = w->lightGridBounds[0] >> 8;
2855 buf[14] = w->lightGridBounds[1] & 255;
2856 buf[15] = w->lightGridBounds[1] >> 8;
2857 buf[16] = 24; // pixel size
2858
2859 in = primaryLightGrid;
2860 for (k = 0; k < w->lightGridBounds[2]; k++)
2861 {
2862 int l;
2863
2864 sprintf(fileName, "primarylg%d.tga", k);
2865
2866 out = buf + 18;
2867 for (l = 0; l < w->lightGridBounds[0] * w->lightGridBounds[1]; l++)
2868 {
2869 if (*in == 1)
2870 {
2871 *out++ = 255;
2872 *out++ = 255;
2873 *out++ = 255;
2874 }
2875 else if (*in == 255)
2876 {
2877 *out++ = 64;
2878 *out++ = 64;
2879 *out++ = 64;
2880 }
2881 else
2882 {
2883 *out++ = 0;
2884 *out++ = 0;
2885 *out++ = 0;
2886 }
2887 in++;
2888 }
2889
2890 ri.FS_WriteFile(fileName, buf, w->lightGridBounds[0] * w->lightGridBounds[1] * 3 + 18);
2891 }
2892
2893 ri.Free(buf);
2894 }
2895
2896 for (j = 0; j < w->numWorldSurfaces; j++)
2897 {
2898 msurface_t *surf = w->surfaces + j;
2899 cullinfo_t *ci = &surf->cullinfo;
2900
2901 if(ci->type & CULLINFO_PLANE)
2902 {
2903 if (DotProduct(ci->plane.normal, tr.sunDirection) <= 0.0f)
2904 {
2905 //ri.Printf(PRINT_ALL, "surface %d is not oriented towards sunlight\n", i);
2906 continue;
2907 }
2908 }
2909
2910 if(ci->type & CULLINFO_BOX)
2911 {
2912 int ibounds[2][3], x, y, z, goodSamples, numSamples;
2913 vec3_t lightOrigin;
2914
2915 VectorSubtract( ci->bounds[0], w->lightGridOrigin, lightOrigin );
2916
2917 ibounds[0][0] = floor(lightOrigin[0] * w->lightGridInverseSize[0]);
2918 ibounds[0][1] = floor(lightOrigin[1] * w->lightGridInverseSize[1]);
2919 ibounds[0][2] = floor(lightOrigin[2] * w->lightGridInverseSize[2]);
2920
2921 VectorSubtract( ci->bounds[1], w->lightGridOrigin, lightOrigin );
2922
2923 ibounds[1][0] = ceil(lightOrigin[0] * w->lightGridInverseSize[0]);
2924 ibounds[1][1] = ceil(lightOrigin[1] * w->lightGridInverseSize[1]);
2925 ibounds[1][2] = ceil(lightOrigin[2] * w->lightGridInverseSize[2]);
2926
2927 ibounds[0][0] = CLAMP(ibounds[0][0], 0, w->lightGridSize[0]);
2928 ibounds[0][1] = CLAMP(ibounds[0][1], 0, w->lightGridSize[1]);
2929 ibounds[0][2] = CLAMP(ibounds[0][2], 0, w->lightGridSize[2]);
2930
2931 ibounds[1][0] = CLAMP(ibounds[1][0], 0, w->lightGridSize[0]);
2932 ibounds[1][1] = CLAMP(ibounds[1][1], 0, w->lightGridSize[1]);
2933 ibounds[1][2] = CLAMP(ibounds[1][2], 0, w->lightGridSize[2]);
2934
2935 /*
2936 ri.Printf(PRINT_ALL, "surf %d bounds (%f %f %f)-(%f %f %f) ibounds (%d %d %d)-(%d %d %d)\n", i,
2937 ci->bounds[0][0], ci->bounds[0][1], ci->bounds[0][2],
2938 ci->bounds[1][0], ci->bounds[1][1], ci->bounds[1][2],
2939 ibounds[0][0], ibounds[0][1], ibounds[0][2],
2940 ibounds[1][0], ibounds[1][1], ibounds[1][2]);
2941 */
2942
2943 goodSamples = 0;
2944 numSamples = 0;
2945 for (x = ibounds[0][0]; x <= ibounds[1][0]; x++)
2946 {
2947 for (y = ibounds[0][1]; y <= ibounds[1][1]; y++)
2948 {
2949 for (z = ibounds[0][2]; z <= ibounds[1][2]; z++)
2950 {
2951 uint8_t primaryLight = primaryLightGrid[x * 8 + y * 8 * w->lightGridBounds[0] + z * 8 * w->lightGridBounds[0] * w->lightGridBounds[2]];
2952
2953 if (primaryLight == 0)
2954 continue;
2955
2956 numSamples++;
2957
2958 if (primaryLight == 1)
2959 goodSamples++;
2960 }
2961 }
2962 }
2963
2964 // FIXME: magic number for determining whether object is mostly in sunlight
2965 if (goodSamples > numSamples * 0.75f)
2966 {
2967 //ri.Printf(PRINT_ALL, "surface %d is in sunlight\n", i);
2968 //surf->primaryLight = 1;
2969 }
2970 }
2971 }
2972
2973 ri.Free(primaryLightGrid);
2974 }
2975
2976 // load cubemaps
2977 if (r_cubeMapping->integer)
2978 {
2979 // Try loading an env.json file first
2980 R_LoadEnvironmentJson(s_worldData.baseName);
2981
2982 if (!tr.numCubemaps)
2983 {
2984 R_LoadCubemapEntities("misc_cubemap");
2985 }
2986
2987 if (!tr.numCubemaps)
2988 {
2989 // use deathmatch spawn points as cubemaps
2990 R_LoadCubemapEntities("info_player_deathmatch");
2991 }
2992
2993 if (tr.numCubemaps)
2994 {
2995 R_AssignCubemapsToWorldSurfaces();
2996 }
2997 }
2998
2999 s_worldData.dataSize = (byte *)ri.Hunk_Alloc(0, h_low) - startMarker;
3000
3001 // only set tr.world now that we know the entire level has loaded properly
3002 tr.world = &s_worldData;
3003
3004 // make sure the VAO glState entry is safe
3005 R_BindNullVao();
3006
3007 // Render or load all cubemaps
3008 if (r_cubeMapping->integer && tr.numCubemaps && glRefConfig.framebufferObject)
3009 {
3010 R_LoadCubemaps();
3011 R_RenderMissingCubemaps();
3012 }
3013
3014 ri.FS_FreeFile( buffer.v );
3015 }