/
UnitScript.cpp
1668 lines (1430 loc) · 42.3 KB
/
UnitScript.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 */
/* heavily based on CobInstance.cpp */
#include "UnitScript.h"
#include "CobDefines.h"
#include "CobFile.h"
#include "CobInstance.h"
#include "UnitScriptEngine.h"
#ifndef _CONSOLE
#include "Game/GameHelper.h"
#include "Game/GlobalUnsynced.h"
#include "Map/Ground.h"
#include "Sim/Misc/GroundBlockingObjectMap.h"
#include "Sim/Misc/LosHandler.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/MoveTypes/AAirMoveType.h"
#include "Sim/MoveTypes/GroundMoveType.h"
#include "Sim/MoveTypes/MoveDefHandler.h"
#include "Sim/MoveTypes/MoveType.h"
#include "Sim/Projectiles/ExplosionGenerator.h"
#include "Sim/Projectiles/PieceProjectile.h"
#include "Sim/Projectiles/ProjectileHandler.h"
#include "Sim/Projectiles/Unsynced/BubbleProjectile.h"
#include "Sim/Projectiles/Unsynced/HeatCloudProjectile.h"
#include "Sim/Projectiles/Unsynced/MuzzleFlame.h"
#include "Sim/Projectiles/Unsynced/SmokeProjectile.h"
#include "Sim/Projectiles/Unsynced/WakeProjectile.h"
#include "Sim/Projectiles/Unsynced/WreckProjectile.h"
#include "Sim/Units/CommandAI/CommandAI.h"
#include "Sim/Units/CommandAI/Command.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Units/Unit.h"
#include "Sim/Units/UnitHandler.h"
#include "Sim/Units/UnitTypes/TransportUnit.h"
#include "Sim/Weapons/PlasmaRepulser.h"
#include "Sim/Weapons/Weapon.h"
#include "Sim/Weapons/WeaponDef.h"
#include "System/FastMath.h"
#include "System/myMath.h"
#include "System/Log/ILog.h"
#include "System/Util.h"
#include "System/Sound/ISoundChannels.h"
#include "System/Sync/SyncTracer.h"
#endif
std::vector< std::vector<int> > CUnitScript::teamVars;
std::vector< std::vector<int> > CUnitScript::allyVars;
int CUnitScript::globalVars[GLOBAL_VAR_COUNT] = { 0 };
void CUnitScript::InitVars(int numTeams, int numAllyTeams)
{
// clear all globals in case we reloaded
memset(&globalVars[0], 0, GLOBAL_VAR_COUNT * sizeof(globalVars[0]));
teamVars.clear();
teamVars.resize(numTeams, std::vector<int>());
allyVars.clear();
allyVars.resize(numAllyTeams, std::vector<int>());
for (int t = 0; t < numTeams; t++) {
teamVars[t].resize(TEAM_VAR_COUNT, 0);
}
for (int t = 0; t < numAllyTeams; t++) {
allyVars[t].resize(ALLY_VAR_COUNT, 0);
}
}
CUnitScript::CUnitScript(CUnit* unit, const std::vector<LocalModelPiece*>& pieces)
: unit(unit)
, busy(false)
, hasSetSFXOccupy(false)
, hasRockUnit(false)
, hasStartBuilding(false)
, pieces(pieces)
{
memset(unitVars, 0, sizeof(unitVars));
}
CUnitScript::~CUnitScript()
{
bool haveAnimations = false;
for (int animType = ATurn; animType <= AMove; animType++) {
for (std::list<AnimInfo*>::iterator i = anims[animType].begin(); i != anims[animType].end(); ++i) {
// anim listeners are not owned by the anim in general, so don't delete them here
delete *i;
}
haveAnimations = (haveAnimations || !anims[animType].empty());
}
// Remove us from possible animation ticking
if (haveAnimations)
GUnitScriptEngine.RemoveInstance(this);
}
/******************************************************************************/
/**
* @brief Unblocks all threads waiting on an animation
* @param anim AnimInfo the corresponding animation
*/
void CUnitScript::UnblockAll(AnimInfo* anim)
{
std::list<IAnimListener *>::iterator li;
for (li = anim->listeners.begin(); li != anim->listeners.end(); ++li) {
(*li)->AnimFinished(anim->type, anim->piece, anim->axis);
}
}
/**
* @brief Updates move animations
* @param cur float value to update
* @param dest float final value
* @param speed float max increment per tick
* @return returns true if destination was reached, false otherwise
*/
bool CUnitScript::MoveToward(float& cur, float dest, float speed)
{
const float delta = dest - cur;
if (math::fabsf(delta) <= speed) {
cur = dest;
return true;
}
if (delta > 0.0f) {
cur += speed;
} else {
cur -= speed;
}
return false;
}
/**
* @brief Updates turn animations
* @param cur float value to update
* @param dest float final value
* @param speed float max increment per tick
* @return returns true if destination was reached, false otherwise
*/
bool CUnitScript::TurnToward(float& cur, float dest, float speed)
{
float delta = dest - cur;
// clamp: -pi .. 0 .. +pi (remainder(x,TWOPI) would do the same but is slower due to streflop)
if (delta > PI) {
delta -= TWOPI;
} else if (delta<=-PI) {
delta += TWOPI;
}
if (math::fabsf(delta) <= speed) {
cur = dest;
return true;
}
if (delta > 0.0f) {
cur += speed;
} else {
cur -= speed;
}
ClampRad(&cur);
return false;
}
/**
* @brief Updates spin animations
* @param cur float value to update
* @param dest float the final desired speed (NOT the final angle!)
* @param speed float is updated if it is not equal to dest
* @param divisor int is the deltatime, it is not added before the call because speed may have to be updated
* @return true if the desired speed is 0 and it is reached, false otherwise
*/
bool CUnitScript::DoSpin(float& cur, float dest, float &speed, float accel, int divisor)
{
const float delta = dest - speed;
// Check if we are not at the final speed and
// make sure we dont go past desired speed
if (math::fabsf(delta) <= accel) {
speed = dest;
if (speed == 0.0f)
return true;
}
else {
if (delta > 0.0f) {
// accelerations are defined in speed/frame (at GAME_SPEED fps)
speed += accel * (float(GAME_SPEED) / divisor);
} else {
speed -= accel * (float(GAME_SPEED) / divisor);
}
}
cur += (speed / divisor);
ClampRad(&cur);
return false;
}
void CUnitScript::TickAnims(int deltaTime, AnimType type, std::list< std::list<AnimInfo*>::iterator >& doneAnims) {
switch (type) {
case AMove: {
for (std::list<AnimInfo*>::iterator it = anims[type].begin(); it != anims[type].end(); ++it) {
AnimInfo* ai = *it;
// NOTE: we should not need to copy-and-set here, because
// MoveToward/TurnToward/DoSpin modify pos/rot by reference
float3 pos = pieces[ai->piece]->GetPosition();
if (MoveToward(pos[ai->axis], ai->dest, ai->speed / (1000 / deltaTime))) {
ai->done = true; doneAnims.push_back(it);
}
pieces[ai->piece]->SetPosition(pos);
unit->localModel->PieceUpdated(ai->piece);
}
} break;
case ATurn: {
for (std::list<AnimInfo*>::iterator it = anims[type].begin(); it != anims[type].end(); ++it) {
AnimInfo* ai = *it;
float3 rot = pieces[ai->piece]->GetRotation();
if (TurnToward(rot[ai->axis], ai->dest, ai->speed / (1000 / deltaTime))) {
ai->done = true; doneAnims.push_back(it);
}
pieces[ai->piece]->SetRotation(rot);
unit->localModel->PieceUpdated(ai->piece);
}
} break;
case ASpin: {
for (std::list<AnimInfo*>::iterator it = anims[type].begin(); it != anims[type].end(); ++it) {
AnimInfo* ai = *it;
float3 rot = pieces[ai->piece]->GetRotation();
if (DoSpin(rot[ai->axis], ai->dest, ai->speed, ai->accel, 1000 / deltaTime)) {
ai->done = true; doneAnims.push_back(it);
}
pieces[ai->piece]->SetRotation(rot);
unit->localModel->PieceUpdated(ai->piece);
}
} break;
default: {
} break;
}
}
/**
* @brief Called by the engine when we are registered as animating.
If we return false there are no active animations left.
* @param deltaTime int delta time to update
* @return true if there are still active animations
*/
bool CUnitScript::Tick(int deltaTime)
{
typedef std::list<AnimInfo*>::iterator AnimInfoIt;
// list of _iterators_ to finished animations,
// so we can get rid of them in constant time
std::list<AnimInfoIt> doneAnims;
for (int animType = ATurn; animType <= AMove; animType++) {
TickAnims(deltaTime, AnimType(animType), doneAnims);
}
//! Tell listeners to unblock, and remove finished animations from the unit/script.
//! NOTE:
//! removing a finished animation _must_ happen before notifying its listeners,
//! otherwise the callback function (AnimFinished()) can call AddAnimListener()
//! and append it to the listeners-list again (causing an endless loop)!
//! NOTE: UnblockAll might result in new anims being added
for (std::list<AnimInfoIt>::const_iterator it = doneAnims.begin(); it != doneAnims.end(); ++it) {
AnimInfoIt animInfoIt = *it;
AnimInfo* animInfo = *animInfoIt;
anims[animInfo->type].erase(animInfoIt);
UnblockAll(animInfo);
delete animInfo;
}
return (HaveAnimations());
}
std::list<CUnitScript::AnimInfo*>::iterator CUnitScript::FindAnim(AnimType type, int piece, int axis)
{
for (std::list<AnimInfo*>::iterator i = anims[type].begin(); i != anims[type].end(); ++i) {
if (((*i)->piece == piece) && ((*i)->axis == axis))
return i;
}
return anims[type].end();
}
void CUnitScript::RemoveAnim(AnimType type, const std::list<AnimInfo*>::iterator& animInfoIt)
{
if (animInfoIt != anims[type].end()) {
AnimInfo* ai = *animInfoIt;
anims[type].erase(animInfoIt);
// If this was the last animation, remove from currently animating list
// FIXME: this could be done in a cleaner way
if (!HaveAnimations()) {
GUnitScriptEngine.RemoveInstance(this);
}
//! We need to unblock threads waiting on this animation, otherwise they will be lost in the void
//! NOTE: UnblockAll might result in new anims being added
UnblockAll(ai);
delete ai;
}
}
//Overwrites old information. This means that threads blocking on turn completion
//will now wait for this new turn instead. Not sure if this is the expected behaviour
//Other option would be to kill them. Or perhaps unblock them.
void CUnitScript::AddAnim(AnimType type, int piece, int axis, float speed, float dest, float accel)
{
if (!PieceExists(piece)) {
ShowUnitScriptError("Invalid piecenumber");
return;
}
float destf = 0.0f;
if (type == AMove) {
destf = pieces[piece]->original->offset[axis] + dest;
} else {
destf = dest;
if (type == ATurn) {
ClampRad(&destf);
}
}
std::list<AnimInfo*>::iterator animInfoIt;
AnimInfo* ai = NULL;
AnimType overrideType = ANone;
// first find an animation of a type we override
// Turns override spins.. Not sure about the other way around? If so
// the system should probably be redesigned to only have two types of
// anims (turns and moves), with spin as a bool
switch (type) {
case ATurn: {
overrideType = ASpin;
animInfoIt = FindAnim(overrideType, piece, axis);
} break;
case ASpin: {
overrideType = ATurn;
animInfoIt = FindAnim(overrideType, piece, axis);
} break;
case AMove: {
// ensure we never remove an animation of this type
overrideType = AMove;
animInfoIt = anims[overrideType].end();
} break;
default: {
} break;
}
assert(overrideType >= 0);
if (animInfoIt != anims[overrideType].end())
RemoveAnim(overrideType, animInfoIt);
// now find an animation of our own type
animInfoIt = FindAnim(type, piece, axis);
if (animInfoIt == anims[type].end()) {
// If we were not animating before, inform the engine of this so it can schedule us
// FIXME: this could be done in a cleaner way
if (!HaveAnimations()) {
GUnitScriptEngine.AddInstance(this);
}
ai = new AnimInfo();
ai->type = type;
ai->piece = piece;
ai->axis = axis;
anims[type].push_back(ai);
} else {
ai = *animInfoIt;
}
ai->dest = destf;
ai->speed = speed;
ai->accel = accel;
ai->done = false;
}
void CUnitScript::Spin(int piece, int axis, float speed, float accel)
{
std::list<AnimInfo*>::iterator animInfoIt = FindAnim(ASpin, piece, axis);
//If we are already spinning, we may have to decelerate to the new speed
if (animInfoIt != anims[ASpin].end()) {
AnimInfo* ai = *animInfoIt;
ai->dest = speed;
if (accel > 0) {
ai->accel = accel;
} else {
//Go there instantly. Or have a defaul accel?
ai->speed = speed;
ai->accel = 0;
}
} else {
//No accel means we start at desired speed instantly
if (accel <= 0)
AddAnim(ASpin, piece, axis, speed, speed, 0);
else
AddAnim(ASpin, piece, axis, 0, speed, accel);
}
}
void CUnitScript::StopSpin(int piece, int axis, float decel)
{
std::list<AnimInfo*>::iterator animInfoIt = FindAnim(ASpin, piece, axis);
if (decel <= 0) {
RemoveAnim(ASpin, animInfoIt);
} else {
if (animInfoIt == anims[ASpin].end())
return;
AnimInfo* ai = *animInfoIt;
ai->dest = 0;
ai->accel = decel;
}
}
void CUnitScript::Turn(int piece, int axis, float speed, float destination)
{
AddAnim(ATurn, piece, axis, std::max(speed, -speed), destination, 0);
}
void CUnitScript::Move(int piece, int axis, float speed, float destination)
{
AddAnim(AMove, piece, axis, std::max(speed, -speed), destination, 0);
}
void CUnitScript::MoveNow(int piece, int axis, float destination)
{
if (!PieceExists(piece)) {
ShowUnitScriptError("Invalid piecenumber");
return;
}
LocalModel* m = unit->localModel;
LocalModelPiece* p = pieces[piece];
float3 pos = p->GetPosition();
pos[axis] = pieces[piece]->original->offset[axis] + destination;
p->SetPosition(pos);
m->PieceUpdated(piece);
}
void CUnitScript::TurnNow(int piece, int axis, float destination)
{
if (!PieceExists(piece)) {
ShowUnitScriptError("Invalid piecenumber");
return;
}
LocalModel* m = unit->localModel;
LocalModelPiece* p = pieces[piece];
float3 rot = p->GetRotation();
rot[axis] = destination;
p->SetRotation(rot);
m->PieceUpdated(piece);
}
void CUnitScript::SetVisibility(int piece, bool visible)
{
if (!PieceExists(piece)) {
ShowUnitScriptError("Invalid piecenumber");
return;
}
pieces[piece]->scriptSetVisible = visible;
}
void CUnitScript::EmitSfx(int sfxType, int piece)
{
#ifndef _CONSOLE
if (!PieceExists(piece)) {
ShowUnitScriptError("Invalid piecenumber for emit-sfx");
return;
}
if (projectileHandler->GetParticleSaturation() > 1.0f && sfxType < SFX_CEG) {
// skip adding (unsynced!) particles when we have too many
return;
}
// Make sure wakes are only emitted on water
if ((sfxType >= SFX_WAKE) && (sfxType <= SFX_REVERSE_WAKE_2)) {
if (CGround::GetApproximateHeight(unit->pos.x, unit->pos.z) > 0.0f) {
return;
}
}
float3 relPos = ZeroVector;
float3 relDir = UpVector;
if (!GetEmitDirPos(piece, relPos, relDir)) {
ShowUnitScriptError("emit-sfx: GetEmitDirPos failed");
return;
}
relDir.SafeNormalize();
const float3 pos = unit->GetObjectSpacePos(relPos);
const float3 dir = unit->GetObjectSpaceVec(relDir);
float alpha = 0.3f + gu->RandFloat() * 0.2f;
float alphaFalloff = 0.004f;
float fadeupTime = 4;
const UnitDef* ud = unit->unitDef;
const MoveDef* md = unit->moveDef;
// hovercraft need special care
if (md != NULL && md->speedModClass == MoveDef::Hover) {
fadeupTime = 8.0f;
alpha = 0.15f + gu->RandFloat() * 0.2f;
alphaFalloff = 0.008f;
}
switch (sfxType) {
case SFX_REVERSE_WAKE:
case SFX_REVERSE_WAKE_2: { //reverse wake
new CWakeProjectile(
unit,
pos + gu->RandVector() * 2.0f,
dir * 0.4f,
6.0f + gu->RandFloat() * 4.0f,
0.15f + gu->RandFloat() * 0.3f,
alpha, alphaFalloff, fadeupTime
);
break;
}
case SFX_WAKE_2: //wake 2, in TA it lives longer..
case SFX_WAKE: { //regular ship wake
new CWakeProjectile(
unit,
pos + gu->RandVector() * 2.0f,
dir * 0.4f,
6.0f + gu->RandFloat() * 4.0f,
0.15f + gu->RandFloat() * 0.3f,
alpha, alphaFalloff, fadeupTime
);
break;
}
case SFX_BUBBLE: { //submarine bubble. does not provide direction through piece vertices..
float3 pspeed = gu->RandVector() * 0.1f;
pspeed.y += 0.2f;
new CBubbleProjectile(
unit,
pos + gu->RandVector() * 2.0f,
pspeed,
40.0f + gu->RandFloat() * GAME_SPEED,
1.0f + gu->RandFloat() * 2.0f,
0.01f,
0.3f + gu->RandFloat() * 0.3f
);
} break;
case SFX_WHITE_SMOKE: //damaged unit smoke
new CSmokeProjectile(unit, pos, gu->RandVector() * 0.5f + UpVector * 1.1f, 60, 4, 0.5f, 0.5f);
break;
case SFX_BLACK_SMOKE: //damaged unit smoke
new CSmokeProjectile(unit, pos, gu->RandVector() * 0.5f + UpVector * 1.1f, 60, 4, 0.5f, 0.6f);
break;
case SFX_VTOL: {
const float3 speed =
unit->speed * 0.7f +
unit->frontdir * 0.5f * relDir.z +
unit->updir * 0.5f * -math::fabs(relDir.y) +
unit->rightdir * 0.5f * relDir.x;
CHeatCloudProjectile* hc = new CHeatCloudProjectile(
unit,
pos,
speed,
10 + gu->RandFloat() * 5,
3 + gu->RandFloat() * 2
);
hc->size = 3;
break;
}
default: {
if (sfxType & SFX_CEG) {
// emit defined explosion-generator (can only be custom, not standard)
// index is made valid by callee, an ID of -1 means CEG failed to load
explGenHandler->GenExplosion(ud->GetModelExplosionGeneratorID(sfxType - SFX_CEG), pos, dir, unit->cegDamage, 1.0f, 0.0f, unit, NULL);
}
else if (sfxType & SFX_FIRE_WEAPON) {
// make a weapon fire from the piece
const unsigned index = sfxType - SFX_FIRE_WEAPON;
if (index >= unit->weapons.size()) {
ShowUnitScriptError("Invalid weapon index for emit-sfx");
break;
}
CWeapon* w = unit->weapons[index];
const SWeaponTarget origTarget = w->GetCurrentTarget();
const float3 origWeaponMuzzlePos = w->weaponMuzzlePos;
w->SetAttackTarget(SWeaponTarget(pos + dir));
w->weaponMuzzlePos = pos;
w->Fire(true);
w->weaponMuzzlePos = origWeaponMuzzlePos;
bool origRestored = w->Attack(origTarget);
assert(origRestored);
}
else if (sfxType & SFX_DETONATE_WEAPON) {
const unsigned index = sfxType - SFX_DETONATE_WEAPON;
if (index >= unit->weapons.size()) {
ShowUnitScriptError("Invalid weapon index for emit-sfx");
break;
}
// detonate weapon from piece
const WeaponDef* weaponDef = unit->weapons[index]->weaponDef;
CGameHelper::ExplosionParams params = {
pos,
ZeroVector,
weaponDef->damages,
weaponDef,
unit, // owner
NULL, // hitUnit
NULL, // hitFeature
weaponDef->craterAreaOfEffect,
weaponDef->damageAreaOfEffect,
weaponDef->edgeEffectiveness,
weaponDef->explosionSpeed,
1.0f, // gfxMod
weaponDef->impactOnly,
weaponDef->noSelfDamage, // ignoreOwner
true, // damageGround
-1u // projectileID
};
helper->Explosion(params);
}
} break;
}
#endif
}
void CUnitScript::AttachUnit(int piece, int u)
{
// -1 is valid, indicates that the unit should be hidden
if ((piece >= 0) && (!PieceExists(piece))) {
ShowUnitScriptError("Invalid piecenumber for attach");
return;
}
#ifndef _CONSOLE
CTransportUnit* tu = dynamic_cast<CTransportUnit*>(unit);
if (tu && unitHandler->units[u]) {
tu->AttachUnit(unitHandler->units[u], piece);
}
#endif
}
void CUnitScript::DropUnit(int u)
{
#ifndef _CONSOLE
CTransportUnit* tu = dynamic_cast<CTransportUnit*>(unit);
if (tu && unitHandler->units[u]) {
tu->DetachUnit(unitHandler->units[u]);
}
#endif
}
//Returns true if there was an animation to listen to
bool CUnitScript::AddAnimListener(AnimType type, int piece, int axis, IAnimListener *listener)
{
std::list<AnimInfo*>::iterator animInfoIt = FindAnim(type, piece, axis);
if (animInfoIt != anims[type].end()) {
AnimInfo* ai = *animInfoIt;
if (!ai->done) {
ai->listeners.push_back(listener);
return true;
}
// if the animation is already finished, listening for
// it just adds some overhead since either the current
// or the next Tick will remove it and call UnblockAll
// (which calls AnimFinished for each listener)
//
// we could notify the listener here, but a cleaner way
// is to treat the animation as if it did not exist and
// simply disregard the WaitFor* (no side-effects)
//
// listener->AnimFinished(ai->type, ai->piece, ai->axis);
}
return false;
}
//Flags as defined by the cob standard
void CUnitScript::Explode(int piece, int flags)
{
if (!PieceExists(piece)) {
ShowUnitScriptError("Invalid piecenumber for explode");
return;
}
#ifndef _CONSOLE
const float3 relPos = GetPiecePos(piece);
const float3 absPos = unit->GetObjectSpacePos(relPos);
#ifdef TRACE_SYNC
tracefile << "Cob explosion: ";
tracefile << absPos.x << " " << absPos.y << " " << absPos.z << " " << piece << " " << flags << "\n";
#endif
if (!(flags & PF_NoHeatCloud)) {
// Do an explosion at the location first
new CHeatCloudProjectile(NULL, absPos, ZeroVector, 30, 30);
}
// If this is true, no stuff should fly off
if (flags & PF_NONE)
return;
// This means that we are going to do a full fledged piece explosion!
float3 baseSpeed = unit->speed;
float3 explSpeed((0.5f - gs->randFloat()) * 6.0f, 1.2f + gs->randFloat() * 5.0f, (0.5f - gs->randFloat()) * 6.0f);
if (baseSpeed.SqLength() > 9) {
const float l = baseSpeed.Length();
const float l2 = 3 + math::sqrt(l - 3);
baseSpeed *= (l2 / l);
}
if (unit->pos.y - CGround::GetApproximateHeight(unit->pos.x, unit->pos.z) > 15) {
explSpeed.y = (0.5f - gs->randFloat()) * 6.0f;
}
explSpeed += baseSpeed;
// limit projectile speed to 12 elmos/frame (why?)
if (false && explSpeed.SqLength() > (12.0f*12.0f)) {
explSpeed = (explSpeed.Normalize() * 12.0f);
}
if (flags & PF_Shatter) {
Shatter(piece, absPos, explSpeed);
return;
}
if (pieces[piece]->original == NULL)
return;
// projectiles that don't fall could live forever
int newflags = PF_Fall;
const float partSat = projectileHandler->GetParticleSaturation();
if (flags & PF_Explode) { newflags |= PF_Explode; }
// if (flags & PF_Fall) { newflags |= PF_Fall; }
if ((flags & PF_Smoke) && partSat < 1.0f) { newflags |= PF_Smoke; }
if ((flags & PF_Fire) && partSat < 0.95f) { newflags |= PF_Fire; }
if (flags & PF_NoCEGTrail) { newflags |= PF_NoCEGTrail; }
if (flags & PF_Recursive) { newflags |= PF_Recursive; }
new CPieceProjectile(unit, pieces[piece], absPos, explSpeed, newflags, 0.5f);
#endif
}
void CUnitScript::Shatter(int piece, const float3& pos, const float3& speed)
{
const LocalModelPiece* lmp = pieces[piece];
const S3DModelPiece* omp = lmp->original;
const float pieceChance = 1.0f - (projectileHandler->GetCurrentParticles() - (projectileHandler->maxParticles - 2000)) / 2000.0f;
if (pieceChance > 0.0f) {
omp->Shatter(pieceChance, unit->model->textureType, unit->team, pos, speed);
}
}
void CUnitScript::ShowFlare(int piece)
{
if (!PieceExists(piece)) {
ShowUnitScriptError("Invalid piecenumber for show(flare)");
return;
}
#ifndef _CONSOLE
const float3 relPos = GetPiecePos(piece);
const float3 absPos = unit->GetObjectSpacePos(relPos);
const float3 dir = unit->lastMuzzleFlameDir;
const float size = unit->lastMuzzleFlameSize;
new CMuzzleFlame(absPos, unit->speed, dir, size);
#endif
}
/******************************************************************************/
int CUnitScript::GetUnitVal(int val, int p1, int p2, int p3, int p4)
{
// may happen in case one uses Spring.GetUnitCOBValue (Lua) on a unit with CNullUnitScript
if (!unit) {
ShowUnitScriptError("no unit (in GetUnitVal)");
return 0;
}
#ifndef _CONSOLE
switch (val)
{
case ACTIVATION:
if (unit->activated)
return 1;
else
return 0;
break;
case STANDINGMOVEORDERS:
return unit->moveState;
break;
case STANDINGFIREORDERS:
return unit->fireState;
break;
case HEALTH: {
if (p1 <= 0)
return int((unit->health / unit->maxHealth) * 100.0f);
const CUnit* u = unitHandler->GetUnit(p1);
if (u == NULL)
return 0;
else
return int((u->health / u->maxHealth) * 100.0f);
}
case INBUILDSTANCE:
if (unit->inBuildStance)
return 1;
else
return 0;
case BUSY:
if (busy)
return 1;
else
return 0;
break;
case PIECE_XZ: {
if (!PieceExists(p1)) {
ShowUnitScriptError("Invalid piecenumber for get piece_xz");
break;
}
const float3 relPos = GetPiecePos(p1);
const float3 absPos = unit->GetObjectSpacePos(relPos);
return PACKXZ(absPos.x, absPos.z);
}
case PIECE_Y: {
if (!PieceExists(p1)) {
ShowUnitScriptError("Invalid piecenumber for get piece_y");
break;
}
const float3 relPos = GetPiecePos(p1);
const float3 absPos = unit->GetObjectSpacePos(relPos);
return int(absPos.y * COBSCALE);
}
case UNIT_XZ: {
if (p1 <= 0)
return PACKXZ(unit->pos.x, unit->pos.z);
const CUnit* u = unitHandler->GetUnit(p1);
if (u == NULL)
return PACKXZ(0, 0);
else
return PACKXZ(u->pos.x, u->pos.z);
}
case UNIT_Y: {
if (p1 <= 0)
return int(unit->pos.y * COBSCALE);
const CUnit* u = unitHandler->GetUnit(p1);
if (u == NULL)
return 0;
else
return int(u->pos.y * COBSCALE);
}
case UNIT_HEIGHT: {
if (p1 <= 0)
return int(unit->radius * COBSCALE);
const CUnit* u = unitHandler->GetUnit(p1);
if (u == NULL)
return 0;
else
return int(u->radius * COBSCALE);
}
case XZ_ATAN:
return int(RAD2TAANG*math::atan2((float)UNPACKX(p1), (float)UNPACKZ(p1)) + 32768 - unit->heading);
case XZ_HYPOT:
return int(math::hypot((float)UNPACKX(p1), (float)UNPACKZ(p1)) * COBSCALE);
case ATAN:
return int(RAD2TAANG*math::atan2((float)p1, (float)p2));
case HYPOT:
return int(math::hypot((float)p1, (float)p2));
case GROUND_HEIGHT:
return int(CGround::GetHeightAboveWater(UNPACKX(p1), UNPACKZ(p1)) * COBSCALE);
case GROUND_WATER_HEIGHT:
return int(CGround::GetHeightReal(UNPACKX(p1), UNPACKZ(p1)) * COBSCALE);
case BUILD_PERCENT_LEFT:
return int((1.0f - unit->buildProgress) * 100);
case YARD_OPEN:
return (unit->yardOpen) ? 1 : 0;
case BUGGER_OFF:
break;
case ARMORED:
return (unit->armoredState) ? 1 : 0;
case VETERAN_LEVEL:
return int(100 * unit->experience);
case CURRENT_SPEED:
return int(unit->speed.w * COBSCALE);
case ON_ROAD:
return 0;
case IN_WATER:
return (unit->IsInWater());
case MAX_ID:
return unitHandler->MaxUnits()-1;
case MY_ID:
return unit->id;
case UNIT_TEAM: {
const CUnit* u = unitHandler->GetUnit(p1);
return (u != NULL)? unit->team : 0;
}
case UNIT_ALLIED: {
const CUnit* u = unitHandler->GetUnit(p1);
if (u != NULL) {
return teamHandler->Ally(unit->allyteam, u->allyteam) ? 1 : 0;
}
return 0;
}
case UNIT_BUILD_PERCENT_LEFT: {