forked from clusterio/subspace_storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.lua
1325 lines (1152 loc) · 41.6 KB
/
control.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
require("config")
require("mod-gui")
require("LinkedList")
local json = require("json")
------------------------------------------------------------
--[[Method that handle creation and deletion of entities]]--
------------------------------------------------------------
function OnBuiltEntity(event)
local entity = event.created_entity
if not (entity and entity.valid) then return end
local player = false
if event.player_index then player = game.players[event.player_index] end
local spawn
if player and player.valid then
spawn = game.players[event.player_index].force.get_spawn_position(entity.surface)
else
spawn = game.forces["player"].get_spawn_position(entity.surface)
end
local x = entity.position.x - spawn.x
local y = entity.position.y - spawn.y
local name = entity.name
if name == "entity-ghost" then name = entity.ghost_name end
if ENTITY_TELEPORTATION_RESTRICTION and global.config.PlacableArea>0 and (name == INPUT_CHEST_NAME or name == OUTPUT_CHEST_NAME or name == INPUT_TANK_NAME or name == OUTPUT_TANK_NAME) then
if (x < global.config.PlacableArea and x > 0-global.config.PlacableArea and y < global.config.PlacableArea and y > 0-global.config.PlacableArea) then
--only add entities that are not ghosts
if entity.type ~= "entity-ghost" then
AddEntity(entity)
end
else
if player and player.valid then
-- Tell the player what is happening
if player then player.print("Attempted placing entity outside allowed area (placed at x "..x.." y "..y.." out of allowed "..global.config.PlacableArea..")") end
-- kill entity, try to give it back to the player though
if not player.mine_entity(entity, true) then
entity.destroy()
end
else
-- it wasn't placed by a player, we can't tell em whats wrong
entity.destroy()
end
end
else
--only add entities that are not ghosts
if entity.type ~= "entity-ghost" then
AddEntity(entity)
end
end
end
function AddAllEntitiesOfNames(names)
local filters = {}
for i = 1, #names do
local name = names[i]
filters[#filters + 1] = {name = name}
end
for k, surface in pairs(game.surfaces) do
AddEntities(surface.find_entities_filtered(filters))
end
end
function AddEntities(entities)
for k, entity in pairs(entities) do
AddEntity(entity)
end
end
function AddEntity(entity)
if entity.name == INPUT_CHEST_NAME then
--add the chests to a lists if these chests so they can be interated over
AddLink(global.inputChestsData.entitiesData, {
entity = entity,
inv = entity.get_inventory(defines.inventory.chest)
}, entity.unit_number)
elseif entity.name == OUTPUT_CHEST_NAME then
--add the chests to a lists if these chests so they can be interated over
AddLink(global.outputChestsData.entitiesData, {
entity = entity,
inv = entity.get_inventory(defines.inventory.chest),
filterCount = entity.prototype.filter_count
}, entity.unit_number)
elseif entity.name == INPUT_TANK_NAME then
--add the chests to a lists if these chests so they can be interated over
AddLink(global.inputTanksData.entitiesData, {
entity = entity,
fluidbox = entity.fluidbox
}, entity.unit_number)
elseif entity.name == OUTPUT_TANK_NAME then
--add the chests to a lists if these chests so they can be interated over
AddLink(global.outputTanksData.entitiesData, {
entity = entity,
fluidbox = entity.fluidbox
}, entity.unit_number)
--previous version made then inactive which isn't desired anymore
entity.active = true
elseif entity.name == TX_COMBINATOR_NAME then
global.txControls[entity.unit_number] = entity.get_or_create_control_behavior()
elseif entity.name == RX_COMBINATOR_NAME then
global.rxControls[entity.unit_number] = entity.get_or_create_control_behavior()
entity.operable=false
elseif entity.name == INV_COMBINATOR_NAME then
global.invControls[entity.unit_number] = entity.get_or_create_control_behavior()
entity.operable=false
elseif entity.name == INPUT_ELECTRICITY_NAME then
AddLink(global.inputElectricityData.entitiesData, entity, entity.unit_number)
elseif entity.name == OUTPUT_ELECTRICITY_NAME then
AddLink(global.outputElectricityData.entitiesData, {
entity = entity,
bufferSize = entity.electric_buffer_size
}, entity.unit_number)
end
end
function OnKilledEntity(event)
local entity = event.entity
if entity.type ~= "entity-ghost" then
--remove the entities from the tables as they are dead
if entity.name == INPUT_CHEST_NAME then
RemoveLink(global.inputChestsData.entitiesData, entity.unit_number)
elseif entity.name == OUTPUT_CHEST_NAME then
RemoveLink(global.outputChestsData.entitiesData, entity.unit_number)
elseif entity.name == INPUT_TANK_NAME then
RemoveLink(global.inputTanksData.entitiesData, entity.unit_number)
elseif entity.name == OUTPUT_TANK_NAME then
RemoveLink(global.outputTanksData.entitiesData, entity.unit_number)
elseif entity.name == TX_COMBINATOR_NAME then
global.txControls[entity.unit_number] = nil
elseif entity.name == RX_COMBINATOR_NAME then
global.rxControls[entity.unit_number] = nil
elseif entity.name == INV_COMBINATOR_NAME then
global.invControls[entity.unit_number] = nil
elseif entity.name == INPUT_ELECTRICITY_NAME then
RemoveLink(global.inputElectricityData.entitiesData, entity.unit_number)
elseif entity.name == OUTPUT_ELECTRICITY_NAME then
RemoveLink(global.outputElectricityData.entitiesData, entity.unit_number)
end
end
end
-----------------------------
--[[Thing creation events]]--
-----------------------------
script.on_event(defines.events.on_built_entity, function(event)
OnBuiltEntity(event)
end)
script.on_event(defines.events.on_robot_built_entity, function(event)
OnBuiltEntity(event)
end)
----------------------------
--[[Thing killing events]]--
----------------------------
script.on_event(defines.events.on_entity_died, function(event)
OnKilledEntity(event)
end)
script.on_event(defines.events.on_robot_pre_mined, function(event)
OnKilledEntity(event)
end)
script.on_event(defines.events.on_pre_player_mined_item, function(event)
OnKilledEntity(event)
end)
------------------------------
--[[Thing resetting events]]--
------------------------------
script.on_init(function()
Reset()
end)
script.on_configuration_changed(function(data)
if data.mod_changes and data.mod_changes["clusterio"] then
Reset()
end
end)
function Reset()
global.ticksSinceMasterPinged = 601
global.isConnected = false
global.prevIsConnected = false
global.allowedToMakeElectricityRequests = false
global.workTick = 0
global.hasInfiniteResources = false
if global.config == nil then
global.config =
{
BWitems = {},
item_is_whitelist = false,
BWfluids = {},
fluid_is_whitelist = false,
PlacableArea = 200
}
end
if global.invdata == nil then
global.invdata = {}
end
global.outputList = {}
global.inputList = {}
global.itemStorage = {}
global.useableItemStorage = {}
global.inputChestsData =
{
entitiesData = CreateDoublyLinkedList()
}
global.outputChestsData =
{
entitiesData = CreateDoublyLinkedList(),
requests = {},
requestsLL = nil
}
global.inputTanksData =
{
entitiesData = CreateDoublyLinkedList()
}
global.outputTanksData =
{
entitiesData = CreateDoublyLinkedList(),
requests = {},
requestsLL = nil
}
global.inputElectricityData =
{
entitiesData = CreateDoublyLinkedList()
}
global.outputElectricityData =
{
entitiesData = CreateDoublyLinkedList(),
requests = {},
requestsLL = nil
}
global.lastElectricityUpdate = 0
global.maxElectricity = 100000000000000 / ELECTRICITY_RATIO --100TJ assuming a ratio of 1.000.000
global.rxControls = {}
global.rxBuffer = {}
global.txControls = {}
global.invControls = {}
AddAllEntitiesOfNames(
{
INPUT_CHEST_NAME,
OUTPUT_CHEST_NAME,
INPUT_TANK_NAME,
OUTPUT_TANK_NAME,
RX_COMBINATOR_NAME,
TX_COMBINATOR_NAME,
INV_COMBINATOR_NAME,
INPUT_ELECTRICITY_NAME,
OUTPUT_ELECTRICITY_NAME
})
end
script.on_event(defines.events.on_tick, function(event)
-- TX Combinators must run every tick to catch single pulses
HandleTXCombinators()
--If the mod isn't connected then still pretend that it's
--so items requests and removals can be fulfilled
if global.hasInfiniteResources then
global.ticksSinceMasterPinged = 0
end
global.ticksSinceMasterPinged = global.ticksSinceMasterPinged + 1
if global.ticksSinceMasterPinged < 300 then
global.isConnected = true
if global.prevIsConnected == false then
global.workTick = 0
end
if global.workTick == 0 then
--importing electricity should be limited because it requests so
--much at once. If it wasn't limited then the electricity could
--make small burst of requests which requests >10x more than it needs
--which could temporarily starve other networks.
--Updating every 4 seconds give two chances to give electricity in
--the 10 second period.
local timeSinceLastElectricityUpdate = game.tick - global.lastElectricityUpdate
global.allowedToMakeElectricityRequests = timeSinceLastElectricityUpdate > 60 * 3.5
end
--First retrieve requests and then fulfill them
if global.workTick >= 0 and global.workTick < TICKS_TO_COLLECT_REQUESTS then
if global.workTick == 0 then
ResetRequestGathering()
end
RetrieveGetterRequests(global.allowedToMakeElectricityRequests)
elseif global.workTick >= TICKS_TO_COLLECT_REQUESTS and global.workTick < TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS then
if global.workTick == TICKS_TO_COLLECT_REQUESTS then
UpdateUseableStorage()
PrepareToFulfillRequests()
ResetFulfillRequestIterators()
end
FulfillGetterRequests(global.allowedToMakeElectricityRequests)
end
--Emptying putters will continiously happen
--while requests are gathered and fulfilled
if global.workTick >= 0 and global.workTick < TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS then
if global.workTick == 0 then
ResetPutterIterators()
end
EmptyPutters()
end
if global.workTick == TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS + 0 then
ExportInputList()
global.workTick = global.workTick + 1
elseif global.workTick == TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS + 1 then
ExportOutputList()
global.workTick = global.workTick + 1
elseif global.workTick == TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS + 2 then
ExportFluidFlows()
global.workTick = global.workTick + 1
elseif global.workTick == TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS + 3 then
ExportItemFlows()
--Restart loop
global.workTick = 0
if global.allowedToMakeElectricityRequests then
global.lastElectricityUpdate = game.tick
end
else
global.workTick = global.workTick + 1
end
else
global.isConnected = false
end
global.prevIsConnected = global.isConnected
-- RX Combinators are set and then cleared on sequential ticks to create pulses
UpdateRXCombinators()
end)
function UpdateUseableStorage()
for k, v in pairs(global.itemStorage) do
GiveItemsToUseableStorage(k, v)
global.useableItemStorage[k].initialItemCount = global.useableItemStorage[k].remainingItems
end
global.itemStorage = {}
end
----------------------------------------
--[[Getter and setter update methods]]--
----------------------------------------
function ResetRequestGathering()
RestartIterator(global.outputChestsData.entitiesData , TICKS_TO_COLLECT_REQUESTS)
global.outputChestsData.requests = {}
RestartIterator(global.outputTanksData.entitiesData , TICKS_TO_COLLECT_REQUESTS)
global.outputTanksData.requests = {}
RestartIterator(global.outputElectricityData.entitiesData, TICKS_TO_COLLECT_REQUESTS)
global.outputElectricityData.requests = {}
end
function ResetFulfillRequestIterators()
RestartIterator(global.outputChestsData.requestsLL , TICKS_TO_FULFILL_REQUESTS)
RestartIterator(global.outputTanksData.requestsLL , TICKS_TO_FULFILL_REQUESTS)
RestartIterator(global.outputElectricityData.requestsLL, TICKS_TO_FULFILL_REQUESTS)
end
function ResetPutterIterators()
RestartIterator(global.inputChestsData.entitiesData , TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS)
RestartIterator(global.inputTanksData.entitiesData , TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS)
RestartIterator(global.inputElectricityData.entitiesData, TICKS_TO_COLLECT_REQUESTS + TICKS_TO_FULFILL_REQUESTS)
end
function PrepareToFulfillRequests()
global.outputChestsData.requestsLL = ArrayToLinkedListOfRequests(global.outputChestsData.requests , true)
global.outputTanksData.requestsLL = ArrayToLinkedListOfRequests(global.outputTanksData.requests , false)
global.outputElectricityData.requestsLL = ArrayToLinkedListOfRequests(global.outputElectricityData.requests, false)
end
function RetrieveGetterRequests(allowedToGetElectricityRequests)
local chestLL = global.outputChestsData.entitiesData
for i = 1, chestLL.iterator.linksPerTick do
local nextLink = NextLink(chestLL)
if nextLink ~= nil then
GetOutputChestRequest(global.outputChestsData.requests, nextLink.data)
end
end
local tankLL = global.outputTanksData.entitiesData
for i = 1, tankLL.iterator.linksPerTick do
local nextLink = NextLink(tankLL)
if nextLink ~= nil then
GetOutputTankRequest(global.outputTanksData.requests, nextLink.data)
end
end
if allowedToGetElectricityRequests then
local electricityLL = global.outputElectricityData.entitiesData
for i = 1, electricityLL.iterator.linksPerTick do
local nextLink = NextLink(electricityLL)
if nextLink ~= nil then
GetOutputElectricityRequest(global.outputElectricityData.requests, nextLink.data)
end
end
end
end
function FulfillGetterRequests(allowedToGetElectricityRequests)
local chestLL = global.outputChestsData.requestsLL
for i = 1, chestLL.iterator.linksPerTick do
local nextLink = NextLink(chestLL)
if nextLink ~= nil then
FulfillOutputChestRequest(nextLink.data)
end
end
local tankLL = global.outputTanksData.requestsLL
for i = 1, tankLL.iterator.linksPerTick do
local nextLink = NextLink(tankLL)
if nextLink ~= nil then
FulfillOutputTankRequest(nextLink.data)
end
end
if allowedToGetElectricityRequests then
local electricityLL = global.outputElectricityData.requestsLL
for i = 1, electricityLL.iterator.linksPerTick do
local nextLink = NextLink(electricityLL)
if nextLink ~= nil then
FulfillOutputElectricityRequest(nextLink.data)
end
end
end
end
function EmptyPutters()
local chestLL = global.inputChestsData.entitiesData
for i = 1, chestLL.iterator.linksPerTick do
local nextLink = NextLink(chestLL)
if nextLink ~= nil then
HandleInputChest(nextLink.data)
end
end
local tankLL = global.inputTanksData.entitiesData
for i = 1, tankLL.iterator.linksPerTick do
local nextLink = NextLink(tankLL)
if nextLink ~= nil then
HandleInputTank(nextLink.data)
end
end
local electricityLL = global.inputElectricityData.entitiesData
for i = 1, electricityLL.iterator.linksPerTick do
local nextLink = NextLink(electricityLL)
if nextLink ~= nil then
HandleInputElectricity(nextLink.data)
end
end
end
function HandleInputChest(entityData)
local entity = entityData.entity
local inventory = entityData.inv
if entity.valid then
--get the content of the chest
local items = inventory.get_contents()
--write everything to the file
for itemName, itemCount in pairs(items) do
if isItemLegal(itemName) then
AddItemToInputList(itemName, itemCount)
inventory.remove({name = itemName, count = itemCount})
end
end
end
end
function HandleInputTank(entityData)
local entity = entityData.entity
local fluidbox = entityData.fluidbox
if entity.valid then
--get the content of the chest
local fluid = fluidbox[1]
if fluid ~= nil and math.floor(fluid.amount) > 0 then
if isFluidLegal(fluid.name) then
AddItemToInputList(fluid.name, math.floor(fluid.amount))
fluid.amount = fluid.amount - math.floor(fluid.amount)
end
end
fluidbox[1] = fluid
end
end
function HandleInputElectricity(entity)
--if there is too much energy in the network then stop outputting more
if global.invdata and global.invdata[ELECTRICITY_ITEM_NAME] and global.invdata[ELECTRICITY_ITEM_NAME] >= global.maxElectricity then
return
end
if entity.valid then
local energy = entity.energy
local availableEnergy = math.floor(energy / ELECTRICITY_RATIO)
if availableEnergy > 0 then
AddItemToInputList(ELECTRICITY_ITEM_NAME, availableEnergy)
entity.energy = energy - (availableEnergy * ELECTRICITY_RATIO)
end
end
end
function GetOutputChestRequest(requests, entityData)
local entity = entityData.entity
local chestInventory = entityData.inv
local filterCount = entityData.filterCount
--Don't insert items into the chest if it's being deconstructed
--as that just leads to unnecessary bot work
if entity.valid and not entity.to_be_deconstructed(entity.force) then
--Go though each request slot
for i = 1, filterCount do
local requestItem = entity.get_request_slot(i)
--Some request slots may be empty and some items are not allowed
--to be imported
if requestItem ~= nil and isItemLegal(requestItem.name) then
local itemsInChest = chestInventory.get_item_count(requestItem.name)
--If there isn't enough items in the chest
local missingAmount = requestItem.count - itemsInChest
if missingAmount > 0 then
local entry = AddRequestToTable(requests, requestItem.name, missingAmount, entity)
entry.inv = chestInventory
end
end
end
end
end
function GetOutputTankRequest(requests, entityData)
local entity = entityData.entity
local fluidbox = entityData.fluidbox
--The type of fluid the tank should output
--is determined by the recipe set in the entity.
--If no recipe is set then it shouldn't output anything
local recipe = entity.get_recipe()
if entity.valid and recipe ~= nil then
--Get name of the fluid to output
local fluidName = recipe.products[1].name
--Some fluids may be illegal. If that's the case then don't process them
if isFluidLegal(fluidName) then
--Either get the current fluid or reset it to the requested fluid
local fluid = fluidbox[1] or {name = fluidName, amount = 0}
--If the current fluid isn't the correct fluid
--then remove that fluid
if fluid.name ~= fluidName then
fluid = {name = fluidName, amount = 0}
end
local missingFluid = math.max(math.ceil(MAX_FLUID_AMOUNT - fluid.amount), 0)
--If the entity is missing fluid than add a request for fluid
if missingFluid > 0 then
local entry = AddRequestToTable(requests, fluidName, missingFluid, entity)
--Add fluid to the request so it doesn't have to be created again
entry.fluid = fluid
entry.fluidbox = fluidbox
end
end
end
end
function GetOutputElectricityRequest(requests, entityData)
local entity = entityData.entity
local bufferSize = entityData.bufferSize
if entity.valid then
local energy = entity.energy
local missingElectricity = math.floor((bufferSize - energy) / ELECTRICITY_RATIO)
if missingElectricity > 0 then
local entry = AddRequestToTable(requests, ELECTRICITY_ITEM_NAME, missingElectricity, entity)
entry.energy = energy
end
end
end
function FulfillOutputChestRequest(requests)
EvenlyDistributeItems(requests, OutputChestInputMethod)
end
function FulfillOutputTankRequest(requests)
EvenlyDistributeItems(requests, OutputTankInputMethod)
end
function FulfillOutputElectricityRequest(requests)
EvenlyDistributeItems(requests, OutputElectricityinputMethod)
end
function OutputChestInputMethod(request, itemName, evenShareOfItems)
if request.storage.valid then
local itemsToInsert =
{
name = itemName,
count = evenShareOfItems
}
return request.inv.insert(itemsToInsert)
else
return 0
end
end
function OutputTankInputMethod(request, _, evenShareOfFluid)
if request.storage.valid then
request.fluid.amount = request.fluid.amount + evenShareOfFluid
--Need to set steams heat because otherwise it's too low
if request.fluid.name == "steam" then
request.fluid.temperature = 165
end
request.fluidbox[1] = request.fluid
return evenShareOfFluid
else
return 0
end
end
function OutputElectricityinputMethod(request, _, evenShare)
if request.storage.valid then
request.storage.energy = request.energy + (evenShare * ELECTRICITY_RATIO)
return evenShare
else
return 0
end
end
function ArrayToLinkedListOfRequests(array, shouldSort)
local linkedList = CreateDoublyLinkedList()
for itemName, requestInfo in pairs(array) do
if shouldSort then
--To be able to distribute it fairly, the requesters need to be sorted in order of how
--much they are missing, so the requester with the least missing of the item will be first.
--If this isn't done then there could be items leftover after they have been distributed
--even though they could all have been distributed if they had been distributed in order.
table.sort(requestInfo.requesters, function(left, right)
return left.missingAmount < right.missingAmount
end)
end
for i = 1, #requestInfo.requesters do
local request = requestInfo.requesters[i]
request.itemName = itemName
request.requestedAmount = requestInfo.requestedAmount
AddLink(linkedList, request, 0)
end
end
return linkedList
end
function AddRequestToTable(requests, itemName, missingAmount, storage)
--If this is the first entry for this item type then
--create a table for this item type first
if requests[itemName] == nil then
requests[itemName] =
{
requestedAmount = 0,
requesters = {}
}
end
local itemEntry = requests[itemName]
--Add missing item to the count and add this chest inv to the list
itemEntry.requestedAmount = itemEntry.requestedAmount + missingAmount
itemEntry.requesters[#itemEntry.requesters + 1] =
{
storage = storage,
missingAmount = missingAmount
}
return itemEntry.requesters[#itemEntry.requesters]
end
function EvenlyDistributeItems(request, functionToInsertItems)
--Take the required item count from storage or how much storage has
local itemCount = RequestItemsFromUseableStorage(request.itemName, request.requestedAmount)
--need to scale all the requests according to how much of the requested items are available.
--Can't be more than 100% because otherwise the chests will overfill
local avaiableItemsRatio = math.min(GetInitialItemCount(request.itemName) / request.requestedAmount, 1)
--Floor is used here so no chest uses more than its fair share.
--If they used more then the last entity would bet less which would be
--an issue with +1000 entities requesting items.
local chestHold = math.floor(request.missingAmount * avaiableItemsRatio)
--If there is less items than requests then floor will return zero and thus not
--distributes the remaining items. Thus here the mining is set to 1 but still
--it can't be set to 1 if there is no more items to distribute, which is what
--the last min corresponds to.
chestHold = math.max(chestHold, 1)
chestHold = math.min(chestHold, itemCount)
--If there wasn't enough items to fulfill the whole request
--then ask for more items from outside the game
local missingItems = request.missingAmount - chestHold
if missingItems > 0 then
AddItemToOutputList(request.itemName, missingItems)
end
if itemCount > 0 then
--No need to insert 0 of something
if chestHold > 0 then
local insertedItemsCount = functionToInsertItems(request, request.itemName, chestHold)
itemCount = itemCount - insertedItemsCount
end
--In some cases it's possible for the entity to not use up
--all the items.
--In those cases the items should be put back into storage.
if itemCount > 0 then
GiveItemsToUseableStorage(request.itemName, itemCount)
end
end
end
-----------------------------------
--[[Methods that write to files]]--
-----------------------------------
function ExportInputList()
local exportStrings = {}
for k,v in pairs(global.inputList) do
exportStrings[#exportStrings + 1] = k.." "..v.."\n"
end
global.inputList = {}
if #exportStrings > 0 then
--only write to file once as i/o is slow
--it's much faster to concatenate all the lines with table.concat
--instead of doing it with the .. operator
game.write_file(OUTPUT_FILE, table.concat(exportStrings), true, global.write_file_player or 0)
end
end
function ExportOutputList()
local exportStrings = {}
for k,v in pairs(global.outputList) do
exportStrings[#exportStrings + 1] = k.." "..v.."\n"
end
global.outputList = {}
if #exportStrings > 0 then
--only write to file once as i/o is slow
--it's much faster to concatenate all the lines with table.concat
--instead of doing it with the .. operator
game.write_file(ORDER_FILE, table.concat(exportStrings), true, global.write_file_player or 0)
end
end
function ExportItemFlows()
local flowreport = {type="item",flows={}}
for _,force in pairs(game.forces) do
flowreport.flows[force.name] = {
input_counts = force.item_production_statistics.input_counts,
output_counts = force.item_production_statistics.output_counts,
}
end
game.write_file(FLOWS_FILE, json:encode(flowreport).."\n", true, global.write_file_player or 0)
end
function ExportFluidFlows()
local flowreport = {type="fluid",flows={}}
for _,force in pairs(game.forces) do
flowreport.flows[force.name] = {
input_counts = force.fluid_production_statistics.input_counts,
output_counts = force.fluid_production_statistics.output_counts,
}
end
game.write_file(FLOWS_FILE, json:encode(flowreport).."\n", true, global.write_file_player or 0)
end
---------------------------------
--[[Update combinator methods]]--
---------------------------------
local validsignals
function AddFrameToRXBuffer(frame)
if not validsignals then
validsignals = {
["virtual"] = game.virtual_signal_prototypes,
["fluid"] = game.fluid_prototypes,
["item"] = game.item_prototypes
}
end
-- Add a frame to the buffer. return remaining space in buffer
-- if buffer is full, drop frame
if #global.rxBuffer >= MAX_RX_BUFFER_SIZE then return 0 end
-- frame = {{count=42,name="signal-grey",type="virtual"},{...},...}
local signals = {}
local index = 1
for _,signal in pairs(frame) do
if validsignals[signal.type] and validsignals[signal.type][signal.name] then
signals[index] =
{
index=index,
count=signal.count,
signal={ name=signal.name, type=signal.type }
}
index = index + 1
--TODO: break if too many?
--TODO: error token on mismatched signals? maybe mismatch1-n signals?
end
end
if index > 1 then table.insert(global.rxBuffer,signals) end
return MAX_RX_BUFFER_SIZE - #global.rxBuffer
end
function HandleTXCombinators()
-- Check all TX Combinators, and if condition satisfied, add frame to transmit buffer
-- frame = {{count=42,name="signal-grey",type="virtual"},{...},...}
local signals = {["item"]={},["virtual"]={},["fluid"]={}}
for i,txControl in pairs(global.txControls) do
if txControl.valid then
local frame = txControl.signals_last_tick
if frame then
for _,signal in pairs(frame) do
local signalType = signal.signal.type
local signalName = signal.signal.name
signals[signalType][signalName] = (signals[signalType][signalName] or 0) + signal.count
end
end
end
end
--Don't send the exact same signals in a row
if AreTablesSame(global.oldTXSignals, signals) then
global.oldTXSignals = signals
return
end
global.oldTXSignals = signals
local frame = {}
for type,arr in pairs(signals) do
for name,count in pairs(arr) do
table.insert(frame,{count=count,name=name,type=type})
end
end
if #frame > 0 then
if global.worldID then
table.insert(frame,1,{count=global.worldID,name="signal-srcid",type="virtual"})
end
table.insert(frame,{count=game.tick,name="signal-srctick",type="virtual"})
game.write_file(TX_BUFFER_FILE, json:encode(frame).."\n", true, global.write_file_player or 0)
-- Loopback for testing
--AddFrameToRXBuffer(frame)
end
end
function AreTablesSame(tableA, tableB)
if tableA == nil and tableB ~= nil then
return false
elseif tableA ~= nil and tableB == nil then
return false
elseif tableA == nil and tableB == nil then
return true
end
if TableWithKeysLength(tableA) ~= TableWithKeysLength(tableB) then
return false
end
for keyA, valueA in pairs(tableA) do
local valueB = tableB[keyA]
if type(valueA) == "table" and type(valueB) == "table" then
if not AreTablesSame(valueA, valueB) then
return false
end
elseif type(valueA) ~= type(valueB) then
return false
elseif valueA ~= valueB then
return false
end
end
return true
end
function TableWithKeysLength(tableA)
local count = 0
for k, v in pairs(tableA) do
count = count + 1
end
return count
end
function UpdateRXCombinators()
-- if the RX buffer is not empty, get a frame from it and output on all RX Combinators
if #global.rxBuffer > 0 then
local frame = table.remove(global.rxBuffer)
for i,rxControl in pairs(global.rxControls) do
if rxControl.valid then
rxControl.parameters = {parameters = frame}
rxControl.enabled = true
end
end
else
-- no frames to send right now, blank all...
for i,rxControl in pairs(global.rxControls) do
if rxControl.valid then
rxControl.parameters = {parameters = {}}
rxControl.enabled = false
end
end
end
end
function UpdateInvCombinators()
-- Update all inventory Combinators
-- Prepare a frame from the last inventory report, plus any virtuals
local invframe = {}
if global.worldID then
table.insert(invframe,{count=global.worldID,index=#invframe+1,signal={name="signal-localid",type="virtual"}})
end
local items = game.item_prototypes
local fluids = game.fluid_prototypes
local virtuals = game.virtual_signal_prototypes
if global.invdata then
for name,count in pairs(global.invdata) do
if virtuals[name] then
invframe[#invframe+1] = {count=count,index=#invframe+1,signal={name=name,type="virtual"}}
elseif fluids[name] then
invframe[#invframe+1] = {count=count,index=#invframe+1,signal={name=name,type="fluid"}}
elseif items[name] then
invframe[#invframe+1] = {count=count,index=#invframe+1,signal={name=name,type="item"}}
end
end
end
for i,invControl in pairs(global.invControls) do
if invControl.valid then
invControl.parameters={parameters=invframe}
invControl.enabled=true
end
end
end
---------------------
--[[Remote things]]--
---------------------
remote.add_interface("clusterio",
{
runcode=function(codeToRun) loadstring(codeToRun)() end,
import = function(itemName, itemCount)
GiveItemsToStorage(itemName, itemCount)
end,
importMany = function(jsonString)
local items = json:decode(jsonString)
for k, item in pairs(items) do
for itemName, itemCount in pairs(item) do
GiveItemsToStorage(itemName, itemCount)
end
end
end,
printStorage = function()
local items = ""
for itemName, itemCount in pairs(global.itemStorage) do
items = items.."\n"..itemName..": "..tostring(itemCount)
end
game.print(items)
end,