/
GameHelper.cpp
1372 lines (1104 loc) · 42 KB
/
GameHelper.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 "GameHelper.h"
#include "Camera.h"
#include "GameSetup.h"
#include "Game/GlobalUnsynced.h"
#include "Lua/LuaUI.h"
#include "Map/Ground.h"
#include "Map/MapDamage.h"
#include "Map/ReadMap.h"
#include "Rendering/Models/3DModel.h"
#include "Sim/Features/Feature.h"
#include "Sim/Features/FeatureDef.h"
#include "Sim/Misc/BuildingMaskMap.h"
#include "Sim/Misc/CollisionHandler.h"
#include "Sim/Misc/CollisionVolume.h"
#include "Sim/Misc/DamageArray.h"
#include "Sim/Misc/GeometricObjects.h"
#include "Sim/Misc/GroundBlockingObjectMap.h"
#include "Sim/Misc/QuadField.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Misc/ModInfo.h"
#include "Sim/MoveTypes/MoveType.h"
#include "Sim/MoveTypes/MoveDefHandler.h"
#include "Sim/MoveTypes/MoveMath/MoveMath.h"
#include "Sim/Projectiles/ExplosionGenerator.h"
#include "Sim/Projectiles/ExplosionListener.h"
#include "Sim/Projectiles/Projectile.h"
#include "Sim/Units/CommandAI/MobileCAI.h"
#include "Sim/Units/UnitTypes/Factory.h"
#include "Sim/Units/BuildInfo.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Units/Unit.h"
#include "Sim/Units/UnitHandler.h"
#include "Sim/Weapons/WeaponDefHandler.h"
#include "Sim/Weapons/Weapon.h"
#include "System/EventHandler.h"
#include "System/myMath.h"
#include "System/Sound/ISoundChannels.h"
#include "System/Sync/SyncTracer.h"
static CGameHelper gGameHelper;
CGameHelper* helper = &gGameHelper;
void CGameHelper::Init()
{
for (auto& wdVec: waitingDamages) {
wdVec.clear();
wdVec.reserve(32);
}
}
void CGameHelper::Update()
{
const int wdIdx = gs->frameNum & (waitingDamages.size() - 1);
// need to use explicit indexing because CUnit::DoDamage
// can add *new* WaitingDamage's for this frame while we
// are still iterating
for (size_t n = 0; n < waitingDamages[wdIdx].size(); n++) {
const WaitingDamage& wd = waitingDamages[wdIdx][n];
CUnit* attackee = unitHandler.GetUnit(wd.targetID);
CUnit* attacker = unitHandler.GetUnit(wd.attackerID); // null if wd.attacker is -1
if (attackee == nullptr)
continue;
attackee->DoDamage(wd.damage, wd.impulse, attacker, wd.weaponID, wd.projectileID);
}
waitingDamages[wdIdx].clear();
}
//////////////////////////////////////////////////////////////////////
// Explosions/Damage
//////////////////////////////////////////////////////////////////////
float CGameHelper::CalcImpulseScale(const DamageArray& damages, const float expDistanceMod)
{
// limit the impulse to prevent later FP overflow
// (several weapons have _default_ damage values in the order of 1e4,
// which make the simulation highly unstable because they can impart
// speeds of several thousand elmos/frame to units and throw them far
// outside the map)
// DamageArray::operator* scales damage multipliers,
// not the impulse factor --> need to scale manually
// by it for impulse
const float impulseDmgMult = (damages.GetDefault() + damages.impulseBoost);
const float rawImpulseScale = damages.impulseFactor * expDistanceMod * impulseDmgMult;
return Clamp(rawImpulseScale, -MAX_EXPLOSION_IMPULSE, MAX_EXPLOSION_IMPULSE);
}
void CGameHelper::DoExplosionDamage(
CUnit* unit,
CUnit* owner,
const float3& expPos,
const float expRadius,
const float expSpeed,
const float expEdgeEffect,
const bool ignoreOwner,
const DamageArray& damages,
const int weaponDefID,
const int projectileID
) {
assert(unit != nullptr);
if (ignoreOwner && (unit == owner))
return;
const LocalModelPiece* lhp = unit->GetLastHitPiece(gs->frameNum);
const CollisionVolume* vol = unit->GetCollisionVolume(lhp);
const float3& lhpPos = (lhp != nullptr && vol == lhp->GetCollisionVolume())? lhp->GetAbsolutePos(): ZeroVector;
const float3& volPos = vol->GetWorldSpacePos(unit, lhpPos);
// linear damage falloff with distance
const float expDist = (expRadius != 0.0f) ? vol->GetPointSurfaceDistance(unit, lhp, expPos) : 0.0f;
const float expRim = expDist * expEdgeEffect;
// return early if (distance > radius)
if (expDist > expRadius)
return;
// expEdgeEffect should be in [0, 1], so expRadius >= expDist >= expDist*expEdgeEffect
assert(expRadius >= expRim);
// expMod will also be in [0, 1], no negatives
// TODO: damage attenuation for underwater units from surface explosions?
const float expDistanceMod = (expRadius + 0.001f - expDist) / (expRadius + 0.001f - expRim);
const float modImpulseScale = CalcImpulseScale(damages, expDistanceMod);
// NOTE: if an explosion occurs right underneath a
// unit's map footprint, it might cause damage even
// if the unit's collision volume is greatly offset
// (because CQuadField coverage is based exclusively
// on unit->radius, so the DoDamage() iteration will
// include units that should not be touched)
const float3 impulseDir = (volPos - expPos).SafeNormalize();
const float3 expImpulse = impulseDir * modImpulseScale;
DamageArray expDamages = damages * expDistanceMod;
if (expDist < (expSpeed * DIRECT_EXPLOSION_DAMAGE_SPEED_SCALE)) {
// damage directly
unit->DoDamage(expDamages, expImpulse, owner, weaponDefID, projectileID);
} else {
// damage later
waitingDamages[(gs->frameNum + int(expDist / expSpeed) - (DIRECT_EXPLOSION_DAMAGE_SPEED_SCALE - 1)) & (waitingDamages.size() - 1)].emplace_back(std::move(expDamages), expImpulse, ((owner != nullptr)? owner->id: -1), unit->id, weaponDefID, projectileID);
}
}
void CGameHelper::DoExplosionDamage(
CFeature* feature,
CUnit* owner,
const float3& expPos,
const float expRadius,
const float expEdgeEffect,
const DamageArray& damages,
const int weaponDefID,
const int projectileID
) {
assert(feature != nullptr);
const LocalModelPiece* lhp = feature->GetLastHitPiece(gs->frameNum);
const CollisionVolume* vol = feature->GetCollisionVolume(lhp);
const float3& lhpPos = (lhp != nullptr && vol == lhp->GetCollisionVolume())? lhp->GetAbsolutePos(): ZeroVector;
const float3& volPos = vol->GetWorldSpacePos(feature, lhpPos);
const float expDist = (expRadius != 0.0f) ? vol->GetPointSurfaceDistance(feature, nullptr, expPos) : 0.0f;
const float expRim = expDist * expEdgeEffect;
if (expDist > expRadius)
return;
assert(expRadius >= expRim);
const float expDistanceMod = (expRadius + 0.001f - expDist) / (expRadius + 0.001f - expRim);
const float modImpulseScale = CalcImpulseScale(damages, expDistanceMod);
const float3 impulseDir = (volPos - expPos).SafeNormalize();
const float3 expImpulse = impulseDir * modImpulseScale;
feature->DoDamage(damages * expDistanceMod, expImpulse, owner, weaponDefID, projectileID);
}
void CGameHelper::DamageObjectsInExplosionRadius(
const CExplosionParams& params,
const float expRad,
const int weaponDefID
) {
static std::vector<CUnit*> unitCache;
static std::vector<CFeature*> featureCache;
const unsigned int oldNumUnits = unitCache.size();
const unsigned int oldNumFeatures = featureCache.size();
quadField.GetUnitsAndFeaturesColVol(params.pos, expRad, unitCache, featureCache);
const unsigned int newNumUnits = unitCache.size();
const unsigned int newNumFeatures = featureCache.size();
// damage all units within the explosion radius
// NOTE:
// this can recursively trigger ::Explosion() again
// which would overwrite our object cache if we did
// not keep track of end-markers --> certain objects
// would not be damaged AT ALL (!)
for (unsigned int n = oldNumUnits; n < newNumUnits; n++)
DoExplosionDamage(unitCache[n], params.owner, params.pos, expRad, params.explosionSpeed, params.edgeEffectiveness, params.ignoreOwner, params.damages, weaponDefID, params.projectileID);
unitCache.resize(oldNumUnits);
// damage all features within the explosion radius
for (unsigned int n = oldNumFeatures; n < newNumFeatures; n++)
DoExplosionDamage(featureCache[n], params.owner, params.pos, expRad, params.edgeEffectiveness, params.damages, weaponDefID, params.projectileID);
featureCache.resize(oldNumFeatures);
}
void CGameHelper::Explosion(const CExplosionParams& params) {
const DamageArray& damages = params.damages;
// if weaponDef is NULL, this is a piece-explosion
// (implicit damage-type -DAMAGE_EXPLOSION_DEBRIS)
const WeaponDef* weaponDef = params.weaponDef;
const int weaponDefID = (weaponDef != nullptr)? weaponDef->id: -CSolidObject::DAMAGE_EXPLOSION_DEBRIS;
const int explosionID = (weaponDef != nullptr)? weaponDef->impactExplosionGeneratorID: CExplosionGeneratorHandler::EXPGEN_ID_STANDARD;
const float craterAOE = std::max(1.0f, params.craterAreaOfEffect);
const float damageAOE = std::max(1.0f, params.damageAreaOfEffect);
const float realHeight = CGround::GetHeightReal(params.pos);
const float altitude = (params.pos).y - realHeight;
// NOTE: event triggers before damage is applied to objects
const bool noGfx = eventHandler.Explosion(weaponDefID, params.projectileID, params.pos, params.owner);
if (luaUI != nullptr && weaponDef != nullptr)
luaUI->ShockFront(params.pos, weaponDef->cameraShake, damageAOE);
if (params.impactOnly) {
if (params.hitUnit != nullptr) {
DoExplosionDamage(
params.hitUnit,
params.owner,
params.pos,
0.0f,
params.explosionSpeed,
params.edgeEffectiveness,
params.ignoreOwner,
params.damages,
weaponDefID,
params.projectileID
);
}
if (params.hitFeature != nullptr) {
DoExplosionDamage(
params.hitFeature,
params.owner,
params.pos,
0.0f,
params.edgeEffectiveness,
params.damages,
weaponDefID,
params.projectileID
);
}
} else {
DamageObjectsInExplosionRadius(params, damageAOE, weaponDefID);
// deform the map if the explosion was above-ground
// (but had large enough radius to touch the ground)
if (altitude >= -1.0f) {
if (params.damageGround && !mapDamage->Disabled() && (craterAOE > altitude) && (damages.craterMult > 0.0f)) {
// limit the depth somewhat
const float craterDepth = damages.GetDefault() * (1.0f - (altitude / craterAOE));
const float damageDepth = std::min(craterAOE * 10.0f, craterDepth);
const float craterStrength = (damageDepth + damages.craterBoost) * damages.craterMult;
const float craterRadius = craterAOE - altitude;
mapDamage->Explosion(params.pos, craterStrength, craterRadius);
}
}
}
if (!noGfx) {
explGenHandler.GenExplosion(
explosionID,
params.pos,
params.dir,
damages.GetDefault(),
damageAOE,
params.gfxMod,
params.owner,
params.hitUnit
);
}
CExplosionCreator::FireExplosionEvent(params);
{
if (weaponDef == nullptr)
return;
const GuiSoundSet& soundSet = weaponDef->hitSound;
const unsigned int soundFlags = CCustomExplosionGenerator::GetFlagsFromHeight(params.pos.y, realHeight);
const unsigned int soundMask = CCustomExplosionGenerator::CEG_SPWF_WATER | CCustomExplosionGenerator::CEG_SPWF_UNDERWATER;
// 0 or 1, use regular sound if explosion went off in voidwater
const int soundNum = ((soundFlags & soundMask) != 0);
const int soundID = soundSet.getID(soundNum);
if (soundID <= 0)
return;
Channels::Battle->PlaySample(soundID, params.pos, soundSet.getVolume(soundNum));
}
}
//////////////////////////////////////////////////////////////////////
// Spatial unit queries
//////////////////////////////////////////////////////////////////////
/**
* @brief Generic spatial unit query.
*
* Filter should implement two methods:
* - bool Team(int allyTeam): returns true if this allyteam should be considered
* - bool Unit(const CUnit*): returns true if the unit should be returned
*
* Query should implement three methods:
* - float3 GetPos(): returns the center of the (circular) search area
* - float GetRadius(): returns the radius of the search area
* - void AddUnit(const CUnit*): add the unit to the result
*
* The area as returned by Query is approximate; exact circular filtering
* should be implemented in the Query object if desired.
* (It isn't necessary for e.g. GetClosest** methods.)
*/
template<typename TFilter, typename TQuery>
static inline void QueryUnits(TFilter filter, TQuery& query)
{
QuadFieldQuery qfQuery;
quadField.GetQuads(qfQuery, query.pos, query.radius);
const int tempNum = gs->GetTempNum();
for (int t = 0; t < teamHandler.ActiveAllyTeams(); ++t) { //FIXME
if (!filter.Team(t))
continue;
for (const int qi: *qfQuery.quads) {
const auto& allyTeamUnits = quadField.GetQuad(qi).teamUnits[t];
for (CUnit* u: allyTeamUnits) {
if (u->tempNum == tempNum)
continue;
u->tempNum = tempNum;
if (!filter.Unit(u))
continue;
query.AddUnit(u);
}
}
}
}
namespace {
namespace Filter {
/**
* Base class for Filter::Friendly and Filter::Enemy.
*/
struct Base
{
const int searchAllyteam;
Base(int at) : searchAllyteam(at) {}
};
/**
* Look for friendly units only.
* All units are included by default.
*/
struct Friendly : public Base
{
public:
Friendly(const CUnit* exclUnit, int allyTeam) : Base(allyTeam), excludeUnit(exclUnit) {}
bool Team(int allyTeam) { return teamHandler.Ally(searchAllyteam, allyTeam); }
bool Unit(const CUnit* unit) { return (unit != excludeUnit); }
protected:
const CUnit* excludeUnit;
};
/**
* Look for enemy units only.
* All units are included by default.
*/
struct Enemy : public Base
{
public:
Enemy(const CUnit* exclUnit, int allyTeam) : Base(allyTeam), excludeUnit(exclUnit) {}
bool Team(int allyTeam) { return !teamHandler.Ally(searchAllyteam, allyTeam); }
bool Unit(const CUnit* unit) { return (unit != excludeUnit && !unit->IsNeutral()); }
protected:
const CUnit* excludeUnit;
};
/**
* Look for enemy units which are in LOS/Radar only.
*/
struct Enemy_InLos : public Enemy
{
Enemy_InLos(const CUnit* exclUnit, int allyTeam) : Enemy(exclUnit, allyTeam) {}
bool Unit(const CUnit* u) {
return (u->losStatus[searchAllyteam] & (LOS_INLOS | LOS_INRADAR) && Enemy::Unit(u));
}
};
/**
* Look for enemy aircraft which are in LOS/Radar only.
*/
struct EnemyAircraft : public Enemy_InLos
{
EnemyAircraft(const CUnit* exclUnit, int allyTeam) : Enemy_InLos(exclUnit, allyTeam) {}
bool Unit(const CUnit* u) {
return (u->unitDef->canfly && !u->IsCrashing() && Enemy_InLos::Unit(u));
}
};
/**
* Look for units of any team. Enemy units must be in LOS/Radar.
*
* NOT SYNCED
*/
struct Friendly_All_Plus_Enemy_InLos_NOT_SYNCED
{
bool Team(int) const { return true; }
bool Unit(const CUnit* u) const {
return (u->allyteam == gu->myAllyTeam) ||
(u->losStatus[gu->myAllyTeam] & (LOS_INLOS | LOS_INRADAR)) ||
gu->spectatingFullView;
}
};
/**
* Delegates filtering to CMobileCAI::IsValidTarget.
*
* This is necessary in CMobileCAI and CAirCAI so they can select the closest
* enemy unit which they consider a valid target.
*
* Without the valid target condition, units don't attack anything if an
* the nearest enemy is an invalid target. (e.g. noChaseCategory)
*/
struct Enemy_InLos_ValidTarget : public Enemy_InLos
{
const CMobileCAI* const cai;
Enemy_InLos_ValidTarget(int at, const CMobileCAI* cai) :
Enemy_InLos(nullptr, at), cai(cai) {}
bool Unit(const CUnit* u) {
return Enemy_InLos::Unit(u) && cai->IsValidTarget(u);
}
};
} // end of namespace Filter
namespace Query {
/**
* Base class for Query objects, containing the basic methods needed by
* QueryUnits which defined the search area.
*/
struct Base
{
const float3& pos;
const float radius;
const float sqRadius;
Base(const float3& pos, float searchRadius) :
pos(pos), radius(searchRadius), sqRadius(searchRadius * searchRadius) {}
};
/**
* Return the closest unit.
*/
struct ClosestUnit : public Base
{
protected:
float closeSqDist;
CUnit* closeUnit;
public:
ClosestUnit(const float3& pos, float searchRadius) :
Base(pos, searchRadius), closeSqDist(sqRadius), closeUnit(nullptr) {}
void AddUnit(CUnit* u) {
const float sqDist = (pos - u->midPos).SqLength2D();
if (sqDist <= closeSqDist) {
closeSqDist = sqDist;
closeUnit = u;
}
}
CUnit* GetClosestUnit() const { return closeUnit; }
};
/**
* Return the closest unit, using GetUnitErrorPos
* instead of the unit's actual position.
*
* NOT SYNCED
*/
struct ClosestUnit_ErrorPos_NOT_SYNCED : public ClosestUnit
{
ClosestUnit_ErrorPos_NOT_SYNCED(const float3& pos, float searchRadius) :
ClosestUnit(pos, searchRadius) {}
void AddUnit(CUnit* u) {
float3 unitPos;
if (gu->spectatingFullView) {
unitPos = u->midPos;
} else {
unitPos = u->GetErrorPos(gu->myAllyTeam);
}
const float sqDist = (pos - unitPos).SqLength2D();
if (sqDist <= closeSqDist) {
closeSqDist = sqDist;
closeUnit = u;
}
}
};
/**
* Returns the closest unit (3D) which may have LOS on the search position.
* LOS is spherical in the context of this query. Whether the unit actually has
* LOS depends on nearby obstacles.
*
* Search area just needs to touch the unit's radius: this query includes the
* target unit's radius.
*
* If canBeBlind is true then the LOS test is skipped.
*/
struct ClosestUnit_InLos : public Base
{
protected:
float closeDist;
CUnit* closeUnit;
const bool canBeBlind;
public:
ClosestUnit_InLos(const float3& pos, float searchRadius, bool canBeBlind) :
Base(pos, searchRadius + unitHandler.MaxUnitRadius()),
closeDist(searchRadius), closeUnit(nullptr), canBeBlind(canBeBlind) {}
void AddUnit(CUnit* u) {
// FIXME: use volumeBoundingRadius?
// (more for consistency than need)
const float dist = pos.distance(u->midPos) - u->radius;
if (dist <= closeDist &&
(canBeBlind || (u->losRadius > dist))
) {
closeDist = dist;
closeUnit = u;
}
}
CUnit* GetClosestUnit() const { return closeUnit; }
};
/**
* Returns the closest unit (2D) which may have LOS on the search position.
* Whether it actually has LOS depends on nearby obstacles.
*
* If canBeBlind is true then the LOS test is skipped.
*/
struct ClosestUnit_InLos_Cylinder : public ClosestUnit
{
const bool canBeBlind;
ClosestUnit_InLos_Cylinder(const float3& pos, float searchRadius, bool canBeBlind) :
ClosestUnit(pos, searchRadius), canBeBlind(canBeBlind) {}
void AddUnit(CUnit* u) {
const float sqDist = (pos - u->midPos).SqLength2D();
if (sqDist <= closeSqDist &&
(canBeBlind || Square(u->losRadius) > sqDist)
) {
closeSqDist = sqDist;
closeUnit = u;
}
}
};
/**
* Return the unitIDs of all units exactly within the search area.
*/
struct AllUnitsById : public Base
{
protected:
vector<int>& found;
public:
AllUnitsById(const float3& pos, float searchRadius, vector<int>& found) :
Base(pos, searchRadius), found(found) {}
void AddUnit(CUnit* u) {
if ((pos - u->midPos).SqLength2D() <= sqRadius) {
found.push_back(u->id);
}
}
};
} // end of namespace Query
} // end of namespace
void CGameHelper::GenerateWeaponTargets(const CWeapon* weapon, const CUnit* avoidUnit, std::vector<std::pair<float, CUnit*>>& targets)
{
const CUnit* weaponOwner = weapon->owner;
const CUnit* lastAttacker = ((weaponOwner->lastAttackFrame + 200) <= gs->frameNum) ? weaponOwner->lastAttacker : nullptr;
const WeaponDef* weaponDef = weapon->weaponDef;
const DynDamageArray* weaponDmg = weapon->damages;
const float3& ownerPos = weaponOwner->pos;
const float3 testPos;
const float aimPosHeight = weapon->aimFromPos.y;
const float minMapHeight = std::max(0.0f, readMap->GetInitMinHeight());
// how much damage the weapon deals over 1 second
const float secDamage = weaponDmg->GetDefault() * weapon->salvoSize / weapon->reloadTime * GAME_SPEED;
const float heightMod = weaponDef->heightmod;
const float baseRange = weapon->range;
const float rangeBoost = weapon->autoTargetRangeBoost;
const float scanRadius = weapon->GetRange2D(rangeBoost, (aimPosHeight - minMapHeight) * heightMod);
// [0] := default, [1,2,3,4,5,6] := target is {avoidee, in bad category, crashing, last attacker, paralyzed, outside unboosted range}
constexpr float tgtPriorityMults[] = {1.0f, 10.0f, 100.0f, 1000.0f, 0.5f, 4.0f, 100000.0f};
const bool paralyzer = (weaponDmg->paralyzeDamageTime != 0);
// copy on purpose since the below calls lua
QuadFieldQuery qfQuery;
quadField.GetQuads(qfQuery, ownerPos, scanRadius);
const int tempNum = gs->GetTempNum();
for (int t = 0; t < teamHandler.ActiveAllyTeams(); ++t) {
if (teamHandler.Ally(weaponOwner->allyteam, t))
continue;
for (const int qi: *qfQuery.quads) {
const std::vector<CUnit*>& allyTeamUnits = quadField.GetQuad(qi).teamUnits[t];
for (CUnit* targetUnit: allyTeamUnits) {
if (targetUnit->tempNum == tempNum)
continue;
targetUnit->tempNum = tempNum;
if (!weapon->TestTarget(testPos, SWeaponTarget(targetUnit)))
continue;
const unsigned short targetLOSState = targetUnit->losStatus[weaponOwner->allyteam];
float targetPriority = tgtPriorityMults[(targetUnit == avoidUnit) * 1];
float3 targetPos;
if (targetLOSState & LOS_INLOS) {
targetPos = targetUnit->aimPos;
} else if (targetLOSState & LOS_INRADAR) {
targetPos = weapon->GetUnitPositionWithError(targetUnit);
targetPriority *= tgtPriorityMults[1];
} else {
continue;
}
const float modRange = weapon->GetRange2D(rangeBoost, (aimPosHeight - targetPos.y) * heightMod);
const float sqDist2D = ownerPos.SqDistance2D(targetPos);
if (sqDist2D > Square(modRange))
continue;
const float dist2D = math::sqrt(sqDist2D);
const float rangeMul = (dist2D * weaponDef->proximityPriority + modRange * 0.4f + 100.0f);
const float damageMul = weaponDmg->Get(targetUnit->armorType) * targetUnit->curArmorMultiple;
targetPriority *= rangeMul;
targetPriority *= tgtPriorityMults[(dist2D > baseRange) * 6];
if (targetLOSState & LOS_INLOS) {
targetPriority *= (secDamage + targetUnit->health);
if (paralyzer && targetUnit->paralyzeDamage > (modInfo.paralyzeOnMaxHealth? targetUnit->maxHealth: targetUnit->health))
targetPriority *= tgtPriorityMults[5];
if (weapon->hasTargetWeight)
targetPriority *= weapon->TargetWeight(targetUnit);
} else {
targetPriority *= (secDamage + 10000.0f);
}
if (targetLOSState & LOS_PREVLOS) {
targetPriority /= (damageMul * targetUnit->power * (0.7f + gsRNG.NextFloat() * 0.6f));
targetPriority *= tgtPriorityMults[((targetUnit->category & weapon->badTargetCategory) != 0) * 2];
targetPriority *= tgtPriorityMults[(targetUnit->IsCrashing()) * 3];
targetPriority *= tgtPriorityMults[(targetUnit == lastAttacker) * 4];
}
const bool allowTarget = eventHandler.AllowWeaponTarget(weaponOwner->id, targetUnit->id, weapon->weaponNum, weaponDef->id, &targetPriority);
// Lua call may have changed tempNum, so needs to be set again
targetUnit->tempNum = tempNum;
if (!allowTarget)
continue;
targets.emplace_back(targetPriority, targetUnit);
}
}
}
std::stable_sort(targets.begin(), targets.end(), [](const std::pair<float, CUnit*>& a, const std::pair<float, CUnit*>& b) { return (a.first < b.first); });
#ifdef TRACE_SYNC
{
tracefile << "[GenerateWeaponTargets] ownerID, attackRadius: " << weaponOwner->id << ", " << scanRadius << " ";
for (const auto& ti: targets) {
tracefile << "\tpriority: " << (ti.first) << ", targetID: " << (ti.second)->id << " ";
}
tracefile << "\n";
}
#endif
}
CUnit* CGameHelper::GetClosestUnit(const float3& pos, float searchRadius)
{
Query::ClosestUnit_ErrorPos_NOT_SYNCED q(pos, searchRadius);
QueryUnits(Filter::Friendly_All_Plus_Enemy_InLos_NOT_SYNCED(), q);
return q.GetClosestUnit();
}
CUnit* CGameHelper::GetClosestEnemyUnit(const CUnit* excludeUnit, const float3& pos, float searchRadius, int searchAllyteam)
{
Query::ClosestUnit q(pos, searchRadius);
QueryUnits(Filter::Enemy_InLos(excludeUnit, searchAllyteam), q);
return q.GetClosestUnit();
}
CUnit* CGameHelper::GetClosestValidTarget(const float3& pos, float searchRadius, int searchAllyteam, const CMobileCAI* cai)
{
Query::ClosestUnit q(pos, searchRadius);
QueryUnits(Filter::Enemy_InLos_ValidTarget(searchAllyteam, cai), q);
return q.GetClosestUnit();
}
CUnit* CGameHelper::GetClosestEnemyUnitNoLosTest(
const CUnit* excludeUnit,
const float3& pos,
float searchRadius,
int searchAllyteam,
bool sphere,
bool canBeBlind
) {
if (sphere) {
// includes target radius
Query::ClosestUnit_InLos q(pos, searchRadius, canBeBlind);
QueryUnits(Filter::Enemy(excludeUnit, searchAllyteam), q);
return q.GetClosestUnit();
} else {
// cylinder (doesn't include target radius)
Query::ClosestUnit_InLos_Cylinder q(pos, searchRadius, canBeBlind);
QueryUnits(Filter::Enemy(excludeUnit, searchAllyteam), q);
return q.GetClosestUnit();
}
}
CUnit* CGameHelper::GetClosestFriendlyUnit(const CUnit* excludeUnit, const float3& pos, float searchRadius, int searchAllyteam)
{
Query::ClosestUnit q(pos, searchRadius);
QueryUnits(Filter::Friendly(excludeUnit, searchAllyteam), q);
return q.GetClosestUnit();
}
CUnit* CGameHelper::GetClosestEnemyAircraft(const CUnit* excludeUnit, const float3& pos, float searchRadius, int searchAllyteam)
{
Query::ClosestUnit q(pos, searchRadius);
QueryUnits(Filter::EnemyAircraft(excludeUnit, searchAllyteam), q);
return q.GetClosestUnit();
}
void CGameHelper::GetEnemyUnits(const float3& pos, float searchRadius, int searchAllyteam, vector<int> &found)
{
Query::AllUnitsById q(pos, searchRadius, found);
QueryUnits(Filter::Enemy_InLos(nullptr, searchAllyteam), q);
}
void CGameHelper::GetEnemyUnitsNoLosTest(const float3& pos, float searchRadius, int searchAllyteam, vector<int> &found)
{
Query::AllUnitsById q(pos, searchRadius, found);
QueryUnits(Filter::Enemy(nullptr, searchAllyteam), q);
}
//////////////////////////////////////////////////////////////////////
// Miscellaneous (i.e. not yet categorized)
//////////////////////////////////////////////////////////////////////
void CGameHelper::BuggerOff(float3 pos, float radius, bool spherical, bool forced, int teamId, CUnit* excludeUnit)
{
// copy on purpose since BuggerOff can call risky stuff
QuadFieldQuery qfQuery;
quadField.GetUnitsExact(qfQuery, pos, radius + SQUARE_SIZE, spherical);
const int allyTeamId = teamHandler.AllyTeam(teamId);
for (CUnit* u: *qfQuery.units) {
if (u == excludeUnit)
continue;
// don't send BuggerOff commands to enemy units
if (!teamHandler.Ally(u->allyteam, allyTeamId) && !teamHandler.Ally(allyTeamId, u->allyteam))
continue;
if (!forced && (u->moveType->IsPushResistant() || u->UsingScriptMoveType()))
continue;
u->commandAI->BuggerOff(pos, radius + SQUARE_SIZE);
}
}
float3 CGameHelper::Pos2BuildPos(const BuildInfo& buildInfo, bool synced)
{
float3 pos;
constexpr int BUILDMAP_SQ = SQUARE_SIZE * 2;
// snap build-positions to 16-elmo grid
if (buildInfo.GetXSize() & 2)
pos.x = math::floor((buildInfo.pos.x ) / (BUILDMAP_SQ)) * BUILDMAP_SQ + SQUARE_SIZE;
else
pos.x = math::floor((buildInfo.pos.x + SQUARE_SIZE) / (BUILDMAP_SQ)) * BUILDMAP_SQ;
if (buildInfo.GetZSize() & 2)
pos.z = math::floor((buildInfo.pos.z ) / (BUILDMAP_SQ)) * BUILDMAP_SQ + SQUARE_SIZE;
else
pos.z = math::floor((buildInfo.pos.z + SQUARE_SIZE) / (BUILDMAP_SQ)) * BUILDMAP_SQ;
pos.y = CGameHelper::GetBuildHeight(pos, buildInfo.def, synced);
return pos;
}
struct SearchOffset {
int dx,dy;
int qdist; // dx*dx+dy*dy
};
static bool SearchOffsetComparator (const SearchOffset& a, const SearchOffset& b)
{
return a.qdist < b.qdist;
}
static const vector<SearchOffset>& GetSearchOffsetTable (int radius)
{
static vector <SearchOffset> searchOffsets;
unsigned int size = radius*radius*4;
if (size > searchOffsets.size()) {
searchOffsets.resize (size);
for (int y = 0; y < radius*2; y++)
for (int x = 0; x < radius*2; x++)
{
SearchOffset& i = searchOffsets[y*radius*2 + x];
i.dx = x - radius;
i.dy = y - radius;
i.qdist = i.dx*i.dx + i.dy*i.dy;
}
std::stable_sort(searchOffsets.begin(), searchOffsets.end(), SearchOffsetComparator);
}
return searchOffsets;
}
//! only used by the AI callback of the same name
float3 CGameHelper::ClosestBuildSite(int team, const UnitDef* unitDef, float3 pos, float searchRadius, int minDist, int facing)
{
if (unitDef == nullptr)
return -RgtVector;
CFeature* feature = nullptr;
const int allyTeam = teamHandler.AllyTeam(team);
const int endr = (int) (searchRadius / (SQUARE_SIZE * 2));
const vector<SearchOffset>& ofs = GetSearchOffsetTable(endr);
for (int so = 0; so < endr * endr * 4; so++) {
const float x = pos.x + ofs[so].dx * SQUARE_SIZE * 2;
const float z = pos.z + ofs[so].dy * SQUARE_SIZE * 2;
BuildInfo bi(unitDef, float3(x, 0.0f, z), facing);
bi.pos = Pos2BuildPos(bi, false);
if (CGameHelper::TestUnitBuildSquare(bi, feature, allyTeam, false) && (!feature || feature->allyteam != allyTeam)) {
const int xs = (int) (x / SQUARE_SIZE);
const int zs = (int) (z / SQUARE_SIZE);
const int xsize = bi.GetXSize();
const int zsize = bi.GetZSize();
bool good = true;
int z2Min = std::max( 0, zs - (zsize ) / 2 - minDist);
int z2Max = std::min(mapDims.mapy, zs + (zsize + 1) / 2 + minDist);
int x2Min = std::max( 0, xs - (xsize ) / 2 - minDist);
int x2Max = std::min(mapDims.mapx, xs + (xsize + 1) / 2 + minDist);
// check for nearby blocking features
for (int z2 = z2Min; z2 < z2Max; ++z2) {
for (int x2 = x2Min; x2 < x2Max; ++x2) {
CSolidObject* solObj = groundBlockingObjectMap.GroundBlockedUnsafe(z2 * mapDims.mapx + x2);
if (solObj && solObj->immobile && !dynamic_cast<CFeature*>(solObj)) {
good = false;
break;
}
}
}
if (good) {
z2Min = std::max( 0, zs - (zsize ) / 2 - minDist - 2);
z2Max = std::min(mapDims.mapy, zs + (zsize + 1) / 2 + minDist + 2);
x2Min = std::max( 0, xs - (xsize ) / 2 - minDist - 2);
x2Max = std::min(mapDims.mapx, xs + (xsize + 1) / 2 + minDist + 2);
// check for nearby factories with open yards
for (int z2 = z2Min; z2 < z2Max; ++z2) {
for (int x2 = x2Min; x2 < x2Max; ++x2) {
CSolidObject* solObj = groundBlockingObjectMap.GroundBlockedUnsafe(z2 * mapDims.mapx + x2);
if (solObj == nullptr)
continue;
if (!solObj->immobile)
continue;
if (!solObj->yardOpen)
continue;
good = false;
break;
}
}
}
if (good) {
return bi.pos;
}
}
}
return -RgtVector;
}
// find the reference height for a build-position
// against which to compare all footprint squares
float CGameHelper::GetBuildHeight(const float3& pos, const UnitDef* unitdef, bool synced)
{
// we are not going to terraform the ground for mobile units
// (so we do not care about maxHeightDif constraints either)
// TODO: maybe respect waterline if <pos> is in water
if (!unitdef->IsImmobileUnit())
return (std::max(pos.y, CGround::GetHeightReal(pos.x, pos.z, synced)));
const float* orgHeightMap = readMap->GetOriginalHeightMapSynced();
const float* curHeightMap = readMap->GetCornerHeightMapSynced();