forked from spring/spring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHoverAirMoveType.cpp
More file actions
1211 lines (943 loc) · 33.9 KB
/
HoverAirMoveType.cpp
File metadata and controls
1211 lines (943 loc) · 33.9 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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include "HoverAirMoveType.h"
#include "Game/Players/Player.h"
#include "Map/Ground.h"
#include "Map/MapInfo.h"
#include "Sim/Misc/GeometricObjects.h"
#include "Sim/Misc/GlobalSynced.h"
#include "Sim/Misc/GroundBlockingObjectMap.h"
#include "Sim/Misc/QuadField.h"
#include "Sim/Misc/ModInfo.h"
#include "Sim/Units/Scripts/UnitScript.h"
#include "Sim/Units/Unit.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Units/CommandAI/CommandAI.h"
#include "System/SpringMath.h"
#include "System/Matrix44f.h"
#include "System/Sync/HsiehHash.h"
CR_BIND_DERIVED(CHoverAirMoveType, AAirMoveType, (nullptr))
CR_REG_METADATA(CHoverAirMoveType, (
CR_MEMBER(flyState),
CR_MEMBER(bankingAllowed),
CR_MEMBER(airStrafe),
CR_MEMBER(wantToStop),
CR_MEMBER(goalDistance),
CR_MEMBER(currentBank),
CR_MEMBER(currentPitch),
CR_MEMBER(turnRate),
CR_MEMBER(maxDrift),
CR_MEMBER(maxTurnAngle),
CR_MEMBER(wantedSpeed),
CR_MEMBER(deltaSpeed),
CR_MEMBER(circlingPos),
CR_MEMBER(randomWind),
CR_MEMBER(forceHeading),
CR_MEMBER(wantedHeading),
CR_MEMBER(forcedHeading),
CR_MEMBER(waitCounter),
CR_MEMBER(lastMoveRate)
))
#define MEMBER_CHARPTR_HASH(memberName) HsiehHash(memberName, strlen(memberName), 0)
#define MEMBER_LITERAL_HASH(memberName) HsiehHash(memberName, sizeof(memberName) - 1, 0)
static const unsigned int BOOL_MEMBER_HASHES[] = {
MEMBER_LITERAL_HASH( "collide"),
MEMBER_LITERAL_HASH( "dontLand"),
MEMBER_LITERAL_HASH( "airStrafe"),
MEMBER_LITERAL_HASH( "useSmoothMesh"),
MEMBER_LITERAL_HASH("bankingAllowed"),
};
static const unsigned int FLOAT_MEMBER_HASHES[] = {
MEMBER_LITERAL_HASH( "wantedHeight"),
MEMBER_LITERAL_HASH( "accRate"),
MEMBER_LITERAL_HASH( "decRate"),
MEMBER_LITERAL_HASH( "turnRate"),
MEMBER_LITERAL_HASH( "altitudeRate"),
MEMBER_LITERAL_HASH( "currentBank"),
MEMBER_LITERAL_HASH( "currentPitch"),
MEMBER_LITERAL_HASH( "maxDrift"),
};
#undef MEMBER_CHARPTR_HASH
#undef MEMBER_LITERAL_HASH
static bool UnitIsBusy(const CCommandAI* cai) {
// queued move-commands (or active build/repair/etc-commands) mean unit has to stay airborne
return (cai->inCommand || cai->HasMoreMoveCommands(false));
}
static bool UnitHasLoadCmd(const CCommandAI* cai) {
const auto& que = cai->commandQue;
const auto& cmd = (que.empty())? Command(CMD_STOP): que.front();
// NOTE:
// CMD_LOAD_ONTO is not tested here, HAMT is rarely a transport*ee*
// and only transport*er*s can be given the CMD_LOAD_UNITS command
return (cmd.GetID() == CMD_LOAD_UNITS);
}
static bool UnitIsBusy(const CUnit* u) { return (UnitIsBusy(u->commandAI)); }
static bool UnitHasLoadCmd(const CUnit* u) { return (UnitHasLoadCmd(u->commandAI)); }
extern AAirMoveType::GetGroundHeightFunc amtGetGroundHeightFuncs[6];
extern AAirMoveType::EmitCrashTrailFunc amtEmitCrashTrailFuncs[2];
CHoverAirMoveType::CHoverAirMoveType(CUnit* owner) :
AAirMoveType(owner),
flyState(FLY_CRUISING),
bankingAllowed(true),
airStrafe(owner != nullptr ? owner->unitDef->airStrafe : false),
wantToStop(false),
goalDistance(1.0f),
// we want to take off in direction of factory facing
currentBank(0.0f),
currentPitch(0.0f),
turnRate(1.0f),
maxDrift(1.0f),
maxTurnAngle(math::cos((owner != nullptr ? owner->unitDef->turnInPlaceAngleLimit : 0.0f) * math::DEG_TO_RAD) * -1.0f),
wantedSpeed(ZeroVector),
deltaSpeed(ZeroVector),
circlingPos(ZeroVector),
randomWind(ZeroVector),
forceHeading(false),
wantedHeading(owner != nullptr ? GetHeadingFromFacing(owner->buildFacing) : 0),
forcedHeading(wantedHeading),
waitCounter(0),
lastMoveRate(0)
{
// creg
if (owner == nullptr)
return;
assert(owner->unitDef != nullptr);
turnRate = owner->unitDef->turnRate;
wantedHeight = owner->unitDef->wantedHeight + gsRNG.NextFloat() * 5.0f;
orgWantedHeight = wantedHeight;
bankingAllowed = owner->unitDef->bankingAllowed;
// prevent weapons from being updated and firing while on the ground
owner->dontUseWeapons = true;
}
void CHoverAirMoveType::SetGoal(const float3& pos, float distance)
{
goalPos = pos;
oldGoalPos = pos;
// aircraft need some marginals to avoid uber stacking
// when lots of them are ordered to one place
maxDrift = std::max(16.0f, distance);
wantedHeight = orgWantedHeight;
forceHeading = false;
}
void CHoverAirMoveType::SetState(AircraftState newState)
{
// once in crashing, we should never change back into another state
if (aircraftState == AIRCRAFT_CRASHING && newState != AIRCRAFT_CRASHING)
return;
if (newState == aircraftState)
return;
owner->dontUseWeapons = (newState == AIRCRAFT_LANDED);
owner->useAirLos = (newState != AIRCRAFT_LANDED);
aircraftState = newState;
switch (aircraftState) {
case AIRCRAFT_CRASHING:
owner->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_CRASHING);
break;
#if 0
case AIRCRAFT_FLYING:
owner->Activate();
break;
case AIRCRAFT_LANDING:
owner->Deactivate();
break;
#endif
case AIRCRAFT_LANDED:
// FIXME already inform commandAI in AIRCRAFT_LANDING!
owner->commandAI->StopMove();
owner->Deactivate();
owner->Block();
owner->ClearPhysicalStateBit(CSolidObject::PSTATE_BIT_FLYING);
break;
case AIRCRAFT_TAKEOFF:
owner->Activate();
owner->UnBlock();
owner->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_FLYING);
break;
case AIRCRAFT_HOVERING: {
// when heading is forced by TCAI we are busy (un-)loading
// a unit and do not want wantedHeight to be tampered with
wantedHeight = mix(orgWantedHeight, wantedHeight, forceHeading);
wantedSpeed = ZeroVector;
} // fall through
default:
ClearLandingPos();
break;
}
// Cruise as default
// FIXME: RHS overrides FLY_ATTACKING and FLY_CIRCLING (via UpdateFlying-->ExecuteStop)
if (aircraftState == AIRCRAFT_FLYING || aircraftState == AIRCRAFT_HOVERING)
flyState = FLY_CRUISING;
owner->UpdatePhysicalStateBit(CSolidObject::PSTATE_BIT_MOVING, (aircraftState != AIRCRAFT_LANDED));
waitCounter = 0;
}
void CHoverAirMoveType::SetAllowLanding(bool allowLanding)
{
dontLand = !allowLanding;
if (CanLand(false))
return;
if (aircraftState != AIRCRAFT_LANDED && aircraftState != AIRCRAFT_LANDING)
return;
// do not start hovering if still (un)loading a unit
if (forceHeading)
return;
SetState(AIRCRAFT_HOVERING);
}
void CHoverAirMoveType::StartMoving(float3 pos, float goalRadius)
{
forceHeading = false;
wantToStop = false;
waitCounter = 0;
owner->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_MOVING);
switch (aircraftState) {
case AIRCRAFT_LANDED:
SetState(AIRCRAFT_TAKEOFF);
break;
case AIRCRAFT_TAKEOFF:
SetState(AIRCRAFT_TAKEOFF);
break;
case AIRCRAFT_FLYING:
flyState = FLY_CRUISING;
break;
case AIRCRAFT_LANDING:
SetState(AIRCRAFT_TAKEOFF);
break;
case AIRCRAFT_HOVERING:
SetState(AIRCRAFT_FLYING);
break;
case AIRCRAFT_CRASHING:
break;
}
SetGoal(pos, goalRadius);
progressState = AMoveType::Active;
}
void CHoverAirMoveType::StartMoving(float3 pos, float goalRadius, float speed)
{
StartMoving(pos, goalRadius);
}
void CHoverAirMoveType::KeepPointingTo(float3 pos, float distance, bool aggressive)
{
wantToStop = false;
forceHeading = false;
wantedHeight = orgWantedHeight;
// close in a little to avoid the command AI overriding pos constantly
distance -= 15.0f;
// Ignore the exact same order
if ((aircraftState == AIRCRAFT_FLYING) && (flyState == FLY_CIRCLING || flyState == FLY_ATTACKING) && ((circlingPos - pos).SqLength2D() < 64) && (goalDistance == distance))
return;
circlingPos = pos;
goalDistance = distance;
goalPos = owner->pos;
// let this handle any needed state transitions
StartMoving(goalPos, goalDistance);
// FIXME:
// the FLY_ATTACKING state is broken (unknown how long this has been
// the case because <aggressive> was always false up until e7ae68df)
// aircraft fly *right up* to their target without stopping
// after fixing this, the "circling" behavior is now broken
// (waitCounter is always 0)
if (aggressive) {
flyState = FLY_ATTACKING;
} else {
flyState = FLY_CIRCLING;
}
}
void CHoverAirMoveType::ExecuteStop()
{
wantToStop = false;
wantedSpeed = ZeroVector;
SetGoal(owner->pos);
ClearLandingPos();
switch (aircraftState) {
case AIRCRAFT_TAKEOFF: {
if (CanLand(UnitIsBusy(owner))) {
SetState(AIRCRAFT_LANDING);
// trick to land directly
waitCounter = GAME_SPEED;
break;
}
} // fall through
case AIRCRAFT_FLYING: {
if (CanLand(UnitIsBusy(owner))) {
SetState(AIRCRAFT_LANDING);
} else {
SetState(AIRCRAFT_HOVERING);
}
} break;
case AIRCRAFT_LANDING: {
if (!CanLand(UnitIsBusy(owner)))
SetState(AIRCRAFT_HOVERING);
} break;
case AIRCRAFT_LANDED: {} break;
case AIRCRAFT_CRASHING: {} break;
case AIRCRAFT_HOVERING: {
if (CanLand(UnitIsBusy(owner))) {
// land immediately, otherwise keep hovering
SetState(AIRCRAFT_LANDING);
waitCounter = GAME_SPEED;
}
} break;
}
}
void CHoverAirMoveType::StopMoving(bool callScript, bool hardStop, bool)
{
// transports switch to landed state (via SetState which calls
// us) during pickup but must *not* be allowed to change their
// heading while "landed" (see MobileCAI)
forceHeading &= (aircraftState == AIRCRAFT_LANDED);
wantToStop = true;
wantedHeight = orgWantedHeight;
owner->ClearPhysicalStateBit(CSolidObject::PSTATE_BIT_MOVING);
if (progressState != AMoveType::Failed)
progressState = AMoveType::Done;
}
void CHoverAirMoveType::UpdateLanded()
{
AAirMoveType::UpdateLanded();
if (progressState != AMoveType::Failed)
progressState = AMoveType::Done;
}
void CHoverAirMoveType::UpdateTakeoff()
{
const float3& pos = owner->pos;
wantedSpeed = ZeroVector;
wantedHeight = orgWantedHeight;
UpdateAirPhysics();
const float curAltitude = pos.y - amtGetGroundHeightFuncs[canSubmerge](pos.x, pos.z);
const float minAltitude = orgWantedHeight * 0.8f;
if (curAltitude <= minAltitude)
return;
SetState(AIRCRAFT_FLYING);
}
// Move the unit around a bit..
void CHoverAirMoveType::UpdateHovering()
{
#if 0
#define NOZERO(x) std::max(x, 0.0001f)
float3 deltaVec = goalPos - owner->pos;
float3 deltaDir = float3(deltaVec.x, 0.0f, deltaVec.z);
const float driftSpeed = math::fabs(owner->unitDef->dlHoverFactor);
const float goalDistance = NOZERO(deltaDir.Length2D());
const float brakeDistance = 0.5f * owner->speed.SqLength2D() / decRate;
// move towards goal position if it's not immediately
// behind us when we have more waypoints to get to
// *** this behavior interferes with the loading procedure of transports ***
const bool b0 = (aircraftState != AIRCRAFT_LANDING && owner->commandAI->HasMoreMoveCommands());
const bool b1 = (goalDistance < brakeDistance && goalDistance > 1.0f);
if (b0 && b1 && !owner->unitDef->IsTransportUnit()) {
deltaDir = owner->frontdir;
} else {
deltaDir *= smoothstep(0.0f, 20.0f, goalDistance) / goalDistance;
deltaDir -= owner->speed;
}
if (deltaDir.SqLength2D() > (maxSpeed * maxSpeed))
deltaDir *= (maxSpeed / NOZERO(math::sqrt(deltaDir.SqLength2D())));
// random movement (a sort of fake wind effect)
// random drift values are in range -0.5 ... 0.5
randomWind.x = randomWind.x * 0.9f + (gsRNG.NextFloat() - 0.5f) * 0.5f;
randomWind.z = randomWind.z * 0.9f + (gsRNG.NextFloat() - 0.5f) * 0.5f;
wantedSpeed = owner->speed + deltaDir;
wantedSpeed += (randomWind * driftSpeed * 0.5f);
UpdateAirPhysics();
#endif
#if 1
randomWind.x = randomWind.x * 0.9f + (gsRNG.NextFloat() - 0.5f) * 0.5f;
randomWind.z = randomWind.z * 0.9f + (gsRNG.NextFloat() - 0.5f) * 0.5f;
// randomly drift (but not too far from goal-position; a larger
// deviation causes a larger wantedSpeed back in its direction)
// when not picking up a transportee
wantedSpeed = (randomWind * math::fabs(owner->unitDef->dlHoverFactor) * 0.5f * (1 - UnitHasLoadCmd(owner)));
wantedSpeed += (smoothstep(0.0f, 20.0f * 20.0f, float3::fabs(goalPos - owner->pos)) * (goalPos - owner->pos));
UpdateAirPhysics();
#endif
}
void CHoverAirMoveType::UpdateFlying()
{
const float3& pos = owner->pos;
// const float4& spd = owner->speed;
// Direction to where we would like to be
float3 goalVec = goalPos - pos;
float3 goalDir = goalVec;
// don't change direction for waypoints we just flew over and missed slightly
if (flyState != FLY_LANDING && owner->commandAI->HasMoreMoveCommands()) {
if ((goalDir != ZeroVector) && (goalVec.dot(goalDir.UnsafeANormalize()) < 1.0f))
goalVec = owner->frontdir;
}
const float goalDistSq2D = goalVec.SqLength2D();
const float groundHeight = amtGetGroundHeightFuncs[4 * UseSmoothMesh()](pos.x, pos.z);
const bool closeToGoal = (flyState == FLY_ATTACKING)?
(goalDistSq2D < ( 400.0f)):
(goalDistSq2D < (maxDrift * maxDrift)) && (math::fabs(groundHeight + wantedHeight - pos.y) < maxDrift);
if (closeToGoal) {
switch (flyState) {
case FLY_CRUISING: {
const bool isTransporter = owner->unitDef->IsTransportUnit();
const bool hasLoadCmds = isTransporter && UnitHasLoadCmd(owner);
// [?] transport aircraft need some time to detect that they can pickup
const bool canLoad = isTransporter && (++waitCounter < ((GAME_SPEED << 1) - 5));
const bool isBusy = UnitIsBusy(owner);
if (!CanLand(isBusy) || (canLoad && hasLoadCmds)) {
wantedSpeed = ZeroVector;
if (isTransporter) {
if (waitCounter > (GAME_SPEED << 1))
wantedHeight = orgWantedHeight;
SetState(AIRCRAFT_HOVERING);
} else {
if (!isBusy) {
wantToStop = true;
// NOTE:
// this is not useful, next frame UpdateFlying()
// will change it to _LANDING because wantToStop
// is now true
SetState(AIRCRAFT_HOVERING);
}
}
} else {
wantedHeight = orgWantedHeight;
SetState(AIRCRAFT_LANDING);
}
} break;
case FLY_CIRCLING: {
if ((++waitCounter) > ((GAME_SPEED * 3) + 10)) {
if (airStrafe) {
float3 relPos = pos - circlingPos;
if (relPos.x < 0.0001f && relPos.x > -0.0001f)
relPos.x = 0.0001f;
static const CMatrix44f rotCCW(0.0f, math::QUARTERPI, 0.0f);
static const CMatrix44f rotCW(0.0f, -math::QUARTERPI, 0.0f);
// make sure the point is on the circle, go there in a straight line
if (gsRNG.NextFloat() > 0.5f) {
goalPos = circlingPos + (rotCCW.Mul(relPos.Normalize2D()) * goalDistance);
} else {
goalPos = circlingPos + (rotCW.Mul(relPos.Normalize2D()) * goalDistance);
}
}
waitCounter = 0;
}
} break;
case FLY_ATTACKING: {
if (airStrafe) {
float3 relPos = pos - circlingPos;
if (relPos.x < 0.0001f && relPos.x > -0.0001f)
relPos.x = 0.0001f;
const float rotY = 0.6f + gsRNG.NextFloat() * 0.6f;
const float sign = (gsRNG.NextFloat() > 0.5f) ? 1.0f : -1.0f;
const CMatrix44f rot(0.0f, rotY * sign, 0.0f);
// Go there in a straight line
goalPos = circlingPos + (rot.Mul(relPos.Normalize2D()) * goalDistance);
}
} break;
case FLY_LANDING: {
} break;
}
}
// not "close" to goal yet, so keep going
// use 2D math since goal is on the ground
// but we are not
goalVec.y = 0.0f;
// if we are close to our goal, we should
// adjust speed st. we never overshoot it
// (by respecting current brake-distance)
const float curSpeed = owner->speed.Length2D();
const float brakeDist = (0.5f * curSpeed * curSpeed) / decRate;
const float goalDist = goalVec.Length() + 0.1f;
const float goalSpeed =
(maxSpeed ) * (goalDist > brakeDist) +
(curSpeed - decRate) * (goalDist <= brakeDist);
if (goalDist > goalSpeed) {
// update our velocity and heading so long as goal is still
// further away than the distance we can cover in one frame
// we must use a variable-size "dead zone" to avoid freezing
// in mid-air or oscillation behavior at very close distances
// NOTE:
// wantedSpeed is a vector, so even aircraft with turnRate=0
// are coincidentally able to reach any goal by side-strafing
wantedHeading = GetHeadingFromVector(goalVec.x, goalVec.z);
wantedSpeed = (goalVec / goalDist) * std::min(goalSpeed, maxWantedSpeed);
} else {
// switch to hovering (if !CanLand()))
if (!UnitIsBusy(owner)) {
ExecuteStop();
} else {
wantedSpeed = ZeroVector;
}
}
// redundant, done in Update()
// UpdateHeading();
UpdateAirPhysics();
// Point toward goal or forward - unless we just passed it to get to another goal
if ((flyState == FLY_ATTACKING) || (flyState == FLY_CIRCLING)) {
goalVec = circlingPos - pos;
} else {
const bool b0 = (flyState != FLY_LANDING && (owner->commandAI->HasMoreMoveCommands()));
const bool b1 = (goalDist < brakeDist && goalDist > 1.0f);
if (b0 && b1) {
goalVec = owner->frontdir;
} else {
goalVec = goalPos - pos;
}
}
if (goalVec.SqLength2D() > 1.0f) {
// update heading again in case goalVec changed
wantedHeading = GetHeadingFromVector(goalVec.x, goalVec.z);
}
}
void CHoverAirMoveType::UpdateLanding()
{
const float3 pos = owner->pos;
if (!HaveLandingPos()) {
if (CanLandAt(pos)) {
// found a landing spot
reservedLandingPos = pos;
goalPos = pos;
UpdateLandingHeight(0.0f);
owner->Move(reservedLandingPos, false);
owner->Block();
owner->Move(pos, false);
owner->script->StopMoving();
} else {
if (goalPos.SqDistance2D(pos) < (30.0f * 30.0f)) {
// randomly pick another landing spot and try again
goalPos += (gsRNG.NextVector() * 300.0f);
goalPos.ClampInBounds();
// exact landing pos failed, make sure finishcommand is called anyway
progressState = AMoveType::Failed;
}
flyState = FLY_LANDING;
UpdateFlying();
return;
}
}
flyState = FLY_LANDING;
const float altitude = pos.y - reservedLandingPos.y;
const float distSq2D = reservedLandingPos.SqDistance2D(pos);
if (distSq2D > landRadiusSq) {
const float tmpWantedHeight = wantedHeight;
SetGoal(reservedLandingPos);
wantedHeight = std::min((orgWantedHeight - wantedHeight) * distSq2D / altitude + wantedHeight, orgWantedHeight);
UpdateFlying();
wantedHeight = tmpWantedHeight;
return;
}
// We want to land, and therefore cancel our speed first
wantedSpeed = ZeroVector;
AAirMoveType::UpdateLanding();
UpdateAirPhysics();
}
void CHoverAirMoveType::UpdateHeading()
{
if (aircraftState == AIRCRAFT_TAKEOFF && !owner->unitDef->factoryHeadingTakeoff)
return;
// UpdateDirVectors() resets our up-vector but we
// might have residual pitch angle from attacking
// if (aircraftState == AIRCRAFT_LANDING)
// return;
const short refHeading = mix(wantedHeading, forcedHeading, forceHeading);
const short deltaHeading = refHeading - owner->heading;
if (deltaHeading > 0) {
owner->AddHeading(std::min(deltaHeading, short(turnRate)), owner->IsOnGround(), false);
} else {
owner->AddHeading(std::max(deltaHeading, short(-turnRate)), owner->IsOnGround(), false);
}
}
void CHoverAirMoveType::UpdateBanking(bool noBanking)
{
// need to allow LANDING so (autoLand=true) aircraft reset their
// pitch naturally after attacking ground and being told to stop
if (aircraftState != AIRCRAFT_FLYING && aircraftState != AIRCRAFT_HOVERING && aircraftState != AIRCRAFT_LANDING)
return;
// always positive
const float bankLimit = std::min(1.0f, goalPos.SqDistance2D(owner->pos) * Square(0.15f));
float wantedBank = 0.0f;
float wantedPitch = 0.0f;
SyncedFloat3& frontDir = owner->frontdir;
SyncedFloat3& upDir = owner->updir;
SyncedFloat3& rightDir3D = owner->rightdir;
SyncedFloat3 rightDir2D;
// pitching does not affect rightdir, but we want a flat right-vector to calculate wantedBank
frontDir.y = currentPitch;
frontDir.Normalize();
rightDir2D = frontDir.cross(UpVector);
if (!owner->upright)
wantedPitch = (circlingPos.y - owner->pos.y) / circlingPos.distance(owner->pos);
wantedPitch *= (aircraftState == AIRCRAFT_FLYING && flyState == FLY_ATTACKING && circlingPos.y != owner->pos.y);
currentPitch = mix(currentPitch, wantedPitch, 0.05f);
if (!noBanking && bankingAllowed)
wantedBank = rightDir2D.dot(deltaSpeed) / accRate * 0.5f;
if (Square(wantedBank) > bankLimit)
wantedBank = math::sqrt(bankLimit);
// Adjust our banking to the desired value
if (currentBank > wantedBank) {
currentBank -= std::min(0.03f, currentBank - wantedBank);
} else {
currentBank += std::min(0.03f, wantedBank - currentBank);
}
upDir = rightDir2D.cross(frontDir);
upDir = upDir * math::cos(currentBank) + rightDir2D * math::sin(currentBank);
upDir = upDir.Normalize();
rightDir3D = frontDir.cross(upDir);
// NOTE:
// heading might not be fully in sync with frontDir due to the
// vector<-->heading mapping not being 1:1 (such that heading
// != GetHeadingFromVector(frontDir)), therefore this call can
// cause owner->heading to change --> unwanted if forceHeading
//
// it is "safe" to skip because only frontDir.y is manipulated
// above so its xz-direction does not change, but the problem
// should really be fixed elsewhere
if (!forceHeading)
owner->SetHeadingFromDirection();
owner->UpdateMidAndAimPos();
}
void CHoverAirMoveType::UpdateVerticalSpeed(const float4& spd, float curRelHeight, float curVertSpeed) const
{
float wh = wantedHeight; // wanted RELATIVE height (altitude)
float ws = 0.0f; // wanted vertical speed
// first restore original vertical speed
owner->SetVelocity((spd * XZVector) + (UpVector * curVertSpeed));
if (collisionState == COLLISION_DIRECT) {
const float3 dir = lastCollidee->midPos - owner->midPos;
const float3 sdir = lastCollidee->speed - spd;
if (spd.dot(dir + sdir * 20.0f) < 0.0f) {
wh -= (30.0f * (lastCollidee->midPos.y > owner->pos.y));
wh += (50.0f * (lastCollidee->midPos.y <= owner->pos.y));
}
}
if (curRelHeight < wh) {
ws = altitudeRate;
ws *= (1.0f - ((spd.y > 0.0001f) && (((wh - curRelHeight) / spd.y) * accRate * 1.5f) < spd.y));
} else {
ws = -altitudeRate;
ws *= (1.0f - ((spd.y < -0.0001f) && (((wh - curRelHeight) / spd.y) * accRate * 0.7f) < -spd.y));
}
ws *= (1 - owner->beingBuilt);
// note: don't want this in case unit is built on some raised platform?
wh *= (1 - owner->beingBuilt);
if (math::fabs(wh - curRelHeight) > 2.0f) {
if (spd.y > ws) {
owner->SetVelocity((spd * XZVector) + (UpVector * std::max(ws, spd.y - accRate * 1.5f)));
} else {
// accelerate upward faster if close to ground
owner->SetVelocity((spd * XZVector) + (UpVector * std::min(ws, spd.y + accRate * ((curRelHeight < 20.0f)? 2.0f: 0.7f))));
}
} else {
owner->SetVelocity((spd * XZVector) + (UpVector * spd.y * 0.95f));
}
// finally update w-component
owner->SetSpeed(spd);
}
void CHoverAirMoveType::UpdateAirPhysics()
{
const float3& pos = owner->pos;
const float4& spd = owner->speed;
// division by .w cancels out here
// const float3 brakePos = pos + (spd / spd.w) * BrakingDistance(spd.w, decRate) * 4.0f;
// const float3 brakePos = pos + (spd / spd.w) * ((0.5f * spd.w * spd.w) / decRate) * 4.0f;
const float3 brakePos = pos + spd * ((0.5f * spd.w) / decRate) * 4.0f;
// copy vertical speed
const float verticalSpeed = spd.y;
const float ownerMinHeight = owner->midPos.y - owner->radius;
// absolute ground heights at pos and brakePos
// if this aircraft uses the smoothmesh, these values are
// calculated with respect to that when changing vertical
// speed (but not for ground collision)
float cpGroundHeight = amtGetGroundHeightFuncs[canSubmerge]( pos.x, pos.z);
float bpGroundHeight = amtGetGroundHeightFuncs[canSubmerge](brakePos.x, brakePos.z);
if (((gs->frameNum + owner->id) & 3) == 0)
CheckForCollision();
// cancel out vertical speed, acc and dec are applied in xz-plane
owner->SetVelocity(spd * XZVector);
// always stay above the actual terrain (therefore either the value of
// <midPos.y - radius> or pos.y must never become smaller than the real
// ground height; prefer to use radius since this leaves more clearance
// between model and ground)
// note: unlike StrafeAirMoveType, UpdateTakeoff and UpdateLanding call
// UpdateAirPhysics() so we ignore terrain while we are in those states
if (modInfo.allowAircraftToHitGround) {
const bool cpGroundContact = (cpGroundHeight > ownerMinHeight);
const bool bpGroundContact = (bpGroundHeight > ownerMinHeight);
const bool handleContact = (aircraftState != AIRCRAFT_LANDED && aircraftState != AIRCRAFT_TAKEOFF);
// hard avoidance in case soft constraint fails
if (cpGroundContact && handleContact)
owner->Move(UpVector * (cpGroundHeight - ownerMinHeight + 0.01f), true);
// soft avoidance
if (bpGroundContact && handleContact)
wantedSpeed = UpVector * altitudeRate;
}
{
const float3 deltaSpeed = wantedSpeed - spd;
// apply {acc,dec}eleration as wanted
const float deltaSpeedSqr = deltaSpeed.SqLength();
const float deltaSpeedRate = mix(accRate, decRate, deltaSpeed.dot(spd) < 0.0f);
if (deltaSpeedSqr < Square(deltaSpeedRate)) {
owner->SetVelocity(wantedSpeed);
} else {
owner->SetVelocity(spd + (deltaSpeed / math::sqrt(deltaSpeedSqr) * deltaSpeedRate));
}
}
cpGroundHeight = amtGetGroundHeightFuncs[UseSmoothMesh() * 2 + canSubmerge]( pos.x, pos.z);
bpGroundHeight = amtGetGroundHeightFuncs[UseSmoothMesh() * 2 + canSubmerge](brakePos.x, brakePos.z);
// compute new vertical speed
// NOTE:
// if altitudeRate is too small then aircraft can disappear
// below cliffs (with terrain collision disabled) unless it
// stops moving forward, which needs to happen some time in
// advance to not break immersion
// since true terrain-following is expensive, instead sample
// the ground height N braking distances ahead and base next
// VS on that
UpdateVerticalSpeed(spd, pos.y - std::max(cpGroundHeight, bpGroundHeight), verticalSpeed);
if (modInfo.allowAircraftToLeaveMap || (pos + spd).IsInBounds())
owner->Move(spd, true);
}
void CHoverAirMoveType::UpdateMoveRate()
{
int curMoveRate = 1;
// currentspeed is not used correctly for vertical movement, so compensate with this hax
if (aircraftState != AIRCRAFT_LANDING && aircraftState != AIRCRAFT_TAKEOFF)
curMoveRate = CalcScriptMoveRate(owner->speed.w, 3.0f);
if (curMoveRate == lastMoveRate)
return;
owner->script->MoveRate(lastMoveRate = curMoveRate);
}
bool CHoverAirMoveType::Update()
{
const float3 lastPos = owner->pos;
const float4 lastSpd = owner->speed;
AAirMoveType::Update();
if ((owner->IsStunned() && !owner->IsCrashing()) || owner->beingBuilt) {
wantedSpeed = ZeroVector;
UpdateAirPhysics();
return (HandleCollisions(collide && !owner->beingBuilt && (aircraftState != AIRCRAFT_TAKEOFF)));
}
// allow us to stop if wanted (changes aircraft state)
if (wantToStop)
ExecuteStop();
if (aircraftState != AIRCRAFT_CRASHING) {
if (owner->UnderFirstPersonControl()) {
SetState(AIRCRAFT_FLYING);
const CPlayer* fpsPlayer = owner->fpsControlPlayer;
const FPSUnitController& fpsCon = fpsPlayer->fpsController;
const float3 forward = fpsCon.viewDir;
const float3 right = forward.cross(UpVector);
const float3 nextPos = lastPos + owner->speed;
float3 flatForward = forward;
flatForward.Normalize2D();
wantedSpeed = ZeroVector;
wantedSpeed += (flatForward * fpsCon.forward);
wantedSpeed -= (flatForward * fpsCon.back );
wantedSpeed += ( right * fpsCon.right );
wantedSpeed -= ( right * fpsCon.left );
wantedSpeed.Normalize();
wantedSpeed *= maxWantedSpeed;
if (!nextPos.IsInBounds())
owner->SetVelocityAndSpeed(ZeroVector);
UpdateAirPhysics();
wantedHeading = GetHeadingFromVector(flatForward.x, flatForward.z);
}
}
switch (aircraftState) {
case AIRCRAFT_LANDED:
UpdateLanded();
break;
case AIRCRAFT_TAKEOFF:
UpdateTakeoff();
break;
case AIRCRAFT_FLYING:
UpdateFlying();
break;
case AIRCRAFT_LANDING:
UpdateLanding();
break;
case AIRCRAFT_HOVERING:
UpdateHovering();
break;
case AIRCRAFT_CRASHING: {
UpdateAirPhysics();
if ((CGround::GetHeightAboveWater(owner->pos.x, owner->pos.z) + 5.0f + owner->radius) > owner->pos.y) {
owner->ForcedKillUnit(nullptr, true, false);
} else {
#define SPIN_DIR(o) ((o->id & 1) * 2 - 1)
wantedHeading = GetHeadingFromVector(owner->rightdir.x * SPIN_DIR(owner), owner->rightdir.z * SPIN_DIR(owner));
wantedHeight = 0.0f;
#undef SPIN_DIR
}
amtEmitCrashTrailFuncs[crashExpGenID != -1u](owner, crashExpGenID);
} break;
}
if (lastSpd == ZeroVector && owner->speed != ZeroVector) { owner->script->StartMoving(false); }
if (lastSpd != ZeroVector && owner->speed == ZeroVector) { owner->script->StopMoving(); }
// Banking requires deltaSpeed.y = 0
deltaSpeed = owner->speed - lastSpd;
deltaSpeed.y = 0.0f;
// Turn and bank and move; update dirs
UpdateHeading();
UpdateBanking(aircraftState == AIRCRAFT_HOVERING || aircraftState == AIRCRAFT_LANDING);
return (HandleCollisions(collide && !owner->beingBuilt && (aircraftState != AIRCRAFT_TAKEOFF)));
}
void CHoverAirMoveType::SlowUpdate()
{
UpdateMoveRate();
// note: NOT AAirMoveType::SlowUpdate