File: AASBuild.cpp

package info (click to toggle)
dhewm3 1.5.1~pre%2Bgit20200905%2Bdfsg-1
  • links: PTS, VCS
  • area: contrib
  • in suites: bullseye
  • size: 21,664 kB
  • sloc: cpp: 408,868; ansic: 1,188; objc: 1,034; python: 330; sh: 94; makefile: 11
file content (1033 lines) | stat: -rw-r--r-- 25,548 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
/*
===========================================================================

Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.

This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").

Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Doom 3 Source Code.  If not, see <http://www.gnu.org/licenses/>.

In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code.  If not, please request a copy in writing from id Software at the address below.

If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.

===========================================================================
*/

#include "sys/platform.h"
#include "framework/FileSystem.h"
#include "framework/Game.h"
#include "renderer/RenderWorld.h"

#include "tools/compilers/aas/AASBuild_local.h"

#define BFL_PATCH		0x1000

//===============================================================
//
//	idAASBuild
//
//===============================================================

/*
============
idAASBuild::idAASBuild
============
*/
idAASBuild::idAASBuild( void ) {
	file = NULL;
	procNodes = NULL;
	numProcNodes = 0;
	numGravitationalSubdivisions = 0;
	numMergedLeafNodes = 0;
	numLedgeSubdivisions = 0;
	ledgeMap = NULL;
}

/*
============
idAASBuild::~idAASBuild
============
*/
idAASBuild::~idAASBuild( void ) {
	Shutdown();
}

/*
================
idAASBuild::Shutdown
================
*/
void idAASBuild::Shutdown( void ) {
	aasSettings = NULL;
	if ( file ) {
		delete file;
		file = NULL;
	}
	DeleteProcBSP();
	numGravitationalSubdivisions = 0;
	numMergedLeafNodes = 0;
	numLedgeSubdivisions = 0;
	ledgeList.Clear();
	if ( ledgeMap ) {
		delete ledgeMap;
		ledgeMap = NULL;
	}
}

/*
================
idAASBuild::ParseProcNodes
================
*/
void idAASBuild::ParseProcNodes( idLexer *src ) {
	int i;

	src->ExpectTokenString( "{" );

	idAASBuild::numProcNodes = src->ParseInt();
	if ( idAASBuild::numProcNodes < 0 ) {
		src->Error( "idAASBuild::ParseProcNodes: bad numProcNodes" );
	}
	idAASBuild::procNodes = (aasProcNode_t *)Mem_ClearedAlloc( idAASBuild::numProcNodes * sizeof( aasProcNode_t ) );

	for ( i = 0; i < idAASBuild::numProcNodes; i++ ) {
		aasProcNode_t *node;

		node = &(idAASBuild::procNodes[i]);

		src->Parse1DMatrix( 4, node->plane.ToFloatPtr() );
		node->children[0] = src->ParseInt();
		node->children[1] = src->ParseInt();
	}

	src->ExpectTokenString( "}" );
}

/*
================
idAASBuild::LoadProcBSP
================
*/
bool idAASBuild::LoadProcBSP( const char *name, ID_TIME_T minFileTime ) {
	idStr fileName;
	idToken token;
	idLexer *src;

	// load it
	fileName = name;
	fileName.SetFileExtension( PROC_FILE_EXT );
	src = new idLexer( fileName, LEXFL_NOSTRINGCONCAT | LEXFL_NODOLLARPRECOMPILE );
	if ( !src->IsLoaded() ) {
		common->Warning("idAASBuild::LoadProcBSP: couldn't load %s", fileName.c_str() );
		delete src;
		return false;
	}

	// if the file is too old
	if ( src->GetFileTime() < minFileTime ) {
		delete src;
		return false;
	}

	if ( !src->ReadToken( &token ) || token.Icmp( PROC_FILE_ID ) ) {
		common->Warning( "idAASBuild::LoadProcBSP: bad id '%s' instead of '%s'", token.c_str(), PROC_FILE_ID );
		delete src;
		return false;
	}

	// parse the file
	while ( 1 ) {
		if ( !src->ReadToken( &token ) ) {
			break;
		}

		if ( token == "model" ) {
			src->SkipBracedSection();
			continue;
		}

		if ( token == "shadowModel" ) {
			src->SkipBracedSection();
			continue;
		}

		if ( token == "interAreaPortals" ) {
			src->SkipBracedSection();
			continue;
		}

		if ( token == "nodes" ) {
			idAASBuild::ParseProcNodes( src );
			break;
		}

		src->Error( "idAASBuild::LoadProcBSP: bad token \"%s\"", token.c_str() );
	}

	delete src;

	return true;
}

