-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy pathUnit.lua
4438 lines (3758 loc) · 162 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 Entity = import('/lua/sim/Entity.lua').Entity
local EffectTemplate = import('/lua/EffectTemplates.lua')
local explosion = import('/lua/defaultexplosions.lua')
local EffectUtilities = import('/lua/EffectUtilities.lua')
local Game = import('/lua/game.lua')
local utilities = import('/lua/utilities.lua')
local Shield = import('/lua/shield.lua').Shield
local PersonalBubble = import('/lua/shield.lua').PersonalBubble
local TransportShield = import('/lua/shield.lua').TransportShield
local PersonalShield = import('/lua/shield.lua').PersonalShield
local AntiArtilleryShield = import('/lua/shield.lua').AntiArtilleryShield
local Buff = import('/lua/sim/buff.lua')
local AIUtils = import('/lua/ai/aiutilities.lua')
local BuffFieldBlueprints = import('/lua/sim/BuffField.lua').BuffFieldBlueprints
local Wreckage = import('/lua/wreckage.lua')
local Set = import('/lua/system/setutils.lua')
local Factions = import('/lua/factions.lua').GetFactions(true)
local DeprecatedWarnings = { }
-- Localised category operations for performance
local UpdateAssistersConsumptionCats = categories.REPAIR - categories.INSIGNIFICANTUNIT -- anything that repairs but insignificant things, such as drones
-- Localised global functions for speed. ~10% for single references, ~30% for double (eg table.insert)
-- Deprecated function warning flags
local GetUnitBeingBuiltWarning = false
SyncMeta = {
__index = function(t, key)
local id = rawget(t, 'id')
return UnitData[id].Data[key]
end,
__newindex = function(t, key, val)
local id = rawget(t, 'id')
local army = rawget(t, 'army')
if not UnitData[id] then
UnitData[id] = {
OwnerArmy = rawget(t, 'army'),
Data = {}
}
end
UnitData[id].Data[key] = val
local focus = GetFocusArmy()
if army == focus or focus == -1 then -- Let observers get unit data
if not Sync.UnitData[id] then
Sync.UnitData[id] = {}
end
Sync.UnitData[id][key] = val
end
end,
}
Unit = Class(moho.unit_methods) {
Weapons = {},
FxScale = 1,
FxDamageScale = 1,
-- 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 = {},
EconomyProductionInitiallyActive = true,
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
-------------------------------------------------------------------------------------------
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)
if not self.Trash then
self.Trash = TrashBag()
end
self.IntelDisables = {
Radar = {NotInitialized = true},
Sonar = {NotInitialized = true},
Omni = {NotInitialized = true},
RadarStealth = {NotInitialized = true},
SonarStealth = {NotInitialized = true},
RadarStealthField = {NotInitialized = true},
SonarStealthField = {NotInitialized = true},
Cloak = {NotInitialized = true},
CloakField = {NotInitialized = true}, -- We really shouldn't use this. Cloak/Stealth fields are pretty busted
Spoof = {NotInitialized = true},
Jammer = {NotInitialized = true},
}
self.EventCallbacks = {
OnKilled = {},
OnUnitBuilt = {},
OnStartBuild = {},
OnReclaimed = {},
OnStartReclaim = {},
OnStopReclaim = {},
OnStopBeingBuilt = {},
OnHorizontalStartMove = {},
OnCaptured = {},
OnCapturedNewUnit = {},
OnDamaged = {},
OnStartCapture = {},
OnStopCapture = {},
OnFailedCapture = {},
OnStartBeingCaptured = {},
OnStopBeingCaptured = {},
OnFailedBeingCaptured = {},
OnFailedToBuild = {},
OnVeteran = {},
OnGiven = {},
ProjectileDamaged = {},
SpecialToggleEnableFunction = false,
SpecialToggleDisableFunction = false,
OnAttachedToTransport = {}, -- Returns self, transport, bone
OnDetachedFromTransport = {}, -- Returns self, transport, bone
}
end,
OnCreate = function(self)
Entity.OnCreate(self)
-- cache commonly used values from the engine
-- self.Layer = self:GetCurrentLayer() -- Not required: ironically OnLayerChange is called _before_ OnCreate is called!
-- Turn off land bones if this unit has them.
self:HideLandBones()
-- Set number of effects per damage depending on its volume
local x, y, z = self:GetUnitSizes()
local vol = x * y * z
self:ShowPresetEnhancementBones()
local damageamounts = 1
if vol >= 20 then
damageamounts = 6
self.FxDamageScale = 2
elseif vol >= 10 then
damageamounts = 4
self.FxDamageScale = 1.5
elseif vol >= 0.5 then
damageamounts = 2
end
self.FxDamage1Amount = self.FxDamage1Amount or damageamounts
self.FxDamage2Amount = self.FxDamage2Amount or damageamounts
self.FxDamage3Amount = self.FxDamage3Amount or damageamounts
self.DamageEffectsBag = {
{},
{},
{},
}
-- Set up effect emitter bags
self.MovementEffectsBag = {}
self.IdleEffectsBag = {}
self.TopSpeedEffectsBag = {}
self.BeamExhaustEffectsBag = {}
self.TransportBeamEffectsBag = {}
self.BuildEffectsBag = TrashBag()
self.ReclaimEffectsBag = TrashBag()
self.OnBeingBuiltEffectsBag = TrashBag()
self.CaptureEffectsBag = TrashBag()
self.UpgradeEffectsBag = TrashBag()
self.TeleportFxBag = TrashBag()
-- Store targets and attackers for proper Stealth management
self.Targets = {}
self.WeaponTargets = {}
self.WeaponAttackers = {}
-- Set up veterancy
self.xp = 0
self.Instigators = {}
self.totalDamageTaken = 0
self.debris_Vector = Vector(0, 0, 0)
local bp = self:GetBlueprint()
-- Save common lookup info
self.UnitId = self:GetUnitId()
self.techCategory = bp.TechCategory
self.layerCategory = bp.LayerCategory
self.factionCategory = bp.FactionCategory
-- 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)
if self.EconomyProductionInitiallyActive then
self:SetProductionActive(true)
end
self.Buffs = {
BuffTable = {},
Affects = {},
}
local bpVision = bp.Intel.VisionRadius
self:SetIntelRadius('Vision', bpVision or 0)
self:SetCanTakeDamage(true)
self:SetCanBeKilled(true)
local bpDeathAnim = bp.Display.AnimationDeath
if bpDeathAnim and not table.empty(bpDeathAnim) then
self.PlayDeathAnimation = true
end
-- Used for keeping track of resource consumption
self.MaintenanceConsumption = false
self.ActiveConsumption = false
self.ProductionEnabled = true
self.EnergyModifier = 0
self.MassModifier = 0
-- Cheating
if self:GetAIBrain().CheatEnabled then
AIUtils.ApplyCheatBuffs(self)
end
self.Dead = false
self:InitBuffFields()
self:OnCreated()
-- Ensure transport slots are available
self.attachmentBone = nil
-- Set up Adjacency container
self.AdjacentUnits = {}
self.Repairers = {}
end,
OnGotTarget = function(self, Weapon)
end,
OnLostTarget = function(self, Weapon)
end,
-------------------------------------------------------------------------------------------
---- MISC FUNCTIONS
-------------------------------------------------------------------------------------------
SetDead = function(self)
self.Dead = true
end,
IsDead = function(self)
return self.Dead
end,
GetCachePosition = function(self)
return self:GetPosition()
end,
GetFootPrintSize = function(self)
local fp = self:GetBlueprint().Footprint
return math.max(fp.SizeX, fp.SizeZ)
end,
-- Returns 4 numbers: skirt x0, skirt z0, skirt.x1, skirt.z1
GetSkirtRect = function(self)
local bp = self:GetBlueprint()
local x, y, z = unpack(self:GetPosition())
local fx = x - bp.Footprint.SizeX * .5
local fz = z - bp.Footprint.SizeZ * .5
local sx = fx + bp.Physics.SkirtOffsetX
local sz = fz + bp.Physics.SkirtOffsetZ
return sx, sz, sx + bp.Physics.SkirtSizeX, sz + bp.Physics.SkirtSizeZ
end,
-- Returns collision box size
GetUnitSizes = function(self)
local bp = self:GetBlueprint()
return bp.SizeX, bp.SizeY, bp.SizeZ
end,
GetRandomOffset = function(self, scalar)
local sx, sy, sz = self:GetUnitSizes()
local heading = self:GetHeading()
sx = sx * scalar
sy = sy * scalar
sz = sz * scalar
local rx = Random() * sx - (sx * 0.5)
local y = Random() * sy + (self:GetBlueprint().CollisionOffsetY or 0)
local rz = Random() * sz - (sz * 0.5)
local x = math.cos(heading) * rx - math.sin(heading) * rz
local z = math.sin(heading) * rx - math.cos(heading) * rz
return x, y, z
end,
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,
SetTargetPriorities = function(self, priTable)
for i = 1, self:GetWeaponCount() do
local wep = self:GetWeapon(i)
wep:SetWeaponPriorities(priTable)
end
end,
SetLandTargetPriorities = function(self, priTable)
for i = 1, self:GetWeaponCount() do
local wep = self:GetWeapon(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
UpdateBuildRestrictions = function(self)
-- retrieve info of factory
local faction = self.factionCategory
local layer = self.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,
-- Deprecation / refactored warning for mods.
updateBuildRestrictions = function(self)
if not DeprecatedWarnings.updateBuildRestrictions then
WARN("updateBuildRestrictions is refactored since PR #3319. Call UpdateBuildRestrictions instead.")
DeprecatedWarnings.updateBuildRestrictions = true
end
-- call the old function
self.UpdateBuildRestrictions(self)
end,
-- Deprecation warning for mods.
FindHQType = function(aiBrain, category)
if not DeprecatedWarnings.FindHQType then
WARN("FindHQType is deprecated since PR #3319.")
DeprecatedWarnings.FindHQType = true
end
end,
-------------------------------------------------------------------------------------------
---- TOGGLES
-------------------------------------------------------------------------------------------
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,
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,
OnPaused = function(self)
if self:IsUnitState('Building') or self:IsUnitState('Upgrading') or self:IsUnitState('Repairing') then
self:SetActiveConsumptionInactive()
self:StopUnitAmbientSound('ConstructLoop')
end
end,
OnUnpaused = function(self)
if self:IsUnitState('Building') or self:IsUnitState('Upgrading') or self:IsUnitState('Repairing') then
self:SetActiveConsumptionActive()
self:PlayUnitAmbientSound('ConstructLoop')
end
end,
EnableSpecialToggle = function(self)
if self.EventCallbacks.SpecialToggleEnableFunction then
self.EventCallbacks.SpecialToggleEnableFunction(self)
end
end,
DisableSpecialToggle = function(self)
if self.EventCallbacks.SpecialToggleDisableFunction then
self.EventCallbacks.SpecialToggleDisableFunction(self)
end
end,
AddSpecialToggleEnable = function(self, fn)
if fn then
self.EventCallbacks.SpecialToggleEnableFunction = fn
end
end,
AddSpecialToggleDisable = function(self, fn)
if fn then
self.EventCallbacks.SpecialToggleDisableFunction = fn
end
end,
EnableDefaultToggleCaps = function(self)
if self.ToggleCaps then
for _, v in self.ToggleCaps do
self:AddToggleCap(v)
end
end
end,
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
-------------------------------------------------------------------------------------------
OnSpecialAction = function(self, location)
end,
OnProductionActive = function(self)
end,
OnActive = function(self)
end,
OnInactive = function(self)
end,
OnStartCapture = function(self, target)
self:DoUnitCallbacks('OnStartCapture', target)
self:StartCaptureEffects(target)
self:PlayUnitSound('StartCapture')
self:PlayUnitAmbientSound('CaptureLoop')
end,
OnStopCapture = function(self, target)
self:DoUnitCallbacks('OnStopCapture', target)
self:StopCaptureEffects(target)
self:PlayUnitSound('StopCapture')
self:StopUnitAmbientSound('CaptureLoop')
end,
StartCaptureEffects = function(self, target)
self.CaptureEffectsBag:Add(self:ForkThread(self.CreateCaptureEffects, target))
end,
CreateCaptureEffects = function(self, target)
end,
StopCaptureEffects = function(self, target)
self.CaptureEffectsBag:Destroy()
end,
OnFailedCapture = function(self, target)
self:DoUnitCallbacks('OnFailedCapture', target)
self:StopCaptureEffects(target)
self:StopUnitAmbientSound('CaptureLoop')
self:PlayUnitSound('FailedCapture')
end,
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,
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,
ResetCaptors = function(self)
if self.CaptureThread then
KillThread(self.CaptureThread)
end
self.Captors = {}
self.CaptureThread = nil
self.CaptureProgress = nil
end,
RemoveCaptor = function(self, captor)
self.Captors[captor.EntityId] = nil
if table.empty(self.Captors) then
self:ResetCaptors()
end
end,
OnStartBeingCaptured = function(self, captor)
self:AddCaptor(captor)
self:DoUnitCallbacks('OnStartBeingCaptured', captor)
self:PlayUnitSound('StartBeingCaptured')
end,
OnStopBeingCaptured = function(self, captor)
self:RemoveCaptor(captor)
self:DoUnitCallbacks('OnStopBeingCaptured', captor)
self:PlayUnitSound('StopBeingCaptured')
end,
OnFailedBeingCaptured = function(self, captor)
self:RemoveCaptor(captor)
self:DoUnitCallbacks('OnFailedBeingCaptured', captor)
self:PlayUnitSound('FailedBeingCaptured')
end,
OnReclaimed = function(self, entity)
self:DoUnitCallbacks('OnReclaimed', entity)
self.CreateReclaimEndEffects(entity, self)
self:Destroy()
end,
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
end,
OnStopRepair = function(self, unit)
end,
OnStartReclaim = function(self, target)
self:SetUnitState('Reclaiming', true)
self:SetFocusEntity(target)
self:CheckAssistersFocus()
self:DoUnitCallbacks('OnStartReclaim', target)
self:StartReclaimEffects(target)
self:PlayUnitSound('StartReclaim')
self:PlayUnitAmbientSound('ReclaimLoop')
-- Force me to move on to the guard properly when done
local guard = self:GetGuardedUnit()
if guard then
IssueClearCommands({self})
IssueReclaim({self}, target)
IssueGuard({self}, guard)
end
end,
OnStopReclaim = function(self, target)
self:DoUnitCallbacks('OnStopReclaim', target)
self:StopReclaimEffects(target)
self:StopUnitAmbientSound('ReclaimLoop')
self:PlayUnitSound('StopReclaim')
self:SetUnitState('Reclaiming', false)
if target.MaxMassReclaim then -- This is a prop
target:UpdateReclaimLeft()
end
end,
StartReclaimEffects = function(self, target)
self.ReclaimEffectsBag:Add(self:ForkThread(self.CreateReclaimEffects, target))
end,
CreateReclaimEffects = function(self, target)
end,
CreateReclaimEndEffects = function(self, target)
end,
StopReclaimEffects = function(self, target)
self.ReclaimEffectsBag:Destroy()
end,
OnDecayed = function(self)
self:Destroy()
end,
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 = import('/lua/SimUtils.lua').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,
OnGiven = function(self, newUnit)
newUnit:SendNotifyMessage('transferred')
self:DoUnitCallbacks('OnGiven', newUnit)
end,
AddOnGivenCallback = function(self, fn)
self:AddUnitCallback(fn, 'OnGiven')
end,
-------------------------------------------------------------------------------------------
-- ECONOMY
-------------------------------------------------------------------------------------------
OnConsumptionActive = function(self)
end,
OnConsumptionInActive = function(self)
end,
-- We are splitting Consumption into two catagories:
-- Maintenance -- for units that are usually "on": radar, mass extractors, etc.
-- Active -- when upgrading, constructing, or something similar.
--
-- It will be possible for both or neither of these consumption methods to be
-- in operation at the same time. Here are the functions to turn them off and on.
SetMaintenanceConsumptionActive = function(self)
self.MaintenanceConsumption = true
self:UpdateConsumptionValues()
end,
SetMaintenanceConsumptionInactive = function(self)
self.MaintenanceConsumption = false
self:UpdateConsumptionValues()
end,
SetActiveConsumptionActive = function(self)
self.ActiveConsumption = true
self:UpdateConsumptionValues()
end,
SetActiveConsumptionInactive = function(self)
self.ActiveConsumption = false
self:UpdateConsumptionValues()
end,
OnProductionPaused = function(self)
self:SetMaintenanceConsumptionInactive()
self:SetProductionActive(false)
end,
OnProductionUnpaused = function(self)
self:SetMaintenanceConsumptionActive()
self:SetProductionActive(true)
end,
SetBuildTimeMultiplier = function(self, time_mult)
self.BuildTimeMultiplier = time_mult
end,
GetMassBuildAdjMod = function(self)
return self.MassBuildAdjMod or 1
end,
GetEnergyBuildAdjMod = function(self)
return self.EnergyBuildAdjMod or 1
end,
GetEconomyBuildRate = function(self)
return self:GetBuildRate()
end,
GetBuildRate = function(self)
return math.max(moho.unit_methods.GetBuildRate(self), 0.00001) -- Make sure we're never returning 0, this value will be used to divide with
end,
UpdateAssistersConsumption = function(self)
local units = {}
-- We need to check all the units assisting.
for _, v in self:GetGuards() do
if not v.Dead and (v:IsUnitState('Building') or v:IsUnitState('Repairing')) then
table.insert(units, v)
end
end
local workers = self:GetAIBrain():GetUnitsAroundPoint(UpdateAssistersConsumptionCats, self:GetPosition(), 50, 'Ally')
for _, v in workers do
if not v.Dead and v:IsUnitState('Repairing') and v:GetFocusUnit() == self then
table.insert(units, v)
end
end
for _, v in units do
if not v.updatedConsumption then
v.updatedConsumption = true -- Recursive protection
v:UpdateConsumptionValues()
v.updatedConsumption = false
end
end
end,
-- Called when we start building a unit, turn on/off, get/lose bonuses, or on
-- any other change that might affect our build rate or resource use.
UpdateConsumptionValues = function(self)
local energy_rate = 0
local mass_rate = 0
if self.ActiveConsumption then
local focus = self:GetFocusUnit()
local time = 1
local mass = 0
local energy = 0
local targetData
local baseData
local repairRatio = 0.75
if focus then -- Always inherit work status of focus
self:InheritWork(focus)
end
if self.WorkItem then -- Enhancement
targetData = self.WorkItem
elseif focus then -- Handling upgrades
if self:IsUnitState('Upgrading') then
baseData = self:GetBlueprint().Economy -- Upgrading myself, subtract ev. baseCost
elseif focus.originalBuilder and not focus.originalBuilder.Dead and focus.originalBuilder:IsUnitState('Upgrading') and focus.originalBuilder:GetFocusUnit() == focus then
baseData = focus.originalBuilder:GetBlueprint().Economy
end
if baseData then
targetData = focus:GetBlueprint().Economy
end
end
if targetData then -- Upgrade/enhancement
time, energy, mass = Game.GetConstructEconomyModel(self, targetData, baseData)
elseif focus then -- Building/repairing something
if focus:IsUnitState('SiloBuildingAmmo') then
local siloBuildRate = focus:GetBuildRate() or 1
time, energy, mass = focus:GetBuildCosts(focus.SiloProjectile)
energy = (energy / siloBuildRate) * (self:GetBuildRate() or 1)
mass = (mass / siloBuildRate) * (self:GetBuildRate() or 1)
else
time, energy, mass = self:GetBuildCosts(focus:GetBlueprint())
if self:IsUnitState('Repairing') and focus.isFinishedUnit then
energy = energy * repairRatio
mass = mass * repairRatio
end
end
end
energy = math.max(1, energy * (self.EnergyBuildAdjMod or 1))
mass = math.max(1, mass * (self.MassBuildAdjMod or 1))
energy_rate = energy / time
mass_rate = mass / time
end
self:UpdateAssistersConsumption()
local myBlueprint = self:GetBlueprint()
if self.MaintenanceConsumption then
local mai_energy = (self.EnergyMaintenanceConsumptionOverride or myBlueprint.Economy.MaintenanceConsumptionPerSecondEnergy) or 0
local mai_mass = myBlueprint.Economy.MaintenanceConsumptionPerSecondMass or 0
-- Apply economic bonuses
mai_energy = mai_energy * (100 + self.EnergyModifier) * (self.EnergyMaintAdjMod or 1) * 0.01
mai_mass = mai_mass * (100 + self.MassModifier) * (self.MassMaintAdjMod or 1) * 0.01
energy_rate = energy_rate + mai_energy
mass_rate = mass_rate + mai_mass
end
-- Apply minimum rates
energy_rate = math.max(energy_rate, myBlueprint.Economy.MinConsumptionPerSecondEnergy or 0)
mass_rate = math.max(mass_rate, myBlueprint.Economy.MinConsumptionPerSecondMass or 0)
self:SetConsumptionPerSecondEnergy(energy_rate)
self:SetConsumptionPerSecondMass(mass_rate)
self:SetConsumptionActive(energy_rate > 0 or mass_rate > 0)
end,
UpdateProductionValues = function(self)
local bpEcon = self:GetBlueprint().Economy
if not bpEcon then return end