forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildAssistant.cpp
More file actions
1580 lines (1298 loc) · 56.1 KB
/
BuildAssistant.cpp
File metadata and controls
1580 lines (1298 loc) · 56.1 KB
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
/*
** Command & Conquer Generals(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program 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.
**
** This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// FILE: BuildAssistant.cpp ///////////////////////////////////////////////////////////////////////
// Author: Colin Day, February 2002
// Desc: Singleton class to encapsulate some of the more common functions or rules
// that apply to building structures and units
///////////////////////////////////////////////////////////////////////////////////////////////////
// USER INCLUDES //////////////////////////////////////////////////////////////////////////////////
#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
#include "Common/BuildAssistant.h"
#include "Common/GlobalData.h"
#include "Common/Player.h"
#include "Common/ThingTemplate.h"
#include "Common/GameAudio.h"
#include "Common/ThingFactory.h"
#include "Common/Team.h"
#include "Common/TerrainTypes.h"
#include "Common/MapObject.h"
#include "GameClient/ControlBar.h"
#include "GameClient/Drawable.h"
#include "GameClient/InGameUI.h"
#include "GameClient/TerrainVisual.h"
#include "GameLogic/AI.h"
#include "GameLogic/PartitionManager.h"
#include "GameLogic/TerrainLogic.h"
#include "GameLogic/AIPathfind.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/BehaviorModule.h"
#include "GameLogic/Module/ContainModule.h"
#include "GameLogic/Module/CreateModule.h"
#include "GameLogic/Module/ProductionUpdate.h"
#include "GameLogic/Module/ContainModule.h"
#include "GameLogic/Module/ParkingPlaceBehavior.h"
// PUBLIC DATA ////////////////////////////////////////////////////////////////////////////////////
BuildAssistant *TheBuildAssistant = NULL;
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
ObjectSellInfo::ObjectSellInfo( void )
{
m_id = INVALID_ID;
m_sellFrame = 0;
} // end ObjectSellInfo
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
ObjectSellInfo::~ObjectSellInfo( void )
{
} // end ~ObjectSellInfo
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------------------------------------------------
/** Is this object a dozer */
//-------------------------------------------------------------------------------------------------
static Bool isDozer( Object *obj )
{
// sanity
if( obj == NULL )
return FALSE;
if( obj->isKindOf(KINDOF_DOZER))
return TRUE;
return FALSE;
} // end isDozer
// PUBLIC /////////////////////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
BuildAssistant::BuildAssistant( void )
{
m_buildPositions = NULL;
m_buildPositionSize = 0;
m_sellList.clear();
} // end BuildAssistant
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
BuildAssistant::~BuildAssistant( void )
{
// delete build position array if we used it
if( m_buildPositions )
{
delete [] m_buildPositions;
m_buildPositions = NULL;
m_buildPositionSize = 0;
} // end if
} // end ~BuildAssistant
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void BuildAssistant::init( void )
{
//
// allocate our array of positions that we use to assist ourselves when constructing
// a tiled array of locations to build things like walls
//
m_buildPositionSize = TheGlobalData->m_maxLineBuildObjects;
m_buildPositions = NEW Coord3D[ m_buildPositionSize ];
} // end init
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void BuildAssistant::reset( void )
{
// clear all our data from the sell list
ObjectSellInfo *sellInfo;
ObjectSellListIterator it;
for( it = m_sellList.begin(); it != m_sellList.end(); ++it )
{
// get sell info
sellInfo = (*it);
// delete our data and erase this entry from the list
sellInfo->deleteInstance();
} // end for
// clear the sell list
m_sellList.clear();
} // end reset
static const Real FRAMES_TO_ALLOW_SCAFFOLD = LOGICFRAMES_PER_SECOND * 1.5f;
static const Real TOTAL_FRAMES_TO_SELL_OBJECT = LOGICFRAMES_PER_SECOND * 3.0f;
//-------------------------------------------------------------------------------------------------
/** Update phase for the build assistant */
//-------------------------------------------------------------------------------------------------
void BuildAssistant::update( void )
{
ObjectSellInfo *sellInfo;
Object *obj;
// remove any objects from the sell list who's "sell time" is up
ObjectSellListIterator it, thisIterator;
for( it = m_sellList.begin(); it != m_sellList.end(); /*empty*/ )
{
// get this object info
sellInfo = (*it);
// increment the iterator to the next as we may remove it
thisIterator = it;
++it;
// find the object
obj = TheGameLogic->findObjectByID( sellInfo->m_id );
//
// if object is not found, remove it from the list immediately ... this is valid as
// the object maybe was destroyed by other means during the sell process
//
if( obj == NULL )
{
sellInfo->deleteInstance();
m_sellList.erase( thisIterator );
continue;
} // end if
// decrement the construction percent
if( TheGameLogic->getFrame() - sellInfo->m_sellFrame >= FRAMES_TO_ALLOW_SCAFFOLD )
{
Real previousConstructionPercent = obj->getConstructionPercent();
// do the constructoin
obj->setConstructionPercent( previousConstructionPercent - (100.0f / TOTAL_FRAMES_TO_SELL_OBJECT) );
//
// did we cross the threshold from positive to negative ... if so, we will clear
// visual construction indicators
//
if( previousConstructionPercent > 0.0f && obj->getConstructionPercent() <= 0.0f )
{
obj->clearAndSetModelConditionFlags( MAKE_MODELCONDITION_MASK2( MODELCONDITION_PARTIALLY_CONSTRUCTED,
MODELCONDITION_ACTIVELY_BEING_CONSTRUCTED ),
MAKE_MODELCONDITION_MASK( MODELCONDITION_SOLD ) );
//
// set the animation durations so that the regular build up loop animations can be
// done a bit faster for selling
//
Drawable *draw = obj->getDrawable();
if( draw )
draw->setAnimationLoopDuration( TOTAL_FRAMES_TO_SELL_OBJECT / 2 );
} // end if
} // end if
//
// after we've reached zero ... the object has "sunk" back down into the ground ... but
// we need to keep the object around for a little while longer so that the scaffold
// animation can finish up and sink itself back into the ground
//
if( obj->getConstructionPercent() <= -50.0f )
{
// refund the money to the controlling player
Player *player = obj->getControllingPlayer();
if( player )
{
UnsignedInt sellValue;
// 0 is the init, and means you have no override. We would be marked unsellable if someone wanted us to not sell
if( obj->getTemplate()->getRefundValue() != 0 )
sellValue = obj->getTemplate()->getRefundValue();
else
sellValue = REAL_TO_UNSIGNEDINT( obj->getTemplate()->calcCostToBuild( player ) *
TheGlobalData->m_sellPercentage );
player->getMoney()->deposit( sellValue );
// this money shouldn't be scored since it wasn't really "earned."
// player->getScoreKeeper()->addMoneyEarned( sellValue );
} // end if
// cancel any of the production items and refund to the controlling player
ProductionUpdateInterface *pui = obj->getProductionUpdateInterface();
if( pui )
pui->cancelAndRefundAllProduction();
// for debugging
// UnicodeString msg;
// msg.format( L"'%S' has been sold\n", obj->getTemplate()->getName().str() );
// TheInGameUI->message( msg );
// destroy the object
TheGameLogic->destroyObject( obj );
// remove this object from the sell list
sellInfo->deleteInstance();
m_sellList.erase( thisIterator );
} // end if
} // end for
} // end update
//-------------------------------------------------------------------------------------------------
/** Xfer the sell list. */
//-------------------------------------------------------------------------------------------------
void BuildAssistant::xferTheSellList( Xfer *xfer )
{
ObjectSellInfo *sellInfo;
Int count=0;
ObjectSellListIterator it, thisIterator;
for( it = m_sellList.begin(); it != m_sellList.end(); ++it ) {
count++;
}
xfer->xferInt(&count);
if (xfer->getXferMode() == XFER_LOAD) {
m_sellList.clear();
Int i;
for (i=0; i<count; i++) {
// add this object to the list of objects being sold
sellInfo = newInstance(ObjectSellInfo);
xfer->xferObjectID(&sellInfo->m_id);
xfer->xferUnsignedInt(&sellInfo->m_sellFrame);
m_sellList.push_back( sellInfo );
}
} else {
for( it = m_sellList.begin(); it != m_sellList.end(); ++it ) {
// get this object info
sellInfo = (*it);
xfer->xferObjectID(&sellInfo->m_id);
xfer->xferUnsignedInt(&sellInfo->m_sellFrame);
count--;
}
DEBUG_ASSERTCRASH(count==0, ("Inconsistent list size counts."));
}
} // end xferTheSellList
//-------------------------------------------------------------------------------------------------
/** Nice little method to wrap up creating an object from a build */
//-------------------------------------------------------------------------------------------------
Object *BuildAssistant::buildObjectNow( Object *constructorObject, const ThingTemplate *what,
const Coord3D *pos, Real angle, Player *owningPlayer )
{
// sanity
if( what == NULL || pos == NULL )
return NULL;
if( owningPlayer == NULL )
return NULL;// Invalid pointer. Won't happen.
// sanity
if( constructorObject )
{
DEBUG_ASSERTCRASH( constructorObject->getControllingPlayer() == owningPlayer,
("buildObjectNow: Constructor object player is not the same as the controlling player passed in\n") );
} // end if
// Need to validate that we can make this in case someone fakes their CommandSet
// A Null constructorObject is used by the script engine to cheat, so let it slide
if( constructorObject && !isPossibleToMakeUnit(constructorObject, what) )
return NULL;
// clear out any objects from the building area that are "auto-clearable" when building
clearRemovableForConstruction( what, pos, angle );
if ( moveObjectsForConstruction( what, pos, angle, owningPlayer ) == FALSE )
{
// totally bogus. We tried to move our units out of the way, but they wouldn't.
// Chode-boys.
if (owningPlayer->getPlayerType()==PLAYER_HUMAN) {
return NULL; // ai gets to cheat. jba.
}
}
// do the build
if( isDozer( constructorObject ) && isLineBuildTemplate( what ) == FALSE )
{
AIUpdateInterface *ai = constructorObject->getAIUpdateInterface();
if( ai )
{
ai->aiIdle(CMD_FROM_AI); // stop any current behavior.
return ai->construct( what, pos, angle, owningPlayer, FALSE );
}
return NULL;
} // end else if
else
{
// create the new object. We need to construct it with UnderConstruction set, since we are going to insta build it,
// but we don't want to send double construction type events like power creation. onStructureConstructionComplete
// is called below, so we need to simulate the proper object creation flow from the start. Be like Dozer.
ObjectStatusMaskType startingStatus;
if( what->isKindOf( KINDOF_STRUCTURE ) )
startingStatus.set( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_UNDER_CONSTRUCTION ) );
Object *obj = TheThingFactory->newObject( what, owningPlayer->getDefaultTeam(), startingStatus );
obj->setProducer(constructorObject);
// place on terrain surface
Coord3D groundPos;
groundPos.x = pos->x;
groundPos.y = pos->y;
groundPos.z = TheTerrainLogic->getGroundHeight( groundPos.x, groundPos.y );
obj->setPosition( &groundPos );
obj->setOrientation( angle );
TheAI->pathfinder()->addObjectToPathfindMap( obj );
// notify the player that this thing has come into existence
if( obj->isKindOf( KINDOF_STRUCTURE ) )
{
//
// this is a cheat since this method is currently used by the solo AI to make
// buildings out of thin air
//
owningPlayer->onStructureCreated( constructorObject, obj );
owningPlayer->onStructureConstructionComplete( constructorObject, obj, FALSE );
} // end if
else
{
owningPlayer->onUnitCreated( constructorObject, obj );
//Call the voice created for the 1st object -- because it's possible to create multiple objects like redguards!
AudioEventRTS sound = *obj->getTemplate()->getPerUnitSound( "VoiceCreated" );
sound.setObjectID( obj->getID() );
TheAudio->addAudioEvent( &sound );
}
// Now onCreates were called at the constructor. This magically created
// thing needs to be considered as Built for Game specific stuff.
for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m)
{
CreateModuleInterface* create = (*m)->getCreate();
if (!create)
continue;
create->onBuildComplete();
}
// Creation is another valid and essential time to call this. This building now Looks.
obj->handlePartitionCellMaintenance();
return obj;
} // end else
return NULL;
} // end buildObjectNow
//-------------------------------------------------------------------------------------------------
/** This method will create a line of objects end to end along the line defined in 3D
* space from start to end. This is especially useful in building walls */
//-------------------------------------------------------------------------------------------------
void BuildAssistant::buildObjectLineNow( Object *constructorObject, const ThingTemplate *what,
const Coord3D *start, const Coord3D *end, Real angle,
Player *owningPlayer )
{
TileBuildInfo *tileBuildInfo;
// sanity
if( what == NULL || start == NULL || end == NULL )
return;
// how big are each of our objects
Real objectSize = what->getTemplateGeometryInfo().getMajorRadius() * 2.0f;
// what is our max tiling length we can make
Int maxObjects = TheGlobalData->m_maxLineBuildObjects;
// build an array of locations that we want to build from start to end
tileBuildInfo = buildTiledLocations( what, angle, start, end,
objectSize, maxObjects, constructorObject );
// create an object at each position
for( Int i = 0; i < tileBuildInfo->tilesUsed; i++ )
buildObjectNow( constructorObject, what, &tileBuildInfo->positions[ i ], angle, owningPlayer );
} // end buildObjectLineNow
//-------------------------------------------------------------------------------------------------
/** This structure is passed along to the checkSampleBuildLocation while iterating the
* footprint of an area in order to determine if the entire location is a legal place to
* build */
//-------------------------------------------------------------------------------------------------
struct SampleBuildData
{
Region3D mapRegion;
Bool terrainRestricted; ///< one of the terrain tiles prevents building
Real hiZ; ///< highest sample point used
Real loZ; ///< lowest sample point used
};
//-------------------------------------------------------------------------------------------------
/** This will check the build conditions at the specified sample location point */
//-------------------------------------------------------------------------------------------------
static void checkSampleBuildLocation( const Coord3D *samplePoint, void *userData )
{
TerrainType *terrain;
SampleBuildData *sampleData = (SampleBuildData *)userData;
// get the terrain tile here
terrain = TheTerrainVisual->getTerrainTile( samplePoint->x, samplePoint->y );
if( terrain )
{
// check for the restricts building flag
if( terrain->getRestrictConstruction() )
sampleData->terrainRestricted = TRUE;
} // end if
Int cellX = REAL_TO_INT_FLOOR( samplePoint->x / PATHFIND_CELL_SIZE );
Int cellY = REAL_TO_INT_FLOOR( samplePoint->y / PATHFIND_CELL_SIZE );
PathfindCell* cell = TheAI->pathfinder()->getCell( LAYER_GROUND, cellX, cellY );
if (!cell) {
sampleData->terrainRestricted = TRUE;
} else {
enum PathfindCell::CellType type = cell->getType();
if ( (type == PathfindCell::CELL_WATER) || (type == PathfindCell::CELL_CLIFF) ||
(type == PathfindCell::CELL_IMPASSABLE)) {
sampleData->terrainRestricted = true;
}
}
//
// record the highest and lowest Z points from all the samples and do not allow
// building when the difference between them is too great
//
if( samplePoint->z < sampleData->loZ )
sampleData->loZ = samplePoint->z;
if( samplePoint->z > sampleData->hiZ )
sampleData->hiZ = samplePoint->z;
// too close to edge of map?
if (TheGlobalData->m_MinDistFromEdgeOfMapForBuild > 0.0f)
{
if (samplePoint->x < sampleData->mapRegion.lo.x + TheGlobalData->m_MinDistFromEdgeOfMapForBuild
|| samplePoint->x > sampleData->mapRegion.hi.x - TheGlobalData->m_MinDistFromEdgeOfMapForBuild
|| samplePoint->y < sampleData->mapRegion.lo.y + TheGlobalData->m_MinDistFromEdgeOfMapForBuild
|| samplePoint->y > sampleData->mapRegion.hi.y - TheGlobalData->m_MinDistFromEdgeOfMapForBuild)
{
sampleData->terrainRestricted = TRUE;
}
}
} // end checkSampleBuildLocation
//-------------------------------------------------------------------------------------------------
/** This function will call the user callback at each "sample point" across the footprint
* of where this object would be in the world. The smaller the sample resolution param is
* the more samples will be taken across the footprint area */
//-------------------------------------------------------------------------------------------------
void BuildAssistant::iterateFootprint( const ThingTemplate *build,
Real buildOrientation,
const Coord3D *worldPos,
Real sampleResolution,
IterateFootprintFunc func,
void *funcUserData )
{
// sanity
if( build == NULL || worldPos == NULL || func == NULL )
return;
//
// create a transform matrix for the object position at the specified angle, we will
// iterate the object footprints in "local object extent space" and transform those
// points using this matrix into the world coords for the object at the real
// location and specified angle
//
Matrix3D transform;
transform.Make_Identity();
transform.Adjust_Translation( Vector3( worldPos->x, worldPos->y, worldPos->z ) );
transform.Rotate_Z( buildOrientation );
// get the bounding footprint rectangle for the geometry we're looking at
Real halfFootprintHeight,
halfFootprintWidth;
if( build->getTemplateGeometryInfo().getGeomType() == GEOMETRY_BOX )
{
halfFootprintHeight = build->getTemplateGeometryInfo().getMinorRadius();
halfFootprintWidth = build->getTemplateGeometryInfo().getMajorRadius();
} // end if
else if( build->getTemplateGeometryInfo().getGeomType() == GEOMETRY_SPHERE ||
build->getTemplateGeometryInfo().getGeomType() == GEOMETRY_CYLINDER )
{
halfFootprintHeight = build->getTemplateGeometryInfo().getBoundingCircleRadius();
halfFootprintWidth = build->getTemplateGeometryInfo().getBoundingCircleRadius();
} // end else if
else
{
DEBUG_ASSERTCRASH( 0, ("iterateFootprint: Undefined geometry '%d' for '%s'\n",
build->getTemplateGeometryInfo().getGeomType(), build->getName().str()) );
return;
} // end else
//
// start at a corner of the extent ... box geometries have a major radius down
// the X axis with the minor radius on the Y axis. Note that we are allowing
// the sample process to go an "extra" sample resolution outside of the
// real extent here. This is so that we can be sure to sample all of the
// footprint area, if our sample point is outside of the actual extent footprint
// area because of this we snap it back to sample on the exact edge
//
Real x, y;
Vector3 v;
for( y = -halfFootprintHeight;
y < halfFootprintHeight + sampleResolution;
y += sampleResolution )
{
// snap it to the actual extent since we can go over by one sample resolution
if( y > halfFootprintHeight )
y = halfFootprintHeight;
for( x = -halfFootprintWidth;
x < halfFootprintWidth + sampleResolution;
x += sampleResolution )
{
// snap it to the actual extent since we can go over by one sample resolution
if( x > halfFootprintWidth )
x = halfFootprintWidth;
// transform to world
v.Set( x, y, TheTerrainLogic->getGroundHeight( x, y ) );
transform.Transform_Vector( transform, v, &v );
// for circular geometries we must actually be within the circle
if( build->getTemplateGeometryInfo().getGeomType() == GEOMETRY_SPHERE ||
build->getTemplateGeometryInfo().getGeomType() == GEOMETRY_CYLINDER )
{
Coord2D vector;
vector.x = v.X - worldPos->x;
vector.y = v.Y - worldPos->y;
if( vector.length() > halfFootprintWidth ) // could be height too, radius is all the same for circles
continue; // ignore this point
} // end if
// call the user callback
Coord3D pos;
pos.x = v.X;
pos.y = v.Y;
pos.z = TheTerrainLogic->getGroundHeight( pos.x, pos.y );
func( &pos, funcUserData );
} // end for x
} // end for y
} // end iterateFootprint
//-------------------------------------------------------------------------------------------------
/** Check for objects preventing building at this location. */
//-------------------------------------------------------------------------------------------------
Bool BuildAssistant::isLocationClearOfObjects( const Coord3D *worldPos,
const ThingTemplate *build,
Real angle,
Object *builderObject,
UnsignedInt options,
Player *thePlayer)
{
ObjectIterator *iter =
ThePartitionManager->iteratePotentialCollisions( worldPos,
build->getTemplateGeometryInfo(),
angle );
Object *them;
Bool onlyCheckEnemies = (options == NO_ENEMY_OBJECT_OVERLAP);
MemoryPoolObjectHolder hold(iter);
for( them = iter->first(); them; them = iter->next() )
{
Relationship rel = builderObject ? builderObject->getRelationship( them ) : NEUTRAL;
// ignore any kind of class of objects that we will "remove" for building
if( isRemovableForConstruction( them ) == TRUE )
continue;
// ignore land mines, cluster mines and demo traps, since you can build on them
// doing so will damage them during construction, by the way
if (them->isKindOf( KINDOF_MINE ))
continue;
// same story for inert things: ie, radiation fields, pings, and projectile streams (!)...
if (them->isKindOf(KINDOF_INERT))
continue;
// an immobile object may obstruct our building depending on flags.
if( them->isKindOf( KINDOF_IMMOBILE ) ) {
if (onlyCheckEnemies && builderObject && rel != ENEMIES ) {
continue;
}
TheTerrainVisual->addFactionBib(them, true);
return false;
}
//
// if this is an enemy object of the builder object (and therefore the thing
// that will be constructed) we can't build here
//
if( builderObject && rel == ENEMIES ) {
TheTerrainVisual->addFactionBib(them, true);
return false;
}
} // end for, them
if (onlyCheckEnemies) {
return true;
}
// Check for overlapping exit areas.
Real range = 2*(build->getTemplateGeometryInfo().getMajorRadius()+build->getTemplateGeometryInfo().getMinorRadius());
PartitionFilterAcceptByKindOf f1(MAKE_KINDOF_MASK(KINDOF_STRUCTURE), KINDOFMASK_NONE);
PartitionFilter *filters[] = { &f1, NULL };
ObjectIterator *iter2 = ThePartitionManager->iterateObjectsInRange(worldPos, range, FROM_BOUNDINGSPHERE_2D, filters);
MemoryPoolObjectHolder hold2(iter2);
Real myFactoryExitWidth = build->getFactoryExitWidth();
Real myExtraWidth = build->getFactoryExtraBibWidth();
if (thePlayer && thePlayer->isSkirmishAIPlayer()) {
// Skirmish ai adds a little extra around the edges so it doesn't build itself into a corner.
if (myExtraWidth < 3*PATHFIND_CELL_SIZE_F) {
myExtraWidth = 3*PATHFIND_CELL_SIZE_F;
myFactoryExitWidth -= myExtraWidth;
if (myFactoryExitWidth<0) myFactoryExitWidth = 0;
}
}
Bool checkMyExit = false;
Coord3D myExitPos;
GeometryInfo myBounds = build->getTemplateGeometryInfo();
myBounds.setMajorRadius(myBounds.getMajorRadius()+myExtraWidth);
if (myBounds.getGeomType() != GEOMETRY_BOX) {
myBounds.set(GEOMETRY_BOX, false, 40, myBounds.getMajorRadius(), myBounds.getMajorRadius());
} else {
myBounds.setMinorRadius(myBounds.getMinorRadius()+myExtraWidth);
}
GeometryInfo myGeom = build->getTemplateGeometryInfo();
if (myGeom.getGeomType() != GEOMETRY_BOX) {
myGeom.setMinorRadius(myGeom.getMajorRadius());
}
myGeom.setMajorRadius(myFactoryExitWidth/2.0f);
if (myFactoryExitWidth>0) {
myExitPos = *worldPos;
checkMyExit = true;
Real c = (Real)cos(angle);
Real s = (Real)sin(angle);
Real offset = build->getTemplateGeometryInfo().getMajorRadius() + myFactoryExitWidth/2.0f;
myExitPos.x += c*offset;
myExitPos.y += s*offset;
}
for( them = iter2->first(); them; them = iter2->next() )
{
// ignore any kind of class of objects that we will "remove" for building
if( isRemovableForConstruction( them ) == TRUE )
continue;
Real themFactoryExitWidth = them->getTemplate()->getFactoryExitWidth();
Real hisExtraWidth = them->getTemplate()->getFactoryExtraBibWidth();
Bool checkHisExit = false;
Coord3D hisExitPos;
GeometryInfo hisBounds = them->getGeometryInfo();
hisBounds.setMajorRadius(hisBounds.getMajorRadius()+hisExtraWidth);
if (hisBounds.getGeomType() != GEOMETRY_BOX) {
hisBounds.set(GEOMETRY_BOX, false, 40, hisBounds.getMajorRadius(), hisBounds.getMajorRadius());
} else {
hisBounds.setMinorRadius(hisBounds.getMinorRadius()+myExtraWidth);
}
GeometryInfo hisGeom = them->getGeometryInfo();
hisGeom.setMajorRadius(themFactoryExitWidth/2.0f);
if (hisGeom.getGeomType() != GEOMETRY_BOX) {
hisGeom.setMinorRadius(them->getGeometryInfo().getMajorRadius());
}
if (themFactoryExitWidth>0) {
hisExitPos = *them->getPosition();
checkHisExit = true;
Real c = (Real)cos(them->getOrientation());
Real s = (Real)sin(them->getOrientation());
Real offset = them->getGeometryInfo().getMajorRadius() + themFactoryExitWidth/2.0f;
hisExitPos.x += c*offset;
hisExitPos.y += s*offset;
}
if (ThePartitionManager->geomCollidesWithGeom(them->getPosition(), hisBounds, them->getOrientation(),
worldPos, myBounds, angle)) {
TheTerrainVisual->addFactionBib(them, true);
return false;
}
if (!checkMyExit && !checkHisExit && !hisExtraWidth && !myExtraWidth)
{
continue; // neither has extra exit space.
}
// an immobile object will obstruct our building no matter what team it's on
if ( them->isKindOf( KINDOF_IMMOBILE ) ) {
/* Check for overlap of my exit rectangle to his geom info. */
if (checkMyExit && ThePartitionManager->geomCollidesWithGeom(them->getPosition(), hisBounds, them->getOrientation(),
&myExitPos, myGeom, angle)) {
TheTerrainVisual->addFactionBib(them, true);
return false;
}
// Check for overlap of his exit rectangle with my geom info
if (checkHisExit && ThePartitionManager->geomCollidesWithGeom(&hisExitPos, hisGeom, them->getOrientation(),
worldPos, myBounds, angle)) {
TheTerrainVisual->addFactionBib(them, true);
return false;
}
// Check both exit rectangles together.
if (checkMyExit&&checkHisExit&&ThePartitionManager->geomCollidesWithGeom(&hisExitPos, hisGeom, them->getOrientation(),
&myExitPos, myGeom, angle)) {
TheTerrainVisual->addFactionBib(them, true);
return false;
}
}
} // end for, them
return true;
}
//-------------------------------------------------------------------------------------------------
/** Query if we can build at this location. Note that 'build' may be null and is NOT required
* to be valid to know if a location is legal to build at. 'builderObject' is used
* for queries that require a pathfind check and should be NULL if not required */
//-------------------------------------------------------------------------------------------------
LegalBuildCode BuildAssistant::isLocationLegalToBuild( const Coord3D *worldPos,
const ThingTemplate *build,
Real angle,
UnsignedInt options,
Object *builderObject,
Player *player)
{
/* You just can't never build off the map, regardless of options. jba. */
Region3D mapExtent;
TheTerrainLogic->getMaximumPathfindExtent(&mapExtent);
if (!mapExtent.isInRegionNoZ(worldPos)) {
return LBC_RESTRICTED_TERRAIN;
}
// check shroud level
// This should be the first check, since returning other errors for shrouded areas could be used to game the system
if( BitIsSet( options, SHROUD_REVEALED ) )
{
{
Int x, y;
ThePartitionManager->worldToCell(worldPos->x, worldPos->y, &x, &y);
Int playerIndex = -1;
if (builderObject && builderObject->getControllingPlayer())
playerIndex = builderObject->getControllingPlayer()->getPlayerIndex();
DEBUG_ASSERTCRASH(playerIndex >= 0, ("isLocationLegalToBuild() needs a builderObject with a team to check for shroud"));
if( ThePartitionManager->getShroudStatusForPlayer(playerIndex, x, y) != CELLSHROUD_CLEAR )
{
return LBC_SHROUD;
}
}
}
//
// if NO_OBJECT_OVERLAP is set, we are not allowed to construct 'build' if it would overlap
// any immobile objects, or an enemy object. Friendly objects should politely
// "move out of the way" when you build something where they're standing
//
if( BitIsSet( options, NO_OBJECT_OVERLAP ) )
{
if (!isLocationClearOfObjects(worldPos, build, angle, builderObject, NO_OBJECT_OVERLAP, player))
{
return LBC_OBJECTS_IN_THE_WAY;
}
} // end if
//
// if NO_ENEMY_OBJECT_OVERLAP is set, we are not allowed to construct 'build' if it would overlap
// any enemy objects. Friendly objects are ignored.
//
if( BitIsSet( options, NO_ENEMY_OBJECT_OVERLAP ) )
{
if (!isLocationClearOfObjects(worldPos, build, angle, builderObject, NO_ENEMY_OBJECT_OVERLAP, player))
{
return LBC_OBJECTS_IN_THE_WAY;
}
} // end if
if (build->isKindOf(KINDOF_CANNOT_BUILD_NEAR_SUPPLIES) && TheGlobalData->m_SupplyBuildBorder > 0)
{
// special case for supply centers: can't build too close to supply sources
PartitionFilterAcceptByKindOf f1(MAKE_KINDOF_MASK(KINDOF_SUPPLY_SOURCE), KINDOFMASK_NONE);
PartitionFilter *filters[] = { &f1, NULL };
// see if there are any reasonably close by
Real range = build->getTemplateGeometryInfo().getBoundingCircleRadius() + TheGlobalData->m_SupplyBuildBorder*2;
Object* tooClose = ThePartitionManager->getClosestObject(worldPos, range, FROM_BOUNDINGSPHERE_2D, filters);
if (tooClose != NULL)
{
// yep, see if we would collide with an expanded version
GeometryInfo tooCloseGeom = tooClose->getGeometryInfo();
tooCloseGeom.expandFootprint(TheGlobalData->m_SupplyBuildBorder);
if (ThePartitionManager->geomCollidesWithGeom(
worldPos,
build->getTemplateGeometryInfo(),
angle,
tooClose->getPosition(),
tooCloseGeom,
tooClose->getOrientation()))
{
TheTerrainVisual->addFactionBib(tooClose, true, TheGlobalData->m_SupplyBuildBorder);
return LBC_TOO_CLOSE_TO_SUPPLIES;
}
}
}
// if clear path is requestsed check to see if the builder object can get there
if( BitIsSet( options, CLEAR_PATH ) && builderObject )
{
AIUpdateInterface *ai = builderObject->getAIUpdateInterface();
//
// if there is no AI interface for this object, it cannot possible pass a clear path
// check since it will never be able to move there
//
/**todo remove this if we need to change the semantics of this function of the builderObject
// actually being able to get to the destination */
//
if( ai == NULL )
return LBC_NO_CLEAR_PATH;
//
// check for an available path using one of two methods (the quick less accurate one,
// or the slow more accurate one)
//
if( BitIsSet( options, USE_QUICK_PATHFIND ) )
{
if( ai->isQuickPathAvailable( worldPos ) == FALSE )
return LBC_NO_CLEAR_PATH;
} // end if
else
{
if( ai->isPathAvailable( worldPos ) == FALSE )
return LBC_NO_CLEAR_PATH;
} // end else
} // end if
// check basic terrain restrctions
if( BitIsSet( options, TERRAIN_RESTRICTIONS ) )
{
//
// we will take "samples" at this resolution across the footprint of where we are
// going to build the structure
//
Real sampleResolution = MAP_XY_FACTOR;
// get the terrain extents
Region3D terrainExtent;
TheTerrainLogic->getExtent( &terrainExtent );
if (TheTerrainLogic->getLayerForDestination(worldPos) != LAYER_GROUND) {
// we're on a bridge. This is somewhat restricted.
return LBC_RESTRICTED_TERRAIN;
}
//
// check the footprint of where the structure would go to be clear of any non-buildable
// tiles and to make sure there isn't a restricted tile and to make sure it's "flat" enough
//
SampleBuildData sampleData;
TheTerrainLogic->getExtent( &sampleData.mapRegion );
sampleData.terrainRestricted = FALSE;
sampleData.hiZ = terrainExtent.lo.z; // note we set hi point to lowest point
sampleData.loZ = terrainExtent.hi.z; // note we set lo point to highest point
// quick check at triple res.
iterateFootprint( build, angle, worldPos, 3*sampleResolution,
checkSampleBuildLocation, &sampleData );
if( sampleData.terrainRestricted == TRUE )
return LBC_RESTRICTED_TERRAIN;
// check if the height across the whole footprint area is too varied (not flat enough)
if( sampleData.hiZ - sampleData.loZ > TheGlobalData->m_allowedHeightVariationForBuilding )
return LBC_NOT_FLAT_ENOUGH;