/*
============
idAASBuild::DeleteProcBSP
============
*/
void idAASBuild::DeleteProcBSP( void ) {
	if ( procNodes ) {
		Mem_Free( procNodes );
		procNodes = NULL;
	}
	numProcNodes = 0;
}

/*
============
idAASBuild::ChoppedAwayByProcBSP
============
*/
bool idAASBuild::ChoppedAwayByProcBSP( int nodeNum, idFixedWinding *w, const idVec3 &normal, const idVec3 &origin, const float radius ) {
	int res;
	idFixedWinding back;
	aasProcNode_t *node;
	float dist;

	do {
		node = idAASBuild::procNodes + nodeNum;
		dist = node->plane.Normal() * origin + node->plane[3];
		if ( dist > radius ) {
			res = SIDE_FRONT;
		}
		else if ( dist < -radius ) {
			res = SIDE_BACK;
		}
		else {
			res = w->Split( &back, node->plane, ON_EPSILON );
		}
		if ( res == SIDE_FRONT ) {
			nodeNum = node->children[0];
		}
		else if ( res == SIDE_BACK ) {
			nodeNum = node->children[1];
		}
		else if ( res == SIDE_ON ) {
			// continue with the side the winding faces
			if ( node->plane.Normal() * normal > 0.0f ) {
				nodeNum = node->children[0];
			}
			else {
				nodeNum = node->children[1];
			}
		}
		else {
			// if either node is not solid
			if ( node->children[0] < 0 || node->children[1] < 0 ) {
				return false;
			}
			// only recurse if the node is not solid
			if ( node->children[1] > 0 ) {
				if ( !idAASBuild::ChoppedAwayByProcBSP( node->children[1], &back, normal, origin, radius ) ) {
					return false;
				}
			}
			nodeNum = node->children[0];
		}
	} while ( nodeNum > 0 );
	if ( nodeNum < 0 ) {
		return false;
	}
	return true;
}

/*
============
idAASBuild::ClipBrushSidesWithProcBSP
============
*/
void idAASBuild::ClipBrushSidesWithProcBSP( idBrushList &brushList ) {
	int i, clippedSides;
	idBrush *brush;
	idFixedWinding neww;
	idBounds bounds;
	float radius;
	idVec3 origin;

	// if the .proc file has no BSP tree
	if ( idAASBuild::procNodes == NULL ) {
		return;
	}

	clippedSides = 0;
	for ( brush = brushList.Head(); brush; brush = brush->Next() ) {
		for ( i = 0; i < brush->GetNumSides(); i++ ) {

			if ( !brush->GetSide(i)->GetWinding() ) {
				continue;
			}

			// make a local copy of the winding
			neww = *brush->GetSide(i)->GetWinding();
			neww.GetBounds( bounds );
			origin = (bounds[1] - bounds[0]) * 0.5f;
			radius = origin.Length() + ON_EPSILON;
			origin = bounds[0] + origin;

			if ( ChoppedAwayByProcBSP( 0, &neww, brush->GetSide(i)->GetPlane().Normal(), origin, radius ) ) {
				brush->GetSide(i)->SetFlag( SFL_USED_SPLITTER );
				clippedSides++;
			}
		}
	}

	common->Printf( "%6d brush sides clipped\n", clippedSides );
}

