/po/it/

on.png'/>
aboutsummaryrefslogtreecommitdiff
path: root/advtrains/advtrains/trainlogic.lua
blob: 07a48ccfcb1b9fe36703d09514380f289ae75602 (plain)
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
--trainlogic.lua
--controls train entities stuff about connecting/disconnecting/colliding trains and other things


local benchmark=false
local bm={}
local bmlt=0
local bmsteps=0
local bmstepint=200
atprintbm=function(action, ta)
	if not benchmark then return end
	local t=(os.clock()-ta)*1000
	if not bm[action] then
		bm[action]=t
	else
		bm[action]=bm[action]+t
	end
	bmlt=bmlt+t
end
function endstep()
	if not benchmark then return end
	bmsteps=bmsteps-1
	if bmsteps<=0 then
		bmsteps=bmstepint
		for key, value in pairs(bm) do
			minetest.chat_send_all(key.." "..(value/bmstepint).." ms avg.")
		end
		minetest.chat_send_all("Total time consumed by all advtrains actions per step: "..(bmlt/bmstepint).." ms avg.")
		bm={}
		bmlt=0
	end
end

advtrains.train_accel_force=2--per second and divided by number of wagons
advtrains.train_brake_force=3--per second, not divided by number of wagons
advtrains.train_roll_force=0.5--per second, not divided by number of wagons, acceleration when rolling without brake
advtrains.train_emerg_force=10--for emergency brakes(when going off track)

advtrains.audit_interval=10


advtrains.trains={}
advtrains.wagon_save={}

--load initially
advtrains.fpath=minetest.get_worldpath().."/advtrains"
local file, err = io.open(advtrains.fpath, "r")
if not file then
	local er=err or "Unknown Error"
	atprint("Failed loading advtrains save file "..er)
else
	local tbl = minetest.deserialize(file:read("*a"))
	if type(tbl) == "table" then
		advtrains.trains=tbl
	end
	file:close()
end
advtrains.fpath_ws=minetest.get_worldpath().."/advtrains_wagon_save"
local file, err = io.open(advtrains.fpath_ws, "r")
if not file then
	local er=err or "Unknown Error"
	atprint("Failed loading advtrains save file "..er)
else
	local tbl = minetest.deserialize(file:read("*a"))
	if type(tbl) == "table" then
		advtrains.wagon_save=tbl
	end
	file:close()
end


advtrains.save = function()
	atprint("saving")
	advtrains.invalidate_all_paths()
	local datastr = minetest.serialize(advtrains.trains)
	if not datastr then
		minetest.log("error", " Failed to serialize train data!")
		return
	end
	local file, err = io.open(advtrains.fpath, "w")
	if err then
		return err
	end
	file:write(datastr)
	file:close()
	
	-- update wagon saves
	for _,wagon in pairs(minetest.luaentities) do
		if wagon.is_wagon and wagon.initialized then
			wagon:get_staticdata()
		end
	end
	--cross out userdata
	for w_id, data in pairs(advtrains.wagon_save) do
		data.name=nil
		data.object=nil
		if data.driver then
			data.driver_name=data.driver:get_player_name()
			data.driver=nil
		else
			data.driver_name=nil
		end
		if data.discouple then
			data.discouple.object:remove()
			data.discouple=nil
		end
	end
	--atprint(dump(advtrains.wagon_save))
	datastr = minetest.serialize(advtrains.wagon_save)
	if not datastr then
		minetest.log("error", " Failed to serialize train data!")
		return
	end
	file, err = io.open(advtrains.fpath_ws, "w")
	if err then
		return err
	end
	file:write(datastr)
	file:close()
	
	advtrains.save_trackdb()
	advtrains.atc.save()
end
minetest.register_on_shutdown(advtrains.save)

advtrains.save_and_audit_timer=advtrains.audit_interval
minetest.register_globalstep(function(dtime)
	advtrains.save_and_audit_timer=advtrains.save_and_audit_timer-dtime
	if advtrains.save_and_audit_timer<=0 then
		local t=os.clock()
		
		--save
		advtrains.save()
		advtrains.save_and_audit_timer=advtrains.audit_interval
		atprintbm("saving", t)
	end
	--regular train step
	local t=os.clock()
	for k,v in pairs(advtrains.trains) do
		advtrains.train_step(k, v, dtime)
	end
	
	--see tracks.lua
	if advtrains.detector.clean_step_before then
		advtrains.detector.finalize_restore()
	end
	
	atprintbm("trainsteps", t)
	endstep()
end)

