/
unit_mex_overdrive.lua
1619 lines (1364 loc) · 54.2 KB
/
unit_mex_overdrive.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
-- $Id: unit_mex_overdrive.lua 4550 2009-05-05 18:07:29Z licho $
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
if not (gadgetHandler:IsSyncedCode()) then
return
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Mex Control with energy link",
desc = "Controls mex overload and energy link grid",
author = "Licho, Google Frog (pylon conversion)",
date = "16.5.2008 (OD date)",
license = "GNU GPL, v2 or later",
layer = -4, -- OD grid circles must be drawn before lava drawing gadget some maps have (which has layer = -3)
enabled = true -- loaded by default?
}
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local mexDefs = {}
--local energyDefs = {}
local pylonDefs = {}
local generatorDefs = {}
local odSharingModOptions = (Spring.GetModOptions()).overdrivesharingscheme or "investmentreturn"
local enableEnergyPayback = ((odSharingModOptions == "investmentreturn") or (odSharingModOptions == "investmentreturn_od"))
local enableMexPayback = ((odSharingModOptions == "investmentreturn") or (odSharingModOptions == "investmentreturn_base"))
include("LuaRules/Configs/constants.lua")
include("LuaRules/Configs/mex_overdrive.lua")
for i = 1, #UnitDefs do
local udef = UnitDefs[i]
if (udef.customParams.ismex) then
mexDefs[i] = true
end
local pylonRange = tonumber(udef.customParams.pylonrange) or 0
if pylonRange > 0 then
pylonDefs[i] = {
range = pylonRange or DEFAULT_PYLON_RANGE,
neededLink = tonumber(udef.customParams.neededlink) or false,
keeptooltip = udef.customParams.keeptooltip or false,
}
end
local metalIncome = tonumber(udef.customParams.income_metal) or 0
local energyIncome = tonumber(udef.customParams.income_energy) or 0
local isWind = (udef.customParams.windgen and true) or false
if metalIncome > 0 or energyIncome > 0 or isWind then
generatorDefs[i] = {
metalIncome = metalIncome,
energyIncome = energyIncome,
}
end
end
local alliedTrueTable = {allied = true}
local inlosTrueTable = {inlos = true}
local sentErrorWarning = false
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
Spring.SetGameRulesParam("lowpower",1)
local MEX_DIAMETER = Game.extractorRadius*2
local function paybackFactorFunction(repayRatio)
-- Must map [0,1) to (0,1]
-- Must not have any sequences on the domain that converge to 0 in the codomain.
local repay = 0.35 - repayRatio*0.25
if repay > 0.33 then
return 0.33
else
return repay
end
end
local PAYBACK_FACTOR = 0.5
local paybackDefs = { -- cost is how much to pay back
[UnitDefNames["armwin"].id] = {cost = UnitDefNames["armwin"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["armsolar"].id] = {cost = UnitDefNames["armsolar"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["armfus"].id] = {cost = UnitDefNames["armfus"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["cafus"].id] = {cost = UnitDefNames["cafus"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["geo"].id] = {cost = UnitDefNames["geo"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["amgeo"].id] = {cost = UnitDefNames["amgeo"].metalCost*PAYBACK_FACTOR},
}
--local PYLON_ENERGY_RANGESQ = 160000
--local PYLON_LINK_RANGESQ = 40000
--local PYLON_MEX_RANGESQ = 10000
--local PYLON_MEX_LIMIT = 100
--local CMD_MEXE = 30666
local spammedError = false
local debugMode = false
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local sqrt = math.sqrt
local min = math.min
local max = math.max
local spValidUnitID = Spring.ValidUnitID
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitAllyTeam = Spring.GetUnitAllyTeam
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitPosition = Spring.GetUnitPosition
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetUnitStates = Spring.GetUnitStates
local spGetUnitHealth = Spring.GetUnitHealth
local spGetUnitResources = Spring.GetUnitResources
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local spCallCOBScript = Spring.CallCOBScript
local spSetTeamRulesParam = Spring.SetTeamRulesParam
local spGetTeamResources = Spring.GetTeamResources
local spAddTeamResource = Spring.AddTeamResource
local spUseTeamResource = Spring.UseTeamResource
local spGetTeamInfo = Spring.GetTeamInfo
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local mexes = {} -- mexes[teamID][gridID][unitID] == mexMetal
local mexByID = {} -- mexByID[unitID] = {gridID, allyTeamID, refundTeamID, refundTime, refundTotal, refundSoFar}
local lowPowerUnits = {inner = {count = 0, units = {}}}
local pylon = {} -- pylon[allyTeamID][unitID] = {gridID,mexes,mex[unitID],x,z,overdrive, nearPlant[unitID],nearPylon[unitID], color}
local pylonList = {} -- pylon[allyTeamID] = {data = {[1] = unitID, [2] = unitID, ...}, count = number}
local generator = {} -- generator[allyTeamID][teamID][unitID] = {generatorListID, metalIncome, energyIncome}
local generatorList = {} -- generator[allyTeamID][teamID] = {data = {[1] = unitID, [2] = unitID, ...}, count = number}
local pylonGridQueue = false -- pylonGridQueue[unitID] = true
local unitPaybackTeamID = {} -- indexed by unitID, tells unit which team gets it's payback.
local teamPayback = {} -- teamPayback[teamID] = {count = 0, toRemove = {}, data = {[1] = {unitID = unitID, cost = costOfUnit, repaid = howMuchHasBeenRepaid}}}
local allyTeamInfo = {}
do
local allyTeamList = Spring.GetAllyTeamList()
for i = 1, #allyTeamList do
local allyTeamID = allyTeamList[i]
pylon[allyTeamID] = {}
pylonList[allyTeamID] = {data = {}, count = 0}
generator[allyTeamID] = {}
generatorList[allyTeamID] = {}
mexes[allyTeamID] = {}
mexes[allyTeamID][0] = {}
allyTeamInfo[allyTeamID] = {
--plant = {},
mexMetal = 0,
mexSquaredSum = 0,
mexCount = 0,
grids = 0,
grid = {}, -- pylon[unitID], plant[unitID], mexMetal, mexSquaredSum
nilGrid = {},
team = {},
teams = 0,
}
local teamList = Spring.GetTeamList(allyTeamID)
for j = 1, #teamList do
local teamID = teamList[j]
allyTeamInfo[allyTeamID].teams = allyTeamInfo[allyTeamID].teams + 1
allyTeamInfo[allyTeamID].team[allyTeamInfo[allyTeamID].teams] = teamID
generator[allyTeamID][teamID] = {}
generatorList[allyTeamID][teamID] = {data = {}, count = 0}
end
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Awards
GG.Overdrive_allyTeamResources = {}
local lastAllyTeamResources = {} -- 1 second lag for resource updates
local function sendAllyTeamInformationToAwards(allyTeamID, summedBaseMetal, summedOverdrive, allyTeamEnergyIncome, ODenergy, wasteEnergy)
local last = lastAllyTeamResources[allyTeamID] or {}
GG.Overdrive_allyTeamResources[allyTeamID] = {
baseMetal = summedBaseMetal,
overdriveMetal = last.overdriveMetal or 0,
baseEnergy = allyTeamEnergyIncome,
overdriveEnergy = last.overdriveEnergy or 0,
wasteEnergy = last.wasteEnergy or 0,
}
lastAllyTeamResources[allyTeamID] = {
overdriveMetal = summedOverdrive,
overdriveEnergy = ODenergy,
wasteEnergy = wasteEnergy,
}
end
GG.Overdrive_teamResources = {}
local lastTeamResources = {} -- 1 second lag for resource updates
local function sendTeamInformationToAwards(teamID, baseMetal, overdriveMetal, overdriveEnergyChange)
local last = lastTeamResources[teamID] or {}
GG.Overdrive_teamResources[teamID] = {
baseMetal = baseMetal,
overdriveMetal = last.overdriveMetal or 0,
overdriveEnergyChange = last.overdriveEnergyChange or 0,
}
lastTeamResources[teamID] = {
overdriveMetal = overdriveMetal,
overdriveEnergyChange = overdriveEnergyChange,
}
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Debug Functions
function TableEcho(data, indent)
indent = indent or ""
for name, v in pairs(data) do
local ty = type(v)
if ty == "table" then
Spring.Echo(indent .. name .. " = {")
TableEcho(v, indent .. " ")
--Spring.Echo(indent .. "}")
elseif ty == "boolean" then
Spring.Echo(indent .. name .. " = " .. (v and "true" or "false"))
else
Spring.Echo(indent .. name .. " = " .. v)
end
end
end
function UnitEcho(unitID, st)
st = st or unitID
if Spring.ValidUnitID(unitID) then
local x,y,z = Spring.GetUnitPosition(unitID)
Spring.MarkerAddPoint(x,y,z, st)
else
Spring.Echo("Invalid unitID")
Spring.Echo(unitID)
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- local functions
local function energyToExtraM(energy)
return sqrt(energy)*0.25
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Information Sharing to Widget functions
local privateTable = {private = true}
local previousData = {}
local function SetTeamEconomyRulesParams(
teamID, activeCount, -- TeamID of the team as well as number of active allies.
summedBaseMetal, -- AllyTeam base metal extrator income
summedOverdrive, -- AllyTeam overdrive income
allyTeamMiscMetalIncome, -- AllyTeam constructor income
allyTeamEnergyIncome, -- AllyTeam total energy generator income
overdriveEnergySpending, -- AllyTeam energy spent on overdrive
energyWasted, -- AllyTeam energy excess
baseShare, -- Team share of base metal extractor income
odShare, -- Team share of overdrive income
miscShare, -- Team share of constructor metal income
energyIncome, -- Total energy generator income
overdriveEnergyNet, -- Amount of energy spent or recieved due to overdrive and income
overdriveEnergyChange) -- real change in energy due to overdrive
if previousData[teamID] then
local pd = previousData[teamID]
spSetTeamRulesParam(teamID, "OD_allies", pd.activeCount, privateTable)
spSetTeamRulesParam(teamID, "OD_team_metalBase", pd.summedBaseMetal, privateTable)
spSetTeamRulesParam(teamID, "OD_team_metalOverdrive", pd.summedOverdrive, privateTable)
spSetTeamRulesParam(teamID, "OD_team_metalMisc", pd.allyTeamMiscMetalIncome, privateTable)
spSetTeamRulesParam(teamID, "OD_team_energyIncome", pd.allyTeamEnergyIncome, privateTable)
spSetTeamRulesParam(teamID, "OD_team_energyOverdrive", pd.overdriveEnergySpending, privateTable)
spSetTeamRulesParam(teamID, "OD_team_energyWaste", pd.energyWasted, privateTable)
spSetTeamRulesParam(teamID, "OD_metalBase", pd.baseShare, privateTable)
spSetTeamRulesParam(teamID, "OD_metalOverdrive", pd.odShare, privateTable)
spSetTeamRulesParam(teamID, "OD_metalMisc", pd.miscShare, privateTable)
spSetTeamRulesParam(teamID, "OD_energyIncome", pd.energyIncome, privateTable)
spSetTeamRulesParam(teamID, "OD_energyOverdrive", pd.overdriveEnergyNet, privateTable)
spSetTeamRulesParam(teamID, "OD_energyChange", pd.overdriveEnergyChange, privateTable)
spSetTeamRulesParam(teamID, "OD_RoI_metalDue", teamPayback[teamID].metalDueOD, privateTable)
spSetTeamRulesParam(teamID, "OD_base_metalDue", teamPayback[teamID].metalDueBase, privateTable)
else
previousData[teamID] = {}
end
local pd = previousData[teamID]
pd.activeCount = activeCount
pd.summedBaseMetal = summedBaseMetal
pd.summedOverdrive = summedOverdrive
pd.allyTeamMiscMetalIncome = allyTeamMiscMetalIncome
pd.allyTeamEnergyIncome = allyTeamEnergyIncome
pd.overdriveEnergySpending = overdriveEnergySpending
pd.energyWasted = energyWasted
pd.baseShare = baseShare
pd.odShare = odShare
pd.miscShare = miscShare
pd.energyIncome = energyIncome
pd.overdriveEnergyNet = overdriveEnergyNet
pd.overdriveEnergyChange = overdriveEnergyChange
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- PYLONS
local function AddPylonToGrid(unitID)
local allyTeamID = spGetUnitAllyTeam(unitID)
local pX,_,pZ = spGetUnitPosition(unitID)
local ai = allyTeamInfo[allyTeamID]
if debugMode then
Spring.Echo("AddPylonToGrid " .. unitID)
end
local newGridID = 0
local attachedGrids = 0
local attachedGrid = {}
local attachedGridID = {}
--check for nearby pylons
local ownRange = pylon[allyTeamID][unitID].linkRange
local list = pylonList[allyTeamID]
for i = 1, list.count do
local pid = list.data[i]
local pylonData = pylon[allyTeamID][pid]
if pylonData then
if pid ~= unitID and (pylonData.x-pX)^2 + (pylonData.z-pZ)^2 <= (pylonData.linkRange+ownRange)^2 and pylonData.gridID ~= 0 and pylonData.active then
pylon[allyTeamID][unitID].nearPylon[pid] = true
if not attachedGridID[pylonData.gridID] then
attachedGrids = attachedGrids + 1
attachedGrid[attachedGrids] = pylonData.gridID
attachedGridID[pylonData.gridID] = true
end
end
elseif not spammedError then
Spring.Echo("Pylon problem detected in AddPylonToGrid.")
end
end
if attachedGrids == 0 then -- create a new grid
local foundSpot = false
for i = 1, ai.grids do
if ai.nilGrid[i] then
ai.grid[i] = {
pylon = {},
--plant = {},
mexMetal = 0,
mexSquaredSum = 0,
}
newGridID = i
ai.nilGrid[i] = false
foundSpot = true
break
end
end
if not foundSpot then
ai.grids = ai.grids + 1
newGridID = ai.grids
ai.grid[ai.grids] = {
pylon = {},
--plant = {},
mexMetal = 0,
mexSquaredSum = 0,
}
mexes[allyTeamID][newGridID] = {}
end
else -- add to an existing grid
newGridID = attachedGrid[1]
for i = 2, attachedGrids do -- merge grids if it attaches to 2 or more
local oldGridID = attachedGrid[i]
for pid,_ in pairs(ai.grid[oldGridID].pylon) do
local pylonData = pylon[allyTeamID][pid]
pylonData.gridID = newGridID
--NOTE: since mex became a pylon it no longer store list of mex, now only store itself as mex
if pylonData.mex then
local mid = pid
mexes[allyTeamID][newGridID][mid] = mexes[allyTeamID][oldGridID][mid]
mexByID[mid].gridID = newGridID
mexes[allyTeamID][oldGridID][mid] = nil
end
ai.grid[newGridID].pylon[pid] = true
spSetUnitRulesParam(pid,"gridNumber",newGridID,alliedTrueTable)
end
--[[for eid,_ in pairs(ai.grid[oldGridID].plant) do
ai.grid[newGridID].plant[eid] = true
end--]]
ai.grid[newGridID].mexMetal = ai.grid[newGridID].mexMetal + ai.grid[oldGridID].mexMetal
ai.grid[newGridID].mexSquaredSum = ai.grid[newGridID].mexSquaredSum + ai.grid[oldGridID].mexSquaredSum
ai.nilGrid[oldGridID] = true
end
end
ai.grid[newGridID].pylon[unitID] = true
pylon[allyTeamID][unitID].gridID = newGridID
spSetUnitRulesParam(unitID,"gridNumber",newGridID,alliedTrueTable)
-- add econ to new grid
-- mexes
if pylon[allyTeamID][unitID].mex then
local mid = unitID
local orgMetal = mexes[allyTeamID][0][mid]
ai.mexMetal = ai.mexMetal + orgMetal
ai.mexSquaredSum = ai.mexSquaredSum + (orgMetal * orgMetal)
ai.grid[newGridID].mexMetal = ai.grid[newGridID].mexMetal + orgMetal
ai.grid[newGridID].mexSquaredSum = ai.grid[newGridID].mexSquaredSum + (orgMetal * orgMetal)
mexes[allyTeamID][newGridID][mid] = orgMetal
mexByID[mid].gridID = newGridID
mexes[allyTeamID][0][mid] = nil
end
-- energy
--[[for eid,_ in pairs(pylon[allyTeamID][unitID].nearEnergy) do
ai.grid[newGridID].plant[eid] = true
end--]]
end
local function QueueAddPylonToGrid(unitID)
if debugMode then
Spring.Echo("QueueAddPylonToGrid " .. unitID)
end
if not pylonGridQueue then
pylonGridQueue = {}
end
pylonGridQueue[unitID] = true
end
local function RemovePylonsFromGridQueue(unitID)
if debugMode then
Spring.Echo("RemovePylonsFromGridQueue " .. unitID)
end
if pylonGridQueue then
pylonGridQueue[unitID] = nil
end
end
local function AddPylon(unitID, unitDefID, range)
local allyTeamID = spGetUnitAllyTeam(unitID)
local pX,_,pZ = spGetUnitPosition(unitID)
local ai = allyTeamInfo[allyTeamID]
if pylon[allyTeamID][unitID] then
return
end
pylon[allyTeamID][unitID] = {
gridID = 0,
--mexes = 0,
mex = (mexByID[unitID] and true) or false,
nearPylon = {},
linkRange = range,
mexRange = 10,
--nearEnergy = {},
x = pX,
z = pZ,
neededLink = pylonDefs[unitDefID].neededLink,
active = true,
}
local list = pylonList[allyTeamID]
list.count = list.count + 1
list.data[list.count] = unitID
pylon[allyTeamID][unitID].listID = list.count
if debugMode then
Spring.Echo("AddPylon " .. unitID)
UnitEcho(unitID, list.count .. ", " .. unitID)
end
-- check for mexes
--[[
if unitOverdrive then
for mid, orgMetal in pairs(mexes[allyTeamID][0]) do
local mX,_,mZ = spGetUnitPosition(mid)
if (mid == unitID) then -- mex as pylon
--if (pX-mX)^2 + (pZ-mZ)^2 <= range^2 and not takenMexId[mid] then
--pylon[allyTeamID][unitID].mexes = pylon[allyTeamID][unitID].mexes + 1
pylon[allyTeamID][unitID].mex = true
--takenMexId[mid] = true
--if pylon[allyTeamID][unitID].mexes >= PYLON_MEX_LIMIT then
-- break
--end
end
end
end
--]]
-- check for energy
--[[
for eid, state in pairs(ai.plant) do
if (state == 0) then
local eX,_,eZ = spGetUnitPosition(eid)
if (pX-eX)^2 + (pZ-eZ)^2 < PYLON_ENERGY_RANGESQ then
ai.plant[eid] = 1
pylon[allyTeamID][unitID].nearEnergy[eid] = true
end
end
end
--]]
QueueAddPylonToGrid(unitID)
end
local function DestroyGrid(allyTeamID,oldGridID)
local ai = allyTeamInfo[allyTeamID]
if debugMode then
Spring.Echo("DestroyGrid " .. oldGridID)
end
for pid,_ in pairs(ai.grid[oldGridID].pylon) do
pylon[allyTeamID][pid].gridID = 0
pylon[allyTeamID][pid].nearPylon = {}
if (pylon[allyTeamID][pid].mex) then
local mid = pid
local orgMetal = mexes[allyTeamID][oldGridID][mid]
mexes[allyTeamID][oldGridID][mid] = nil
mexes[allyTeamID][0][mid] = orgMetal
mexByID[mid].gridID = 0
ai.mexCount = ai.mexCount - 1
ai.mexMetal = ai.mexMetal - orgMetal
ai.mexSquaredSum = ai.mexSquaredSum - (orgMetal * orgMetal)
end
end
ai.nilGrid[oldGridID] = true
end
local function ReactivatePylon(unitID)
local allyTeamID = spGetUnitAllyTeam(unitID)
local ai = allyTeamInfo[allyTeamID]
if debugMode then
Spring.Echo("ReactivatePylon " .. unitID)
end
--local pX,_,pZ = spGetUnitPosition(unitID)
pylon[allyTeamID][unitID].active = true
-- check for energy
--[[
for eid, state in pairs(ai.plant) do
if state == 0 then
local eX,_,eZ = spGetUnitPosition(eid)
if (pX-eX)^2 + (pZ-eZ)^2 < PYLON_ENERGY_RANGESQ then
state = 1
pylon[allyTeamID][unitID].nearEnergy[eid] = true
end
end
end
--]]
QueueAddPylonToGrid(unitID)
end
local function DeactivatePylon(unitID)
local allyTeamID = spGetUnitAllyTeam(unitID)
local ai = allyTeamInfo[allyTeamID]
if debugMode then
Spring.Echo("DeactivatePylon " .. unitID)
end
RemovePylonsFromGridQueue(unitID)
local oldGridID = pylon[allyTeamID][unitID].gridID
if oldGridID ~= 0 then
local pylonMap = ai.grid[oldGridID].pylon
local energyList = pylon[allyTeamID][unitID].nearEnergy
DestroyGrid(allyTeamID,oldGridID)
for pid,_ in pairs(pylonMap) do
if (pid ~= unitID) then
QueueAddPylonToGrid(pid)
end
end
end
pylon[allyTeamID][unitID].active = false
end
local function RemovePylon(unitID)
local allyTeamID = spGetUnitAllyTeam(unitID)
if debugMode then
Spring.Echo("RemovePylon start " .. unitID)
TableEcho(pylonList[allyTeamID])
TableEcho(pylon[allyTeamID])
end
RemovePylonsFromGridQueue(unitID)
if not pylon[allyTeamID][unitID] then
--Spring.Echo("RemovePylon not pylon[allyTeamID][unitID] " .. unitID)
return
end
local pX,_,pZ = spGetUnitPosition(unitID)
local ai = allyTeamInfo[allyTeamID]
local oldGridID = pylon[allyTeamID][unitID].gridID
local activeState = pylon[allyTeamID][unitID].active
local isMex = pylon[allyTeamID][unitID].mex
if activeState and oldGridID ~= 0 then
local pylonMap = ai.grid[oldGridID].pylon
local energyList = pylon[allyTeamID][unitID].nearEnergy
DestroyGrid(allyTeamID,oldGridID)
for pid,_ in pairs(pylonMap) do
if (pid ~= unitID) then
QueueAddPylonToGrid(pid)
end
end
end
local list = pylonList[allyTeamID]
local listID = pylon[allyTeamID][unitID].listID
list.data[listID] = list.data[list.count]
pylon[allyTeamID][list.data[listID]].listID = listID
list.data[list.count] = nil
list.count = list.count - 1
pylon[allyTeamID][unitID] = nil
-- mexes
if isMex then
local mid = unitID
local orgMetal = mexes[allyTeamID][0][mid]
mexes[allyTeamID][0][mid] = nil
local teamID = mexByID[unitID].refundTeamID
if teamID then
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - mexByID[unitID].refundTotal + mexByID[unitID].refundSoFar
end
mexByID[unitID] = nil
local mexGridID = oldGridID --Note: mexGridID is oldGridID of this pylon because mex is this pylon
-- takenMexId[unitID] = false
mexes[allyTeamID][mexGridID][mid] = orgMetal
mexByID[unitID].gridID = mexGridID
if mexGridID ~= 0 then
local ai = allyTeamInfo[allyTeamID]
ai.mexCount = ai.mexCount + 1
ai.mexMetal = ai.mexMetal + orgMetal
ai.mexSquaredSum = ai.mexSquaredSum + (orgMetal * orgMetal)
ai.grid[mexGridID].mexMetal = ai.grid[mexGridID].mexMetal + orgMetal
ai.grid[mexGridID].mexSquaredSum = ai.grid[mexGridID].mexSquaredSum + (orgMetal * orgMetal)
end
end
if debugMode then
Spring.Echo("RemovePylon end " .. unitID)
TableEcho(pylonList[allyTeamID])
TableEcho(pylon[allyTeamID])
end
end
local function AddPylonsInQueueToGrid()
if pylonGridQueue then
for pid,_ in pairs(pylonGridQueue) do
AddPylonToGrid(pid)
end
pylonGridQueue =false
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- PAYBACK
-- teamPayback[teamID] = {count = 0, toRemove = {}, data = {[1] = {unitID = unitID, cost = costOfUnit, repaid = howMuchHasBeenRepaid}}}
local function AddEnergyToPayback(unitID, unitDefID, unitTeam)
if unitPaybackTeamID[unitID] then
-- Only add units to payback once.
return
end
local def = paybackDefs[unitDefID]
unitPaybackTeamID[unitID] = unitTeam
local teamData = teamPayback[unitTeam]
teamData.count = teamData.count + 1
teamData.data[teamData.count] = {
unitID = unitID,
cost = def.cost,
repaid = 0,
}
teamData.metalDueOD = teamData.metalDueOD + def.cost
end
local function RemoveEnergyToPayback(unitID, unitDefID)
local unitTeam = unitPaybackTeamID[unitID]
if unitTeam then -- many energy pieces will not have a payback when destroyed
local teamData = teamPayback[unitTeam]
teamData.toRemove[unitID] = true
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Overdrive and resource handling
local function OptimizeOverDrive(allyTeamID,allyTeamData,allyE,maxGridCapacity)
local summedMetalProduction = 0
local summedBaseMetal = 0
local summedOverdrive = 0
local maxedMetalProduction = 0
local maxedBaseMetal = 0
local maxedOverdrive = 0
local allyMetal = allyTeamData.mexMetal
local allyMetalSquared = allyTeamData.mexSquaredSum
local allyTeamMexes = mexes[allyTeamID]
local energyWasted = allyE
local gridEnergySpent = {}
local gridMetalGain = {}
local mexBaseMetal = {}
local privateBaseMetal = {}
local reCalc = true
local maxedGrid = {}
while reCalc do -- calculate overdrive for as long as a new grid is not maxed
reCalc = false
for i = 1, allyTeamData.grids do -- loop through grids
if not (maxedGrid[i] or allyTeamData.nilGrid[i]) then -- do not check maxed grids
gridEnergySpent[i] = 0
gridMetalGain[i] = 0
for unitID, orgMetal in pairs(allyTeamMexes[i]) do -- loop mexes
local stunned_or_inbuld = spGetUnitIsStunned(unitID) or (spGetUnitRulesParam(unitID,"disarmed") == 1)
if stunned_or_inbuld then
orgMetal = 0
end
local incomeFactor = spGetUnitRulesParam(unitID, "resourceGenerationFactor") or 1
if incomeFactor then
orgMetal = orgMetal*incomeFactor
end
local mexE = 0
if (allyMetalSquared > 0) then -- divide energy in ratio given by squared metal from mex
mexE = allyE*(orgMetal * orgMetal)/ allyMetalSquared --the fraction of E to be consumed with respect to all other Mex
energyWasted = energyWasted-mexE --leftover E minus Mex usage
gridEnergySpent[i] = gridEnergySpent[i] + mexE
-- if a grid is being too overdriven it has become maxed.
-- the grid's mexSqauredSum is used for best distribution
if gridEnergySpent[i] > maxGridCapacity[i] then --final Mex to be looped since we are out of E to OD the rest of the Mex
gridMetalGain[i] = 0
local gridE = maxGridCapacity[i]
local gridMetalSquared = allyTeamData.grid[i].mexSquaredSum
if gridMetalSquared <= 0 and not sentErrorWarning then
Spring.Echo("** Warning: gridMetalSquared <= 0 **")
Spring.Echo(gridMetalSquared)
sentErrorWarning = true
end
gridEnergySpent[i] = maxGridCapacity[i]
summedMetalProduction = 0
summedBaseMetal = 0
summedOverdrive = 0
maxedGrid[i] = true
reCalc = true
allyE = allyE - gridE
energyWasted = allyE
for unitID, orgMetal in pairs(allyTeamMexes[i]) do --re-distribute the grid energy to Mex (again! except taking account the limited energy of the grid)
local stunned_or_inbuld = spGetUnitIsStunned(unitID) or (spGetUnitRulesParam(unitID,"disarmed") == 1)
if stunned_or_inbuld then
orgMetal = 0
end
local incomeFactor = spGetUnitRulesParam(unitID,"resourceGenerationFactor")
if incomeFactor then
orgMetal = orgMetal*incomeFactor
end
local mexE = gridE*(orgMetal * orgMetal)/ gridMetalSquared
local metalMult = energyToExtraM(mexE)
local thisMexM = orgMetal + orgMetal * metalMult
spSetUnitRulesParam(unitID, "overdrive", 1+mexE/5, inlosTrueTable)
spSetUnitRulesParam(unitID, "overdrive_energyDrain", mexE, inlosTrueTable)
spSetUnitRulesParam(unitID, "current_metalIncome", thisMexM, inlosTrueTable)
spSetUnitRulesParam(unitID, "overdrive_proportion", metalMult, inlosTrueTable)
maxedMetalProduction = maxedMetalProduction + thisMexM
maxedBaseMetal = maxedBaseMetal + orgMetal
maxedOverdrive = maxedOverdrive + orgMetal * metalMult
allyMetalSquared = allyMetalSquared - orgMetal * orgMetal
gridMetalGain[i] = gridMetalGain[i] + orgMetal * metalMult
if mexByID[unitID].refundTeamID then
mexBaseMetal[unitID] = orgMetal
end
end
break --finish distributing energy to 1 grid, go to next grid
end
end
local metalMult = energyToExtraM(mexE)
local thisMexM = orgMetal + orgMetal * metalMult
spSetUnitRulesParam(unitID, "overdrive", 1+mexE/5, inlosTrueTable)
spSetUnitRulesParam(unitID, "overdrive_energyDrain", mexE, inlosTrueTable)
spSetUnitRulesParam(unitID, "current_metalIncome", thisMexM, inlosTrueTable)
spSetUnitRulesParam(unitID, "overdrive_proportion", metalMult, inlosTrueTable)
summedMetalProduction = summedMetalProduction + thisMexM
summedBaseMetal = summedBaseMetal + orgMetal
summedOverdrive = summedOverdrive + orgMetal * metalMult
gridMetalGain[i] = gridMetalGain[i] + orgMetal * metalMult
if mexByID[unitID].refundTeamID then
mexBaseMetal[unitID] = orgMetal
end
end
if reCalc then
break
end
end
end
end
for unitID, value in pairs(mexBaseMetal) do
local teamID = mexByID[unitID].refundTeamID
local private_share = value*MEX_REFUND_SHARE*mexByID[unitID].refundTime/mexByID[unitID].refundTimeTotal
privateBaseMetal[teamID] = (privateBaseMetal[teamID] or 0) + private_share
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - private_share
mexByID[unitID].refundTime = mexByID[unitID].refundTime - 1
mexByID[unitID].refundSoFar = mexByID[unitID].refundSoFar + private_share
if mexByID[unitID].refundTime <= 0 then
mexByID[unitID].refundTeamID = nil
mexByID[unitID].refundTime = nil
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - mexByID[unitID].refundTotal + mexByID[unitID].refundSoFar
end
end
if energyWasted < 0.01 then
energyWasted = 0
end
return energyWasted,
summedMetalProduction + maxedMetalProduction,
summedBaseMetal + maxedBaseMetal,
summedOverdrive + maxedOverdrive,
gridEnergySpent,
gridMetalGain,
privateBaseMetal
end
local function teamEcho(team, st)
if team == 0 then
Spring.Echo(st)
end
end
local lastTeamOverdriveSpending = {}
function gadget:GameFrame(n)
if (n%TEAM_SLOWUPDATE_RATE == 1) then
lowPowerUnits.inner = {count = 0, units = {}}
for allyTeamID, allyTeamData in pairs(allyTeamInfo) do
--// Check if pylons changed their active status (emp, reverse-build, ..)
local list = pylonList[allyTeamID]
for i = 1, list.count do
local unitID = list.data[i]
local pylonData = pylon[allyTeamID][unitID]
if pylonData then
if spValidUnitID(unitID) then
local stunned_or_inbuld = spGetUnitIsStunned(unitID) or
(spGetUnitRulesParam(unitID,"disarmed") == 1) or
(spGetUnitRulesParam(unitID,"morphDisable") == 1)
local states = spGetUnitStates(unitID)
local currentlyActive = (not stunned_or_inbuld) and states and states.active
if (currentlyActive) and (not pylonData.active) then
ReactivatePylon(unitID)
elseif (not currentlyActive) and (pylonData.active) then
DeactivatePylon(unitID)
end
end
elseif not spammedError then
Spring.Echo("Pylon problem detected in status check.")
end
end
AddPylonsInQueueToGrid()
--// Calculate total energy and other metal income from structures and units
-- Does not include reclaim
local teamEnergy = {}
local allyTeamEnergyIncome = 0
local allyTeamExpense = 0
local allyTeamEnergySpare = 0
local allyTeamPositiveSpare = 0
local allyTeamNegativeSpare = 0
local allyTeamEnergyCurrent = 0
local allyTeamEnergyMax = 0
local allyTeamMiscMetalIncome = 0
local sumInc = 0
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
-- Calculate total energy and misc. metal income from units and structures
local genList = generatorList[allyTeamID][teamID]
local gen = generator[allyTeamID][teamID]
local sumMetal = 0
local sumEnergy = 0
for i = 1, genList.count do
local unitID = genList.data[i]
local data = gen[unitID]
if spValidUnitID(unitID) then
if spGetUnitRulesParam(unitID, "isWind") then
local energy = spGetUnitRulesParam(unitID,"current_energyIncome") or 0
sumEnergy = sumEnergy + energy
else
local stunned_or_inbuld = spGetUnitIsStunned(unitID)
local states = spGetUnitStates(unitID)
local currentlyActive = not stunned_or_inbuld
metal, energy = 0, 0, 0
if currentlyActive then
local incomeFactor = spGetUnitRulesParam(unitID,"resourceGenerationFactor") or 1
metal = data.metalIncome*incomeFactor
energy = data.energyIncome*incomeFactor
sumMetal = sumMetal + metal
sumEnergy = sumEnergy + energy
end
spSetUnitRulesParam(unitID, "current_metalIncome", metal, inlosTrueTable)
spSetUnitRulesParam(unitID, "current_energyIncome", energy, inlosTrueTable)
end
end
end
-- Collect energy information and contribute to ally team data.
teamEnergy[teamID] = {}
local te = teamEnergy[teamID]
te.cur, te.max, te.pull, _, te.exp, _, te.sent, te.rec = spGetTeamResources(teamID, "energy")