forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenContain.cpp
More file actions
1950 lines (1597 loc) · 62.7 KB
/
OpenContain.cpp
File metadata and controls
1950 lines (1597 loc) · 62.7 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 Zero Hour(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: OpenContain.cpp //////////////////////////////////////////////////////////////////////////
// Author: Colin Day, November 2001
// Desc: The OpenContain ContainModule allows objects to be contained inside of other
// objects. There is a set of functionality that will be common to
// all container modules that provides the actual containment
// implementations, those implementations are found here
///////////////////////////////////////////////////////////////////////////////////////////////////
// INCLUDES ///////////////////////////////////////////////////////////////////////////////////////
#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine
#include "Common/BitFlagsIO.h"
#include "Common/GameAudio.h"
#include "Common/GameState.h"
#include "Common/Module.h"
#include "Common/Player.h"
#include "Common/RandomValue.h"
#include "Common/ThingTemplate.h"
#include "Common/Xfer.h"
#include "GameClient/Drawable.h"
#include "GameClient/InGameUI.h"
#include "GameClient/ControlBar.h"
#include "GameLogic/AIPathfind.h"
#include "GameLogic/GameLogic.h"
#include "GameLogic/Module/OpenContain.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/PhysicsUpdate.h"
#include "GameLogic/Module/StealthUpdate.h"
#include "GameLogic/Module/BodyModule.h"
#include "GameLogic/Object.h"
#include "GameLogic/PartitionManager.h"
#include "GameLogic/Weapon.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS ///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
OpenContainModuleData::OpenContainModuleData()
{
m_containMax = CONTAIN_MAX_UNKNOWN; // means we don't care, infinite, unassigned, whatever
m_passengersAllowedToFire = FALSE;
m_passengersInTurret = FALSE;
m_numberOfExitPaths = 1;
m_damagePercentageToUnits = 0;
m_isBurnedDeathToUnits = TRUE;
m_doorOpenTime = 1;
m_allowInsideKindOf.clear(); m_allowInsideKindOf.flip(); // everything is allowed
m_forbidInsideKindOf.clear(); // nothing is forbidden
m_weaponBonusPassedToPassengers = FALSE;
m_allowAlliesInside = TRUE;
m_allowEnemiesInside = TRUE;
m_allowNeutralInside = TRUE;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
/*static*/ void OpenContainModuleData::buildFieldParse(MultiIniFieldParse& p)
{
UpdateModuleData::buildFieldParse(p);
static const FieldParse dataFieldParse[] =
{
{ "ContainMax", INI::parseInt, nullptr, offsetof( OpenContainModuleData, m_containMax ) },
{ "EnterSound", INI::parseAudioEventRTS, nullptr, offsetof( OpenContainModuleData, m_enterSound ) },
{ "ExitSound", INI::parseAudioEventRTS, nullptr, offsetof( OpenContainModuleData, m_exitSound ) },
{ "DamagePercentToUnits", INI::parsePercentToReal, nullptr, offsetof( OpenContainModuleData, m_damagePercentageToUnits ) },
{ "BurnedDeathToUnits", INI::parseBool, nullptr, offsetof( OpenContainModuleData, m_isBurnedDeathToUnits ) },
{ "AllowInsideKindOf", KindOfMaskType::parseFromINI, nullptr, offsetof( OpenContainModuleData, m_allowInsideKindOf ) },
{ "ForbidInsideKindOf", KindOfMaskType::parseFromINI, nullptr, offsetof( OpenContainModuleData, m_forbidInsideKindOf ) },
{ "PassengersAllowedToFire", INI::parseBool, nullptr, offsetof( OpenContainModuleData, m_passengersAllowedToFire ) },
{ "PassengersInTurret", INI::parseBool, nullptr, offsetof( OpenContainModuleData, m_passengersInTurret ) },
{ "NumberOfExitPaths", INI::parseInt, nullptr, offsetof( OpenContainModuleData, m_numberOfExitPaths ) },
{ "DoorOpenTime", INI::parseDurationUnsignedInt, nullptr, offsetof( OpenContainModuleData, m_doorOpenTime ) },
{ "WeaponBonusPassedToPassengers", INI::parseBool, nullptr, offsetof( OpenContainModuleData, m_weaponBonusPassedToPassengers ) },
{ "AllowAlliesInside", INI::parseBool, nullptr, offsetof( OpenContainModuleData, m_allowAlliesInside ) },
{ "AllowEnemiesInside", INI::parseBool, nullptr, offsetof( OpenContainModuleData, m_allowEnemiesInside ) },
{ "AllowNeutralInside", INI::parseBool, nullptr, offsetof( OpenContainModuleData, m_allowNeutralInside ) },
{ nullptr, nullptr, nullptr, 0 }
};
p.add(dataFieldParse);
p.add(DieMuxData::getFieldParse(), offsetof( OpenContainModuleData, m_dieMuxData ));
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
OpenContain::OpenContain( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData )
{
// initialize our lists
m_containList.clear();
m_objectEnterExitInfo.clear();
m_playerEnteredMask = 0;
m_lastUnloadSoundFrame = 0;
m_lastLoadSoundFrame = 0;
m_containListSize = 0;
m_stealthUnitsContained = 0;
m_heroUnitsContained = 0;
m_doorCloseCountdown = 0;
m_rallyPoint.zero();
m_rallyPointExists = FALSE;
m_conditionState.clear();
m_firePointStart = -1;
m_firePointNext = 0;
m_firePointSize = 0;
m_noFirePointsInArt = false;
m_whichExitPath = 1;
m_loadSoundsEnabled = TRUE;
m_passengerAllowedToFire = getOpenContainModuleData()->m_passengersAllowedToFire;
// overridable by setPass...() in the parent interface (for use by upgrade module)
for( Int i = 0; i < MAX_FIRE_POINTS; i++ )
{
m_firePoints[ i ].Make_Identity();
}
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
Int OpenContain::getContainMax() const
{
const OpenContainModuleData *modData = getOpenContainModuleData();
return modData->m_containMax;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
OpenContain::~OpenContain()
{
// sanity, the system should be cleaning these up itself if all is going well
DEBUG_ASSERTCRASH( m_containList.empty(),
("OpenContain %s: destroying a container that still has items in it!",
getObject()->getTemplate()->getName().str() ) );
// sanity
DEBUG_ASSERTCRASH( m_xferContainIDList.empty(),
("OpenContain %s: m_xferContainIDList is not empty but should be",
getObject()->getTemplate()->getName().str() ) );
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// our object changed position... react as appropriate.
void OpenContain::containReactToTransformChange()
{
// Our transform changed, which means our bones moved, and we keep people positioned on bones.
redeployOccupants();
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
UpdateSleepTime OpenContain::update()
{
m_playerEnteredMask = 0;
// we need to monitor changes in the art and position
monitorConditionChanges();
if( m_doorCloseCountdown )
{
/// @todo srj -- for now, OpenContain assumes at most one door
--m_doorCloseCountdown;
if( m_doorCloseCountdown == 0 )
getObject()->clearAndSetModelConditionState( MODELCONDITION_DOOR_1_OPENING, MODELCONDITION_DOOR_1_CLOSING );
}
if (!m_objectEnterExitInfo.empty())
pruneDeadWanters();
return UPDATE_SLEEP_NONE;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void OpenContain::addOrRemoveObjFromWorld(Object* obj, Bool add)
{
//
// it's expensive to add and remove structures from the pathfinder, but we really shouldn't
// be doing it anyway as it doesn't make much sense to contain a structure, but we'll
// check for it here and print a warning
//
if( obj->isKindOf( KINDOF_STRUCTURE ) )
DEBUG_LOG(( "WARNING: Containing/Removing structures like '%s' is potentially a very expensive and slow operation",
obj->getTemplate()->getName().str() ));
if (add)
{
ThePartitionManager->registerObject( obj );
if( obj->getDrawable() )
{
obj->getDrawable()->setDrawableHidden( false );
}
// add object to pathfind map
TheAI->pathfinder()->addObjectToPathfindMap( obj );
}
else
{
// remove object from its group (if any)
obj->leaveGroup();
// remove rider from partition manager
ThePartitionManager->unRegisterObject( obj );
// hide the drawable associated with rider
if( obj->getDrawable() )
obj->getDrawable()->setDrawableHidden( true );
// remove object from pathfind map
TheAI->pathfinder()->removeObjectFromPathfindMap( obj );
}
// if we're a non-enclosing container (eg, parachute), and we're inside an
// enclosing container (eg, b52), we need to be able to show/hide the contained riders...
if( obj->getContain() )
{
const ContainedItemsList* items = obj->getContain()->getContainedItemsList();
if (items)
{
for(ContainedItemsList::const_iterator it = items->begin(); it != items->end(); ++it)
{
if( !obj->getContain()->isEnclosingContainerFor(*it) )
addOrRemoveObjFromWorld(*it, add);
}
}
}
}
//-------------------------------------------------------------------------------------------------
/** Add 'rider' to the m_containList of objects in this module.
* This will trigger an onContaining event for the object that this module
* is a part of and an onContainedBy event for the object being contained */
//-------------------------------------------------------------------------------------------------
void OpenContain::addToContain( Object *rider )
{
if( getObject()->checkAndDetonateBoobyTrap(rider) )
{
// Whoops, I was mined. Cancel if I (or they) am now dead.
if( getObject()->isEffectivelyDead() || rider->isEffectivelyDead() )
{
return;
}
}
// sanity
if( rider == nullptr )
return;
// TheSuperHackers @bugfix Stubbjax 06/02/2026 Ensure the rider is not destroyed to prevent a
// likely crash if it enters the container on the same frame. If this occurs with an unpatched
// client present in a match, the game has a small chance to mismatch.
if (rider->isDestroyed())
return;
Drawable *riderDraw = rider->getDrawable();
Bool wasSelected = FALSE;
if( riderDraw && riderDraw->isSelected() )
{
wasSelected = TRUE;
}
#if defined(RTS_DEBUG)
if( !isValidContainerFor( rider, false ) )
{
Object *reportObject = rider;
if( rider->getContain() )
{
//Report the first thing inside it!
const ContainedItemsList *items = rider->getContain()->getContainedItemsList();
if( items )
{
reportObject = *items->begin();
}
}
DEBUG_CRASH( ("OpenContain::addToContain() - Object %s not valid for container %s!", reportObject?reportObject->getTemplate()->getName().str():"null", getObject()->getTemplate()->getName().str() ) );
}
#endif
// this object cannot be contained by this module if it is already contained in something
if( rider->getContainedBy() != nullptr )
{
DEBUG_LOG(( "'%s' is trying to contain '%s', but '%s' is already contained by '%s'",
getObject()->getTemplate()->getName().str(),
rider->getTemplate()->getName().str(),
rider->getTemplate()->getName().str(),
rider->getContainedBy()->getTemplate()->getName().str() ));
return;
}
// Which list to physically add to needs to be overridable
addToContainList(rider);
m_playerEnteredMask = rider->getControllingPlayer()->getPlayerMask();
if (isEnclosingContainerFor( rider ))
{
addOrRemoveObjFromWorld(rider, false);
}
#if RETAIL_COMPATIBLE_CRC
// ensure our occupants are positioned correctly.
// TheSuperHackers @info Moving this call elsewhere will cause retail mismatch.
redeployOccupants();
#endif
// trigger an onContaining event for the object that just "ate" something
if( getObject()->getContain() )
{
getObject()->getContain()->onContaining( rider, wasSelected );
}
// ensure our occupants are positioned correctly.
// TheSuperHackers @fix Skyaero 10/07/2025 Now (re)deploys the occupants after the garrison points
// had a chance to initialize with prior call to onContaining(). No user facing bug was observed.
#if !RETAIL_COMPATIBLE_CRC
redeployOccupants();
#endif
// trigger an onContainedBy event for the object that just got "eaten" by us
rider->onContainedBy( getObject() );
doLoadSound();
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void OpenContain::addToContainList( Object *rider )
{
m_containList.push_back(rider);
m_containListSize++;
if( rider->isKindOf( KINDOF_STEALTH_GARRISON ) )
{
m_stealthUnitsContained++;
}
if( rider->isKindOf( KINDOF_HERO ) )
{
m_heroUnitsContained++;
}
}
//-------------------------------------------------------------------------------------------------
/** Remove 'rider' from the m_containList of objects in this module.
* This will trigger an onRemoving event for the object that this module
* is a part of and an onRemovedFrom event for the object being removed */
//-------------------------------------------------------------------------------------------------
void OpenContain::removeFromContain( Object *rider, Bool exposeStealthUnits )
{
// sanity
if( rider == nullptr )
return;
//
// we can only remove this object from the contains list of this module if
// it is actually contained by this module
//
Object *containedBy = rider->getContainedBy();
if( containedBy != getObject() )
{
DEBUG_LOG(( "'%s' is trying to un-contain '%s', but '%s' is really contained by '%s'",
getObject()->getTemplate()->getName().str(),
rider->getTemplate()->getName().str(),
rider->getTemplate()->getName().str(),
containedBy ? containedBy->getTemplate()->getName().str() : "Nothing" ));
return;
}
ContainedItemsList::iterator it = std::find(m_containList.begin(), m_containList.end(), rider);
if (it != m_containList.end())
{
// note that this invalidates the iterator!
removeFromContainViaIterator( it, exposeStealthUnits );
}
}
//-------------------------------------------------------------------------------------------------
/** Remove all contained objects from the contained list */
//-------------------------------------------------------------------------------------------------
void OpenContain::removeAllContained( Bool exposeStealthUnits )
{
ContainedItemsList::iterator it;
while ((it = m_containList.begin()) != m_containList.end())
{
// note that this invalidates the iterator!
removeFromContainViaIterator( it, exposeStealthUnits );
}
}
//-------------------------------------------------------------------------------------------------
/** Kill all contained objects in the contained list */
//-------------------------------------------------------------------------------------------------
void OpenContain::killAllContained()
{
// TheSuperHackers @bugfix xezon 23/05/2025 Empty m_containList straight away
// to prevent a potential child call to catastrophically modify the m_containList as well.
// This scenario can happen if the killed occupant(s) apply deadly damage on death
// to the host container, which then attempts to remove all remaining occupants
// on the death of the host container. This is reproducible by shooting with
// Neutron Shells on a GLA Technical containing GLA Terrorists.
ContainedItemsList list;
list.swap(m_containList);
m_containListSize = 0;
ContainedItemsList::iterator it = list.begin();
while ( it != list.end() )
{
Object *rider = *it++;
DEBUG_ASSERTCRASH( rider, ("Contain list must not contain null element"));
if ( rider )
{
onRemoving( rider );
rider->onRemovedFrom( getObject() );
rider->kill();
}
}
}
//--------------------------------------------------------------------------------------------------------
/** Force all contained objects in the contained list to exit, and kick them in the pants on the way out*/
//--------------------------------------------------------------------------------------------------------
void OpenContain::harmAndForceExitAllContained( DamageInfo *info )
{
ContainedItemsList::iterator it = m_containList.begin();
while ( it != m_containList.end() )
{
Object *rider = *it;
DEBUG_ASSERTCRASH( rider, ("Contain list must not contain null element"));
if ( rider )
{
removeFromContain( rider, true );
rider->attemptDamage( info );
}
//Kris: Patch 1.03 -- Crash fix when neutral bunker on Alpine Assault is occupied with 10 demo general
//infantry units with the suicide upgrade and US stealth fighters with bunker busters kill the guys inside.
//Causes recursive damage where a bunker buster destroys an infantry, the infantry explodes and blows up
//another missile which kills everyone inside while the first missile is killing everyone. And the game blows up.
//Fix is to reset the list.
it = m_containList.begin();
}
DEBUG_ASSERTCRASH( m_containListSize == 0, ("harmAndForceExitAllContained just made a booboo, list size != zero.") );
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void OpenContain::doLoadSound()
{
//
// play a sound for loading someone into a building
//
if( m_loadSoundsEnabled )
{
UnsignedInt now = TheGameLogic->getFrame();
if( now != m_lastLoadSoundFrame )
{
if (getOpenContainModuleData())
{
AudioEventRTS enterSound(getOpenContainModuleData()->m_enterSound);
enterSound.setObjectID(getObject()->getID());
TheAudio->addAudioEvent(&enterSound);
}
// save this frame as the last time we did this sound
m_lastLoadSoundFrame = now;
}
}
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void OpenContain::doUnloadSound()
{
//
// play a sound for unloading someone from a building ... but don't play more
// than one per frame (we can do meta unload all commands)
//
UnsignedInt now = TheGameLogic->getFrame();
if( now != m_lastUnloadSoundFrame )
{
if (getOpenContainModuleData())
{
AudioEventRTS exitSound(getOpenContainModuleData()->m_exitSound);
exitSound.setObjectID(getObject()->getID());
TheAudio->addAudioEvent(&exitSound);
}
// save this frame as the last time we did this sound
m_lastUnloadSoundFrame = now;
}
}
//-------------------------------------------------------------------------------------------------
/** Iterate the contained list and call the callback on each of the objects */
//-------------------------------------------------------------------------------------------------
void OpenContain::iterateContained( ContainIterateFunc func, void *userData, Bool reverse )
{
if (reverse)
{
// note that this has to be smart enough to handle items in the list being deleted
// via the callback function.
for(ContainedItemsList::reverse_iterator it = m_containList.rbegin(); it != m_containList.rend(); )
{
// save the rider...
Object* rider = *it;
// incr the iterator BEFORE calling the func (if the func removes the rider,
// the iterator becomes invalid)
++it;
// call it
(*func)( rider, userData );
}
}
else
{
// note that this has to be smart enough to handle items in the list being deleted
// via the callback function.
for(ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); )
{
// save the rider...
Object* rider = *it;
// incr the iterator BEFORE calling the func (if the func removes the rider,
// the iterator becomes invalid)
++it;
// call it
(*func)( rider, userData );
}
}
}
//-------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
Object* OpenContain::getClosestRider( const Coord3D *pos )
{
Object *closest = nullptr;
Real closestDistance;
for(ContainedItemsList::const_iterator it = m_containList.begin(); it != m_containList.end(); ++it)
{
Object *rider = *it;
if (rider)
{
Real distance = ThePartitionManager->getDistanceSquared( rider, pos, FROM_CENTER_2D );
if( !closest || closestDistance > distance )
{
closest = rider;
closestDistance = distance;
}
}
}
return closest; //Could be null!
}
//-------------------------------------------------------------------------------------------------
struct DropData
{
Real minRadius;
Real maxRadius;
Object *container;
};
///////////////////////////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS //////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------------------------------------------------
/** Remove an object from the containment of this module given the item
* to remove and trigger the proper callback events */
//-------------------------------------------------------------------------------------------------
void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, Bool exposeStealthUnits )
{
/*
#ifdef RTS_DEBUG
TheInGameUI->message( L"'%S(%d)' no longer contains '%S(%d)'",
getObject()->getTemplate()->getName().str(),
getObject()->getID(),
itemToRemove->m_object->getTemplate()->getName().str(),
itemToRemove->m_object->getID() );
#endif
*/
Object *rider = *it;
// remove item from list
m_containList.erase(it);
m_containListSize--;
if( rider->isKindOf( KINDOF_STEALTH_GARRISON ) )
{
DEBUG_ASSERTCRASH( m_stealthUnitsContained > 0, ("OpenContain::removeFromContainViaIterator - Removing stealth unit but stealth count is %d", m_stealthUnitsContained) );
m_stealthUnitsContained--;
if( exposeStealthUnits )
{
StealthUpdate* stealth = rider->getStealth();
if( stealth )
{
stealth->markAsDetected();
}
}
}
if( rider->isKindOf( KINDOF_HERO ) )
{
DEBUG_ASSERTCRASH( m_heroUnitsContained > 0, ("OpenContain::removeFromContainViaIterator - Removing hero but hero count is %d", m_heroUnitsContained) );
m_heroUnitsContained--;
}
if (isEnclosingContainerFor( rider ))
{
addOrRemoveObjFromWorld(rider, true);
rider->setPosition( getObject()->getPosition() );
// if we are not enclosed, then just walk away from where we "are."
}
/// place the object in the world at position of the container m_object
rider->setLayer( getObject()->getLayer() );
doUnloadSound();
// trigger an onRemoving event for 'm_object' no longer containing 'itemToRemove->m_object'
DEBUG_ASSERTCRASH(getObject()->getContain() == this, ("hmm, wrong container"));
if( getObject()->getContain() )
{
getObject()->getContain()->onRemoving( rider );
}
// trigger an onRemovedFrom event for 'remove'
DEBUG_ASSERTCRASH(getObject()->getContain() == this, ("hmm, wrong container 2"));
rider->onRemovedFrom( getObject() );
}
//-------------------------------------------------------------------------------------------------
void OpenContain::scatterToNearbyPosition(Object* rider)
{
Object *theContainer = getObject();
//
// for now we will just set the position of the object that is being removed from us
// at a random angle away from our center out some distance
//
//
// pick an angle that is in the view of the current camera position so that
// the thing will come out "toward" the player and they can see it
// NOPE, can't do that ... all players screen angles will be different, unless
// we maintain the angle of each players screen in the player structure or something
//
Real angle = GameLogicRandomValueReal( 0.0f, 2.0f * PI );
// angle = TheTacticalView->getAngle();
// angle -= GameLogicRandomValueReal( PI / 3.0f, 2.0f * (PI / 3.0F) );
Real minRadius = theContainer->getGeometryInfo().getBoundingCircleRadius();
Real maxRadius = minRadius + minRadius / 2.0f;
const Coord3D *containerPos = theContainer->getPosition();
Real dist = GameLogicRandomValueReal( minRadius, maxRadius );
Coord3D pos;
pos.x = dist * Cos( angle ) + containerPos->x;
pos.y = dist * Sin( angle ) + containerPos->y;
pos.z = TheTerrainLogic->getLayerHeight( pos.x, pos.y, theContainer->getLayer() );
// set orientation
rider->setOrientation( angle );
AIUpdateInterface *ai = rider->getAI();
if( ai )
{
// set position of the object at center of building and move them toward pos
rider->setPosition( theContainer->getPosition() );
ai->ignoreObstacle(theContainer);
ai->aiMoveToPosition( &pos, CMD_FROM_AI );
}
else
{
// no ai, just set position at the target pos
rider->setPosition( &pos );
}
}
//-------------------------------------------------------------------------------------------------
void OpenContain::onContaining( Object *rider, Bool wasSelected )
{
// Play audio
if( m_loadSoundsEnabled )
{
AudioEventRTS enterSound = *getObject()->getTemplate()->getSoundEnter();
enterSound.setObjectID(getObject()->getID());
TheAudio->addAudioEvent(&enterSound);
}
}
//-------------------------------------------------------------------------------------------------
void OpenContain::onRemoving( Object *rider)
{
// Play audio
AudioEventRTS exitSound = *getObject()->getTemplate()->getSoundExit();
exitSound.setObjectID(getObject()->getID());
TheAudio->addAudioEvent(&exitSound);
if (rider) {
// This is a misnomer, but it makes it clearer for the user.
AudioEventRTS fallingSound = *rider->getTemplate()->getSoundFalling();
fallingSound.setObjectID(rider->getID());
TheAudio->addAudioEvent(&fallingSound);
}
}
//-------------------------------------------------------------------------------------------------
Real OpenContain::getContainedItemsMass() const
{
/// @todo srj -- may want to cache this information.
Real mass = 0;
for(ContainedItemsList::const_iterator it = m_containList.begin(); it != m_containList.end(); ++it)
{
PhysicsBehavior* phys = (*it)->getPhysics();
if (phys)
mass += phys->getMass();
}
return mass;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void OpenContain::onCollide( Object *other, const Coord3D *loc, const Coord3D *normal )
{
// colliding with nothing? we don't care.
if( other == nullptr )
return;
// ok, step two: only contain stuff that wants us to contain it.
// (it would suck to have accidental collisions contain things...)
// must be an AI object....
AIUpdateInterface *ai = other->getAI();
if (ai == nullptr)
return;
// ...and must be trying to enter our object.
// (huh huh, he said "enter")
if (ai->getEnterTarget() != getObject())
return;
// last-minute change: don't allow units from multiple (different) players to occupy the same
// unit. so eject everyone else if they aren't controlled by the same player. (srj)
for( ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); )
{
// save the rider...
Object* rider = *it;
// incr the iterator BEFORE calling the func (if the func removes the rider,
// the iterator becomes invalid)
++it;
// call it
if( rider->getControllingPlayer() != other->getControllingPlayer() )
{
if( rider->getAI() )
{
if( rider->isKindOf( KINDOF_STEALTH_GARRISON ) )
{
// aiExit is needed to walk away from the building well, but it doesn't take the Unstealth flag
StealthUpdate* stealth = rider->getStealth();
if( stealth )
{
stealth->markAsDetected();
}
}
rider->getAI()->aiExit( getObject(), CMD_FROM_AI );
}
else
removeFromContain( rider, TRUE );
}
}
// finally, we must have space to contain it.
if( !isValidContainerFor( other, TRUE ) )
return;
addToContain(other);
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void OpenContain::onDelete() ///< Last possible moment cleanup
{
// This uses my literal list, and not the gettor, because we don't want to get redirected some place fancy.
for(ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); )
{
Object* rider = *it;
++it;
TheGameLogic->destroyObject( rider );
}
}
//-------------------------------------------------------------------------------------------------
/** The die callback. */
//-------------------------------------------------------------------------------------------------
void OpenContain::onDie( const DamageInfo * damageInfo )
{
if (!getOpenContainModuleData()->m_dieMuxData.isDieApplicable(getObject(), damageInfo))
return;
#if !RETAIL_COMPATIBLE_CRC
killRidersWhoAreNotFreeToExit();
#endif
//Check to see if we are going to inflict damage on contained units.
if( getDamagePercentageToUnits() > 0 )
{
//Cycle through the units and apply damage to them!
processDamageToContained(getDamagePercentageToUnits());
}
#if RETAIL_COMPATIBLE_CRC
killRidersWhoAreNotFreeToExit();
#endif
// Leaving this commented out to show it can't work. We are about to die, so they will have zero
// chance to hit an exitState::Update. At least we would clean them up in onDelete.
// orderAllPassengersToExit( CMD_FROM_AI, FALSE );
removeAllContained();
}
// ------------------------------------------------------------------------------------------------
/** Check to see if we are a valid container for 'obj' */
// ------------------------------------------------------------------------------------------------
Bool OpenContain::isValidContainerFor(const Object* obj, Bool checkCapacity) const
{
const Object *us = getObject();
const OpenContainModuleData *modData = getOpenContainModuleData();
// if we have any kind of masks set then we must make that check
if (obj->isAnyKindOf( modData->m_allowInsideKindOf ) == FALSE ||
obj->isAnyKindOf( modData->m_forbidInsideKindOf ) == TRUE)
{
return false;
}
//
// check relationship, note that this behavior is defined as the relation between
// 'obj' and the container 'us', and not the reverse
//
Bool relationshipRestricted = FALSE;
Relationship r = obj->getRelationship( us );
switch( r )
{
case ALLIES:
if( modData->m_allowAlliesInside == FALSE )
relationshipRestricted = TRUE;
break;
case ENEMIES:
if( modData->m_allowEnemiesInside == FALSE )
relationshipRestricted = TRUE;
break;
case NEUTRAL:
if( modData->m_allowNeutralInside == FALSE )
relationshipRestricted = TRUE;
break;
default:
DEBUG_CRASH(( "isValidContainerFor: Undefined relationship (%d) between '%s' and '%s'",
r, getObject()->getTemplate()->getName().str(),
obj->getTemplate()->getName().str() ));
return FALSE;
}
if( relationshipRestricted == TRUE )
return FALSE;
// all is well
return true;
}
// ------------------------------------------------------------------------------------------------
/**
This new call is going to replace all game callings of removeFromContain.
Consider rFC a 'system' call, while this is a 'game' call. rFC will pull
from the contained list and just plop the guy in the world, this function
will then override that location with cool game stuff.
Exit and Evacuate can fail, removeAllContain and removeFromContain cannot.
*/
void OpenContain::exitObjectViaDoor( Object *exitObj, ExitDoorType exitDoor )
{
DEBUG_ASSERTCRASH(exitDoor == DOOR_1, ("multiple exit doors not supported here"));
removeFromContain( exitObj );
Object *me = getObject();
m_doorCloseCountdown = getOpenContainModuleData()->m_doorOpenTime;
if (m_doorCloseCountdown)
{
// srj sez: only diddle the doors if this countdown is nonzero.
// this allows us to prevent this module from messing with the doors
// at all, which is required for DeliverPayloadAIUpdate.
/// @todo srj -- for now, OpenContain assumes at most one door
me->clearAndSetModelConditionState( MODELCONDITION_DOOR_1_CLOSING, MODELCONDITION_DOOR_1_OPENING );
}
Int numberExits = getOpenContainModuleData()->m_numberOfExitPaths;
if( numberExits > 0 )
{
// We have ExitStart/End specified in art to use when we kick people out. If >1, then
// we have many and we need to decide which one to use.
AsciiString startBone("ExitStart");
AsciiString endBone("ExitEnd");
Coord3D startPosition;
Coord3D endPosition;
if( numberExits > 1 )
{
char suffix[8];
itoa(m_whichExitPath, suffix, 10);
if( m_whichExitPath < 10 )
{
startBone.concat('0');
endBone.concat('0');