/
Unit.cpp
2944 lines (2245 loc) · 77.4 KB
/
Unit.cpp
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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include "UnitDef.h"
#include "Unit.h"
#include "UnitHandler.h"
#include "UnitDefHandler.h"
#include "UnitLoader.h"
#include "UnitMemPool.h"
#include "UnitToolTipMap.hpp"
#include "UnitTypes/Building.h"
#include "Scripts/NullUnitScript.h"
#include "Scripts/UnitScriptFactory.h"
#include "Scripts/CobInstance.h" // for TAANG2RAD
#include "CommandAI/CommandAI.h"
#include "CommandAI/FactoryCAI.h"
#include "CommandAI/AirCAI.h"
#include "CommandAI/BuilderCAI.h"
#include "CommandAI/CommandAI.h"
#include "CommandAI/FactoryCAI.h"
#include "CommandAI/MobileCAI.h"
#include "ExternalAI/EngineOutHandler.h"
#include "Game/GameHelper.h"
#include "Game/GameSetup.h"
#include "Game/GlobalUnsynced.h"
#include "Game/SelectedUnitsHandler.h"
#include "Game/Players/Player.h"
#include "Map/Ground.h"
#include "Map/MapInfo.h"
#include "Map/ReadMap.h"
#include "Rendering/GroundFlash.h"
#include "Game/UI/Groups/Group.h"
#include "Game/UI/Groups/GroupHandler.h"
#include "Sim/Features/Feature.h"
#include "Sim/Features/FeatureDef.h"
#include "Sim/Features/FeatureDefHandler.h"
#include "Sim/Features/FeatureHandler.h"
#include "Sim/Misc/GlobalConstants.h"
#include "Sim/Misc/CollisionVolume.h"
#include "Sim/Misc/LosHandler.h"
#include "Sim/Misc/QuadField.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Misc/Wind.h"
#include "Sim/Misc/ModInfo.h"
#include "Sim/MoveTypes/GroundMoveType.h"
#include "Sim/MoveTypes/HoverAirMoveType.h"
#include "Sim/MoveTypes/MoveDefHandler.h"
#include "Sim/MoveTypes/MoveType.h"
#include "Sim/MoveTypes/MoveTypeFactory.h"
#include "Sim/MoveTypes/ScriptMoveType.h"
#include "Sim/Projectiles/FlareProjectile.h"
#include "Sim/Projectiles/ProjectileMemPool.h"
#include "Sim/Projectiles/WeaponProjectiles/MissileProjectile.h"
#include "Sim/Weapons/Weapon.h"
#include "Sim/Weapons/WeaponDefHandler.h"
#include "Sim/Weapons/WeaponLoader.h"
#include "System/EventHandler.h"
#include "System/Log/ILog.h"
#include "System/Matrix44f.h"
#include "System/SpringMath.h"
#include "System/creg/DefTypes.h"
#include "System/creg/STL_List.h"
#include "System/Sound/ISoundChannels.h"
#include "System/Sync/SyncedPrimitive.h"
#undef near
// See end of source for member bindings
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
float CUnit::empDeclineRate = 0.0f;
float CUnit::expMultiplier = 0.0f;
float CUnit::expPowerScale = 0.0f;
float CUnit::expHealthScale = 0.0f;
float CUnit::expReloadScale = 0.0f;
float CUnit::expGrade = 0.0f;
CUnit::CUnit(): CSolidObject()
{
assert(unitMemPool.alloced(this));
static_assert((sizeof(los) / sizeof(los[0])) == ILosType::LOS_TYPE_COUNT, "");
static_assert((sizeof(losStatus) / sizeof(losStatus[0])) == MAX_TEAMS, "");
fireState = FIRESTATE_FIREATWILL;
moveState = MOVESTATE_MANEUVER;
lastNanoAdd = gs->frameNum;
}
CUnit::~CUnit()
{
assert(unitMemPool.mapped(this));
// clean up if we are still under MoveCtrl here
DisableScriptMoveType();
// NOTE:
// could also do this in Update() or even in CUnitKilledCB(), but not
// in KillUnit() since we have to wait for deathScriptFinished there
// we nevertheless want the sim-frame latency between CUnitKilledCB()
// and the CreateWreckage() call to be as low as possible to prevent
// position discontinuities
if (delayedWreckLevel >= 0)
featureHandler.CreateWreckage({this, unitDef, featureDefHandler->GetFeatureDefByID(featureDefID), {}, {}, -1, team, -1, heading, buildFacing, delayedWreckLevel - 1, 1});
if (deathExpDamages != nullptr)
DynDamageArray::DecRef(deathExpDamages);
if (selfdExpDamages != nullptr)
DynDamageArray::DecRef(selfdExpDamages);
if (fpsControlPlayer != nullptr) {
fpsControlPlayer->StopControllingUnit();
assert(fpsControlPlayer == nullptr);
}
if (activated && unitDef->targfac)
losHandler->IncreaseAllyTeamRadarErrorSize(allyteam);
SetMetalStorage(0);
SetEnergyStorage(0);
// not all unit deletions run through KillUnit(),
// but we always want to call this for ourselves
UnBlock();
// Remove us from our group, if we were in one
SetGroup(nullptr);
// delete script first so any callouts still see valid ptrs
DeleteScript();
spring::SafeDestruct(commandAI);
spring::SafeDestruct(moveType);
spring::SafeDestruct(prevMoveType);
// ScriptCallback may reference weapons, so delete the script first
CWeaponLoader::FreeWeapons(this);
quadField.RemoveUnit(this);
}
void CUnit::InitStatic()
{
// numerator was 2*UNIT_SLOWUPDATE_RATE/GAME_SPEED which equals 1 since 99.0
SetEmpDeclineRate(1.0f / modInfo.paralyzeDeclineRate);
SetExpMultiplier(modInfo.unitExpMultiplier);
SetExpPowerScale(modInfo.unitExpPowerScale);
SetExpHealthScale(modInfo.unitExpHealthScale);
SetExpReloadScale(modInfo.unitExpReloadScale);
SetExpGrade(0.0f);
CBuilderCAI::InitStatic();
unitToolTipMap.Clear();
}
void CUnit::SanityCheck() const
{
pos.AssertNaNs();
midPos.AssertNaNs();
relMidPos.AssertNaNs();
preFramePos.AssertNaNs();
speed.AssertNaNs();
rightdir.AssertNaNs();
updir.AssertNaNs();
frontdir.AssertNaNs();
if (unitDef->IsGroundUnit()) {
assert(pos.x >= -(float3::maxxpos * 16.0f));
assert(pos.x <= (float3::maxxpos * 16.0f));
assert(pos.z >= -(float3::maxzpos * 16.0f));
assert(pos.z <= (float3::maxzpos * 16.0f));
}
}
void CUnit::PreInit(const UnitLoadParams& params)
{
// if this is < 0, UnitHandler will give us a random ID
id = params.unitID;
featureDefID = -1;
unitDef = params.unitDef;
{
const FeatureDef* wreckFeatureDef = featureDefHandler->GetFeatureDef(unitDef->wreckName);
if (wreckFeatureDef != nullptr) {
featureDefID = wreckFeatureDef->id;
while (wreckFeatureDef != nullptr) {
wreckFeatureDef->PreloadModel();
wreckFeatureDef = featureDefHandler->GetFeatureDefByID(wreckFeatureDef->deathFeatureDefID);
}
}
}
for (const auto it: unitDef->buildOptions) {
const UnitDef* ud = unitDefHandler->GetUnitDefByName(it.second);
if (ud == nullptr)
continue;
ud->PreloadModel();
}
team = params.teamID;
allyteam = teamHandler.AllyTeam(team);
buildFacing = std::abs(params.facing) % NUM_FACINGS;
xsize = ((buildFacing & 1) == 0) ? unitDef->xsize : unitDef->zsize;
zsize = ((buildFacing & 1) == 1) ? unitDef->xsize : unitDef->zsize;
localModel.SetModel(model = unitDef->LoadModel());
collisionVolume = unitDef->collisionVolume;
selectionVolume = unitDef->selectionVolume;
// specialize defaults if non-custom sphere or footprint-box
collisionVolume.InitDefault(float4(model->radius, model->height, xsize * SQUARE_SIZE, zsize * SQUARE_SIZE));
selectionVolume.InitDefault(float4(model->radius, model->height, xsize * SQUARE_SIZE, zsize * SQUARE_SIZE));
mapSquare = CGround::GetSquare((params.pos).cClampInMap());
heading = GetHeadingFromFacing(buildFacing);
upright = unitDef->upright;
SetVelocity(params.speed);
Move(preFramePos = params.pos.cClampInMap(), false);
UpdateDirVectors(!upright && IsOnGround(), false);
SetMidAndAimPos(model->relMidPos, model->relMidPos, true);
SetRadiusAndHeight(model);
UpdateMidAndAimPos();
unitHandler.AddUnit(this);
quadField.MovedUnit(this);
losStatus[allyteam] = LOS_ALL_MASK_BITS | LOS_INLOS | LOS_INRADAR | LOS_PREVLOS | LOS_CONTRADAR;
ASSERT_SYNCED(pos);
footprint = int2(unitDef->xsize, unitDef->zsize);
beingBuilt = params.beingBuilt;
mass = (beingBuilt)? mass: unitDef->mass;
crushResistance = unitDef->crushResistance;
power = unitDef->power;
maxHealth = unitDef->health;
health = beingBuilt? 0.1f: unitDef->health;
cost.metal = unitDef->metal;
cost.energy = unitDef->energy;
buildTime = unitDef->buildTime;
armoredMultiple = std::max(0.0001f, unitDef->armoredMultiple); // armored multiple of 0 will crash spring
armorType = unitDef->armorType;
category = unitDef->category;
leaveTracks = unitDef->decalDef.leaveTrackDecals;
unitToolTipMap.Set(id, unitDef->humanName + " - " + unitDef->tooltip);
// sensor parameters
realLosRadius = Clamp(int(unitDef->losRadius) , 0, MAX_UNIT_SENSOR_RADIUS);
realAirLosRadius = Clamp(int(unitDef->airLosRadius) , 0, MAX_UNIT_SENSOR_RADIUS);
radarRadius = Clamp( unitDef->radarRadius , 0, MAX_UNIT_SENSOR_RADIUS);
sonarRadius = Clamp( unitDef->sonarRadius , 0, MAX_UNIT_SENSOR_RADIUS);
jammerRadius = Clamp( unitDef->jammerRadius , 0, MAX_UNIT_SENSOR_RADIUS);
sonarJamRadius = Clamp( unitDef->sonarJamRadius, 0, MAX_UNIT_SENSOR_RADIUS);
seismicRadius = Clamp( unitDef->seismicRadius , 0, MAX_UNIT_SENSOR_RADIUS);
seismicSignature = unitDef->seismicSignature;
stealth = unitDef->stealth;
sonarStealth = unitDef->sonarStealth;
// can be overridden by cloak orders during construction
wantCloak |= unitDef->startCloaked;
decloakDistance = unitDef->decloakDistance;
flankingBonusMode = unitDef->flankingBonusMode;
flankingBonusDir = unitDef->flankingBonusDir;
flankingBonusMobility = unitDef->flankingBonusMobilityAdd * 1000;
flankingBonusMobilityAdd = unitDef->flankingBonusMobilityAdd;
flankingBonusAvgDamage = (unitDef->flankingBonusMax + unitDef->flankingBonusMin) * 0.5f;
flankingBonusDifDamage = (unitDef->flankingBonusMax - unitDef->flankingBonusMin) * 0.5f;
useHighTrajectory = (unitDef->highTrajectoryType == 1);
harvestStorage.metal = unitDef->harvestMetalStorage;
harvestStorage.energy = unitDef->harvestEnergyStorage;
moveType = MoveTypeFactory::GetMoveType(this, unitDef);
script = CUnitScriptFactory::CreateScript(this, unitDef);
if (unitDef->selfdExpWeaponDef != nullptr)
selfdExpDamages = DynDamageArray::IncRef(&unitDef->selfdExpWeaponDef->damages);
if (unitDef->deathExpWeaponDef != nullptr)
deathExpDamages = DynDamageArray::IncRef(&unitDef->deathExpWeaponDef->damages);
commandAI = CUnitLoader::NewCommandAI(this, unitDef);
}
void CUnit::PostInit(const CUnit* builder)
{
CWeaponLoader::LoadWeapons(this);
CWeaponLoader::InitWeapons(this);
// does nothing for LUS, calls Create+SetMaxReloadTime for COB
script->Create();
// all units are blocking (ie. register on the blocking-map
// when not flying) except mines, since their position would
// be given away otherwise by the PF, etc.
// NOTE: this does mean that mines can be stacked indefinitely
// (an extra yardmap character would be needed to prevent this)
immobile = unitDef->IsImmobileUnit();
UpdateCollidableStateBit(CSolidObject::CSTATE_BIT_SOLIDOBJECTS, unitDef->collidable && (!immobile || !unitDef->canKamikaze));
Block();
if (unitDef->windGenerator > 0.0f)
envResHandler.AddGenerator(this);
UpdateTerrainType();
UpdatePhysicalState(0.1f);
UpdatePosErrorParams(true, true);
if (FloatOnWater() && IsInWater())
Move(UpVector * (std::max(CGround::GetHeightReal(pos.x, pos.z), -moveType->GetWaterline()) - pos.y), true);
if (unitDef->canmove || unitDef->builder) {
if (unitDef->moveState <= MOVESTATE_NONE) {
// always inherit our builder's movestate
// if none, set CUnit's default (maneuver)
if (builder != nullptr)
moveState = builder->moveState;
} else {
// use our predefined movestate
moveState = unitDef->moveState;
}
commandAI->GiveCommand(Command(CMD_MOVE_STATE, 0, moveState));
}
if (commandAI->CanChangeFireState()) {
if (unitDef->fireState <= FIRESTATE_NONE) {
// inherit our builder's firestate (if it is a factory)
// if no builder, CUnit's default (fire-at-will) is set
if (builder != nullptr && dynamic_cast<CFactoryCAI*>(builder->commandAI) != nullptr)
fireState = builder->fireState;
} else {
// use our predefined firestate
fireState = unitDef->fireState;
}
commandAI->GiveCommand(Command(CMD_FIRE_STATE, 0, fireState));
}
// Lua might call SetUnitHealth within UnitCreated
// and trigger FinishedBuilding before we get to it
const bool preBeingBuilt = beingBuilt;
// these must precede UnitFinished from FinishedBuilding
eventHandler.UnitCreated(this, builder);
eoh->UnitCreated(*this, builder);
// skip past the gradual build-progression
if (!preBeingBuilt && !beingBuilt)
FinishedBuilding(true);
eventHandler.RenderUnitCreated(this, isCloaked);
}
void CUnit::PostLoad()
{
if (unitDef->windGenerator > 0.0f)
envResHandler.AddGenerator(this);
eventHandler.RenderUnitCreated(this, isCloaked);
}
//////////////////////////////////////////////////////////////////////
//
void CUnit::FinishedBuilding(bool postInit)
{
if (!beingBuilt && !postInit)
return;
beingBuilt = false;
buildProgress = 1.0f;
mass = unitDef->mass;
if (soloBuilder != nullptr) {
DeleteDeathDependence(soloBuilder, DEPENDENCE_BUILDER);
soloBuilder = nullptr;
}
ChangeLos(realLosRadius, realAirLosRadius);
if (unitDef->activateWhenBuilt)
Activate();
SetMetalStorage(unitDef->metalStorage);
SetEnergyStorage(unitDef->energyStorage);
// Sets the frontdir in sync with heading.
frontdir = GetVectorFromHeading(heading) + (UpVector * frontdir.y);
eventHandler.UnitFinished(this);
eoh->UnitFinished(*this);
{
if (!unitDef->isFeature)
return;
CFeature* f = featureHandler.CreateWreckage({this, nullptr, featureDefHandler->GetFeatureDefByID(featureDefID), {}, {}, -1, team, allyteam, heading, buildFacing, 0, 0});
if (f == nullptr)
return;
f->blockHeightChanges = true;
UnBlock();
KillUnit(nullptr, false, true);
}
}
void CUnit::KillUnit(CUnit* attacker, bool selfDestruct, bool reclaimed, bool showDeathSequence)
{
if (IsCrashing() && !beingBuilt)
return;
ForcedKillUnit(attacker, selfDestruct, reclaimed, showDeathSequence);
}
void CUnit::ForcedKillUnit(CUnit* attacker, bool selfDestruct, bool reclaimed, bool showDeathSequence)
{
if (isDead)
return;
isDead = true;
// release attached units
ReleaseTransportees(attacker, selfDestruct, reclaimed);
// pre-destruction event; unit may be kept around for its death sequence
eventHandler.UnitDestroyed(this, attacker);
eoh->UnitDestroyed(*this, attacker);
// Will be called in the destructor again, but this can not hurt
SetGroup(nullptr);
if (unitDef->windGenerator > 0.0f)
envResHandler.DelGenerator(this);
blockHeightChanges = false;
deathScriptFinished = (!showDeathSequence || reclaimed || beingBuilt);
if (deathScriptFinished)
return;
const WeaponDef* wd = selfDestruct? unitDef->selfdExpWeaponDef: unitDef->deathExpWeaponDef;
const DynDamageArray* da = selfDestruct? selfdExpDamages: deathExpDamages;
if (wd != nullptr) {
assert(da != nullptr);
CExplosionParams params = {
pos,
ZeroVector,
*da,
wd,
this, // owner
nullptr, // hitUnit
nullptr, // hitFeature
da->craterAreaOfEffect,
da->damageAreaOfEffect,
da->edgeEffectiveness,
da->explosionSpeed,
(da->GetDefault() > 500.0f)? 1.0f: 2.0f, // gfxMod
false, // impactOnly
false, // ignoreOwner
true, // damageGround
-1u // projectileID
};
helper->Explosion(params);
}
recentDamage += (maxHealth * 2.0f * selfDestruct);
// start running the unit's kill-script
script->Killed();
}
void CUnit::ForcedMove(const float3& newPos)
{
UnBlock();
Move((preFramePos = newPos) - pos, true);
Block();
eventHandler.UnitMoved(this);
quadField.MovedUnit(this);
}
float3 CUnit::GetErrorVector(int argAllyTeam) const
{
const int tstAllyTeam = argAllyTeam * (argAllyTeam >= 0) * (argAllyTeam < teamHandler.ActiveAllyTeams());
const bool limitRead = (1 ) && (tstAllyTeam != argAllyTeam); // LuaHandle without full read access
const bool isVisible = (1 - limitRead) && ((losStatus[tstAllyTeam] & LOS_INLOS ) != 0 || teamHandler.Ally(tstAllyTeam, allyteam)); // in LOS or allied, no error
const bool seenGhost = (1 - limitRead) && ((losStatus[tstAllyTeam] & LOS_PREVLOS) != 0 && gameSetup->ghostedBuildings && unitDef->IsBuildingUnit()); // seen ghosted building, no error
const bool isOnRadar = (1 - limitRead) && ((losStatus[tstAllyTeam] & LOS_INRADAR) != 0); // current radar contact
switch ((limitRead * 1) + (isVisible * 2) + (seenGhost * 4) + (isOnRadar * 8)) {
case 0: { return (posErrorVector * losHandler->GetBaseRadarErrorSize() * 2.0f); } break; // !limitRead && !isVisible && !seenGhost && !isOnRadar
case 1: { return (posErrorVector * losHandler->GetBaseRadarErrorSize() * 2.0f); } break; // limitRead
case 8: { return (posErrorVector * losHandler->GetAllyTeamRadarErrorSize(tstAllyTeam)); } break; // !limitRead && !isVisible && !seenGhost && isOnRadar
default: { } break; // !limitRead && ( isVisible || seenGhost) && !isOnRadar
}
return ZeroVector;
}
void CUnit::UpdatePosErrorParams(bool updateError, bool updateDelta)
{
// every frame, magnitude of error increases
// error-direction is fixed until next delta
if (updateError)
posErrorVector += posErrorDelta;
if (!updateDelta)
return;
if ((--nextPosErrorUpdate) > 0)
return;
constexpr float errorScale = 1.0f / 256.0f;
constexpr float errorMults[] = {1.0f, -1.0f};
float3 newPosError = gsRNG.NextVector();
newPosError.y *= 0.2f;
newPosError *= errorMults[posErrorVector.dot(newPosError) < 0.0f];
posErrorDelta = (newPosError - posErrorVector) * errorScale;
nextPosErrorUpdate = UNIT_SLOWUPDATE_RATE;
}
void CUnit::Drop(const float3& parentPos, const float3& parentDir, CUnit* parent)
{
// drop unit from position
fallSpeed = mix(unitDef->unitFallSpeed, parent->unitDef->fallSpeed, unitDef->unitFallSpeed <= 0.0f);
frontdir = parentDir * XZVector;
SetVelocityAndSpeed(speed * XZVector);
Move(UpVector * ((parentPos.y - height) - pos.y), true);
UpdateMidAndAimPos();
SetPhysicalStateBit(CSolidObject::PSTATE_BIT_FALLING);
// start parachute animation
script->Falling();
}
void CUnit::DeleteScript()
{
if (script != &CNullUnitScript::value)
spring::SafeDestruct(script);
script = &CNullUnitScript::value;
}
void CUnit::EnableScriptMoveType()
{
if (UsingScriptMoveType())
return;
prevMoveType = moveType;
moveType = MoveTypeFactory::GetScriptMoveType(this);
}
void CUnit::DisableScriptMoveType()
{
if (!UsingScriptMoveType())
return;
spring::SafeDestruct(moveType);
moveType = prevMoveType;
prevMoveType = nullptr;
// ensure unit does not try to move back to the
// position it was at when MoveCtrl was enabled
// FIXME: prevent the issuing of extra commands?
if (moveType == nullptr)
return;
moveType->SetGoal(moveType->oldPos = pos);
moveType->StopMoving();
}
void CUnit::Update()
{
ASSERT_SYNCED(pos);
UpdatePhysicalState(0.1f);
UpdatePosErrorParams(true, false);
UpdateTransportees(); // none if already dead
if (beingBuilt)
return;
if (isDead)
return;
recentDamage *= 0.9f;
flankingBonusMobility += flankingBonusMobilityAdd;
if (IsStunned()) {
// paralyzed weapons shouldn't reload
for (CWeapon* w: weapons) {
++(w->reloadStatus);
}
return;
}
restTime += 1;
outOfMapTime += 1;
outOfMapTime *= (!pos.IsInBounds());
}
void CUnit::UpdateWeapons()
{
if (!CanUpdateWeapons())
return;
for (CWeapon* w: weapons) {
w->Update();
}
}
void CUnit::UpdateTransportees()
{
for (TransportedUnit& tu: transportedUnits) {
CUnit* transportee = tu.unit;
transportee->mapSquare = mapSquare;
float3 relPiecePos = ZeroVector;
float3 absPiecePos = pos;
if (tu.piece >= 0) {
relPiecePos = script->GetPiecePos(tu.piece);
absPiecePos = this->GetObjectSpacePos(relPiecePos);
}
if (unitDef->holdSteady) {
// slave transportee orientation to piece
if (tu.piece >= 0) {
const CMatrix44f& transMat = GetTransformMatrix(true);
const CMatrix44f& pieceMat = script->GetPieceMatrix(tu.piece);
transportee->SetDirVectors(transMat * pieceMat);
}
} else {
// slave transportee orientation to body
transportee->heading = heading;
transportee->updir = updir;
transportee->frontdir = frontdir;
transportee->rightdir = rightdir;
}
transportee->Move(absPiecePos, false);
transportee->UpdateMidAndAimPos();
transportee->SetHeadingFromDirection();
// see ::AttachUnit
if (transportee->IsStunned()) {
quadField.MovedUnit(transportee);
}
}
}
void CUnit::ReleaseTransportees(CUnit* attacker, bool selfDestruct, bool reclaimed)
{
for (TransportedUnit& tu: transportedUnits) {
CUnit* transportee = tu.unit;
assert(transportee != this);
if (transportee->isDead)
continue;
transportee->SetTransporter(nullptr);
transportee->DeleteDeathDependence(this, DEPENDENCE_TRANSPORTER);
transportee->UpdateVoidState(false);
if (!unitDef->releaseHeld) {
// we don't want transportees to leave a corpse
if (!selfDestruct)
transportee->DoDamage(DamageArray(1e6f), ZeroVector, nullptr, -DAMAGE_EXTSOURCE_KILLED, -1);
transportee->KillUnit(attacker, selfDestruct, reclaimed);
} else {
// NOTE: game's responsibility to deal with edge-cases now
transportee->Move(transportee->pos.cClampInBounds(), false);
// if this transporter uses the piece-underneath-ground
// method to "hide" transportees, place transportee near
// the transporter's place of death
if (transportee->pos.y < CGround::GetHeightReal(transportee->pos.x, transportee->pos.z)) {
const float r1 = transportee->radius + radius;
const float r2 = r1 * std::max(unitDef->unloadSpread, 1.0f);
// try to unload in a presently unoccupied spot
// (if no such spot, unload on transporter wreck)
for (int i = 0; i < 10; ++i) {
float3 pos = transportee->pos;
pos.x += (gsRNG.NextFloat() * 2.0f * r2 - r2);
pos.z += (gsRNG.NextFloat() * 2.0f * r2 - r2);
pos.y = CGround::GetHeightReal(pos.x, pos.z);
if (!pos.IsInBounds())
continue;
if (quadField.NoSolidsExact(pos, transportee->radius + 2.0f, 0xFFFFFFFF, CSolidObject::CSTATE_BIT_SOLIDOBJECTS)) {
transportee->Move(pos, false);
break;
}
}
} else {
if (transportee->unitDef->IsGroundUnit()) {
transportee->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_FLYING);
transportee->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_SKIDDING);
}
}
transportee->moveType->SlowUpdate();
transportee->moveType->LeaveTransport();
// issue a move order so that units dropped from flying
// transports won't try to return to their pick-up spot
if (unitDef->canfly && transportee->unitDef->canmove)
transportee->commandAI->GiveCommand(Command(CMD_MOVE, transportee->pos));
transportee->SetStunned(transportee->paralyzeDamage > (modInfo.paralyzeOnMaxHealth? transportee->maxHealth: transportee->health));
transportee->SetVelocityAndSpeed(speed * (0.5f + 0.5f * gsRNG.NextFloat()));
eventHandler.UnitUnloaded(transportee, this);
}
}
transportedUnits.clear();
}
void CUnit::TransporteeKilled(const CObject* o)
{
const auto pred = [&](const TransportedUnit& tu) { return (tu.unit == o); };
const auto iter = std::find_if(transportedUnits.begin(), transportedUnits.end(), pred);
if (iter == transportedUnits.end())
return;
const CUnit* unit = iter->unit;
transportCapacityUsed -= (unit->xsize / SPRING_FOOTPRINT_SCALE);
transportMassUsed -= unit->mass;
SetMass(mass - unit->mass);
*iter = transportedUnits.back();
transportedUnits.pop_back();
}
void CUnit::UpdateResources()
{
resourcesMake.metal = resourcesMakeI.metal + resourcesMakeOld.metal;
resourcesUse.metal = resourcesUseI.metal + resourcesUseOld.metal;
resourcesMake.energy = resourcesMakeI.energy + resourcesMakeOld.energy;
resourcesUse.energy = resourcesUseI.energy + resourcesUseOld.energy;
resourcesMakeOld.metal = resourcesMakeI.metal;
resourcesUseOld.metal = resourcesUseI.metal;
resourcesMakeOld.energy = resourcesMakeI.energy;
resourcesUseOld.energy = resourcesUseI.energy;
resourcesMakeI.metal = resourcesUseI.metal = resourcesMakeI.energy = resourcesUseI.energy = 0.0f;
}
void CUnit::SetLosStatus(int at, unsigned short newStatus)
{
const unsigned short currStatus = losStatus[at];
const unsigned short diffBits = (currStatus ^ newStatus);
// add to the state before running the callins
//
// note that is not symmetric: UnitEntered* and
// UnitLeft* are after-the-fact events, yet the
// Left* call-ins would still see the old state
// without first clearing the IN{LOS, RADAR} bit
losStatus[at] |= newStatus;
if (diffBits) {
if (diffBits & LOS_INLOS) {
if (newStatus & LOS_INLOS) {
eventHandler.UnitEnteredLos(this, at);
eoh->UnitEnteredLos(*this, at);
} else {
// clear before sending the event
losStatus[at] &= ~LOS_INLOS;
eventHandler.UnitLeftLos(this, at);
eoh->UnitLeftLos(*this, at);
}
}
if (diffBits & LOS_INRADAR) {
if (newStatus & LOS_INRADAR) {
eventHandler.UnitEnteredRadar(this, at);
eoh->UnitEnteredRadar(*this, at);
} else {
// clear before sending the event
losStatus[at] &= ~LOS_INRADAR;
eventHandler.UnitLeftRadar(this, at);
eoh->UnitLeftRadar(*this, at);
}
}
}
// remove from the state after running the callins
losStatus[at] &= newStatus;
}
unsigned short CUnit::CalcLosStatus(int at)
{
const unsigned short currStatus = losStatus[at];
unsigned short newStatus = currStatus;
unsigned short mask = ~(currStatus >> LOS_MASK_SHIFT);
if (losHandler->InLos(this, at)) {
newStatus |= (mask & (LOS_INLOS | LOS_INRADAR |
LOS_PREVLOS | LOS_CONTRADAR));
}
else if (losHandler->InRadar(this, at)) {
newStatus |= (mask & LOS_INRADAR);
newStatus &= ~(mask & LOS_INLOS);
}
else {
newStatus &= ~(mask & (LOS_INLOS | LOS_INRADAR | LOS_CONTRADAR));
}
return newStatus;
}
void CUnit::UpdateLosStatus(int at)
{
const unsigned short currStatus = losStatus[at];
if ((currStatus & LOS_ALL_MASK_BITS) == LOS_ALL_MASK_BITS) {
return; // no need to update, all changes are masked
}
SetLosStatus(at, CalcLosStatus(at));
}
void CUnit::SetStunned(bool stun) {
stunned = stun;
if (moveType->progressState == AMoveType::Active) {
if (stunned) {
script->StopMoving();
} else {
script->StartMoving(moveType->IsReversing());
}
}
eventHandler.UnitStunned(this, stun);
}
void CUnit::SlowUpdate()
{
UpdatePosErrorParams(false, true);
DoWaterDamage();
if (health < 0.0f) {
KillUnit(nullptr, false, true);
return;
}
repairAmount = 0.0f;
if (paralyzeDamage > 0.0f) {
// NOTE: the paralysis degradation-rate has to vary, because
// when units are paralyzed based on their current health (in
// DoDamage) we potentially start decaying from a lower damage
// level and would otherwise be de-paralyzed more quickly than
// specified by <paralyzeTime>
paralyzeDamage -= ((modInfo.paralyzeOnMaxHealth? maxHealth: health) * (UNIT_SLOWUPDATE_RATE / float(GAME_SPEED)) * CUnit::empDeclineRate);
paralyzeDamage = std::max(paralyzeDamage, 0.0f);
}
UpdateResources();
if (IsStunned()) {
// call this because we can be pushed into a different quad while stunned
// which would make us invulnerable to most non-/small-AOE weapon impacts
static_cast<AMoveType*>(moveType)->SlowUpdate();
const bool notStunned = (paralyzeDamage <= (modInfo.paralyzeOnMaxHealth? maxHealth: health));
const bool inFireBase = (transporter == nullptr || !transporter->unitDef->IsTransportUnit() || transporter->unitDef->isFirePlatform);
// de-stun only if we are not (still) inside a non-firebase transport
if (notStunned && inFireBase)
SetStunned(false);
SlowUpdateCloak(true);
return;
}
if (selfDCountdown > 0) {
if ((selfDCountdown -= 1) == 0) {
// avoid unfinished buildings making an explosion
KillUnit(nullptr, !beingBuilt, beingBuilt);
return;
}
if ((selfDCountdown & 1) && (team == gu->myTeam) && !gu->spectating)
LOG("%s: self-destruct in %is", unitDef->humanName.c_str(), (selfDCountdown >> 1) + 1);
}
if (beingBuilt) {
if (modInfo.constructionDecay && (lastNanoAdd < (gs->frameNum - modInfo.constructionDecayTime))) {
float buildDecay = buildTime * modInfo.constructionDecaySpeed;
buildDecay = 1.0f / std::max(0.001f, buildDecay);
buildDecay = std::min(buildProgress, buildDecay);
health = std::max(0.0f, health - maxHealth * buildDecay);
buildProgress -= buildDecay;
AddMetal(cost.metal * buildDecay, false);
if (health <= 0.0f || buildProgress <= 0.0f)
KillUnit(nullptr, false, true);
}
ScriptDecloak(nullptr, nullptr);
return;
}
// below is stuff that should not be run while being built
commandAI->SlowUpdate();
moveType->SlowUpdate();
// FIXME: scriptMakeMetal ...?
AddMetal(resourcesUncondMake.metal);
AddEnergy(resourcesUncondMake.energy);
UseMetal(resourcesUncondUse.metal);
UseEnergy(resourcesUncondUse.energy);
if (activated) {
if (UseMetal(resourcesCondUse.metal))
AddEnergy(resourcesCondMake.energy);
if (UseEnergy(resourcesCondUse.energy))
AddMetal(resourcesCondMake.metal);
}
AddMetal(unitDef->metalMake * 0.5f);
if (activated) {
if (UseEnergy(unitDef->energyUpkeep * 0.5f)) {
AddMetal(unitDef->makesMetal * 0.5f);
if (unitDef->extractsMetal > 0.0f)
AddMetal(metalExtract * 0.5f);