/*
============
idAASBuild::ContentsForAAS
============
*/
int idAASBuild::ContentsForAAS( int contents ) {
	int c;

	if ( contents & ( CONTENTS_SOLID|CONTENTS_AAS_SOLID|CONTENTS_MONSTERCLIP ) ) {
		return AREACONTENTS_SOLID;
	}
	c = 0;
	if ( contents & CONTENTS_WATER ) {
		c |= AREACONTENTS_WATER;
	}
	if ( contents & CONTENTS_AREAPORTAL ) {
		c |= AREACONTENTS_CLUSTERPORTAL;
	}
	if ( contents & CONTENTS_AAS_OBSTACLE ) {
		c |= AREACONTENTS_OBSTACLE;
	}
	return c;
}

/*
============
idAASBuild::AddBrushForMapBrush
============
*/
idBrushList idAASBuild::AddBrushesForMapBrush( const idMapBrush *mapBrush, const idVec3 &origin, const idMat3 &axis, int entityNum, int primitiveNum, idBrushList brushList ) {
	int contents, i;
	idMapBrushSide *mapSide;
	const idMaterial *mat;
	idList<idBrushSide *> sideList;
	idBrush *brush;
	idPlane plane;

	contents = 0;
	for ( i = 0; i < mapBrush->GetNumSides(); i++ ) {
		mapSide = mapBrush->GetSide(i);
		mat = declManager->FindMaterial( mapSide->GetMaterial() );
		contents |= mat->GetContentFlags();
		plane = mapSide->GetPlane();
		plane.FixDegeneracies( DEGENERATE_DIST_EPSILON );
		sideList.Append( new idBrushSide( plane, -1 ) );
	}

	contents = ContentsForAAS( contents );
	if ( !contents ) {
		for ( i = 0; i < sideList.Num(); i++ ) {
			delete sideList[i];
		}
		return brushList;
	}

	brush = new idBrush();
	brush->SetContents( contents );

	if ( !brush->FromSides( sideList ) ) {
		common->Warning( "brush primitive %d on entity %d is degenerate", primitiveNum, entityNum );
		delete brush;
		return brushList;
	}

	brush->SetEntityNum( entityNum );
	brush->SetPrimitiveNum( primitiveNum );
	brush->Transform( origin, axis );
	brushList.AddToTail( brush );

	return brushList;
}

