forked from FAForever/fa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaibrain.lua
1525 lines (1332 loc) · 53.8 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 SUtils = import("/lua/ai/sorianutilities.lua")
local TransferUnitsOwnership = import("/lua/simutils.lua").TransferUnitsOwnership
local TransferUnfinishedUnitsAfterDeath = import("/lua/simutils.lua").TransferUnfinishedUnitsAfterDeath
local CalculateBrainScore = import("/lua/sim/score.lua").CalculateBrainScore
local StorageManagerBrainComponent = import("/lua/aibrains/components/StorageManagerBrainComponent.lua").StorageManagerBrainComponent
local FactoryManagerBrainComponent = import("/lua/aibrains/components/FactoryManagerBrainComponent.lua").FactoryManagerBrainComponent
local JammerManagerBrainComponent = import("/lua/aibrains/components/JammerManagerBrainComponent.lua").JammerManagerBrainComponent
local StatManagerBrainComponent = import("/lua/aibrains/components/StatManagerBrainComponent.lua").StatManagerBrainComponent
local EnergyManagerBrainComponent = import("/lua/aibrains/components/EnergyManagerBrainComponent.lua").EnergyManagerBrainComponent
---@class TriggerSpec
---@field Callback function
---@field ReconTypes ReconTypes
---@field Blip boolean
---@field Value boolean
---@field Category EntityCategory
---@field OnceOnly boolean
---@field TargetAIBrain AIBrain
---@class ScoutLocation
---@field Position Vector
---@field TaggedBy Unit
---@class PlatoonTable
---@alias AIResult "defeat" | "draw" | "victor"
---@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'
local BrainGetUnitsAroundPoint = moho.aibrain_methods.GetUnitsAroundPoint
local BrainGetListOfUnits = moho.aibrain_methods.GetListOfUnits
local CategoriesDummyUnit = categories.DUMMYUNIT
---@class AIBrain: FactoryManagerBrainComponent, StatManagerBrainComponent, JammerManagerBrainComponent, EnergyManagerBrainComponent, StorageManagerBrainComponent, moho.aibrain_methods
---@field AI boolean
---@field Name string # Army name
---@field Nickname string # Player / AI / character name
---@field Status BrainState
---@field Human boolean
---@field Civilian boolean
---@field Trash TrashBag
---@field UnitBuiltTriggerList table
---@field PingCallbackList { CallbackFunction: fun(pingData: any), PingType: string }[]
---@field BrainType 'Human' | 'AI'
---@field CustomUnits { [string]: EntityId[] }
AIBrain = Class(FactoryManagerBrainComponent, StatManagerBrainComponent, JammerManagerBrainComponent,
EnergyManagerBrainComponent, StorageManagerBrainComponent, moho.aibrain_methods) {
Status = 'InProgress',
--- Called after `SetupSession` but before `BeginSession` - no initial units, props or resources exist at this point
---@param self AIBrain
---@param planName string
OnCreateHuman = function(self, planName)
self.BrainType = 'Human'
self:CreateBrainShared(planName)
self.EnergyExcessThread = ForkThread(self.ToggleEnergyExcessUnitsThread, self)
end,
--- Called after `SetupSession` but before `BeginSession` - no initial units, props or resources exist at this point
---@param self AIBrain
---@param planName string
OnCreateAI = function(self, planName)
self.BrainType = 'AI'
self:CreateBrainShared(planName)
end,
--- Called after `SetupSession` but before `BeginSession` - no initial units, props or resources exist at this point
---@param self AIBrain
---@param planName string
CreateBrainShared = function(self, planName)
self.Army = self:GetArmyIndex()
self.Trash = TrashBag()
self.TriggerList = {}
-- local notInteresting = {
-- GetArmyStat = true,
-- GetBlueprintStat = true,
-- GetEconomyStored = true,
-- IsDefeated = true,
-- Status = true,
-- GetEconomyTrend = true,
-- GetEconomyRatio = true,
-- GetEconomyStoredRatio = true,
-- }
-- local meta = getmetatable(self)
-- meta.__index = function(t, key)
-- if not notInteresting[key] then
-- LOG("BrainAccess: " .. tostring(key))
-- end
-- return meta[key]
-- end
-- keep track of radars
self.Radars = {
TECH1 = {},
TECH2 = {},
TECH3 = {},
EXPERIMENTAL = {},
}
self.PingCallbackList = {}
EnergyManagerBrainComponent.CreateBrainShared(self)
FactoryManagerBrainComponent.CreateBrainShared(self)
StatManagerBrainComponent.CreateBrainShared(self)
JammerManagerBrainComponent.CreateBrainShared(self)
StorageManagerBrainComponent.CreateBrainShared(self)
end,
--- Called after `BeginSession`, at this point all props, resources and initial units exist
---@param self AIBrain
OnBeginSession = function(self)
end,
---@param self AIBrain
OnDestroy = function(self)
self.Trash:Destroy()
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,
---@param self AIBrain
OnUnitCapLimitReached = function(self) end,
---@param self AIBrain
OnFailedUnitTransfer = function(self)
self:PlayVOSound('OnFailedUnitTransfer')
end,
---@param self AIBrain
OnPlayNoStagingPlatformsVO = function(self)
self:PlayVOSound('OnPlayNoStagingPlatformsVO')
end,
---@param self AIBrain
OnPlayBusyStagingPlatformsVO = function(self)
self:PlayVOSound('OnPlayBusyStagingPlatformsVO')
end,
---@param self AIBrain
OnPlayCommanderUnderAttackVO = function(self)
self:PlayVOSound('OnPlayCommanderUnderAttackVO')
end,
---@param self AIBrain
---@param sound SoundHandle
NuclearLaunchDetected = function(self, sound)
self:PlayVOSound('NuclearLaunchDetected', sound)
end,
---@param self AIBrain
---@param triggerSpec TriggerSpec
SetupArmyIntelTrigger = function(self, triggerSpec)
local intelTriggerList = self.IntelTriggerList
if not intelTriggerList then
intelTriggerList = {}
self.IntelTriggerList = intelTriggerList
end
table.insert(intelTriggerList, triggerSpec)
end,
---@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)
local intelTriggerList = self.IntelTriggerList
if intelTriggerList then
for k, v in 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
intelTriggerList[k] = nil
end
end
end
end
JammerManagerBrainComponent.OnIntelChange(self, blip, reconType, val)
end,
-- System for playing VOs to the Player
VOSounds = {
NuclearLaunchDetected = { timeout = 1, bank = nil, obs = true },
OnTransportFull = { timeout = 1, bank = nil },
OnFailedUnitTransfer = { timeout = 10, bank = 'Computer_Computer_CommandCap_01298' },
OnPlayNoStagingPlatformsVO = { timeout = 5, bank = 'XGG_Computer_CV01_04756' },
OnPlayBusyStagingPlatformsVO = { timeout = 5, bank = 'XGG_Computer_CV01_04755' },
OnPlayCommanderUnderAttackVO = { timeout = 15, bank = 'Computer_Computer_Commanders_01314' },
},
---@param self AIBrain
---@param key string
---@param sound SoundHandle
PlayVOSound = function(self, key, sound)
if not self.VOSounds[key] then
WARN("PlayVOSound: " .. key .. " not found")
return
end
local cue, bank
if sound then
cue, bank = GetCueBank(sound)
else
-- note: what the VO sound table calls a "bank" is actually a "cue"
cue, bank = self.VOSounds[key]["bank"], "XGG"
end
if not (bank and cue) then
WARN("PlayVOSound: No valid bank/cue for " .. key)
return
end
ForkThread(self.PlayVOSoundThread, self, key, {
Cue = cue,
Bank = bank,
})
end,
---@param self AIBrain
---@param key string
---@param data SoundBlueprint
PlayVOSoundThread = function(self, key, data)
if not self.VOTable then
self.VOTable = {}
end
if self.VOTable[key] then
return
end
local sound = self.VOSounds[key]
local focusArmy = GetFocusArmy()
local armyIndex = self:GetArmyIndex()
if focusArmy ~= armyIndex and not (focusArmy == -1 and armyIndex == 1 and sound.obs) then
return
end
self.VOTable[key] = true
import("/lua/SimSyncUtils.lua").SyncVoice(data)
WaitSeconds(sound.timeout)
self.VOTable[key] = nil
end,
--- Triggers based on an AiBrain
---@param self AIBrain
---@param triggerName string
OnStatsTrigger = function(self, triggerName)
EnergyManagerBrainComponent.OnStatsTrigger(self, triggerName)
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,
---@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
local unitBuiltTriggerList = self.UnitBuiltTriggerList
if not unitBuiltTriggerList then
unitBuiltTriggerList = {}
self.UnitBuiltTriggerList = unitBuiltTriggerList
end
table.insert(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
local veterancyTriggerList = self.VeterancyTriggerList
if not veterancyTriggerList then
veterancyTriggerList = {}
self.VeterancyTriggerList = veterancyTriggerList
end
table.insert(veterancyTriggerList, triggerSpec)
end,
---@param self AIBrain
---@param unit Unit
---@param level number
OnBrainUnitVeterancyLevel = function(self, unit, level)
local veterancyTriggerList = self.VeterancyTriggerList
if veterancyTriggerList then
for _, v in veterancyTriggerList do
if v.CallCount > 0 and
level == v.Level and
EntityCategoryContains(v.Category, unit)
then
v.CallCount = v.CallCount - 1
v.CallbackFunction(unit)
end
end
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
IsDefeated = function(self)
local status = self.Status
return status == "Defeat" or status == "Recalled" or ArmyIsOutOfGame(self.Army)
end,
---@param self AIBrain
OnTransportFull = function(self)
if not self.loadingTransport or self.loadingTransport.full then return end
local cue
self.loadingTransport.transData.full = true
if EntityCategoryContains(categories.uaa0310, self.loadingTransport) then
-- "CZAR FULL"
cue = 'XGG_Computer_CV01_04753'
elseif EntityCategoryContains(categories.NAVALCARRIER, self.loadingTransport) then
-- "Aircraft Carrier Full"
cue = 'XGG_Computer_CV01_04751'
else
cue = 'Computer_TransportIsFull'
end
self:PlayVOSound('OnTransportFull', Sound { Bank = 'XGG', Cue = cue })
end,
---@param self AIBrain
OnDraw = function(self)
self.Status = 'Draw'
end,
---@param self AIBrain
OnVictory = function(self)
self.Status = 'Victory'
end,
---@param self AIBrain
OnDefeat = function(self)
self.Status = 'Defeat'
import("/lua/simutils.lua").UpdateUnitCap(self:GetArmyIndex())
import("/lua/simping.lua").OnArmyDefeat(self:GetArmyIndex())
import("/lua/sim/Recall.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 givenUnits = TransferUnitsOwnership(units, brain.index)
-- only show message when we actually gift that player some units
if not table.empty(givenUnits) 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
local function ReturnBorrowedUnits()
local units = self:GetListOfUnits(categories.ALLUNITS - categories.WALL, false)
local borrowed = {}
for index, unit in units do
local oldowner = unit.oldowner
if oldowner and oldowner ~= self:GetArmyIndex() and not GetArmyBrain(oldowner):IsDefeated() then
if not borrowed[oldowner] then
borrowed[oldowner] = {}
end
table.insert(borrowed[oldowner], unit)
end
end
for owner, units in borrowed do
TransferUnitsOwnership(units, owner)
end
WaitSeconds(1)
end
-- Return units I gave away to my control. Mainly needed to stop EcoManager mods bypassing all this stuff with auto-give
local function GetBackUnits(brains)
local given = {}
for index, brain in brains do
local units = brain:GetListOfUnits(categories.ALLUNITS - categories.WALL, false)
if units and not table.empty(units) then
for _, unit in units do
if unit.oldowner == selfIndex then -- The unit was built by me
table.insert(given, unit)
unit.oldowner = nil
end
end
end
end
TransferUnitsOwnership(given, selfIndex)
end
-- Sort brains out into mutually exclusive categories
for index, brain in ArmyBrains do
brain.index = index
brain.score = CalculateBrainScore(brain)
if not brain:IsDefeated() and selfIndex ~= index then
if ArmyIsCivilian(index) then
table.insert(BrainCategories.Civilians, brain)
elseif IsEnemy(selfIndex, brain:GetArmyIndex()) then
table.insert(BrainCategories.Enemies, brain)
else
table.insert(BrainCategories.Allies, brain)
end
end
end
local KillSharedUnits = import("/lua/simutils.lua").KillSharedUnits
-- This part determines the share condition
if shareOption == 'ShareUntilDeath' then
KillSharedUnits(self:GetArmyIndex()) -- Kill things I gave away
ReturnBorrowedUnits() -- Give back things I was given by others
elseif shareOption == 'FullShare' then
TransferUnitsToHighestBrain(BrainCategories.Allies) -- Transfer things to allies, highest rating first
TransferOwnershipOfBorrowedUnits(BrainCategories.Allies) -- Give stuff away permanently
elseif shareOption == 'PartialShare' then
KillSharedUnits(self:GetArmyIndex(), categories.ALLUNITS - categories.STRUCTURE - categories.ENGINEER) -- Kill some things I gave away
ReturnBorrowedUnits() -- Give back things I was given by others
TransferUnitsToHighestBrain(BrainCategories.Allies, categories.STRUCTURE + categories.ENGINEER) -- Transfer some things to allies, highest rating first
TransferOwnershipOfBorrowedUnits(BrainCategories.Allies) -- Give stuff away permanently
else
GetBackUnits(BrainCategories.Allies) -- Get back units I gave away
if shareOption == 'CivilianDeserter' then
TransferUnitsToBrain(BrainCategories.Civilians)
elseif shareOption == 'TransferToKiller' then
TransferUnitsToKiller()
elseif shareOption == 'Defectors' then
TransferUnitsToHighestBrain(BrainCategories.Enemies)
else -- Something went wrong in settings. Act like share until death to avoid abuse
WARN('Invalid share condition was used for this game. Defaulting to killing all units')
KillSharedUnits(self:GetArmyIndex()) -- Kill things I gave away
ReturnBorrowedUnits() -- Give back things I was given by other
end
end
-- Kill all units left over
local tokill = self:GetListOfUnits(categories.ALLUNITS - categories.WALL, false)
if tokill and not table.empty(tokill) then
for index, unit in tokill do
unit:Kill()
end
end
end
-- AI
if self.BrainType == 'AI' then
-- print AI "ilost" text to chat
SUtils.AISendChat('enemies', ArmyBrains[self:GetArmyIndex()].Nickname, 'ilost')
-- remove PlatoonHandle from all AI units before we kill / transfer the army
local units = self:GetListOfUnits(categories.ALLUNITS - categories.WALL, false)
if units and not table.empty(units) then
for _, unit in units do
if not unit.Dead then
if unit.PlatoonHandle and self:PlatoonExists(unit.PlatoonHandle) then
unit.PlatoonHandle:Stop()
unit.PlatoonHandle:PlatoonDisbandNoAssign()
end
IssueStop({ unit })
IssueToUnitClearCommands(unit)
end
end
end
-- Stop the AI from executing AI plans
self.RepeatExecution = false
-- removing AI BrainConditionsMonitor
if self.ConditionsMonitor then
self.ConditionsMonitor:Destroy()
end
-- removing AI BuilderManagers
if self.BuilderManagers then
for k, manager in self.BuilderManagers do
if manager.EngineerManager then
manager.EngineerManager:SetEnabled(false)
end
if manager.FactoryManager then
manager.FactoryManager:SetEnabled(false)
end
if manager.PlatoonFormManager then
manager.PlatoonFormManager:SetEnabled(false)
end
if manager.EngineerManager then
manager.EngineerManager:Destroy()
end
if manager.FactoryManager then
manager.FactoryManager:Destroy()
end
if manager.PlatoonFormManager then
manager.PlatoonFormManager:Destroy()
end
if manager.StrategyManager then
manager.StrategyManager:SetEnabled(false)
manager.StrategyManager:Destroy()
end
self.BuilderManagers[k].EngineerManager = nil
self.BuilderManagers[k].FactoryManager = nil
self.BuilderManagers[k].PlatoonFormManager = nil
self.BuilderManagers[k].BaseSettings = nil
self.BuilderManagers[k].BuilderHandles = nil
self.BuilderManagers[k].Position = nil
end
end
-- delete the AI pathcache
self.PathCache = nil
end
ForkThread(KillArmy)
if self.Trash then
self.Trash:Destroy()
end
end,
AbandonedByPlayer = function(self)
if not IsGameOver() then
self:OnDefeat()
end
end,
---@param self AIBrain
RecallAllCommanders = function(self)
local commandCat = categories.COMMAND + categories.SUBCOMMANDER
self:ForkThread(self.RecallArmyThread, self:GetListOfUnits(commandCat, false))
end,
---@param self AIBrain
---@param recallingUnits Unit[]
RecallArmyThread = function(self, recallingUnits)
if recallingUnits then
import("/lua/scenarioframework.lua").FakeTeleportUnits(recallingUnits, true)
end
self:OnRecalled()
end,
OnRecalled = function(self)
-- TODO: create a common function for `OnDefeat` and `OnRecall`
self.Status = "Recalled"
local army = self.Army
import("/lua/simutils.lua").UpdateUnitCap(army)
import("/lua/simping.lua").OnArmyDefeat(army)
-- AI
if self.BrainType == "AI" then
-- print AI "ilost" text to chat
SUtils.AISendChat("enemies", ArmyBrains[army].Nickname, "ilost")
-- remove PlatoonHandle from all AI units before we kill / transfer the army
local units = self:GetListOfUnits(categories.ALLUNITS - categories.WALL, false)
if units and units[1] then
local halt = 0
local haltUnits = {}
for _, unit in units do
if not unit.Dead then
local handle = unit.PlatoonHandle
if handle and self:PlatoonExists(handle) then
handle:Stop()
handle:PlatoonDisbandNoAssign()
end
halt = halt + 1
haltUnits[halt] = unit
end
end
IssueStop(haltUnits)
IssueClearCommands(haltUnits)
end
-- Stop the AI from executing AI plans
self.RepeatExecution = false
-- removing AI BrainConditionsMonitor
if self.ConditionsMonitor then
self.ConditionsMonitor:Destroy()
end
-- removing AI BuilderManagers
if self.BuilderManagers then
for _, v in self.BuilderManagers do
local manager = v.EngineerManager
manager:SetEnabled(false)
manager:Destroy()
manager = v.FactoryManager
manager:SetEnabled(false)
manager:Destroy()
manager = v.PlatoonFormManager
manager:SetEnabled(false)
manager:Destroy()
manager = v.StrategyManager
if manager then
manager:SetEnabled(false)
manager:Destroy()
end
v.EngineerManager = nil
v.FactoryManager = nil
v.PlatoonFormManager = nil
v.BaseSettings = nil
v.BuilderHandles = nil
v.Position = nil
end
end
-- delete the AI pathcache
self.PathCache = nil
end
local enemies, civilians = {}, {}
-- Transfer our units to other brains. Wait in between stops transfer of the same units to multiple armies.
local function TransferUnitsToBrain(brains)
if brains[1] then
local cat = categories.ALLUNITS - categories.WALL - categories.COMMAND - categories.SUBCOMMANDER
for _, brain in brains do
local units = self:GetListOfUnits(cat, false)
if units and units[1] then
local givenUnits = TransferUnitsOwnership(units, brain.index)
-- only show message when we actually gift that player some units
if not table.empty(givenUnits) then
Sync.ArmyTransfer = { {
from = army,
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)
local function TransferUnitsToHighestBrain(brains)
if not table.empty(brains) then
local ratings = ScenarioInfo.Options.Ratings
for _, 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)
end
end
-- Sort brains out into mutually exclusive categories
for index, brain in ArmyBrains do
brain.index = index
brain.score = CalculateBrainScore(brain)
if not brain:IsDefeated() and army ~= index then
if ArmyIsCivilian(index) then
table.insert(civilians, brain)
elseif IsEnemy(army, brain:GetArmyIndex()) then
table.insert(enemies, brain)
end
end
end
-- This part determines the share condition
local shareOption = ScenarioInfo.Options.Share
if shareOption == 'CivilianDeserter' then
TransferUnitsToBrain(civilians)
elseif shareOption == 'Defectors' then
TransferUnitsToHighestBrain(enemies)
end
-- let the average, team vs team game end first
WaitSeconds(10.0)
-- Kill all units left over
local tokill = self:GetListOfUnits(categories.ALLUNITS - categories.WALL, false)
if tokill then
for _, unit in tokill do
if not IsDestroyed(unit) then
unit:Kill()
end
end
end
local trash = self.Trash
if trash then
trash:Destroy()
end
end,
--------------------------------------------------------------------------------
--#region ping functionality
---@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,
---@param self AIBrain
---@param pingData table
DoAIPing = function(self, pingData)
if self.Sorian then
if pingData.Type then
SUtils.AIHandlePing(self, pingData)
end
end
end,
--#endregion
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--#region overwritten c-functionality
--- Retrieves all units that fit the criteria around some point. Excludes dummy units.
---@param self AIBrain
---@param category EntityCategory The categories the units should fit.
---@param position Vector The center point to start looking for units.
---@param radius number The radius of the circle we look for units in.
---@param alliance AllianceStatus
---@return Unit[]
GetUnitsAroundPoint = function(self, category, position, radius, alliance)
if alliance then
-- call where we do care about alliance
return BrainGetUnitsAroundPoint(self, category - CategoriesDummyUnit, position, radius, alliance)
else
-- call where we do not, which is different from providing nil (as there would be a fifth argument then)
return BrainGetUnitsAroundPoint(self, category - CategoriesDummyUnit, position, radius)
end
end,
--- Returns list of units by category. Excludes dummy units.
---@param self AIBrain
---@param cats EntityCategory Unit's category, example: categories.TECH2 .
---@param needToBeIdle boolean true/false Unit has to be idle (appears to be not functional).
---@param requireBuilt? boolean true/false defaults to false which excludes units that are NOT finished (appears to be not functional).
---@return Unit[]
GetListOfUnits = function(self, cats, needToBeIdle, requireBuilt)
-- defaults to false, prevent sending nil
requireBuilt = requireBuilt or false
-- retrieve units, excluding insignificant units
return BrainGetListOfUnits(self, cats - CategoriesDummyUnit, needToBeIdle, requireBuilt)
end,
--#endregion
-------------------------------------------------------------------------------
---------------------------------------------------------------------------
--#region Unit events
--- Represents a list of unit events that are communicated to the brain. It makes it
--- easier to respond to conditions that are happening on the battlefield. The following
--- unit events are not communicated to the brain:
---
--- - OnStorageChange (use OnAddToStorage and OnRemoveFromStorage instead)
--- - OnAnimCollision
--- - OnTerrainTypeChange
--- - OnMotionVertEventChange
--- - OnMotionHorzEventChange
--- - OnLayerChange
--- - OnPrepareArmToBuild
--- - OnStartBuilderTracking
--- - OnStopBuilderTracking
--- - OnStopRepeatQueue
--- - OnStartRepeatQueue
--- - OnAssignedFocusEntity
---
--- And events that are purposefully not communicated:
---
--- - OnDamage
--- - OnDamageBy
--- - OnMotionHorzEventChange
--- - OnMotionVertEventChange
---
--- If you're interested for one of these events then you're encouraged to make a pull
--- request to add the event!
--- Called by a unit as it starts being built
---@param self AIBrain
---@param unit Unit
---@param builder Unit
---@param layer Layer
OnUnitStartBeingBuilt = function(self, unit, builder, layer)
-- do nothing
end,
--- Called by a unit as it is finished being built
---@param self AIBrain
---@param unit Unit