fdeca2c2de88d531e7d31be2a663f52b0b8fc7cc
[xonotic/netradiant.git] / tools / quake3 / q3map2 / writebsp.c
1 /* -------------------------------------------------------------------------------
2
3 Copyright (C) 1999-2006 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         int                             i = 0;
140
141         
142         /* check limits */
143         if( numBSPLeafs >= MAX_MAP_LEAFS )
144                 Error( "MAX_MAP_LEAFS" );
145
146         leaf_p = &bspLeafs[numBSPLeafs];
147         numBSPLeafs++;
148
149         leaf_p->cluster = node->cluster;
150         leaf_p->area = node->area;
151
152         /* emit bounding box */
153         VectorCopy( node->mins, leaf_p->mins );
154         VectorCopy( node->maxs, leaf_p->maxs );
155         
156         /* emit leaf brushes */
157         leaf_p->firstBSPLeafBrush = numBSPLeafBrushes;
158         for( b = node->brushlist; b; b = b->next )
159         {
160                 /* something is corrupting brushes */
161                 if( (int) b < 256 )
162                 {
163                         Sys_Printf( "WARNING: Node brush list corrupted (0x%08X)\n", b );
164                         break;
165                 }
166                 //%     if( b->guard != 0xDEADBEEF )
167                 //%             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 );
168                 
169                 if( numBSPLeafBrushes >= MAX_MAP_LEAFBRUSHES )
170                         Error( "MAX_MAP_LEAFBRUSHES" );
171                 bspLeafBrushes[ numBSPLeafBrushes ] = b->original->outputNum;
172                 numBSPLeafBrushes++;
173         }
174         
175         leaf_p->numBSPLeafBrushes = numBSPLeafBrushes - leaf_p->firstBSPLeafBrush;
176         
177         /* emit leaf surfaces */
178         if( node->opaque )
179                 return;
180         
181         /* add the drawSurfRef_t drawsurfs */
182         leaf_p->firstBSPLeafSurface = numBSPLeafSurfaces;
183         for ( dsr = node->drawSurfReferences; dsr; dsr = dsr->nextRef )
184         {
185                 if( numBSPLeafSurfaces >= MAX_MAP_LEAFFACES )
186                         Error( "MAX_MAP_LEAFFACES" );
187                 bspLeafSurfaces[ numBSPLeafSurfaces ] = dsr->outputNum;
188                 numBSPLeafSurfaces++;                   
189         }
190         
191         leaf_p->numBSPLeafSurfaces = numBSPLeafSurfaces - leaf_p->firstBSPLeafSurface;
192 }
193
194
195 /*
196 EmitDrawNode_r()
197 recursively emit the bsp nodes
198 */
199
200 int EmitDrawNode_r( node_t *node )
201 {
202         bspNode_t       *n;
203         int                     i;
204         
205         
206         /* check for leafnode */
207         if( node->planenum == PLANENUM_LEAF )
208         {
209                 EmitLeaf( node );
210                 return -numBSPLeafs;
211         }
212         
213         /* emit a node */
214         if( numBSPNodes == MAX_MAP_NODES )
215                 Error( "MAX_MAP_NODES" );
216         n = &bspNodes[ numBSPNodes ];
217         numBSPNodes++;
218         
219         VectorCopy (node->mins, n->mins);
220         VectorCopy (node->maxs, n->maxs);
221
222         if (node->planenum & 1)
223                 Error ("WriteDrawNodes_r: odd planenum");
224         n->planeNum = node->planenum;
225
226         //
227         // recursively output the other nodes
228         //      
229         for (i=0 ; i<2 ; i++)
230         {
231                 if (node->children[i]->planenum == PLANENUM_LEAF)
232                 {
233                         n->children[i] = -(numBSPLeafs + 1);
234                         EmitLeaf (node->children[i]);
235                 }
236                 else
237                 {
238                         n->children[i] = numBSPNodes;   
239                         EmitDrawNode_r (node->children[i]);
240                 }
241         }
242
243         return n - bspNodes;
244 }
245
246
247
248 /*
249 ============
250 SetModelNumbers
251 ============
252 */
253 void SetModelNumbers (void)
254 {
255         int             i;
256         int             models;
257         char    value[10];
258
259         models = 1;
260         for ( i=1 ; i<numEntities ; i++ ) {
261                 if ( entities[i].brushes || entities[i].patches ) {
262                         sprintf ( value, "*%i", models );
263                         models++;
264                         SetKeyValue (&entities[i], "model", value);
265                 }
266         }
267
268 }
269
270
271
272
273 /*
274 SetLightStyles()
275 sets style keys for entity lights
276 */
277
278 void SetLightStyles( void )
279 {
280         int                     i, j, style, numStyles;
281         qboolean        keepLights;
282         const char      *t;
283         entity_t        *e;
284         epair_t         *ep, *next;
285         char            value[ 10 ];
286         char            lightTargets[ MAX_SWITCHED_LIGHTS ][ 64 ];
287         int                     lightStyles[ MAX_SWITCHED_LIGHTS ];
288         
289         
290         /* ydnar: determine if we keep lights in the bsp */
291         t = ValueForKey( &entities[ 0 ], "_keepLights" );
292         keepLights = (t[ 0 ] == '1') ? qtrue : qfalse;
293         
294         /* any light that is controlled (has a targetname) must have a unique style number generated for it */
295         numStyles = 0;
296         for( i = 1; i < numEntities; i++ )
297         {
298                 e = &entities[ i ];
299
300                 t = ValueForKey( e, "classname" );
301                 if( Q_strncasecmp( t, "light", 5 ) )
302                         continue;
303                 t = ValueForKey( e, "targetname" );
304                 if( t[ 0 ] == '\0' )
305                 {
306                         /* ydnar: strip the light from the BSP file */
307                         if( keepLights == qfalse )
308                         {
309                                 ep = e->epairs;
310                                 while( ep != NULL )
311                                 {
312                                         next = ep->next;
313                                         free( ep->key );
314                                         free( ep->value );
315                                         free( ep );
316                                         ep = next;
317                                 }
318                                 e->epairs = NULL;
319                                 numStrippedLights++;
320                         }
321                         
322                         /* next light */
323                         continue;
324                 }
325                 
326                 /* get existing style */
327                 style = IntForKey( e, "style" );
328                 if( style < LS_NORMAL || style > LS_NONE )
329                         Error( "Invalid lightstyle (%d) on entity %d", style, i );
330                 
331                 /* find this targetname */
332                 for( j = 0; j < numStyles; j++ )
333                         if( lightStyles[ j ] == style && !strcmp( lightTargets[ j ], t ) )
334                                 break;
335                 
336                 /* add a new style */
337                 if( j >= numStyles )
338                 {
339                         if( numStyles == MAX_SWITCHED_LIGHTS )
340                                 Error( "MAX_SWITCHED_LIGHTS (%d) exceeded, reduce the number of lights with targetnames", MAX_SWITCHED_LIGHTS );
341                         strcpy( lightTargets[ j ], t );
342                         lightStyles[ j ] = style;
343                         numStyles++;
344                 }
345                 
346                 /* set explicit style */
347                 sprintf( value, "%d", 32 + j );
348                 SetKeyValue( e, "style", value );
349                 
350                 /* set old style */
351                 if( style != LS_NORMAL )
352                 {
353                         sprintf( value, "%d", style );
354                         SetKeyValue( e, "switch_style", value );
355                 }
356         }
357         
358         /* emit some statistics */
359         Sys_FPrintf( SYS_VRB, "%9d light entities stripped\n", numStrippedLights );
360 }
361
362
363
364 /*
365 BeginBSPFile()
366 starts a new bsp file
367 */
368
369 void BeginBSPFile( void )
370 {
371         /* these values may actually be initialized if the file existed when loaded, so clear them explicitly */
372         numBSPModels = 0;
373         numBSPNodes = 0;
374         numBSPBrushSides = 0;
375         numBSPLeafSurfaces = 0;
376         numBSPLeafBrushes = 0;
377         
378         /* leave leaf 0 as an error, because leafs are referenced as negative number nodes */
379         numBSPLeafs = 1;
380         
381         
382         /* ydnar: gs mods: set the first 6 drawindexes to 0 1 2 2 1 3 for triangles and quads */
383         numBSPDrawIndexes = 6;
384         bspDrawIndexes[ 0 ] = 0;
385         bspDrawIndexes[ 1 ] = 1;
386         bspDrawIndexes[ 2 ] = 2;
387         bspDrawIndexes[ 3 ] = 0;
388         bspDrawIndexes[ 4 ] = 2;
389         bspDrawIndexes[ 5 ] = 3;
390 }
391
392
393
394 /*
395 EndBSPFile()
396 finishes a new bsp and writes to disk
397 */
398
399 void EndBSPFile( void )
400 {
401         char    path[ 1024 ];
402         
403
404         EmitPlanes();
405         
406         numBSPEntities = numEntities;
407         UnparseEntities();
408         
409         /* write the surface extra file */
410         WriteSurfaceExtraFile( source );
411         
412         /* write the bsp */
413         sprintf( path, "%s.bsp", source );
414         Sys_Printf( "Writing %s\n", path );
415         WriteBSPFile( path );
416 }
417
418
419
420 /*
421 EmitBrushes()
422 writes the brush list to the bsp
423 */
424
425 void EmitBrushes( brush_t *brushes, int *firstBrush, int *numBrushes )
426 {
427         int                             j;
428         brush_t                 *b;
429         bspBrush_t              *db;
430         bspBrushSide_t  *cp;
431         
432         
433         /* set initial brush */
434         if( firstBrush != NULL )
435                 *firstBrush = numBSPBrushes;
436         if( numBrushes != NULL )
437                 *numBrushes = 0;
438         
439         /* walk list of brushes */
440         for( b = brushes; b != NULL; b = b->next )
441         {
442                 /* check limits */
443                 if( numBSPBrushes == MAX_MAP_BRUSHES )
444                         Error( "MAX_MAP_BRUSHES (%d)", numBSPBrushes );
445                 
446                 /* get bsp brush */
447                 b->outputNum = numBSPBrushes;
448                 db = &bspBrushes[ numBSPBrushes ];
449                 numBSPBrushes++;
450                 if( numBrushes != NULL )
451                         (*numBrushes)++;
452                 
453                 db->shaderNum = EmitShader( b->contentShader->shader, &b->contentShader->contentFlags, &b->contentShader->surfaceFlags );
454                 db->firstSide = numBSPBrushSides;
455                 
456                 /* walk sides */
457                 db->numSides = 0;
458                 for( j = 0; j < b->numsides; j++ )
459                 {
460                         /* set output number to bogus initially */
461                         b->sides[ j ].outputNum = -1;
462                         
463                         /* check count */
464                         if( numBSPBrushSides == MAX_MAP_BRUSHSIDES )
465                                 Error( "MAX_MAP_BRUSHSIDES ");
466                         
467                         /* emit side */
468                         b->sides[ j ].outputNum = numBSPBrushSides;
469                         cp = &bspBrushSides[ numBSPBrushSides ];
470                         db->numSides++;
471                         numBSPBrushSides++;
472                         cp->planeNum = b->sides[ j ].planenum;
473                         
474                         /* emit shader */
475                         if( b->sides[ j ].shaderInfo )
476                                 cp->shaderNum = EmitShader( b->sides[ j ].shaderInfo->shader, &b->sides[ j ].shaderInfo->contentFlags, &b->sides[ j ].shaderInfo->surfaceFlags );
477                         else
478                                 cp->shaderNum = EmitShader( NULL, NULL, NULL );
479                 }
480         }
481 }
482
483
484
485 /*
486 EmitFogs() - ydnar
487 turns map fogs into bsp fogs
488 */
489
490 void EmitFogs( void )
491 {
492         int                     i, j;
493         
494         
495         /* setup */
496         numBSPFogs = numMapFogs;
497         
498         /* walk list */
499         for( i = 0; i < numMapFogs; i++ )
500         {
501                 /* set shader */
502                 strcpy( bspFogs[ i ].shader, mapFogs[ i ].si->shader );
503                 
504                 /* global fog doesn't have an associated brush */
505                 if( mapFogs[ i ].brush == NULL )
506                 {
507                         bspFogs[ i ].brushNum = -1;
508                         bspFogs[ i ].visibleSide = -1;
509                 }
510                 else
511                 {
512                         /* set brush */
513                         bspFogs[ i ].brushNum = mapFogs[ i ].brush->outputNum;
514                         
515                         /* try to use forced visible side */
516                         if( mapFogs[ i ].visibleSide >= 0 )
517                         {
518                                 bspFogs[ i ].visibleSide = mapFogs[ i ].visibleSide;
519                                 continue;
520                         }
521                         
522                         /* find visible side */
523                         for( j = 0; j < 6; j++ )
524                         {
525                                 if( mapFogs[ i ].brush->sides[ j ].visibleHull != NULL )
526                                 {
527                                         Sys_Printf( "Fog %d has visible side %d\n", i, j );
528                                         bspFogs[ i ].visibleSide = j;
529                                         break;
530                                 }
531                         }
532                 }
533         }
534 }
535
536
537
538 /*
539 BeginModel()
540 sets up a new brush model
541 */
542
543 void BeginModel( void )
544 {
545         bspModel_t      *mod;
546         brush_t         *b;
547         entity_t        *e;
548         vec3_t          mins, maxs;
549         vec3_t          lgMins, lgMaxs;         /* ydnar: lightgrid mins/maxs */
550         parseMesh_t     *p;
551         int                     i;
552         
553         
554         /* test limits */
555         if( numBSPModels == MAX_MAP_MODELS )
556                 Error( "MAX_MAP_MODELS" );
557         
558         /* get model and entity */
559         mod = &bspModels[ numBSPModels ];
560         e = &entities[ mapEntityNum ];
561         
562         /* ydnar: lightgrid mins/maxs */
563         ClearBounds( lgMins, lgMaxs );
564         
565         /* bound the brushes */
566         ClearBounds( mins, maxs );
567         for ( b = e->brushes; b; b = b->next )
568         {
569                 /* ignore non-real brushes (origin, etc) */
570                 if( b->numsides == 0 )
571                         continue;
572                 AddPointToBounds( b->mins, mins, maxs );
573                 AddPointToBounds( b->maxs, mins, maxs );
574                 
575                 /* ydnar: lightgrid bounds */
576                 if( b->compileFlags & C_LIGHTGRID )
577                 {
578                         AddPointToBounds( b->mins, lgMins, lgMaxs );
579                         AddPointToBounds( b->maxs, lgMins, lgMaxs );
580                 }
581         }
582         
583         /* bound patches */
584         for( p = e->patches; p; p = p->next )
585         {
586                 for( i = 0; i < (p->mesh.width * p->mesh.height); i++ )
587                         AddPointToBounds( p->mesh.verts[i].xyz, mins, maxs );
588         }
589         
590         /* ydnar: lightgrid mins/maxs */
591         if( lgMins[ 0 ] < 99999 )
592         {
593                 /* use lightgrid bounds */
594                 VectorCopy( lgMins, mod->mins );
595                 VectorCopy( lgMaxs, mod->maxs );
596         }
597         else
598         {
599                 /* use brush/patch bounds */
600                 VectorCopy( mins, mod->mins );
601                 VectorCopy( maxs, mod->maxs );
602         }
603         
604         /* note size */
605         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 ] );
606         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 ] );
607         
608         /* set firsts */
609         mod->firstBSPSurface = numBSPDrawSurfaces;
610         mod->firstBSPBrush = numBSPBrushes;
611 }
612
613
614
615
616 /*
617 EndModel()
618 finish a model's processing
619 */
620
621 void EndModel( entity_t *e, node_t *headnode )
622 {
623         bspModel_t      *mod;
624         
625         
626         /* note it */
627         Sys_FPrintf( SYS_VRB, "--- EndModel ---\n" );
628         
629         /* emit the bsp */
630         mod = &bspModels[ numBSPModels ];
631         EmitDrawNode_r( headnode );
632         
633         /* set surfaces and brushes */
634         mod->numBSPSurfaces = numBSPDrawSurfaces - mod->firstBSPSurface;
635         mod->firstBSPBrush = e->firstBrush;
636         mod->numBSPBrushes = e->numBrushes;
637         
638         /* increment model count */
639         numBSPModels++;
640 }
641
642
643