/*
============
idAASBuild::AddBrushesForPatch
============
*/
idBrushList idAASBuild::AddBrushesForMapPatch( const idMapPatch *mapPatch, const idVec3 &origin, const idMat3 &axis, int entityNum, int primitiveNum, idBrushList brushList ) {
	int i, j, contents, validBrushes;
	float dot;
	int v1, v2, v3, v4;
	idFixedWinding w;
	idPlane plane;
	idVec3 d1, d2;
	idBrush *brush;
	idSurface_Patch mesh;
	const idMaterial *mat;

	mat = declManager->FindMaterial( mapPatch->GetMaterial() );
	contents = ContentsForAAS( mat->GetContentFlags() );

	if ( !contents ) {
		return brushList;
	}

	mesh = idSurface_Patch( *mapPatch );

	// if the patch has an explicit number of subdivisions use it to avoid cracks
	if ( mapPatch->GetExplicitlySubdivided() ) {
		mesh.SubdivideExplicit( mapPatch->GetHorzSubdivisions(), mapPatch->GetVertSubdivisions(), false, true );
	} else {
		mesh.Subdivide( DEFAULT_CURVE_MAX_ERROR_CD, DEFAULT_CURVE_MAX_ERROR_CD, DEFAULT_CURVE_MAX_LENGTH_CD, false );
	}

	validBrushes = 0;

	for ( i = 0; i < mesh.GetWidth() - 1; i++ ) {
		for ( j = 0; j < mesh.GetHeight() - 1; j++ ) {

			v1 = j * mesh.GetWidth() + i;
			v2 = v1 + 1;
			v3 = v1 + mesh.GetWidth() + 1;
			v4 = v1 + mesh.GetWidth();

			d1 = mesh[v2].xyz - mesh[v1].xyz;
			d2 = mesh[v3].xyz - mesh[v1].xyz;
			plane.SetNormal( d1.Cross(d2) );
			if ( plane.Normalize() != 0.0f ) {
				plane.FitThroughPoint( mesh[v1].xyz );
				dot = plane.Distance( mesh[v4].xyz );
				// if we can turn it into a quad
				if ( idMath::Fabs(dot) < 0.1f ) {
					w.Clear();
					w += mesh[v1].xyz;
					w += mesh[v2].xyz;
					w += mesh[v3].xyz;
					w += mesh[v4].xyz;

					brush = new idBrush();
					brush->SetContents( contents );
					if ( brush->FromWinding( w, plane ) ) {
						brush->SetEntityNum( entityNum );
						brush->SetPrimitiveNum( primitiveNum );
						brush->SetFlag( BFL_PATCH );
						brush->Transform( origin, axis );
						brushList.AddToTail( brush );
						validBrushes++;
					}
					else {
						delete brush;
					}
					continue;
				}
				else {
					// create one of the triangles
					w.Clear();
					w += mesh[v1].xyz;
					w += mesh[v2].xyz;
					w += mesh[v3].xyz;

					brush = new idBrush();
					brush->SetContents( contents );
					if ( brush->FromWinding( w, plane ) ) {
						brush->SetEntityNum( entityNum );
						brush->SetPrimitiveNum( primitiveNum );
						brush->SetFlag( BFL_PATCH );
						brush->Transform( origin, axis );
						brushList.AddToTail( brush );
						validBrushes++;
					}
					else {
						delete brush;
					}
				}
			}
			// create the other triangle
			d1 = mesh[v3].xyz - mesh[v1].xyz;
			d2 = mesh[v4].xyz - mesh[v1].xyz;
			plane.SetNormal( d1.Cross(d2) );
			if ( plane.Normalize() != 0.0f ) {
				plane.FitThroughPoint( mesh[v1].xyz );

				w.Clear();
				w += mesh[v1].xyz;
				w += mesh[v3].xyz;
				w += mesh[v4].xyz;

				brush = new idBrush();
				brush->SetContents( contents );
				if ( brush->FromWinding( w, plane ) ) {
					brush->SetEntityNum( entityNum );
					brush->SetPrimitiveNum( primitiveNum );
					brush->SetFlag( BFL_PATCH );
					brush->Transform( origin, axis );
					brushList.AddToTail( brush );
					validBrushes++;
				}
				else {
					delete brush;
				}
			}
		}
	}

	if ( !validBrushes ) {
		common->Warning( "patch primitive %d on entity %d is completely degenerate", primitiveNum, entityNum );
	}

	return brushList;
}

/*
============
idAASBuild::AddBrushesForMapEntity
============
*/
idBrushList idAASBuild::AddBrushesForMapEntity( const idMapEntity *mapEnt, int entityNum, idBrushList brushList ) {
	int i;
	idVec3 origin;
	idMat3 axis;

	if ( mapEnt->GetNumPrimitives() < 1 ) {
		return brushList;
	}

	mapEnt->epairs.GetVector( "origin", "0 0 0", origin );
	if ( !mapEnt->epairs.GetMatrix( "rotation", "1 0 0 0 1 0 0 0 1", axis ) ) {
		float angle = mapEnt->epairs.GetFloat( "angle" );
		if ( angle != 0.0f ) {
			axis = idAngles( 0.0f, angle, 0.0f ).ToMat3();
		} else {
			axis.Identity();
		}
	}

	for ( i = 0; i < mapEnt->GetNumPrimitives(); i++ ) {
		idMapPrimitive	*mapPrim;

		mapPrim = mapEnt->GetPrimitive(i);
		if ( mapPrim->GetType() == idMapPrimitive::TYPE_BRUSH ) {
			brushList = AddBrushesForMapBrush( static_cast<idMapBrush*>(mapPrim), origin, axis, entityNum, i, brushList );
			continue;
		}
		if ( mapPrim->GetType() == idMapPrimitive::TYPE_PATCH ) {
			if ( aasSettings->usePatches ) {
				brushList = AddBrushesForMapPatch( static_cast<idMapPatch*>(mapPrim), origin, axis, entityNum, i, brushList );
			}
			continue;
		}
	}

	return brushList;
}

