]> icculus.org git repositories - divverent/netradiant.git/blob - tools/quake3/q3map2/main.c
NOW I do it right: #woxblox#
[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, brightness, contrast;
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 static void MiniMapBrightnessContrast(int y)
307 {
308         int x;
309         float *q = &minimap.data1f[y * minimap.width];
310         for(x = 0; x < minimap.width; ++x)
311         {
312                 *q = *q * minimap.contrast + minimap.brightness;
313                 ++q;
314         }
315 }
316
317 void MiniMapMakeMinsMaxs(vec3_t mins_in, vec3_t maxs_in, float border, qboolean keepaspect)
318 {
319         vec3_t mins, maxs, extend;
320         VectorCopy(mins_in, mins);
321         VectorCopy(maxs_in, maxs);
322
323         // line compatible to nexuiz mapinfo
324         Sys_Printf("size %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
325
326         if(keepaspect)
327         {
328                 VectorSubtract(maxs, mins, extend);
329                 if(extend[1] > extend[0])
330                 {
331                         mins[0] -= (extend[1] - extend[0]) * 0.5;
332                         maxs[0] += (extend[1] - extend[0]) * 0.5;
333                 }
334                 else
335                 {
336                         mins[1] -= (extend[0] - extend[1]) * 0.5;
337                         maxs[1] += (extend[0] - extend[1]) * 0.5;
338                 }
339         }
340
341         /* border: amount of black area around the image */
342         /* input: border, 1-2*border, border but we need border/(1-2*border) */
343
344         VectorSubtract(maxs, mins, extend);
345         VectorScale(extend, border / (1 - 2 * border), extend);
346
347         VectorSubtract(mins, extend, mins);
348         VectorAdd(maxs, extend, maxs);
349
350         VectorCopy(mins, minimap.mins);
351         VectorSubtract(maxs, mins, minimap.size);
352
353         // line compatible to nexuiz mapinfo
354         Sys_Printf("size_texcoords %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
355 }
356
357 /*
358 MiniMapSetupBrushes()
359 determines solid non-sky brushes in the world
360 */
361
362 void MiniMapSetupBrushes( void )
363 {
364         SetupBrushesFlags(C_SOLID | C_SKY, C_SOLID, 0, 0);
365                 // at least one must be solid
366                 // none may be sky
367                 // not all may be nodraw
368 }
369
370 qboolean MiniMapEvaluateSampleOffsets(int *bestj, int *bestk, float *bestval)
371 {
372         float val, dx, dy;
373         int j, k;
374
375         *bestj = *bestk = -1;
376         *bestval = 3; /* max possible val is 2 */
377
378         for(j = 0; j < minimap.samples; ++j)
379                 for(k = j + 1; k < minimap.samples; ++k)
380                 {
381                         dx = minimap.sample_offsets[2*j+0] - minimap.sample_offsets[2*k+0];
382                         dy = minimap.sample_offsets[2*j+1] - minimap.sample_offsets[2*k+1];
383                         if(dx > +0.5) dx -= 1;
384                         if(dx < -0.5) dx += 1;
385                         if(dy > +0.5) dy -= 1;
386                         if(dy < -0.5) dy += 1;
387                         val = dx * dx + dy * dy;
388                         if(val < *bestval)
389                         {
390                                 *bestj = j;
391                                 *bestk = k;
392                                 *bestval = val;
393                         }
394                 }
395         
396         return *bestval < 3;
397 }
398
399 void MiniMapMakeSampleOffsets()
400 {
401         int i, j, k, jj, kk;
402         float val, valj, valk, sx, sy, rx, ry;
403
404         Sys_Printf( "Generating good sample offsets (this may take a while)...\n" );
405
406         /* start with entirely random samples */
407         for(i = 0; i < minimap.samples; ++i)
408         {
409                 minimap.sample_offsets[2*i+0] = Random();
410                 minimap.sample_offsets[2*i+1] = Random();
411         }
412
413         for(i = 0; i < 1000; ++i)
414         {
415                 if(MiniMapEvaluateSampleOffsets(&j, &k, &val))
416                 {
417                         sx = minimap.sample_offsets[2*j+0];
418                         sy = minimap.sample_offsets[2*j+1];
419                         minimap.sample_offsets[2*j+0] = rx = Random();
420                         minimap.sample_offsets[2*j+1] = ry = Random();
421                         if(!MiniMapEvaluateSampleOffsets(&jj, &kk, &valj))
422                                 valj = -1;
423                         minimap.sample_offsets[2*j+0] = sx;
424                         minimap.sample_offsets[2*j+1] = sy;
425
426                         sx = minimap.sample_offsets[2*k+0];
427                         sy = minimap.sample_offsets[2*k+1];
428                         minimap.sample_offsets[2*k+0] = rx;
429                         minimap.sample_offsets[2*k+1] = ry;
430                         if(!MiniMapEvaluateSampleOffsets(&jj, &kk, &valk))
431                                 valk = -1;
432                         minimap.sample_offsets[2*k+0] = sx;
433                         minimap.sample_offsets[2*k+1] = sy;
434
435                         if(valj > valk)
436                         {
437                                 if(valj > val)
438                                 {
439                                         /* valj is the greatest */
440                                         minimap.sample_offsets[2*j+0] = rx;
441                                         minimap.sample_offsets[2*j+1] = ry;
442                                         i = -1;
443                                 }
444                                 else
445                                 {
446                                         /* valj is the greater and it is useless - forget it */
447                                 }
448                         }
449                         else
450                         {
451                                 if(valk > val)
452                                 {
453                                         /* valk is the greatest */
454                                         minimap.sample_offsets[2*k+0] = rx;
455                                         minimap.sample_offsets[2*k+1] = ry;
456                                         i = -1;
457                                 }
458                                 else
459                                 {
460                                         /* valk is the greater and it is useless - forget it */
461                                 }
462                         }
463                 }
464                 else
465                         break;
466         }
467 }
468
469 void MergeRelativePath(char *out, const char *absolute, const char *relative)
470 {
471         const char *endpos = absolute + strlen(absolute);
472         while(endpos != absolute && (endpos[-1] == '/' || endpos[-1] == '\\'))
473                 --endpos;
474         while(relative[0] == '.' && relative[1] == '.' && (relative[2] == '/' || relative[2] == '\\'))
475         {
476                 relative += 3;
477                 while(endpos != absolute)
478                 {
479                         --endpos;
480                         if(*endpos == '/' || *endpos == '\\')
481                                 break;
482                 }
483                 while(endpos != absolute && (endpos[-1] == '/' || endpos[-1] == '\\'))
484                         --endpos;
485         }
486         memcpy(out, absolute, endpos - absolute);
487         out[endpos - absolute] = '/';
488         strcpy(out + (endpos - absolute + 1), relative);
489 }
490
491 int MiniMapBSPMain( int argc, char **argv )
492 {
493         char minimapFilename[1024];
494         char basename[1024];
495         char path[1024];
496         char relativeMinimapFilename[1024];
497         qboolean autolevel;
498         float minimapSharpen;
499         float border;
500         byte *data4b, *p;
501         float *q;
502         int x, y;
503         int i;
504         miniMapMode_t mode;
505         vec3_t mins, maxs;
506         qboolean keepaspect;
507
508         /* arg checking */
509         if( argc < 2 )
510         {
511                 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" );
512                 return 0;
513         }
514
515         /* load the BSP first */
516         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
517         StripExtension( source );
518         DefaultExtension( source, ".bsp" );
519         Sys_Printf( "Loading %s\n", source );
520         BeginMapShaderFile( source );
521         LoadShaderInfo();
522         LoadBSPFile( source );
523
524         minimap.model = &bspModels[0];
525         VectorCopy(minimap.model->mins, mins);
526         VectorCopy(minimap.model->maxs, maxs);
527
528         *minimapFilename = 0;
529         minimapSharpen = game->miniMapSharpen;
530         minimap.width = minimap.height = game->miniMapSize;
531         border = game->miniMapBorder;
532         keepaspect = game->miniMapKeepAspect;
533         mode = game->miniMapMode;
534
535         autolevel = qfalse;
536         minimap.samples = 1;
537         minimap.sample_offsets = NULL;
538         minimap.boost = 1.0;
539         minimap.brightness = 0.0;
540         minimap.contrast = 1.0;
541
542         /* process arguments */
543         for( i = 1; i < (argc - 1); i++ )
544         {
545                 if( !strcmp( argv[ i ],  "-size" ) )
546                 {
547                         minimap.width = minimap.height = atoi(argv[i + 1]);
548                         i++;
549                         Sys_Printf( "Image size set to %i\n", minimap.width );
550                 }
551                 else if( !strcmp( argv[ i ],  "-sharpen" ) )
552                 {
553                         minimapSharpen = atof(argv[i + 1]);
554                         i++;
555                         Sys_Printf( "Sharpening coefficient set to %f\n", minimapSharpen );
556                 }
557                 else if( !strcmp( argv[ i ],  "-samples" ) )
558                 {
559                         minimap.samples = atoi(argv[i + 1]);
560                         i++;
561                         Sys_Printf( "Samples set to %i\n", minimap.samples );
562                         if(minimap.sample_offsets)
563                                 free(minimap.sample_offsets);
564                         minimap.sample_offsets = malloc(2 * sizeof(*minimap.sample_offsets) * minimap.samples);
565                         MiniMapMakeSampleOffsets();
566                 }
567                 else if( !strcmp( argv[ i ],  "-random" ) )
568                 {
569                         minimap.samples = atoi(argv[i + 1]);
570                         i++;
571                         Sys_Printf( "Random samples set to %i\n", minimap.samples );
572                         if(minimap.sample_offsets)
573                                 free(minimap.sample_offsets);
574                         minimap.sample_offsets = NULL;
575                 }
576                 else if( !strcmp( argv[ i ],  "-border" ) )
577                 {
578                         border = atof(argv[i + 1]);
579                         i++;
580                         Sys_Printf( "Border set to %f\n", border );
581                 }
582                 else if( !strcmp( argv[ i ],  "-keepaspect" ) )
583                 {
584                         keepaspect = qtrue;
585                         Sys_Printf( "Keeping aspect ratio by letterboxing\n", border );
586                 }
587                 else if( !strcmp( argv[ i ],  "-nokeepaspect" ) )
588                 {
589                         keepaspect = qfalse;
590                         Sys_Printf( "Not keeping aspect ratio\n", border );
591                 }
592                 else if( !strcmp( argv[ i ],  "-o" ) )
593                 {
594                         strcpy(minimapFilename, argv[i + 1]);
595                         i++;
596                         Sys_Printf( "Output file name set to %s\n", minimapFilename );
597                 }
598                 else if( !strcmp( argv[ i ],  "-minmax" ) && i < (argc - 7) )
599                 {
600                         mins[0] = atof(argv[i + 1]);
601                         mins[1] = atof(argv[i + 2]);
602                         mins[2] = atof(argv[i + 3]);
603                         maxs[0] = atof(argv[i + 4]);
604                         maxs[1] = atof(argv[i + 5]);
605                         maxs[2] = atof(argv[i + 6]);
606                         i += 6;
607                         Sys_Printf( "Map mins/maxs overridden\n" );
608                 }
609                 else if( !strcmp( argv[ i ],  "-gray" ) )
610                 {
611                         mode = MINIMAP_MODE_GRAY;
612                         Sys_Printf( "Writing as white-on-black image\n" );
613                 }
614                 else if( !strcmp( argv[ i ],  "-black" ) )
615                 {
616                         mode = MINIMAP_MODE_BLACK;
617                         Sys_Printf( "Writing as black alpha image\n" );
618                 }
619                 else if( !strcmp( argv[ i ],  "-white" ) )
620                 {
621                         mode = MINIMAP_MODE_WHITE;
622                         Sys_Printf( "Writing as white alpha image\n" );
623                 }
624                 else if( !strcmp( argv[ i ],  "-boost" ) && i < (argc - 2) )
625                 {
626                         minimap.boost = atof(argv[i + 1]);
627                         i++;
628                         Sys_Printf( "Contrast boost set to %f\n", minimap.boost );
629                 }
630                 else if( !strcmp( argv[ i ],  "-brightness" ) && i < (argc - 2) )
631                 {
632                         minimap.brightness = atof(argv[i + 1]);
633                         i++;
634                         Sys_Printf( "Brightness set to %f\n", minimap.brightness );
635                 }
636                 else if( !strcmp( argv[ i ],  "-contrast" ) && i < (argc - 2) )
637                 {
638                         minimap.contrast = atof(argv[i + 1]);
639                         i++;
640                         Sys_Printf( "Contrast set to %f\n", minimap.contrast );
641                 }
642                 else if( !strcmp( argv[ i ],  "-autolevel" ) )
643                 {
644                         autolevel = qtrue;
645                         Sys_Printf( "Auto level enabled\n", border );
646                 }
647                 else if( !strcmp( argv[ i ],  "-noautolevel" ) )
648                 {
649                         autolevel = qfalse;
650                         Sys_Printf( "Auto level disabled\n", border );
651                 }
652         }
653
654         MiniMapMakeMinsMaxs(mins, maxs, border, keepaspect);
655
656         if(!*minimapFilename)
657         {
658                 ExtractFileBase(source, basename);
659                 ExtractFilePath(source, path);
660                 sprintf(relativeMinimapFilename, game->miniMapNameFormat, basename);
661                 MergeRelativePath(minimapFilename, path, relativeMinimapFilename);
662                 Sys_Printf("Output file name automatically set to %s\n", minimapFilename);
663         }
664         ExtractFilePath(minimapFilename, path);
665         Q_mkdir(path);
666
667         if(minimapSharpen >= 0)
668         {
669                 minimap.sharpen_centermult = 8 * minimapSharpen + 1;
670                 minimap.sharpen_boxmult    =    -minimapSharpen;
671         }
672
673         minimap.data1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f));
674         data4b = safe_malloc(minimap.width * minimap.height * 4);
675         if(minimapSharpen >= 0)
676                 minimap.sharpendata1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f));
677
678         MiniMapSetupBrushes();
679
680         if(minimap.samples <= 1)
681         {
682                 Sys_Printf( "\n--- MiniMapNoSupersampling (%d) ---\n", minimap.height );
683                 RunThreadsOnIndividual(minimap.height, qtrue, MiniMapNoSupersampling);
684         }
685         else
686         {
687                 if(minimap.sample_offsets)
688                 {
689                         Sys_Printf( "\n--- MiniMapSupersampled (%d) ---\n", minimap.height );
690                         RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSupersampled);
691                 }
692                 else
693                 {
694                         Sys_Printf( "\n--- MiniMapRandomlySupersampled (%d) ---\n", minimap.height );
695                         RunThreadsOnIndividual(minimap.height, qtrue, MiniMapRandomlySupersampled);
696                 }
697         }
698
699         if(minimap.boost != 1.0)
700         {
701                 Sys_Printf( "\n--- MiniMapContrastBoost (%d) ---\n", minimap.height );
702                 RunThreadsOnIndividual(minimap.height, qtrue, MiniMapContrastBoost);
703         }
704
705         if(autolevel)
706         {
707                 Sys_Printf( "\n--- MiniMapAutoLevel (%d) ---\n", minimap.height );
708                 float mi = 1, ma = 0;
709                 float s, o;
710
711                 // TODO threads!
712                 q = minimap.data1f;
713                 for(y = 0; y < minimap.height; ++y)
714                         for(x = 0; x < minimap.width; ++x)
715                         {
716                                 float v = *q++;
717                                 if(v < mi)
718                                         mi = v;
719                                 if(v > ma)
720                                         ma = v;
721                         }
722                 if(ma > mi)
723                 {
724                         s = 1 / (ma - mi);
725                         o = mi / (ma - mi);
726
727                         // equations:
728                         //   brightness + contrast * v
729                         // after autolevel:
730                         //   brightness + contrast * (v * s - o)
731                         // =
732                         //   (brightness - contrast * o) + (contrast * s) * v
733                         minimap.brightness = minimap.brightness - minimap.contrast * o;
734                         minimap.contrast *= s;
735
736                         Sys_Printf( "Auto level: Brightness changed to %f\n", minimap.brightness );
737                         Sys_Printf( "Auto level: Contrast changed to %f\n", minimap.contrast );
738                 }
739                 else
740                         Sys_Printf( "Auto level: failed because all pixels are the same value\n" );
741         }
742
743         if(minimap.brightness != 0 || minimap.contrast != 1)
744         {
745                 Sys_Printf( "\n--- MiniMapBrightnessContrast (%d) ---\n", minimap.height );
746                 RunThreadsOnIndividual(minimap.height, qtrue, MiniMapBrightnessContrast);
747         }
748
749         if(minimap.sharpendata1f)
750         {
751                 Sys_Printf( "\n--- MiniMapSharpen (%d) ---\n", minimap.height );
752                 RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSharpen);
753                 q = minimap.sharpendata1f;
754         }
755         else
756         {
757                 q = minimap.data1f;
758         }
759
760         Sys_Printf( "\nConverting...");
761
762         switch(mode)
763         {
764                 case MINIMAP_MODE_GRAY:
765                         p = data4b;
766                         for(y = 0; y < minimap.height; ++y)
767                                 for(x = 0; x < minimap.width; ++x)
768                                 {
769                                         byte b;
770                                         float v = *q++;
771                                         if(v < 0) v = 0;
772                                         if(v > 255.0/256.0) v = 255.0/256.0;
773                                         b = v * 256;
774                                         *p++ = b;
775                                 }
776                         Sys_Printf( " writing to %s...", minimapFilename );
777                         WriteTGAGray(minimapFilename, data4b, minimap.width, minimap.height);
778                         break;
779                 case MINIMAP_MODE_BLACK:
780                         p = data4b;
781                         for(y = 0; y < minimap.height; ++y)
782                                 for(x = 0; x < minimap.width; ++x)
783                                 {
784                                         byte b;
785                                         float v = *q++;
786                                         if(v < 0) v = 0;
787                                         if(v > 255.0/256.0) v = 255.0/256.0;
788                                         b = v * 256;
789                                         *p++ = 0;
790                                         *p++ = 0;
791                                         *p++ = 0;
792                                         *p++ = b;
793                                 }
794                         Sys_Printf( " writing to %s...", minimapFilename );
795                         WriteTGA(minimapFilename, data4b, minimap.width, minimap.height);
796                         break;
797                 case MINIMAP_MODE_WHITE:
798                         p = data4b;
799                         for(y = 0; y < minimap.height; ++y)
800                                 for(x = 0; x < minimap.width; ++x)
801                                 {
802                                         byte b;
803                                         float v = *q++;
804                                         if(v < 0) v = 0;
805                                         if(v > 255.0/256.0) v = 255.0/256.0;
806                                         b = v * 256;
807                                         *p++ = 255;
808                                         *p++ = 255;
809                                         *p++ = 255;
810                                         *p++ = b;
811                                 }
812                         Sys_Printf( " writing to %s...", minimapFilename );
813                         WriteTGA(minimapFilename, data4b, minimap.width, minimap.height);
814                         break;
815         }
816
817         Sys_Printf( " done.\n" );
818
819         /* return to sender */
820         return 0;
821 }
822
823
824
825
826
827 /*
828 MD4BlockChecksum()
829 calculates an md4 checksum for a block of data
830 */
831
832 static int MD4BlockChecksum( void *buffer, int length )
833 {
834         return Com_BlockChecksum(buffer, length);
835 }
836
837 /*
838 FixAAS()
839 resets an aas checksum to match the given BSP
840 */
841
842 int FixAAS( int argc, char **argv )
843 {
844         int                     length, checksum;
845         void            *buffer;
846         FILE            *file;
847         char            aas[ 1024 ], **ext;
848         char            *exts[] =
849                                 {
850                                         ".aas",
851                                         "_b0.aas",
852                                         "_b1.aas",
853                                         NULL
854                                 };
855         
856         
857         /* arg checking */
858         if( argc < 2 )
859         {
860                 Sys_Printf( "Usage: q3map -fixaas [-v] <mapname>\n" );
861                 return 0;
862         }
863         
864         /* do some path mangling */
865         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
866         StripExtension( source );
867         DefaultExtension( source, ".bsp" );
868         
869         /* note it */
870         Sys_Printf( "--- FixAAS ---\n" );
871         
872         /* load the bsp */
873         Sys_Printf( "Loading %s\n", source );
874         length = LoadFile( source, &buffer );
875         
876         /* create bsp checksum */
877         Sys_Printf( "Creating checksum...\n" );
878         checksum = LittleLong( MD4BlockChecksum( buffer, length ) );
879         
880         /* write checksum to aas */
881         ext = exts;
882         while( *ext )
883         {
884                 /* mangle name */
885                 strcpy( aas, source );
886                 StripExtension( aas );
887                 strcat( aas, *ext );
888                 Sys_Printf( "Trying %s\n", aas );
889                 ext++;
890                 
891                 /* fix it */
892                 file = fopen( aas, "r+b" );
893                 if( !file )
894                         continue;
895                 if( fwrite( &checksum, 4, 1, file ) != 1 )
896                         Error( "Error writing checksum to %s", aas );
897                 fclose( file );
898         }
899         
900         /* return to sender */
901         return 0;
902 }
903
904
905
906 /*
907 AnalyzeBSP() - ydnar
908 analyzes a Quake engine BSP file
909 */
910
911 typedef struct abspHeader_s
912 {
913         char                    ident[ 4 ];
914         int                             version;
915         
916         bspLump_t               lumps[ 1 ];     /* unknown size */
917 }
918 abspHeader_t;
919
920 typedef struct abspLumpTest_s
921 {
922         int                             radix, minCount;
923         char                    *name;
924 }
925 abspLumpTest_t;
926
927 int AnalyzeBSP( int argc, char **argv )
928 {
929         abspHeader_t                    *header;
930         int                                             size, i, version, offset, length, lumpInt, count;
931         char                                    ident[ 5 ];
932         void                                    *lump;
933         float                                   lumpFloat;
934         char                                    lumpString[ 1024 ], source[ 1024 ];
935         qboolean                                lumpSwap = qfalse;
936         abspLumpTest_t                  *lumpTest;
937         static abspLumpTest_t   lumpTests[] =
938                                                         {
939                                                                 { sizeof( bspPlane_t ),                 6,              "IBSP LUMP_PLANES" },
940                                                                 { sizeof( bspBrush_t ),                 1,              "IBSP LUMP_BRUSHES" },
941                                                                 { 8,                                                    6,              "IBSP LUMP_BRUSHSIDES" },
942                                                                 { sizeof( bspBrushSide_t ),             6,              "RBSP LUMP_BRUSHSIDES" },
943                                                                 { sizeof( bspModel_t ),                 1,              "IBSP LUMP_MODELS" },
944                                                                 { sizeof( bspNode_t ),                  2,              "IBSP LUMP_NODES" },
945                                                                 { sizeof( bspLeaf_t ),                  1,              "IBSP LUMP_LEAFS" },
946                                                                 { 104,                                                  3,              "IBSP LUMP_DRAWSURFS" },
947                                                                 { 44,                                                   3,              "IBSP LUMP_DRAWVERTS" },
948                                                                 { 4,                                                    6,              "IBSP LUMP_DRAWINDEXES" },
949                                                                 { 128 * 128 * 3,                                1,              "IBSP LUMP_LIGHTMAPS" },
950                                                                 { 256 * 256 * 3,                                1,              "IBSP LUMP_LIGHTMAPS (256 x 256)" },
951                                                                 { 512 * 512 * 3,                                1,              "IBSP LUMP_LIGHTMAPS (512 x 512)" },
952                                                                 { 0, 0, NULL }
953                                                         };
954         
955         
956         /* arg checking */
957         if( argc < 1 )
958         {
959                 Sys_Printf( "Usage: q3map -analyze [-lumpswap] [-v] <mapname>\n" );
960                 return 0;
961         }
962         
963         /* process arguments */
964         for( i = 1; i < (argc - 1); i++ )
965         {
966                 /* -format map|ase|... */
967                 if( !strcmp( argv[ i ],  "-lumpswap" ) )
968                 {
969                         Sys_Printf( "Swapped lump structs enabled\n" );
970                         lumpSwap = qtrue;
971                 }
972         }
973         
974         /* clean up map name */
975         strcpy( source, ExpandArg( argv[ i ] ) );
976         Sys_Printf( "Loading %s\n", source );
977         
978         /* load the file */
979         size = LoadFile( source, (void**) &header );
980         if( size == 0 || header == NULL )
981         {
982                 Sys_Printf( "Unable to load %s.\n", source );
983                 return -1;
984         }
985         
986         /* analyze ident/version */
987         memcpy( ident, header->ident, 4 );
988         ident[ 4 ] = '\0';
989         version = LittleLong( header->version );
990         
991         Sys_Printf( "Identity:      %s\n", ident );
992         Sys_Printf( "Version:       %d\n", version );
993         Sys_Printf( "---------------------------------------\n" );
994         
995         /* analyze each lump */
996         for( i = 0; i < 100; i++ )
997         {
998                 /* call of duty swapped lump pairs */
999                 if( lumpSwap )
1000                 {
1001                         offset = LittleLong( header->lumps[ i ].length );
1002                         length = LittleLong( header->lumps[ i ].offset );
1003                 }
1004                 
1005                 /* standard lump pairs */
1006                 else
1007                 {
1008                         offset = LittleLong( header->lumps[ i ].offset );
1009                         length = LittleLong( header->lumps[ i ].length );
1010                 }
1011                 
1012                 /* extract data */
1013                 lump = (byte*) header + offset;
1014                 lumpInt = LittleLong( (int) *((int*) lump) );
1015                 lumpFloat = LittleFloat( (float) *((float*) lump) );
1016                 memcpy( lumpString, (char*) lump, ((size_t)length < sizeof(lumpString) ? (size_t)length : sizeof(lumpString)-1) );
1017                 lumpString[ sizeof(lumpString)-1 ] = '\0';
1018                 
1019                 /* print basic lump info */
1020                 Sys_Printf( "Lump:          %d\n", i );
1021                 Sys_Printf( "Offset:        %d bytes\n", offset );
1022                 Sys_Printf( "Length:        %d bytes\n", length );
1023                 
1024                 /* only operate on valid lumps */
1025                 if( length > 0 )
1026                 {
1027                         /* print data in 4 formats */
1028                         Sys_Printf( "As hex:        %08X\n", lumpInt );
1029                         Sys_Printf( "As int:        %d\n", lumpInt );
1030                         Sys_Printf( "As float:      %f\n", lumpFloat );
1031                         Sys_Printf( "As string:     %s\n", lumpString );
1032                         
1033                         /* guess lump type */
1034                         if( lumpString[ 0 ] == '{' && lumpString[ 2 ] == '"' )
1035                                 Sys_Printf( "Type guess:    IBSP LUMP_ENTITIES\n" );
1036                         else if( strstr( lumpString, "textures/" ) )
1037                                 Sys_Printf( "Type guess:    IBSP LUMP_SHADERS\n" );
1038                         else
1039                         {
1040                                 /* guess based on size/count */
1041                                 for( lumpTest = lumpTests; lumpTest->radix > 0; lumpTest++ )
1042                                 {
1043                                         if( (length % lumpTest->radix) != 0 )
1044                                                 continue;
1045                                         count = length / lumpTest->radix;
1046                                         if( count < lumpTest->minCount )
1047                                                 continue;
1048                                         Sys_Printf( "Type guess:    %s (%d x %d)\n", lumpTest->name, count, lumpTest->radix );
1049                                 }
1050                         }
1051                 }
1052                 
1053                 Sys_Printf( "---------------------------------------\n" );
1054                 
1055                 /* end of file */
1056                 if( offset + length >= size )
1057                         break;
1058         }
1059         
1060         /* last stats */
1061         Sys_Printf( "Lump count:    %d\n", i + 1 );
1062         Sys_Printf( "File size:     %d bytes\n", size );
1063         
1064         /* return to caller */
1065         return 0;
1066 }
1067
1068
1069
1070 /*
1071 BSPInfo()
1072 emits statistics about the bsp file
1073 */
1074
1075 int BSPInfo( int count, char **fileNames )
1076 {
1077         int                     i;
1078         char            source[ 1024 ], ext[ 64 ];
1079         int                     size;
1080         FILE            *f;
1081         
1082         
1083         /* dummy check */
1084         if( count < 1 )
1085         {
1086                 Sys_Printf( "No files to dump info for.\n");
1087                 return -1;
1088         }
1089         
1090         /* enable info mode */
1091         infoMode = qtrue;
1092         
1093         /* walk file list */
1094         for( i = 0; i < count; i++ )
1095         {
1096                 Sys_Printf( "---------------------------------\n" );
1097                 
1098                 /* mangle filename and get size */
1099                 strcpy( source, fileNames[ i ] );
1100                 ExtractFileExtension( source, ext );
1101                 if( !Q_stricmp( ext, "map" ) )
1102                         StripExtension( source );
1103                 DefaultExtension( source, ".bsp" );
1104                 f = fopen( source, "rb" );
1105                 if( f )
1106                 {
1107                         size = Q_filelength (f);
1108                         fclose( f );
1109                 }
1110                 else
1111                         size = 0;
1112                 
1113                 /* load the bsp file and print lump sizes */
1114                 Sys_Printf( "%s\n", source );
1115                 LoadBSPFile( source );          
1116                 PrintBSPFileSizes();
1117                 
1118                 /* print sizes */
1119                 Sys_Printf( "\n" );
1120                 Sys_Printf( "          total         %9d\n", size );
1121                 Sys_Printf( "                        %9d KB\n", size / 1024 );
1122                 Sys_Printf( "                        %9d MB\n", size / (1024 * 1024) );
1123                 
1124                 Sys_Printf( "---------------------------------\n" );
1125         }
1126         
1127         /* return count */
1128         return i;
1129 }
1130
1131
1132 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)
1133 {
1134         vec4_t scoeffs, tcoeffs;
1135         float md;
1136         m4x4_t solvematrix;
1137
1138         vec3_t norm;
1139         vec3_t dab, dac;
1140         VectorSubtract(bxyz, axyz, dab);
1141         VectorSubtract(cxyz, axyz, dac);
1142         CrossProduct(dab, dac, norm);
1143         
1144         // assume:
1145         //   s = f(x, y, z)
1146         //   s(v + norm) = s(v) when n ortho xyz
1147         
1148         // s(v) = DotProduct(v, scoeffs) + scoeffs[3]
1149
1150         // solve:
1151         //   scoeffs * (axyz, 1) == ast[0]
1152         //   scoeffs * (bxyz, 1) == bst[0]
1153         //   scoeffs * (cxyz, 1) == cst[0]
1154         //   scoeffs * (norm, 0) == 0
1155         // scoeffs * [axyz, 1 | bxyz, 1 | cxyz, 1 | norm, 0] = [ast[0], bst[0], cst[0], 0]
1156         solvematrix[0] = axyz[0];
1157         solvematrix[4] = axyz[1];
1158         solvematrix[8] = axyz[2];
1159         solvematrix[12] = 1;
1160         solvematrix[1] = bxyz[0];
1161         solvematrix[5] = bxyz[1];
1162         solvematrix[9] = bxyz[2];
1163         solvematrix[13] = 1;
1164         solvematrix[2] = cxyz[0];
1165         solvematrix[6] = cxyz[1];
1166         solvematrix[10] = cxyz[2];
1167         solvematrix[14] = 1;
1168         solvematrix[3] = norm[0];
1169         solvematrix[7] = norm[1];
1170         solvematrix[11] = norm[2];
1171         solvematrix[15] = 0;
1172
1173         md = m4_det(solvematrix);
1174         if(md*md < 1e-10)
1175         {
1176                 Sys_Printf("Cannot invert some matrix, some texcoords aren't extrapolated!");
1177                 return;
1178         }
1179
1180         m4x4_invert(solvematrix);
1181
1182         scoeffs[0] = ast[0];
1183         scoeffs[1] = bst[0];
1184         scoeffs[2] = cst[0];
1185         scoeffs[3] = 0;
1186         m4x4_transform_vec4(solvematrix, scoeffs);
1187         tcoeffs[0] = ast[1];
1188         tcoeffs[1] = bst[1];
1189         tcoeffs[2] = cst[1];
1190         tcoeffs[3] = 0;
1191         m4x4_transform_vec4(solvematrix, tcoeffs);
1192
1193         ast_out[0] = scoeffs[0] * axyz_new[0] + scoeffs[1] * axyz_new[1] + scoeffs[2] * axyz_new[2] + scoeffs[3];
1194         ast_out[1] = tcoeffs[0] * axyz_new[0] + tcoeffs[1] * axyz_new[1] + tcoeffs[2] * axyz_new[2] + tcoeffs[3];
1195         bst_out[0] = scoeffs[0] * bxyz_new[0] + scoeffs[1] * bxyz_new[1] + scoeffs[2] * bxyz_new[2] + scoeffs[3];
1196         bst_out[1] = tcoeffs[0] * bxyz_new[0] + tcoeffs[1] * bxyz_new[1] + tcoeffs[2] * bxyz_new[2] + tcoeffs[3];
1197         cst_out[0] = scoeffs[0] * cxyz_new[0] + scoeffs[1] * cxyz_new[1] + scoeffs[2] * cxyz_new[2] + scoeffs[3];
1198         cst_out[1] = tcoeffs[0] * cxyz_new[0] + tcoeffs[1] * cxyz_new[1] + tcoeffs[2] * cxyz_new[2] + tcoeffs[3];
1199 }
1200
1201 /*
1202 ScaleBSPMain()
1203 amaze and confuse your enemies with wierd scaled maps!
1204 */
1205
1206 int ScaleBSPMain( int argc, char **argv )
1207 {
1208         int                     i, j;
1209         float           f, a;
1210         vec3_t scale;
1211         vec3_t          vec;
1212         char            str[ 1024 ];
1213         int uniform, axis;
1214         qboolean texscale;
1215         float *old_xyzst = NULL;
1216         float spawn_ref = 0;
1217         
1218         
1219         /* arg checking */
1220         if( argc < 3 )
1221         {
1222                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref <value>] <value> <mapname>\n" );
1223                 return 0;
1224         }
1225         
1226         texscale = qfalse;
1227         for(i = 1; i < argc-2; ++i)
1228         {
1229                 if(!strcmp(argv[i], "-tex"))
1230                 {
1231                         texscale = qtrue;
1232                 }
1233                 else if(!strcmp(argv[i], "-spawn_ref"))
1234                 {
1235                         spawn_ref = atof(argv[i+1]);
1236                         ++i;
1237                 }
1238                 else
1239                         break;
1240         }
1241         
1242         /* get scale */
1243         // if(argc-2 >= i) // always true
1244                 scale[2] = scale[1] = scale[0] = atof( argv[ argc - 2 ] );
1245         if(argc-3 >= i)
1246                 scale[1] = scale[0] = atof( argv[ argc - 3 ] );
1247         if(argc-4 >= i)
1248                 scale[0] = atof( argv[ argc - 4 ] );
1249
1250         uniform = ((scale[0] == scale[1]) && (scale[1] == scale[2]));
1251
1252         if( scale[0] == 0.0f || scale[1] == 0.0f || scale[2] == 0.0f )
1253         {
1254                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref <value>] <value> <mapname>\n" );
1255                 Sys_Printf( "Non-zero scale value required.\n" );
1256                 return 0;
1257         }
1258         
1259         /* do some path mangling */
1260         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
1261         StripExtension( source );
1262         DefaultExtension( source, ".bsp" );
1263         
1264         /* load the bsp */
1265         Sys_Printf( "Loading %s\n", source );
1266         LoadBSPFile( source );
1267         ParseEntities();
1268         
1269         /* note it */
1270         Sys_Printf( "--- ScaleBSP ---\n" );
1271         Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities );
1272         
1273         /* scale entity keys */
1274         for( i = 0; i < numBSPEntities && i < numEntities; i++ )
1275         {
1276                 /* scale origin */
1277                 GetVectorForKey( &entities[ i ], "origin", vec );
1278                 if( (vec[ 0 ] || vec[ 1 ] || vec[ 2 ]) )
1279                 {
1280                         if(!strncmp(ValueForKey(&entities[i], "classname"), "info_player_", 12))
1281                                 vec[2] += spawn_ref;
1282                         vec[0] *= scale[0];
1283                         vec[1] *= scale[1];
1284                         vec[2] *= scale[2];
1285                         if(!strncmp(ValueForKey(&entities[i], "classname"), "info_player_", 12))
1286                                 vec[2] -= spawn_ref;
1287                         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1288                         SetKeyValue( &entities[ i ], "origin", str );
1289                 }
1290
1291                 a = FloatForKey( &entities[ i ], "angle" );
1292                 if(a == -1 || a == -2) // z scale
1293                         axis = 2;
1294                 else if(fabs(sin(DEG2RAD(a))) < 0.707)
1295                         axis = 0;
1296                 else
1297                         axis = 1;
1298                 
1299                 /* scale door lip */
1300                 f = FloatForKey( &entities[ i ], "lip" );
1301                 if( f )
1302                 {
1303                         f *= scale[axis];
1304                         sprintf( str, "%f", f );
1305                         SetKeyValue( &entities[ i ], "lip", str );
1306                 }
1307                 
1308                 /* scale plat height */
1309                 f = FloatForKey( &entities[ i ], "height" );
1310                 if( f )
1311                 {
1312                         f *= scale[2];
1313                         sprintf( str, "%f", f );
1314                         SetKeyValue( &entities[ i ], "height", str );
1315                 }
1316
1317                 // TODO maybe allow a definition file for entities to specify which values are scaled how?
1318         }
1319         
1320         /* scale models */
1321         for( i = 0; i < numBSPModels; i++ )
1322         {
1323                 bspModels[ i ].mins[0] *= scale[0];
1324                 bspModels[ i ].mins[1] *= scale[1];
1325                 bspModels[ i ].mins[2] *= scale[2];
1326                 bspModels[ i ].maxs[0] *= scale[0];
1327                 bspModels[ i ].maxs[1] *= scale[1];
1328                 bspModels[ i ].maxs[2] *= scale[2];
1329         }
1330         
1331         /* scale nodes */
1332         for( i = 0; i < numBSPNodes; i++ )
1333         {
1334                 bspNodes[ i ].mins[0] *= scale[0];
1335                 bspNodes[ i ].mins[1] *= scale[1];
1336                 bspNodes[ i ].mins[2] *= scale[2];
1337                 bspNodes[ i ].maxs[0] *= scale[0];
1338                 bspNodes[ i ].maxs[1] *= scale[1];
1339                 bspNodes[ i ].maxs[2] *= scale[2];
1340         }
1341         
1342         /* scale leafs */
1343         for( i = 0; i < numBSPLeafs; i++ )
1344         {
1345                 bspLeafs[ i ].mins[0] *= scale[0];
1346                 bspLeafs[ i ].mins[1] *= scale[1];
1347                 bspLeafs[ i ].mins[2] *= scale[2];
1348                 bspLeafs[ i ].maxs[0] *= scale[0];
1349                 bspLeafs[ i ].maxs[1] *= scale[1];
1350                 bspLeafs[ i ].maxs[2] *= scale[2];
1351         }
1352         
1353         if(texscale)
1354         {
1355                 Sys_Printf("Using texture unlocking (and probably breaking texture alignment a lot)\n");
1356                 old_xyzst = safe_malloc(sizeof(*old_xyzst) * numBSPDrawVerts * 5);
1357                 for(i = 0; i < numBSPDrawVerts; i++)
1358                 {
1359                         old_xyzst[5*i+0] = bspDrawVerts[i].xyz[0];
1360                         old_xyzst[5*i+1] = bspDrawVerts[i].xyz[1];
1361                         old_xyzst[5*i+2] = bspDrawVerts[i].xyz[2];
1362                         old_xyzst[5*i+3] = bspDrawVerts[i].st[0];
1363                         old_xyzst[5*i+4] = bspDrawVerts[i].st[1];
1364                 }
1365         }
1366
1367         /* scale drawverts */
1368         for( i = 0; i < numBSPDrawVerts; i++ )
1369         {
1370                 bspDrawVerts[i].xyz[0] *= scale[0];
1371                 bspDrawVerts[i].xyz[1] *= scale[1];
1372                 bspDrawVerts[i].xyz[2] *= scale[2];
1373                 bspDrawVerts[i].normal[0] /= scale[0];
1374                 bspDrawVerts[i].normal[1] /= scale[1];
1375                 bspDrawVerts[i].normal[2] /= scale[2];
1376                 VectorNormalize(bspDrawVerts[i].normal, bspDrawVerts[i].normal);
1377         }
1378
1379         if(texscale)
1380         {
1381                 for(i = 0; i < numBSPDrawSurfaces; i++)
1382                 {
1383                         switch(bspDrawSurfaces[i].surfaceType)
1384                         {
1385                                 case SURFACE_FACE:
1386                                 case SURFACE_META:
1387                                         if(bspDrawSurfaces[i].numIndexes % 3)
1388                                                 Error("Not a triangulation!");
1389                                         for(j = bspDrawSurfaces[i].firstIndex; j < bspDrawSurfaces[i].firstIndex + bspDrawSurfaces[i].numIndexes; j += 3)
1390                                         {
1391                                                 int ia = bspDrawIndexes[j] + bspDrawSurfaces[i].firstVert, ib = bspDrawIndexes[j+1] + bspDrawSurfaces[i].firstVert, ic = bspDrawIndexes[j+2] + bspDrawSurfaces[i].firstVert;
1392                                                 bspDrawVert_t *a = &bspDrawVerts[ia], *b = &bspDrawVerts[ib], *c = &bspDrawVerts[ic];
1393                                                 float *oa = &old_xyzst[ia*5], *ob = &old_xyzst[ib*5], *oc = &old_xyzst[ic*5];
1394                                                 // extrapolate:
1395                                                 //   a->xyz -> oa
1396                                                 //   b->xyz -> ob
1397                                                 //   c->xyz -> oc
1398                                                 ExtrapolateTexcoords(
1399                                                         &oa[0], &oa[3],
1400                                                         &ob[0], &ob[3],
1401                                                         &oc[0], &oc[3],
1402                                                         a->xyz, a->st,
1403                                                         b->xyz, b->st,
1404                                                         c->xyz, c->st);
1405                                         }
1406                                         break;
1407                         }
1408                 }
1409         }
1410         
1411         /* scale planes */
1412         if(uniform)
1413         {
1414                 for( i = 0; i < numBSPPlanes; i++ )
1415                 {
1416                         bspPlanes[ i ].dist *= scale[0];
1417                 }
1418         }
1419         else
1420         {
1421                 for( i = 0; i < numBSPPlanes; i++ )
1422                 {
1423                         bspPlanes[ i ].normal[0] /= scale[0];
1424                         bspPlanes[ i ].normal[1] /= scale[1];
1425                         bspPlanes[ i ].normal[2] /= scale[2];
1426                         f = 1/VectorLength(bspPlanes[i].normal);
1427                         VectorScale(bspPlanes[i].normal, f, bspPlanes[i].normal);
1428                         bspPlanes[ i ].dist *= f;
1429                 }
1430         }
1431         
1432         /* scale gridsize */
1433         GetVectorForKey( &entities[ 0 ], "gridsize", vec );
1434         if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) == 0.0f )
1435                 VectorCopy( gridSize, vec );
1436         vec[0] *= scale[0];
1437         vec[1] *= scale[1];
1438         vec[2] *= scale[2];
1439         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1440         SetKeyValue( &entities[ 0 ], "gridsize", str );
1441
1442         /* inject command line parameters */
1443         InjectCommandLine(argv, 0, argc - 1);
1444         
1445         /* write the bsp */
1446         UnparseEntities();
1447         StripExtension( source );
1448         DefaultExtension( source, "_s.bsp" );
1449         Sys_Printf( "Writing %s\n", source );
1450         WriteBSPFile( source );
1451         
1452         /* return to sender */
1453         return 0;
1454 }
1455
1456
1457 /*
1458 PseudoCompileBSP()
1459 a stripped down ProcessModels
1460 */
1461 void PseudoCompileBSP(qboolean need_tree)
1462 {
1463         int models;
1464         char modelValue[10];
1465         entity_t *entity;
1466         face_t *faces;
1467         tree_t *tree;
1468         node_t *node;
1469         brush_t *brush;
1470         side_t *side;
1471         int i;
1472
1473         SetDrawSurfacesBuffer();
1474         mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
1475         memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
1476         numMapDrawSurfs = 0;
1477
1478         BeginBSPFile();
1479         models = 1;
1480         for( mapEntityNum = 0; mapEntityNum < numEntities; mapEntityNum++ )
1481         {
1482                 /* get entity */
1483                 entity = &entities[ mapEntityNum ];
1484                 if( entity->brushes == NULL && entity->patches == NULL )
1485                         continue;
1486
1487                 if(mapEntityNum != 0)
1488                 {
1489                         sprintf( modelValue, "*%d", models++);
1490                         SetKeyValue(entity, "model", modelValue);
1491                 }
1492                 
1493                 /* process the model */
1494                 Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", numBSPModels );
1495                 BeginModel();
1496
1497                 entity->firstDrawSurf = numMapDrawSurfs;
1498
1499                 ClearMetaTriangles();
1500                 PatchMapDrawSurfs(entity);
1501
1502                 if(mapEntityNum == 0 && need_tree)
1503                 {
1504                         faces = MakeStructuralBSPFaceList(entities[0].brushes);
1505                         tree = FaceBSP(faces);
1506                         node = tree->headnode;
1507                 }
1508                 else
1509                 {
1510                         node = AllocNode();
1511                         node->planenum = PLANENUM_LEAF;
1512                         tree = AllocTree();
1513                         tree->headnode = node;
1514                 }
1515
1516                 /* a minimized ClipSidesIntoTree */
1517                 for( brush = entity->brushes; brush; brush = brush->next )
1518                 {
1519                         /* walk the brush sides */
1520                         for( i = 0; i < brush->numsides; i++ )
1521                         {
1522                                 /* get side */
1523                                 side = &brush->sides[ i ];
1524                                 if( side->winding == NULL )
1525                                         continue;
1526                                 /* shader? */
1527                                 if( side->shaderInfo == NULL )
1528                                         continue;
1529                                 /* save this winding as a visible surface */
1530                                 DrawSurfaceForSide(entity, brush, side, side->winding);
1531                         }
1532                 }
1533
1534                 if(meta)
1535                 {
1536                         ClassifyEntitySurfaces(entity);
1537                         MakeEntityDecals(entity);
1538                         MakeEntityMetaTriangles(entity);
1539                         SmoothMetaTriangles();
1540                         MergeMetaTriangles();
1541                 }
1542                 FilterDrawsurfsIntoTree(entity, tree);
1543
1544                 FilterStructuralBrushesIntoTree(entity, tree);
1545                 FilterDetailBrushesIntoTree(entity, tree);
1546
1547                 EmitBrushes(entity->brushes, &entity->firstBrush, &entity->numBrushes );
1548                 EndModel(entity, node);
1549         }
1550         EndBSPFile(qfalse);
1551 }
1552
1553 /*
1554 ConvertBSPMain()
1555 main argument processing function for bsp conversion
1556 */
1557
1558 int ConvertBSPMain( int argc, char **argv )
1559 {
1560         int             i;
1561         int             (*convertFunc)( char * );
1562         game_t  *convertGame;
1563         char            ext[1024];
1564         qboolean        map_allowed, force_bsp, force_map;
1565         
1566         
1567         /* set default */
1568         convertFunc = ConvertBSPToASE;
1569         convertGame = NULL;
1570         map_allowed = qfalse;
1571         force_bsp = qfalse;
1572         force_map = qfalse;
1573         
1574         /* arg checking */
1575         if( argc < 1 )
1576         {
1577                 Sys_Printf( "Usage: q3map -convert -format <ase|obj|map_bp|map> [-shadesasbitmap|-lightmapsastexcoord|-deluxemapsastexcoord] [-readbsp|-readmap [-meta|-patchmeta]] <mapname>\n" );
1578                 return 0;
1579         }
1580         
1581         /* process arguments */
1582         for( i = 1; i < (argc - 1); i++ )
1583         {
1584                 /* -format map|ase|... */
1585                 if( !strcmp( argv[ i ],  "-format" ) )
1586                 {
1587                         i++;
1588                         if( !Q_stricmp( argv[ i ], "ase" ) )
1589                         {
1590                                 convertFunc = ConvertBSPToASE;
1591                                 map_allowed = qfalse;
1592                         }
1593                         else if( !Q_stricmp( argv[ i ], "obj" ) )
1594                         {
1595                                 convertFunc = ConvertBSPToOBJ;
1596                                 map_allowed = qfalse;
1597                         }
1598                         else if( !Q_stricmp( argv[ i ], "map_bp" ) )
1599                         {
1600                                 convertFunc = ConvertBSPToMap_BP;
1601                                 map_allowed = qtrue;
1602                         }
1603                         else if( !Q_stricmp( argv[ i ], "map" ) )
1604                         {
1605                                 convertFunc = ConvertBSPToMap;
1606                                 map_allowed = qtrue;
1607                         }
1608                         else
1609                         {
1610                                 convertGame = GetGame( argv[ i ] );
1611                                 map_allowed = qfalse;
1612                                 if( convertGame == NULL )
1613                                         Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] );
1614                         }
1615                 }
1616                 else if( !strcmp( argv[ i ],  "-ne" ) )
1617                 {
1618                         normalEpsilon = atof( argv[ i + 1 ] );
1619                         i++;
1620                         Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon );
1621                 }
1622                 else if( !strcmp( argv[ i ],  "-de" ) )
1623                 {
1624                         distanceEpsilon = atof( argv[ i + 1 ] );
1625                         i++;
1626                         Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon );
1627                 }
1628                 else if( !strcmp( argv[ i ],  "-shaderasbitmap" ) || !strcmp( argv[ i ],  "-shadersasbitmap" ) )
1629                         shadersAsBitmap = qtrue;
1630                 else if( !strcmp( argv[ i ],  "-lightmapastexcoord" ) || !strcmp( argv[ i ],  "-lightmapsastexcoord" ) )
1631                         lightmapsAsTexcoord = qtrue;
1632                 else if( !strcmp( argv[ i ],  "-deluxemapastexcoord" ) || !strcmp( argv[ i ],  "-deluxemapsastexcoord" ) )
1633                 {
1634                         lightmapsAsTexcoord = qtrue;
1635                         deluxemap = qtrue;
1636                 }
1637                 else if( !strcmp( argv[ i ],  "-readbsp" ) )
1638                         force_bsp = qtrue;
1639                 else if( !strcmp( argv[ i ],  "-readmap" ) )
1640                         force_map = qtrue;
1641                 else if( !strcmp( argv[ i ],  "-meta" ) )
1642                         meta = qtrue;
1643                 else if( !strcmp( argv[ i ],  "-patchmeta" ) )
1644                 {
1645                         meta = qtrue;
1646                         patchMeta = qtrue;
1647                 }
1648         }
1649
1650         LoadShaderInfo();
1651         
1652         /* clean up map name */
1653         strcpy(source, ExpandArg(argv[i]));
1654         ExtractFileExtension(source, ext);
1655
1656         if(!map_allowed && !force_map)
1657                 force_bsp = qtrue;
1658
1659         if(force_map || (!force_bsp && !Q_stricmp(ext, "map") && map_allowed))
1660         {
1661                 if(!map_allowed)
1662                         Sys_Printf("WARNING: the requested conversion should not be done from .map files. Compile a .bsp first.\n");
1663                 StripExtension(source);
1664                 DefaultExtension(source, ".map");
1665                 Sys_Printf("Loading %s\n", source);
1666                 LoadMapFile(source, qfalse, convertGame == NULL);
1667                 PseudoCompileBSP(convertGame != NULL);
1668         }
1669         else
1670         {
1671                 StripExtension(source);
1672                 DefaultExtension(source, ".bsp");
1673                 Sys_Printf("Loading %s\n", source);
1674                 LoadBSPFile(source);
1675                 ParseEntities();
1676         }
1677         
1678         /* bsp format convert? */
1679         if( convertGame != NULL )
1680         {
1681                 /* set global game */
1682                 game = convertGame;
1683                 
1684                 /* write bsp */
1685                 StripExtension( source );
1686                 DefaultExtension( source, "_c.bsp" );
1687                 Sys_Printf( "Writing %s\n", source );
1688                 WriteBSPFile( source );
1689                 
1690                 /* return to sender */
1691                 return 0;
1692         }
1693         
1694         /* normal convert */
1695         return convertFunc( source );
1696 }
1697
1698
1699
1700 /*
1701 main()
1702 q3map mojo...
1703 */
1704
1705 int main( int argc, char **argv )
1706 {
1707         int             i, r;
1708         double  start, end;
1709         
1710         
1711         /* we want consistent 'randomness' */
1712         srand( 0 );
1713         
1714         /* start timer */
1715         start = I_FloatTime();
1716
1717         /* this was changed to emit version number over the network */
1718         printf( Q3MAP_VERSION "\n" );
1719         
1720         /* set exit call */
1721         atexit( ExitQ3Map );
1722
1723         /* read general options first */
1724         for( i = 1; i < argc; i++ )
1725         {
1726                 /* -connect */
1727                 if( !strcmp( argv[ i ], "-connect" ) )
1728                 {
1729                         argv[ i ] = NULL;
1730                         i++;
1731                         Broadcast_Setup( argv[ i ] );
1732                         argv[ i ] = NULL;
1733                 }
1734                 
1735                 /* verbose */
1736                 else if( !strcmp( argv[ i ], "-v" ) )
1737                 {
1738                         if(!verbose)
1739                         {
1740                                 verbose = qtrue;
1741                                 argv[ i ] = NULL;
1742                         }
1743                 }
1744                 
1745                 /* force */
1746                 else if( !strcmp( argv[ i ], "-force" ) )
1747                 {
1748                         force = qtrue;
1749                         argv[ i ] = NULL;
1750                 }
1751                 
1752                 /* patch subdivisions */
1753                 else if( !strcmp( argv[ i ], "-subdivisions" ) )
1754                 {
1755                         argv[ i ] = NULL;
1756                         i++;
1757                         patchSubdivisions = atoi( argv[ i ] );
1758                         argv[ i ] = NULL;
1759                         if( patchSubdivisions <= 0 )
1760                                 patchSubdivisions = 1;
1761                 }
1762                 
1763                 /* threads */
1764                 else if( !strcmp( argv[ i ], "-threads" ) )
1765                 {
1766                         argv[ i ] = NULL;
1767                         i++;
1768                         numthreads = atoi( argv[ i ] );
1769                         argv[ i ] = NULL;
1770                 }
1771         }
1772
1773         /* init model library */
1774         PicoInit();
1775         PicoSetMallocFunc( safe_malloc );
1776         PicoSetFreeFunc( free );
1777         PicoSetPrintFunc( PicoPrintFunc );
1778         PicoSetLoadFileFunc( PicoLoadFileFunc );
1779         PicoSetFreeFileFunc( free );
1780         
1781         /* set number of threads */
1782         ThreadSetDefault();
1783         
1784         /* generate sinusoid jitter table */
1785         for( i = 0; i < MAX_JITTERS; i++ )
1786         {
1787                 jitters[ i ] = sin( i * 139.54152147 );
1788                 //%     Sys_Printf( "Jitter %4d: %f\n", i, jitters[ i ] );
1789         }
1790         
1791         /* we print out two versions, q3map's main version (since it evolves a bit out of GtkRadiant)
1792            and we put the GtkRadiant version to make it easy to track with what version of Radiant it was built with */
1793         
1794         Sys_Printf( "Q3Map         - v1.0r (c) 1999 Id Software Inc.\n" );
1795         Sys_Printf( "Q3Map (ydnar) - v" Q3MAP_VERSION "\n" );
1796         Sys_Printf( "NetRadiant    - v" RADIANT_VERSION " " __DATE__ " " __TIME__ "\n" );
1797         Sys_Printf( "%s\n", Q3MAP_MOTD );
1798         
1799         /* ydnar: new path initialization */
1800         InitPaths( &argc, argv );
1801
1802         /* set game options */
1803         if (!patchSubdivisions)
1804                 patchSubdivisions = game->patchSubdivisions;
1805         
1806         /* check if we have enough options left to attempt something */
1807         if( argc < 2 )
1808                 Error( "Usage: %s [general options] [options] mapfile", argv[ 0 ] );
1809         
1810         /* fixaas */
1811         if( !strcmp( argv[ 1 ], "-fixaas" ) )
1812                 r = FixAAS( argc - 1, argv + 1 );
1813         
1814         /* analyze */
1815         else if( !strcmp( argv[ 1 ], "-analyze" ) )
1816                 r = AnalyzeBSP( argc - 1, argv + 1 );
1817         
1818         /* info */
1819         else if( !strcmp( argv[ 1 ], "-info" ) )
1820                 r = BSPInfo( argc - 2, argv + 2 );
1821         
1822         /* vis */
1823         else if( !strcmp( argv[ 1 ], "-vis" ) )
1824                 r = VisMain( argc - 1, argv + 1 );
1825         
1826         /* light */
1827         else if( !strcmp( argv[ 1 ], "-light" ) )
1828                 r = LightMain( argc - 1, argv + 1 );
1829         
1830         /* vlight */
1831         else if( !strcmp( argv[ 1 ], "-vlight" ) )
1832         {
1833                 Sys_Printf( "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" );
1834                 argv[ 1 ] = "-fast";    /* eek a hack */
1835                 r = LightMain( argc, argv );
1836         }
1837         
1838         /* ydnar: lightmap export */
1839         else if( !strcmp( argv[ 1 ], "-export" ) )
1840                 r = ExportLightmapsMain( argc - 1, argv + 1 );
1841         
1842         /* ydnar: lightmap import */
1843         else if( !strcmp( argv[ 1 ], "-import" ) )
1844                 r = ImportLightmapsMain( argc - 1, argv + 1 );
1845         
1846         /* ydnar: bsp scaling */
1847         else if( !strcmp( argv[ 1 ], "-scale" ) )
1848                 r = ScaleBSPMain( argc - 1, argv + 1 );
1849         
1850         /* ydnar: bsp conversion */
1851         else if( !strcmp( argv[ 1 ], "-convert" ) )
1852                 r = ConvertBSPMain( argc - 1, argv + 1 );
1853         
1854         /* div0: minimap */
1855         else if( !strcmp( argv[ 1 ], "-minimap" ) )
1856                 r = MiniMapBSPMain(argc - 1, argv + 1);
1857
1858         /* ydnar: otherwise create a bsp */
1859         else
1860                 r = BSPMain( argc, argv );
1861         
1862         /* emit time */
1863         end = I_FloatTime();
1864         Sys_Printf( "%9.0f seconds elapsed\n", end - start );
1865         
1866         /* shut down connection */
1867         Broadcast_Shutdown();
1868         
1869         /* return any error code */
1870         return r;
1871 }