]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/q3map2/main.c
allow not keeping aspect
[xonotic/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         WriteTGA24(minimapFilename, data3b, minimap.width, minimap.height, qfalse);
711
712         Sys_Printf( " done.\n" );
713
714         /* return to sender */
715         return 0;
716 }
717
718
719
720
721
722 /*
723 MD4BlockChecksum()
724 calculates an md4 checksum for a block of data
725 */
726
727 static int MD4BlockChecksum( void *buffer, int length )
728 {
729         return Com_BlockChecksum(buffer, length);
730 }
731
732 /*
733 FixAAS()
734 resets an aas checksum to match the given BSP
735 */
736
737 int FixAAS( int argc, char **argv )
738 {
739         int                     length, checksum;
740         void            *buffer;
741         FILE            *file;
742         char            aas[ 1024 ], **ext;
743         char            *exts[] =
744                                 {
745                                         ".aas",
746                                         "_b0.aas",
747                                         "_b1.aas",
748                                         NULL
749                                 };
750         
751         
752         /* arg checking */
753         if( argc < 2 )
754         {
755                 Sys_Printf( "Usage: q3map -fixaas [-v] <mapname>\n" );
756                 return 0;
757         }
758         
759         /* do some path mangling */
760         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
761         StripExtension( source );
762         DefaultExtension( source, ".bsp" );
763         
764         /* note it */
765         Sys_Printf( "--- FixAAS ---\n" );
766         
767         /* load the bsp */
768         Sys_Printf( "Loading %s\n", source );
769         length = LoadFile( source, &buffer );
770         
771         /* create bsp checksum */
772         Sys_Printf( "Creating checksum...\n" );
773         checksum = LittleLong( MD4BlockChecksum( buffer, length ) );
774         
775         /* write checksum to aas */
776         ext = exts;
777         while( *ext )
778         {
779                 /* mangle name */
780                 strcpy( aas, source );
781                 StripExtension( aas );
782                 strcat( aas, *ext );
783                 Sys_Printf( "Trying %s\n", aas );
784                 ext++;
785                 
786                 /* fix it */
787                 file = fopen( aas, "r+b" );
788                 if( !file )
789                         continue;
790                 if( fwrite( &checksum, 4, 1, file ) != 1 )
791                         Error( "Error writing checksum to %s", aas );
792                 fclose( file );
793         }
794         
795         /* return to sender */
796         return 0;
797 }
798
799
800
801 /*
802 AnalyzeBSP() - ydnar
803 analyzes a Quake engine BSP file
804 */
805
806 typedef struct abspHeader_s
807 {
808         char                    ident[ 4 ];
809         int                             version;
810         
811         bspLump_t               lumps[ 1 ];     /* unknown size */
812 }
813 abspHeader_t;
814
815 typedef struct abspLumpTest_s
816 {
817         int                             radix, minCount;
818         char                    *name;
819 }
820 abspLumpTest_t;
821
822 int AnalyzeBSP( int argc, char **argv )
823 {
824         abspHeader_t                    *header;
825         int                                             size, i, version, offset, length, lumpInt, count;
826         char                                    ident[ 5 ];
827         void                                    *lump;
828         float                                   lumpFloat;
829         char                                    lumpString[ 1024 ], source[ 1024 ];
830         qboolean                                lumpSwap = qfalse;
831         abspLumpTest_t                  *lumpTest;
832         static abspLumpTest_t   lumpTests[] =
833                                                         {
834                                                                 { sizeof( bspPlane_t ),                 6,              "IBSP LUMP_PLANES" },
835                                                                 { sizeof( bspBrush_t ),                 1,              "IBSP LUMP_BRUSHES" },
836                                                                 { 8,                                                    6,              "IBSP LUMP_BRUSHSIDES" },
837                                                                 { sizeof( bspBrushSide_t ),             6,              "RBSP LUMP_BRUSHSIDES" },
838                                                                 { sizeof( bspModel_t ),                 1,              "IBSP LUMP_MODELS" },
839                                                                 { sizeof( bspNode_t ),                  2,              "IBSP LUMP_NODES" },
840                                                                 { sizeof( bspLeaf_t ),                  1,              "IBSP LUMP_LEAFS" },
841                                                                 { 104,                                                  3,              "IBSP LUMP_DRAWSURFS" },
842                                                                 { 44,                                                   3,              "IBSP LUMP_DRAWVERTS" },
843                                                                 { 4,                                                    6,              "IBSP LUMP_DRAWINDEXES" },
844                                                                 { 128 * 128 * 3,                                1,              "IBSP LUMP_LIGHTMAPS" },
845                                                                 { 256 * 256 * 3,                                1,              "IBSP LUMP_LIGHTMAPS (256 x 256)" },
846                                                                 { 512 * 512 * 3,                                1,              "IBSP LUMP_LIGHTMAPS (512 x 512)" },
847                                                                 { 0, 0, NULL }
848                                                         };
849         
850         
851         /* arg checking */
852         if( argc < 1 )
853         {
854                 Sys_Printf( "Usage: q3map -analyze [-lumpswap] [-v] <mapname>\n" );
855                 return 0;
856         }
857         
858         /* process arguments */
859         for( i = 1; i < (argc - 1); i++ )
860         {
861                 /* -format map|ase|... */
862                 if( !strcmp( argv[ i ],  "-lumpswap" ) )
863                 {
864                         Sys_Printf( "Swapped lump structs enabled\n" );
865                         lumpSwap = qtrue;
866                 }
867         }
868         
869         /* clean up map name */
870         strcpy( source, ExpandArg( argv[ i ] ) );
871         Sys_Printf( "Loading %s\n", source );
872         
873         /* load the file */
874         size = LoadFile( source, (void**) &header );
875         if( size == 0 || header == NULL )
876         {
877                 Sys_Printf( "Unable to load %s.\n", source );
878                 return -1;
879         }
880         
881         /* analyze ident/version */
882         memcpy( ident, header->ident, 4 );
883         ident[ 4 ] = '\0';
884         version = LittleLong( header->version );
885         
886         Sys_Printf( "Identity:      %s\n", ident );
887         Sys_Printf( "Version:       %d\n", version );
888         Sys_Printf( "---------------------------------------\n" );
889         
890         /* analyze each lump */
891         for( i = 0; i < 100; i++ )
892         {
893                 /* call of duty swapped lump pairs */
894                 if( lumpSwap )
895                 {
896                         offset = LittleLong( header->lumps[ i ].length );
897                         length = LittleLong( header->lumps[ i ].offset );
898                 }
899                 
900                 /* standard lump pairs */
901                 else
902                 {
903                         offset = LittleLong( header->lumps[ i ].offset );
904                         length = LittleLong( header->lumps[ i ].length );
905                 }
906                 
907                 /* extract data */
908                 lump = (byte*) header + offset;
909                 lumpInt = LittleLong( (int) *((int*) lump) );
910                 lumpFloat = LittleFloat( (float) *((float*) lump) );
911                 memcpy( lumpString, (char*) lump, (length < 1024 ? length : 1024) );
912                 lumpString[ 1024 ] = '\0';
913                 
914                 /* print basic lump info */
915                 Sys_Printf( "Lump:          %d\n", i );
916                 Sys_Printf( "Offset:        %d bytes\n", offset );
917                 Sys_Printf( "Length:        %d bytes\n", length );
918                 
919                 /* only operate on valid lumps */
920                 if( length > 0 )
921                 {
922                         /* print data in 4 formats */
923                         Sys_Printf( "As hex:        %08X\n", lumpInt );
924                         Sys_Printf( "As int:        %d\n", lumpInt );
925                         Sys_Printf( "As float:      %f\n", lumpFloat );
926                         Sys_Printf( "As string:     %s\n", lumpString );
927                         
928                         /* guess lump type */
929                         if( lumpString[ 0 ] == '{' && lumpString[ 2 ] == '"' )
930                                 Sys_Printf( "Type guess:    IBSP LUMP_ENTITIES\n" );
931                         else if( strstr( lumpString, "textures/" ) )
932                                 Sys_Printf( "Type guess:    IBSP LUMP_SHADERS\n" );
933                         else
934                         {
935                                 /* guess based on size/count */
936                                 for( lumpTest = lumpTests; lumpTest->radix > 0; lumpTest++ )
937                                 {
938                                         if( (length % lumpTest->radix) != 0 )
939                                                 continue;
940                                         count = length / lumpTest->radix;
941                                         if( count < lumpTest->minCount )
942                                                 continue;
943                                         Sys_Printf( "Type guess:    %s (%d x %d)\n", lumpTest->name, count, lumpTest->radix );
944                                 }
945                         }
946                 }
947                 
948                 Sys_Printf( "---------------------------------------\n" );
949                 
950                 /* end of file */
951                 if( offset + length >= size )
952                         break;
953         }
954         
955         /* last stats */
956         Sys_Printf( "Lump count:    %d\n", i + 1 );
957         Sys_Printf( "File size:     %d bytes\n", size );
958         
959         /* return to caller */
960         return 0;
961 }
962
963
964
965 /*
966 BSPInfo()
967 emits statistics about the bsp file
968 */
969
970 int BSPInfo( int count, char **fileNames )
971 {
972         int                     i;
973         char            source[ 1024 ], ext[ 64 ];
974         int                     size;
975         FILE            *f;
976         
977         
978         /* dummy check */
979         if( count < 1 )
980         {
981                 Sys_Printf( "No files to dump info for.\n");
982                 return -1;
983         }
984         
985         /* enable info mode */
986         infoMode = qtrue;
987         
988         /* walk file list */
989         for( i = 0; i < count; i++ )
990         {
991                 Sys_Printf( "---------------------------------\n" );
992                 
993                 /* mangle filename and get size */
994                 strcpy( source, fileNames[ i ] );
995                 ExtractFileExtension( source, ext );
996                 if( !Q_stricmp( ext, "map" ) )
997                         StripExtension( source );
998                 DefaultExtension( source, ".bsp" );
999                 f = fopen( source, "rb" );
1000                 if( f )
1001                 {
1002                         size = Q_filelength (f);
1003                         fclose( f );
1004                 }
1005                 else
1006                         size = 0;
1007                 
1008                 /* load the bsp file and print lump sizes */
1009                 Sys_Printf( "%s\n", source );
1010                 LoadBSPFile( source );          
1011                 PrintBSPFileSizes();
1012                 
1013                 /* print sizes */
1014                 Sys_Printf( "\n" );
1015                 Sys_Printf( "          total         %9d\n", size );
1016                 Sys_Printf( "                        %9d KB\n", size / 1024 );
1017                 Sys_Printf( "                        %9d MB\n", size / (1024 * 1024) );
1018                 
1019                 Sys_Printf( "---------------------------------\n" );
1020         }
1021         
1022         /* return count */
1023         return i;
1024 }
1025
1026
1027 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)
1028 {
1029         vec4_t scoeffs, tcoeffs;
1030         float md;
1031         m4x4_t solvematrix;
1032
1033         vec3_t norm;
1034         vec3_t dab, dac;
1035         VectorSubtract(bxyz, axyz, dab);
1036         VectorSubtract(cxyz, axyz, dac);
1037         CrossProduct(dab, dac, norm);
1038         
1039         // assume:
1040         //   s = f(x, y, z)
1041         //   s(v + norm) = s(v) when n ortho xyz
1042         
1043         // s(v) = DotProduct(v, scoeffs) + scoeffs[3]
1044
1045         // solve:
1046         //   scoeffs * (axyz, 1) == ast[0]
1047         //   scoeffs * (bxyz, 1) == bst[0]
1048         //   scoeffs * (cxyz, 1) == cst[0]
1049         //   scoeffs * (norm, 0) == 0
1050         // scoeffs * [axyz, 1 | bxyz, 1 | cxyz, 1 | norm, 0] = [ast[0], bst[0], cst[0], 0]
1051         solvematrix[0] = axyz[0];
1052         solvematrix[4] = axyz[1];
1053         solvematrix[8] = axyz[2];
1054         solvematrix[12] = 1;
1055         solvematrix[1] = bxyz[0];
1056         solvematrix[5] = bxyz[1];
1057         solvematrix[9] = bxyz[2];
1058         solvematrix[13] = 1;
1059         solvematrix[2] = cxyz[0];
1060         solvematrix[6] = cxyz[1];
1061         solvematrix[10] = cxyz[2];
1062         solvematrix[14] = 1;
1063         solvematrix[3] = norm[0];
1064         solvematrix[7] = norm[1];
1065         solvematrix[11] = norm[2];
1066         solvematrix[15] = 0;
1067
1068         md = m4_det(solvematrix);
1069         if(md*md < 1e-10)
1070         {
1071                 Sys_Printf("Cannot invert some matrix, some texcoords aren't extrapolated!");
1072                 return;
1073         }
1074
1075         m4x4_invert(solvematrix);
1076
1077         scoeffs[0] = ast[0];
1078         scoeffs[1] = bst[0];
1079         scoeffs[2] = cst[0];
1080         scoeffs[3] = 0;
1081         m4x4_transform_vec4(solvematrix, scoeffs);
1082         tcoeffs[0] = ast[1];
1083         tcoeffs[1] = bst[1];
1084         tcoeffs[2] = cst[1];
1085         tcoeffs[3] = 0;
1086         m4x4_transform_vec4(solvematrix, tcoeffs);
1087
1088         ast_out[0] = scoeffs[0] * axyz_new[0] + scoeffs[1] * axyz_new[1] + scoeffs[2] * axyz_new[2] + scoeffs[3];
1089         ast_out[1] = tcoeffs[0] * axyz_new[0] + tcoeffs[1] * axyz_new[1] + tcoeffs[2] * axyz_new[2] + tcoeffs[3];
1090         bst_out[0] = scoeffs[0] * bxyz_new[0] + scoeffs[1] * bxyz_new[1] + scoeffs[2] * bxyz_new[2] + scoeffs[3];
1091         bst_out[1] = tcoeffs[0] * bxyz_new[0] + tcoeffs[1] * bxyz_new[1] + tcoeffs[2] * bxyz_new[2] + tcoeffs[3];
1092         cst_out[0] = scoeffs[0] * cxyz_new[0] + scoeffs[1] * cxyz_new[1] + scoeffs[2] * cxyz_new[2] + scoeffs[3];
1093         cst_out[1] = tcoeffs[0] * cxyz_new[0] + tcoeffs[1] * cxyz_new[1] + tcoeffs[2] * cxyz_new[2] + tcoeffs[3];
1094 }
1095
1096 /*
1097 ScaleBSPMain()
1098 amaze and confuse your enemies with wierd scaled maps!
1099 */
1100
1101 int ScaleBSPMain( int argc, char **argv )
1102 {
1103         int                     i, j;
1104         float           f, a;
1105         vec3_t scale;
1106         vec3_t          vec;
1107         char            str[ 1024 ];
1108         int uniform, axis;
1109         qboolean texscale;
1110         float *old_xyzst = NULL;
1111         
1112         
1113         /* arg checking */
1114         if( argc < 3 )
1115         {
1116                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] <value> <mapname>\n" );
1117                 return 0;
1118         }
1119         
1120         /* get scale */
1121         scale[2] = scale[1] = scale[0] = atof( argv[ argc - 2 ] );
1122         if(argc >= 4)
1123                 scale[1] = scale[0] = atof( argv[ argc - 3 ] );
1124         if(argc >= 5)
1125                 scale[0] = atof( argv[ argc - 4 ] );
1126
1127         texscale = !strcmp(argv[1], "-tex");
1128         
1129         uniform = ((scale[0] == scale[1]) && (scale[1] == scale[2]));
1130
1131         if( scale[0] == 0.0f || scale[1] == 0.0f || scale[2] == 0.0f )
1132         {
1133                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] <value> <mapname>\n" );
1134                 Sys_Printf( "Non-zero scale value required.\n" );
1135                 return 0;
1136         }
1137         
1138         /* do some path mangling */
1139         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
1140         StripExtension( source );
1141         DefaultExtension( source, ".bsp" );
1142         
1143         /* load the bsp */
1144         Sys_Printf( "Loading %s\n", source );
1145         LoadBSPFile( source );
1146         ParseEntities();
1147         
1148         /* note it */
1149         Sys_Printf( "--- ScaleBSP ---\n" );
1150         Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities );
1151         
1152         /* scale entity keys */
1153         for( i = 0; i < numBSPEntities && i < numEntities; i++ )
1154         {
1155                 /* scale origin */
1156                 GetVectorForKey( &entities[ i ], "origin", vec );
1157                 if( (vec[ 0 ] || vec[ 1 ] || vec[ 2 ]) )
1158                 {
1159                         vec[0] *= scale[0];
1160                         vec[1] *= scale[1];
1161                         vec[2] *= scale[2];
1162                         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1163                         SetKeyValue( &entities[ i ], "origin", str );
1164                 }
1165
1166                 a = FloatForKey( &entities[ i ], "angle" );
1167                 if(a == -1 || a == -2) // z scale
1168                         axis = 2;
1169                 else if(fabs(sin(DEG2RAD(a))) < 0.707)
1170                         axis = 0;
1171                 else
1172                         axis = 1;
1173                 
1174                 /* scale door lip */
1175                 f = FloatForKey( &entities[ i ], "lip" );
1176                 if( f )
1177                 {
1178                         f *= scale[axis];
1179                         sprintf( str, "%f", f );
1180                         SetKeyValue( &entities[ i ], "lip", str );
1181                 }
1182                 
1183                 /* scale plat height */
1184                 f = FloatForKey( &entities[ i ], "height" );
1185                 if( f )
1186                 {
1187                         f *= scale[2];
1188                         sprintf( str, "%f", f );
1189                         SetKeyValue( &entities[ i ], "height", str );
1190                 }
1191
1192                 // TODO maybe allow a definition file for entities to specify which values are scaled how?
1193         }
1194         
1195         /* scale models */
1196         for( i = 0; i < numBSPModels; i++ )
1197         {
1198                 bspModels[ i ].mins[0] *= scale[0];
1199                 bspModels[ i ].mins[1] *= scale[1];
1200                 bspModels[ i ].mins[2] *= scale[2];
1201                 bspModels[ i ].maxs[0] *= scale[0];
1202                 bspModels[ i ].maxs[1] *= scale[1];
1203                 bspModels[ i ].maxs[2] *= scale[2];
1204         }
1205         
1206         /* scale nodes */
1207         for( i = 0; i < numBSPNodes; i++ )
1208         {
1209                 bspNodes[ i ].mins[0] *= scale[0];
1210                 bspNodes[ i ].mins[1] *= scale[1];
1211                 bspNodes[ i ].mins[2] *= scale[2];
1212                 bspNodes[ i ].maxs[0] *= scale[0];
1213                 bspNodes[ i ].maxs[1] *= scale[1];
1214                 bspNodes[ i ].maxs[2] *= scale[2];
1215         }
1216         
1217         /* scale leafs */
1218         for( i = 0; i < numBSPLeafs; i++ )
1219         {
1220                 bspLeafs[ i ].mins[0] *= scale[0];
1221                 bspLeafs[ i ].mins[1] *= scale[1];
1222                 bspLeafs[ i ].mins[2] *= scale[2];
1223                 bspLeafs[ i ].maxs[0] *= scale[0];
1224                 bspLeafs[ i ].maxs[1] *= scale[1];
1225                 bspLeafs[ i ].maxs[2] *= scale[2];
1226         }
1227         
1228         if(texscale)
1229         {
1230                 Sys_Printf("Using texture unlocking (and probably breaking texture alignment a lot)\n");
1231                 old_xyzst = safe_malloc(sizeof(*old_xyzst) * numBSPDrawVerts * 5);
1232                 for(i = 0; i < numBSPDrawVerts; i++)
1233                 {
1234                         old_xyzst[5*i+0] = bspDrawVerts[i].xyz[0];
1235                         old_xyzst[5*i+1] = bspDrawVerts[i].xyz[1];
1236                         old_xyzst[5*i+2] = bspDrawVerts[i].xyz[2];
1237                         old_xyzst[5*i+3] = bspDrawVerts[i].st[0];
1238                         old_xyzst[5*i+4] = bspDrawVerts[i].st[1];
1239                 }
1240         }
1241
1242         /* scale drawverts */
1243         for( i = 0; i < numBSPDrawVerts; i++ )
1244         {
1245                 bspDrawVerts[i].xyz[0] *= scale[0];
1246                 bspDrawVerts[i].xyz[1] *= scale[1];
1247                 bspDrawVerts[i].xyz[2] *= scale[2];
1248                 bspDrawVerts[i].normal[0] /= scale[0];
1249                 bspDrawVerts[i].normal[1] /= scale[1];
1250                 bspDrawVerts[i].normal[2] /= scale[2];
1251                 VectorNormalize(bspDrawVerts[i].normal, bspDrawVerts[i].normal);
1252         }
1253
1254         if(texscale)
1255         {
1256                 for(i = 0; i < numBSPDrawSurfaces; i++)
1257                 {
1258                         switch(bspDrawSurfaces[i].surfaceType)
1259                         {
1260                                 case SURFACE_FACE:
1261                                 case SURFACE_META:
1262                                         if(bspDrawSurfaces[i].numIndexes % 3)
1263                                                 Error("Not a triangulation!");
1264                                         for(j = bspDrawSurfaces[i].firstIndex; j < bspDrawSurfaces[i].firstIndex + bspDrawSurfaces[i].numIndexes; j += 3)
1265                                         {
1266                                                 int ia = bspDrawIndexes[j] + bspDrawSurfaces[i].firstVert, ib = bspDrawIndexes[j+1] + bspDrawSurfaces[i].firstVert, ic = bspDrawIndexes[j+2] + bspDrawSurfaces[i].firstVert;
1267                                                 bspDrawVert_t *a = &bspDrawVerts[ia], *b = &bspDrawVerts[ib], *c = &bspDrawVerts[ic];
1268                                                 float *oa = &old_xyzst[ia*5], *ob = &old_xyzst[ib*5], *oc = &old_xyzst[ic*5];
1269                                                 // extrapolate:
1270                                                 //   a->xyz -> oa
1271                                                 //   b->xyz -> ob
1272                                                 //   c->xyz -> oc
1273                                                 ExtrapolateTexcoords(
1274                                                         &oa[0], &oa[3],
1275                                                         &ob[0], &ob[3],
1276                                                         &oc[0], &oc[3],
1277                                                         a->xyz, a->st,
1278                                                         b->xyz, b->st,
1279                                                         c->xyz, c->st);
1280                                         }
1281                                         break;
1282                         }
1283                 }
1284         }
1285         
1286         /* scale planes */
1287         if(uniform)
1288         {
1289                 for( i = 0; i < numBSPPlanes; i++ )
1290                 {
1291                         bspPlanes[ i ].dist *= scale[0];
1292                 }
1293         }
1294         else
1295         {
1296                 for( i = 0; i < numBSPPlanes; i++ )
1297                 {
1298                         bspPlanes[ i ].normal[0] /= scale[0];
1299                         bspPlanes[ i ].normal[1] /= scale[1];
1300                         bspPlanes[ i ].normal[2] /= scale[2];
1301                         f = 1/VectorLength(bspPlanes[i].normal);
1302                         VectorScale(bspPlanes[i].normal, f, bspPlanes[i].normal);
1303                         bspPlanes[ i ].dist *= f;
1304                 }
1305         }
1306         
1307         /* scale gridsize */
1308         GetVectorForKey( &entities[ 0 ], "gridsize", vec );
1309         if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) == 0.0f )
1310                 VectorCopy( gridSize, vec );
1311         vec[0] *= scale[0];
1312         vec[1] *= scale[1];
1313         vec[2] *= scale[2];
1314         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1315         SetKeyValue( &entities[ 0 ], "gridsize", str );
1316
1317         /* inject command line parameters */
1318         InjectCommandLine(argv, 0, argc - 1);
1319         
1320         /* write the bsp */
1321         UnparseEntities();
1322         StripExtension( source );
1323         DefaultExtension( source, "_s.bsp" );
1324         Sys_Printf( "Writing %s\n", source );
1325         WriteBSPFile( source );
1326         
1327         /* return to sender */
1328         return 0;
1329 }
1330
1331
1332
1333 /*
1334 ConvertBSPMain()
1335 main argument processing function for bsp conversion
1336 */
1337
1338 int ConvertBSPMain( int argc, char **argv )
1339 {
1340         int             i;
1341         int             (*convertFunc)( char * );
1342         game_t  *convertGame;
1343         
1344         
1345         /* set default */
1346         convertFunc = ConvertBSPToASE;
1347         convertGame = NULL;
1348         
1349         /* arg checking */
1350         if( argc < 1 )
1351         {
1352                 Sys_Printf( "Usage: q3map -scale <value> [-v] <mapname>\n" );
1353                 return 0;
1354         }
1355         
1356         /* process arguments */
1357         for( i = 1; i < (argc - 1); i++ )
1358         {
1359                 /* -format map|ase|... */
1360                 if( !strcmp( argv[ i ],  "-format" ) )
1361                 {
1362                         i++;
1363                         if( !Q_stricmp( argv[ i ], "ase" ) )
1364                                 convertFunc = ConvertBSPToASE;
1365                         else if( !Q_stricmp( argv[ i ], "map" ) )
1366                                 convertFunc = ConvertBSPToMap;
1367                         else
1368                         {
1369                                 convertGame = GetGame( argv[ i ] );
1370                                 if( convertGame == NULL )
1371                                         Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] );
1372                         }
1373                 }
1374                 else if( !strcmp( argv[ i ],  "-ne" ) )
1375                 {
1376                         normalEpsilon = atof( argv[ i + 1 ] );
1377                         i++;
1378                         Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon );
1379                 }
1380                 else if( !strcmp( argv[ i ],  "-de" ) )
1381                 {
1382                         distanceEpsilon = atof( argv[ i + 1 ] );
1383                         i++;
1384                         Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon );
1385                 }
1386                 else if( !strcmp( argv[ i ],  "-shadersasbitmap" ) )
1387                         shadersAsBitmap = qtrue;
1388         }
1389         
1390         /* clean up map name */
1391         strcpy( source, ExpandArg( argv[ i ] ) );
1392         StripExtension( source );
1393         DefaultExtension( source, ".bsp" );
1394         
1395         LoadShaderInfo();
1396         
1397         Sys_Printf( "Loading %s\n", source );
1398         
1399         /* ydnar: load surface file */
1400         //%     LoadSurfaceExtraFile( source );
1401         
1402         LoadBSPFile( source );
1403         
1404         /* parse bsp entities */
1405         ParseEntities();
1406         
1407         /* bsp format convert? */
1408         if( convertGame != NULL )
1409         {
1410                 /* set global game */
1411                 game = convertGame;
1412                 
1413                 /* write bsp */
1414                 StripExtension( source );
1415                 DefaultExtension( source, "_c.bsp" );
1416                 Sys_Printf( "Writing %s\n", source );
1417                 WriteBSPFile( source );
1418                 
1419                 /* return to sender */
1420                 return 0;
1421         }
1422         
1423         /* normal convert */
1424         return convertFunc( source );
1425 }
1426
1427
1428
1429 /*
1430 main()
1431 q3map mojo...
1432 */
1433
1434 int main( int argc, char **argv )
1435 {
1436         int             i, r;
1437         double  start, end;
1438         
1439         
1440         /* we want consistent 'randomness' */
1441         srand( 0 );
1442         
1443         /* start timer */
1444         start = I_FloatTime();
1445
1446         /* this was changed to emit version number over the network */
1447         printf( Q3MAP_VERSION "\n" );
1448         
1449         /* set exit call */
1450         atexit( ExitQ3Map );
1451
1452         /* read general options first */
1453         for( i = 1; i < argc; i++ )
1454         {
1455                 /* -connect */
1456                 if( !strcmp( argv[ i ], "-connect" ) )
1457                 {
1458                         argv[ i ] = NULL;
1459                         i++;
1460                         Broadcast_Setup( argv[ i ] );
1461                         argv[ i ] = NULL;
1462                 }
1463                 
1464                 /* verbose */
1465                 else if( !strcmp( argv[ i ], "-v" ) )
1466                 {
1467                         if(!verbose)
1468                         {
1469                                 verbose = qtrue;
1470                                 argv[ i ] = NULL;
1471                         }
1472                 }
1473                 
1474                 /* force */
1475                 else if( !strcmp( argv[ i ], "-force" ) )
1476                 {
1477                         force = qtrue;
1478                         argv[ i ] = NULL;
1479                 }
1480                 
1481                 /* patch subdivisions */
1482                 else if( !strcmp( argv[ i ], "-subdivisions" ) )
1483                 {
1484                         argv[ i ] = NULL;
1485                         i++;
1486                         patchSubdivisions = atoi( argv[ i ] );
1487                         argv[ i ] = NULL;
1488                         if( patchSubdivisions <= 0 )
1489                                 patchSubdivisions = 1;
1490                 }
1491                 
1492                 /* threads */
1493                 else if( !strcmp( argv[ i ], "-threads" ) )
1494                 {
1495                         argv[ i ] = NULL;
1496                         i++;
1497                         numthreads = atoi( argv[ i ] );
1498                         argv[ i ] = NULL;
1499                 }
1500         }
1501         
1502         /* init model library */
1503         PicoInit();
1504         PicoSetMallocFunc( safe_malloc );
1505         PicoSetFreeFunc( free );
1506         PicoSetPrintFunc( PicoPrintFunc );
1507         PicoSetLoadFileFunc( PicoLoadFileFunc );
1508         PicoSetFreeFileFunc( free );
1509         
1510         /* set number of threads */
1511         ThreadSetDefault();
1512         
1513         /* generate sinusoid jitter table */
1514         for( i = 0; i < MAX_JITTERS; i++ )
1515         {
1516                 jitters[ i ] = sin( i * 139.54152147 );
1517                 //%     Sys_Printf( "Jitter %4d: %f\n", i, jitters[ i ] );
1518         }
1519         
1520         /* we print out two versions, q3map's main version (since it evolves a bit out of GtkRadiant)
1521            and we put the GtkRadiant version to make it easy to track with what version of Radiant it was built with */
1522         
1523         Sys_Printf( "Q3Map         - v1.0r (c) 1999 Id Software Inc.\n" );
1524         Sys_Printf( "Q3Map (ydnar) - v" Q3MAP_VERSION "\n" );
1525         Sys_Printf( "NetRadiant    - v" RADIANT_VERSION " " __DATE__ " " __TIME__ "\n" );
1526         Sys_Printf( "%s\n", Q3MAP_MOTD );
1527         
1528         /* ydnar: new path initialization */
1529         InitPaths( &argc, argv );
1530
1531         /* set game options */
1532         if (!patchSubdivisions)
1533                 patchSubdivisions = game->patchSubdivisions;
1534         
1535         /* check if we have enough options left to attempt something */
1536         if( argc < 2 )
1537                 Error( "Usage: %s [general options] [options] mapfile", argv[ 0 ] );
1538         
1539         /* fixaas */
1540         if( !strcmp( argv[ 1 ], "-fixaas" ) )
1541                 r = FixAAS( argc - 1, argv + 1 );
1542         
1543         /* analyze */
1544         else if( !strcmp( argv[ 1 ], "-analyze" ) )
1545                 r = AnalyzeBSP( argc - 1, argv + 1 );
1546         
1547         /* info */
1548         else if( !strcmp( argv[ 1 ], "-info" ) )
1549                 r = BSPInfo( argc - 2, argv + 2 );
1550         
1551         /* vis */
1552         else if( !strcmp( argv[ 1 ], "-vis" ) )
1553                 r = VisMain( argc - 1, argv + 1 );
1554         
1555         /* light */
1556         else if( !strcmp( argv[ 1 ], "-light" ) )
1557                 r = LightMain( argc - 1, argv + 1 );
1558         
1559         /* vlight */
1560         else if( !strcmp( argv[ 1 ], "-vlight" ) )
1561         {
1562                 Sys_Printf( "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" );
1563                 argv[ 1 ] = "-fast";    /* eek a hack */
1564                 r = LightMain( argc, argv );
1565         }
1566         
1567         /* ydnar: lightmap export */
1568         else if( !strcmp( argv[ 1 ], "-export" ) )
1569                 r = ExportLightmapsMain( argc - 1, argv + 1 );
1570         
1571         /* ydnar: lightmap import */
1572         else if( !strcmp( argv[ 1 ], "-import" ) )
1573                 r = ImportLightmapsMain( argc - 1, argv + 1 );
1574         
1575         /* ydnar: bsp scaling */
1576         else if( !strcmp( argv[ 1 ], "-scale" ) )
1577                 r = ScaleBSPMain( argc - 1, argv + 1 );
1578         
1579         /* ydnar: bsp conversion */
1580         else if( !strcmp( argv[ 1 ], "-convert" ) )
1581                 r = ConvertBSPMain( argc - 1, argv + 1 );
1582         
1583         /* div0: minimap */
1584         else if( !strcmp( argv[ 1 ], "-minimap" ) )
1585                 r = MiniMapBSPMain(argc - 1, argv + 1);
1586
1587         /* ydnar: otherwise create a bsp */
1588         else
1589                 r = BSPMain( argc, argv );
1590         
1591         /* emit time */
1592         end = I_FloatTime();
1593         Sys_Printf( "%9.0f seconds elapsed\n", end - start );
1594         
1595         /* shut down connection */
1596         Broadcast_Shutdown();
1597         
1598         /* return any error code */
1599         return r;
1600 }