]> icculus.org git repositories - divverent/netradiant.git/blob - tools/quake3/q3map2/main.c
command line options for minimap
[divverent/netradiant.git] / tools / quake3 / q3map2 / main.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 MAIN_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 /*
42 Random()
43 returns a pseudorandom number between 0 and 1
44 */
45
46 vec_t Random( void )
47 {
48         return (vec_t) rand() / RAND_MAX;
49 }
50
51
52
53 /*
54 ExitQ3Map()
55 cleanup routine
56 */
57
58 static void ExitQ3Map( void )
59 {
60         BSPFilesCleanup();
61         if( mapDrawSurfs != NULL )
62                 free( mapDrawSurfs );
63 }
64
65
66
67 /* minimap stuff */
68
69 /* borrowed from light.c */
70 void WriteTGA24( char *filename, byte *data, int width, int height, qboolean flip );
71 typedef struct minimap_s
72 {
73         bspModel_t *model;
74         int width;
75         int height;
76         int samples;
77         float *sample_offsets;
78         float sharpen_boxmult;
79         float sharpen_centermult;
80         float *data1f;
81         float *sharpendata1f;
82         vec3_t mins, size;
83 }
84 minimap_t;
85 static minimap_t minimap;
86
87 qboolean BrushIntersectionWithLine(bspBrush_t *brush, vec3_t start, vec3_t dir, float *t_in, float *t_out)
88 {
89         int i;
90         qboolean in = qfalse, out = qfalse;
91         bspBrushSide_t *sides = &bspBrushSides[brush->firstSide];
92
93         for(i = 0; i < brush->numSides; ++i)
94         {
95                 bspPlane_t *p = &bspPlanes[sides[i].planeNum];
96                 float sn = DotProduct(start, p->normal);
97                 float dn = DotProduct(dir, p->normal);
98                 if(dn == 0)
99                 {
100                         if(sn > p->dist)
101                                 return qfalse; // outside!
102                 }
103                 else
104                 {
105                         float t = (p->dist - sn) / dn;
106                         if(dn < 0)
107                         {
108                                 if(!in || t > *t_in)
109                                 {
110                                         *t_in = t;
111                                         in = qtrue;
112                                         // as t_in can only increase, and t_out can only decrease, early out
113                                         if(out && *t_in >= *t_out)
114                                                 return qfalse;
115                                 }
116                         }
117                         else
118                         {
119                                 if(!out || t < *t_out)
120                                 {
121                                         *t_out = t;
122                                         out = qtrue;
123                                         // as t_in can only increase, and t_out can only decrease, early out
124                                         if(in && *t_in >= *t_out)
125                                                 return qfalse;
126                                 }
127                         }
128                 }
129         }
130         return in && out;
131 }
132
133 static float MiniMapSample(float x, float y)
134 {
135         vec3_t org, dir;
136         int i, bi;
137         float t0, t1;
138         float samp;
139         bspBrush_t *b;
140         int cnt;
141
142         org[0] = x;
143         org[1] = y;
144         org[2] = 0;
145         dir[0] = 0;
146         dir[1] = 0;
147         dir[2] = 1;
148
149         cnt = 0;
150         samp = 0;
151         for(i = 0; i < minimap.model->numBSPBrushes; ++i)
152         {
153                 bi = minimap.model->firstBSPBrush + i;
154                 if(opaqueBrushes[bi >> 3] & (1 << (bi & 7)))
155                 {
156                         b = &bspBrushes[bi];
157
158                         // sort out mins/maxs of the brush
159                         bspBrushSide_t *s = &bspBrushSides[b->firstSide];
160                         if(x < -bspPlanes[s[0].planeNum].dist)
161                                 continue;
162                         if(x > +bspPlanes[s[1].planeNum].dist)
163                                 continue;
164                         if(y < -bspPlanes[s[2].planeNum].dist)
165                                 continue;
166                         if(y > +bspPlanes[s[3].planeNum].dist)
167                                 continue;
168
169                         if(BrushIntersectionWithLine(b, org, dir, &t0, &t1))
170                         {
171                                 samp += t1 - t0;
172                                 ++cnt;
173                         }
174                 }
175         }
176
177         return samp;
178 }
179
180 static void MiniMapRandomlySubsampled(int y)
181 {
182         int x, i;
183         float *p = &minimap.data1f[y * minimap.width];
184         float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height);
185         float dx   =                   minimap.size[0]      / (float) minimap.width;
186         float dy   =                   minimap.size[1]      / (float) minimap.height;
187
188         for(x = 0; x < minimap.width; ++x)
189         {
190                 float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width);
191                 float val = 0;
192
193                 for(i = 0; i < minimap.samples; ++i)
194                 {
195                         float thisval = MiniMapSample(
196                                 xmin + Random() * dx,
197                                 ymin + Random() * dy
198                         );
199                         val += thisval;
200                 }
201                 val /= minimap.samples * minimap.size[2];
202                 *p++ = val;
203         }
204 }
205
206 static void MiniMapSubsampled(int y)
207 {
208         int x, i;
209         float *p = &minimap.data1f[y * minimap.width];
210         float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height);
211         float dx   =                   minimap.size[0]      / (float) minimap.width;
212         float dy   =                   minimap.size[1]      / (float) minimap.height;
213
214         for(x = 0; x < minimap.width; ++x)
215         {
216                 float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width);
217                 float val = 0;
218
219                 for(i = 0; i < minimap.samples; ++i)
220                 {
221                         float thisval = MiniMapSample(
222                                 xmin + minimap.sample_offsets[2*i+0] * dx,
223                                 ymin + minimap.sample_offsets[2*i+1] * dy
224                         );
225                         val += thisval;
226                 }
227                 val /= minimap.samples * minimap.size[2];
228                 *p++ = val;
229         }
230 }
231
232 static void MiniMapNoSubsampling(int y)
233 {
234         int x;
235         float *p = &minimap.data1f[y * minimap.width];
236         float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height);
237
238         for(x = 0; x < minimap.width; ++x)
239         {
240                 float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width);
241                 *p++ = MiniMapSample(xmin, ymin) / minimap.size[2];
242         }
243 }
244
245 static void MiniMapSharpen(int y)
246 {
247         int x;
248         qboolean up = (y > 0);
249         qboolean down = (y < minimap.height - 1);
250         float *p = &minimap.data1f[y * minimap.width];
251         float *q = &minimap.sharpendata1f[y * minimap.width];
252
253         for(x = 0; x < minimap.width; ++x)
254         {
255                 qboolean left = (x > 0);
256                 qboolean right = (x < minimap.width - 1);
257                 float val = p[0] * minimap.sharpen_centermult;
258
259                 if(left && up)
260                         val += p[-1 -minimap.width] * minimap.sharpen_boxmult;
261                 if(left && down)
262                         val += p[-1 +minimap.width] * minimap.sharpen_boxmult;
263                 if(right && up)
264                         val += p[+1 -minimap.width] * minimap.sharpen_boxmult;
265                 if(right && down)
266                         val += p[+1 +minimap.width] * minimap.sharpen_boxmult;
267                         
268                 if(left)
269                         val += p[-1] * minimap.sharpen_boxmult;
270                 if(right)
271                         val += p[+1] * minimap.sharpen_boxmult;
272                 if(up)
273                         val += p[-minimap.width] * minimap.sharpen_boxmult;
274                 if(down)
275                         val += p[+minimap.width] * minimap.sharpen_boxmult;
276
277                 ++p;
278                 *q++ = val;
279         }
280 }
281
282 void MiniMapMakeMinsMaxs()
283 {
284         vec3_t mins, maxs, extend;
285         VectorCopy(minimap.model->mins, mins);
286         VectorCopy(minimap.model->maxs, maxs);
287
288         // line compatible to nexuiz mapinfo
289         Sys_Printf("size %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
290
291         VectorSubtract(maxs, mins, extend);
292
293         if(extend[1] > extend[0])
294         {
295                 mins[0] -= (extend[1] - extend[0]) * 0.5;
296                 maxs[0] += (extend[1] - extend[0]) * 0.5;
297         }
298         else
299         {
300                 mins[1] -= (extend[0] - extend[1]) * 0.5;
301                 maxs[1] += (extend[0] - extend[1]) * 0.5;
302         }
303
304         VectorSubtract(maxs, mins, extend);
305         VectorScale(extend, 1.0 / 64.0, extend);
306
307         VectorSubtract(mins, extend, mins);
308         VectorAdd(maxs, extend, maxs);
309
310         VectorCopy(mins, minimap.mins);
311         VectorSubtract(maxs, mins, minimap.size);
312
313         // line compatible to nexuiz mapinfo
314         Sys_Printf("size_texcoords %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
315 }
316
317 int MiniMapBSPMain( int argc, char **argv )
318 {
319         char minimapFilename[1024];
320         float minimapSharpen;
321         byte *data3b, *p;
322         float *q;
323         int x, y;
324         int i;
325
326         /* arg checking */
327         if( argc < 2 )
328         {
329                 Sys_Printf( "Usage: q3map [-v] -minimap [-size n] [-sharpen n] [-samples f] [-o filename.tga] [-minmax Xmin Ymin Zmin Xmax Ymax Zmax] <mapname>\n" );
330                 return 0;
331         }
332
333         /* load the BSP first */
334         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
335         StripExtension( source );
336         DefaultExtension( source, ".bsp" );
337         Sys_Printf( "Loading %s\n", source );
338         LoadBSPFile( source );
339
340         minimap.model = &bspModels[0];
341         MiniMapMakeMinsMaxs();
342
343         *minimapFilename = 0;
344         minimapSharpen = 1;
345         minimap.width = minimap.height = 512;
346         minimap.samples = 1;
347         minimap.sample_offsets = NULL;
348
349         /* process arguments */
350         for( i = 1; i < (argc - 1); i++ )
351         {
352                 if( !strcmp( argv[ i ],  "-size" ) )
353                 {
354                         minimap.width = minimap.height = atoi(argv[i + 1]);
355                         i++;
356                         Sys_Printf( "Image size set to %i\n", minimap.width );
357                 }
358                 else if( !strcmp( argv[ i ],  "-sharpen" ) )
359                 {
360                         minimapSharpen = atof(argv[i + 1]);
361                         i++;
362                         Sys_Printf( "Sharpening coefficient set to %f\n", minimapSharpen );
363                 }
364                 else if( !strcmp( argv[ i ],  "-samples" ) )
365                 {
366                         minimap.samples = atoi(argv[i + 1]);
367                         i++;
368                         Sys_Printf( "Samples set to %i\n", minimap.samples );
369                         /* TODO generate a static subsampling pattern */
370                 }
371                 else if( !strcmp( argv[ i ],  "-o" ) )
372                 {
373                         strcpy(minimapFilename, argv[i + 1]);
374                         i++;
375                         Sys_Printf( "Output file name set to %s\n", minimapFilename );
376                 }
377                 else if( !strcmp( argv[ i ],  "-minmax" ) && i < (argc - 7) )
378                 {
379                         minimap.mins[0] = atof(argv[i + 1]);
380                         minimap.mins[1] = atof(argv[i + 2]);
381                         minimap.mins[2] = atof(argv[i + 3]);
382                         minimap.size[0] = atof(argv[i + 4]) - minimap.mins[0];
383                         minimap.size[1] = atof(argv[i + 5]) - minimap.mins[1];
384                         minimap.size[2] = atof(argv[i + 6]) - minimap.mins[2];
385                         i += 6;
386                         Sys_Printf( "Map mins/maxs overridden\n" );
387                 }
388         }
389
390         strcpy( minimapFilename, ExpandArg( argv[ argc - 1 ] ) );
391         StripExtension( minimapFilename );
392         DefaultExtension( minimapFilename, ".tga" );
393
394         if(minimapSharpen >= 0)
395         {
396                 minimap.sharpen_centermult = 8 * minimapSharpen + 1;
397                 minimap.sharpen_boxmult    =    -minimapSharpen;
398         }
399
400         minimap.data1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f));
401         data3b = safe_malloc(minimap.width * minimap.height * 3);
402         if(minimapSharpen >= 0)
403                 minimap.sharpendata1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f));
404
405         SetupBrushes();
406
407         if(minimap.samples <= 1)
408         {
409                 Sys_Printf( "\n--- MiniMapNoSubsampling (%d) ---\n", minimap.height );
410                 RunThreadsOnIndividual(minimap.height, qtrue, MiniMapNoSubsampling);
411         }
412         else
413         {
414                 if(minimap.sample_offsets)
415                 {
416                         Sys_Printf( "\n--- MiniMapSubsampled (%d) ---\n", minimap.height );
417                         RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSubsampled);
418                 }
419                 else
420                 {
421                         Sys_Printf( "\n--- MiniMapRandomlySubsampled (%d) ---\n", minimap.height );
422                         RunThreadsOnIndividual(minimap.height, qtrue, MiniMapRandomlySubsampled);
423                 }
424         }
425
426         if(minimap.sharpendata1f)
427         {
428                 Sys_Printf( "\n--- MiniMapSharpen (%d) ---\n", minimap.height );
429                 RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSharpen);
430                 q = minimap.sharpendata1f;
431         }
432         else
433         {
434                 q = minimap.data1f;
435         }
436
437         Sys_Printf( "\nConverting...");
438         p = data3b;
439         for(y = 0; y < minimap.height; ++y)
440                 for(x = 0; x < minimap.width; ++x)
441                 {
442                         byte b;
443                         float v = *q++;
444                         if(v < 0) v = 0;
445                         if(v > 255.0/256.0) v = 255.0/256.0;
446                         b = v * 256;
447                         *p++ = b;
448                         *p++ = b;
449                         *p++ = b;
450                 }
451
452         Sys_Printf( " writing to %s...", minimapFilename );
453         WriteTGA24(minimapFilename, data3b, minimap.width, minimap.height, qfalse);
454
455         Sys_Printf( " done.\n" );
456
457         /* return to sender */
458         return 0;
459 }
460
461
462
463
464
465 /*
466 MD4BlockChecksum()
467 calculates an md4 checksum for a block of data
468 */
469
470 static int MD4BlockChecksum( void *buffer, int length )
471 {
472         return Com_BlockChecksum(buffer, length);
473 }
474
475 /*
476 FixAAS()
477 resets an aas checksum to match the given BSP
478 */
479
480 int FixAAS( int argc, char **argv )
481 {
482         int                     length, checksum;
483         void            *buffer;
484         FILE            *file;
485         char            aas[ 1024 ], **ext;
486         char            *exts[] =
487                                 {
488                                         ".aas",
489                                         "_b0.aas",
490                                         "_b1.aas",
491                                         NULL
492                                 };
493         
494         
495         /* arg checking */
496         if( argc < 2 )
497         {
498                 Sys_Printf( "Usage: q3map -fixaas [-v] <mapname>\n" );
499                 return 0;
500         }
501         
502         /* do some path mangling */
503         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
504         StripExtension( source );
505         DefaultExtension( source, ".bsp" );
506         
507         /* note it */
508         Sys_Printf( "--- FixAAS ---\n" );
509         
510         /* load the bsp */
511         Sys_Printf( "Loading %s\n", source );
512         length = LoadFile( source, &buffer );
513         
514         /* create bsp checksum */
515         Sys_Printf( "Creating checksum...\n" );
516         checksum = LittleLong( MD4BlockChecksum( buffer, length ) );
517         
518         /* write checksum to aas */
519         ext = exts;
520         while( *ext )
521         {
522                 /* mangle name */
523                 strcpy( aas, source );
524                 StripExtension( aas );
525                 strcat( aas, *ext );
526                 Sys_Printf( "Trying %s\n", aas );
527                 ext++;
528                 
529                 /* fix it */
530                 file = fopen( aas, "r+b" );
531                 if( !file )
532                         continue;
533                 if( fwrite( &checksum, 4, 1, file ) != 1 )
534                         Error( "Error writing checksum to %s", aas );
535                 fclose( file );
536         }
537         
538         /* return to sender */
539         return 0;
540 }
541
542
543
544 /*
545 AnalyzeBSP() - ydnar
546 analyzes a Quake engine BSP file
547 */
548
549 typedef struct abspHeader_s
550 {
551         char                    ident[ 4 ];
552         int                             version;
553         
554         bspLump_t               lumps[ 1 ];     /* unknown size */
555 }
556 abspHeader_t;
557
558 typedef struct abspLumpTest_s
559 {
560         int                             radix, minCount;
561         char                    *name;
562 }
563 abspLumpTest_t;
564
565 int AnalyzeBSP( int argc, char **argv )
566 {
567         abspHeader_t                    *header;
568         int                                             size, i, version, offset, length, lumpInt, count;
569         char                                    ident[ 5 ];
570         void                                    *lump;
571         float                                   lumpFloat;
572         char                                    lumpString[ 1024 ], source[ 1024 ];
573         qboolean                                lumpSwap = qfalse;
574         abspLumpTest_t                  *lumpTest;
575         static abspLumpTest_t   lumpTests[] =
576                                                         {
577                                                                 { sizeof( bspPlane_t ),                 6,              "IBSP LUMP_PLANES" },
578                                                                 { sizeof( bspBrush_t ),                 1,              "IBSP LUMP_BRUSHES" },
579                                                                 { 8,                                                    6,              "IBSP LUMP_BRUSHSIDES" },
580                                                                 { sizeof( bspBrushSide_t ),             6,              "RBSP LUMP_BRUSHSIDES" },
581                                                                 { sizeof( bspModel_t ),                 1,              "IBSP LUMP_MODELS" },
582                                                                 { sizeof( bspNode_t ),                  2,              "IBSP LUMP_NODES" },
583                                                                 { sizeof( bspLeaf_t ),                  1,              "IBSP LUMP_LEAFS" },
584                                                                 { 104,                                                  3,              "IBSP LUMP_DRAWSURFS" },
585                                                                 { 44,                                                   3,              "IBSP LUMP_DRAWVERTS" },
586                                                                 { 4,                                                    6,              "IBSP LUMP_DRAWINDEXES" },
587                                                                 { 128 * 128 * 3,                                1,              "IBSP LUMP_LIGHTMAPS" },
588                                                                 { 256 * 256 * 3,                                1,              "IBSP LUMP_LIGHTMAPS (256 x 256)" },
589                                                                 { 512 * 512 * 3,                                1,              "IBSP LUMP_LIGHTMAPS (512 x 512)" },
590                                                                 { 0, 0, NULL }
591                                                         };
592         
593         
594         /* arg checking */
595         if( argc < 1 )
596         {
597                 Sys_Printf( "Usage: q3map -analyze [-lumpswap] [-v] <mapname>\n" );
598                 return 0;
599         }
600         
601         /* process arguments */
602         for( i = 1; i < (argc - 1); i++ )
603         {
604                 /* -format map|ase|... */
605                 if( !strcmp( argv[ i ],  "-lumpswap" ) )
606                 {
607                         Sys_Printf( "Swapped lump structs enabled\n" );
608                         lumpSwap = qtrue;
609                 }
610         }
611         
612         /* clean up map name */
613         strcpy( source, ExpandArg( argv[ i ] ) );
614         Sys_Printf( "Loading %s\n", source );
615         
616         /* load the file */
617         size = LoadFile( source, (void**) &header );
618         if( size == 0 || header == NULL )
619         {
620                 Sys_Printf( "Unable to load %s.\n", source );
621                 return -1;
622         }
623         
624         /* analyze ident/version */
625         memcpy( ident, header->ident, 4 );
626         ident[ 4 ] = '\0';
627         version = LittleLong( header->version );
628         
629         Sys_Printf( "Identity:      %s\n", ident );
630         Sys_Printf( "Version:       %d\n", version );
631         Sys_Printf( "---------------------------------------\n" );
632         
633         /* analyze each lump */
634         for( i = 0; i < 100; i++ )
635         {
636                 /* call of duty swapped lump pairs */
637                 if( lumpSwap )
638                 {
639                         offset = LittleLong( header->lumps[ i ].length );
640                         length = LittleLong( header->lumps[ i ].offset );
641                 }
642                 
643                 /* standard lump pairs */
644                 else
645                 {
646                         offset = LittleLong( header->lumps[ i ].offset );
647                         length = LittleLong( header->lumps[ i ].length );
648                 }
649                 
650                 /* extract data */
651                 lump = (byte*) header + offset;
652                 lumpInt = LittleLong( (int) *((int*) lump) );
653                 lumpFloat = LittleFloat( (float) *((float*) lump) );
654                 memcpy( lumpString, (char*) lump, (length < 1024 ? length : 1024) );
655                 lumpString[ 1024 ] = '\0';
656                 
657                 /* print basic lump info */
658                 Sys_Printf( "Lump:          %d\n", i );
659                 Sys_Printf( "Offset:        %d bytes\n", offset );
660                 Sys_Printf( "Length:        %d bytes\n", length );
661                 
662                 /* only operate on valid lumps */
663                 if( length > 0 )
664                 {
665                         /* print data in 4 formats */
666                         Sys_Printf( "As hex:        %08X\n", lumpInt );
667                         Sys_Printf( "As int:        %d\n", lumpInt );
668                         Sys_Printf( "As float:      %f\n", lumpFloat );
669                         Sys_Printf( "As string:     %s\n", lumpString );
670                         
671                         /* guess lump type */
672                         if( lumpString[ 0 ] == '{' && lumpString[ 2 ] == '"' )
673                                 Sys_Printf( "Type guess:    IBSP LUMP_ENTITIES\n" );
674                         else if( strstr( lumpString, "textures/" ) )
675                                 Sys_Printf( "Type guess:    IBSP LUMP_SHADERS\n" );
676                         else
677                         {
678                                 /* guess based on size/count */
679                                 for( lumpTest = lumpTests; lumpTest->radix > 0; lumpTest++ )
680                                 {
681                                         if( (length % lumpTest->radix) != 0 )
682                                                 continue;
683                                         count = length / lumpTest->radix;
684                                         if( count < lumpTest->minCount )
685                                                 continue;
686                                         Sys_Printf( "Type guess:    %s (%d x %d)\n", lumpTest->name, count, lumpTest->radix );
687                                 }
688                         }
689                 }
690                 
691                 Sys_Printf( "---------------------------------------\n" );
692                 
693                 /* end of file */
694                 if( offset + length >= size )
695                         break;
696         }
697         
698         /* last stats */
699         Sys_Printf( "Lump count:    %d\n", i + 1 );
700         Sys_Printf( "File size:     %d bytes\n", size );
701         
702         /* return to caller */
703         return 0;
704 }
705
706
707
708 /*
709 BSPInfo()
710 emits statistics about the bsp file
711 */
712
713 int BSPInfo( int count, char **fileNames )
714 {
715         int                     i;
716         char            source[ 1024 ], ext[ 64 ];
717         int                     size;
718         FILE            *f;
719         
720         
721         /* dummy check */
722         if( count < 1 )
723         {
724                 Sys_Printf( "No files to dump info for.\n");
725                 return -1;
726         }
727         
728         /* enable info mode */
729         infoMode = qtrue;
730         
731         /* walk file list */
732         for( i = 0; i < count; i++ )
733         {
734                 Sys_Printf( "---------------------------------\n" );
735                 
736                 /* mangle filename and get size */
737                 strcpy( source, fileNames[ i ] );
738                 ExtractFileExtension( source, ext );
739                 if( !Q_stricmp( ext, "map" ) )
740                         StripExtension( source );
741                 DefaultExtension( source, ".bsp" );
742                 f = fopen( source, "rb" );
743                 if( f )
744                 {
745                         size = Q_filelength (f);
746                         fclose( f );
747                 }
748                 else
749                         size = 0;
750                 
751                 /* load the bsp file and print lump sizes */
752                 Sys_Printf( "%s\n", source );
753                 LoadBSPFile( source );          
754                 PrintBSPFileSizes();
755                 
756                 /* print sizes */
757                 Sys_Printf( "\n" );
758                 Sys_Printf( "          total         %9d\n", size );
759                 Sys_Printf( "                        %9d KB\n", size / 1024 );
760                 Sys_Printf( "                        %9d MB\n", size / (1024 * 1024) );
761                 
762                 Sys_Printf( "---------------------------------\n" );
763         }
764         
765         /* return count */
766         return i;
767 }
768
769
770 static void ExtrapolateTexcoords(const float *axyz, const float *ast, const float *bxyz, const float *bst, const float *cxyz, const float *cst, const float *axyz_new, float *ast_out, const float *bxyz_new, float *bst_out, const float *cxyz_new, float *cst_out)
771 {
772         vec4_t scoeffs, tcoeffs;
773         float md;
774         m4x4_t solvematrix;
775
776         vec3_t norm;
777         vec3_t dab, dac;
778         VectorSubtract(bxyz, axyz, dab);
779         VectorSubtract(cxyz, axyz, dac);
780         CrossProduct(dab, dac, norm);
781         
782         // assume:
783         //   s = f(x, y, z)
784         //   s(v + norm) = s(v) when n ortho xyz
785         
786         // s(v) = DotProduct(v, scoeffs) + scoeffs[3]
787
788         // solve:
789         //   scoeffs * (axyz, 1) == ast[0]
790         //   scoeffs * (bxyz, 1) == bst[0]
791         //   scoeffs * (cxyz, 1) == cst[0]
792         //   scoeffs * (norm, 0) == 0
793         // scoeffs * [axyz, 1 | bxyz, 1 | cxyz, 1 | norm, 0] = [ast[0], bst[0], cst[0], 0]
794         solvematrix[0] = axyz[0];
795         solvematrix[4] = axyz[1];
796         solvematrix[8] = axyz[2];
797         solvematrix[12] = 1;
798         solvematrix[1] = bxyz[0];
799         solvematrix[5] = bxyz[1];
800         solvematrix[9] = bxyz[2];
801         solvematrix[13] = 1;
802         solvematrix[2] = cxyz[0];
803         solvematrix[6] = cxyz[1];
804         solvematrix[10] = cxyz[2];
805         solvematrix[14] = 1;
806         solvematrix[3] = norm[0];
807         solvematrix[7] = norm[1];
808         solvematrix[11] = norm[2];
809         solvematrix[15] = 0;
810
811         md = m4_det(solvematrix);
812         if(md*md < 1e-10)
813         {
814                 Sys_Printf("Cannot invert some matrix, some texcoords aren't extrapolated!");
815                 return;
816         }
817
818         m4x4_invert(solvematrix);
819
820         scoeffs[0] = ast[0];
821         scoeffs[1] = bst[0];
822         scoeffs[2] = cst[0];
823         scoeffs[3] = 0;
824         m4x4_transform_vec4(solvematrix, scoeffs);
825         tcoeffs[0] = ast[1];
826         tcoeffs[1] = bst[1];
827         tcoeffs[2] = cst[1];
828         tcoeffs[3] = 0;
829         m4x4_transform_vec4(solvematrix, tcoeffs);
830
831         ast_out[0] = scoeffs[0] * axyz_new[0] + scoeffs[1] * axyz_new[1] + scoeffs[2] * axyz_new[2] + scoeffs[3];
832         ast_out[1] = tcoeffs[0] * axyz_new[0] + tcoeffs[1] * axyz_new[1] + tcoeffs[2] * axyz_new[2] + tcoeffs[3];
833         bst_out[0] = scoeffs[0] * bxyz_new[0] + scoeffs[1] * bxyz_new[1] + scoeffs[2] * bxyz_new[2] + scoeffs[3];
834         bst_out[1] = tcoeffs[0] * bxyz_new[0] + tcoeffs[1] * bxyz_new[1] + tcoeffs[2] * bxyz_new[2] + tcoeffs[3];
835         cst_out[0] = scoeffs[0] * cxyz_new[0] + scoeffs[1] * cxyz_new[1] + scoeffs[2] * cxyz_new[2] + scoeffs[3];
836         cst_out[1] = tcoeffs[0] * cxyz_new[0] + tcoeffs[1] * cxyz_new[1] + tcoeffs[2] * cxyz_new[2] + tcoeffs[3];
837 }
838
839 /*
840 ScaleBSPMain()
841 amaze and confuse your enemies with wierd scaled maps!
842 */
843
844 int ScaleBSPMain( int argc, char **argv )
845 {
846         int                     i, j;
847         float           f, a;
848         vec3_t scale;
849         vec3_t          vec;
850         char            str[ 1024 ];
851         int uniform, axis;
852         qboolean texscale;
853         float *old_xyzst = NULL;
854         
855         
856         /* arg checking */
857         if( argc < 3 )
858         {
859                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] <value> <mapname>\n" );
860                 return 0;
861         }
862         
863         /* get scale */
864         scale[2] = scale[1] = scale[0] = atof( argv[ argc - 2 ] );
865         if(argc >= 4)
866                 scale[1] = scale[0] = atof( argv[ argc - 3 ] );
867         if(argc >= 5)
868                 scale[0] = atof( argv[ argc - 4 ] );
869
870         texscale = !strcmp(argv[1], "-tex");
871         
872         uniform = ((scale[0] == scale[1]) && (scale[1] == scale[2]));
873
874         if( scale[0] == 0.0f || scale[1] == 0.0f || scale[2] == 0.0f )
875         {
876                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] <value> <mapname>\n" );
877                 Sys_Printf( "Non-zero scale value required.\n" );
878                 return 0;
879         }
880         
881         /* do some path mangling */
882         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
883         StripExtension( source );
884         DefaultExtension( source, ".bsp" );
885         
886         /* load the bsp */
887         Sys_Printf( "Loading %s\n", source );
888         LoadBSPFile( source );
889         ParseEntities();
890         
891         /* note it */
892         Sys_Printf( "--- ScaleBSP ---\n" );
893         Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities );
894         
895         /* scale entity keys */
896         for( i = 0; i < numBSPEntities && i < numEntities; i++ )
897         {
898                 /* scale origin */
899                 GetVectorForKey( &entities[ i ], "origin", vec );
900                 if( (vec[ 0 ] || vec[ 1 ] || vec[ 2 ]) )
901                 {
902                         vec[0] *= scale[0];
903                         vec[1] *= scale[1];
904                         vec[2] *= scale[2];
905                         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
906                         SetKeyValue( &entities[ i ], "origin", str );
907                 }
908
909                 a = FloatForKey( &entities[ i ], "angle" );
910                 if(a == -1 || a == -2) // z scale
911                         axis = 2;
912                 else if(fabs(sin(DEG2RAD(a))) < 0.707)
913                         axis = 0;
914                 else
915                         axis = 1;
916                 
917                 /* scale door lip */
918                 f = FloatForKey( &entities[ i ], "lip" );
919                 if( f )
920                 {
921                         f *= scale[axis];
922                         sprintf( str, "%f", f );
923                         SetKeyValue( &entities[ i ], "lip", str );
924                 }
925                 
926                 /* scale plat height */
927                 f = FloatForKey( &entities[ i ], "height" );
928                 if( f )
929                 {
930                         f *= scale[2];
931                         sprintf( str, "%f", f );
932                         SetKeyValue( &entities[ i ], "height", str );
933                 }
934
935                 // TODO maybe allow a definition file for entities to specify which values are scaled how?
936         }
937         
938         /* scale models */
939         for( i = 0; i < numBSPModels; i++ )
940         {
941                 bspModels[ i ].mins[0] *= scale[0];
942                 bspModels[ i ].mins[1] *= scale[1];
943                 bspModels[ i ].mins[2] *= scale[2];
944                 bspModels[ i ].maxs[0] *= scale[0];
945                 bspModels[ i ].maxs[1] *= scale[1];
946                 bspModels[ i ].maxs[2] *= scale[2];
947         }
948         
949         /* scale nodes */
950         for( i = 0; i < numBSPNodes; i++ )
951         {
952                 bspNodes[ i ].mins[0] *= scale[0];
953                 bspNodes[ i ].mins[1] *= scale[1];
954                 bspNodes[ i ].mins[2] *= scale[2];
955                 bspNodes[ i ].maxs[0] *= scale[0];
956                 bspNodes[ i ].maxs[1] *= scale[1];
957                 bspNodes[ i ].maxs[2] *= scale[2];
958         }
959         
960         /* scale leafs */
961         for( i = 0; i < numBSPLeafs; i++ )
962         {
963                 bspLeafs[ i ].mins[0] *= scale[0];
964                 bspLeafs[ i ].mins[1] *= scale[1];
965                 bspLeafs[ i ].mins[2] *= scale[2];
966                 bspLeafs[ i ].maxs[0] *= scale[0];
967                 bspLeafs[ i ].maxs[1] *= scale[1];
968                 bspLeafs[ i ].maxs[2] *= scale[2];
969         }
970         
971         if(texscale)
972         {
973                 Sys_Printf("Using texture unlocking (and probably breaking texture alignment a lot)\n");
974                 old_xyzst = safe_malloc(sizeof(*old_xyzst) * numBSPDrawVerts * 5);
975                 for(i = 0; i < numBSPDrawVerts; i++)
976                 {
977                         old_xyzst[5*i+0] = bspDrawVerts[i].xyz[0];
978                         old_xyzst[5*i+1] = bspDrawVerts[i].xyz[1];
979                         old_xyzst[5*i+2] = bspDrawVerts[i].xyz[2];
980                         old_xyzst[5*i+3] = bspDrawVerts[i].st[0];
981                         old_xyzst[5*i+4] = bspDrawVerts[i].st[1];
982                 }
983         }
984
985         /* scale drawverts */
986         for( i = 0; i < numBSPDrawVerts; i++ )
987         {
988                 bspDrawVerts[i].xyz[0] *= scale[0];
989                 bspDrawVerts[i].xyz[1] *= scale[1];
990                 bspDrawVerts[i].xyz[2] *= scale[2];
991                 bspDrawVerts[i].normal[0] /= scale[0];
992                 bspDrawVerts[i].normal[1] /= scale[1];
993                 bspDrawVerts[i].normal[2] /= scale[2];
994                 VectorNormalize(bspDrawVerts[i].normal, bspDrawVerts[i].normal);
995         }
996
997         if(texscale)
998         {
999                 for(i = 0; i < numBSPDrawSurfaces; i++)
1000                 {
1001                         switch(bspDrawSurfaces[i].surfaceType)
1002                         {
1003                                 case SURFACE_FACE:
1004                                 case SURFACE_META:
1005                                         if(bspDrawSurfaces[i].numIndexes % 3)
1006                                                 Error("Not a triangulation!");
1007                                         for(j = bspDrawSurfaces[i].firstIndex; j < bspDrawSurfaces[i].firstIndex + bspDrawSurfaces[i].numIndexes; j += 3)
1008                                         {
1009                                                 int ia = bspDrawIndexes[j] + bspDrawSurfaces[i].firstVert, ib = bspDrawIndexes[j+1] + bspDrawSurfaces[i].firstVert, ic = bspDrawIndexes[j+2] + bspDrawSurfaces[i].firstVert;
1010                                                 bspDrawVert_t *a = &bspDrawVerts[ia], *b = &bspDrawVerts[ib], *c = &bspDrawVerts[ic];
1011                                                 float *oa = &old_xyzst[ia*5], *ob = &old_xyzst[ib*5], *oc = &old_xyzst[ic*5];
1012                                                 // extrapolate:
1013                                                 //   a->xyz -> oa
1014                                                 //   b->xyz -> ob
1015                                                 //   c->xyz -> oc
1016                                                 ExtrapolateTexcoords(
1017                                                         &oa[0], &oa[3],
1018                                                         &ob[0], &ob[3],
1019                                                         &oc[0], &oc[3],
1020                                                         a->xyz, a->st,
1021                                                         b->xyz, b->st,
1022                                                         c->xyz, c->st);
1023                                         }
1024                                         break;
1025                         }
1026                 }
1027         }
1028         
1029         /* scale planes */
1030         if(uniform)
1031         {
1032                 for( i = 0; i < numBSPPlanes; i++ )
1033                 {
1034                         bspPlanes[ i ].dist *= scale[0];
1035                 }
1036         }
1037         else
1038         {
1039                 for( i = 0; i < numBSPPlanes; i++ )
1040                 {
1041                         bspPlanes[ i ].normal[0] /= scale[0];
1042                         bspPlanes[ i ].normal[1] /= scale[1];
1043                         bspPlanes[ i ].normal[2] /= scale[2];
1044                         f = 1/VectorLength(bspPlanes[i].normal);
1045                         VectorScale(bspPlanes[i].normal, f, bspPlanes[i].normal);
1046                         bspPlanes[ i ].dist *= f;
1047                 }
1048         }
1049         
1050         /* scale gridsize */
1051         GetVectorForKey( &entities[ 0 ], "gridsize", vec );
1052         if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) == 0.0f )
1053                 VectorCopy( gridSize, vec );
1054         vec[0] *= scale[0];
1055         vec[1] *= scale[1];
1056         vec[2] *= scale[2];
1057         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1058         SetKeyValue( &entities[ 0 ], "gridsize", str );
1059
1060         /* inject command line parameters */
1061         InjectCommandLine(argv, 0, argc - 1);
1062         
1063         /* write the bsp */
1064         UnparseEntities();
1065         StripExtension( source );
1066         DefaultExtension( source, "_s.bsp" );
1067         Sys_Printf( "Writing %s\n", source );
1068         WriteBSPFile( source );
1069         
1070         /* return to sender */
1071         return 0;
1072 }
1073
1074
1075
1076 /*
1077 ConvertBSPMain()
1078 main argument processing function for bsp conversion
1079 */
1080
1081 int ConvertBSPMain( int argc, char **argv )
1082 {
1083         int             i;
1084         int             (*convertFunc)( char * );
1085         game_t  *convertGame;
1086         
1087         
1088         /* set default */
1089         convertFunc = ConvertBSPToASE;
1090         convertGame = NULL;
1091         
1092         /* arg checking */
1093         if( argc < 1 )
1094         {
1095                 Sys_Printf( "Usage: q3map -scale <value> [-v] <mapname>\n" );
1096                 return 0;
1097         }
1098         
1099         /* process arguments */
1100         for( i = 1; i < (argc - 1); i++ )
1101         {
1102                 /* -format map|ase|... */
1103                 if( !strcmp( argv[ i ],  "-format" ) )
1104                 {
1105                         i++;
1106                         if( !Q_stricmp( argv[ i ], "ase" ) )
1107                                 convertFunc = ConvertBSPToASE;
1108                         else if( !Q_stricmp( argv[ i ], "map" ) )
1109                                 convertFunc = ConvertBSPToMap;
1110                         else
1111                         {
1112                                 convertGame = GetGame( argv[ i ] );
1113                                 if( convertGame == NULL )
1114                                         Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] );
1115                         }
1116                 }
1117                 else if( !strcmp( argv[ i ],  "-ne" ) )
1118                 {
1119                         normalEpsilon = atof( argv[ i + 1 ] );
1120                         i++;
1121                         Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon );
1122                 }
1123                 else if( !strcmp( argv[ i ],  "-de" ) )
1124                 {
1125                         distanceEpsilon = atof( argv[ i + 1 ] );
1126                         i++;
1127                         Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon );
1128                 }
1129                 else if( !strcmp( argv[ i ],  "-shadersasbitmap" ) )
1130                         shadersAsBitmap = qtrue;
1131         }
1132         
1133         /* clean up map name */
1134         strcpy( source, ExpandArg( argv[ i ] ) );
1135         StripExtension( source );
1136         DefaultExtension( source, ".bsp" );
1137         
1138         LoadShaderInfo();
1139         
1140         Sys_Printf( "Loading %s\n", source );
1141         
1142         /* ydnar: load surface file */
1143         //%     LoadSurfaceExtraFile( source );
1144         
1145         LoadBSPFile( source );
1146         
1147         /* parse bsp entities */
1148         ParseEntities();
1149         
1150         /* bsp format convert? */
1151         if( convertGame != NULL )
1152         {
1153                 /* set global game */
1154                 game = convertGame;
1155                 
1156                 /* write bsp */
1157                 StripExtension( source );
1158                 DefaultExtension( source, "_c.bsp" );
1159                 Sys_Printf( "Writing %s\n", source );
1160                 WriteBSPFile( source );
1161                 
1162                 /* return to sender */
1163                 return 0;
1164         }
1165         
1166         /* normal convert */
1167         return convertFunc( source );
1168 }
1169
1170
1171
1172 /*
1173 main()
1174 q3map mojo...
1175 */
1176
1177 int main( int argc, char **argv )
1178 {
1179         int             i, r;
1180         double  start, end;
1181         
1182         
1183         /* we want consistent 'randomness' */
1184         srand( 0 );
1185         
1186         /* start timer */
1187         start = I_FloatTime();
1188
1189         /* this was changed to emit version number over the network */
1190         printf( Q3MAP_VERSION "\n" );
1191         
1192         /* set exit call */
1193         atexit( ExitQ3Map );
1194
1195         /* read general options first */
1196         for( i = 1; i < argc; i++ )
1197         {
1198                 /* -connect */
1199                 if( !strcmp( argv[ i ], "-connect" ) )
1200                 {
1201                         argv[ i ] = NULL;
1202                         i++;
1203                         Broadcast_Setup( argv[ i ] );
1204                         argv[ i ] = NULL;
1205                 }
1206                 
1207                 /* verbose */
1208                 else if( !strcmp( argv[ i ], "-v" ) )
1209                 {
1210                         if(!verbose)
1211                         {
1212                                 verbose = qtrue;
1213                                 argv[ i ] = NULL;
1214                         }
1215                 }
1216                 
1217                 /* force */
1218                 else if( !strcmp( argv[ i ], "-force" ) )
1219                 {
1220                         force = qtrue;
1221                         argv[ i ] = NULL;
1222                 }
1223                 
1224                 /* patch subdivisions */
1225                 else if( !strcmp( argv[ i ], "-subdivisions" ) )
1226                 {
1227                         argv[ i ] = NULL;
1228                         i++;
1229                         patchSubdivisions = atoi( argv[ i ] );
1230                         argv[ i ] = NULL;
1231                         if( patchSubdivisions <= 0 )
1232                                 patchSubdivisions = 1;
1233                 }
1234                 
1235                 /* threads */
1236                 else if( !strcmp( argv[ i ], "-threads" ) )
1237                 {
1238                         argv[ i ] = NULL;
1239                         i++;
1240                         numthreads = atoi( argv[ i ] );
1241                         argv[ i ] = NULL;
1242                 }
1243         }
1244         
1245         /* init model library */
1246         PicoInit();
1247         PicoSetMallocFunc( safe_malloc );
1248         PicoSetFreeFunc( free );
1249         PicoSetPrintFunc( PicoPrintFunc );
1250         PicoSetLoadFileFunc( PicoLoadFileFunc );
1251         PicoSetFreeFileFunc( free );
1252         
1253         /* set number of threads */
1254         ThreadSetDefault();
1255         
1256         /* generate sinusoid jitter table */
1257         for( i = 0; i < MAX_JITTERS; i++ )
1258         {
1259                 jitters[ i ] = sin( i * 139.54152147 );
1260                 //%     Sys_Printf( "Jitter %4d: %f\n", i, jitters[ i ] );
1261         }
1262         
1263         /* we print out two versions, q3map's main version (since it evolves a bit out of GtkRadiant)
1264            and we put the GtkRadiant version to make it easy to track with what version of Radiant it was built with */
1265         
1266         Sys_Printf( "Q3Map         - v1.0r (c) 1999 Id Software Inc.\n" );
1267         Sys_Printf( "Q3Map (ydnar) - v" Q3MAP_VERSION "\n" );
1268         Sys_Printf( "NetRadiant    - v" RADIANT_VERSION " " __DATE__ " " __TIME__ "\n" );
1269         Sys_Printf( "%s\n", Q3MAP_MOTD );
1270         
1271         /* ydnar: new path initialization */
1272         InitPaths( &argc, argv );
1273
1274         /* set game options */
1275         if (!patchSubdivisions)
1276                 patchSubdivisions = game->patchSubdivisions;
1277         
1278         /* check if we have enough options left to attempt something */
1279         if( argc < 2 )
1280                 Error( "Usage: %s [general options] [options] mapfile", argv[ 0 ] );
1281         
1282         /* fixaas */
1283         if( !strcmp( argv[ 1 ], "-fixaas" ) )
1284                 r = FixAAS( argc - 1, argv + 1 );
1285         
1286         /* analyze */
1287         else if( !strcmp( argv[ 1 ], "-analyze" ) )
1288                 r = AnalyzeBSP( argc - 1, argv + 1 );
1289         
1290         /* info */
1291         else if( !strcmp( argv[ 1 ], "-info" ) )
1292                 r = BSPInfo( argc - 2, argv + 2 );
1293         
1294         /* vis */
1295         else if( !strcmp( argv[ 1 ], "-vis" ) )
1296                 r = VisMain( argc - 1, argv + 1 );
1297         
1298         /* light */
1299         else if( !strcmp( argv[ 1 ], "-light" ) )
1300                 r = LightMain( argc - 1, argv + 1 );
1301         
1302         /* vlight */
1303         else if( !strcmp( argv[ 1 ], "-vlight" ) )
1304         {
1305                 Sys_Printf( "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" );
1306                 argv[ 1 ] = "-fast";    /* eek a hack */
1307                 r = LightMain( argc, argv );
1308         }
1309         
1310         /* ydnar: lightmap export */
1311         else if( !strcmp( argv[ 1 ], "-export" ) )
1312                 r = ExportLightmapsMain( argc - 1, argv + 1 );
1313         
1314         /* ydnar: lightmap import */
1315         else if( !strcmp( argv[ 1 ], "-import" ) )
1316                 r = ImportLightmapsMain( argc - 1, argv + 1 );
1317         
1318         /* ydnar: bsp scaling */
1319         else if( !strcmp( argv[ 1 ], "-scale" ) )
1320                 r = ScaleBSPMain( argc - 1, argv + 1 );
1321         
1322         /* ydnar: bsp conversion */
1323         else if( !strcmp( argv[ 1 ], "-convert" ) )
1324                 r = ConvertBSPMain( argc - 1, argv + 1 );
1325         
1326         /* div0: minimap */
1327         else if( !strcmp( argv[ 1 ], "-minimap" ) )
1328                 r = MiniMapBSPMain(argc - 1, argv + 1);
1329
1330         /* ydnar: otherwise create a bsp */
1331         else
1332                 r = BSPMain( argc, argv );
1333         
1334         /* emit time */
1335         end = I_FloatTime();
1336         Sys_Printf( "%9.0f seconds elapsed\n", end - start );
1337         
1338         /* shut down connection */
1339         Broadcast_Shutdown();
1340         
1341         /* return any error code */
1342         return r;
1343 }