/*
============
idAASBuild::AddBrushesForMapFile
============
*/
idBrushList idAASBuild::AddBrushesForMapFile( const idMapFile * mapFile, idBrushList brushList ) {
	int i;

	common->Printf( "[Brush Load]\n" );

	brushList = AddBrushesForMapEntity( mapFile->GetEntity( 0 ), 0, brushList );

	for ( i = 1; i < mapFile->GetNumEntities(); i++ ) {
		const char *classname = mapFile->GetEntity( i )->epairs.GetString( "classname" );

		if ( idStr::Icmp( classname, "func_aas_obstacle" ) == 0 ) {
			brushList = AddBrushesForMapEntity( mapFile->GetEntity( i ), i, brushList );
		}
	}

	common->Printf( "%6d brushes\n", brushList.Num() );

	return brushList;
}

/*
============
idAASBuild::CheckForEntities
============
*/
bool idAASBuild::CheckForEntities( const idMapFile *mapFile, idStrList &entityClassNames ) const {
	int		i;
	idStr	classname;

	com_editors |= EDITOR_AAS;

	for ( i = 0; i < mapFile->GetNumEntities(); i++ ) {
		if ( !mapFile->GetEntity(i)->epairs.GetString( "classname", "", classname ) ) {
			continue;
		}

		if ( aasSettings->ValidEntity( classname ) ) {
			entityClassNames.AddUnique( classname );
		}
	}

	com_editors &= ~EDITOR_AAS;

	return ( entityClassNames.Num() != 0 );
}

/*
============
MergeAllowed
============
*/
bool MergeAllowed( idBrush *b1, idBrush *b2 ) {
	return ( b1->GetContents() == b2->GetContents() && !( ( b1->GetFlags() | b2->GetFlags() ) & BFL_PATCH ) );
}

/*
============
ExpandedChopAllowed
============
*/
bool ExpandedChopAllowed( idBrush *b1, idBrush *b2 ) {
	return ( b1->GetContents() == b2->GetContents() );
}

/*
============
ExpandedMergeAllowed
============
*/
bool ExpandedMergeAllowed( idBrush *b1, idBrush *b2 ) {
	return ( b1->GetContents() == b2->GetContents() );
}

/*
============
idAASBuild::ChangeMultipleBoundingBoxContents
============
*/
void idAASBuild::ChangeMultipleBoundingBoxContents_r( idBrushBSPNode *node, int mask ) {
	while( node ) {
		if ( !( node->GetContents() & mask ) ) {
			node->SetContents( node->GetContents() & ~AREACONTENTS_SOLID );
		}
		ChangeMultipleBoundingBoxContents_r( node->GetChild( 0 ), mask );
		node = node->GetChild( 1 );
	}
}

