forked from Choumiko/SmartTrains
-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.lua
1843 lines (1681 loc) · 68.3 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 "__core__/lualib/util"
require '__SmartTrains__/stdlib/area/position'
require '__SmartTrains__/stdlib/surface'
require '__SmartTrains__/stdlib/string'
require '__SmartTrains__/stdlib/table'
Logger = require('__SmartTrains__/stdlib/log/logger')
LOGGERS = {} --luacheck: allow defined top
--LOGGERS.main = Logger.new("SmartTrains","main", true)
--LOGGERS.update = Logger.new("SmartTrains", "updates", true)
-- myevent = game.generateeventname()
-- the name and tick are filled for the event automatically
-- this event is raised with extra parameter foo with value "bar"
--game.raiseevent(myevent, {foo="bar"})
events = {} --luacheck: allow defined top
events["on_player_opened"] = script.generate_event_name()
events["on_player_closed"] = script.generate_event_name()
--luacheck: allow defined top
combinator_index = {
station_number = 1,
train_at_station = 2,
locomotives = 3,
cargowagons = 4,
passenger = 5,
lowest_fuel = 6,
line = 7,
destination = 8
}
require("__SmartTrains__/gui")
require("__SmartTrains__/Train")
defaultSettings =
{ refuel = { station = "Refuel", rangeMin = 25*8, rangeMax = 50*8, time = 600 },
intervals = {
write = 60, -- ticks between constant combinator updates
inactivity = 120, --ticks between cargo comparison
},
}
stationsPerPage = 5
linesPerPage = 5
rulesPerPage = 5
mappingsPerPage = 10
colors = {
RED = {r = 0.9},
GREEN = {g = 0.7},
YELLOW = {r = 0.8, g = 0.8}
}
train_state = {left_station = 11}
function isHybridTrain(train)
for k,loco in pairs(train.locomotives.front_movers) do
if loco.name == "hybrid-train" then
return true
end
end
for k,loco in pairs(train.locomotives.back_movers) do
if loco.name == "hybrid-train" then
return true
end
end
return false
end
function insertInTable(tableA, key, value)
if not tableA[key] then tableA[key] = {} end
table.insert(tableA[key], value)
end
TrainList = {}
TrainList.getMainLocomotive = function(train)
if train.valid and train.locomotives and (#train.locomotives.front_movers > 0 or #train.locomotives.back_movers > 0) then
return train.locomotives.front_movers and train.locomotives.front_movers[1] or train.locomotives.back_movers[1]
end
end
TrainList.getTrainID = function(train)
local loco = TrainList.getMainLocomotive(train)
return loco and loco.unit_number
end
TrainList.getLocomotives = function(train)
local locomotives = {}
if train.locomotives then
for _, loco in pairs(train.locomotives.front_movers) do
table.insert(locomotives, loco)
end
for _, loco in pairs(train.locomotives.back_movers) do
table.insert(locomotives, loco)
end
end
return locomotives
end
TrainList.addTrainInfo = function(train)
local id = TrainList.getTrainID(train)
if id then
local trainInfo = Train.new(train, id)
global.trains[id] = trainInfo
return trainInfo
end
end
TrainList.updateTrainInfo = function(train)
local newMainID = TrainList.getTrainID(train)
if not newMainID then return end
local newLocos = TrainList.getLocomotives(train)
local found = {}
local foundMainID = false
for _, loco in pairs(newLocos) do
if global.trains[loco.unit_number] then
if newMainID == loco.unit_number then
--log("found main loco " .. newMainID)
foundMainID = global.trains[newMainID]
else
table.insert(found, global.trains[loco.unit_number])
end
end
end
-- old front loco stays front loco
if foundMainID then
for _, old in pairs(found) do
TrainList.removeTrain(old)
end
-- check old locomotives for different train (decoupling)
local newTrain = false
for _, oldLoco in pairs(foundMainID.locomotives) do
if oldLoco.valid and TrainList.getTrainID(oldLoco.train) ~= newMainID then
newTrain = oldLoco.train
end
end
if newTrain then
TrainList.addTrainInfo(newTrain)
end
foundMainID:update(train, newMainID)
foundMainID:resetWaitingStation()
global.trains[newMainID] = foundMainID
-- loco/cargo wagon added in front of old front loco
else
if #found > 0 then
found[1]:update(train, newMainID)
found[1]:resetWaitingStation()
global.trains[newMainID] = found[1]
for i=#found, 2, -1 do
TrainList.removeTrain(found[i])
end
else
--loco was added to cargo-wagon
return TrainList.addTrainInfo(train)
end
end
return global.trains[newMainID]
end
TrainList.getTrainInfo = function(train)
local id = TrainList.getTrainID(train)
local trainInfo = global.trains[id]
if not trainInfo or not trainInfo.train.valid then
if train.valid and id then
return TrainList.addTrainInfo(train)
end
end
return trainInfo
end
TrainList.getTrainInfoFromUI = function(playerIndex)
local player = game.players[playerIndex]
local trainInfo
if player.opened ~= nil and player.opened.valid then
if player.opened.type == "locomotive" then
trainInfo = TrainList.getTrainInfo(player.opened.train)
end
return trainInfo
end
end
TrainList.removeTrain = function(trainInfo)
if trainInfo and trainInfo.ID and global.trains[trainInfo.ID] then
trainInfo:resetWaitingStation()
global.trains[trainInfo.ID] = nil
end
end
TrainList.removeInvalidTrains = function(show)
local removed = 0
for id, ti in pairs(global.trains) do
if not ti.train or not ti.train.valid or (#ti.train.locomotives.front_movers == 0 and #ti.train.locomotives.back_movers == 0) then
ti:resetCircuitSignal()
TrainList.removeTrain(ti)
removed = removed + 1
-- try to detect change through pressing G/V
else
local test = ti:getType()
if test ~= ti.type then
ti:resetCircuitSignal()
TrainList.removeTrain(ti)
removed = removed + 1
end
end
end
if removed > 0 and show then
flyingText("Removed "..removed.." invalid trains", colors.RED, false, true)
end
return removed
end
TrainList.getCount = function()
local c = 0
for _, _ in pairs(global.trains) do
c = c + 1
end
return c
end
TrainList.removeDuplicates = function()
local removeIds = {}
local addIds = {}
local validTrains = {}
for i, ti in pairs(global.trains) do
if ti.train and ti.train.valid then
local ID = TrainList.getTrainID(ti.train)
log("i: " .. i .. " mainId: " .. ID)
if i == ID and global.trains[ID] and global.trains[ID].train == ti.train then
validTrains[ID] = ti
log("valid: " .. ID)
else
log("invalid: " .. ID)
-- update lookup table
if i ~= ID then
if not global.trains[ID] then
addIds[ID] = ti
else
removeIds[i] = ti
end
end
end
else
removeIds[i] = ti
end
end
for _, ti in pairs(addIds) do
TrainList.addTrainInfo(ti.train)
end
for id, ti in pairs(removeIds) do
TrainList.removeTrain(ti)
global.trains[id] = nil
end
end
local function debugLog(var, prepend)
if not global.debug_log then return end
local str = prepend or ""
for _,_ in pairs(game.players) do
local msg
if type(var) == "string" then
msg = var
else
msg = serpent.dump(var, {name="var", comment=false, sparse=false, sortkeys=true})
end
--player.print(str..msg)
log(str..msg)
end
end
function util.getKeyByValue(tableA, value)
for i,c in pairs(tableA) do
if c == value then
return i
end
end
end
function util.formattime(ticks, showTicks)
if ticks then
local seconds = ticks / 60
local minutes = math.floor((seconds)/60)
seconds = math.floor(seconds - 60*minutes)
local tick = ticks - (minutes*60*60+seconds*60)
local format = showTicks and "%d:%02d:%02d" or "%d:%02d"
return string.format(format, minutes, seconds, tick)
else
return "-"
end
end
function resetMetatable(o, mt)
setmetatable(o,{__index=mt})
return o
end
function setMetatables()
for _, object in pairs(global.trains) do
resetMetatable(object, Train)
end
if global.update_cargo then
for _, tick in pairs(global.update_cargo) do
for _, object in pairs(tick) do
resetMetatable(object, Train)
end
end
end
if global.check_rules then
for _, tick in pairs(global.check_rules) do
for _, object in pairs(tick) do
resetMetatable(object, Train)
end
end
end
end
function initGlob()
global = global or {}
global.version = global.version or "0.3.75"
global.trains = global.trains or {}
global.train = nil
global.trainLines = global.trainLines or {}
global.scheduleUpdate = global.scheduleUpdate or {}
global.update_cargo = global.update_cargo or {}
global.check_rules = global.check_rules or {}
global.refueling = global.refueling or {}
global.reset_signals = global.reset_signals or {}
global.player_passenger = global.player_passenger or {}
global.showFlyingText = global.showFlyingText or false
global.playerPage = global.playerPage or {}
global.playerRules = global.playerRules or {}
global.guiData = global.guiData or {}
-- by force
global.stationCount = global.stationCount or {}
global.smartTrainstops = global.smartTrainstops or {}
global.stationMapping = global.stationMapping or {}
global.stationMap = global.stationMap or {}
global.stationNumbers = global.stationNumbers or {}
global.settings = global.settings or defaultSettings
global.settings.stationsPerPage = stationsPerPage
global.settings.linesPerPage = linesPerPage
global.settings.rulesPerPage = rulesPerPage
global.settings.mappingsPerPage = mappingsPerPage
global.settings.intervals = global.settings.intervals or {}
global.settings.intervals.write = global.settings.intervals.write or defaultSettings.intervals.write
global.settings.intervals.inactivity = global.settings.intervals.inactivity or defaultSettings.intervals.inactivity
global.fuel_values = global.fuel_values or {}
global.fuel_values["coal"] = game.item_prototypes["coal"].fuel_value/1000000
global.blueprinted_proxies = global.blueprinted_proxies or {}
global.stopped_trains = global.stopped_trains or {}
setMetatables()
end
local function init_player(player)
global.playerRules[player.index] = global.playerRules[player.index] or {page=1}
global.player_passenger[player.index] = player.vehicle
end
local function init_players()
for _,player in pairs(game.players) do
init_player(player)
end
end
local function init_force(force)
initGlob()
global.stationCount[force.name] = global.stationCount[force.name] or {}
global.smartTrainstops[force.name] = global.smartTrainstops[force.name] or {}
global.stationMapping[force.name] = global.stationMapping[force.name] or {}
global.stationMap[force.name] = global.stationMap[force.name] or {}
global.stationNumbers[force.name] = global.stationNumbers[force.name] or {}
global.stopped_trains[force.name] = global.stopped_trains[force.name] or {}
end
local function init_forces()
for _, force in pairs(game.forces) do
init_force(force)
end
end
local function on_force_created(event)
init_force(event.force)
end
local function on_player_created(event)
init_player(game.players[event.player_index])
end
function oninit()
initGlob()
init_forces()
init_players()
findStations()
end
function onload()
setMetatables()
end
function get_station_number(force_name, station_name)
if global.stationMapping[force_name][station_name] then
return global.stationMapping[force_name][station_name]
end
local count_lines = 0
local station_number = 0
for line, line_data in pairs(global.trainLines) do
for index, record in pairs(line_data.records) do
if record.station == station_name then
count_lines = count_lines + 1
station_number = index
end
end
end
if count_lines > 1 then
station_number = 0
end
return station_number
end
function add_or_update_parameter(behavior, signal, index)
if behavior then
local parameters = behavior.parameters
if not parameters[index] or (not parameters[index].signal.name or parameters[index].signal.name == signal.signal.name)then
if signal.count == 0 then
signal = {signal={type = "item"}, count = 1, index = index}
end
parameters[index] = signal
behavior.parameters = parameters
return
else
for i, param in pairs(parameters) do
if not param.signal or not param.signal.name then
if signal.count == 0 then
signal = {signal={type = "item"}, count = 1, index = i}
end
parameters[i] = signal
parameters[i].index = i
behavior.parameters = parameters
return
end
end
end
end
end
function update_station_numbers()
for force, smartTrainstops in pairs(global.smartTrainstops) do
global.stationNumbers[force] = {}
for _, station in pairs(smartTrainstops) do
if station.station and station.station.valid then
local number = get_station_number(force,tostring(station.station.backer_name))
global.stationNumbers[force][tostring(station.station.backer_name)] = number
local signal = {signal={type = "virtual", name = "signal-station-number"}, count = number, index = combinator_index.station_number}
add_or_update_parameter(station.cargo.get_or_create_control_behavior(), signal, combinator_index.station_number)
end
end
end
end
local function getProxyPositions(trainstop)
local offset = {
[0] = {x=-0.5,y=-0.5},
[2]={x=0.5,y=-0.5},
[4]={x=0.5,y=0.5},
[6]={x=-0.5,y=0.5}}
local offsetcargo = {
[0] = {x=0.5,y=-0.5},
[2]={x=0.5,y=0.5},
[4]={x=-0.5,y=0.5},
[6]={x=-0.5,y=-0.5}}
local pos = Position.add(trainstop.position, offset[trainstop.direction])
local poscargo = Position.add(trainstop.position, offsetcargo[trainstop.direction])
return {signalProxy = poscargo, cargo = pos}
end
local function recreateProxy(station)
local key = stationKey(station)
if not global.smartTrainstops[station.force.name][key] then
global.smartTrainstops[station.force.name][key] = {station = station}
end
local trainstop = global.smartTrainstops[station.force.name][key]
local positions = getProxyPositions(trainstop.station)
if trainstop.station.valid then
local force = trainstop.station.force.name
if not trainstop.cargo or not trainstop.cargo.valid then
local poscargo = positions.cargo
local proxycargo = {name="smart-train-stop-proxy-cargo", direction=0, force=trainstop.station.force, position=poscargo}
local ent2 = trainstop.station.surface.create_entity(proxycargo)
if ent2.valid then
global.smartTrainstops[force][key].cargo = ent2
ent2.minable = false
ent2.operable = false
ent2.destructible = false
--log("Updated smart train stop cargo: " .. trainstop.station.unit_number .. " " ..trainstop.station.backer_name)
end
else
if trainstop.cargo and trainstop.cargo.valid then
if not Position.equals(positions.cargo, trainstop.cargo.position) then
if not trainstop.cargo.teleport(positions.cargo) then
log("fail: moved cargo proxy " .. trainstop.station.backer_name)
end
end
end
end
if not trainstop.signalProxy or not trainstop.signalProxy.valid then
local pos = positions.signalProxy
local proxy = {name="smart-train-stop-proxy", direction=0, force=trainstop.station.force, position=pos}
local ent = trainstop.station.surface.create_entity(proxy)
if ent.valid then
global.smartTrainstops[force][key].signalProxy=ent
ent.minable = false
ent.destructible = false
--log("Updated smart train stop signal: " .. trainstop.station.unit_number .. " " ..trainstop.station.backer_name)
end
else
if trainstop.signalProxy and trainstop.signalProxy.valid then
if not Position.equals(positions.signalProxy, trainstop.signalProxy.position) then
if not trainstop.signalProxy.teleport(positions.signalProxy) then
log("fail: moved signal proxy " .. trainstop.station.backer_name)
end
end
end
end
end
end
local function fixSmartstopTable()
local tmp = {
player = global.smartTrainstops.player or {},
enemy = global.smartTrainstops.enemy or {},
neutral = global.smartTrainstops.neutral or {}
}
local forces = {player = true, enemy=true, neutral=true, gate=true}
for key, smartStop in pairs(global.smartTrainstops) do
if not forces[key] then
if smartStop.entity then
smartStop.station = smartStop.entity
smartStop.entity = nil
end
if smartStop.proxy then
smartStop.signalProxy = smartStop.proxy
smartStop.proxy = nil
end
tmp[smartStop.station.force.name] =tmp[smartStop.station.force.name] or {}
tmp[smartStop.station.force.name][key] = smartStop
end
end
global.smartTrainstops = tmp
for _, stops in pairs(global.smartTrainstops) do
for _, smartStop in pairs(stops) do
recreateProxy(smartStop.station)
end
end
end
local function factorioVersion()
local baseVersion = game.active_mods.base and string.split(game.active_mods.base, ".")
if baseVersion then
return baseVersion[2]
end
end
local function removeDuplicateTrains()
for k, ent in pairs(global.blueprinted_proxies) do
if not ent.valid then
global.blueprinted_proxies[k] = nil
end
end
TrainList.removeInvalidTrains()
local r = {}
local found = false
for i, ti in pairs(global.trains) do
if ti.train and ti.train.valid then
local id = TrainList.getTrainID(ti.train)
if i ~= id then
for _, loco in pairs(TrainList.getLocomotives(ti.train)) do
if global.trains[loco.unit_number] then
found = true
end
end
if found then
r[i] = true
else
global.trains[id] = ti
end
end
else
r[i] = true
end
end
for id, _ in pairs(r) do
if global.trains[id] and global.trains[id].train and global.trains[id].train.valid then
global.trains[id]:resetWaitingStation()
end
global.trains[id] = nil
end
--TrainList.removeDuplicates()
end
local update_from_version = {
["0.0.0"] = function()
return "4.0.8"
end,
}
function on_configuration_changed(data)
local status, err = pcall(function()
if not data.mod_changes then
return
end
if data.mod_changes.SmartTrains then
local old_version = data.mod_changes.SmartTrains.old_version
local new_version = data.mod_changes.SmartTrains.new_version
if old_version then
saveGlob("PreUpdate"..old_version.."_"..game.tick)
end
initGlob()
init_forces()
init_players()
setMetatables()
local searchedStations = false
if old_version and new_version then
if old_version < "2.0.3" then
error("Updating from an outdated version, get at least SmartTrains 2.0.3 from the mod portal to update this save.")
end
local ver = update_from_version[old_version] and old_version or "0.0.0"
local searched
while ver ~= new_version do
if update_from_version[ver] then
ver, searched = update_from_version[ver]()
searchedStations = searchedStations or searched
else
break
end
end
debugDump("SmartTrains version changed from "..old_version.." to ".. new_version,true)
end
if not searchedStations then
findStations()
end
global.version = new_version
end
--clear fuelvalue cache
global.fuel_values = {}
end)
if not status then
--LOGGERS.main.write()
error(err, 2)
end
end
function createProxy(trainstop)
local positions = getProxyPositions(trainstop)
local force = trainstop.force.name
local key = stationKey(trainstop)
local smartStop = global.smartTrainstops[force][key]
local keySignal = stationKey({position=positions.signalProxy})
local keyCargo = stationKey({position=positions.cargo})
local signalProxy, cargoProxy
local proxy = {name="smart-train-stop-proxy", direction = 0, force=trainstop.force, position=positions.signalProxy}
local proxycargo = {name="smart-train-stop-proxy-cargo", direction = trainstop.direction, force=trainstop.force, position=positions.cargo}
if global.blueprinted_proxies[keySignal] then
local signal = global.blueprinted_proxies[keySignal]
if signal and signal.valid then
--debugDump("signal: "..serpent.line(signal.position),true)
signal.revive()
end
global.blueprinted_proxies[keySignal] = nil
end
if global.blueprinted_proxies[keyCargo] then
local cargo = global.blueprinted_proxies[keyCargo]
if cargo and cargo.valid then
--debugDump("cargo: "..serpent.line(cargo.position),true)
cargo.revive()
end
global.blueprinted_proxies[keyCargo] = nil
end
if smartStop and smartStop.station and smartStop.station.valid then
if smartStop.signalProxy and smartStop.signalProxy.valid then
if not Position.equals(positions.signalProxy, smartStop.signalProxy.position) then
smartStop.signalProxy.teleport(positions.signalProxy)
log("moved signal proxy " .. trainstop.backer_name)
end
end
if smartStop.cargo and smartStop.cargo.valid then
if not Position.equals(positions.cargo, smartStop.cargo.position) then
smartStop.cargo.teleport(positions.cargo)
log("moved cargo proxy " .. trainstop.backer_name)
end
end
end
signalProxy = trainstop.surface.find_entity("smart-train-stop-proxy", positions.signalProxy)
if not signalProxy then
signalProxy = trainstop.surface.create_entity(proxy)
end
cargoProxy = trainstop.surface.find_entity("smart-train-stop-proxy-cargo", positions.cargo)
if not cargoProxy then
cargoProxy = trainstop.surface.create_entity(proxycargo)
end
if signalProxy.valid and cargoProxy.valid then
cargoProxy.operable = false
cargoProxy.destructible = false
cargoProxy.minable = false
cargoProxy.get_or_create_control_behavior().parameters = nil
signalProxy.destructible = false
signalProxy.minable = false
if not global.smartTrainstops[force][key] then
global.smartTrainstops[force][key] = {station = trainstop, signalProxy = signalProxy, cargo = cargoProxy}
end
else
pauseError("Could not find signal/cargo proxy for " .. trainstop.backer_name .. " @ " .. serpent.line(trainstop.position,{comment=false}))
end
end
function removeProxy(trainstop)
local force = trainstop.force.name
local key = stationKey(trainstop)
if global.smartTrainstops[force][key] then
local proxy = global.smartTrainstops[force][key].signalProxy
local cargo = global.smartTrainstops[force][key].cargo
if proxy and proxy.valid then
proxy.destroy()
end
if cargo and cargo.valid then
cargo.destroy()
end
global.smartTrainstops[force][key] = nil
end
end
function findTrainStopByTrain(trainInfo)
return trainInfo.train.station
end
function findSmartTrainStopByTrain(trainInfo, stationName)
local station = findTrainStopByTrain(trainInfo)
if station and station.name == "smart-train-stop" and station.backer_name == stationName then
flyingText("S", colors.GREEN, station.position, true, station.surface)
return global.smartTrainstops[station.force.name][stationKey(station)]
end
return false
end
function inSchedule(station, schedule)
if type(schedule) == "table" and type(schedule.records) == "table" then
for i, rec in pairs(schedule.records) do
if rec.station == station then
return i
end
end
end
return false
end
function inSchedule_reverse(station, schedule)
if type(schedule) == "table" and type(schedule.records) == "table" then
for i=#schedule.records, 1, -1 do
if schedule.records[i].station == station then
return i
end
end
end
return false
end
function removeStation(station, schedule)
local found = false
local tmp = schedule
for i, rec in pairs(schedule.records) do
if rec.station == station then
found = i
end
end
if found then
table.remove(schedule.records, found)
end
return tmp
end
function addStation(station, schedule, wait, after)
wait = wait or 600
local tmp = {wait_conditions = {{type="time", ticks = wait, compare_type = "and"}}, station = station}
if after then
table.insert(schedule.records, after+1, tmp)
else
table.insert(schedule.records, tmp)
end
return schedule
end
function fuelvalue(item)
if not global.fuel_values[item] then
global.fuel_values[item] = game.item_prototypes[item].fuel_value/1000000
end
--return game.item_prototypes[item].fuel_value/1000000
return global.fuel_values[item]
end
function fuel_value_to_coal(value)
return math.ceil(value/fuelvalue('coal'))
end
local function getKeyByValue(t, value)
for k, v in pairs(t) do
if v == value then
return k
end
end
end
function on_train_changed_state(event)
--log(game.tick.." "..getKeyByValue(defines.train_state, event.train.state))
--debugLog("train changed state to "..event.train.state.. " s")
local status, err = pcall(function()
local train = event.train
local t = TrainList.getTrainInfo(train)
--log(serpent.block(t,{comment=false}))
--assert(t.train.valid)
-- TODO is this for de/coupling an automated train???
if t and not t.train.valid then
t = TrainList.updateTrainInfo(train)
end
if not t then
return
end
--log(event.tick .. " " .. t.name .. ": State change from " .. util.getKeyByValue(defines.train_state, event.old_state) .. " to " .. util.getKeyByValue(defines.train_state, event.train.state))
--log(t.name .. " ".. util.getKeyByValue(defines.train_state, event.train.state))
t:updateState()
if t.advancedState == train_state.left_station then
--if t.current then
--log(t.name .. ": Leaving station #" .. t.current .. " " .. t.train.schedule.records[t.current].station .. " @tick: "..event.tick)
--log(t.name .. ": t.train current #" .. t.train.schedule.current)
--end
local jump, use_mapping
local needs_update = (t.line and global.trainLines[t.line]) and t.lineVersion < global.trainLines[t.line].changed or false
--log("Checking line, needs update: " ..serpent.line( needs_update,{comment=false}))
local oldSchedule = t.train.schedule
local oldName = t:getStationName(t.current)
local numRecordsOld = #oldSchedule.records
local newSchedule, numRecordsNew, newName
if needs_update and oldSchedule then
if t:updateLine() then
newSchedule = t.train.schedule
newName = t:getStationName(t.current)
numRecordsNew = #newSchedule.records
--log("old count: " .. numRecordsOld .. " new count: " .. numRecordsNew)
if t.current == numRecordsOld and numRecordsOld < numRecordsNew then
jump = t.current + 1
--log("setting current to " .. jump)
end
if t.current > numRecordsNew then
jump = 1
--log("setting current to " .. jump)
end
if newName ~= oldName then
--TODO find oldStation in schedule and use its rules?
--for newIndex, r in pairs(newSchedule.records) do
--if r.station == oldName then
--log("setting current to new value: " .. t.current .. " -> " .. newIndex)
--t.current = newIndex
--end
--end
log("updating line changed name of current station, so what?")
end
--TODO check if jumpTo is still used for the departing station and jump target is valid with the new schedule
end
end
local rules = t:get_rules(t.current)
if t.departAt and event.tick < t.departAt and rules and (rules.jumpTo or rules.jumpToCircuit) then
local signalValue = rules.jumpToCircuit
local gotoStation = rules.jumpTo
if signalValue then
signalValue = t:getCircuitValue(t.current)
--log("signalValue: " .. signalValue)
end
use_mapping = global.trainLines[t.line] and global.trainLines[t.line].settings.useMapping or false
--log("Signal: "..serpent.line(signalValue,{comment=false}) .. " use mapping: " .. serpent.line(use_mapping,{comment=false}))
if use_mapping then
local jumpSignal, jumpTo
if signalValue then
jumpSignal = t:get_first_matching_station(signalValue, t.current)
--log("jumpSignal: " .. serpent.line(jumpSignal, {comment=false}) .. " -> " .. t:getStationName(jumpSignal) or " invalid index")
end
if gotoStation then
jumpTo = t:get_first_matching_station(gotoStation, t.current)
--log("jumpTo: " .. serpent.line(jumpTo, {comment=false}) .. " -> " .. t:getStationName(jumpTo) or " invalid index")
end
jump = jumpSignal or jumpTo or false
else
jump = (t:isValidScheduleIndex(signalValue)) or gotoStation or false
--log("Jumping to " .. tostring(jump))
end
end
if jump then
t:nextStation(false, jump)
end
if t.settings.autoRefuel and t.current == #t.train.schedule.records then --t.refueling might be false already
if t:getStationName(t.current) == t:refuelStation() and t:isRefuelingDone() then
t.refueling = false
t:removeRefuelStation()
end
end
t.current = nil
t:resetWaitingStation(true)
return
end
if train.state == defines.train_state.wait_signal or train.state == defines.train_state.arrive_signal then
return
end
local settings = t.settings
local lowest_fuel = t:lowestFuel()
local schedule = train.schedule
if train.state == defines.train_state.manual_control_stop or train.state == defines.train_state.manual_control then
-- TODO Why like this??
for _, train_ in pairs(global.trains) do
if train_ == t then
t:resetWaitingStation()
end
end
t:updateLine()
elseif train.state == defines.train_state.wait_station then
-- if global.timingStarted then
-- global.timedTrains = global.timedTrains - 1
-- if global.timedTrains == 0 then
-- remote.call("st", "stopTiming")
-- end
-- end
--LOGGERS.main.log("Train arrived at " .. t:currentStation() .. "\t\t train: " .. t.name .. " Speed: " .. t.train.speed)
--t:updateLine()
t:setWaitingStation()
t.current = t.train.schedule.current
--local rules = t:get_rules()
--log("waiting: " .. serpent.line(rules,{comment=false}))
t.departAt = event.tick + t:getWaitingTime()
if settings.autoRefuel then
if t:currentStation() == t:refuelStation() and #schedule.records == schedule.current then
t:startRefueling()
end
end
elseif train.state == defines.train_state.arrive_station then
if t.settings.autoRefuel then
if not isHybridTrain(train) and lowest_fuel < (global.settings.refuel.rangeMin) and not inSchedule(t:refuelStation(), train.schedule) then
train.schedule = addStation(t:refuelStation(), train.schedule, global.settings.refuel.time)
if global.showFlyingText then
t:flyingText("Refuel station added", colors.YELLOW)
end
end
if t:isRefuelingDone() and t:currentStation() ~= t:refuelStation() and train.schedule.current < #train.schedule.records then
t:removeRefuelStation()
end
end
--log(t.name .. " updating")
t:updateLine()
if t.train.speed ~= 0 then --only update direction when train is moving: prevents direction being lost when train is stopped/started at a station
t.direction = t.train.speed < 0 and 1 or 0
end
end
end)
if not status then
pauseError(err, "train_changed_state")
end
--debugLog("train changed state to "..event.train.state.. " e")
--log("state change e")