merge branch work back into trunk
[xonotic/netradiant.git] / tools / quake3 / q3map2 / writebsp.c
1 /* -------------------------------------------------------------------------------
2
3 Copyright (C) 1999-2007 id Software, Inc. and contributors.
4 For a list of contributors, see the accompanying CONTRIBUTORS file.
5
6 This file is part of GtkRadiant.
7
8 GtkRadiant is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 GtkRadiant is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GtkRadiant; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21
22 ----------------------------------------------------------------------------------
23
24 This code has been altered significantly from its original form, to support
25 several games based on the Quake III Arena engine, in the form of "Q3Map2."
26
27 ------------------------------------------------------------------------------- */
28
29
30
31 /* marker */
32 #define WRITEBSP_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 /*
42 EmitShader()
43 emits a bsp shader entry
44 */
45
46 int     EmitShader( const char *shader, int *contentFlags, int *surfaceFlags )
47 {
48         int                             i;
49         shaderInfo_t    *si;
50         
51         
52         /* handle special cases */
53         if( shader == NULL )
54                 shader = "noshader";
55         
56         /* try to find an existing shader */
57         for( i = 0; i < numBSPShaders; i++ )
58         {
59                 /* ydnar: handle custom surface/content flags */
60                 if( surfaceFlags != NULL && bspShaders[ i ].surfaceFlags != *surfaceFlags )
61                         continue;
62                 if( contentFlags != NULL && bspShaders[ i ].contentFlags != *contentFlags )
63                         continue;
64                 
65                 /* compare name */
66                 if( !Q_stricmp( shader, bspShaders[ i ].shader ) )
67                         return i;
68         }
69         
70         /* get shaderinfo */
71         si = ShaderInfoForShader( shader );
72         
73         /* emit a new shader */
74         if( i == MAX_MAP_SHADERS )
75                 Error( "MAX_MAP_SHADERS" );
76         numBSPShaders++;
77         strcpy( bspShaders[ i ].shader, shader );
78         bspShaders[ i ].surfaceFlags = si->surfaceFlags;
79         bspShaders[ i ].contentFlags = si->contentFlags;
80         
81         /* handle custom content/surface flags */
82         if( surfaceFlags != NULL )
83                 bspShaders[ i ].surfaceFlags = *surfaceFlags;
84         if( contentFlags != NULL )
85                 bspShaders[ i ].contentFlags = *contentFlags;
86         
87         /* recursively emit any damage shaders */
88         if( si->damageShader != NULL && si->damageShader[ 0 ] != '\0' )
89         {
90                 Sys_FPrintf( SYS_VRB, "Shader %s has damage shader %s\n", si->shader, si->damageShader );
91                 EmitShader( si->damageShader, NULL, NULL );
92         }
93         
94         /* return it */
95         return i;
96 }
97
98
99
100 /*
101 EmitPlanes()
102 there is no oportunity to discard planes, because all of the original
103 brushes will be saved in the map
104 */
105
106 void EmitPlanes( void )
107 {
108         int                     i;
109         bspPlane_t      *bp;
110         plane_t         *mp;
111         
112         
113         /* walk plane list */
114         mp = mapplanes;
115         for( i = 0; i < nummapplanes; i++, mp++ )
116         {
117                 bp = &bspPlanes[ numBSPPlanes ];
118                 VectorCopy( mp->normal, bp->normal );
119                 bp->dist = mp->dist;
120                 numBSPPlanes++;
121         }
122         
123         /* emit some statistics */
124         Sys_FPrintf( SYS_VRB, "%9d BSP planes\n", numBSPPlanes );
125 }
126
127
128
129 /*
130 EmitLeaf()
131 emits a leafnode to the bsp file
132 */
133
134 void EmitLeaf( node_t *node )
135 {
136         bspLeaf_t               *leaf_p;
137         brush_t                 *b;
138         drawSurfRef_t   *dsr;
139
140         
141         /* check limits */
142         if( numBSPLeafs >= MAX_MAP_LEAFS )
143                 Error( "MAX_MAP_LEAFS" );
144
145         leaf_p = &bspLeafs[numBSPLeafs];
146         numBSPLeafs++;
147
148         leaf_p->cluster = node->cluster;
149         leaf_p->area = node->area;
150
151         /* emit bounding box */
152         VectorCopy( node->mins, leaf_p->mins );
153         VectorCopy( node->maxs, leaf_p->maxs );
154         
155         /* emit leaf brushes */
156         leaf_p->firstBSPLeafBrush = numBSPLeafBrushes;
157         for( b = node->brushlist; b; b = b->next )
158         {
159                 /* something is corrupting brushes */
160                 if( (size_t) b < 256 )
161                 {
162                         Sys_Printf( "WARNING: Node brush list corrupted (0x%08X)\n", b );
163                         break;
164                 }
165                 //%     if( b->guard != 0xDEADBEEF )
166                 //%             Sys_Printf( "Brush %6d: 0x%08X Guard: 0x%08X Next: 0x%08X Original: 0x%08X Sides: %d\n", b->brushNum, b, b, b->next, b->original, b->numsides );
167                 
168                 if( numBSPLeafBrushes >= MAX_MAP_LEAFBRUSHES )
169                         Error( "MAX_MAP_LEAFBRUSHES" );
170                 bspLeafBrushes[ numBSPLeafBrushes ] = b->original->outputNum;
171                 numBSPLeafBrushes++;
172         }
173         
174         leaf_p->numBSPLeafBrushes = numBSPLeafBrushes - leaf_p->firstBSPLeafBrush;
175         
176         /* emit leaf surfaces */
177         if( node->opaque )
178                 return;
179         
180         /* add the drawSurfRef_t drawsurfs */
181         leaf_p->firstBSPLeafSurface = numBSPLeafSurfaces;
182         for ( dsr = node->drawSurfReferences; dsr; dsr = dsr->nextRef )
183         {
184                 if( numBSPLeafSurfaces >= MAX_MAP_LEAFFACES )
185                         Error( "MAX_MAP_LEAFFACES" );
186                 bspLeafSurfaces[ numBSPLeafSurfaces ] = dsr->outputNum;
187                 numBSPLeafSurfaces++;                   
188         }
189         
190         leaf_p->numBSPLeafSurfaces = numBSPLeafSurfaces - leaf_p->firstBSPLeafSurface;
191 }
192
193
194 /*
195 EmitDrawNode_r()
196 recursively emit the bsp nodes
197 */
198
199 int EmitDrawNode_r( node_t *node )
200 {
201         bspNode_t       *n;
202         int                     i;
203         
204         
205         /* check for leafnode */
206         if( node->planenum == PLANENUM_LEAF )
207         {
208                 EmitLeaf( node );
209                 return -numBSPLeafs;
210         }
211         
212         /* emit a node */
213         if( numBSPNodes == MAX_MAP_NODES )
214                 Error( "MAX_MAP_NODES" );
215         n = &bspNodes[ numBSPNodes ];
216         numBSPNodes++;
217         
218         VectorCopy (node->mins, n->mins);
219         VectorCopy (node->maxs, n->maxs);
220
221         if (node->planenum & 1)
222                 Error ("WriteDrawNodes_r: odd planenum");
223         n->planeNum = node->planenum;
224
225         //
226         // recursively output the other nodes
227         //      
228         for (i=0 ; i<2 ; i++)
229         {
230                 if (node->children[i]->planenum == PLANENUM_LEAF)
231                 {
232                         n->children[i] = -(numBSPLeafs + 1);
233                         EmitLeaf (node->children[i]);
234                 }
235                 else
236                 {
237                         n->children[i] = numBSPNodes;   
238                         EmitDrawNode_r (node->children[i]);
239                 }
240         }
241
242         return n - bspNodes;
243 }
244
245
246
247 /*
248 ============
249 SetModelNumbers
250 ============
251 */
252 void SetModelNumbers (void)
253 {
254         int             i;
255         int             models;
256         char    value[10];
257
258         models = 1;
259         for ( i=1 ; i<numEntities ; i++ ) {
260                 if ( entities[i].brushes || entities[i].patches ) {
261                         sprintf ( value, "*%i", models );
262                         models++;
263                         SetKeyValue (&entities[i], "model", value);
264                 }
265         }
266
267 }
268
269
270
271
272 /*
273 SetLightStyles()
274 sets style keys for entity lights
275 */
276
277 void SetLightStyles( void )
278 {
279         int                     i, j, style, numStyles;
280         qboolean        keepLights;
281         const char      *t;
282         entity_t        *e;
283         epair_t         *ep, *next;
284         char            value[ 10 ];
285         char            lightTargets[ MAX_SWITCHED_LIGHTS ][ 64 ];
286         int                     lightStyles[ MAX_SWITCHED_LIGHTS ];
287         
288         
289         /* ydnar: determine if we keep lights in the bsp */
290         t = ValueForKey( &entities[ 0 ], "_keepLights" );
291         keepLights = (t[ 0 ] == '1') ? qtrue : qfalse;
292         
293         /* any light that is controlled (has a targetname) must have a unique style number generated for it */
294         numStyles = 0;
295         for( i = 1; i < numEntities; i++ )
296         {
297                 e = &entities[ i ];
298
299                 t = ValueForKey( e, "classname" );
300                 if( Q_strncasecmp( t, "light", 5 ) )
301                         continue;
302                 t = ValueForKey( e, "targetname" );
303                 if( t[ 0 ] == '\0' )
304                 {
305                         /* ydnar: strip the light from the BSP file */
306                         if( keepLights == qfalse )
307                         {
308                                 ep = e->epairs;
309                                 while( ep != NULL )
310                                 {
311                                         next = ep->next;
312                                         free( ep->key );
313                                         free( ep->value );
314                                         free( ep );
315                                         ep = next;
316                                 }
317                                 e->epairs = NULL;
318                                 numStrippedLights++;
319                         }
320                         
321                         /* next light */
322                         continue;
323                 }
324                 
325                 /* get existing style */
326                 style = IntForKey( e, "style" );
327                 if( style < LS_NORMAL || style > LS_NONE )
328                         Error( "Invalid lightstyle (%d) on entity %d", style, i );
329                 
330                 /* find this targetname */
331                 for( j = 0; j < numStyles; j++ )
332                         if( lightStyles[ j ] == style && !strcmp( lightTargets[ j ], t ) )
333                                 break;
334                 
335                 /* add a new style */
336                 if( j >= numStyles )
337                 {
338                         if( numStyles == MAX_SWITCHED_LIGHTS )
339                                 Error( "MAX_SWITCHED_LIGHTS (%d) exceeded, reduce the number of lights with targetnames", MAX_SWITCHED_LIGHTS );
340                         strcpy( lightTargets[ j ], t );
341                         lightStyles[ j ] = style;
342                         numStyles++;
343                 }
344                 
345                 /* set explicit style */
346                 sprintf( value, "%d", 32 + j );
347                 SetKeyValue( e, "style", value );
348                 
349                 /* set old style */
350                 if( style != LS_NORMAL )
351                 {
352                         sprintf( value, "%d", style );
353                         SetKeyValue( e, "switch_style", value );
354                 }
355         }
356         
357         /* emit some statistics */
358         Sys_FPrintf( SYS_VRB, "%9d light entities stripped\n", numStrippedLights );
359 }
360
361
362
363 /*
364 BeginBSPFile()
365 starts a new bsp file
366 */
367
368 void BeginBSPFile( void )
369 {
370         /* these values may actually be initialized if the file existed when loaded, so clear them explicitly */
371         numBSPModels = 0;
372         numBSPNodes = 0;
373         numBSPBrushSides = 0;
374         numBSPLeafSurfaces = 0;
375         numBSPLeafBrushes = 0;
376         
377         /* leave leaf 0 as an error, because leafs are referenced as negative number nodes */
378         numBSPLeafs = 1;
379         
380         
381         /* ydnar: gs mods: set the first 6 drawindexes to 0 1 2 2 1 3 for triangles and quads */
382         numBSPDrawIndexes = 6;
383         bspDrawIndexes[ 0 ] = 0;
384         bspDrawIndexes[ 1 ] = 1;
385         bspDrawIndexes[ 2 ] = 2;
386         bspDrawIndexes[ 3 ] = 0;
387         bspDrawIndexes[ 4 ] = 2;
388         bspDrawIndexes[ 5 ] = 3;
389 }
390
391
392
393 /*
394 EndBSPFile()
395 finishes a new bsp and writes to disk
396 */
397
398 void EndBSPFile( void )
399 {
400         char    path[ 1024 ];
401         
402
403         Sys_FPrintf( SYS_VRB, "--- EndBSPFile ---\n" );
404
405         EmitPlanes();
406         
407         numBSPEntities = numEntities;
408         UnparseEntities();
409         
410         /* write the surface extra file */
411         WriteSurfaceExtraFile( source );
412         
413         /* write the bsp */
414         sprintf( path, "%s.bsp", source );
415         Sys_Printf( "Writing %s\n", path );
416         WriteBSPFile( path );
417 }
418
419
420
421 /*
422 EmitBrushes()
423 writes the brush list to the bsp
424 */
425
426 void EmitBrushes( brush_t *brushes, int *firstBrush, int *numBrushes )
427 {
428         int                             j;
429         brush_t                 *b;
430         bspBrush_t              *db;
431         bspBrushSide_t  *cp;
432         
433         
434         /* set initial brush */
435         if( firstBrush != NULL )
436                 *firstBrush = numBSPBrushes;
437         if( numBrushes != NULL )
438                 *numBrushes = 0;
439         
440         /* walk list of brushes */
441         for( b = brushes; b != NULL; b = b->next )
442         {
443                 /* check limits */
444                 if( numBSPBrushes == MAX_MAP_BRUSHES )
445                         Error( "MAX_MAP_BRUSHES (%d)", numBSPBrushes );
446                 
447                 /* get bsp brush */
448                 b->outputNum = numBSPBrushes;
449                 db = &bspBrushes[ numBSPBrushes ];
450                 numBSPBrushes++;
451                 if( numBrushes != NULL )
452                         (*numBrushes)++;
453                 
454                 db->shaderNum = EmitShader( b->contentShader->shader, &b->contentShader->contentFlags, &b->contentShader->surfaceFlags );
455                 db->firstSide = numBSPBrushSides;
456                 
457                 /* walk sides */
458                 db->numSides = 0;
459                 for( j = 0; j < b->numsides; j++ )
460                 {
461                         /* set output number to bogus initially */
462                         b->sides[ j ].outputNum = -1;
463                         
464                         /* check count */
465                         if( numBSPBrushSides == MAX_MAP_BRUSHSIDES )
466                                 Error( "MAX_MAP_BRUSHSIDES ");
467                         
468                         /* emit side */
469                         b->sides[ j ].outputNum = numBSPBrushSides;
470                         cp = &bspBrushSides[ numBSPBrushSides ];
471                         db->numSides++;
472                         numBSPBrushSides++;
473                         cp->planeNum = b->sides[ j ].planenum;
474                         
475                         /* emit shader */
476                         if( b->sides[ j ].shaderInfo )
477                                 cp->shaderNum = EmitShader( b->sides[ j ].shaderInfo->shader, &b->sides[ j ].shaderInfo->contentFlags, &b->sides[ j ].shaderInfo->surfaceFlags );
478                         else
479                                 cp->shaderNum = EmitShader( NULL, NULL, NULL );
480                 }
481         }
482 }
483
484
485
486 /*
487 EmitFogs() - ydnar
488 turns map fogs into bsp fogs
489 */
490
491 void EmitFogs( void )
492 {
493         int                     i, j;
494         
495         
496         /* setup */
497         numBSPFogs = numMapFogs;
498         
499         /* walk list */
500         for( i = 0; i < numMapFogs; i++ )
501         {
502                 /* set shader */
503                 strcpy( bspFogs[ i ].shader, mapFogs[ i ].si->shader );
504                 
505                 /* global fog doesn't have an associated brush */
506                 if( mapFogs[ i ].brush == NULL )
507                 {
508                         bspFogs[ i ].brushNum = -1;
509                         bspFogs[ i ].visibleSide = -1;
510                 }
511                 else
512                 {
513                         /* set brush */
514                         bspFogs[ i ].brushNum = mapFogs[ i ].brush->outputNum;
515                         
516                         /* try to use forced visible side */
517                         if( mapFogs[ i ].visibleSide >= 0 )
518                         {
519                                 bspFogs[ i ].visibleSide = mapFogs[ i ].visibleSide;
520                                 continue;
521                         }
522                         
523                         /* find visible side */
524                         for( j = 0; j < 6; j++ )
525                         {
526                                 if( mapFogs[ i ].brush->sides[ j ].visibleHull != NULL )
527                                 {
528                                         Sys_Printf( "Fog %d has visible side %d\n", i, j );
529                                         bspFogs[ i ].visibleSide = j;
530                                         break;
531                                 }
532                         }
533                 }
534         }
535 }
536
537
538
539 /*
540 BeginModel()
541 sets up a new brush model
542 */
543
544 void BeginModel( void )
545 {
546         bspModel_t      *mod;
547         brush_t         *b;
548         entity_t        *e;
549         vec3_t          mins, maxs;
550         vec3_t          lgMins, lgMaxs;         /* ydnar: lightgrid mins/maxs */
551         parseMesh_t     *p;
552         int                     i;
553         
554         
555         /* test limits */
556         if( numBSPModels == MAX_MAP_MODELS )
557                 Error( "MAX_MAP_MODELS" );
558         
559         /* get model and entity */
560         mod = &bspModels[ numBSPModels ];
561         e = &entities[ mapEntityNum ];
562         
563         /* ydnar: lightgrid mins/maxs */
564         ClearBounds( lgMins, lgMaxs );
565         
566         /* bound the brushes */
567         ClearBounds( mins, maxs );
568         for ( b = e->brushes; b; b = b->next )
569         {
570                 /* ignore non-real brushes (origin, etc) */
571                 if( b->numsides == 0 )
572                         continue;
573                 AddPointToBounds( b->mins, mins, maxs );
574                 AddPointToBounds( b->maxs, mins, maxs );
575                 
576                 /* ydnar: lightgrid bounds */
577                 if( b->compileFlags & C_LIGHTGRID )
578                 {
579                         AddPointToBounds( b->mins, lgMins, lgMaxs );
580                         AddPointToBounds( b->maxs, lgMins, lgMaxs );
581                 }
582         }
583         
584         /* bound patches */
585         for( p = e->patches; p; p = p->next )
586         {
587                 for( i = 0; i < (p->mesh.width * p->mesh.height); i++ )
588                         AddPointToBounds( p->mesh.verts[i].xyz, mins, maxs );
589         }
590         
591         /* ydnar: lightgrid mins/maxs */
592         if( lgMins[ 0 ] < 99999 )
593         {
594                 /* use lightgrid bounds */
595                 VectorCopy( lgMins, mod->mins );
596                 VectorCopy( lgMaxs, mod->maxs );
597         }
598         else
599         {
600                 /* use brush/patch bounds */
601                 VectorCopy( mins, mod->mins );
602                 VectorCopy( maxs, mod->maxs );
603         }
604         
605         /* note size */
606         Sys_FPrintf( SYS_VRB, "BSP bounds: { %f %f %f } { %f %f %f }\n", mins[ 0 ], mins[ 1 ], mins[ 2 ], maxs[ 0 ], maxs[ 1 ], maxs[ 2 ] );
607         Sys_FPrintf( SYS_VRB, "Lightgrid bounds: { %f %f %f } { %f %f %f }\n", lgMins[ 0 ], lgMins[ 1 ], lgMins[ 2 ], lgMaxs[ 0 ], lgMaxs[ 1 ], lgMaxs[ 2 ] );
608         
609         /* set firsts */
610         mod->firstBSPSurface = numBSPDrawSurfaces;
611         mod->firstBSPBrush = numBSPBrushes;
612 }
613
614
615
616
617 /*
618 EndModel()
619 finish a model's processing
620 */
621
622 void EndModel( entity_t *e, node_t *headnode )
623 {
624         bspModel_t      *mod;
625         
626         
627         /* note it */
628         Sys_FPrintf( SYS_VRB, "--- EndModel ---\n" );
629         
630         /* emit the bsp */
631         mod = &bspModels[ numBSPModels ];
632         EmitDrawNode_r( headnode );
633         
634         /* set surfaces and brushes */
635         mod->numBSPSurfaces = numBSPDrawSurfaces - mod->firstBSPSurface;
636         mod->firstBSPBrush = e->firstBrush;
637         mod->numBSPBrushes = e->numBrushes;
638         
639         /* increment model count */
640         numBSPModels++;
641 }
642
643
644