-
Notifications
You must be signed in to change notification settings - Fork 54
/
control.lua
1467 lines (1296 loc) · 58.9 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 "interface"
local MOD_NAME = "LogisticTrainNetwork"
local MINTRAINLENGTH = "min-train-length"
local MAXTRAINLENGTH = "max-train-length"
local MAXTRAINS = "ltn-max-trains"
local MINDELIVERYSIZE = "min-delivery-size"
local PRIORITY = "stop-priority"
local IGNOREMINDELIVERYSIZE = "ltn-no-min-delivery-size"
local LOCKEDSLOTS = "ltn-locked-slots"
local ISDEPOT = "ltn-depot"
local ErrorCodes = {
"red", -- circuit/signal error
"pink" -- duplicate stop name
}
local StopIDList = {} -- stopIDs list for on_tick updates
local match = string.match
local ceil = math.ceil
local sort = table.sort
---- BOOTSTRAP ----
do
local function initialize(oldVersion, newVersion)
--log("oldVersion: "..tostring(oldVersion)..", newVersion: "..tostring(newVersion))
---- disable instant blueprint in creative mode
if game.active_mods["creative-mode"] then
remote.call("creative-mode", "exclude_from_instant_blueprint", "logistic-train-stop-input")
remote.call("creative-mode", "exclude_from_instant_blueprint", "logistic-train-stop-output")
remote.call("creative-mode", "exclude_from_instant_blueprint", "logistic-train-stop-lamp-control")
end
---- initialize logger
global.messageBuffer = {}
global.StopDistances = global.StopDistances or {} -- station distance lookup table
---- initialize Dispatcher
global.Dispatcher = global.Dispatcher or {}
global.Dispatcher.availableTrains = global.Dispatcher.availableTrains or {}
global.Dispatcher.Deliveries = global.Dispatcher.Deliveries or {}
global.Dispatcher.Provided = global.Dispatcher.Provided or {}
global.Dispatcher.Requests = global.Dispatcher.Requests or {}
global.Dispatcher.RequestAge = global.Dispatcher.RequestAge or {}
-- clean obsolete global
global.Dispatcher.Requested = nil
global.Dispatcher.Orders = nil
global.Dispatcher.OrderAge = nil
global.Dispatcher.Storage = nil
global.useRailTanker = nil
-- update to 0.4
if oldVersion and oldVersion < "00.04.00" then
log("[LTN] Updating Dispatcher.Deliveries to 0.4.0.")
for trainID, delivery in pairs (global.Dispatcher.Deliveries) do
if delivery.shipment == nil then
if delivery.item and delivery.count then
global.Dispatcher.Deliveries[trainID].shipment = {[delivery.item] = delivery.count}
else
global.Dispatcher.Deliveries[trainID].shipment = {}
end
end
end
end
---- initialize stops
global.LogisticTrainStops = global.LogisticTrainStops or {}
local validLampControls = {}
if next(global.LogisticTrainStops) ~= nil then
for stopID, stop in pairs (global.LogisticTrainStops) do
global.LogisticTrainStops[stopID].errorCode = global.LogisticTrainStops[stopID].errorCode or 0
-- update to 0.3.8
if stop.lampControl == nil then
local lampctrl = stop.entity.surface.create_entity
{
name = "logistic-train-stop-lamp-control",
position = stop.input.position,
force = stop.entity.force
}
lampctrl.operable = false -- disable gui
lampctrl.minable = false
lampctrl.destructible = false -- don't bother checking if alive
lampctrl.connect_neighbour({target_entity=stop.input, wire=defines.wire_type.green})
lampctrl.get_control_behavior().parameters = {parameters={{index = 1, signal = {type="virtual",name="signal-white"}, count = 1 }}}
global.LogisticTrainStops[stopID].lampControl = lampctrl
global.LogisticTrainStops[stopID].input.operable = false
global.LogisticTrainStops[stopID].input.get_or_create_control_behavior().use_colors = true
global.LogisticTrainStops[stopID].input.get_or_create_control_behavior().circuit_condition = {condition = {comparator=">",first_signal={type="virtual",name="signal-anything"}}}
end
-- update to 1.1.1 remove orphaned lamp controls
validLampControls[stop.lampControl.unit_number] = true
-- update to 0.9.5
global.LogisticTrainStops[stopID].activeDeliveries = global.LogisticTrainStops[stopID].activeDeliveries or {}
if type(stop.activeDeliveries) ~= "table" then
stop.activeDeliveries = {}
for trainID, delivery in pairs (global.Dispatcher.Deliveries) do
if delivery.from == stop.entity.backer_name or delivery.to == stop.entity.backer_name then
table.insert(stop.activeDeliveries, trainID)
end
end
end
-- update to 0.10.2
global.LogisticTrainStops[stopID].trainLimit = global.LogisticTrainStops[stopID].trainLimit or 0
global.LogisticTrainStops[stopID].parkedTrainFacesStop = global.LogisticTrainStops[stopID].parkedTrainFacesStop or true
global.LogisticTrainStops[stopID].lockedSlots = global.LogisticTrainStops[stopID].lockedSlots or 0
UpdateStopOutput(stop) --make sure output is set
--UpdateStop(stopID)
end
script.on_event(defines.events.on_tick, ticker) --subscribe ticker when train stops exist
end
-- update to 1.1.1 remove orphaned lamp controls
if oldVersion and oldVersion < "01.01.01" then
local lcDeleted = 0
for _, surface in pairs(game.surfaces) do
local lcEntities = surface.find_entities_filtered{name="logistic-train-stop-lamp-control"}
for k, v in pairs(lcEntities) do
if not validLampControls[v.unit_number] then
v.destroy()
lcDeleted = lcDeleted+1
end
end
end
log("[LTN] removed "..lcDeleted.. " orphaned lamp control entities.")
end
end
script.on_load(function()
if global.LogisticTrainStops ~= nil and next(global.LogisticTrainStops) ~= nil then
script.on_event(defines.events.on_tick, ticker) --subscribe ticker when train stops exist
for stopID, stop in pairs(global.LogisticTrainStops) do --outputs are not stored in save
UpdateStopOutput(stop)
StopIDList[#StopIDList+1] = stopID
end
stopsPerTick = ceil(#StopIDList/(dispatcher_update_interval-1))
stopIdStartIndex = 1
end
log("[LTN] on_load: complete")
end)
script.on_init(function()
-- format version string to "00.00.00"
local oldVersion, newVersion = nil
local newVersionString = game.active_mods[MOD_NAME]
if newVersionString then
newVersion = string.format("%02d.%02d.%02d", string.match(newVersionString, "(%d+).(%d+).(%d+)"))
end
initialize(oldVersion, newVersion)
log("[LTN] on_init: ".. MOD_NAME.." "..tostring(newVersionString).." initialized.")
end)
script.on_configuration_changed(function(data)
if data and data.mod_changes[MOD_NAME] then
-- format version string to "00.00.00"
local oldVersion, newVersion = nil
local oldVersionString = data.mod_changes[MOD_NAME].old_version
if oldVersionString then
oldVersion = string.format("%02d.%02d.%02d", string.match(oldVersionString, "(%d+).(%d+).(%d+)"))
end
local newVersionString = data.mod_changes[MOD_NAME].new_version
if newVersionString then
newVersion = string.format("%02d.%02d.%02d", string.match(newVersionString, "(%d+).(%d+).(%d+)"))
end
initialize(oldVersion, newVersion)
log("[LTN] on_configuration_changed: ".. MOD_NAME.." "..tostring(newVersionString).." initialized. Previous version: "..tostring(oldVersionString))
end
end)
end
---- EVENTS ----
do --create stop
local function createStop(entity)
if global.LogisticTrainStops[entity.unit_number] then
if log_level >= 1 then printmsg({"ltn-message.error-duplicated-unit-number", entity.unit_number}) end
return
end
local posIn, posOut, rot
--log("Stop created at "..entity.position.x.."/"..entity.position.y..", orientation "..entity.direction)
if entity.direction == 0 then --SN
posIn = {entity.position.x, entity.position.y-1}
posOut = {entity.position.x-1, entity.position.y-1}
--tracks = entity.surface.find_entities_filtered{type="straight-rail", area={{entity.position.x-3, entity.position.y-3},{entity.position.x-1, entity.position.y+3}} }
rot = 0
elseif entity.direction == 2 then --WE
posIn = {entity.position.x, entity.position.y}
posOut = {entity.position.x, entity.position.y-1}
--tracks = entity.surface.find_entities_filtered{type="straight-rail", area={{entity.position.x-3, entity.position.y-3},{entity.position.x+3, entity.position.y-1}} }
rot = 2
elseif entity.direction == 4 then --NS
posIn = {entity.position.x-1, entity.position.y}
posOut = {entity.position.x, entity.position.y}
--tracks = entity.surface.find_entities_filtered{type="straight-rail", area={{entity.position.x+1, entity.position.y-3},{entity.position.x+3, entity.position.y+3}} }
rot = 4
elseif entity.direction == 6 then --EW
posIn = {entity.position.x-1, entity.position.y-1}
posOut = {entity.position.x-1, entity.position.y}
--tracks = entity.surface.find_entities_filtered{type="straight-rail", area={{entity.position.x-3, entity.position.y+1},{entity.position.x+3, entity.position.y+3}} }
rot = 6
else --invalid orientation
if log_level >= 1 then printmsg({"ltn-message.error-stop-orientation", entity.direction}) end
entity.destroy()
return
end
local lampctrl = entity.surface.create_entity
{
name = "logistic-train-stop-lamp-control",
position = posIn,
force = entity.force
}
lampctrl.operable = false -- disable gui
lampctrl.minable = false
lampctrl.destructible = false -- don't bother checking if alive
lampctrl.get_control_behavior().parameters = {parameters={{index = 1, signal = {type="virtual",name="signal-white"}, count = 1 }}}
local input, output
-- revive ghosts (should preserve connections)
--local ghosts = entity.surface.find_entities_filtered{area={{entity.position.x-2, entity.position.y-2},{entity.position.x+2, entity.position.y+2}} , name="entity-ghost"}
local ghosts = entity.surface.find_entities({{entity.position.x-1.1, entity.position.y-1.1},{entity.position.x+1.1, entity.position.y+1.1}} )
for _,ghost in pairs (ghosts) do
if ghost.name == "entity-ghost" and ghost.ghost_name == "logistic-train-stop-input" then
--printmsg("reviving ghost input at "..ghost.position.x..", "..ghost.position.y)
_, input = ghost.revive()
elseif ghost.name == "entity-ghost" and ghost.ghost_name == "logistic-train-stop-output" then
--printmsg("reviving ghost output at "..ghost.position.x..", "..ghost.position.y)
_, output = ghost.revive()
-- something has built I/O already (e.g.) Creative Mode Instant Blueprint
elseif ghost.name == "logistic-train-stop-input" then
input = ghost
--printmsg("Found existing input at "..ghost.position.x..", "..ghost.position.y)
elseif ghost.name == "logistic-train-stop-output" then
output = ghost
--printmsg("Found existing output at "..ghost.position.x..", "..ghost.position.y)
end
end
if input == nil then -- create new
input = entity.surface.create_entity
{
name = "logistic-train-stop-input",
position = posIn,
force = entity.force
}
end
input.operable = false -- disable gui
input.minable = false
input.destructible = false -- don't bother checking if alive
input.connect_neighbour({target_entity=lampctrl, wire=defines.wire_type.green})
input.get_or_create_control_behavior().use_colors = true
input.get_or_create_control_behavior().circuit_condition = {condition = {comparator=">",first_signal={type="virtual",name="signal-anything"}}}
if output == nil then -- create new
output = entity.surface.create_entity
{
name = "logistic-train-stop-output",
position = posOut,
direction = rot,
force = entity.force
}
end
output.operable = false -- disable gui
output.minable = false
output.destructible = false -- don't bother checking if alive
global.LogisticTrainStops[entity.unit_number] = {
entity = entity,
input = input,
output = output,
lampControl = lampctrl,
isDepot = false,
ignoreMinDeliverySize = false,
trainLimit = 0,
activeDeliveries = {}, --delivery IDs to/from stop
errorCode = 0, --key to errorCodes table
parkedTrain = nil,
parkedTrainID = nil
}
StopIDList[#StopIDList+1] = entity.unit_number
UpdateStopOutput(global.LogisticTrainStops[entity.unit_number])
if #StopIDList == 1 then
stopsPerTick = 1 --initialize ticker indexes
stopIdStartIndex = 1
script.on_event(defines.events.on_tick, ticker) --subscribe ticker on first created train stop
if log_level >= 4 then printmsg("on_tick subscribed", false) end
end
end
script.on_event(defines.events.on_built_entity, function(event)
local entity = event.created_entity
if entity.valid and entity.name == "logistic-train-stop" then
createStop(entity)
return
end
-- handle adding carriages to parked trains
if entity.type == "locomotive" or entity.type == "cargo-wagon" then
entity.train.manual_mode = true
UpdateStopParkedTrain(entity.train)
--entity.train.manual_mode = false
return
end
end)
script.on_event(defines.events.on_robot_built_entity, function(event)
local entity = event.created_entity
if entity.valid and entity.name == "logistic-train-stop" then
createStop(entity)
end
end)
end
do -- stop removed / train changed
function removeStop(entity)
local stopID = entity.unit_number
local stop = global.LogisticTrainStops[stopID]
-- clean lookup tables
for i=#StopIDList, 0, -1 do
if StopIDList[i] == stopID then
table.remove(StopIDList, i)
end
end
for k,v in pairs(global.StopDistances) do
if k:find(stopID) then
global.StopDistances[k] = nil
end
end
-- remove available train
if stop and stop.isDepot and stop.parkedTrainID then
global.Dispatcher.availableTrains[stop.parkedTrainID] = nil
end
-- destroy IO entities
if stop and stop.input and stop.input.valid and stop.output and stop.output.valid and stop.lampControl and stop.lampControl.valid then
stop.input.destroy()
stop.output.destroy()
stop.lampControl.destroy()
else
-- destroy broken IO entities
local ghosts = entity.surface.find_entities({{entity.position.x-1.1, entity.position.y-1.1},{entity.position.x+1.1, entity.position.y+1.1}} )
for _,ghost in pairs (ghosts) do
if ghost.name == "logistic-train-stop-input" or ghost.name == "logistic-train-stop-output" or ghost.name == "logistic-train-stop-lamp-control" then
--printmsg("removing broken "..ghost.name.." at "..ghost.position.x..", "..ghost.position.y)
ghost.destroy()
end
end
end
global.LogisticTrainStops[stopID] = nil
if StopIDList == nil or #StopIDList == 0 then
script.on_event(defines.events.on_tick, nil) --unsubscribe ticker on last removed train stop
if log_level >= 4 then printmsg("on_tick unsubscribed: Removed last Logistic Train Stop", false) end
end
end
script.on_event(defines.events.on_preplayer_mined_item, function(event)
local entity = event.entity
if entity.name == "logistic-train-stop" then
removeStop(entity)
return
end
-- handle removing carriages from parked trains
if entity.type == "locomotive" or entity.type == "cargo-wagon" or entity.type == "fluid-wagon" then
entity.train.manual_mode = true
UpdateStopParkedTrain(entity.train)
--entity.train.manual_mode = false
return
end
end)
script.on_event(defines.events.on_robot_pre_mined, function(event)
local entity = event.entity
if entity.name == "logistic-train-stop" then
removeStop(entity)
end
end)
script.on_event(defines.events.on_entity_died, function(event)
local entity = event.entity
if entity.name == "logistic-train-stop" then
removeStop(entity)
return
end
-- handle removing carriages from parked trains
if entity.type == "locomotive" or entity.type == "cargo-wagon" or entity.type == "fluid-wagon" then
entity.train.manual_mode = true
UpdateStopParkedTrain(entity.train)
--entity.train.manual_mode = false
return
end
end)
script.on_event(defines.events.on_train_changed_state, function(event)
UpdateStopParkedTrain(event.train)
end)
end
do --rename stop
local function renamedStop(targetID, old_name, new_name)
-- find identical stop names
local duplicateName = false
local renameDeliveries = true
for stopID, stop in pairs(global.LogisticTrainStops) do
if stop.entity.backer_name == old_name then
renameDeliveries = false
end
end
-- rename deliveries if no other stop old_name exists
if renameDeliveries then
for trainID, delivery in pairs(global.Dispatcher.Deliveries) do
if delivery.to == old_name then
delivery.to = new_name
--log("renamed delivery.to "..old_name.." > "..new_name)
end
if delivery.from == old_name then
delivery.from = new_name
--log("renamed delivery.from "..old_name.." > "..new_name)
end
end
end
end
script.on_event(defines.events.on_entity_renamed, function(event)
if event.entity.name == "logistic-train-stop" then
log("(on_entity_renamed) uid:"..event.entity.unit_number..", old name: "..event.old_name..", new name: "..event.entity.backer_name)
renamedStop(event.entity.unit_number, event.old_name, event.entity.backer_name)
end
end)
script.on_event(defines.events.on_pre_entity_settings_pasted, function(event)
if event.destination.name == "logistic-train-stop" then
log("(on_pre_entity_settings_pasted) uid:"..event.destination.unit_number..", old name: "..event.destination.backer_name..", new name: "..event.source.backer_name)
renamedStop(event.destination.unit_number, event.destination.backer_name, event.source.backer_name)
end
end)
end
function ticker(event)
-- exit when there are no logistic train stops
local next = next
if global.LogisticTrainStops == nil or next(global.LogisticTrainStops) == nil then
script.on_event(defines.events.on_tick, nil)
if log_level >= 4 then printmsg("no LogisticTrainStops, unsubscribed from on_tick", false) end
return
end
local tick = game.tick
global.tickCount = global.tickCount or 1
if global.tickCount == 1 then
stopsPerTick = ceil(#StopIDList/(dispatcher_update_interval-1)) -- 59 ticks for stop Updates, 60th tick for dispatcher
stopIdStartIndex = 1
-- clear Dispatcher.Storage
global.Dispatcher.Provided = {}
global.Dispatcher.Requests = {}
-- remove messages older than message_filter_age from messageBuffer
for bufferedMsg, v in pairs(global.messageBuffer) do
if (tick - v.tick) > message_filter_age then
global.messageBuffer[bufferedMsg] = nil
end
end
end
stopIdLastIndex = stopIdStartIndex + stopsPerTick - 1
if stopIdLastIndex > #StopIDList then
stopIdLastIndex = #StopIDList
end
for i = stopIdStartIndex, stopIdLastIndex, 1 do
local stopID = StopIDList[i]
if log_level >= 4 then printmsg(global.tickCount.."/"..tick.." updating stopID "..tostring(stopID), false) end
UpdateStop(stopID)
end
stopIdStartIndex = stopIdLastIndex + 1
if global.tickCount == dispatcher_update_interval then
global.tickCount = 1
--clean up deliveries in case train was destroyed or removed
for trainID, delivery in pairs (global.Dispatcher.Deliveries) do
if not delivery.train or not delivery.train.valid then
if log_level >= 1 then printmsg({"ltn-message.delivery-removed-train-invalid", delivery.from, delivery.to}) end
removeDelivery(trainID)
elseif tick-delivery.started > delivery_timeout then
if log_level >= 1 then printmsg({"ltn-message.delivery-removed-timeout", delivery.from, delivery.to, tick-delivery.started}) end
removeDelivery(trainID)
end
end
-- remove no longer active requests from global.Dispatcher.RequestAge[stopID]
local newRequestAge = {}
for _,request in pairs (global.Dispatcher.Requests) do
local age = global.Dispatcher.RequestAge[request.stopID]
if age then
newRequestAge[request.stopID] = age
end
end
global.Dispatcher.RequestAge = newRequestAge
-- sort requests by age
sort(global.Dispatcher.Requests, function(a, b)
return a.age < b.age
end)
-- find best provider, merge shipments, find train, generate delivery, reset age
if next(global.Dispatcher.availableTrains) ~= nil then -- no need to parse requests without available trains
for reqIndex, request in pairs (global.Dispatcher.Requests) do
local delivery = ProcessRequest(request)
if delivery then
break
end
end
end
else -- dispatcher update
global.tickCount = global.tickCount + 1
end
end
---------------------------------- DISPATCHER FUNCTIONS ----------------------------------
function removeDelivery(trainID)
if global.Dispatcher.Deliveries[trainID] then
for stopID, stop in pairs(global.LogisticTrainStops) do
for i=#stop.activeDeliveries, 1, -1 do --trainID should be unique => checking matching stop name not required
if stop.activeDeliveries[i] == trainID then
table.remove(stop.activeDeliveries, i)
end
end
end
global.Dispatcher.Deliveries[trainID] = nil
end
end
-- return new schedule_record
-- itemlist = {first_signal.type, first_signal.name, constant}
function NewScheduleRecord(stationName, condType, condComp, itemlist, countOverride)
local record = {station = stationName, wait_conditions = {}}
if condType == "item_count" then
-- write itemlist to conditions
for i=1, #itemlist do
local condFluid = nil
if itemlist[i].type == "fluid" then
condFluid = "fluid_count"
end
-- make > into >=
if condComp == ">" then
countOverride = itemlist[i].count - 1
end
local cond = {comparator = condComp, first_signal = {type = itemlist[i].type, name = itemlist[i].name}, constant = countOverride or itemlist[i].count}
record.wait_conditions[#record.wait_conditions+1] = {type = condFluid or condType, compare_type = "and", condition = cond }
end
if finish_loading then -- let inserters finish
record.wait_conditions[#record.wait_conditions+1] = {type = "inactivity", compare_type = "and", ticks = 120 }
end
if stop_timeout > 0 then -- if stop_timeout is set add inactivity condition
record.wait_conditions[#record.wait_conditions+1] = {type = "inactivity", compare_type = "or", ticks = stop_timeout } -- send stuck trains away
end
elseif condType == "inactivity" then
record.wait_conditions[#record.wait_conditions+1] = {type = condType, compare_type = "and", ticks = condComp }
end
return record
end
do --ProcessRequest
-- return all stations providing item, ordered by priority and item-count
local function GetProviders(force, item, min_count)
local stations = {}
local providers = global.Dispatcher.Provided[item]
if not providers then
return nil
end
-- get all providing stations
for stopID, count in pairs (providers) do
if not(stopID == "sumCount" or stopID == "sumStops") then --skip sumCount, sumStops
local stop = global.LogisticTrainStops[stopID]
if stop and stop.entity.force.name == force.name then
local activeDeliveryCount = #stop.activeDeliveries
if count > 0 and (use_Best_Effort or stop.ignoreMinDeliverySize or count >= min_count) and (stop.trainLimit == 0 or activeDeliveryCount < stop.trainLimit) then
if log_level >= 4 then printmsg("(GetProviders): found ".. count .."/"..min_count.." ".. item.." at "..stop.entity.backer_name.." priority: "..stop.priority.." minTraincars: "..stop.minTraincars.." maxTraincars: "..stop.maxTraincars.." locked Slots: "..stop.lockedSlots, false) end
stations[#stations +1] = {entity = stop.entity, priority = stop.priority, activeDeliveryCount = activeDeliveryCount, item = item, count = count, minTraincars = stop.minTraincars, maxTraincars = stop.maxTraincars, lockedSlots = stop.lockedSlots}
end
end
end
end
-- sort by priority and count
sort(stations, function(a, b)
if a.activeDeliveryCount ~= b.activeDeliveryCount then --sort by #deliveries 1st
return a.activeDeliveryCount < b.activeDeliveryCount
end
if a.priority ~= b.priority then --sort by priority 2nd
return a.priority > b.priority
end
return a.count > b.count --finally sort by item count
end)
return stations
end
local function GetStationDistance(stationA, stationB)
local stationPair = stationA.unit_number..","..stationB.unit_number
if global.StopDistances[stationPair] then
--log(stationPair.." found, distance: "..global.StopDistances[stationPair])
return global.StopDistances[stationPair]
else
local dist = GetDistance(stationA.position, stationB.position)
global.StopDistances[stationPair] = dist
--log(stationPair.." calculated, distance: "..dist)
return dist
end
end
local InventoryLookup = { --preoccupy table with wagons to ignore at 0 capacity
["rail-tanker"] = 0
}
local function getInventorySize(entity)
local capacity = 0
if entity.type == "cargo-wagon" then
capacity = entity.prototype.get_inventory_size(defines.inventory.cargo_wagon)
elseif entity.type == "fluid-wagon" then
for n=1, #entity.fluidbox do
capacity = capacity + entity.fluidbox.get_capacity(n)
end
end
--log("(getInventorySize) adding "..entity.name.." capcacity: "..capacity)
InventoryLookup[entity.name] = capacity
return capacity
end
local function GetTrainInventorySize(train, type, reserved)
local inventorySize = 0
local fluidCapacity = 0
if not train.valid then
return inventorySize
end
--log("Train "..GetTrainName(train).." carriages: "..#train.carriages..", cargo_wagons: "..#train.cargo_wagons)
for _,wagon in pairs (train.carriages) do
if wagon.type ~= "locomotive" then
local capacity = InventoryLookup[wagon.name] or getInventorySize(wagon)
--log("(GetTrainInventorySize) wagon.name:"..wagon.name.." capacity:"..capacity)
if wagon.type == "fluid-wagon" then
fluidCapacity = fluidCapacity + capacity
else
inventorySize = inventorySize + capacity - reserved
end
end
end
if type == "fluid" then
return fluidCapacity
end
return inventorySize
end
-- return available train with smallest suitable inventory or largest available inventory
-- if minTraincars is set, number of locos + wagons has to be bigger
-- if maxTraincars is set, number of locos + wagons has to be smaller
local function GetFreeTrain(nextStop, minTraincars, maxTraincars, type, size, reserved)
local train = nil
if minTraincars == nil or minTraincars < 0 then minTraincars = 0 end
if maxTraincars == nil or maxTraincars < 0 then maxTraincars = 0 end
local largestInventory = 0
local smallestInventory = 0
local smallestDistance = 0
for DispTrainKey, DispTrain in pairs (global.Dispatcher.availableTrains) do
if DispTrain.valid and DispTrain.station then
local locomotive = GetMainLocomotive(DispTrain)
if locomotive.force.name == nextStop.force.name then -- train force matches
local inventorySize = 0
if (minTraincars == 0 or #DispTrain.carriages >= minTraincars) and (maxTraincars == 0 or #DispTrain.carriages <= maxTraincars) then -- train length fits
-- get total inventory of train for requested item type
inventorySize = GetTrainInventorySize(DispTrain, type, reserved)
if inventorySize >= size then
-- train can be used for delivery
if inventorySize <= smallestInventory or smallestInventory == 0 then
local distance = GetStationDistance(DispTrain.station, nextStop)
if distance < smallestDistance or smallestDistance == 0 then
smallestDistance = distance
smallestInventory = inventorySize
train = {id=DispTrainKey, inventorySize=inventorySize}
if log_level >= 4 then printmsg("(GetFreeTrain): found train "..locomotive.backer_name..", length: "..minTraincars.."<="..#DispTrain.carriages.."<="..maxTraincars.. ", inventory size: "..inventorySize.."/"..size..", distance: "..distance, false) end
end
end
elseif smallestInventory == 0 and inventorySize > 0 and (inventorySize >= largestInventory or largestInventory == 0) then
-- store biggest available train
local distance = GetStationDistance(DispTrain.station, nextStop)
if distance < smallestDistance or smallestDistance == 0 then
smallestDistance = distance
largestInventory = inventorySize
train = {id=DispTrainKey, inventorySize=inventorySize}
if log_level >= 4 then printmsg("(GetFreeTrain): largest available train "..locomotive.backer_name..", length: "..minTraincars.."<="..#DispTrain.carriages.."<="..maxTraincars.. ", inventory size: "..inventorySize.."/"..size..", distance: "..distance, false) end
end
end
end --train length fits
end
else
-- remove invalid train
global.Dispatcher.availableTrains[DispTrainKey] = nil
end
end
return train
end
-- creates a single delivery from a given request
-- returns generated delivery or nil
function ProcessRequest(request)
local stopID = request.stopID
local requestStation = global.LogisticTrainStops[stopID]
if not requestStation or not (requestStation.entity and requestStation.entity.valid) then
return nil -- station was removed since request was generated
end
local minDelivery = requestStation.minDelivery
local orders = {}
local deliveries = nil
if requestStation.trainLimit > 0 and #requestStation.activeDeliveries >= requestStation.trainLimit then
if log_level >= 4 then printmsg(requestStation.entity.backer_name.." skipped: "..#requestStation.activeDeliveries.." >= "..requestStation.trainLimit) end
return nil -- reached train limit
end
-- find providers for requested items
for item, count in pairs (request.itemlist) do
-- split merged key into type & name
local itype, iname = match(item, "([^,]+),([^,]+)")
if not (itype and iname and (game.item_prototypes[iname] or game.fluid_prototypes[iname])) then
if log_level >= 1 then printmsg({"ltn-message.error-parse-item", item}) end
goto skipRequestItem
end
local localname
if itype=="fluid" then
localname = game.fluid_prototypes[iname].localised_name
else
localname = game.item_prototypes[iname].localised_name
end
-- get providers ordered by priority
local providers = GetProviders(requestStation.entity.force, item, minDelivery)
if not providers or #providers < 1 then
if log_level >= 2 then printmsg({"ltn-message.no-provider-found", localname}, true) end
goto skipRequestItem
end
-- only one delivery is created so use only the best provider
local providerStation = providers[1]
if log_level >= 3 then printmsg({"ltn-message.provider-found", providerStation.entity.backer_name, tostring(providerStation.priority), tostring(providerStation.activeDeliveryCount), providerStation.count, localname}, true)
elseif log_level >= 4 then
for n, provider in pairs (providers) do
printmsg("Provider["..n.."] "..provider.entity.backer_name..": Priority "..tostring(provider.priority)..", "..tostring(provider.activeDeliveryCount).." deliveries, "..tostring(provider.count).." "..localname.." available.")
end
end
-- limit count to availability of highest priority provider
local deliverySize = count
if count > providerStation.count then
deliverySize = providerStation.count
end
local stacks = deliverySize -- for fluids stack = tanker capacity
if itype == "item" then
stacks = ceil(deliverySize / game.item_prototypes[iname].stack_size) -- calculate amount of stacks item count will occupy
end
-- maxTraincars = shortest set max-train-length
local maxTraincars = requestStation.maxTraincars
if providerStation.maxTraincars > 0 and (providerStation.maxTraincars < requestStation.maxTraincars or requestStation.maxTraincars == 0) then
maxTraincars = providerStation.maxTraincars
end
-- minTraincars = longest set min-train-length
local minTraincars = requestStation.minTraincars
if providerStation.minTraincars > 0 and (providerStation.minTraincars > requestStation.minTraincars or requestStation.minTraincars == 0) then
minTraincars = providerStation.minTraincars
end
-- merge into existing shipments
local to = requestStation.entity.backer_name
local from = providerStation.entity.backer_name
local toID = requestStation.entity.unit_number
local fromID = providerStation.entity.unit_number
local insertnew = true
local loadingList = {type=itype, name=iname, localname=localname, count=deliverySize, stacks=stacks}
-- try inserting into existing order
for i=1, #orders do
if orders[i].fromID == fromID and itype == "item" and orders[i].loadingList[1].type == "item" then
orders[i].loadingList[#orders[i].loadingList+1] = loadingList
orders[i].totalStacks = orders[i].totalStacks + stacks
insertnew = false
if log_level >= 4 then printmsg("inserted into order "..i.."/"..#orders.." "..from.." >> "..to..": "..deliverySize.." in "..stacks.." stacks "..itype..","..iname.." min length: "..minTraincars.." max length: "..maxTraincars, false) end
break
end
end
-- create new order for fluids and different provider-requester pairs
if insertnew then
orders[#orders+1] = {toID=toID, fromID=fromID, minDelivery=minDelivery, minTraincars=minTraincars, maxTraincars=maxTraincars, totalStacks=stacks, lockedSlots=providerStation.lockedSlots, loadingList={loadingList} }
if log_level >= 4 then printmsg("added new order "..#orders.." "..from.." >> "..to..": "..deliverySize.." in "..stacks.." stacks "..itype..","..iname.." min length: "..minTraincars.." max length: "..maxTraincars, false) end
end
::skipRequestItem:: -- use goto since lua doesn't know continue
end -- find providers for requested items
-- find trains for orders
for orderIndex=1, #orders do
local loadingList = orders[orderIndex].loadingList
local totalStacks = orders[orderIndex].totalStacks
local lockedSlots = orders[orderIndex].lockedSlots
local minTraincars = orders[orderIndex].minTraincars
local maxTraincars = orders[orderIndex].maxTraincars
-- get station names
local toStop = global.LogisticTrainStops[orders[orderIndex].toID]
local fromStop = global.LogisticTrainStops[orders[orderIndex].fromID]
if not toStop or not fromStop then
if log_level >= 1 then printmsg({"ltn-message.error-no-stop"}) end
goto skipOrder
end
local to = toStop.entity.backer_name
local from = fromStop.entity.backer_name
-- find train
local train = GetFreeTrain(fromStop.entity, minTraincars, maxTraincars, loadingList[1].type, totalStacks, lockedSlots)
if not train then
if log_level >= 3 then
if #loadingList == 1 then
printmsg({"ltn-message.no-train-found", tostring(minTraincars), tostring(maxTraincars), loadingList[1].localname}, true)
else
printmsg({"ltn-message.no-train-found-merged", tostring(minTraincars), tostring(maxTraincars), tostring(totalStacks)}, true)
end
end
goto skipOrder
end
if log_level >= 3 then printmsg({"ltn-message.train-found", tostring(train.inventorySize), tostring(totalStacks)}) end
-- recalculate delivery amount to fit in train
if train.inventorySize < totalStacks then
-- recalculate partial shipment
if loadingList[1].type == "fluid" then
-- fluids are simple
loadingList[1].count = train.inventorySize
else
-- items need a bit more math
for i=#loadingList, 1, -1 do
if totalStacks - loadingList[i].stacks < train.inventorySize then
-- remove stacks until it fits in train
loadingList[i].stacks = loadingList[i].stacks - (totalStacks - train.inventorySize)
totalStacks = train.inventorySize
local newcount = loadingList[i].stacks * game.item_prototypes[loadingList[i].name].stack_size
loadingList[i].count = newcount
break
else
-- remove item and try again
totalStacks = totalStacks - loadingList[i].stacks
table.remove(loadingList, i)
end
end
end
end
if log_level >= 4 then
for i=1, #loadingList do
printmsg("Creating Delivery: "..loadingList[i].count.." in "..loadingList[i].stacks.." stacks "..loadingList[i].type..","..loadingList[i].name..", "..from.." >> "..to, false)
end
elseif log_level >= 2 then
if #loadingList == 1 then
printmsg({"ltn-message.creating-delivery", from, to, loadingList[1].count, loadingList[1].localname})
else
printmsg({"ltn-message.creating-delivery-merged", from, to, totalStacks})
end
end
-- create schedule
local selectedTrain = global.Dispatcher.availableTrains[train.id]
local depot = global.LogisticTrainStops[selectedTrain.station.unit_number]
local schedule = {current = 1, records = {}}
schedule.records[1] = NewScheduleRecord(depot.entity.backer_name, "inactivity", 120)
schedule.records[2] = NewScheduleRecord(from, "item_count", ">", loadingList)
schedule.records[3] = NewScheduleRecord(to, "item_count", "=", loadingList, 0)
selectedTrain.schedule = schedule
-- store delivery
local delivery = {}
for i=1, #loadingList do
delivery[loadingList[i].type..","..loadingList[i].name] = loadingList[i].count
end
global.Dispatcher.Deliveries[train.id] = {train=selectedTrain, started=game.tick, from=from, to=to, shipment=delivery}
global.Dispatcher.availableTrains[train.id] = nil
-- move Request to the back of the queue
global.Dispatcher.RequestAge[orders[orderIndex].toID] = nil
-- set lamps on stations to yellow
-- trains will pick a stop by their own logic so we have to parse by name
for stopID, stop in pairs (global.LogisticTrainStops) do
if stop.entity.backer_name == from or stop.entity.backer_name == to then
table.insert(global.LogisticTrainStops[stopID].activeDeliveries, train.id)
end
end
-- stop after first delivery was created
do return delivery end -- explicit block needed ... lua really sucks ...
::skipOrder:: -- use goto since lua doesn't know continue
end --for orders
return nil
end
end
------------------------------------- STOP FUNCTIONS -------------------------------------
-- update stop output when train enters/leaves
function UpdateStopParkedTrain(train)
local trainID = GetTrainID(train)
local trainName = GetTrainName(train)
if not trainID then --train has no locomotive
if log_level >= 4 then printmsg("Notice (UpdateStopParkedTrain): couldn't assign train id", false) end
--TODO: Update all stops?
return
end
if train.valid and train.manual_mode == false and train.state == defines.train_state.wait_station and train.station ~= nil and train.station.name == "logistic-train-stop" then
local stopID = train.station.unit_number
local stop = global.LogisticTrainStops[stopID]
if stop then
stop.parkedTrain = train
stop.parkedTrainID = trainID
if log_level >= 3 then printmsg({"ltn-message.train-arrived", trainName, stop.entity.backer_name}) end
local frontDistance = GetDistance(train.front_stock.position, train.station.position)
local backDistance = GetDistance(train.back_stock.position, train.station.position)
if log_level >= 4 then printmsg("Front Stock Distance: "..frontDistance..", Back Stock Distance: "..backDistance, false) end
if frontDistance > backDistance then
stop.parkedTrainFacesStop = false
else
stop.parkedTrainFacesStop = true
end
if stop.isDepot then
-- remove delivery
removeDelivery(trainID)
-- make train available for new deliveries
global.Dispatcher.availableTrains[trainID] = train
-- reset schedule
local schedule = {current = 1, records = {}}
schedule.records[1] = NewScheduleRecord(stop.entity.backer_name, "inactivity", 300)
train.schedule = schedule
if stop.errorCode == 0 then
setLamp(stopID, "blue")
end
end
UpdateStopOutput(stop)
return
end
else --remove train from station
for stopID, stop in pairs(global.LogisticTrainStops) do
if stop.parkedTrainID == trainID then