/
GroundMoveType.cpp
2531 lines (2020 loc) · 88.1 KB
/
GroundMoveType.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 "GroundMoveType.h"
#include "MoveDefHandler.h"
#include "ExternalAI/EngineOutHandler.h"
#include "Game/Camera.h"
#include "Game/GameHelper.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 "MoveMath/MoveMath.h"
#include "Sim/Features/Feature.h"
#include "Sim/Features/FeatureHandler.h"
#include "Sim/Misc/GeometricObjects.h"
#include "Sim/Misc/ModInfo.h"
#include "Sim/Misc/QuadField.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Path/IPathManager.h"
#include "Sim/Units/Scripts/CobInstance.h"
#include "Sim/Units/CommandAI/CommandAI.h"
#include "Sim/Units/CommandAI/MobileCAI.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Units/UnitHandler.h"
#include "Sim/Weapons/WeaponDefHandler.h"
#include "Sim/Weapons/Weapon.h"
#include "System/EventHandler.h"
#include "System/Log/ILog.h"
#include "System/FastMath.h"
#include "System/myMath.h"
#include "System/TimeProfiler.h"
#include "System/type2.h"
#include "System/Sound/ISoundChannels.h"
#include "System/Sync/HsiehHash.h"
#include "System/Sync/SyncTracer.h"
#if 1
#include "Rendering/IPathDrawer.h"
#define DEBUG_DRAWING_ENABLED ((gs->cheatEnabled || gu->spectatingFullView) && pathDrawer->IsEnabled())
#else
#define DEBUG_DRAWING_ENABLED false
#endif
#define LOG_SECTION_GMT "GroundMoveType"
LOG_REGISTER_SECTION_GLOBAL(LOG_SECTION_GMT)
// use the specific section for all LOG*() calls in this source file
#ifdef LOG_SECTION_CURRENT
#undef LOG_SECTION_CURRENT
#endif
#define LOG_SECTION_CURRENT LOG_SECTION_GMT
// speeds near (MAX_UNIT_SPEED * 1e1) elmos / frame can be caused by explosion impulses
// CUnitHandler removes units with speeds > MAX_UNIT_SPEED as soon as they exit the map,
// so the assertion can be less strict
#define ASSERT_SANE_OWNER_SPEED(v) assert(v.SqLength() < (MAX_UNIT_SPEED * MAX_UNIT_SPEED * 1e2));
// magic number to reduce damage taken from collisions
// between a very heavy and a very light CSolidObject
#define COLLISION_DAMAGE_MULT 0.02f
#define MAX_IDLING_SLOWUPDATES 16
#define IGNORE_OBSTACLES 0
#define WAIT_FOR_PATH 1
#define UNIT_CMD_QUE_SIZE(u) (u->commandAI->commandQue.size())
// Not using IsMoveCommand on purpose, as the following is changing the effective goalRadius
#define UNIT_HAS_MOVE_CMD(u) (u->commandAI->commandQue.empty() || u->commandAI->commandQue[0].GetID() == CMD_MOVE || u->commandAI->commandQue[0].GetID() == CMD_FIGHT)
#define FOOTPRINT_RADIUS(xs, zs, s) ((math::sqrt((xs * xs + zs * zs)) * 0.5f * SQUARE_SIZE) * s)
#define MAXREVERSESPEED_MEMBER_IDX 7
#define MEMBER_CHARPTR_HASH(memberName) HsiehHash(memberName, strlen(memberName), 0)
#define MEMBER_LITERAL_HASH(memberName) HsiehHash(memberName, sizeof(memberName) - 1, 0)
CR_BIND_DERIVED(CGroundMoveType, AMoveType, (nullptr))
CR_REG_METADATA(CGroundMoveType, (
CR_IGNORED(pathController),
CR_MEMBER(currWayPoint),
CR_MEMBER(nextWayPoint),
CR_MEMBER(waypointDir),
CR_MEMBER(flatFrontDir),
CR_MEMBER(lastAvoidanceDir),
CR_MEMBER(mainHeadingPos),
CR_MEMBER(skidRotVector),
CR_MEMBER(turnRate),
CR_MEMBER(turnSpeed),
CR_MEMBER(turnAccel),
CR_MEMBER(accRate),
CR_MEMBER(decRate),
CR_MEMBER(myGravity),
CR_MEMBER(maxReverseDist),
CR_MEMBER(minReverseAngle),
CR_MEMBER(maxReverseSpeed),
CR_MEMBER(sqSkidSpeedMult),
CR_MEMBER(wantedSpeed),
CR_MEMBER(currentSpeed),
CR_MEMBER(deltaSpeed),
CR_MEMBER(atGoal),
CR_MEMBER(atEndOfPath),
CR_MEMBER(wantRepath),
CR_MEMBER(currWayPointDist),
CR_MEMBER(prevWayPointDist),
CR_MEMBER(goalRadius),
CR_MEMBER(numIdlingUpdates),
CR_MEMBER(numIdlingSlowUpdates),
CR_MEMBER(wantedHeading),
CR_MEMBER(minScriptChangeHeading),
CR_MEMBER(pathID),
CR_MEMBER(nextObstacleAvoidanceFrame),
CR_MEMBER(reversing),
CR_MEMBER(idling),
CR_MEMBER(canReverse),
CR_MEMBER(useMainHeading),
CR_MEMBER(useRawMovement),
CR_MEMBER(skidRotSpeed),
CR_MEMBER(skidRotAccel),
CR_POSTLOAD(PostLoad)
))
static CGroundMoveType::MemberData gmtMemberData = {
{
std::pair<unsigned int, bool*>{MEMBER_LITERAL_HASH( "atGoal"), nullptr},
std::pair<unsigned int, bool*>{MEMBER_LITERAL_HASH( "atEndOfPath"), nullptr},
},
{
std::pair<unsigned int, short*>{MEMBER_LITERAL_HASH("minScriptChangeHeading"), nullptr},
},
{
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH( "turnRate"), nullptr},
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH( "turnAccel"), nullptr},
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH( "accRate"), nullptr},
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH( "decRate"), nullptr},
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH( "myGravity"), nullptr},
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH( "maxReverseDist"), nullptr},
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH("minReverseAngle"), nullptr},
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH("maxReverseSpeed"), nullptr},
std::pair<unsigned int, float*>{MEMBER_LITERAL_HASH("sqSkidSpeedMult"), nullptr},
},
};
CGroundMoveType::CGroundMoveType(CUnit* owner):
AMoveType(owner),
pathController(owner),
currWayPoint(ZeroVector),
nextWayPoint(ZeroVector),
flatFrontDir(FwdVector),
lastAvoidanceDir(ZeroVector),
mainHeadingPos(ZeroVector),
skidRotVector(UpVector),
turnRate(0.1f),
turnSpeed(0.0f),
turnAccel(0.0f),
accRate(0.01f),
decRate(0.01f),
myGravity(0.0f),
maxReverseDist(0.0f),
minReverseAngle(0.0f),
maxReverseSpeed(0.0f),
sqSkidSpeedMult(0.95f),
wantedSpeed(0.0f),
currentSpeed(0.0f),
deltaSpeed(0.0f),
atGoal(false),
atEndOfPath(false),
wantRepath(false),
currWayPointDist(0.0f),
prevWayPointDist(0.0f),
goalRadius(0.0f),
reversing(false),
idling(false),
canReverse((owner != nullptr) && (owner->unitDef->rSpeed > 0.0f)),
useMainHeading(false),
useRawMovement(false),
skidRotSpeed(0.0f),
skidRotAccel(0.0f),
pathID(0),
nextObstacleAvoidanceFrame(0),
numIdlingUpdates(0),
numIdlingSlowUpdates(0),
wantedHeading(0),
minScriptChangeHeading(SPRING_CIRCLE_DIVS >> 1)
{
// creg
if (owner == nullptr)
return;
assert(owner->unitDef != nullptr);
assert(owner->moveDef != nullptr);
// maxSpeed is set in AMoveType's ctor
maxReverseSpeed = owner->unitDef->rSpeed / GAME_SPEED;
turnRate = std::max(owner->unitDef->turnRate, 1.0f);
turnAccel = turnRate * mix(0.333f, 0.033f, owner->moveDef->speedModClass == MoveDef::Ship);
accRate = std::max(0.01f, owner->unitDef->maxAcc);
decRate = std::max(0.01f, owner->unitDef->maxDec);
// unit-gravity must always be negative
myGravity = mix(-math::fabs(owner->unitDef->myGravity), mapInfo->map.gravity, owner->unitDef->myGravity == 0.0f);
}
CGroundMoveType::~CGroundMoveType()
{
if (pathID == 0)
return;
pathManager->DeletePath(pathID);
}
void CGroundMoveType::PostLoad()
{
pathController = GMTDefaultPathController(owner);
// HACK: re-initialize path after load
if (pathID == 0)
return;
pathID = pathManager->RequestPath(owner, owner->moveDef, owner->pos, goalPos, goalRadius, true);
}
bool CGroundMoveType::OwnerMoved(const short oldHeading, const float3& posDif, const float3& cmpEps) {
if (posDif.equals(ZeroVector, cmpEps)) {
// note: the float3::== test is not exact, so even if this
// evaluates to true the unit might still have an epsilon
// speed vector --> nullify it to prevent apparent visual
// micro-stuttering (speed is used to extrapolate drawPos)
owner->SetVelocityAndSpeed(ZeroVector);
// negative y-coordinates indicate temporary waypoints that
// only exist while we are still waiting for the pathfinder
// (so we want to avoid being considered "idle", since that
// will cause our path to be re-requested and again give us
// a temporary waypoint, etc.)
// NOTE: this is only relevant for QTPFS (at present)
// if the unit is just turning in-place over several frames
// (eg. to maneuver around an obstacle), do not consider it
// as "idling"
idling = true;
idling &= (currWayPoint.y != -1.0f && nextWayPoint.y != -1.0f);
idling &= (std::abs(owner->heading - oldHeading) < turnRate);
return false;
}
// note: HandleObjectCollisions() may have negated the position set
// by UpdateOwnerPos() (so that owner->pos is again equal to oldPos)
// note: the idling-check can only succeed if we are oriented in the
// direction of our waypoint, which compensates for the fact distance
// decreases much less quickly when moving orthogonal to <waypointDir>
oldPos = owner->pos;
const float3 ffd = flatFrontDir * posDif.SqLength() * 0.5f;
const float3 wpd = waypointDir * ((int(!reversing) * 2) - 1);
// too many false negatives: speed is unreliable if stuck behind an obstacle
// idling = (Square(owner->speed.w) < (accRate * accRate));
// idling &= (Square(currWayPointDist - prevWayPointDist) <= (accRate * accRate));
// too many false positives: waypoint-distance delta and speed vary too much
// idling = (Square(currWayPointDist - prevWayPointDist) < Square(owner->speed.w));
// too many false positives: many slow units cannot even manage 1 elmo/frame
// idling = (Square(currWayPointDist - prevWayPointDist) < 1.0f);
idling = true;
idling &= (math::fabs(posDif.y) < math::fabs(cmpEps.y * owner->pos.y));
idling &= (Square(currWayPointDist - prevWayPointDist) < ffd.dot(wpd));
return true;
}
bool CGroundMoveType::Update()
{
ASSERT_SYNCED(owner->pos);
// do nothing at all if we are inside a transport
if (owner->GetTransporter() != nullptr)
return false;
owner->UpdatePhysicalStateBit(CSolidObject::PSTATE_BIT_SKIDDING, owner->IsSkidding() || OnSlope(1.0f));
if (owner->IsSkidding()) {
UpdateSkid();
return false;
}
ASSERT_SYNCED(owner->pos);
// set drop height when we start to drop
if (owner->IsFalling()) {
UpdateControlledDrop();
return false;
}
ASSERT_SYNCED(owner->pos);
const short heading = owner->heading;
// these must be executed even when stunned (so
// units do not get buried by restoring terrain)
UpdateOwnerSpeedAndHeading();
UpdateOwnerPos(owner->speed, GetNewSpeedVector(deltaSpeed, myGravity));
HandleObjectCollisions();
AdjustPosToWaterLine();
ASSERT_SANE_OWNER_SPEED(owner->speed);
// <dif> is normally equal to owner->speed (if no collisions)
// we need more precision (less tolerance) in the y-dimension
// for all-terrain units that are slowed down a lot on cliffs
return (OwnerMoved(heading, owner->pos - oldPos, float3(float3::cmp_eps(), float3::cmp_eps() * 1e-2f, float3::cmp_eps())));
}
void CGroundMoveType::UpdateOwnerSpeedAndHeading()
{
if (owner->IsStunned() || owner->beingBuilt) {
ChangeSpeed(0.0f, false);
return;
}
// either follow user control input or pathfinder
// waypoints; change speed and heading as required
if (owner->UnderFirstPersonControl()) {
UpdateDirectControl();
} else {
FollowPath();
}
}
void CGroundMoveType::SlowUpdate()
{
if (owner->GetTransporter() != NULL) {
if (progressState == Active) {
StopEngine(false);
}
} else {
if (progressState == Active) {
if (pathID != 0) {
if (idling) {
numIdlingSlowUpdates = std::min(MAX_IDLING_SLOWUPDATES, int(numIdlingSlowUpdates + 1));
} else {
numIdlingSlowUpdates = std::max(0, int(numIdlingSlowUpdates - 1));
}
if (numIdlingUpdates > (SHORTINT_MAXVALUE / turnRate)) {
// case A: we have a path but are not moving
LOG_L(L_DEBUG, "SlowUpdate: unit %i has pathID %i but %i ETA failures", owner->id, pathID, numIdlingUpdates);
if (numIdlingSlowUpdates < MAX_IDLING_SLOWUPDATES) {
ReRequestPath(true);
} else {
// unit probably ended up on a non-traversable
// square, or got stuck in a non-moving crowd
Fail(false);
}
}
} else {
// case B: we want to be moving but don't have a path
LOG_L(L_DEBUG, "SlowUpdate: unit %i has no path", owner->id);
ReRequestPath(true);
}
if (wantRepath) {
ReRequestPath(true);
}
}
if (!owner->IsFlying()) {
// move us into the map, and update <oldPos>
// to prevent any extreme changes in <speed>
if (!owner->pos.IsInBounds()) {
owner->Move(oldPos = owner->pos.cClampInBounds(), false);
}
}
}
AMoveType::SlowUpdate();
}
void CGroundMoveType::StartMovingRaw(const float3 moveGoalPos, float moveGoalRadius) {
goalPos = moveGoalPos * XZVector;
goalRadius = moveGoalRadius;
currWayPoint = goalPos;
nextWayPoint = goalPos;
atGoal = moveGoalPos.SqDistance2D(owner->pos) < Square(moveGoalRadius);
atEndOfPath = false;
useMainHeading = false;
useRawMovement = true;
progressState = Active;
numIdlingUpdates = 0;
numIdlingSlowUpdates = 0;
currWayPointDist = 0.0f;
prevWayPointDist = 0.0f;
}
void CGroundMoveType::StartMoving(float3 moveGoalPos, float moveGoalRadius) {
#ifdef TRACE_SYNC
tracefile << "[" << __FUNCTION__ << "] ";
tracefile << owner->pos.x << " " << owner->pos.y << " " << owner->pos.z << " " << owner->id << "\n";
#endif
// set the new goal
goalPos = moveGoalPos * XZVector;
goalRadius = moveGoalRadius;
atGoal = moveGoalPos.SqDistance2D(owner->pos) < Square(moveGoalRadius);
atEndOfPath = false;
useMainHeading = false;
useRawMovement = false;
progressState = Active;
numIdlingUpdates = 0;
numIdlingSlowUpdates = 0;
currWayPointDist = 0.0f;
prevWayPointDist = 0.0f;
LOG_L(L_DEBUG, "StartMoving: starting engine for unit %i", owner->id);
if (atGoal)
return;
// silently free previous path if unit already had one
//
// units passing intermediate waypoints will TYPICALLY not cause any
// script->{Start,Stop}Moving calls now (even when turnInPlace=true)
// unless they come to a full stop first
ReRequestPath(true);
if (owner->team == gu->myTeam) {
Channels::General->PlayRandomSample(owner->unitDef->sounds.activate, owner);
}
}
void CGroundMoveType::StopMoving(bool callScript, bool hardStop, bool cancelRaw) {
#ifdef TRACE_SYNC
tracefile << "[" << __FUNCTION__ << "] ";
tracefile << owner->pos.x << " " << owner->pos.y << " " << owner->pos.z << " " << owner->id << "\n";
#endif
LOG_L(L_DEBUG, "StopMoving: stopping engine for unit %i", owner->id);
if (!atGoal) {
currWayPoint = Here();
goalPos = currWayPoint;
}
// this gets called under a variety of conditions (see MobileCAI)
// the most common case is a CMD_STOP being issued which means no
// StartMoving-->StartEngine will follow
StopEngine(callScript, hardStop);
useMainHeading = false;
// only a new StartMoving call can normally reset this
useRawMovement &= (!cancelRaw);
progressState = Done;
}
bool CGroundMoveType::FollowPath()
{
bool wantReverse = false;
if (WantToStop()) {
currWayPoint.y = -1.0f;
nextWayPoint.y = -1.0f;
SetMainHeading();
ChangeSpeed(0.0f, false);
} else {
ASSERT_SYNCED(currWayPoint);
ASSERT_SYNCED(nextWayPoint);
ASSERT_SYNCED(owner->pos);
prevWayPointDist = currWayPointDist;
currWayPointDist = owner->pos.distance2D(currWayPoint);
{
// NOTE:
// uses owner->pos instead of currWayPoint (ie. not the same as atEndOfPath)
//
// if our first command is a build-order, then goalRadius is set to our build-range
// and we cannot increase tolerance safely (otherwise the unit might stop when still
// outside its range and fail to start construction)
const float curGoalDistSq = (owner->pos - goalPos).SqLength2D();
const float minGoalDistSq = (UNIT_HAS_MOVE_CMD(owner))?
Square(goalRadius * (numIdlingSlowUpdates + 1)):
Square(goalRadius );
atGoal |= (curGoalDistSq <= minGoalDistSq);
}
if (!atGoal) {
if (!idling) {
numIdlingUpdates = std::max(0, int(numIdlingUpdates - 1));
} else {
numIdlingUpdates = std::min(SHORTINT_MAXVALUE, int(numIdlingUpdates + 1));
}
}
// atEndOfPath never becomes true when useRawMovement
if (!atEndOfPath && !useRawMovement) {
GetNextWayPoint();
} else {
if (atGoal) {
Arrived(false);
}
}
// set direction to waypoint AFTER requesting it; should not be a null-vector
if (currWayPoint != owner->pos)
waypointDir = ((currWayPoint - owner->pos) * XZVector).SafeNormalize();
ASSERT_SYNCED(waypointDir);
wantReverse = WantReverse(waypointDir, flatFrontDir);
// apply obstacle avoidance (steering)
const float3 rawWantedDir = waypointDir * Sign(int(!wantReverse));
const float3& modWantedDir = GetObstacleAvoidanceDir(rawWantedDir);
// ASSERT_SYNCED(modWantedDir);
ChangeHeading(GetHeadingFromVector(modWantedDir.x, modWantedDir.z));
ChangeSpeed(maxWantedSpeed, wantReverse);
}
pathManager->UpdatePath(owner, pathID);
return wantReverse;
}
void CGroundMoveType::ChangeSpeed(float newWantedSpeed, bool wantReverse, bool fpsMode)
{
wantedSpeed = newWantedSpeed;
// round low speeds to zero
if (wantedSpeed <= 0.0f && currentSpeed < 0.01f) {
currentSpeed = 0.0f;
deltaSpeed = 0.0f;
return;
}
// first calculate the "unrestricted" speed and acceleration
float targetSpeed = mix(maxSpeed, maxReverseSpeed, wantReverse);
#if (WAIT_FOR_PATH == 1)
// don't move until we have an actual path, trying to hide queuing
// lag is too dangerous since units can blindly drive into objects,
// cliffs, etc. (requires the QTPFS idle-check in Update)
if (currWayPoint.y == -1.0f && nextWayPoint.y == -1.0f) {
targetSpeed = 0.0f;
} else
#endif
{
if (wantedSpeed > 0.0f) {
const UnitDef* ud = owner->unitDef;
const MoveDef* md = owner->moveDef;
// the pathfinders do NOT check the entire footprint to determine
// passability wrt. terrain (only wrt. structures), so we look at
// the center square ONLY for our current speedmod
float groundSpeedMod = CMoveMath::GetPosSpeedMod(*md, owner->pos, flatFrontDir);
// the pathfinders don't check the speedmod of the square our unit is currently on
// so if we got stuck on a nonpassable square and can't move try to see if we're
// trying to release ourselves towards a passable square
if (groundSpeedMod == 0.0f)
groundSpeedMod = CMoveMath::GetPosSpeedMod(*md, owner->pos + flatFrontDir * SQUARE_SIZE, flatFrontDir);
const float curGoalDistSq = (owner->pos - goalPos).SqLength2D();
const float minGoalDistSq = Square(BrakingDistance(currentSpeed, decRate));
const float3& waypointDifFwd = waypointDir;
const float3 waypointDifRev = -waypointDifFwd;
const float3& waypointDif = mix(waypointDifFwd, waypointDifRev, reversing);
const short turnDeltaHeading = owner->heading - GetHeadingFromVector(waypointDif.x, waypointDif.z);
// NOTE: <= 2 because every CMD_MOVE has a trailing CMD_SET_WANTED_MAX_SPEED
const bool startBraking = (UNIT_CMD_QUE_SIZE(owner) <= 2 && curGoalDistSq <= minGoalDistSq && !fpsMode);
if (!fpsMode && turnDeltaHeading != 0) {
// only auto-adjust speed for turns when not in FPS mode
const float reqTurnAngle = math::fabs(180.0f * short(owner->heading - wantedHeading) / SHORTINT_MAXVALUE);
const float maxTurnAngle = (turnRate / SPRING_CIRCLE_DIVS) * 360.0f;
const float turnMaxSpeed = mix(maxSpeed, maxReverseSpeed, reversing);
float turnModSpeed = turnMaxSpeed;
if (reqTurnAngle != 0.0f)
turnModSpeed *= Clamp(maxTurnAngle / reqTurnAngle, 0.1f, 1.0f);
if (waypointDir.SqLength() > 0.1f) {
if (!ud->turnInPlace) {
// never let speed drop below TIPSL, but limit TIPSL itself to turnMaxSpeed
targetSpeed = Clamp(turnModSpeed, std::min(ud->turnInPlaceSpeedLimit, turnMaxSpeed), turnMaxSpeed);
} else {
if (reqTurnAngle > ud->turnInPlaceAngleLimit) {
targetSpeed = turnModSpeed;
}
}
}
if (atEndOfPath) {
// at this point, Update() will no longer call GetNextWayPoint()
// and we must slow down to prevent entering an infinite circle
targetSpeed = std::min(targetSpeed, (currWayPointDist * math::PI) / (SPRING_CIRCLE_DIVS / turnRate));
}
}
// now apply the terrain and command restrictions
// NOTE:
// if wantedSpeed > targetSpeed, the unit will
// not accelerate to speed > targetSpeed unless
// its actual max{Reverse}Speed is also changed
//
// raise wantedSpeed iff the terrain-modifier is
// larger than 1 (so units still get their speed
// bonus correctly), otherwise leave it untouched
//
// disallow changing speed (except to zero) without
// a path if not in FPS mode (FIXME: legacy PFS can
// return path when none should exist, mantis3720)
wantedSpeed *= std::max(groundSpeedMod, 1.0f);
targetSpeed *= groundSpeedMod;
targetSpeed *= (1 - startBraking);
targetSpeed *= ((1 - WantToStop()) || fpsMode);
targetSpeed = std::min(targetSpeed, wantedSpeed);
} else {
targetSpeed = 0.0f;
}
}
deltaSpeed = pathController.GetDeltaSpeed(
pathID,
targetSpeed,
currentSpeed,
accRate,
decRate,
wantReverse,
reversing
);
}
/*
* Changes the heading of the owner.
* FIXME near-duplicate of HoverAirMoveType::UpdateHeading
*/
void CGroundMoveType::ChangeHeading(short newHeading) {
if (owner->IsFlying())
return;
if (owner->GetTransporter() != nullptr)
return;
#if 0
const short rawDeltaHeading = pathController.GetDeltaHeading(pathID, (wantedHeading = newHeading), owner->heading, turnRate);
#else
// model rotational inertia (more realistic for ships)
const short rawDeltaHeading = pathController.GetDeltaHeading(pathID, (wantedHeading = newHeading), owner->heading, turnRate, turnAccel, BrakingDistance(turnSpeed, turnAccel), &turnSpeed);
#endif
const short absDeltaHeading = rawDeltaHeading * Sign(rawDeltaHeading);
if (absDeltaHeading >= minScriptChangeHeading)
owner->script->ChangeHeading(rawDeltaHeading);
owner->AddHeading(rawDeltaHeading, !owner->upright);
flatFrontDir = owner->frontdir;
flatFrontDir.Normalize2D();
}
bool CGroundMoveType::CanApplyImpulse(const float3& impulse)
{
// NOTE: ships must be able to receive impulse too (for collision handling)
if (owner->beingBuilt)
return false;
// will be applied to transporter instead
if (owner->GetTransporter() != nullptr)
return false;
if (impulse.SqLength() <= 0.01f)
return false;
useHeading = false;
skidRotSpeed = 0.0f;
skidRotAccel = 0.0f;
float3 newSpeed = owner->speed + impulse;
float3 skidDir = owner->frontdir;
// NOTE:
// we no longer delay the skidding-state until owner has "accumulated" an
// arbitrary hardcoded amount of impulse (possibly across several frames),
// but enter it on any vector that causes speed to become misaligned with
// frontdir
// TODO (95.0+):
// there should probably be a configurable minimum-impulse below which the
// unit does not react at all but also does NOT "store" the impulse like a
// small-charge capacitor
//
const bool startSkidding = StartSkidding(newSpeed, skidDir);
const bool startFlying = StartFlying(newSpeed, CGround::GetNormal(owner->pos.x, owner->pos.z));
if (startSkidding)
owner->script->StartSkidding(newSpeed);
if (newSpeed.SqLength2D() >= 0.01f)
skidDir = newSpeed.Normalize2D();
skidRotVector = skidDir.cross(UpVector) * startSkidding;
skidRotAccel = ((gsRNG.NextFloat() - 0.5f) * 0.04f) * startFlying;
owner->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_SKIDDING * (startSkidding | startFlying));
owner->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_FLYING * startFlying);
// indicate we want to react to the impulse
return true;
}
void CGroundMoveType::UpdateSkid()
{
ASSERT_SYNCED(owner->midPos);
const float3& pos = owner->pos;
const float4& spd = owner->speed;
const UnitDef* ud = owner->unitDef;
const float groundHeight = GetGroundHeight(pos);
owner->SetVelocity(spd + owner->GetDragAccelerationVec(float4(mapInfo->atmosphere.fluidDensity, mapInfo->water.fluidDensity, 1.0f, 0.01f)));
if (owner->IsFlying()) {
const float impactSpeed = pos.IsInBounds()?
-spd.dot(CGround::GetNormal(pos.x, pos.z)):
-spd.dot(UpVector);
const float impactDamageMult = impactSpeed * owner->mass * COLLISION_DAMAGE_MULT;
const bool doColliderDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > ud->minCollisionSpeed && ud->minCollisionSpeed >= 0.0f);
if (groundHeight > pos.y) {
// ground impact, stop flying
owner->ClearPhysicalStateBit(CSolidObject::PSTATE_BIT_FLYING);
owner->Move(UpVector * (groundHeight - pos.y), true);
// deal ground impact damage
// TODO:
// bouncing behaves too much like a rubber-ball,
// most impact energy needs to go into the ground
if (doColliderDamage)
owner->DoDamage(DamageArray(impactDamageMult), ZeroVector, nullptr, -CSolidObject::DAMAGE_COLLISION_GROUND, -1);
skidRotSpeed = 0.0f;
// skidRotAccel = 0.0f;
} else {
owner->SetVelocity(spd + (UpVector * mapInfo->map.gravity));
}
} else {
// *assume* this means the unit is still on the ground
// (Lua gadgetry can interfere with our "physics" logic)
float skidRotSpd = 0.0f;
const bool onSlope = OnSlope(0.0f);
const float speedReduction = 0.35f;
if (!onSlope && StopSkidding(spd, owner->frontdir)) {
useHeading = true;
skidRotSpd = math::floor(skidRotSpeed + skidRotAccel + 0.5f);
skidRotAccel = (skidRotSpd - skidRotSpeed) * 0.5f;
skidRotAccel *= math::DEG_TO_RAD;
owner->ClearPhysicalStateBit(CSolidObject::PSTATE_BIT_SKIDDING);
owner->script->StopSkidding();
// update wanted-heading after coming to a stop
ChangeHeading(owner->heading);
} else {
// number of frames until rotational speed would drop to 0
const float speedScale = owner->SetSpeed(spd);
const float remTime = std::max(1.0f, speedScale / speedReduction);
if (onSlope) {
const float3& normalVector = CGround::GetNormal(pos.x, pos.z);
const float3 normalForce = normalVector * normalVector.dot(UpVector * mapInfo->map.gravity);
const float3 newForce = UpVector * mapInfo->map.gravity - normalForce;
owner->SetVelocity(spd + newForce);
owner->SetVelocity(spd * (1.0f - (0.1f * normalVector.y)));
} else {
// RHS is clamped to 0..1
owner->SetVelocity(spd * (1.0f - std::min(1.0f, speedReduction / speedScale)));
}
skidRotSpd = math::floor(skidRotSpeed + skidRotAccel * (remTime - 1.0f) + 0.5f);
skidRotAccel = (skidRotSpd - skidRotSpeed) / remTime;
skidRotAccel *= math::DEG_TO_RAD;
if (math::floor(skidRotSpeed) != math::floor(skidRotSpeed + skidRotAccel)) {
skidRotSpeed = 0.0f;
skidRotAccel = 0.0f;
}
}
if ((groundHeight - pos.y) < (spd.y + mapInfo->map.gravity)) {
owner->SetVelocity(spd + (UpVector * mapInfo->map.gravity));
// flying requires skidding and relies on CalcSkidRot
owner->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_FLYING);
owner->SetPhysicalStateBit(CSolidObject::PSTATE_BIT_SKIDDING);
useHeading = false;
} else if ((groundHeight - pos.y) > spd.y) {
// LHS is always negative, so this becomes true when the
// unit is falling back down and will impact the ground
// in one frame
const float3& normal = (pos.IsInBounds())? CGround::GetNormal(pos.x, pos.z): UpVector;
const float dot = spd.dot(normal);
if (dot > 0.0f) {
// not possible without lateral movement
owner->SetVelocity(spd * 0.95f);
} else {
owner->SetVelocity(spd + (normal * (math::fabs(spd.dot(normal)) + 0.1f)));
owner->SetVelocity(spd * 0.8f);
}
}
}
// finally update speed.w
owner->SetSpeed(spd);
// translate before rotate, match terrain normal if not in air
owner->Move(spd, true);
owner->UpdateDirVectors(!owner->upright);
if (owner->IsSkidding()) {
CalcSkidRot();
CheckCollisionSkid();
} else {
// do this here since ::Update returns early if it calls us
HandleObjectCollisions();
}
AdjustPosToWaterLine();
// always update <oldPos> here so that <speed> does not make
// extreme jumps when the unit transitions from skidding back
// to non-skidding
oldPos = owner->pos;
ASSERT_SANE_OWNER_SPEED(spd);
ASSERT_SYNCED(owner->midPos);
}
void CGroundMoveType::UpdateControlledDrop()
{
const float3& pos = owner->pos;
const float4& spd = owner->speed;
const float3 acc = UpVector * std::min(mapInfo->map.gravity * owner->fallSpeed, 0.0f);
const float gh = GetGroundHeight(pos);
owner->SetVelocity(spd + acc);
owner->SetVelocity(spd + owner->GetDragAccelerationVec(float4(mapInfo->atmosphere.fluidDensity, mapInfo->water.fluidDensity, 1.0f, 0.1f)));
owner->SetSpeed(spd);
owner->Move(spd, true);
if (gh > pos.y) {
// ground impact, stop parachute animation
owner->Move(UpVector * (gh - pos.y), true);
owner->ClearPhysicalStateBit(CSolidObject::PSTATE_BIT_FALLING);
owner->script->Landed();
}
}
void CGroundMoveType::CheckCollisionSkid()
{
CUnit* collider = owner;
// NOTE:
// the QuadField::Get* functions check o->midPos,
// but the quad(s) that objects are stored in are
// derived from o->pos (!)
const float3& pos = collider->pos;
const UnitDef* colliderUD = collider->unitDef;
// copy on purpose, since the below can call Lua
const vector<CUnit*> nearUnits = quadField->GetUnitsExact(pos, collider->radius);
const vector<CFeature*> nearFeatures = quadField->GetFeaturesExact(pos, collider->radius);
vector<CUnit*>::const_iterator ui;
vector<CFeature*>::const_iterator fi;
for (ui = nearUnits.begin(); ui != nearUnits.end(); ++ui) {
CUnit* collidee = *ui;
if (!collidee->HasCollidableStateBit(CSolidObject::CSTATE_BIT_SOLIDOBJECTS))
continue;
const UnitDef* collideeUD = collider->unitDef;
const float sqDist = (pos - collidee->pos).SqLength();
const float totRad = collider->radius + collidee->radius;
if ((sqDist >= totRad * totRad) || (sqDist <= 0.01f))
continue;
const float3 dif = (pos - collidee->pos).SafeNormalize();
if (collidee->unitDef->IsImmobileUnit()) {
const float impactSpeed = -collider->speed.dot(dif);
const float impactDamageMult = std::min(impactSpeed * collider->mass * COLLISION_DAMAGE_MULT, MAX_UNIT_SPEED);
const bool doColliderDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > colliderUD->minCollisionSpeed && colliderUD->minCollisionSpeed >= 0.0f);
const bool doCollideeDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > collideeUD->minCollisionSpeed && collideeUD->minCollisionSpeed >= 0.0f);
if (impactSpeed <= 0.0f)
continue;
// damage the collider, no added impulse
if (doColliderDamage)
collider->DoDamage(DamageArray(impactDamageMult), ZeroVector, nullptr, -CSolidObject::DAMAGE_COLLISION_OBJECT, -1);
// damage the (static) collidee based on collider's mass, no added impulse
if (doCollideeDamage)
collidee->DoDamage(DamageArray(impactDamageMult), ZeroVector, nullptr, -CSolidObject::DAMAGE_COLLISION_OBJECT, -1);
collider->Move(dif * impactSpeed, true);
collider->SetVelocity(collider->speed + ((dif * impactSpeed) * 1.8f));
} else {
assert(collider->mass > 0.0f && collidee->mass > 0.0f);
// don't conserve momentum (impact speed is halved, so impulses are too)
// --> collisions are neither truly elastic nor truly inelastic to prevent
// the simulation from blowing up from impulses applied to tight groups of
// units
const float impactSpeed = (collidee->speed - collider->speed).dot(dif) * 0.5f;
const float colliderRelMass = (collider->mass / (collider->mass + collidee->mass));
const float colliderRelImpactSpeed = impactSpeed * (1.0f - colliderRelMass);
const float collideeRelImpactSpeed = impactSpeed * ( colliderRelMass);
const float colliderImpactDmgMult = std::min(colliderRelImpactSpeed * collider->mass * COLLISION_DAMAGE_MULT, MAX_UNIT_SPEED);
const float collideeImpactDmgMult = std::min(collideeRelImpactSpeed * collider->mass * COLLISION_DAMAGE_MULT, MAX_UNIT_SPEED);
const float3 colliderImpactImpulse = dif * colliderRelImpactSpeed;
const float3 collideeImpactImpulse = dif * collideeRelImpactSpeed;
const bool doColliderDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > colliderUD->minCollisionSpeed && colliderUD->minCollisionSpeed >= 0.0f);
const bool doCollideeDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > collideeUD->minCollisionSpeed && collideeUD->minCollisionSpeed >= 0.0f);
if (impactSpeed <= 0.0f)
continue;
// damage the collider
if (doColliderDamage)
collider->DoDamage(DamageArray(colliderImpactDmgMult), dif * colliderImpactDmgMult, nullptr, -CSolidObject::DAMAGE_COLLISION_OBJECT, -1);
// damage the collidee
if (doCollideeDamage)
collidee->DoDamage(DamageArray(collideeImpactDmgMult), dif * -collideeImpactDmgMult, nullptr, -CSolidObject::DAMAGE_COLLISION_OBJECT, -1);