/*
============
idAASBuild::Build
============
*/
bool idAASBuild::Build( const idStr &fileName, const idAASSettings *settings ) {
	int i, bit, mask, startTime;
	idMapFile * mapFile;
	idBrushList brushList;
	idList<idBrushList*> expandedBrushes;
	idBrush *b;
	idBrushBSP bsp;
	idStr name;
	idAASReach reach;
	idAASCluster cluster;
	idStrList entityClassNames;

	startTime = Sys_Milliseconds();

	Shutdown();

	aasSettings = settings;

	name = fileName;
	name.SetFileExtension( "map" );

	mapFile = new idMapFile;
	if ( !mapFile->Parse( name ) ) {
		delete mapFile;
		common->Error( "Couldn't load map file: '%s'", name.c_str() );
		return false;
	}

	// check if this map has any entities that use this AAS file
	if ( !CheckForEntities( mapFile, entityClassNames ) ) {
		delete mapFile;
		common->Printf( "no entities in map that use %s\n", settings->fileExtension.c_str() );
		return true;
	}

	// load map file brushes
	brushList = AddBrushesForMapFile( mapFile, brushList );

	// if empty map
	if ( brushList.Num() == 0 ) {
		delete mapFile;
		common->Error( "%s is empty", name.c_str() );
		return false;
	}

	// merge as many brushes as possible before expansion
	brushList.Merge( MergeAllowed );

	// if there is a .proc file newer than the .map file
	if ( LoadProcBSP( fileName, mapFile->GetFileTime() ) ) {
		ClipBrushSidesWithProcBSP( brushList );
		DeleteProcBSP();
	}

	// make copies of the brush list
	expandedBrushes.Append( &brushList );
	for ( i = 1; i < aasSettings->numBoundingBoxes; i++ ) {
		expandedBrushes.Append( brushList.Copy() );
	}

	// expand brushes for the axial bounding boxes
	mask = AREACONTENTS_SOLID;
	for ( i = 0; i < expandedBrushes.Num(); i++ ) {
		for ( b = expandedBrushes[i]->Head(); b; b = b->Next() ) {
			b->ExpandForAxialBox( aasSettings->boundingBoxes[i] );
			bit = 1 << ( i + AREACONTENTS_BBOX_BIT );
			mask |= bit;
			b->SetContents( b->GetContents() | bit );
		}
	}

	// move all brushes back into the original list
	for ( i = 1; i < aasSettings->numBoundingBoxes; i++ ) {
		brushList.AddToTail( *expandedBrushes[i] );
		delete expandedBrushes[i];
	}

	if ( aasSettings->writeBrushMap ) {
		bsp.WriteBrushMap( fileName, "_" + aasSettings->fileExtension, AREACONTENTS_SOLID );
	}

	// build BSP tree from brushes
	bsp.Build( brushList, AREACONTENTS_SOLID, ExpandedChopAllowed, ExpandedMergeAllowed );

	// only solid nodes with all bits set for all bounding boxes need to stay solid
	ChangeMultipleBoundingBoxContents_r( bsp.GetRootNode(), mask );

	// portalize the bsp tree
	bsp.Portalize();

	// remove subspaces not reachable by entities
	if ( !bsp.RemoveOutside( mapFile, AREACONTENTS_SOLID, entityClassNames ) ) {
		bsp.LeakFile( name );
		delete mapFile;
		common->Printf( "%s has no outside", name.c_str() );
		return false;
	}

	// gravitational subdivision
	GravitationalSubdivision( bsp );

	// merge portals where possible
	bsp.MergePortals( AREACONTENTS_SOLID );

	// melt portal windings
	bsp.MeltPortals( AREACONTENTS_SOLID );

	if ( aasSettings->writeBrushMap ) {
		WriteLedgeMap( fileName, "_" + aasSettings->fileExtension + "_ledge" );
	}

	// ledge subdivisions
	LedgeSubdivision( bsp );

	// merge leaf nodes
	MergeLeafNodes( bsp );

	// merge portals where possible
	bsp.MergePortals( AREACONTENTS_SOLID );

	// melt portal windings
	bsp.MeltPortals( AREACONTENTS_SOLID );

	// store the file from the bsp tree
	StoreFile( bsp );
	file->settings = *aasSettings;

	// calculate reachability
	reach.Build( mapFile, file );

	// build clusters
	cluster.Build( file );

	// optimize the file
	if ( !aasSettings->noOptimize ) {
		file->Optimize();
	}

	// write the file
	name.SetFileExtension( aasSettings->fileExtension );
	file->Write( name, mapFile->GetGeometryCRC() );

	// delete the map file
	delete mapFile;

	common->Printf( "%6d seconds to create AAS\n", (Sys_Milliseconds() - startTime) / 1000 );

	return true;
}

