forked from FAForever/fa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaibrain.lua
5130 lines (4595 loc) · 201 KB
/
aibrain.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/aibrain.lua
-- Author(s):
-- Summary :
-- Copyright Š 2005 Gas Powered Games, Inc. All rights reserved.
-----------------------------------------------------------------
-- AIBrain Lua Module
local AIDefaultPlansList = import("/lua/aibrainplans.lua").AIPlansList
local AIUtils = import("/lua/ai/aiutilities.lua")
local Utilities = import("/lua/utilities.lua")
local ScenarioUtils = import("/lua/sim/scenarioutilities.lua")
local Behaviors = import("/lua/ai/aibehaviors.lua")
local AIBuildUnits = import("/lua/ai/aibuildunits.lua")
local FactoryManager = import("/lua/sim/factorybuildermanager.lua")
local PlatoonFormManager = import("/lua/sim/platoonformmanager.lua")
local BrainConditionsMonitor = import("/lua/sim/brainconditionsmonitor.lua")
local EngineerManager = import("/lua/sim/engineermanager.lua")
local SUtils = import("/lua/ai/sorianutilities.lua")
local StratManager = import("/lua/sim/strategymanager.lua")
local TransferUnitsOwnership = import("/lua/simutils.lua").TransferUnitsOwnership
local TransferUnfinishedUnitsAfterDeath = import("/lua/simutils.lua").TransferUnfinishedUnitsAfterDeath
local CalculateBrainScore = import("/lua/sim/score.lua").CalculateBrainScore
local Factions = import('/lua/factions.lua').GetFactions(true)
-- upvalue for performance
local BrainGetUnitsAroundPoint = moho.aibrain_methods.GetUnitsAroundPoint
local BrainGetListOfUnits = moho.aibrain_methods.GetListOfUnits
local GetEconomyIncome = moho.aibrain_methods.GetEconomyIncome
local GetEconomyRequested = moho.aibrain_methods.GetEconomyRequested
local GetEconomyTrend = moho.aibrain_methods.GetEconomyTrend
local CategoriesDummyUnit = categories.DUMMYUNIT
local CoroutineYield = coroutine.yield
local TableGetn = table.getn
---@class TriggerSpec
---@field Callback function
---@field ReconTypes ReconTypes
---@field Blip boolean
---@field Value boolean
---@field Category EntityCategory
---@field OnceOnly boolean
---@field TargetAIBrain AIBrain
--TODO
---@class PlatoonTable
---@alias AIResult "defeat" | "draw" | "victor"
---@alias HqTech "TECH2" | "TECH3"
---@alias HqLayer "AIR" | "LAND" | "NAVY"
---@alias HqFaction "UEF" | "AEON" | "CYBRAN" | "SERAPHIM" | "NOMADS"
---@alias BrainState "Defeat" | "Draw" | "InProgress" | "Recalled" | "Victory"
---@alias BrainType "AI" | "Human"
---@alias ReconTypes 'Radar' | 'Sonar' | 'Omni' | 'LOSNow'
---@alias PlatoonType 'Air' | 'Land' | 'Sea'
---@alias AllianceStatus 'Ally' | 'Enemy' | 'Neutral'
---@class AIBrain: moho.aibrain_methods
---@field Army number
---@field AIPlansList string[][]
---@field AirAttackPoints? table
---@field AttackData AttackManager
---@field AttackManager AttackManager
---@field AttackPoints? table
---@field BaseMonitor AiBaseMonitor
---@field BrainType BrainType
---@field BuilderManagers table<string, table>
---@field ConditionsMonitor BrainConditionsMonitor
---@field ConstantEval boolean
---@field CurrentPlan string lua file which contains plan
---@field CurrentPlanScript table
---@field EconomyCurrentTick number
---@field EconomyData {EnergyIncome: number, EnergyRequested: number, MassIncome: number, MassRequested: number}[]
---@field EnergyExcessThread thread
---@field EnergyExcessUnitsEnabled table<EntityId, MassFabricationUnit>
---@field EnergyExcessUnitsDisabled table<EntityId, MassFabricationUnit>
---@field EnergyDependingUnits table<EntityId, Unit | Shield>
---@field EnergyDepleted boolean
---@field EconomyTicksMonitor number
---@field HasPlatoonList boolean
---@field HQs table<HqFaction, table<HqLayer, table<HqTech, number>>>
---@field IntelData? table<string, number>
---@field IntelTriggerList table
---@field LayerPref "LAND" | "AIR"
---@field Name string
---@field PBM AiPlatoonBuildManager
---@field PingCallbackList table
---@field PlatoonNameCounter? table<string, number>
---@field Radars table<string, Unit[]>
---@field RepeatExecution boolean
---@field Result? AIResult
---@field SelfMonitor AiSelfMonitor
---@field Sorian boolean
---@field Status BrainState
---@field T4ThreatFound? table
---@field TacticalBases? table
---@field targetoveride boolean
---@field Team number The team this brain's army belongs to. Note that games with unlocked teams behave like free-for-alls.
---@field Trash TrashBag
---@field TriggerList table
---@field UnitBuiltTriggerList table
---@field UnitStats table<EntityId, table<string, number>>
---@field VeterancyTriggerList table
AIBrain = Class(moho.aibrain_methods) {
-- The state of the brain in the match
Status = 'InProgress',
--- HUMAN BRAIN FUNCTIONS HANDLED HERE
---@param self AIBrain
---@param planName string
OnCreateHuman = function(self, planName)
self:CreateBrainShared(planName)
self.BrainType = 'Human'
-- human-only behavior
self.EnergyExcessThread = ForkThread(self.ToggleEnergyExcessUnitsThread, self)
end,
---@param self AIBrain
---@param unitId UnitId
---@param statName string
---@param value number
AddUnitStat = function(self, unitId, statName, value)
if self.UnitStats[unitId] == nil then
self.UnitStats[unitId] = {}
end
if self.UnitStats[unitId][statName] == nil then
self.UnitStats[unitId][statName] = value
else
self.UnitStats[unitId][statName] = self.UnitStats[unitId][statName] + value
end
end,
---@param self AIBrain
---@param unitId EntityId
---@param statName string
---@param value number
SetUnitStat = function(self, unitId, statName, value)
if self.UnitStats[unitId] == nil then
self.UnitStats[unitId] = {}
end
self.UnitStats[unitId][statName] = value
end,
---@param self AIBrain
---@param unitId EntityId
---@param statName string
---@return number
GetUnitStat = function(self, unitId, statName)
if self.UnitStats[unitId] == nil or self.UnitStats[unitId][statName] == nil then
return 0
end
return self.UnitStats[unitId][statName]
end,
---@param self AIBrain
GetUnitStats = function(self)
return self.UnitStats
end,
---@param self AIBrain
---@param planName string
OnCreateAI = function(self, planName)
self:CreateBrainShared(planName)
local civilian = false
for name, data in ScenarioInfo.ArmySetup do
if name == self.Name then
civilian = data.Civilian
break
end
end
if not civilian then
local per = ScenarioInfo.ArmySetup[self.Name].AIPersonality
-- Flag this brain as a possible brain to have skirmish systems enabled on
self.SkirmishSystems = true
local cheatPos = string.find(per, 'cheat')
if cheatPos then
AIUtils.SetupCheat(self, true)
ScenarioInfo.ArmySetup[self.Name].AIPersonality = string.sub(per, 1, cheatPos - 1)
end
LOG('* OnCreateAI: AIPersonality: ('..per..')')
if string.find(per, 'sorian') then
self.Sorian = true
end
if DiskGetFileInfo('/lua/AI/altaiutilities.lua') then
self.Duncan = true
end
self.CurrentPlan = self.AIPlansList[self:GetFactionIndex()][1]
self:ForkThread(self.InitialAIThread)
self.PlatoonNameCounter = {}
self.PlatoonNameCounter['AttackForce'] = 0
self.BaseTemplates = {}
self.RepeatExecution = true
self.IntelData = {
ScoutCounter = 0,
}
-- Flag enemy starting locations with threat?
if ScenarioInfo.type == 'skirmish' then
if self.Sorian then
-- Gives the initial threat a type so initial land platoons will actually attack it.
self:AddInitialEnemyThreatSorian(200, 0.005, 'Economy')
else
self:AddInitialEnemyThreat(200, 0.005)
end
end
end
self.UnitBuiltTriggerList = {}
self.FactoryAssistList = {}
self.DelayEqualBuildPlattons = {}
self.BrainType = 'AI'
end,
IsBaseAI = function(self)
return ScenarioInfo.ArmySetup[self.Name].BaseAI
end,
--- Adds a HQ so that the engi mod knows we have it
---@param self AIBrain
---@param faction HqFaction
---@param layer HqLayer
---@param tech HqTech
AddHQ = function (self, faction, layer, tech)
self.HQs[faction][layer][tech] = self.HQs[faction][layer][tech] + 1
end,
--- Removes an HQ so that the engi mod knows we lost it for the engi mod.
---@param self AIBrain
---@param faction HqFaction
---@param layer HqLayer
---@param tech HqTech
RemoveHQ = function (self, faction, layer, tech)
self.HQs[faction][layer][tech] = math.max(0, self.HQs[faction][layer][tech] - 1)
end,
--- Completely re evaluates the support factory restrictions of the engi mod
---@param self AIBrain
ReEvaluateHQSupportFactoryRestrictions = function (self)
local layers = { "AIR", "LAND", "NAVAL" }
local factions = { "UEF", "AEON", "CYBRAN", "SERAPHIM" }
if categories.NOMADS then
table.insert(factions, 'NOMADS')
end
for _, faction in factions do
for _, layer in layers do
self:SetHQSupportFactoryRestrictions(faction, layer)
end
end
end,
--- Manages the support factory restrictions of the engi mod
---@param self AIBrain
---@param faction HqFaction
---@param layer HqLayer
SetHQSupportFactoryRestrictions = function (self, faction, layer)
-- localize for performance
local army = self:GetArmyIndex()
-- the pessimists we are, restrict everything!
AddBuildRestriction(army, categories[faction] * categories[layer] * categories["TECH2"] * categories.SUPPORTFACTORY)
AddBuildRestriction(army, categories[faction] * categories[layer] * categories["TECH3"] * categories.SUPPORTFACTORY)
-- lift t2 / t3 support factory restrictions
if self.HQs[faction][layer]["TECH3"] > 0 then
RemoveBuildRestriction(army, categories[faction] * categories[layer] * categories["TECH2"] * categories.SUPPORTFACTORY)
RemoveBuildRestriction(army, categories[faction] * categories[layer] * categories["TECH3"] * categories.SUPPORTFACTORY)
end
-- lift t2 support factory restrictions
if self.HQs[faction][layer]["TECH2"] > 0 then
RemoveBuildRestriction(army, categories[faction] * categories[layer] * categories["TECH2"] * categories.SUPPORTFACTORY)
end
end,
--- Counts all HQs of specific faction, layer and tech for the engi mod.
---@param self AIBrain
---@param faction HqFaction
---@param layer HqLayer
---@param tech HqTech
---@return number
CountHQs = function (self, faction, layer, tech)
return self.HQs[faction][layer][tech]
end,
--- Counts all HQs of faction and tech, regardless of layer
---@param self AIBrain
---@param faction HqFaction
---@param tech HqTech
---@return number
CountHQsAllLayers = function (self, faction, tech)
local count = self.HQs[faction]["LAND"][tech]
count = count + self.HQs[faction]["AIR"][tech]
count = count + self.HQs[faction]["NAVAL"][tech]
return count
end,
---@param self AIBrain
---@param planName string
CreateBrainShared = function(self, planName)
-- make sure there is always some storage
self:GiveStorage('Energy', 100)
-- make sure the army stats exist
self:SetArmyStat('Economy_Ratio_Mass', 1.0)
self:SetArmyStat('Economy_Ratio_Energy', 1.0)
-- add initial trigger and assume we're not depleted
self:SetArmyStatsTrigger('Economy_Ratio_Energy', 'EnergyDepleted', 'LessThanOrEqual', 0.0)
self.EnergyDepleted = false
self.EnergyDependingUnits = setmetatable({ }, { __mode = 'v' })
--- Units that we toggle on / off depending on whether we have excess energy
self.EnergyExcessConsumed = 0
self.EnergyExcessRequired = 0
self.EnergyExcessConverted = 0
self.EnergyExcessUnitsEnabled = { }
setmetatable(self.EnergyExcessUnitsEnabled, { __mode = 'v' })
self.EnergyExcessUnitsDisabled = { }
setmetatable(self.EnergyExcessUnitsDisabled, { __mode = 'v' })
-- they are capitalized to match category names
local layers = { "LAND", "AIR", "NAVAL" }
local techs = { "TECH2", "TECH3" }
self.Jammers = { }
setmetatable(self.Jammers, { __mode = 'v' })
self.JammerResetTime = 15
ForkThread(self.JammingToggleThread, self)
-- populate the possible HQs per faction, layer and tech
self.HQs = { }
for _, facData in Factions do
local faction = facData.Category
self.HQs[faction] = { }
for _, layer in layers do
self.HQs[faction][layer] = { }
for _, tech in techs do
self.HQs[faction][layer][tech] = 0
end
end
end
-- keep track of radars
self.Radars = {
TECH1 = { },
TECH2 = { },
TECH3 = { },
EXPERIMENTAL = { },
}
-- restrict all support factories by default
AddBuildRestriction(self:GetArmyIndex(), (categories.TECH3 + categories.TECH2) * categories.SUPPORTFACTORY)
-- end of engi mod
self.Army = self:GetArmyIndex()
self.Result = nil -- No-op, just to be explicit it starts as nil
self.StatsSent = false
self.UnitStats = {}
self.Trash = TrashBag()
local aiScenarioPlans = self:ImportScenarioArmyPlans(planName)
if aiScenarioPlans then
self.AIPlansList = aiScenarioPlans
else
self.DefaultPlan = true
self.AIPlansList = AIDefaultPlansList
end
self.RepeatExecution = false
if ScenarioInfo.type == 'campaign' then
self:SetResourceSharing(false)
end
self.ConstantEval = true
self.IgnoreArmyCaps = false
self.TriggerList = {}
self.IntelTriggerList = {}
self.VeterancyTriggerList = {}
self.PingCallbackList = {}
self.UnitBuiltTriggerList = {}
self.VOTable = {}
end,
---@param self AIBrain
OnSpawnPreBuiltUnits = function(self)
local factionIndex = self:GetFactionIndex()
local resourceStructures = nil
local initialUnits = nil
local posX, posY = self:GetArmyStartPos()
if factionIndex == 1 then
resourceStructures = {'UEB1103', 'UEB1103', 'UEB1103', 'UEB1103'}
initialUnits = {'UEB0101', 'UEB1101', 'UEB1101', 'UEB1101', 'UEB1101'}
elseif factionIndex == 2 then
resourceStructures = {'UAB1103', 'UAB1103', 'UAB1103', 'UAB1103'}
initialUnits = {'UAB0101', 'UAB1101', 'UAB1101', 'UAB1101', 'UAB1101'}
elseif factionIndex == 3 then
resourceStructures = {'URB1103', 'URB1103', 'URB1103', 'URB1103'}
initialUnits = {'URB0101', 'URB1101', 'URB1101', 'URB1101', 'URB1101'}
elseif factionIndex == 4 then
resourceStructures = {'XSB1103', 'XSB1103', 'XSB1103', 'XSB1103'}
initialUnits = {'XSB0101', 'XSB1101', 'XSB1101', 'XSB1101', 'XSB1101'}
end
if resourceStructures then
-- Place resource structures down
for k, v in resourceStructures do
local unit = self:CreateResourceBuildingNearest(v, posX, posY)
end
end
if initialUnits then
-- Place initial units down
for k, v in initialUnits do
local unit = self:CreateUnitNearSpot(v, posX, posY)
end
end
self.PreBuilt = true
end,
--- Jamming Switch Logic
--- Adds a unit to a list of all units with jammers
---@param self AIBrain
---@param unit Unit Jammer unit
TrackJammer = function(self, unit)
self.Jammers[unit.EntityId] = unit
end,
--- Removes a unit to a list of all units with jammers
---@param self AIBrain
---@param unit Unit Jammer unit
UntrackJammer = function(self, unit)
self.Jammers[unit.EntityId] = nil
end,
--- Creates a thread that interates over all jammer units to reset them when vision is lost on them
---@param self AIBrain
JammingToggleThread = function(self)
while true do
for i, jammer in self.Jammers do
if jammer.ResetJammer == 0 then
self:ForkThread(self.JammingFollowUpThread, jammer)
jammer.ResetJammer = -1
else
if jammer.ResetJammer > 0 then
jammer.ResetJammer = jammer.ResetJammer - 1
end
end
end
WaitSeconds(1)
end
end,
--- Toggles a given unit's jammer
---@param self AIBrain
---@param unit Unit Jammer to be toggled
JammingFollowUpThread = function(self, unit)
unit:DisableUnitIntel('AutoToggle', 'Jammer')
WaitSeconds(1)
if not unit:BeenDestroyed() then
unit:EnableUnitIntel('AutoToggle', 'Jammer')
unit.ResetJammer = -1
end
end,
-- Energy storage callbacks
--- Adds a unit that is enabled / disabled depending on how much energy storage we have. The unit starts enabled
---@param self AIBrain The brain itself
---@param unit MassFabricationUnit The unit to keep track of
AddEnabledEnergyExcessUnit = function (self, unit)
self.EnergyExcessUnitsEnabled[unit.EntityId] = unit
self.EnergyExcessUnitsDisabled[unit.EntityId] = nil
local ecobp = unit.Blueprint.Economy
self.EnergyExcessConsumed = self.EnergyExcessConsumed + ecobp.MaintenanceConsumptionPerSecondEnergy
self.EnergyExcessConverted = self.EnergyExcessConverted + ecobp.ProductionPerSecondMass
end,
--- Adds a unit that is enabled / disabled depending on how much energy storage we have. The unit starts disabled
---@param self AIBrain
---@param unit MassFabricationUnit The unit to keep track of
AddDisabledEnergyExcessUnit = function (self, unit)
self.EnergyExcessUnitsEnabled[unit.EntityId] = nil
self.EnergyExcessUnitsDisabled[unit.EntityId] = unit
self.EnergyExcessRequired = self.EnergyExcessRequired + unit.Blueprint.Economy.MaintenanceConsumptionPerSecondEnergy
end,
--- Removes a unit that is enabled / disabled depending on how much energy storage we have
---@param self AIBrain
---@param unit MassFabricationUnit The unit to forget about
RemoveEnergyExcessUnit = function (self, unit)
local ecobp = unit.Blueprint.Economy
if self.EnergyExcessUnitsEnabled[unit.EntityId] then
self.EnergyExcessConsumed = self.EnergyExcessConsumed - ecobp.MaintenanceConsumptionPerSecondEnergy
self.EnergyExcessConverted = self.EnergyExcessConverted - ecobp.ProductionPerSecondMass
self.EnergyExcessUnitsEnabled[unit.EntityId] = nil
elseif self.EnergyExcessUnitsDisabled[unit.EntityId] then
self.EnergyExcessRequired = self.EnergyExcessRequired - ecobp.MaintenanceConsumptionPerSecondEnergy
self.EnergyExcessUnitsDisabled[unit.EntityId] = nil
end
end,
--- A continious thread that across the life span of the brain. Is the heart and sole of the enabling and disabling of units that are designed to eliminate excess energy.
---@param self AIBrain
ToggleEnergyExcessUnitsThread = function (self)
-- allow for protected calls without closures
---@param unitToProcess MassFabricationUnit
local function ProtectedOnExcessEnergy(unitToProcess)
unitToProcess:OnExcessEnergy()
end
---@param unitToProcess MassFabricationUnit
local function ProtectedOnNoExcessEnergy(unitToProcess)
unitToProcess:OnNoExcessEnergy()
end
local fabricatorParameters = import("/lua/shared/fabricatorbehaviorparams.lua")
local disableRatio = fabricatorParameters.DisableRatio
local disableStorage = fabricatorParameters.DisableStorage
local enableRatio = fabricatorParameters.EnableRatio
local enableTrend = fabricatorParameters.EnableTrend
local enableStorage = fabricatorParameters.EnableStorage
-- localize scope for better performance
local pcall = pcall
local TableSize = table.getsize
local CoroutineYield = CoroutineYield
local ok, msg
-- Instead of creating a new sync table each tick, we'll reuse two tables as a double
-- buffer: one table represents the data from the current tick, the other the data last
-- synced. We only send the data when one field in the current tick differs from the last
-- data synced, and then swap the two tables when that happens.
local syncTable = {
on = 0,
off = 0,
totalEnergyConsumed = 0,
totalEnergyRequired = 0,
totalMassProduced = 0,
}
local lastSyncTable = {
on = 0,
off = 0,
totalEnergyConsumed = 0,
totalEnergyRequired = 0,
totalMassProduced = 0,
}
local EnergyExcessUnitsDisabled = self.EnergyExcessUnitsDisabled
local EnergyExcessUnitsEnabled = self.EnergyExcessUnitsEnabled
while true do
local energyStoredRatio = self:GetEconomyStoredRatio('ENERGY')
local energyStored = self:GetEconomyStored('ENERGY')
local energyTrend = 10 * self:GetEconomyTrend('ENERGY')
-- low on storage, start disabling them to fill our storages asap
if energyStoredRatio < disableRatio and energyStored < disableStorage then
-- while we have units to disable
for id, unit in EnergyExcessUnitsEnabled do
if not unit:BeenDestroyed() then
local ecobp = unit.Blueprint.Economy
self.EnergyExcessConsumed = self.EnergyExcessConsumed - ecobp.MaintenanceConsumptionPerSecondEnergy
self.EnergyExcessRequired = self.EnergyExcessRequired + ecobp.MaintenanceConsumptionPerSecondEnergy
self.EnergyExcessConverted = self.EnergyExcessConverted - ecobp.ProductionPerSecondMass
-- update internal state
EnergyExcessUnitsDisabled[id] = unit
EnergyExcessUnitsEnabled[id] = nil
-- try to disable unit
ok, msg = pcall(unit.OnNoExcessEnergy, unit)
-- allow for debugging
if not ok then
WARN("ToggleEnergyExcessUnitsThread: " .. repr(msg))
end
break
end
end
-- high on storage and sufficient energy income, enable units
elseif (energyStoredRatio >= enableRatio and energyTrend > enableTrend) or energyStored > enableStorage then
-- while we have units to retrieve
for id, unit in EnergyExcessUnitsDisabled do
if not unit:BeenDestroyed() then
local ecobp = unit.Blueprint.Economy
self.EnergyExcessConsumed = self.EnergyExcessConsumed + ecobp.MaintenanceConsumptionPerSecondEnergy
self.EnergyExcessRequired = self.EnergyExcessRequired - ecobp.MaintenanceConsumptionPerSecondEnergy
self.EnergyExcessConverted = self.EnergyExcessConverted + ecobp.ProductionPerSecondMass
-- update internal state
EnergyExcessUnitsDisabled[id] = nil
EnergyExcessUnitsEnabled[id] = unit
-- try to enable unit
ok, msg = pcall(unit.OnExcessEnergy, unit)
-- allow for debugging
if not ok then
WARN("ToggleEnergyExcessUnitsThread: " .. repr(msg))
end
break
end
end
end
if self.Army == GetFocusArmy() then
syncTable.on = TableSize(EnergyExcessUnitsEnabled)
syncTable.off = TableSize(EnergyExcessUnitsDisabled)
syncTable.totalEnergyConsumed = self.EnergyExcessConsumed
syncTable.totalEnergyRequired = self.EnergyExcessRequired
syncTable.totalMassProduced = self.EnergyExcessConverted
-- only send new data
if lastSyncTable.on ~= syncTable.on
or lastSyncTable.off ~= syncTable.off
or lastSyncTable.totalEnergyConsumed ~= syncTable.totalEnergyConsumed
or lastSyncTable.totalEnergyRequired ~= syncTable.totalEnergyRequired
or lastSyncTable.totalMassProduced ~= syncTable.totalMassProduced
then
Sync.MassFabs = syncTable
-- swap the data buffers
syncTable, lastSyncTable = lastSyncTable, syncTable
end
end
CoroutineYield(1)
end
end,
--- Adds an entity to the list of entities that receive callbacks when the energy storage is depleted or viable, expects the functions OnEnergyDepleted and OnEnergyViable on the unit
---@param self AIBrain
---@param entity Unit | Shield
AddEnergyDependingEntity = function(self, entity)
self.EnergyDependingUnits[entity.EntityId] = entity
-- guarantee callback when entity is depleted
if self.EnergyDepleted then
entity:OnEnergyDepleted()
end
end,
---@param self AIBrain
---@param triggerName string
OnEnergyTrigger = function(self, triggerName)
if triggerName == "EnergyDepleted" then
-- add trigger when we can recover units
self:SetArmyStatsTrigger('Economy_Ratio_Energy', 'EnergyViable', 'GreaterThanOrEqual', 0.1)
self.EnergyDepleted = true
-- recurse over the list of units and do callbacks accordingly
for id, entity in self.EnergyDependingUnits do
if not IsDestroyed(entity) then
entity:OnEnergyDepleted()
end
end
else
-- add trigger when we're depleted
self:SetArmyStatsTrigger('Economy_Ratio_Energy', 'EnergyDepleted', 'LessThanOrEqual', 0.0)
self.EnergyDepleted = false
-- recurse over the list of units and do callbacks accordingly
for id, entity in self.EnergyDependingUnits do
if not IsDestroyed(entity) then
entity:OnEnergyViable()
end
end
end
end,
--- Triggers based on an AiBrain
---@param self AIBrain
---@param triggerName string
OnStatsTrigger = function(self, triggerName)
if triggerName == "EnergyDepleted" or triggerName == "EnergyViable" then
self:OnEnergyTrigger(triggerName)
end
for k, v in self.TriggerList do
if v.Name == triggerName then
if v.CallingObject then
if not v.CallingObject:BeenDestroyed() then
v.CallbackFunction(v.CallingObject)
end
else
v.CallbackFunction(self)
end
table.remove(self.TriggerList, k)
end
end
end,
---@param self AIBrain
---@param triggerName string
RemoveEconomyTrigger = function(self, triggerName)
for k, v in self.TriggerList do
if v.Name == triggerName then
table.remove(self.TriggerList, k)
end
end
end,
--- ## INTEL TRIGGER SPEC
--- ```
--- CallbackFunction = <function>,
--- Type = 'LOS'/'Radar'/'Sonar'/'Omni',
--- Blip = true/false,
--- Value = true/false,
--- Category: blip category to match
--- OnceOnly: fire onceonly
--- TargetAIBrain: AI Brain of the army you want it to trigger off of.
--- ```
---@param self AIBrain
---@param triggerSpec TriggerSpec
SetupArmyIntelTrigger = function(self, triggerSpec)
table.insert(self.IntelTriggerList, triggerSpec)
end,
---Called when recon data changes for enemy units (e.g. A unit comes into line of sight)
---@param self AIBrain
---@param blip any the unit (could be fake) in question
---@param reconType ReconTypes
---@param val boolean
OnIntelChange = function(self, blip, reconType, val)
if not val then
if reconType == 'LOSNow' or reconType == 'Omni' then
local unit = blip:GetSource()
if unit.Blueprint.Intel.JammerBlips > 0 then
unit.ResetJammer = self.JammerResetTime
end
end
end
if self.IntelTriggerList then
for k, v in self.IntelTriggerList do
if EntityCategoryContains(v.Category, blip:GetBlueprint().BlueprintId)
and v.Type == reconType and (not v.Blip or v.Blip == blip:GetSource())
and v.Value == val and v.TargetAIBrain == blip:GetAIBrain() then
v.CallbackFunction(blip)
if v.OnceOnly then
self.IntelTriggerList[k] = nil
end
end
end
end
end,
---@param self AIBrain
---@param callback fun(unit:Unit)
---@param category EntityCategory
---@param percent number
AddUnitBuiltPercentageCallback = function(self, callback, category, percent)
if not callback or not category or not percent then
error('*ERROR: Attempt to add UnitBuiltPercentageCallback but invalid data given', 2)
end
table.insert(self.UnitBuiltTriggerList, {Callback = callback, Category = category, Percent = percent})
end,
---@param self AIBrain
---@param triggerSpec TriggerSpec
SetupBrainVeterancyTrigger = function(self, triggerSpec)
if not triggerSpec.CallCount then
triggerSpec.CallCount = 1
end
table.insert(self.VeterancyTriggerList, triggerSpec)
end,
---@param self AIBrain
---@param unit Unit
---@param level number
OnBrainUnitVeterancyLevel = function(self, unit, level)
for _, v in self.VeterancyTriggerList do
if EntityCategoryContains(v.Category, unit) and level == v.Level and v.CallCount > 0 then
v.CallCount = v.CallCount - 1
v.CallbackFunction(unit)
end
end
end,
---@param self AIBrain
---@param callback function
---@param pingType string
AddPingCallback = function(self, callback, pingType)
if callback and pingType then
table.insert(self.PingCallbackList, {CallbackFunction = callback, PingType = pingType})
end
end,
---@param self AIBrain
---@param pingData table
DoPingCallbacks = function(self, pingData)
for _, v in self.PingCallbackList do
v.CallbackFunction(self, pingData)
end
end,
-- AI BRAIN FUNCTIONS HANDLED HERE --
---@param self AIBrain
---@param planName FileName
---@return string[]|nil
ImportScenarioArmyPlans = function(self, planName)
if planName and planName ~= '' then
return import(planName).AIPlansList
else
return nil
end
end,
---@param self AIBrain
---@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 AIBrain
OnDestroy = function(self)
if self.BuilderManagers then
self.ConditionsMonitor:Destroy()
for _, v in self.BuilderManagers do
v.EngineerManager:SetEnabled(false)
v.FactoryManager:SetEnabled(false)
v.PlatoonFormManager:SetEnabled(false)
v.FactoryManager:Destroy()
v.PlatoonFormManager:Destroy()
v.EngineerManager:Destroy()
end
end
if self.Trash then
self.Trash:Destroy()
end
end,
---@param self AIBrain
---@deprecated
ReportScore = function(self)
end,
---@param self AIBrain
---@param result AIResult
---@deprecated
SetResult = function(self, result)
end,
---@param self AIBrain
OnDefeat = function(self)
self.Status = 'Defeat'
import("/lua/simutils.lua").UpdateUnitCap(self:GetArmyIndex())
import("/lua/simping.lua").OnArmyDefeat(self:GetArmyIndex())
local function KillArmy()
local shareOption = ScenarioInfo.Options.Share
local function KillWalls()
-- Kill all walls while the ACU is blowing up
local tokill = self:GetListOfUnits(categories.WALL, false)
if tokill and not table.empty(tokill) then
for index, unit in tokill do
unit:Kill()
end
end
end
if shareOption == 'ShareUntilDeath' then
ForkThread(KillWalls)
end
WaitSeconds(10) -- Wait for commander explosion, then transfer units.
local selfIndex = self:GetArmyIndex()
local shareOption = ScenarioInfo.Options.Share
local victoryOption = ScenarioInfo.Options.Victory
local BrainCategories = {Enemies = {}, Civilians = {}, Allies = {}}
-- Used to have units which were transferred to allies noted permanently as belonging to the new player
local function TransferOwnershipOfBorrowedUnits(brains)
for index, brain in brains do
local units = brain:GetListOfUnits(categories.ALLUNITS, false)
if units and not table.empty(units) then
for _, unit in units do
if unit.oldowner == selfIndex then
unit.oldowner = nil
end
end
end
end
end
-- Transfer our units to other brains. Wait in between stops transfer of the same units to multiple armies.
-- Optional Categories input (defaults to all units except wall and command)
local function TransferUnitsToBrain(brains, categoriesToTransfer)
if not table.empty(brains) then
local units
if shareOption == 'FullShare' then
local indexes = {}
for _, brain in brains do
table.insert(indexes, brain.index)
end
units = self:GetListOfUnits(categories.ALLUNITS - categories.WALL - categories.COMMAND, false)
TransferUnfinishedUnitsAfterDeath(units, indexes)
end
for k, brain in brains do
if categoriesToTransfer then
units = self:GetListOfUnits(categoriesToTransfer, false)
else
units = self:GetListOfUnits(categories.ALLUNITS - categories.WALL - categories.COMMAND, false)
end
if units and not table.empty(units) then
local givenUnitCount = table.getn(TransferUnitsOwnership(units, brain.index))
-- only show message when we actually gift that player some units
if givenUnitCount > 0 then
Sync.ArmyTransfer = { { from = selfIndex, to = brain.index, reason = "fullshare" } }
end
WaitSeconds(1)
end
end
end
end
-- Sort the destiniation brains (armies/players) by rating (and if rating does not exist (such as with regular AI's), by score, after players with positive rating)
-- optional category input (default of everything but walls and command)
local function TransferUnitsToHighestBrain(brains, categoriesToTransfer)
if not table.empty(brains) then
local ratings = ScenarioInfo.Options.Ratings
for i, brain in brains do
if ratings[brain.Nickname] then
brain.rating = ratings[brain.Nickname]
else
-- if there is no rating, create a fake negative rating based on score
brain.rating = - (1 / brain.score)
end
end
-- sort brains by rating
table.sort(brains, function(a, b) return a.rating > b.rating end)
TransferUnitsToBrain(brains, categoriesToTransfer)
end
end
-- Transfer units to the player who killed me
local function TransferUnitsToKiller()
local KillerIndex = 0
local units = self:GetListOfUnits(categories.ALLUNITS - categories.WALL - categories.COMMAND, false)
if units and not table.empty(units) then
if victoryOption == 'demoralization' then
KillerIndex = ArmyBrains[selfIndex].CommanderKilledBy or selfIndex
TransferUnitsOwnership(units, KillerIndex)
else
KillerIndex = ArmyBrains[selfIndex].LastUnitKilledBy or selfIndex
TransferUnitsOwnership(units, KillerIndex)
end
end
WaitSeconds(1)
end
-- Return units transferred during the game to me