use "minimaps" directory for warsow
[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         bspBrushSide_t *s;
141         int cnt;
142
143         org[0] = x;
144         org[1] = y;
145         org[2] = 0;
146         dir[0] = 0;
147         dir[1] = 0;
148         dir[2] = 1;
149
150         cnt = 0;
151         samp = 0;
152         for(i = 0; i < minimap.model->numBSPBrushes; ++i)
153         {
154                 bi = minimap.model->firstBSPBrush + i;
155                 if(opaqueBrushes[bi >> 3] & (1 << (bi & 7)))
156                 {
157                         b = &bspBrushes[bi];
158
159                         // sort out mins/maxs of the brush
160                         s = &bspBrushSides[b->firstSide];
161                         if(x < -bspPlanes[s[0].planeNum].dist)
162                                 continue;
163                         if(x > +bspPlanes[s[1].planeNum].dist)
164                                 continue;
165                         if(y < -bspPlanes[s[2].planeNum].dist)
166                                 continue;
167                         if(y > +bspPlanes[s[3].planeNum].dist)
168                                 continue;
169
170                         if(BrushIntersectionWithLine(b, org, dir, &t0, &t1))
171                         {
172                                 samp += t1 - t0;
173                                 ++cnt;
174                         }
175                 }
176         }
177
178         return samp;
179 }
180
181 void RandomVector2f(float v[2])
182 {
183         do
184         {
185                 v[0] = 2 * Random() - 1;
186                 v[1] = 2 * Random() - 1;
187         }
188         while(v[0] * v[0] + v[1] * v[1] > 1);
189 }
190
191 static void MiniMapRandomlySupersampled(int y)
192 {
193         int x, i;
194         float *p = &minimap.data1f[y * minimap.width];
195         float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height);
196         float dx   =                   minimap.size[0]      / (float) minimap.width;
197         float dy   =                   minimap.size[1]      / (float) minimap.height;
198         float uv[2];
199         float thisval;
200
201         for(x = 0; x < minimap.width; ++x)
202         {
203                 float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width);
204                 float val = 0;
205
206                 for(i = 0; i < minimap.samples; ++i)
207                 {
208                         RandomVector2f(uv);
209                         thisval = MiniMapSample(
210                                 xmin + (uv[0] + 0.5) * dx, /* exaggerated random pattern for better results */
211                                 ymin + (uv[1] + 0.5) * dy  /* exaggerated random pattern for better results */
212                         );
213                         val += thisval;
214                 }
215                 val /= minimap.samples * minimap.size[2];
216                 *p++ = val;
217         }
218 }
219
220 static void MiniMapSupersampled(int y)
221 {
222         int x, i;
223         float *p = &minimap.data1f[y * minimap.width];
224         float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height);
225         float dx   =                   minimap.size[0]      / (float) minimap.width;
226         float dy   =                   minimap.size[1]      / (float) minimap.height;
227
228         for(x = 0; x < minimap.width; ++x)
229         {
230                 float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width);
231                 float val = 0;
232
233                 for(i = 0; i < minimap.samples; ++i)
234                 {
235                         float thisval = MiniMapSample(
236                                 xmin + minimap.sample_offsets[2*i+0] * dx,
237                                 ymin + minimap.sample_offsets[2*i+1] * dy
238                         );
239                         val += thisval;
240                 }
241                 val /= minimap.samples * minimap.size[2];
242                 *p++ = val;
243         }
244 }
245
246 static void MiniMapNoSupersampling(int y)
247 {
248         int x;
249         float *p = &minimap.data1f[y * minimap.width];
250         float ymin = minimap.mins[1] + minimap.size[1] * ((y + 0.5) / (float) minimap.height);
251
252         for(x = 0; x < minimap.width; ++x)
253         {
254                 float xmin = minimap.mins[0] + minimap.size[0] * ((x + 0.5) / (float) minimap.width);
255                 *p++ = MiniMapSample(xmin, ymin) / minimap.size[2];
256         }
257 }
258
259 static void MiniMapSharpen(int y)
260 {
261         int x;
262         qboolean up = (y > 0);
263         qboolean down = (y < minimap.height - 1);
264         float *p = &minimap.data1f[y * minimap.width];
265         float *q = &minimap.sharpendata1f[y * minimap.width];
266
267         for(x = 0; x < minimap.width; ++x)
268         {
269                 qboolean left = (x > 0);
270                 qboolean right = (x < minimap.width - 1);
271                 float val = p[0] * minimap.sharpen_centermult;
272
273                 if(left && up)
274                         val += p[-1 -minimap.width] * minimap.sharpen_boxmult;
275                 if(left && down)
276                         val += p[-1 +minimap.width] * minimap.sharpen_boxmult;
277                 if(right && up)
278                         val += p[+1 -minimap.width] * minimap.sharpen_boxmult;
279                 if(right && down)
280                         val += p[+1 +minimap.width] * minimap.sharpen_boxmult;
281                         
282                 if(left)
283                         val += p[-1] * minimap.sharpen_boxmult;
284                 if(right)
285                         val += p[+1] * minimap.sharpen_boxmult;
286                 if(up)
287                         val += p[-minimap.width] * minimap.sharpen_boxmult;
288                 if(down)
289                         val += p[+minimap.width] * minimap.sharpen_boxmult;
290
291                 ++p;
292                 *q++ = val;
293         }
294 }
295
296 void MiniMapMakeMinsMaxs(vec3_t mins_in, vec3_t maxs_in, float border, qboolean keepaspect)
297 {
298         vec3_t mins, maxs, extend;
299         VectorCopy(mins_in, mins);
300         VectorCopy(maxs_in, maxs);
301
302         // line compatible to nexuiz mapinfo
303         Sys_Printf("size %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
304
305         if(keepaspect)
306         {
307                 VectorSubtract(maxs, mins, extend);
308                 if(extend[1] > extend[0])
309                 {
310                         mins[0] -= (extend[1] - extend[0]) * 0.5;
311                         maxs[0] += (extend[1] - extend[0]) * 0.5;
312                 }
313                 else
314                 {
315                         mins[1] -= (extend[0] - extend[1]) * 0.5;
316                         maxs[1] += (extend[0] - extend[1]) * 0.5;
317                 }
318         }
319
320         /* border: amount of black area around the image */
321         /* input: border, 1-2*border, border but we need border/(1-2*border) */
322
323         VectorSubtract(maxs, mins, extend);
324         VectorScale(extend, border / (1 - 2 * border), extend);
325
326         VectorSubtract(mins, extend, mins);
327         VectorAdd(maxs, extend, maxs);
328
329         VectorCopy(mins, minimap.mins);
330         VectorSubtract(maxs, mins, minimap.size);
331
332         // line compatible to nexuiz mapinfo
333         Sys_Printf("size_texcoords %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
334 }
335
336 /*
337 MiniMapSetupBrushes()
338 determines solid non-sky brushes in the world
339 */
340
341 void MiniMapSetupBrushes( void )
342 {
343         int                             i, b, compileFlags;
344         bspBrush_t              *brush;
345         bspShader_t             *shader;
346         shaderInfo_t    *si;
347         
348         
349         /* note it */
350         Sys_FPrintf( SYS_VRB, "--- MiniMapSetupBrushes ---\n" );
351         
352         /* allocate */
353         if( opaqueBrushes == NULL )
354                 opaqueBrushes = safe_malloc( numBSPBrushes / 8 + 1 );
355         
356         /* clear */
357         memset( opaqueBrushes, 0, numBSPBrushes / 8 + 1 );
358         numOpaqueBrushes = 0;
359         
360         /* walk the list of worldspawn brushes */
361         for( i = 0; i < minimap.model->numBSPBrushes; i++ )
362         {
363                 /* get brush */
364                 b = minimap.model->firstBSPBrush + i;
365                 brush = &bspBrushes[ b ];
366                 
367 #if 0
368                 /* check all sides */
369                 compileFlags = 0;
370                 for( j = 0; j < brush->numSides; j++ )
371                 {
372                         /* do bsp shader calculations */
373                         side = &bspBrushSides[ brush->firstSide + j ];
374                         shader = &bspShaders[ side->shaderNum ];
375                         
376                         /* get shader info */
377                         si = ShaderInfoForShader( shader->shader );
378                         if( si == NULL )
379                                 continue;
380                         
381                         /* or together compile flags */
382                         compileFlags |= si->compileFlags;
383                 }
384 #else
385                 shader = &bspShaders[ brush->shaderNum ];
386                 si = ShaderInfoForShader( shader->shader );
387                 if( si == NULL )
388                         compileFlags = 0;
389                 else
390                         compileFlags = si->compileFlags;
391 #endif
392                 
393                 /* determine if this brush is solid */
394                 if( (compileFlags & (C_SOLID | C_SKY)) == C_SOLID )
395                 {
396                         opaqueBrushes[ b >> 3 ] |= (1 << (b & 7));
397                         numOpaqueBrushes++;
398                         maxOpaqueBrush = i;
399                 }
400         }
401         
402         /* emit some statistics */
403         Sys_FPrintf( SYS_VRB, "%9d solid brushes\n", numOpaqueBrushes );
404 }
405
406 qboolean MiniMapEvaluateSampleOffsets(int *bestj, int *bestk, float *bestval)
407 {
408         float val, dx, dy;
409         int j, k;
410
411         *bestj = *bestk = -1;
412         *bestval = 3; /* max possible val is 2 */
413
414         for(j = 0; j < minimap.samples; ++j)
415                 for(k = j + 1; k < minimap.samples; ++k)
416                 {
417                         dx = minimap.sample_offsets[2*j+0] - minimap.sample_offsets[2*k+0];
418                         dy = minimap.sample_offsets[2*j+1] - minimap.sample_offsets[2*k+1];
419                         if(dx > +0.5) dx -= 1;
420                         if(dx < -0.5) dx += 1;
421                         if(dy > +0.5) dy -= 1;
422                         if(dy < -0.5) dy += 1;
423                         val = dx * dx + dy * dy;
424                         if(val < *bestval)
425                         {
426                                 *bestj = j;
427                                 *bestk = k;
428                                 *bestval = val;
429                         }
430                 }
431         
432         return *bestval < 3;
433 }
434
435 void MiniMapMakeSampleOffsets()
436 {
437         int i, j, k, jj, kk;
438         float val, valj, valk, sx, sy, rx, ry;
439
440         Sys_Printf( "Generating good sample offsets (this may take a while)...\n" );
441
442         /* start with entirely random samples */
443         for(i = 0; i < minimap.samples; ++i)
444         {
445                 minimap.sample_offsets[2*i+0] = Random();
446                 minimap.sample_offsets[2*i+1] = Random();
447         }
448
449         for(i = 0; i < 1000; ++i)
450         {
451                 if(MiniMapEvaluateSampleOffsets(&j, &k, &val))
452                 {
453                         sx = minimap.sample_offsets[2*j+0];
454                         sy = minimap.sample_offsets[2*j+1];
455                         minimap.sample_offsets[2*j+0] = rx = Random();
456                         minimap.sample_offsets[2*j+1] = ry = Random();
457                         if(!MiniMapEvaluateSampleOffsets(&jj, &kk, &valj))
458                                 valj = -1;
459                         minimap.sample_offsets[2*j+0] = sx;
460                         minimap.sample_offsets[2*j+1] = sy;
461
462                         sx = minimap.sample_offsets[2*k+0];
463                         sy = minimap.sample_offsets[2*k+1];
464                         minimap.sample_offsets[2*k+0] = rx;
465                         minimap.sample_offsets[2*k+1] = ry;
466                         if(!MiniMapEvaluateSampleOffsets(&jj, &kk, &valk))
467                                 valk = -1;
468                         minimap.sample_offsets[2*k+0] = sx;
469                         minimap.sample_offsets[2*k+1] = sy;
470
471                         if(valj > valk)
472                         {
473                                 if(valj > val)
474                                 {
475                                         /* valj is the greatest */
476                                         minimap.sample_offsets[2*j+0] = rx;
477                                         minimap.sample_offsets[2*j+1] = ry;
478                                         i = -1;
479                                 }
480                                 else
481                                 {
482                                         /* valj is the greater and it is useless - forget it */
483                                 }
484                         }
485                         else
486                         {
487                                 if(valk > val)
488                                 {
489                                         /* valk is the greatest */
490                                         minimap.sample_offsets[2*k+0] = rx;
491                                         minimap.sample_offsets[2*k+1] = ry;
492                                         i = -1;
493                                 }
494                                 else
495                                 {
496                                         /* valk is the greater and it is useless - forget it */
497                                 }
498                         }
499                 }
500                 else
501                         break;
502         }
503 }
504
505 void MergeRelativePath(char *out, const char *absolute, const char *relative)
506 {
507         const char *endpos = absolute + strlen(absolute);
508         while(endpos != absolute && (endpos[-1] == '/' || endpos[-1] == '\\'))
509                 --endpos;
510         while(relative[0] == '.' && relative[1] == '.' && (relative[2] == '/' || relative[2] == '\\'))
511         {
512                 relative += 3;
513                 while(endpos != absolute)
514                 {
515                         --endpos;
516                         if(*endpos == '/' || *endpos == '\\')
517                                 break;
518                 }
519                 while(endpos != absolute && (endpos[-1] == '/' || endpos[-1] == '\\'))
520                         --endpos;
521         }
522         memcpy(out, absolute, endpos - absolute);
523         out[endpos - absolute] = '/';
524         strcpy(out + (endpos - absolute + 1), relative);
525 }
526
527 int MiniMapBSPMain( int argc, char **argv )
528 {
529         char minimapFilename[1024];
530         char basename[1024];
531         char path[1024];
532         char relativeMinimapFilename[1024];
533         float minimapSharpen;
534         float border;
535         byte *data3b, *p;
536         float *q;
537         int x, y;
538         int i;
539         vec3_t mins, maxs;
540         qboolean keepaspect;
541
542         /* arg checking */
543         if( argc < 2 )
544         {
545                 Sys_Printf( "Usage: q3map [-v] -minimap [-size n] [-sharpen f] [-samples n | -random n] [-o filename.tga] [-minmax Xmin Ymin Zmin Xmax Ymax Zmax] <mapname>\n" );
546                 return 0;
547         }
548
549         /* load the BSP first */
550         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
551         StripExtension( source );
552         DefaultExtension( source, ".bsp" );
553         Sys_Printf( "Loading %s\n", source );
554         BeginMapShaderFile( source );
555         LoadShaderInfo();
556         LoadBSPFile( source );
557
558         minimap.model = &bspModels[0];
559         VectorCopy(minimap.model->mins, mins);
560         VectorCopy(minimap.model->maxs, maxs);
561
562         *minimapFilename = 0;
563         minimapSharpen = game->miniMapSharpen;
564         minimap.width = minimap.height = game->miniMapSize;
565         border = game->miniMapBorder;
566         keepaspect = game->miniMapKeepAspect;
567
568         minimap.samples = 1;
569         minimap.sample_offsets = NULL;
570
571         /* process arguments */
572         for( i = 1; i < (argc - 1); i++ )
573         {
574                 if( !strcmp( argv[ i ],  "-size" ) )
575                 {
576                         minimap.width = minimap.height = atoi(argv[i + 1]);
577                         i++;
578                         Sys_Printf( "Image size set to %i\n", minimap.width );
579                 }
580                 else if( !strcmp( argv[ i ],  "-sharpen" ) )
581                 {
582                         minimapSharpen = atof(argv[i + 1]);
583                         i++;
584                         Sys_Printf( "Sharpening coefficient set to %f\n", minimapSharpen );
585                 }
586                 else if( !strcmp( argv[ i ],  "-samples" ) )
587                 {
588                         minimap.samples = atoi(argv[i + 1]);
589                         i++;
590                         Sys_Printf( "Samples set to %i\n", minimap.samples );
591                         if(minimap.sample_offsets)
592                                 free(minimap.sample_offsets);
593                         minimap.sample_offsets = malloc(2 * sizeof(*minimap.sample_offsets) * minimap.samples);
594                         MiniMapMakeSampleOffsets();
595                 }
596                 else if( !strcmp( argv[ i ],  "-random" ) )
597                 {
598                         minimap.samples = atoi(argv[i + 1]);
599                         i++;
600                         Sys_Printf( "Random samples set to %i\n", minimap.samples );
601                         if(minimap.sample_offsets)
602                                 free(minimap.sample_offsets);
603                         minimap.sample_offsets = NULL;
604                 }
605                 else if( !strcmp( argv[ i ],  "-border" ) )
606                 {
607                         border = atof(argv[i + 1]);
608                         i++;
609                         Sys_Printf( "Border set to %f\n", border );
610                 }
611                 else if( !strcmp( argv[ i ],  "-keepaspect" ) )
612                 {
613                         keepaspect = qtrue;
614                         Sys_Printf( "Keeping aspect ratio by letterboxing\n", border );
615                 }
616                 else if( !strcmp( argv[ i ],  "-nokeepaspect" ) )
617                 {
618                         keepaspect = qfalse;
619                         Sys_Printf( "Not keeping aspect ratio\n", border );
620                 }
621                 else if( !strcmp( argv[ i ],  "-o" ) )
622                 {
623                         strcpy(minimapFilename, argv[i + 1]);
624                         i++;
625                         Sys_Printf( "Output file name set to %s\n", minimapFilename );
626                 }
627                 else if( !strcmp( argv[ i ],  "-minmax" ) && i < (argc - 7) )
628                 {
629                         mins[0] = atof(argv[i + 1]);
630                         mins[1] = atof(argv[i + 2]);
631                         mins[2] = atof(argv[i + 3]);
632                         maxs[0] = atof(argv[i + 4]);
633                         maxs[1] = atof(argv[i + 5]);
634                         maxs[2] = atof(argv[i + 6]);
635                         i += 6;
636                         Sys_Printf( "Map mins/maxs overridden\n" );
637                 }
638         }
639
640         MiniMapMakeMinsMaxs(mins, maxs, border, keepaspect);
641
642         if(!*minimapFilename)
643         {
644                 ExtractFileBase(source, basename);
645                 ExtractFilePath(source, path);
646                 sprintf(relativeMinimapFilename, game->miniMapNameFormat, basename);
647                 MergeRelativePath(minimapFilename, path, relativeMinimapFilename);
648                 Sys_Printf("Output file name automatically set to %s\n", minimapFilename);
649         }
650
651         if(minimapSharpen >= 0)
652         {
653                 minimap.sharpen_centermult = 8 * minimapSharpen + 1;
654                 minimap.sharpen_boxmult    =    -minimapSharpen;
655         }
656
657         minimap.data1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f));
658         data3b = safe_malloc(minimap.width * minimap.height * 3);
659         if(minimapSharpen >= 0)
660                 minimap.sharpendata1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f));
661
662         MiniMapSetupBrushes();
663
664         if(minimap.samples <= 1)
665         {
666                 Sys_Printf( "\n--- MiniMapNoSupersampling (%d) ---\n", minimap.height );
667                 RunThreadsOnIndividual(minimap.height, qtrue, MiniMapNoSupersampling);
668         }
669         else
670         {
671                 if(minimap.sample_offsets)
672                 {
673                         Sys_Printf( "\n--- MiniMapSupersampled (%d) ---\n", minimap.height );
674                         RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSupersampled);
675                 }
676                 else
677                 {
678                         Sys_Printf( "\n--- MiniMapRandomlySupersampled (%d) ---\n", minimap.height );
679                         RunThreadsOnIndividual(minimap.height, qtrue, MiniMapRandomlySupersampled);
680                 }
681         }
682
683         if(minimap.sharpendata1f)
684         {
685                 Sys_Printf( "\n--- MiniMapSharpen (%d) ---\n", minimap.height );
686                 RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSharpen);
687                 q = minimap.sharpendata1f;
688         }
689         else
690         {
691                 q = minimap.data1f;
692         }
693
694         Sys_Printf( "\nConverting...");
695         p = data3b;
696         for(y = 0; y < minimap.height; ++y)
697                 for(x = 0; x < minimap.width; ++x)
698                 {
699                         byte b;
700                         float v = *q++;
701                         if(v < 0) v = 0;
702                         if(v > 255.0/256.0) v = 255.0/256.0;
703                         b = v * 256;
704                         *p++ = b;
705                         *p++ = b;
706                         *p++ = b;
707                 }
708
709         Sys_Printf( " writing to %s...", minimapFilename );
710         ExtractFilePath(minimapFilename, path);
711         Q_mkdir(path);
712         WriteTGA24(minimapFilename, data3b, minimap.width, minimap.height, qfalse);
713
714         Sys_Printf( " done.\n" );
715
716         /* return to sender */
717         return 0;
718 }
719
720
721
722
723
724 /*
725 MD4BlockChecksum()
726 calculates an md4 checksum for a block of data
727 */
728
729 static int MD4BlockChecksum( void *buffer, int length )
730 {
731         return Com_BlockChecksum(buffer, length);
732 }
733
734 /*
735 FixAAS()
736 resets an aas checksum to match the given BSP
737 */
738
739 int FixAAS( int argc, char **argv )
740 {
741         int                     length, checksum;
742         void            *buffer;
743         FILE            *file;
744         char            aas[ 1024 ], **ext;
745         char            *exts[] =
746                                 {
747                                         ".aas",
748                                         "_b0.aas",
749                                         "_b1.aas",
750                                         NULL
751                                 };
752         
753         
754         /* arg checking */
755         if( argc < 2 )
756         {
757                 Sys_Printf( "Usage: q3map -fixaas [-v] <mapname>\n" );
758                 return 0;
759         }
760         
761         /* do some path mangling */
762         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
763         StripExtension( source );
764         DefaultExtension( source, ".bsp" );
765         
766         /* note it */
767         Sys_Printf( "--- FixAAS ---\n" );
768         
769         /* load the bsp */
770         Sys_Printf( "Loading %s\n", source );
771         length = LoadFile( source, &buffer );
772         
773         /* create bsp checksum */
774         Sys_Printf( "Creating checksum...\n" );
775         checksum = LittleLong( MD4BlockChecksum( buffer, length ) );
776         
777         /* write checksum to aas */
778         ext = exts;
779         while( *ext )
780         {
781                 /* mangle name */
782                 strcpy( aas, source );
783                 StripExtension( aas );
784                 strcat( aas, *ext );
785                 Sys_Printf( "Trying %s\n", aas );
786                 ext++;
787                 
788                 /* fix it */
789                 file = fopen( aas, "r+b" );
790                 if( !file )
791                         continue;
792                 if( fwrite( &checksum, 4, 1, file ) != 1 )
793                         Error( "Error writing checksum to %s", aas );
794                 fclose( file );
795         }
796         
797         /* return to sender */
798         return 0;
799 }
800
801
802
803 /*
804 AnalyzeBSP() - ydnar
805 analyzes a Quake engine BSP file
806 */
807
808 typedef struct abspHeader_s
809 {
810         char                    ident[ 4 ];
811         int                             version;
812         
813         bspLump_t               lumps[ 1 ];     /* unknown size */
814 }
815 abspHeader_t;
816
817 typedef struct abspLumpTest_s
818 {
819         int                             radix, minCount;
820         char                    *name;
821 }
822 abspLumpTest_t;
823
824 int AnalyzeBSP( int argc, char **argv )
825 {
826         abspHeader_t                    *header;
827         int                                             size, i, version, offset, length, lumpInt, count;
828         char                                    ident[ 5 ];
829         void                                    *lump;
830         float                                   lumpFloat;
831         char                                    lumpString[ 1024 ], source[ 1024 ];
832         qboolean                                lumpSwap = qfalse;
833         abspLumpTest_t                  *lumpTest;
834         static abspLumpTest_t   lumpTests[] =
835                                                         {
836                                                                 { sizeof( bspPlane_t ),                 6,              "IBSP LUMP_PLANES" },
837                                                                 { sizeof( bspBrush_t ),                 1,              "IBSP LUMP_BRUSHES" },
838                                                                 { 8,                                                    6,              "IBSP LUMP_BRUSHSIDES" },
839                                                                 { sizeof( bspBrushSide_t ),             6,              "RBSP LUMP_BRUSHSIDES" },
840                                                                 { sizeof( bspModel_t ),                 1,              "IBSP LUMP_MODELS" },
841                                                                 { sizeof( bspNode_t ),                  2,              "IBSP LUMP_NODES" },
842                                                                 { sizeof( bspLeaf_t ),                  1,              "IBSP LUMP_LEAFS" },
843                                                                 { 104,                                                  3,              "IBSP LUMP_DRAWSURFS" },
844                                                                 { 44,                                                   3,              "IBSP LUMP_DRAWVERTS" },
845                                                                 { 4,                                                    6,              "IBSP LUMP_DRAWINDEXES" },
846                                                                 { 128 * 128 * 3,                                1,              "IBSP LUMP_LIGHTMAPS" },
847                                                                 { 256 * 256 * 3,                                1,              "IBSP LUMP_LIGHTMAPS (256 x 256)" },
848                                                                 { 512 * 512 * 3,                                1,              "IBSP LUMP_LIGHTMAPS (512 x 512)" },
849                                                                 { 0, 0, NULL }
850                                                         };
851         
852         
853         /* arg checking */
854         if( argc < 1 )
855         {
856                 Sys_Printf( "Usage: q3map -analyze [-lumpswap] [-v] <mapname>\n" );
857                 return 0;
858         }
859         
860         /* process arguments */
861         for( i = 1; i < (argc - 1); i++ )
862         {
863                 /* -format map|ase|... */
864                 if( !strcmp( argv[ i ],  "-lumpswap" ) )
865                 {
866                         Sys_Printf( "Swapped lump structs enabled\n" );
867                         lumpSwap = qtrue;
868                 }
869         }
870         
871         /* clean up map name */
872         strcpy( source, ExpandArg( argv[ i ] ) );
873         Sys_Printf( "Loading %s\n", source );
874         
875         /* load the file */
876         size = LoadFile( source, (void**) &header );
877         if( size == 0 || header == NULL )
878         {
879                 Sys_Printf( "Unable to load %s.\n", source );
880                 return -1;
881         }
882         
883         /* analyze ident/version */
884         memcpy( ident, header->ident, 4 );
885         ident[ 4 ] = '\0';
886         version = LittleLong( header->version );
887         
888         Sys_Printf( "Identity:      %s\n", ident );
889         Sys_Printf( "Version:       %d\n", version );
890         Sys_Printf( "---------------------------------------\n" );
891         
892         /* analyze each lump */
893         for( i = 0; i < 100; i++ )
894         {
895                 /* call of duty swapped lump pairs */
896                 if( lumpSwap )
897                 {
898                         offset = LittleLong( header->lumps[ i ].length );
899                         length = LittleLong( header->lumps[ i ].offset );
900                 }
901                 
902                 /* standard lump pairs */
903                 else
904                 {
905                         offset = LittleLong( header->lumps[ i ].offset );
906                         length = LittleLong( header->lumps[ i ].length );
907                 }
908                 
909                 /* extract data */
910                 lump = (byte*) header + offset;
911                 lumpInt = LittleLong( (int) *((int*) lump) );
912                 lumpFloat = LittleFloat( (float) *((float*) lump) );
913                 memcpy( lumpString, (char*) lump, (length < 1024 ? length : 1024) );
914                 lumpString[ 1024 ] = '\0';
915                 
916                 /* print basic lump info */
917                 Sys_Printf( "Lump:          %d\n", i );
918                 Sys_Printf( "Offset:        %d bytes\n", offset );
919                 Sys_Printf( "Length:        %d bytes\n", length );
920                 
921                 /* only operate on valid lumps */
922                 if( length > 0 )
923                 {
924                         /* print data in 4 formats */
925                         Sys_Printf( "As hex:        %08X\n", lumpInt );
926                         Sys_Printf( "As int:        %d\n", lumpInt );
927                         Sys_Printf( "As float:      %f\n", lumpFloat );
928                         Sys_Printf( "As string:     %s\n", lumpString );
929                         
930                         /* guess lump type */
931                         if( lumpString[ 0 ] == '{' && lumpString[ 2 ] == '"' )
932                                 Sys_Printf( "Type guess:    IBSP LUMP_ENTITIES\n" );
933                         else if( strstr( lumpString, "textures/" ) )
934                                 Sys_Printf( "Type guess:    IBSP LUMP_SHADERS\n" );
935                         else
936                         {
937                                 /* guess based on size/count */
938                                 for( lumpTest = lumpTests; lumpTest->radix > 0; lumpTest++ )
939                                 {
940                                         if( (length % lumpTest->radix) != 0 )
941                                                 continue;
942                                         count = length / lumpTest->radix;
943                                         if( count < lumpTest->minCount )
944                                                 continue;
945                                         Sys_Printf( "Type guess:    %s (%d x %d)\n", lumpTest->name, count, lumpTest->radix );
946                                 }
947                         }
948                 }
949                 
950                 Sys_Printf( "---------------------------------------\n" );
951                 
952                 /* end of file */
953                 if( offset + length >= size )
954                         break;
955         }
956         
957         /* last stats */
958         Sys_Printf( "Lump count:    %d\n", i + 1 );
959         Sys_Printf( "File size:     %d bytes\n", size );
960         
961         /* return to caller */
962         return 0;
963 }
964
965
966
967 /*
968 BSPInfo()
969 emits statistics about the bsp file
970 */
971
972 int BSPInfo( int count, char **fileNames )
973 {
974         int                     i;
975         char            source[ 1024 ], ext[ 64 ];
976         int                     size;
977         FILE            *f;
978         
979         
980         /* dummy check */
981         if( count < 1 )
982         {
983                 Sys_Printf( "No files to dump info for.\n");
984                 return -1;
985         }
986         
987         /* enable info mode */
988         infoMode = qtrue;
989         
990         /* walk file list */
991         for( i = 0; i < count; i++ )
992         {
993                 Sys_Printf( "---------------------------------\n" );
994                 
995                 /* mangle filename and get size */
996                 strcpy( source, fileNames[ i ] );
997                 ExtractFileExtension( source, ext );
998                 if( !Q_stricmp( ext, "map" ) )
999                         StripExtension( source );
1000                 DefaultExtension( source, ".bsp" );
1001                 f = fopen( source, "rb" );
1002                 if( f )
1003                 {
1004                         size = Q_filelength (f);
1005                         fclose( f );
1006                 }
1007                 else
1008                         size = 0;
1009                 
1010                 /* load the bsp file and print lump sizes */
1011                 Sys_Printf( "%s\n", source );
1012                 LoadBSPFile( source );          
1013                 PrintBSPFileSizes();
1014                 
1015                 /* print sizes */
1016                 Sys_Printf( "\n" );
1017                 Sys_Printf( "          total         %9d\n", size );
1018                 Sys_Printf( "                        %9d KB\n", size / 1024 );
1019                 Sys_Printf( "                        %9d MB\n", size / (1024 * 1024) );
1020                 
1021                 Sys_Printf( "---------------------------------\n" );
1022         }
1023         
1024         /* return count */
1025         return i;
1026 }
1027
1028
1029 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)
1030 {
1031         vec4_t scoeffs, tcoeffs;
1032         float md;
1033         m4x4_t solvematrix;
1034
1035         vec3_t norm;
1036         vec3_t dab, dac;
1037         VectorSubtract(bxyz, axyz, dab);
1038         VectorSubtract(cxyz, axyz, dac);
1039         CrossProduct(dab, dac, norm);
1040         
1041         // assume:
1042         //   s = f(x, y, z)
1043         //   s(v + norm) = s(v) when n ortho xyz
1044         
1045         // s(v) = DotProduct(v, scoeffs) + scoeffs[3]
1046
1047         // solve:
1048         //   scoeffs * (axyz, 1) == ast[0]
1049         //   scoeffs * (bxyz, 1) == bst[0]
1050         //   scoeffs * (cxyz, 1) == cst[0]
1051         //   scoeffs * (norm, 0) == 0
1052         // scoeffs * [axyz, 1 | bxyz, 1 | cxyz, 1 | norm, 0] = [ast[0], bst[0], cst[0], 0]
1053         solvematrix[0] = axyz[0];
1054         solvematrix[4] = axyz[1];
1055         solvematrix[8] = axyz[2];
1056         solvematrix[12] = 1;
1057         solvematrix[1] = bxyz[0];
1058         solvematrix[5] = bxyz[1];
1059         solvematrix[9] = bxyz[2];
1060         solvematrix[13] = 1;
1061         solvematrix[2] = cxyz[0];
1062         solvematrix[6] = cxyz[1];
1063         solvematrix[10] = cxyz[2];
1064         solvematrix[14] = 1;
1065         solvematrix[3] = norm[0];
1066         solvematrix[7] = norm[1];
1067         solvematrix[11] = norm[2];
1068         solvematrix[15] = 0;
1069
1070         md = m4_det(solvematrix);
1071         if(md*md < 1e-10)
1072         {
1073                 Sys_Printf("Cannot invert some matrix, some texcoords aren't extrapolated!");
1074                 return;
1075         }
1076
1077         m4x4_invert(solvematrix);
1078
1079         scoeffs[0] = ast[0];
1080         scoeffs[1] = bst[0];
1081         scoeffs[2] = cst[0];
1082         scoeffs[3] = 0;
1083         m4x4_transform_vec4(solvematrix, scoeffs);
1084         tcoeffs[0] = ast[1];
1085         tcoeffs[1] = bst[1];
1086         tcoeffs[2] = cst[1];
1087         tcoeffs[3] = 0;
1088         m4x4_transform_vec4(solvematrix, tcoeffs);
1089
1090         ast_out[0] = scoeffs[0] * axyz_new[0] + scoeffs[1] * axyz_new[1] + scoeffs[2] * axyz_new[2] + scoeffs[3];
1091         ast_out[1] = tcoeffs[0] * axyz_new[0] + tcoeffs[1] * axyz_new[1] + tcoeffs[2] * axyz_new[2] + tcoeffs[3];
1092         bst_out[0] = scoeffs[0] * bxyz_new[0] + scoeffs[1] * bxyz_new[1] + scoeffs[2] * bxyz_new[2] + scoeffs[3];
1093         bst_out[1] = tcoeffs[0] * bxyz_new[0] + tcoeffs[1] * bxyz_new[1] + tcoeffs[2] * bxyz_new[2] + tcoeffs[3];
1094         cst_out[0] = scoeffs[0] * cxyz_new[0] + scoeffs[1] * cxyz_new[1] + scoeffs[2] * cxyz_new[2] + scoeffs[3];
1095         cst_out[1] = tcoeffs[0] * cxyz_new[0] + tcoeffs[1] * cxyz_new[1] + tcoeffs[2] * cxyz_new[2] + tcoeffs[3];
1096 }
1097
1098 /*
1099 ScaleBSPMain()
1100 amaze and confuse your enemies with wierd scaled maps!
1101 */
1102
1103 int ScaleBSPMain( int argc, char **argv )
1104 {
1105         int                     i, j;
1106         float           f, a;
1107         vec3_t scale;
1108         vec3_t          vec;
1109         char            str[ 1024 ];
1110         int uniform, axis;
1111         qboolean texscale;
1112         float *old_xyzst = NULL;
1113         
1114         
1115         /* arg checking */
1116         if( argc < 3 )
1117         {
1118                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] <value> <mapname>\n" );
1119                 return 0;
1120         }
1121         
1122         /* get scale */
1123         scale[2] = scale[1] = scale[0] = atof( argv[ argc - 2 ] );
1124         if(argc >= 4)
1125                 scale[1] = scale[0] = atof( argv[ argc - 3 ] );
1126         if(argc >= 5)
1127                 scale[0] = atof( argv[ argc - 4 ] );
1128
1129         texscale = !strcmp(argv[1], "-tex");
1130         
1131         uniform = ((scale[0] == scale[1]) && (scale[1] == scale[2]));
1132
1133         if( scale[0] == 0.0f || scale[1] == 0.0f || scale[2] == 0.0f )
1134         {
1135                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] <value> <mapname>\n" );
1136                 Sys_Printf( "Non-zero scale value required.\n" );
1137                 return 0;
1138         }
1139         
1140         /* do some path mangling */
1141         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
1142         StripExtension( source );
1143         DefaultExtension( source, ".bsp" );
1144         
1145         /* load the bsp */
1146         Sys_Printf( "Loading %s\n", source );
1147         LoadBSPFile( source );
1148         ParseEntities();
1149         
1150         /* note it */
1151         Sys_Printf( "--- ScaleBSP ---\n" );
1152         Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities );
1153         
1154         /* scale entity keys */
1155         for( i = 0; i < numBSPEntities && i < numEntities; i++ )
1156         {
1157                 /* scale origin */
1158                 GetVectorForKey( &entities[ i ], "origin", vec );
1159                 if( (vec[ 0 ] || vec[ 1 ] || vec[ 2 ]) )
1160                 {
1161                         vec[0] *= scale[0];
1162                         vec[1] *= scale[1];
1163                         vec[2] *= scale[2];
1164                         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1165                         SetKeyValue( &entities[ i ], "origin", str );
1166                 }
1167
1168                 a = FloatForKey( &entities[ i ], "angle" );
1169                 if(a == -1 || a == -2) // z scale
1170                         axis = 2;
1171                 else if(fabs(sin(DEG2RAD(a))) < 0.707)
1172                         axis = 0;
1173                 else
1174                         axis = 1;
1175                 
1176                 /* scale door lip */
1177                 f = FloatForKey( &entities[ i ], "lip" );
1178                 if( f )
1179                 {
1180                         f *= scale[axis];
1181                         sprintf( str, "%f", f );
1182                         SetKeyValue( &entities[ i ], "lip", str );
1183                 }
1184                 
1185                 /* scale plat height */
1186                 f = FloatForKey( &entities[ i ], "height" );
1187                 if( f )
1188                 {
1189                         f *= scale[2];
1190                         sprintf( str, "%f", f );
1191                         SetKeyValue( &entities[ i ], "height", str );
1192                 }
1193
1194                 // TODO maybe allow a definition file for entities to specify which values are scaled how?
1195         }
1196         
1197         /* scale models */
1198         for( i = 0; i < numBSPModels; i++ )
1199         {
1200                 bspModels[ i ].mins[0] *= scale[0];
1201                 bspModels[ i ].mins[1] *= scale[1];
1202                 bspModels[ i ].mins[2] *= scale[2];
1203                 bspModels[ i ].maxs[0] *= scale[0];
1204                 bspModels[ i ].maxs[1] *= scale[1];
1205                 bspModels[ i ].maxs[2] *= scale[2];
1206         }
1207         
1208         /* scale nodes */
1209         for( i = 0; i < numBSPNodes; i++ )
1210         {
1211                 bspNodes[ i ].mins[0] *= scale[0];
1212                 bspNodes[ i ].mins[1] *= scale[1];
1213                 bspNodes[ i ].mins[2] *= scale[2];
1214                 bspNodes[ i ].maxs[0] *= scale[0];
1215                 bspNodes[ i ].maxs[1] *= scale[1];
1216                 bspNodes[ i ].maxs[2] *= scale[2];
1217         }
1218         
1219         /* scale leafs */
1220         for( i = 0; i < numBSPLeafs; i++ )
1221         {
1222                 bspLeafs[ i ].mins[0] *= scale[0];
1223                 bspLeafs[ i ].mins[1] *= scale[1];
1224                 bspLeafs[ i ].mins[2] *= scale[2];
1225                 bspLeafs[ i ].maxs[0] *= scale[0];
1226                 bspLeafs[ i ].maxs[1] *= scale[1];
1227                 bspLeafs[ i ].maxs[2] *= scale[2];
1228         }
1229         
1230         if(texscale)
1231         {
1232                 Sys_Printf("Using texture unlocking (and probably breaking texture alignment a lot)\n");
1233                 old_xyzst = safe_malloc(sizeof(*old_xyzst) * numBSPDrawVerts * 5);
1234                 for(i = 0; i < numBSPDrawVerts; i++)
1235                 {
1236                         old_xyzst[5*i+0] = bspDrawVerts[i].xyz[0];
1237                         old_xyzst[5*i+1] = bspDrawVerts[i].xyz[1];
1238                         old_xyzst[5*i+2] = bspDrawVerts[i].xyz[2];
1239                         old_xyzst[5*i+3] = bspDrawVerts[i].st[0];
1240                         old_xyzst[5*i+4] = bspDrawVerts[i].st[1];
1241                 }
1242         }
1243
1244         /* scale drawverts */
1245         for( i = 0; i < numBSPDrawVerts; i++ )
1246         {
1247                 bspDrawVerts[i].xyz[0] *= scale[0];
1248                 bspDrawVerts[i].xyz[1] *= scale[1];
1249                 bspDrawVerts[i].xyz[2] *= scale[2];
1250                 bspDrawVerts[i].normal[0] /= scale[0];
1251                 bspDrawVerts[i].normal[1] /= scale[1];
1252                 bspDrawVerts[i].normal[2] /= scale[2];
1253                 VectorNormalize(bspDrawVerts[i].normal, bspDrawVerts[i].normal);
1254         }
1255
1256         if(texscale)
1257         {
1258                 for(i = 0; i < numBSPDrawSurfaces; i++)
1259                 {
1260                         switch(bspDrawSurfaces[i].surfaceType)
1261                         {
1262                                 case SURFACE_FACE:
1263                                 case SURFACE_META:
1264                                         if(bspDrawSurfaces[i].numIndexes % 3)
1265                                                 Error("Not a triangulation!");
1266                                         for(j = bspDrawSurfaces[i].firstIndex; j < bspDrawSurfaces[i].firstIndex + bspDrawSurfaces[i].numIndexes; j += 3)
1267                                         {
1268                                                 int ia = bspDrawIndexes[j] + bspDrawSurfaces[i].firstVert, ib = bspDrawIndexes[j+1] + bspDrawSurfaces[i].firstVert, ic = bspDrawIndexes[j+2] + bspDrawSurfaces[i].firstVert;
1269                                                 bspDrawVert_t *a = &bspDrawVerts[ia], *b = &bspDrawVerts[ib], *c = &bspDrawVerts[ic];
1270                                                 float *oa = &old_xyzst[ia*5], *ob = &old_xyzst[ib*5], *oc = &old_xyzst[ic*5];
1271                                                 // extrapolate:
1272                                                 //   a->xyz -> oa
1273                                                 //   b->xyz -> ob
1274                                                 //   c->xyz -> oc
1275                                                 ExtrapolateTexcoords(
1276                                                         &oa[0], &oa[3],
1277                                                         &ob[0], &ob[3],
1278                                                         &oc[0], &oc[3],
1279                                                         a->xyz, a->st,
1280                                                         b->xyz, b->st,
1281                                                         c->xyz, c->st);
1282                                         }
1283                                         break;
1284                         }
1285                 }
1286         }
1287         
1288         /* scale planes */
1289         if(uniform)
1290         {
1291                 for( i = 0; i < numBSPPlanes; i++ )
1292                 {
1293                         bspPlanes[ i ].dist *= scale[0];
1294                 }
1295         }
1296         else
1297         {
1298                 for( i = 0; i < numBSPPlanes; i++ )
1299                 {
1300                         bspPlanes[ i ].normal[0] /= scale[0];
1301                         bspPlanes[ i ].normal[1] /= scale[1];
1302                         bspPlanes[ i ].normal[2] /= scale[2];
1303                         f = 1/VectorLength(bspPlanes[i].normal);
1304                         VectorScale(bspPlanes[i].normal, f, bspPlanes[i].normal);
1305                         bspPlanes[ i ].dist *= f;
1306                 }
1307         }
1308         
1309         /* scale gridsize */
1310         GetVectorForKey( &entities[ 0 ], "gridsize", vec );
1311         if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) == 0.0f )
1312                 VectorCopy( gridSize, vec );
1313         vec[0] *= scale[0];
1314         vec[1] *= scale[1];
1315         vec[2] *= scale[2];
1316         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1317         SetKeyValue( &entities[ 0 ], "gridsize", str );
1318
1319         /* inject command line parameters */
1320         InjectCommandLine(argv, 0, argc - 1);
1321         
1322         /* write the bsp */
1323         UnparseEntities();
1324         StripExtension( source );
1325         DefaultExtension( source, "_s.bsp" );
1326         Sys_Printf( "Writing %s\n", source );
1327         WriteBSPFile( source );
1328         
1329         /* return to sender */
1330         return 0;
1331 }
1332
1333
1334
1335 /*
1336 ConvertBSPMain()
1337 main argument processing function for bsp conversion
1338 */
1339
1340 int ConvertBSPMain( int argc, char **argv )
1341 {
1342         int             i;
1343         int             (*convertFunc)( char * );
1344         game_t  *convertGame;
1345         
1346         
1347         /* set default */
1348         convertFunc = ConvertBSPToASE;
1349         convertGame = NULL;
1350         
1351         /* arg checking */
1352         if( argc < 1 )
1353         {
1354                 Sys_Printf( "Usage: q3map -scale <value> [-v] <mapname>\n" );
1355                 return 0;
1356         }
1357         
1358         /* process arguments */
1359         for( i = 1; i < (argc - 1); i++ )
1360         {
1361                 /* -format map|ase|... */
1362                 if( !strcmp( argv[ i ],  "-format" ) )
1363                 {
1364                         i++;
1365                         if( !Q_stricmp( argv[ i ], "ase" ) )
1366                                 convertFunc = ConvertBSPToASE;
1367                         else if( !Q_stricmp( argv[ i ], "map" ) )
1368                                 convertFunc = ConvertBSPToMap;
1369                         else
1370                         {
1371                                 convertGame = GetGame( argv[ i ] );
1372                                 if( convertGame == NULL )
1373                                         Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] );
1374                         }
1375                 }
1376                 else if( !strcmp( argv[ i ],  "-ne" ) )
1377                 {
1378                         normalEpsilon = atof( argv[ i + 1 ] );
1379                         i++;
1380                         Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon );
1381                 }
1382                 else if( !strcmp( argv[ i ],  "-de" ) )
1383                 {
1384                         distanceEpsilon = atof( argv[ i + 1 ] );
1385                         i++;
1386                         Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon );
1387                 }
1388                 else if( !strcmp( argv[ i ],  "-shadersasbitmap" ) )
1389                         shadersAsBitmap = qtrue;
1390         }
1391         
1392         /* clean up map name */
1393         strcpy( source, ExpandArg( argv[ i ] ) );
1394         StripExtension( source );
1395         DefaultExtension( source, ".bsp" );
1396         
1397         LoadShaderInfo();
1398         
1399         Sys_Printf( "Loading %s\n", source );
1400         
1401         /* ydnar: load surface file */
1402         //%     LoadSurfaceExtraFile( source );
1403         
1404         LoadBSPFile( source );
1405         
1406         /* parse bsp entities */
1407         ParseEntities();
1408         
1409         /* bsp format convert? */
1410         if( convertGame != NULL )
1411         {
1412                 /* set global game */
1413                 game = convertGame;
1414                 
1415                 /* write bsp */
1416                 StripExtension( source );
1417                 DefaultExtension( source, "_c.bsp" );
1418                 Sys_Printf( "Writing %s\n", source );
1419                 WriteBSPFile( source );
1420                 
1421                 /* return to sender */
1422                 return 0;
1423         }
1424         
1425         /* normal convert */
1426         return convertFunc( source );
1427 }
1428
1429
1430
1431 /*
1432 main()
1433 q3map mojo...
1434 */
1435
1436 int main( int argc, char **argv )
1437 {
1438         int             i, r;
1439         double  start, end;
1440         
1441         
1442         /* we want consistent 'randomness' */
1443         srand( 0 );
1444         
1445         /* start timer */
1446         start = I_FloatTime();
1447
1448         /* this was changed to emit version number over the network */
1449         printf( Q3MAP_VERSION "\n" );
1450         
1451         /* set exit call */
1452         atexit( ExitQ3Map );
1453
1454         /* read general options first */
1455         for( i = 1; i < argc; i++ )
1456         {
1457                 /* -connect */
1458                 if( !strcmp( argv[ i ], "-connect" ) )
1459                 {
1460                         argv[ i ] = NULL;
1461                         i++;
1462                         Broadcast_Setup( argv[ i ] );
1463                         argv[ i ] = NULL;
1464                 }
1465                 
1466                 /* verbose */
1467                 else if( !strcmp( argv[ i ], "-v" ) )
1468                 {
1469                         if(!verbose)
1470                         {
1471                                 verbose = qtrue;
1472                                 argv[ i ] = NULL;
1473                         }
1474                 }
1475                 
1476                 /* force */
1477                 else if( !strcmp( argv[ i ], "-force" ) )
1478                 {
1479                         force = qtrue;
1480                         argv[ i ] = NULL;
1481                 }
1482                 
1483                 /* patch subdivisions */
1484                 else if( !strcmp( argv[ i ], "-subdivisions" ) )
1485                 {
1486                         argv[ i ] = NULL;
1487                         i++;
1488                         patchSubdivisions = atoi( argv[ i ] );
1489                         argv[ i ] = NULL;
1490                         if( patchSubdivisions <= 0 )
1491                                 patchSubdivisions = 1;
1492                 }
1493                 
1494                 /* threads */
1495                 else if( !strcmp( argv[ i ], "-threads" ) )
1496                 {
1497                         argv[ i ] = NULL;
1498                         i++;
1499                         numthreads = atoi( argv[ i ] );
1500                         argv[ i ] = NULL;
1501                 }
1502         }
1503         
1504         /* init model library */
1505         PicoInit();
1506         PicoSetMallocFunc( safe_malloc );
1507         PicoSetFreeFunc( free );
1508         PicoSetPrintFunc( PicoPrintFunc );
1509         PicoSetLoadFileFunc( PicoLoadFileFunc );
1510         PicoSetFreeFileFunc( free );
1511         
1512         /* set number of threads */
1513         ThreadSetDefault();
1514         
1515         /* generate sinusoid jitter table */
1516         for( i = 0; i < MAX_JITTERS; i++ )
1517         {
1518                 jitters[ i ] = sin( i * 139.54152147 );
1519                 //%     Sys_Printf( "Jitter %4d: %f\n", i, jitters[ i ] );
1520         }
1521         
1522         /* we print out two versions, q3map's main version (since it evolves a bit out of GtkRadiant)
1523            and we put the GtkRadiant version to make it easy to track with what version of Radiant it was built with */
1524         
1525         Sys_Printf( "Q3Map         - v1.0r (c) 1999 Id Software Inc.\n" );
1526         Sys_Printf( "Q3Map (ydnar) - v" Q3MAP_VERSION "\n" );
1527         Sys_Printf( "NetRadiant    - v" RADIANT_VERSION " " __DATE__ " " __TIME__ "\n" );
1528         Sys_Printf( "%s\n", Q3MAP_MOTD );
1529         
1530         /* ydnar: new path initialization */
1531         InitPaths( &argc, argv );
1532
1533         /* set game options */
1534         if (!patchSubdivisions)
1535                 patchSubdivisions = game->patchSubdivisions;
1536         
1537         /* check if we have enough options left to attempt something */
1538         if( argc < 2 )
1539                 Error( "Usage: %s [general options] [options] mapfile", argv[ 0 ] );
1540         
1541         /* fixaas */
1542         if( !strcmp( argv[ 1 ], "-fixaas" ) )
1543                 r = FixAAS( argc - 1, argv + 1 );
1544         
1545         /* analyze */
1546         else if( !strcmp( argv[ 1 ], "-analyze" ) )
1547                 r = AnalyzeBSP( argc - 1, argv + 1 );
1548         
1549         /* info */
1550         else if( !strcmp( argv[ 1 ], "-info" ) )
1551                 r = BSPInfo( argc - 2, argv + 2 );
1552         
1553         /* vis */
1554         else if( !strcmp( argv[ 1 ], "-vis" ) )
1555                 r = VisMain( argc - 1, argv + 1 );
1556         
1557         /* light */
1558         else if( !strcmp( argv[ 1 ], "-light" ) )
1559                 r = LightMain( argc - 1, argv + 1 );
1560         
1561         /* vlight */
1562         else if( !strcmp( argv[ 1 ], "-vlight" ) )
1563         {
1564                 Sys_Printf( "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" );
1565                 argv[ 1 ] = "-fast";    /* eek a hack */
1566                 r = LightMain( argc, argv );
1567         }
1568         
1569         /* ydnar: lightmap export */
1570         else if( !strcmp( argv[ 1 ], "-export" ) )
1571                 r = ExportLightmapsMain( argc - 1, argv + 1 );
1572         
1573         /* ydnar: lightmap import */
1574         else if( !strcmp( argv[ 1 ], "-import" ) )
1575                 r = ImportLightmapsMain( argc - 1, argv + 1 );
1576         
1577         /* ydnar: bsp scaling */
1578         else if( !strcmp( argv[ 1 ], "-scale" ) )
1579                 r = ScaleBSPMain( argc - 1, argv + 1 );
1580         
1581         /* ydnar: bsp conversion */
1582         else if( !strcmp( argv[ 1 ], "-convert" ) )
1583                 r = ConvertBSPMain( argc - 1, argv + 1 );
1584         
1585         /* div0: minimap */
1586         else if( !strcmp( argv[ 1 ], "-minimap" ) )
1587                 r = MiniMapBSPMain(argc - 1, argv + 1);
1588
1589         /* ydnar: otherwise create a bsp */
1590         else
1591                 r = BSPMain( argc, argv );
1592         
1593         /* emit time */
1594         end = I_FloatTime();
1595         Sys_Printf( "%9.0f seconds elapsed\n", end - start );
1596         
1597         /* shut down connection */
1598         Broadcast_Shutdown();
1599         
1600         /* return any error code */
1601         return r;
1602 }