function advtrains.train_step(id, train, dtime)
	--Legacy: set drives_on and max_speed
	if not train.drives_on or not train.max_speed then
		advtrains.update_trainpart_properties(id)
	end
	--TODO check for all vars to be present
	if not train.velocity then
		train.velocity=0
	end
	if not train.movedir or (train.movedir~=1 and train.movedir~=-1) then
		train.movedir=1
	end
	--very unimportant thing: check if couple is here
	if train.couple_eid_front and (not minetest.luaentities[train.couple_eid_front] or not minetest.luaentities[train.couple_eid_front].is_couple) then train.couple_eid_front=nil end
	if train.couple_eid_back and (not minetest.luaentities[train.couple_eid_back] or not minetest.luaentities[train.couple_eid_back].is_couple) then train.couple_eid_back=nil end
	
	--skip certain things (esp. collision) when not moving
	local train_moves=(train.velocity~=0)
	
	--if not train.last_pos then advtrains.trains[id]=nil return end
	
	if not advtrains.pathpredict(id, train) then 
		atprint("pathpredict failed(returned false)")
		train.velocity=0
		train.tarvelocity=0
		return
	end
	
	local path=advtrains.get_or_create_path(id, train)
	if not path then
		train.velocity=0
		train.tarvelocity=0
		atprint("train has no path for whatever reason")
		return 
	end
	
	local train_end_index=advtrains.get_train_end_index(train)
	--apply off-track handling:
	local front_off_track=train.max_index_on_track and train.index>train.max_index_on_track
	local back_off_track=train.min_index_on_track and train_end_index<train.min_index_on_track
	if front_off_track and back_off_track then--allow movement in both directions
		if train.tarvelocity>1 then train.tarvelocity=1 end
	elseif front_off_track then--allow movement only backward
		if train.movedir==1 and train.tarvelocity>0 then train.tarvelocity=0 end
		if train.movedir==-1 and train.tarvelocity>1 then train.tarvelocity=1 end
	elseif back_off_track then--allow movement only forward
		if train.movedir==-1 and train.tarvelocity>0 then train.tarvelocity=0 end
		if train.movedir==1 and train.tarvelocity>1 then train.tarvelocity=1 end
	end
	
	--update advtrains.detector
	if not train.detector_old_index then
		train.detector_old_index = math.floor(train_end_index)
		train.detector_old_end_index = math.floor(train_end_index)
	end
	local ifo, ifn, ibo, ibn = train.detector_old_index, math.floor(train.index), train.detector_old_end_index, math.floor(train_end_index)
	if ifn>ifo then
		for i=ifo, ifn do
			if path[i] then
				advtrains.detector.enter_node(path[i], id)
			end
		end
	elseif ifn<ifo then
		for i=ifn, ifo do
			if path[i] then
				advtrains.detector.leave_node(path[i], id)
			end
		end
	end
	if ibn<ibo then
		for i=ibn, ibn do
			if path[i] then
				advtrains.detector.enter_node(path[i], id)
			end
		end
	elseif ibn>ibo then
		for i=ibo, ibn do
			if path[i] then
				advtrains.detector.leave_node(path[i], id)
			end
		end
	end
	train.detector_old_index = math.floor(train.index)
	train.detector_old_end_index = math.floor(train_end_index)
	
	--remove?
	if #train.trainparts==0 then
		atprint("[train "..sid(id).."] has empty trainparts, removing.")
		advtrains.detector.leave_node(path[train.detector_old_index], id)
		advtrains.trains[id]=nil
		return
	end
	
	if train_moves then
		--check for collisions by finding objects
		
		--heh, new collision again.
		--this time, based on NODES and the advtrains.detector.on_node table.
		local collpos
		local coll_grace=1
		if train.movedir==1 then
			collpos=advtrains.get_real_index_position(path, train.index-coll_grace)
		else
			collpos=advtrains.get_real_index_position(path, train_end_index+coll_grace)
		end
		if collpos then
			local rcollpos=advtrains.round_vector_floor_y(collpos)
			for x=-1,1 do
				for z=-1,1 do
					local testpos=vector.add(rcollpos, {x=x, y=0, z=z})
					local testpts=minetest.pos_to_string(testpos)
					if advtrains.detector.on_node[testpts] and advtrains.detector.on_node[testpts]~=id then
						if advtrains.trains[advtrains.detector.on_node[testpts]] then
							--collides
							advtrains.spawn_couple_on_collide(id, testpos, advtrains.detector.on_node[testpts], train.movedir==-1)
							
							train.recently_collided_with_env=true
							train.velocity=0.5*train.velocity
							train.movedir=train.movedir*-1
							train.tarvelocity=0
						else
							--unexistant train left in this place
							advtrains.detector.on_node[testpts]=nil
						end
					end
				end
			end
		end
	end
	--check for any trainpart entities if they have been unloaded. do this only if train is near a player, to not spawn entities into unloaded areas
	--todo function will be taken by update_trainpart_properties
	train.check_trainpartload=(train.check_trainpartload or 0)-dtime
	local node_range=(math.max((minetest.setting_get("active_block_range") or 0),1)*16)
	if train.check_trainpartload<=0 then
		local ori_pos=advtrains.get_real_index_position(path, train.index) --not much to calculate
		--atprint("[train "..id.."] at "..minetest.pos_to_string(vector.round(ori_pos)))
		
		local should_check=false
		for _,p in ipairs(minetest.get_connected_players()) do
			should_check=should_check or ((vector.distance(ori_pos, p:getpos())<node_range))
		end
		if should_check then
			advtrains.update_trainpart_properties(id)
		end
		train.check_trainpartload=2
	end
	
	
	--handle collided_with_env
	if train.recently_collided_with_env then
		train.tarvelocity=0
		if not train_moves then
			train.recently_collided_with_env=false--reset status when stopped
		end
	end
	if train.locomotives_in_train==0 then
		train.tarvelocity=0
	end
	
	--interpret ATC command
	if train.atc_brake_target and train.atc_brake_target>=train.velocity then
		train.atc_brake_target=nil
	end
	if train.atc_wait_finish then
		if not train.atc_brake_target and train.velocity==train.tarvelocity then
			train.atc_wait_finish=nil
		end
	end
	if train.atc_command then
		if train.atc_delay<=0 and not train.atc_wait_finish then
			advtrains.atc.execute_atc_command(id, train)
		else
			train.atc_delay=train.atc_delay-dtime
		end
	end
	
	--make brake adjust the tarvelocity if necessary
	if train.brake and (math.ceil(train.velocity)-1)<train.tarvelocity then
		train.tarvelocity=math.max((math.ceil(train.velocity)-1), 0)
	end
	--apply tarvel(but with physics in mind!)
	if train.velocity~=train.tarvelocity then
		local applydiff=0
		local mass=#train.trainparts
		local diff=train.tarvelocity-train.velocity
		if diff>0 then--accelerating, force will be brought on only by locomotives.
			--atprint("accelerating with default force")
			applydiff=(math.min((advtrains.train_accel_force*train.locomotives_in_train*dtime)/mass, math.abs(diff)))
		else--decelerating
			if front_off_track or back_off_track or train.recently_collided_with_env then --every wagon has a brake, so not divided by mass.
				--atprint("braking with emergency force")
				applydiff= -(math.min((advtrains.train_emerg_force*dtime), math.abs(diff)))
			elseif train.brake or (train.atc_brake_target and train.atc_brake_target<train.velocity) then
				--atprint("braking with default force")
				--no math.min, because it can grow beyond tarvelocity, see up there
				--dont worry, it will never fall below zero.
				applydiff= -((advtrains.train_brake_force*dtime))
			else
				--atprint("roll")
				applydiff= -(math.min((advtrains.train_roll_force*dtime), math.abs(diff)))
			end
		end
		train.last_accel=(applydiff*train.movedir)
		train.velocity=math.min(math.max( train.velocity+applydiff , 0), train.max_speed or 10)
	else
		train.last_accel=0
	end
	
	--move
	--TODO 3,5 + 0.7
	train.index=train.index and train.index+(((train.velocity*train.movedir)/(train.path_dist[math.floor(train.index)] or 1))*dtime) or 0
	
end


--structure of train table:
--[[
trains={
	[train_id]={
		trainparts={
			[n]=wagon_id
		}
		path={path}
		velocity
		tarvelocity
		index
		trainlen
		path_inv_level
		last_pos       |
		last_dir       | for pathpredicting.
	}
}
--a wagon itself has the following properties:
wagon={
	unique_id
	train_id
	pos_in_train (is index difference, including train_span stuff)
	pos_in_trainparts (is index in trainparts tabel of trains)
}
inherited by metatable:
wagon_proto={
	wagon_span
}
]]

--returns new id
function advtrains.create_new_train_at(pos, pos_prev)
	local newtrain_id=os.time()..os.clock()