-
Notifications
You must be signed in to change notification settings - Fork 235
/
Unit.lua
5553 lines (4735 loc) · 196 KB
/
Unit.lua
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
-----------------------------------------------------------------
-- File : /lua/unit.lua
-- Authors : John Comes, David Tomandl, Gordon Duclos
-- Summary : The Unit lua module
-- Copyright © 2005 Gas Powered Games, Inc. All rights reserved.
-----------------------------------------------------------------
-- Imports. Localise commonly used subfunctions for speed
local EffectTemplate = import("/lua/effecttemplates.lua")
local EffectUtilities = import("/lua/effectutilities.lua")
local EnhancementCommon = import("/lua/enhancementcommon.lua")
local Explosion = import("/lua/defaultexplosions.lua")
local Game = import("/lua/game.lua")
local SimUtils = import("/lua/simutils.lua")
local utilities = import("/lua/utilities.lua")
local Wreckage = import("/lua/wreckage.lua")
local AntiArtilleryShield = import("/lua/shield.lua").AntiArtilleryShield
local PersonalBubble = import("/lua/shield.lua").PersonalBubble
local PersonalShield = import("/lua/shield.lua").PersonalShield
local Shield = import("/lua/shield.lua").Shield
local TransportShield = import("/lua/shield.lua").TransportShield
local Weapon = import("/lua/sim/weapon.lua").Weapon
local IntelComponent = import('/lua/defaultcomponents.lua').IntelComponent
local VeterancyComponent = import('/lua/defaultcomponents.lua').VeterancyComponent
local TrashBag = TrashBag
local TrashAdd = TrashBag.Add
local TrashDestroy = TrashBag.Destroy
local TrashEmpty = TrashBag.Empty
local armies = ListArmies()
local AttachBeamEntityToEntity = AttachBeamEntityToEntity
local CreateEmitterAtBone = CreateEmitterAtBone
local IsAlly = IsAlly
local rawget = rawget
local UpdateAssistersConsumptionCats = categories.REPAIR - categories.INSIGNIFICANTUNIT -- anything that repairs but insignificant things, such as drones
local DefaultTerrainType = GetTerrainType(-1, -1)
local GetNearestPlayablePoint = import("/lua/scenarioframework.lua").GetNearestPlayablePoint
--- Structures that are reused for performance reasons
--- Maps unit.techCategory to a number so we can do math on it for naval units
SyncMeta = {
__index = function(t, key)
local id = rawget(t, 'id')
return UnitData[id].Data[key]
end,
__newindex = function(t, key, val)
-- globals to locals
local rawget = rawget
local UnitData = UnitData
local id = rawget(t, 'id')
local army = rawget(t, 'army')
local unitData = UnitData[id]
if not unitData then
unitData = {
OwnerArmy = army,
Data = {},
}
UnitData[id] = unitData
end
unitData.Data[key] = val
local focus = GetFocusArmy()
if army == focus or focus == -1 then -- Let observers get unit data
local SyncUnitData = Sync.UnitData
unitData = SyncUnitData[id]
if not unitData then
unitData = {}
SyncUnitData[id] = unitData
end
unitData[key] = val
end
end,
}
---@class UnitCommand
---@field x number
---@field y number
---@field z number
---@field targetId? EntityId
---@field target? Entity
---@field commandType string
---@class AIUnitProperties
---@field AIPlatoonReference AIPlatoon
---@field AIBaseManager LocationType
---@field ForkedEngineerTask? thread # used by the engineer manager
---@field DesiresAssist? boolean # used by the engineer manager
---@field NumAssistees? number # used by the engineer manager
---@field MinNumAssistees? number
---@field BuilderManagerData? { EngineerManager: AIEngineerManager, LocationType: LocationType }
---@field UnitBeingAssist? Unit
---@field UnitBeingBuilt? Unit
---@field UnitBeingBuiltBehavior? thread
---@field Combat? boolean
local cUnit = moho.unit_methods
local cUnitGetBuildRate = cUnit.GetBuildRate
---@class Unit : moho.unit_methods, InternalObject, IntelComponent, VeterancyComponent, AIUnitProperties
---@field AIManagerIdentifier? string
---@field Repairers table<EntityId, Unit>
---@field Brain AIBrain
---@field buildBots? Unit[]
---@field Blueprint UnitBlueprint
---@field BuildEffectsBag TrashBag
---@field BuildArmManipulator? moho.BuilderArmManipulator
---@field Trash TrashBag
---@field Layer Layer
---@field Army Army
---@field Dead? boolean
---@field UnitId UnitId
---@field EntityId EntityId
---@field EventCallbacks table<string, function[]>
---@field Buffs {Affects: table<BuffEffectName, BlueprintBuff.Effect>, buffTable: table<string, table>}
---@field EngineFlags? table<string, any>
---@field TerrainType TerrainType
---@field EngineCommandCap? table<string, boolean>
---@field UnitBeingBuilt Unit?
---@field UnitBuildOrder string
---@field MyShield Shield?
---@field EntityBeingReclaimed Unit | Prop | nil
---@field SoundEntity? Unit | Entity
---@field AutoModeEnabled? boolean
---@field OnBeingBuiltEffectsBag TrashBag
---@field IdleEffectsBag TrashBag
---@field SiloWeapon? Weapon
---@field SiloProjectile? ProjectileBlueprint
---@field ReclaimTimeMultiplier? number
---@field CaptureTimeMultiplier? number
Unit = ClassUnit(moho.unit_methods, IntelComponent, VeterancyComponent) {
IsUnit = true,
Weapons = {},
-- FX Damage tables. A random damage effect table of emitters is chosen out of this table
FxDamage1 = {EffectTemplate.DamageSmoke01, EffectTemplate.DamageSparks01},
FxDamage2 = {EffectTemplate.DamageFireSmoke01, EffectTemplate.DamageSparks01},
FxDamage3 = {EffectTemplate.DamageFire01, EffectTemplate.DamageSparks01},
-- Disables all collisions. This will be true for all units being constructed as upgrades
DisallowCollisions = false,
-- Destruction parameters
PlayDestructionEffects = true,
PlayEndAnimDestructionEffects = true,
ShowUnitDestructionDebris = true,
DestructionExplosionWaitDelayMin = 0,
DestructionExplosionWaitDelayMax = 0.5,
DeathThreadDestructionWaitTime = 0.1,
DestructionPartsHighToss = {},
DestructionPartsLowToss = {},
DestructionPartsChassisToss = {},
DisableIntelOfCargo = false,
-- kept for backwards compatibility, these default to true
CanTakeDamage = true,
CanBeKilled = true,
EnergyModifier = 0,
MassModifier = 0,
---@param self Unit
---@return any
GetSync = function(self)
if not Sync.UnitData[self.EntityId] then
Sync.UnitData[self.EntityId] = {}
end
return Sync.UnitData[self.EntityId]
end,
-- The original builder of this unit, set by OnStartBeingBuilt. Used for calculating differential
-- upgrade costs, and tracking the original owner of a unit (for tracking gifting and so on)
originalBuilder = nil,
-------------------------------------------------------------------------------------------
---- INITIALIZATION
-------------------------------------------------------------------------------------------
---@param self Unit
OnPreCreate = function(self)
-- Each unit has a sync table to replicate values to the global sync table to be copied to the user layer at sync time.
self.Sync = {}
self.Sync.id = self:GetEntityId()
self.Sync.army = self:GetArmy()
setmetatable(self.Sync, SyncMeta)
self.Trash = self.Trash or TrashBag()
self.EventCallbacks = {
-- OnKilled = {}, -- done
-- OnUnitBuilt = {}, -- done
-- OnStartBuild = {}, -- done
-- OnReclaimed = {}, -- done
-- OnStartReclaim = {}, -- done
-- OnStopReclaim = {}, -- done
-- OnStopBeingBuilt = {},
-- OnCaptured = {},
-- OnCapturedNewUnit = {},
-- OnDamaged = {},
-- OnStartCapture = {}, -- done
-- OnStopCapture = {}, -- done
-- OnFailedCapture = {}, -- done
-- OnStartBeingCaptured = {}, -- done
-- OnStopBeingCaptured = {},
-- OnFailedBeingCaptured = {},
-- OnFailedToBuild = {},
-- OnVeteran = {},
-- OnGiven = {},
-- ProjectileDamaged = {},
-- SpecialToggleEnableFunction = false,
-- SpecialToggleDisableFunction = false,
-- OnAttachedToTransport = {}, -- Returns self, transport, bone
-- OnDetachedFromTransport = {}, -- Returns self, transport, bone
-- OnTransportAttach = {}
-- OnTransportDetach = {}
-- OnTransportAborted = {}
-- OnTransportOrdered = {}
-- OnAttachedKilled = {}
-- OnStartTransportLoading = {}
-- OnStopTransportLoading = {}
}
end,
---@param self Unit
OnCreate = function(self)
local bp = self:GetBlueprint()
-- cache often accessed values into inner table
self.Blueprint = bp
-- cache engine calls
self.EntityId = self:GetEntityId()
self.Army = self:GetArmy()
self.UnitId = self:GetUnitId()
self.Brain = self:GetAIBrain()
-- used for rebuilding mechanic
self.Repairers = {}
-- used by almost all unit types
self.OnBeingBuiltEffectsBag = TrashBag()
self.IdleEffectsBag = TrashBag()
-- Store weapon information for performance
self.WeaponCount = self:GetWeaponCount() or 0
self.WeaponInstances = { }
for k = 1, self.WeaponCount do
local weapon = self:GetWeapon(k)
self.WeaponInstances[weapon.Label] = weapon
self.WeaponInstances[k] = weapon
end
-- Define Economic modifications
local bpEcon = bp.Economy
self:SetConsumptionPerSecondEnergy(bpEcon.MaintenanceConsumptionPerSecondEnergy or 0)
self:SetConsumptionPerSecondMass(bpEcon.MaintenanceConsumptionPerSecondMass or 0)
self:SetProductionPerSecondEnergy(bpEcon.ProductionPerSecondEnergy or 0)
self:SetProductionPerSecondMass(bpEcon.ProductionPerSecondMass or 0)
self:SetProductionActive(true)
self.Buffs = {
BuffTable = {},
Affects = {},
}
self:ShowPresetEnhancementBones()
local bpDeathAnim = bp.Display.AnimationDeath
if bpDeathAnim and not table.empty(bpDeathAnim) then
self.PlayDeathAnimation = true
end
if self.Brain.CheatEnabled then
import("/lua/ai/aiutilities.lua").ApplyCheatBuffs(self)
end
-- for syncing data to UI
self:UpdateStat("HitpointsRegeneration", bp.Defense.RegenRate)
self:UpdateStat("HitpointsRegeneration", bp.Defense.RegenRate)
-- add support for keeping track of reclaim statistics
if self.Blueprint.General.CommandCapsHash['RULEUCC_Reclaim'] then
self.ReclaimedMass = 0
self.ReclaimedEnergy = 0
self:UpdateStat("ReclaimedMass", 0)
self:UpdateStat("ReclaimedEnergy", 0)
end
-- add support for automated jamming reset
if self.Blueprint.Intel.JammerBlips > 0 then
self.Brain:TrackJammer(self)
self.ResetJammer = -1
end
-- default to ground fire for structures, experimentals and (S)ACUs
if EntityCategoryContains(categories.STRUCTURE + categories.EXPERIMENTAL + categories.COMMAND, self) then
self:SetFireState(2)
end
-- Flags for scripts
self.IsCivilian = armies[self.Army] == "NEUTRAL_CIVILIAN" or nil
VeterancyComponent.OnCreate(self)
end,
-------------------------------------------------------------------------------------------
---- MISC FUNCTIONS
-------------------------------------------------------------------------------------------
-- Returns 4 numbers: skirt x0, skirt z0, skirt.x1, skirt.z1
---@param self Unit
---@return number x0
---@return number z0
---@return number x1
---@return number z1
GetSkirtRect = function(self)
local blueprint = self.Blueprint
local physics = blueprint.Physics
local footprint = blueprint.Footprint
local x, _, z = self:GetPositionXYZ()
local fx = x - footprint.SizeX * .5
local fz = z - footprint.SizeZ * .5
local sx = fx + physics.SkirtOffsetX
local sz = fz + physics.SkirtOffsetZ
return sx, sz, sx + blueprint.Physics.SkirtSizeX, sz + blueprint.Physics.SkirtSizeZ
end,
---@param self Unit
---@param scalar number
---@return number X
---@return number Y
---@return number Z
GetRandomOffset = function(self, scalar)
local bp = self.Blueprint
local sx, sy, sz = bp.SizeX, bp.SizeY, bp.SizeZ
local heading = self:GetHeading()
sx = sx * scalar
sy = sy * scalar
sz = sz * scalar
local rx = Random() * sx - (sx * 0.5)
local y = Random() * sy + (bp.CollisionOffsetY or 0)
local rz = Random() * sz - (sz * 0.5)
local cosh = math.cos(heading)
local sinh = math.sin(heading)
local x = cosh * rx - sinh * rz
local z = sinh * rx + cosh * rz
return x, y, z
end,
---@param self Unit
---@param fn function
---@param ... any
---@return thread | nil
ForkThread = function(self, fn, ...)
if fn then
local thread = ForkThread(fn, self, unpack(arg))
self.Trash:Add(thread)
return thread
else
return nil
end
end,
---@param self Unit
---@param priTable? UnparsedCategory[] | EntityCategory[]
SetTargetPriorities = function(self, priTable)
for i = 1, self.WeaponCount do
self.WeaponInstances[i]:SetWeaponPriorities(priTable)
end
end,
---@param self Unit
---@param priTable? UnparsedCategory[] | EntityCategory[]
SetLandTargetPriorities = function(self, priTable)
for i = 1, self.WeaponCount do
local wep = self.WeaponInstances[i]
for onLayer, targetLayers in wep:GetBlueprint().FireTargetLayerCapsTable do
if string.find(targetLayers, 'Land') then
wep:SetWeaponPriorities(priTable)
break
end
end
end
end,
-- Updates build restrictions of any unit passed, used for support factories
---@param self Unit
UpdateBuildRestrictions = function(self)
-- retrieve info of factory
local faction = self.Blueprint.FactionCategory
local layer = self.Blueprint.LayerCategory
local aiBrain = self:GetAIBrain()
-- the pessimists we are, remove all the units!
self:AddBuildRestriction((categories.TECH3 + categories.TECH2) * categories.MOBILE)
-- if there is a specific T3 HQ - allow all t2 / t3 units of this type
if aiBrain:CountHQs(faction, layer, "TECH3") > 0 then
self:RemoveBuildRestriction((categories.TECH3 + categories.TECH2) * categories.MOBILE)
-- if there is some T3 HQ - allow t2 / t3 engineers
elseif aiBrain:CountHQsAllLayers(faction, "TECH3") > 0 then
self:RemoveBuildRestriction((categories.TECH3 + categories.TECH2) * categories.MOBILE * categories.CONSTRUCTION)
end
-- if there is a specific T2 HQ - allow all t2 units of this type
if aiBrain:CountHQs(faction, layer, "TECH2") > 0 then
self:RemoveBuildRestriction(categories.TECH2 * categories.MOBILE)
-- if there is some T2 HQ - allow t2 engineers
elseif aiBrain:CountHQsAllLayers(faction, "TECH2") > 0 then
self:RemoveBuildRestriction(categories.TECH2 * categories.MOBILE * categories.CONSTRUCTION)
end
end,
-------------------------------------------------------------------------------------------
---- TOGGLES
-------------------------------------------------------------------------------------------
---@param self Unit
---@param bit number
OnScriptBitSet = function(self, bit)
if bit == 0 then -- Shield toggle
self:PlayUnitAmbientSound('ActiveLoop')
self:EnableShield()
elseif bit == 1 then -- Weapon toggle
-- Amended in individual unit's script file
elseif bit == 2 then -- Jamming toggle
self:StopUnitAmbientSound('ActiveLoop')
self:SetMaintenanceConsumptionInactive()
self:DisableUnitIntel('ToggleBit2', 'Jammer')
elseif bit == 3 then -- Intel toggle
self:StopUnitAmbientSound('ActiveLoop')
self:SetMaintenanceConsumptionInactive()
self:DisableUnitIntel('ToggleBit3', 'RadarStealth')
self:DisableUnitIntel('ToggleBit3', 'RadarStealthField')
self:DisableUnitIntel('ToggleBit3', 'SonarStealth')
self:DisableUnitIntel('ToggleBit3', 'SonarStealthField')
self:DisableUnitIntel('ToggleBit3', 'Sonar')
self:DisableUnitIntel('ToggleBit3', 'Omni')
self:DisableUnitIntel('ToggleBit3', 'Cloak')
self:DisableUnitIntel('ToggleBit3', 'CloakField') -- We really shouldn't use this. Cloak/Stealth fields are pretty busted
self:DisableUnitIntel('ToggleBit3', 'Spoof')
self:DisableUnitIntel('ToggleBit3', 'Jammer')
self:DisableUnitIntel('ToggleBit3', 'Radar')
elseif bit == 4 then -- Production toggle
self:OnProductionPaused()
elseif bit == 5 then -- Stealth toggle
self:StopUnitAmbientSound('ActiveLoop')
self:SetMaintenanceConsumptionInactive()
self:DisableUnitIntel('ToggleBit5', 'RadarStealth')
self:DisableUnitIntel('ToggleBit5', 'RadarStealthField')
self:DisableUnitIntel('ToggleBit5', 'SonarStealth')
self:DisableUnitIntel('ToggleBit5', 'SonarStealthField')
elseif bit == 6 then -- Generic pause toggle
self:SetPaused(true)
elseif bit == 7 then -- Special toggle
self:EnableSpecialToggle()
elseif bit == 8 then -- Cloak toggle
self:StopUnitAmbientSound('ActiveLoop')
self:SetMaintenanceConsumptionInactive()
self:DisableUnitIntel('ToggleBit8', 'Cloak')
end
if not self.MaintenanceConsumption then
self.ToggledOff = true
end
end,
---@param self Unit
---@param bit number
OnScriptBitClear = function(self, bit)
if bit == 0 then -- Shield toggle
self:StopUnitAmbientSound('ActiveLoop')
self:DisableShield()
elseif bit == 1 then -- Weapon toggle
elseif bit == 2 then -- Jamming toggle
self:PlayUnitAmbientSound('ActiveLoop')
self:SetMaintenanceConsumptionActive()
self:EnableUnitIntel('ToggleBit2', 'Jammer')
elseif bit == 3 then -- Intel toggle
self:PlayUnitAmbientSound('ActiveLoop')
self:SetMaintenanceConsumptionActive()
self:EnableUnitIntel('ToggleBit3', 'Radar')
self:EnableUnitIntel('ToggleBit3', 'RadarStealth')
self:EnableUnitIntel('ToggleBit3', 'RadarStealthField')
self:EnableUnitIntel('ToggleBit3', 'SonarStealth')
self:EnableUnitIntel('ToggleBit3', 'SonarStealthField')
self:EnableUnitIntel('ToggleBit3', 'Sonar')
self:EnableUnitIntel('ToggleBit3', 'Omni')
self:EnableUnitIntel('ToggleBit3', 'Cloak')
self:EnableUnitIntel('ToggleBit3', 'CloakField') -- We really shouldn't use this. Cloak/Stealth fields are pretty busted
self:EnableUnitIntel('ToggleBit3', 'Spoof')
self:EnableUnitIntel('ToggleBit3', 'Jammer')
elseif bit == 4 then -- Production toggle
self:OnProductionUnpaused()
elseif bit == 5 then -- Stealth toggle
self:PlayUnitAmbientSound('ActiveLoop')
self:SetMaintenanceConsumptionActive()
self:EnableUnitIntel('ToggleBit5', 'RadarStealth')
self:EnableUnitIntel('ToggleBit5', 'RadarStealthField')
self:EnableUnitIntel('ToggleBit5', 'SonarStealth')
self:EnableUnitIntel('ToggleBit5', 'SonarStealthField')
elseif bit == 6 then -- Generic pause toggle
self:SetPaused(false)
elseif bit == 7 then -- Special toggle
self:DisableSpecialToggle()
elseif bit == 8 then -- Cloak toggle
self:PlayUnitAmbientSound('ActiveLoop')
self:SetMaintenanceConsumptionActive()
self:EnableUnitIntel('ToggleBit8', 'Cloak')
end
if self.MaintenanceConsumption then
self.ToggledOff = false
end
end,
---@param self Unit
OnPaused = function(self)
if self:IsUnitState('Building') or self:IsUnitState('Upgrading') or self:IsUnitState('Repairing') then
self:SetActiveConsumptionInactive()
self:StopUnitAmbientSound('ConstructLoop')
end
-- When paused we reclaim at a speed of 0, with thanks to:
-- - https://github.com/FAForever/FA-Binary-Patches/pull/19
if self.EntityBeingReclaimed and (not IsDestroyed(self.EntityBeingReclaimed)) and IsProp(self.EntityBeingReclaimed) then
self:StopReclaimEffects(self.EntityBeingReclaimed)
self:StopUnitAmbientSound('ReclaimLoop')
self:PlayUnitSound('StopReclaim')
end
-- for AI events
self.Brain:OnUnitPaused(self)
end,
---@param self Unit
OnUnpaused = function(self)
if self:IsUnitState('Building') or self:IsUnitState('Upgrading') or self:IsUnitState('Repairing') then
self:SetActiveConsumptionActive()
self:PlayUnitAmbientSound('ConstructLoop')
end
-- When paused we reclaim at a speed of 0, with thanks to:
-- - https://github.com/FAForever/FA-Binary-Patches/pull/19
if self.EntityBeingReclaimed and (not IsDestroyed(self.EntityBeingReclaimed)) and IsProp(self.EntityBeingReclaimed) then
self:StartReclaimEffects(self.EntityBeingReclaimed)
self:PlayUnitSound('StartReclaim')
self:PlayUnitAmbientSound('ReclaimLoop')
end
-- for AI events
self.Brain:OnUnitUnpaused(self)
end,
---@param self Unit
EnableSpecialToggle = function(self)
if self.EventCallbacks.SpecialToggleEnableFunction then
self.EventCallbacks.SpecialToggleEnableFunction(self)
end
end,
---@param self Unit
DisableSpecialToggle = function(self)
if self.EventCallbacks.SpecialToggleDisableFunction then
self.EventCallbacks.SpecialToggleDisableFunction(self)
end
end,
---@param self Unit
---@param fn function
AddSpecialToggleEnable = function(self, fn)
if fn then
self.EventCallbacks.SpecialToggleEnableFunction = fn
end
end,
---@param self Unit
---@param fn function
AddSpecialToggleDisable = function(self, fn)
if fn then
self.EventCallbacks.SpecialToggleDisableFunction = fn
end
end,
---@param self Unit
EnableDefaultToggleCaps = function(self)
if self.ToggleCaps then
for _, v in self.ToggleCaps do
self:AddToggleCap(v)
end
end
end,
---@param self Unit
DisableDefaultToggleCaps = function(self)
self.ToggleCaps = {}
local capsCheckTable = {'RULEUTC_WeaponToggle', 'RULEUTC_ProductionToggle', 'RULEUTC_GenericToggle', 'RULEUTC_SpecialToggle'}
for _, v in capsCheckTable do
if self:TestToggleCaps(v) == true then
table.insert(self.ToggleCaps, v)
end
self:RemoveToggleCap(v)
end
end,
-------------------------------------------------------------------------------------------
---- MISC EVENTS
-------------------------------------------------------------------------------------------
---@param self Unit
---@param target Unit
OnStartCapture = function(self, target)
self:DoUnitCallbacks('OnStartCapture', target)
self:StartCaptureEffects(target)
self:PlayUnitSound('StartCapture')
self:PlayUnitAmbientSound('CaptureLoop')
-- for AI events
self.Brain:OnUnitStartCapture(self, target)
end,
---@param self Unit
---@param target Unit
OnStopCapture = function(self, target)
self:DoUnitCallbacks('OnStopCapture', target)
self:StopCaptureEffects(target)
self:PlayUnitSound('StopCapture')
self:StopUnitAmbientSound('CaptureLoop')
-- for AI events
self.Brain:OnUnitStopCapture(self, target)
end,
---@param self Unit
---@param target Unit
StartCaptureEffects = function(self, target)
self.CaptureEffectsBag = self.CaptureEffectsBag or TrashBag()
self.CaptureEffectsBag:Add(self:ForkThread(self.CreateCaptureEffects, target))
end,
---@param self Unit
---@param target Unit
CreateCaptureEffects = function(self, target)
EffectUtilities.PlayCaptureEffects(self, target, self.BuildEffectBones or {0, }, self.CaptureEffectsBag)
end,
---@param self Unit
---@param target Unit
StopCaptureEffects = function(self, target)
if self.CaptureEffectsBag then
self.CaptureEffectsBag:Destroy()
end
end,
---@param self Unit
---@param target Unit
OnFailedCapture = function(self, target)
self:DoUnitCallbacks('OnFailedCapture', target)
self:StopCaptureEffects(target)
self:StopUnitAmbientSound('CaptureLoop')
self:PlayUnitSound('FailedCapture')
-- for AI events
self.Brain:OnUnitFailedCapture(self, target)
end,
---@param self Unit
---@param captor Unit
CheckCaptor = function(self, captor)
if captor.Dead or captor:GetFocusUnit() ~= self then
self:RemoveCaptor(captor)
else
local progress = captor:GetWorkProgress()
if not self.CaptureProgress or progress > self.CaptureProgress then
self.CaptureProgress = progress
elseif progress < self.CaptureProgress then
captor:SetWorkProgress(self.CaptureProgress)
end
end
end,
---@param self Unit
---@param captor Unit
AddCaptor = function(self, captor)
if not self.Captors then
self.Captors = {}
end
self.Captors[captor.EntityId] = captor
if not self.CaptureThread then
self.CaptureThread = self:ForkThread(function()
local captors = self.Captors or {}
while not table.empty(captors) do
for _, c in captors do
self:CheckCaptor(c)
end
WaitTicks(1)
captors = self.Captors or {}
end
end)
end
end,
---@param self Unit
ResetCaptors = function(self)
if self.CaptureThread then
KillThread(self.CaptureThread)
end
self.Captors = {}
self.CaptureThread = nil
self.CaptureProgress = nil
end,
---@param self Unit
---@param captor Unit
RemoveCaptor = function(self, captor)
self.Captors[captor.EntityId] = nil
if table.empty(self.Captors) then
self:ResetCaptors()
end
end,
---@param self Unit
---@param captor Unit
OnStartBeingCaptured = function(self, captor)
self:AddCaptor(captor)
self:DoUnitCallbacks('OnStartBeingCaptured', captor)
self:PlayUnitSound('StartBeingCaptured')
-- for AI events
self.Brain:OnUnitStartBeingCaptured(self, captor)
end,
---@param self Unit
---@param captor Unit
OnStopBeingCaptured = function(self, captor)
self:RemoveCaptor(captor)
self:DoUnitCallbacks('OnStopBeingCaptured', captor)
self:PlayUnitSound('StopBeingCaptured')
-- for AI events
self.Brain:OnUnitStopBeingCaptured(self, captor)
end,
---@param self Unit
---@param captor Unit
OnFailedBeingCaptured = function(self, captor)
self:RemoveCaptor(captor)
self:DoUnitCallbacks('OnFailedBeingCaptured', captor)
self:PlayUnitSound('FailedBeingCaptured')
-- for AI events
self.Brain:OnUnitFailedBeingCaptured(self, captor)
end,
---@param self Unit
---@param reclaimer Unit
OnReclaimed = function(self, reclaimer)
self:DoUnitCallbacks('OnReclaimed', reclaimer)
self.CreateReclaimEndEffects(reclaimer, self)
self:Destroy()
-- for AI events
self.Brain:OnUnitReclaimed(self, reclaimer)
end,
---@param self Unit
---@param unit Unit
OnStartRepair = function(self, unit)
unit.Repairers[self.EntityId] = self
if unit.WorkItem ~= self.WorkItem then
self:InheritWork(unit)
end
self:SetUnitState('Repairing', true)
-- Force assist over repair when unit is assisting something
if unit:GetFocusUnit() and unit:IsUnitState('Building') then
self:ForkThread(function()
self:CheckAssistFocus()
end)
end
-- for AI events
self.Brain:OnUnitStartRepair(self, unit)
end,
---@param self Unit
---@param unit Unit
OnStopRepair = function(self, unit)
unit.Repairers[self.EntityId] = nil
-- for AI events
self.Brain:OnUnitStopRepair(self, unit)
end,
---@param self Unit
---@param target Unit | Prop
OnStartReclaim = function(self, target)
-- When paused we reclaim at a speed of 0, with thanks to:
-- - https://github.com/FAForever/FA-Binary-Patches/pull/19
if not self:IsPaused() then
self:StartReclaimEffects(target)
self:PlayUnitSound('StartReclaim')
self:PlayUnitAmbientSound('ReclaimLoop')
end
self.EntityBeingReclaimed = target
self:SetUnitState('Reclaiming', true)
self:SetFocusEntity(target)
self:CheckAssistersFocus()
self:DoUnitCallbacks('OnStartReclaim', target)
-- Force me to move on to the guard properly when done
local guard = self:GetGuardedUnit()
if guard then
IssueToUnitClearCommands(self)
IssueReclaim({self}, target)
IssueGuard({self}, guard)
end
-- add state to be able to show the amount reclaimed in the UI
if target.IsProp then
self.OnStartReclaimPropStartTick = GetGameTick() + 2
local time, energy, mass = target:GetReclaimCosts(self)
self.OnStartReclaimPropTicksRequired = 10 * time
self.OnStartReclaimPropMass = mass
self.OnStartReclaimPropEnergy = energy
end
-- awareness of event for AI
self.Brain:OnUnitStartReclaim(self, target)
end,
--- Called when the unit stops reclaiming
---@param self Unit
---@param target Unit | Prop | nil # is nil when the prop or unit is completely reclaimed
OnStopReclaim = function(self, target)
self:DoUnitCallbacks('OnStopReclaim', target)
self:StopReclaimEffects(target)
self:StopUnitAmbientSound('ReclaimLoop')
self:PlayUnitSound('StopReclaim')
self:SetUnitState('Reclaiming', false)
self.EntityBeingReclaimed = nil
if target.IsProp then
target:UpdateReclaimLeft()
end
-- process the amount we reclaimed to show it in the UI
if self.OnStartReclaimPropStartTick then
local ticks = (GetGameTick() - self.OnStartReclaimPropStartTick)
-- can end up negative if another engineer finishes reclaiming the prop between us starting to reclaim, and actually reclaiming
if ticks > 0 then
-- completely consumed this prop
if ticks >= self.OnStartReclaimPropTicksRequired then
self.ReclaimedMass = self.ReclaimedMass + self.OnStartReclaimPropMass
self.ReclaimedEnergy = self.ReclaimedEnergy + self.OnStartReclaimPropEnergy
-- partially consumed the prop
else
local fraction = ticks / self.OnStartReclaimPropTicksRequired
self.ReclaimedMass = self.ReclaimedMass + fraction * self.OnStartReclaimPropMass
self.ReclaimedEnergy = self.ReclaimedEnergy + fraction * self.OnStartReclaimPropEnergy
end
end
-- update UI
self:UpdateStat('ReclaimedMass', self.ReclaimedMass)
self:UpdateStat('ReclaimedEnergy', self.ReclaimedEnergy)
end
-- reset reclaiming state
self.OnStartReclaimPropStartTick = nil
self.OnStartReclaimPropTicksRequired = nil
self.OnStartReclaimPropMass = nil
self.OnStartReclaimPropEnergy = nil
-- awareness of event for AI
self.Brain:OnUnitStopReclaim(self, target)
end,
---@param self Unit
---@param target Unit | Prop
StartReclaimEffects = function(self, target)
self.ReclaimEffectsBag = self.ReclaimEffectsBag or TrashBag()
self.ReclaimEffectsBag:Add(self:ForkThread(self.CreateReclaimEffects, target))
end,
---@param self Unit
---@param target Unit | Prop
CreateReclaimEffects = function(self, target)
EffectUtilities.PlayReclaimEffects(self, target, self.BuildEffectBones or {0, }, self.ReclaimEffectsBag)
end,
---@param self Unit
---@param target Unit | Prop
CreateReclaimEndEffects = function(self, target)
EffectUtilities.PlayReclaimEndEffects(self, target)
end,
---@param self Unit
---@param target Unit | Prop
StopReclaimEffects = function(self, target)
if self.ReclaimEffectsBag then
self.ReclaimEffectsBag:Destroy()
end
end,
---@param self Unit
OnDecayed = function(self)
self:Destroy()
end,
---@param self Unit
---@param captor Unit
OnCaptured = function(self, captor)
if self and not self.Dead and captor and not captor.Dead and self:GetAIBrain() ~= captor:GetAIBrain() then
if not self:IsCapturable() then
self:Kill()
return
end
-- Kill non-capturable things which are in a transport
if EntityCategoryContains(categories.TRANSPORTATION, self) then
local cargo = self:GetCargo()
for _, v in cargo do
if not v.Dead and not v:IsCapturable() then
v:Kill()
end
end
end
self:DoUnitCallbacks('OnCaptured', captor)
local newUnitCallbacks = {}
if self.EventCallbacks.OnCapturedNewUnit then
newUnitCallbacks = self.EventCallbacks.OnCapturedNewUnit
end
local captorBrain = false
-- Ignore army cap during unit transfer in Campaign
if ScenarioInfo.CampaignMode then
captorBrain = captor:GetAIBrain()
SetIgnoreArmyUnitCap(captor.Army, true)
end
if ScenarioInfo.CampaignMode and not captorBrain.IgnoreArmyCaps then
SetIgnoreArmyUnitCap(captor.Army, false)
end
-- Fix captured units not retaining their data
self:ResetCaptors()
local newUnits = SimUtils.TransferUnitsOwnership({self}, captor.Army, true) or {}
-- The unit transfer function returns a table of units. Since we transferred 1 unit, the table contains 1 unit (The new unit).
-- If table would have been nil (Set to {} above), was empty, or contains more than one, kill this sequence
if table.empty(newUnits) or table.getn(newUnits) ~= 1 then
return
end
local newUnit = newUnits[1]
-- Because the old unit is lost we cannot call a member function for newUnit callbacks
for _, cb in newUnitCallbacks do
if cb then
cb(newUnit, captor)
end
end
end
end,