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