/*
============
idAASBuild::BuildReachability
============
*/
bool idAASBuild::BuildReachability( const idStr &fileName, const idAASSettings *settings ) {
	int startTime;
	idMapFile * mapFile;
	idStr name;
	idAASReach reach;
	idAASCluster cluster;

	startTime = Sys_Milliseconds();

	aasSettings = settings;

	name = fileName;
	name.SetFileExtension( "map" );

	mapFile = new idMapFile;
	if ( !mapFile->Parse( name ) ) {
		delete mapFile;
		common->Error( "Couldn't load map file: '%s'", name.c_str() );
		return false;
	}

	file = new idAASFileLocal();

	name.SetFileExtension( aasSettings->fileExtension );
	if ( !file->Load( name, 0 ) ) {
		delete mapFile;
		common->Error( "Couldn't load AAS file: '%s'", name.c_str() );
		return false;
	}

	file->settings = *aasSettings;

	// calculate reachability
	reach.Build( mapFile, file );

	// build clusters
	cluster.Build( file );

	// write the file
	file->Write( name, mapFile->GetGeometryCRC() );

	// delete the map file
	delete mapFile;

	common->Printf( "%6d seconds to calculate reachability\n", (Sys_Milliseconds() - startTime) / 1000 );

	return true;
}

/*
============
ParseOptions
============
*/
int ParseOptions( const idCmdArgs &args, idAASSettings &settings ) {
	int i;
	idStr str;

	for ( i = 1; i < args.Argc(); i++ ) {

		str = args.Argv( i );
		str.StripLeading( '-' );

		if ( str.Icmp( "usePatches" ) == 0 ) {
			settings.usePatches = true;
			common->Printf( "usePatches = true\n" );
		} else if ( str.Icmp( "writeBrushMap" ) == 0 ) {
			settings.writeBrushMap = true;
			common->Printf( "writeBrushMap = true\n" );
		} else if ( str.Icmp( "playerFlood" ) == 0 ) {
			settings.playerFlood = true;
			common->Printf( "playerFlood = true\n" );
		} else if ( str.Icmp( "noOptimize" ) == 0 ) {
			settings.noOptimize = true;
			common->Printf( "noOptimize = true\n" );
		}
	}
	return args.Argc() - 1;
}

/*
============
RunAAS_f
============
*/
void RunAAS_f( const idCmdArgs &args ) {
	int i;
	idAASBuild aas;
	idAASSettings settings;
	idStr mapName;

	if ( args.Argc() <= 1 ) {
		common->Printf( "runAAS [options] <mapfile>\n"
					"options:\n"
					"  -usePatches        = use bezier patches for collision detection.\n"
					"  -writeBrushMap     = write a brush map with the AAS geometry.\n"
					"  -playerFlood       = use player spawn points as valid AAS positions.\n" );
		return;
	}

	common->ClearWarnings( "compiling AAS" );

	common->SetRefreshOnPrint( true );

	// get the aas settings definitions
	const idDict *dict = gameEdit->FindEntityDefDict( "aas_types", false );
	if ( !dict ) {
		common->Error( "Unable to find entityDef for 'aas_types'" );
	}

	const idKeyValue *kv = dict->MatchPrefix( "type" );
	while( kv != NULL ) {
		const idDict *settingsDict = gameEdit->FindEntityDefDict( kv->GetValue(), false );
		if ( !settingsDict ) {
			common->Warning( "Unable to find '%s' in def/aas.def", kv->GetValue().c_str() );
		} else {
			settings.FromDict( kv->GetValue(), settingsDict );
			i = ParseOptions( args, settings );
			mapName = args.Argv(i);
			mapName.BackSlashesToSlashes();
			if ( mapName.Icmpn( "maps/", 4 ) != 0 ) {
				mapName = "maps/" + mapName;
			}
			aas.Build( mapName, &settings );
		}

		kv = dict->MatchPrefix( "type", kv );
		if ( kv ) {
			common->Printf( "=======================================================\n" );
		}
	}
	common->SetRefreshOnPrint( false );
	common->PrintWarnings();
}

