-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy pathaibrain.lua
4057 lines (3625 loc) · 161 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 PCBC = import('/lua/editor/platooncountbuildconditions.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 AIAttackUtils = import('/lua/AI/aiattackutilities.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 observer = false
local Points = {
defeat = -10,
draw = 0,
victory = 10
}
AIBrain = Class(moho.aibrain_methods) {
-- HUMAN BRAIN FUNCTIONS HANDLED HERE
OnCreateHuman = function(self, planName)
self:CreateBrainShared(planName)
self:InitializeEconomyState()
self.BrainType = 'Human'
end,
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,
SetUnitStat = function(self, unitId, statName, value)
if self.UnitStats[unitId] == nil then
self.UnitStats[unitId] = {}
end
self.UnitStats[unitId][statName] = value
end,
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,
GetUnitStats = function(self)
return self.UnitStats
end,
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:InitializeEconomyState()
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,
CreateBrainShared = function(self, planName)
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,
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)
if unit ~= nil and unit:GetBlueprint().Physics.FlattenSkirt then
unit:CreateTarmac(true, true, true, false, false)
end
end
end
if initialUnits then
-- Place initial units down
for k, v in initialUnits do
local unit = self:CreateUnitNearSpot(v, posX, posY)
if unit ~= nil and unit:GetBlueprint().Physics.FlattenSkirt then
unit:CreateTarmac(true, true, true, false, false)
end
end
end
self.PreBuilt = true
end,
-- GLOBAL AI BRAIN ARMY FEATURES
InitializeEconomyState = function(self)
-- This is called very early, so ensure stats exist
self:SetArmyStat('Economy_Ratio_Mass', 0.0)
self:SetArmyStat('Economy_Ratio_Energy', 0.0)
if not self.EconStateUnits then
self.EconStateUnits = {
MassStorage = {},
EnergyStorage = {},
}
end
self.EconMassStorageState = nil
self.EconEnergyStorageState = nil
self.EconStorageTrigs = {}
self:SetArmyStatsTrigger('Economy_Ratio_Mass', 'EconLowMassStore', 'LessThan', 0.1)
self:SetArmyStatsTrigger('Economy_Ratio_Energy', 'EconLowEnergyStore', 'LessThan', 0.1)
end,
ESRegisterUnitMassStorage = function(self, unit)
if not self.EconStateUnits then
self.EconStateUnits = {
MassStorage = {},
EnergyStorage = {},
}
end
table.insert(self.EconStateUnits.MassStorage, unit)
end,
ESRegisterUnitEnergyStorage = function(self, unit)
if not self.EconStateUnits then
self.EconStateUnits = {
MassStorage = {},
EnergyStorage = {},
}
end
table.insert(self.EconStateUnits.EnergyStorage, unit)
end,
ESUnregisterUnit = function(self, unit)
for k, v in self.EconStateUnits do
for i, j in v do
if j == unit then
table.remove(self.EconStateUnits[k], i)
end
end
end
end,
ESMassStorageUpdate = function(self, newState)
if self.EconMassStorageState ~= newState then
for k, v in self.EconStateUnits.MassStorage do
if not v.Dead then
v:OnMassStorageStateChange(newState)
else
table.remove(self.EconStateUnits.MassStorage, k)
end
end
if newState == 'EconLowMassStore' then
if not self.EconStorageTrigs['EconMidMassStore'] then
self:SetArmyStatsTrigger('Economy_Ratio_Mass', 'EconMidMassStore', 'GreaterThanOrEqual', 0.11)
self.EconStorageTrigs['EconMidMassStore'] = true
end
elseif newState == 'EconMidMassStore' then
if not self.EconStorageTrigs['EconLowMassStore'] then
self:SetArmyStatsTrigger('Economy_Ratio_Mass', 'EconLowMassStore', 'LessThan', 0.1)
self.EconStorageTrigs['EconLowMassStore'] = true
end
if not self.EconStorageTrigs['EconFullMassStore'] then
self:SetArmyStatsTrigger('Economy_Ratio_Mass', 'EconFullMassStore', 'GreaterThanOrEqual', 0.9)
self.EconStorageTrigs['EconFullMassStore'] = true
end
elseif newState == 'EconFullMassStore' then
if not self.EconStorageTrigs['EconMidMassStore'] then
self:SetArmyStatsTrigger('Economy_Ratio_Mass', 'EconMidMassStore', 'LessThan', 0.89)
self.EconStorageTrigs['EconMidMassStore'] = true
end
end
self.EconMassStorageState = newState
return true
end
return false
end,
ESEnergyStorageUpdate = function(self, newState)
if self.EconEnergyStorageState ~= newState then
for k, v in self.EconStateUnits.EnergyStorage do
if not v.Dead then
v:OnEnergyStorageStateChange(newState)
else
table.remove(self.EconStateUnits.EnergyStorage, k)
end
end
if newState == 'EconLowEnergyStore' then
if not self.EconStorageTrigs['EconMidEnergyStore'] then
self:SetArmyStatsTrigger('Economy_Ratio_Energy', 'EconMidEnergyStore', 'GreaterThanOrEqual', 0.11)
self.EconStorageTrigs['EconMidEnergyStore'] = true
end
elseif newState == 'EconMidEnergyStore' then
if not self.EconStorageTrigs['EconLowEnergyStore'] then
self:SetArmyStatsTrigger('Economy_Ratio_Energy', 'EconLowEnergyStore', 'LessThan', 0.1)
self.EconStorageTrigs['EconLowEnergyStore'] = true
end
if not self.EconStorageTrigs['EconFullEnergyStore'] then
self:SetArmyStatsTrigger('Economy_Ratio_Energy', 'EconFullEnergyStore', 'GreaterThanOrEqual', 0.9)
self.EconStorageTrigs['EconFullEnergyStore'] = true
end
elseif newState == 'EconFullEnergyStore' then
if not self.EconStorageTrigs['EconMidEnergyStore'] then
self:SetArmyStatsTrigger('Economy_Ratio_Energy', 'EconMidEnergyStore', 'LessThan', 0.89)
self.EconStorageTrigs['EconMidEnergyStore'] = true
end
end
self.EconMassStorageState = newState
return true
end
return false
end,
-- TRIGGERS BASED ON AN AI BRAIN
OnStatsTrigger = function(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
if triggerName == 'EconLowEnergyStore' or triggerName == 'EconMidEnergyStore' or triggerName == 'EconFullEnergyStore' then
self.EconStorageTrigs[triggerName] = false
self:ESEnergyStorageUpdate(triggerName)
elseif triggerName == 'EconLowMassStore' or triggerName == 'EconMidMassStore' or triggerName == 'EconFullMassStore' then
self.EconStorageTrigs[triggerName] = false
self:ESMassStorageUpdate(triggerName)
end
end,
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.
-- },
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)
-- Params
-- blip: the unit (could be fake) in question
-- type: 'LOSNow', 'Radar', 'Sonar', or 'Omni'
-- val: true or false
-- calls callback function with blip it saw.
OnIntelChange = function(self, blip, reconType, val)
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,
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,
SetupBrainVeterancyTrigger = function(self, triggerSpec)
if not triggerSpec.CallCount then
triggerSpec.CallCount = 1
end
table.insert(self.VeterancyTriggerList, triggerSpec)
end,
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,
AddPingCallback = function(self, callback, pingType)
if callback and pingType then
table.insert(self.PingCallbackList, {CallbackFunction = callback, PingType = pingType})
end
end,
DoPingCallbacks = function(self, pingData)
for _, v in self.PingCallbackList do
v.CallbackFunction(self, pingData)
end
end,
-- AI BRAIN FUNCTIONS HANDLED HERE
ImportScenarioArmyPlans = function(self, planName)
if planName and planName ~= '' then
return import(planName).AIPlansList
else
return nil
end
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,
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,
ReportScore = function(self)
local kills = self:GetArmyStat('Enemies_Commanders_Destroyed', 0).Value
local score = Points[self.Result] or 0 + kills
table.insert(Sync.GameResult, {self:GetArmyIndex(), string.format("%s %i", self.Result or 'score', score)})
end,
SetResult = function(self, result)
if self.Result then return end
if not Points[result] then
WARN("brain:SetResult() " .. result .. " not a valid result")
return
end
self.Result = result
self:ReportScore()
end,
OnDefeat = function(self)
self:SetResult("defeat")
SetArmyOutOfGame(self:GetArmyIndex())
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 table.getn(tokill) > 0 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 table.getn(units) > 0 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.
local function TransferUnitsToBrain(brains)
if table.getn(brains) > 0 then
if shareOption == 'FullShare' then
local indexes = {}
for _, brain in brains do
table.insert(indexes, brain.index)
end
local units = self:GetListOfUnits(categories.ALLUNITS - categories.WALL - categories.COMMAND, false)
TransferUnfinishedUnitsAfterDeath(units, indexes)
end
for k, brain in brains do
local units = self:GetListOfUnits(categories.ALLUNITS - categories.WALL - categories.COMMAND, false)
if units and table.getn(units) > 0 then
TransferUnitsOwnership(units, brain.index)
WaitSeconds(1)
end
end
end
end
-- Sort the destiniation armies by score
local function TransferUnitsToHighestBrain(brains)
if table.getn(brains) > 0 then
table.sort(brains, function(a, b) return a.score > b.score end)
TransferUnitsToBrain(brains)
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 table.getn(units) > 0 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 table.getn(units) > 0 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 score 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 table.getn(tokill) > 0 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 table.getn(units) > 0 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})
IssueClearCommands({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, v in self.BuilderManagers do
v.EngineerManager:SetEnabled(false)
v.FactoryManager:SetEnabled(false)
v.PlatoonFormManager:SetEnabled(false)
v.EngineerManager:Destroy()
v.FactoryManager:Destroy()
v.PlatoonFormManager:Destroy()
if v.StrategyManager then
v.StrategyManager:SetEnabled(false)
v.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,
OnVictory = function(self)
self:SetResult("victory")
end,
OnDraw = function(self)
self:SetResult("draw")
end,
IsDefeated = function(self)
return self.Result == "defeat"
end,
SetCurrentPlan = function(self, bestPlan)
if not bestPlan then
self.CurrentPlan = self.AIPlansList[self:GetFactionIndex()][1]
else
self.CurrentPlan = bestPlan
end
if not self.CurrentPlan then
error('*AI ERROR: Invalid plan list for army - '..self.Name, 2)
end
end,
SetConstantEvaluate = function(self, eval)
if eval == true and self.ConstantEval == false then
self.ConstantEval = eval
self:ForkThread(self.EvaluateAIThread)
end
self.ConstantEval = eval
end,
InitialAIThread = function(self)
-- delay the AI so it can't reclaim the start area before it's cleared from the ACU landing blast.
WaitTicks(30)
self.EvaluateThread = self:ForkThread(self.EvaluateAIThread)
self.ExecuteThread = self:ForkThread(self.ExecuteAIThread)
end,
EvaluateAIThread = function(self)
local personality = self:GetPersonality()
local factionIndex = self:GetFactionIndex()
if not self.LayerPref then
self:CalculateLayerPreference()
end
while self.ConstantEval do
self:EvaluateAIPlanList()
local delay = personality:AdjustDelay(100, 2)
WaitTicks(delay)
end
end,
EvaluateAIPlanList = function(self)
local factionIndex = self:GetFactionIndex()
local bestPlan = nil
local bestValue = 0
for _, v in self.AIPlansList[factionIndex] do
local value = self:EvaluatePlan(v)
if value > bestValue then
bestPlan = v
bestValue = value
end
end
if bestPlan then
self:SetCurrentPlan(bestPlan)
local bPlan = import(bestPlan)
if bPlan ~= self.CurrentPlanScript then
self.CurrentPlanScript = import(bestPlan)
self:SetRepeatExecution(true)
self:ExecutePlan(self.CurrentPlan)
end
end
end,
ExecuteAIThread = function(self)
local personality = self:GetPersonality()
while true do
if self.CurrentPlan and self.RepeatExecution then
self:ExecutePlan(self.CurrentPlan)
end
local delay = personality:AdjustDelay(20, 4)
WaitTicks(delay)
end
end,
EvaluatePlan = function(self, planName)
local plan = import(planName)
if plan then
return plan.EvaluatePlan(self)
else
LOG('*WARNING: TRIED TO IMPORT PLAN NAME ', repr(planName), ' BUT IT ERRORED OUT IN THE AI BRAIN.')
return 0
end
end,
ExecutePlan = function(self)
self.CurrentPlanScript.ExecutePlan(self)
end,
SetRepeatExecution = function(self, repeatEx)
self.RepeatExecution = repeatEx
end,
GetCurrentPlanScript = function(self)
return self.CurrentPlanScript
end,
IgnoreArmyUnitCap = function(self, val)
self.IgnoreArmyCaps = val
SetIgnoreArmyCap(self, val)
end,
-- System for playing VOs to the Player
VOSounds = {
-- {timeout delay, default cue, observers}
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'},
},
PlayVOSound = function(self, string, sound)
if not self.VOTable then self.VOTable = {} end
local VO = self.VOSounds[string]
if not VO then
WARN('PlayVOSound: ' .. string .. " not found")
return
end
if not self.VOTable[string] and VO['obs'] and GetFocusArmy() == -1 and self:GetArmyIndex() == 1 then
-- Don't stop sound IF not repeated AND sound is flagged as 'obs' AND i'm observer AND only from PlayerIndex = 1
elseif self.VOTable[string] or GetFocusArmy() ~= self:GetArmyIndex() then
return
end
local cue, bank
if sound then
cue, bank = GetCueBank(sound)
else
cue, bank = VO['bank'], 'XGG'
end
if not (bank and cue) then
WARN('PlayVOSound: No valid bank/cue for ' .. string)
return
end
self.VOTable[string] = true
table.insert(Sync.Voice, {Cue = cue, Bank = bank})
local timeout = VO['timeout']
ForkThread(function()
WaitSeconds(timeout)
self.VOTable[string] = nil
end)
end,
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,
OnUnitCapLimitReached = function(self) end,
OnFailedUnitTransfer = function(self)
self:PlayVOSound('OnFailedUnitTransfer')
end,
OnPlayNoStagingPlatformsVO = function(self)
self:PlayVOSound('OnPlayNoStagingPlatformsVO')
end,
OnPlayBusyStagingPlatformsVO = function(self)
self:PlayVOSound('OnPlayBusyStagingPlatformsVO')
end,
OnPlayCommanderUnderAttackVO = function(self)
self:PlayVOSound('OnPlayCommanderUnderAttackVO')
end,
NuclearLaunchDetected = function(self, sound)
self:PlayVOSound('NuclearLaunchDetected', sound)
end,
-- SKIRMISH AI HELPER SYSTEMS
InitializeSkirmishSystems = function(self)
-- Make sure we don't do anything for the human player!!!
if self.BrainType == 'Human' then
return
end
-- TURNING OFF AI POOL PLATOON, I MAY JUST REMOVE THAT PLATOON FUNCTIONALITY LATER
local poolPlatoon = self:GetPlatoonUniquelyNamed('ArmyPool')
if poolPlatoon then
poolPlatoon:TurnOffPoolAI()
end
-- Stores handles to all builders for quick iteration and updates to all
self.BuilderHandles = {}
-- Condition monitor for the whole brain
self.ConditionsMonitor = BrainConditionsMonitor.CreateConditionsMonitor(self)
-- Economy monitor for new skirmish - stores out econ over time to get trend over 10 seconds
self.EconomyData = {}
self.EconomyTicksMonitor = 50
self.EconomyCurrentTick = 1
self.EconomyMonitorThread = self:ForkThread(self.EconomyMonitor)
self.LowEnergyMode = false
-- Add default main location and setup the builder managers
self.NumBases = 0 -- AddBuilderManagers will increase the number
self.BuilderManagers = {}
SUtils.AddCustomUnitSupport(self)
self:AddBuilderManagers(self:GetStartVector3f(), 100, 'MAIN', false)
-- Begin the base monitor process
if self.Sorian then
local spec = {
DefaultDistressRange = 200,
AlertLevel = 8,
}
self:BaseMonitorInitializationSorian(spec)
else
self:BaseMonitorInitialization()
end
local plat = self:GetPlatoonUniquelyNamed('ArmyPool')
if self.Sorian then
plat:ForkThread(plat.BaseManagersDistressAISorian)
else
plat:ForkThread(plat.BaseManagersDistressAI)
end
self.DeadBaseThread = self:ForkThread(self.DeadBaseMonitor)
if self.Sorian then
self.EnemyPickerThread = self:ForkThread(self.PickEnemySorian)
else
self.EnemyPickerThread = self:ForkThread(self.PickEnemy)
end
end,
AddInitialEnemyThreatSorian = function(self, amount, decay, threatType)
local aiBrain = self
local myArmy = ScenarioInfo.ArmySetup[self.Name]
if ScenarioInfo.Options.TeamSpawn == 'fixed' then
-- Spawn locations were fixed. We know exactly where our opponents are.
for i = 1, 16 do
local token = 'ARMY_' .. i
local army = ScenarioInfo.ArmySetup[token]
if army then
if army.ArmyIndex ~= myArmy.ArmyIndex and (army.Team ~= myArmy.Team or army.Team == 1) then
local startPos = ScenarioUtils.GetMarker('ARMY_' .. i).position
if startPos then
self:AssignThreatAtPosition(startPos, amount, decay, threatType or 'Overall')
end