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