/*
============
RunAASDir_f
============
*/
void RunAASDir_f( const idCmdArgs &args ) {
	int i;
	idAASBuild aas;
	idAASSettings settings;
	idFileList *mapFiles;

	if ( args.Argc() <= 1 ) {
		common->Printf( "runAASDir <folder>\n" );
		return;
	}

	common->ClearWarnings( "compiling AAS" );

	common->SetRefreshOnPrint( true );

	// get the aas settings definitions
	const idDict *dict = gameEdit->FindEntityDefDict( "aas_types", false );
	if ( !dict ) {
		common->Error( "Unable to find entityDef for 'aas_types'" );
	}

	// scan for .map files
	mapFiles = fileSystem->ListFiles( idStr("maps/") + args.Argv(1), ".map" );

	// create AAS files for all the .map files
	for ( i = 0; i < mapFiles->GetNumFiles(); i++ ) {
		if ( i ) {
			common->Printf( "=======================================================\n" );
		}

		const idKeyValue *kv = dict->MatchPrefix( "type" );
		while( kv != NULL ) {
			const idDict *settingsDict = gameEdit->FindEntityDefDict( kv->GetValue(), false );
			if ( !settingsDict ) {
				common->Warning( "Unable to find '%s' in def/aas.def", kv->GetValue().c_str() );
			} else {
				settings.FromDict( kv->GetValue(), settingsDict );
				aas.Build( idStr( "maps/" ) + args.Argv( 1 ) + "/" + mapFiles->GetFile( i ), &settings );
			}

			kv = dict->MatchPrefix( "type", kv );
			if ( kv ) {
				common->Printf( "=======================================================\n" );
			}
		}
	}

	fileSystem->FreeFileList( mapFiles );

	common->SetRefreshOnPrint( false );
	common->PrintWarnings();
}

/*
============
RunReach_f
============
*/
void RunReach_f( const idCmdArgs &args ) {
	int i;
	idAASBuild aas;
	idAASSettings settings;

	if ( args.Argc() <= 1 ) {
		common->Printf( "runReach [options] <mapfile>\n" );
		return;
	}

	common->ClearWarnings( "calculating AAS reachability" );

	common->SetRefreshOnPrint( true );

	// get the aas settings definitions
	const idDict *dict = gameEdit->FindEntityDefDict( "aas_types", false );
	if ( !dict ) {
		common->Error( "Unable to find entityDef for 'aas_types'" );
	}

	const idKeyValue *kv = dict->MatchPrefix( "type" );
	while( kv != NULL ) {
		const idDict *settingsDict = gameEdit->FindEntityDefDict( kv->GetValue(), false );
		if ( !settingsDict ) {
			common->Warning( "Unable to find '%s' in def/aas.def", kv->GetValue().c_str() );
		} else {
			settings.FromDict( kv->GetValue(), settingsDict );
			i = ParseOptions( args, settings );
			aas.BuildReachability( idStr("maps/") + args.Argv(i), &settings );
		}

		kv = dict->MatchPrefix( "type", kv );
		if ( kv ) {
			common->Printf( "=======================================================\n" );
		}
	}

	common->SetRefreshOnPrint( false );
	common->PrintWarnings();
}