aboutsummaryrefslogtreecommitdiff
path: root/advtrains
diff options
context:
space:
mode:
Diffstat (limited to 'advtrains')
-rw-r--r--advtrains/api_doc.txt3
-rw-r--r--advtrains/init.lua3
-rw-r--r--advtrains/lzb.lua192
-rw-r--r--advtrains/trainlogic.lua24
-rw-r--r--advtrains/wagons.lua4
5 files changed, 221 insertions, 5 deletions
diff --git a/advtrains/api_doc.txt b/advtrains/api_doc.txt
index 0a2cb44..34f1beb 100644
--- a/advtrains/api_doc.txt
+++ b/advtrains/api_doc.txt
@@ -180,8 +180,9 @@ minetest.register_node(nodename, {
^- called when a train leaves the rail
-- The following function is only in effect when interlocking is enabled:
- on_train_approach = function(pos, train_id, train, index)
+ on_train_approach = function(pos, train_id, train, index, lzbdata)
^- called when a train is approaching this position, called exactly once for every path recalculation (which can happen at any time)
^- This is called so that if the train would start braking now, it would come to halt about(wide approx) 5 nodes before the rail.
+ ^- lzbdata should be ignored and nothing should be assigned to it
}
})
diff --git a/advtrains/init.lua b/advtrains/init.lua
index 14a5a02..4e5ae90 100644
--- a/advtrains/init.lua
+++ b/advtrains/init.lua
@@ -25,6 +25,7 @@ local no_action=false
local function reload_saves()
atwarn("Restoring saved state in 1 second...")
no_action=true
+ advtrains.lock_path_inval = false
--read last save state and continue, as if server was restarted
for aoi, le in pairs(minetest.luaentities) do
if le.is_wagon then
@@ -192,6 +193,8 @@ dofile(advtrains.modpath.."/craft_items.lua")
dofile(advtrains.modpath.."/log.lua")
dofile(advtrains.modpath.."/passive.lua")
+dofile(advtrains.modpath.."/lzb.lua")
+
--load/save
diff --git a/advtrains/lzb.lua b/advtrains/lzb.lua
new file mode 100644
index 0000000..efbce66
--- /dev/null
+++ b/advtrains/lzb.lua
@@ -0,0 +1,192 @@
+-- lzb.lua
+-- Enforced and/or automatic train override control, providing the on_train_approach callback
+
+--[[
+Documentation of train.lzb table
+train.lzb = {
+ trav = Current index that the traverser has advanced so far
+ oncoming = table containing oncoming signals, in order of appearance on the path
+ {
+ pos = position of the point
+ idx = where this is on the path
+ spd = speed allowed to pass
+ fun = function(pos, id, train, index, speed, lzbdata)
+ -- Function that determines what to do on the train in the moment it drives over that point.
+ }
+}
+each step, for every item in "oncoming", we need to determine the location to start braking (+ some safety margin)
+and, if we passed this point for at least one of the items, initiate brake.
+When speed has dropped below, say 3, decrease the margin to zero, so that trains actually stop at the signal IP.
+The spd variable and travsht need to be updated on every aspect change. it's probably best to reset everything when any aspect changes
+]]
+
+
+local params = {
+ BRAKE_SPACE = 10,
+ AWARE_ZONE = 50,
+
+ ADD_STAND = 2.5,
+ ADD_SLOW = 1.5,
+ ADD_FAST = 7,
+ ZONE_ROLL = 2,
+ ZONE_HOLD = 5, -- added on top of ZONE_ROLL
+ ZONE_VSLOW = 3, -- When speed is <2, still allow accelerating
+
+ DST_FACTOR = 1.5,
+
+ SHUNT_SPEED_MAX = advtrains.SHUNT_SPEED_MAX,
+}
+
+function advtrains.set_lzb_param(par, val)
+ if params[par] and tonumber(val) then
+ params[par] = tonumber(val)
+ else
+ error("Inexistant param or not a number")
+ end
+end
+
+
+local function look_ahead(id, train)
+
+ local acc = advtrains.get_acceleration(train, 1)
+ local vel = train.velocity
+ local brakedst = ( -(vel*vel) / (2*acc) ) * params.DST_FACTOR
+
+ local brake_i = advtrains.path_get_index_by_offset(train, train.index, brakedst + params.BRAKE_SPACE)
+ --local aware_i = advtrains.path_get_index_by_offset(train, brake_i, AWARE_ZONE)
+
+ local lzb = train.lzb
+ local trav = lzb.trav
+
+ --train.debug = lspd
+
+ while trav <= brake_i do
+ trav = trav + 1
+ local pos = advtrains.path_get(train, trav)
+ -- check offtrack
+ if trav > train.path_trk_f then
+ table.insert(lzb.oncoming, {
+ pos = pos,
+ idx = trav-1,
+ spd = 0,
+ })
+ else
+ -- run callbacks
+ -- Note: those callbacks are defined in trainlogic.lua for consistency with the other node callbacks
+ advtrains.tnc_call_approach_callback(pos, id, train, trav, lzb.data)
+
+ end
+ end
+
+ lzb.trav = trav
+
+end
+
+--[[
+Distance needed to accelerate from v0 to v1 with constant acceleration a:
+
+ v1 - v0 a / v1 - v0 \ 2
+s = v0 * ------- + - * | ------- |
+ a 2 \ a /
+]]
+
+local function apply_control(id, train)
+ local lzb = train.lzb
+
+ local i = 1
+ while i<=#lzb.oncoming do
+ if lzb.oncoming[i].idx < train.index then
+ local ent = lzb.oncoming[i]
+ if ent.fun then
+ ent.fun(ent.pos, id, train, ent.idx, ent.spd, lzb.data)
+ end
+
+ table.remove(lzb.oncoming, i)
+ else
+ i = i + 1
+ end
+ end
+
+ for i, it in ipairs(lzb.oncoming) do
+ local a = advtrains.get_acceleration(train, 1) --should be negative
+ local v0 = train.velocity
+ local v1 = it.spd
+ if v1 and v1 <= v0 then
+ local f = (v1-v0) / a
+ local s = v0*f + a*f*f/2
+
+ local st = s + params.ADD_SLOW
+ if v0 > 3 then
+ st = s + params.ADD_FAST
+ end
+ if v0<=0 then
+ st = s + params.ADD_STAND
+ end
+
+ local i = advtrains.path_get_index_by_offset(train, it.idx, -st)
+
+ --train.debug = dump({v0f=v0*f, aff=a*f*f,v0=v0, v1=v1, f=f, a=a, s=s, st=st, i=i, idx=train.index})
+ if i <= train.index then
+ -- Gotcha! Braking...
+ train.ctrl.lzb = 1
+ --train.debug = train.debug .. "BRAKE!!!"
+ return
+ end
+
+ i = advtrains.path_get_index_by_offset(train, i, -params.ZONE_ROLL)
+ if i <= train.index and v0>1 then
+ -- roll control
+ train.ctrl.lzb = 2
+ return
+ end
+ i = advtrains.path_get_index_by_offset(train, i, -params.ZONE_HOLD)
+ if i <= train.index and v0>1 then
+ -- hold speed
+ train.ctrl.lzb = 3
+ return
+ end
+ end
+ end
+ train.ctrl.lzb = nil
+end
+
+local function invalidate(train)
+ train.lzb = {
+ trav = atfloor(train.index),
+ data = {},
+ oncoming = {},
+ }
+end
+
+function advtrains.lzb_invalidate(train)
+ invalidate(train)
+end
+
+-- Add LZB control point
+-- udata: User-defined additional data
+function advtrains.lzb_add_checkpoint(train, index, speed, callback, udata)
+ local lzb = train.lzb
+ local pos = advtrains.path_get(train, index)
+ table.insert(lzb.oncoming, {
+ pos = pos,
+ idx = index,
+ spd = speed,
+ fun = callback,
+ data = udata,
+ })
+end
+
+
+advtrains.te_register_on_new_path(function(id, train)
+ invalidate(train)
+ look_ahead(id, train)
+end)
+
+advtrains.te_register_on_update(function(id, train)
+ if not train.path or not train.lzb then
+ atprint("LZB run: no path on train, skip step")
+ return
+ end
+ look_ahead(id, train)
+ apply_control(id, train)
+end, true)
diff --git a/advtrains/trainlogic.lua b/advtrains/trainlogic.lua
index 523e51d..ce9ec8b 100644
--- a/advtrains/trainlogic.lua
+++ b/advtrains/trainlogic.lua
@@ -585,9 +585,9 @@ local function mknodecallback(name)
table.insert(callt, func)
end
end
- return callt, function(pos, id, train, index)
+ return callt, function(pos, id, train, index, paramx1, paramx2, paramx3)
for _,f in ipairs(callt) do
- f(pos, id, train, index)
+ f(pos, id, train, index, paramx1, paramx2, paramx3)
end
end
end
@@ -597,6 +597,14 @@ end
local callbacks_enter_node, run_callbacks_enter_node = mknodecallback("enter")
local callbacks_leave_node, run_callbacks_leave_node = mknodecallback("leave")
+-- Node callback for approaching
+-- Might be called multiple times, whenever path is recalculated
+-- signature is function(pos, id, train, index, lzbdata)
+-- lzbdata: arbitrary data (shared between all callbacks), deleted when LZB is restarted.
+-- These callbacks are called in order of distance as train progresses along tracks, so lzbdata can be used to
+-- keep track of a train's state once it passes this point
+local callbacks_approach_node, run_callbacks_approach_node = mknodecallback("approach")
+
local function tnc_call_enter_callback(pos, train_id, train, index)
--atdebug("tnc enter",pos,train_id)
@@ -621,6 +629,18 @@ local function tnc_call_leave_callback(pos, train_id, train, index)
run_callbacks_leave_node(pos, train_id, train, index)
end
+function advtrains.tnc_call_approach_callback(pos, train_id, train, index, lzbdata)
+ --atdebug("tnc approach",pos,train_id, lzbdata)
+ local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
+ local mregnode=minetest.registered_nodes[node.name]
+ if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_approach then
+ mregnode.advtrains.on_train_approach(pos, train_id, train, index, lzbdata)
+ end
+
+ -- call other registered callbacks
+ run_callbacks_approach_node(pos, train_id, train, index, lzbdata)
+end
+
advtrains.te_register_on_new_path(function(id, train)
train.tnc = {
diff --git a/advtrains/wagons.lua b/advtrains/wagons.lua
index 5b15c70..381f835 100644
--- a/advtrains/wagons.lua
+++ b/advtrains/wagons.lua
@@ -846,8 +846,8 @@ function wagon:show_bordcom(pname)
local i=1
while train.lzb.oncoming[i] do
local oci = train.lzb.oncoming[i]
- if oci.pos then
- if advtrains.interlocking.db.get_sigd_for_signal(oci.pos) then
+ if oci.udata and oci.udata.signal_pos then
+ if advtrains.interlocking.db.get_sigd_for_signal(oci.udata.signal_pos) then
form = form .. "button[4.5,8;5,1;ilrs;Remote Routesetting]"
break
end
'>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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
--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

--acceleration for lever modes (trainhud.lua), per wagon
local t_accel_all={
	[0] = -10,
	[1] = -3,
	[2] = -0.5,
	[4] = 0.5,
}
--acceleration per engine
local t_accel_eng={
	[0] = 0,
	[1] = 0,
	[2] = 0,
	[4] = 1.5,
}

tp_player_tmr = 0

advtrains.mainloop_trainlogic=function(dtime)
	--build a table of all players indexed by pts. used by damage and door system.
	advtrains.playersbypts={}
	for _, player in pairs(minetest.get_connected_players()) do
		if not advtrains.player_to_train_mapping[player:get_player_name()] then
			--players in train are not subject to damage
			local ptspos=minetest.pos_to_string(vector.round(player:getpos()))
			advtrains.playersbypts[ptspos]=player
		end
	end
	
	if tp_player_tmr<=0 then
		-- teleport players to their train every 2 seconds
		for _, player in pairs(minetest.get_connected_players()) do
			advtrains.tp_player_to_train(player)
		end
		tp_player_tmr = 2
	else
		tp_player_tmr = tp_player_tmr - dtime
	end
	--regular train step
	--[[ structure:
	1. make trains calculate their occupation windows when needed (a)
	2. when occupation tells us so, restore the occupation tables (a)
	4. make trains move and update their new occupation windows and write changes
	   to occupation tables (b)
	5. make trains do other stuff (c)
	]]--
	local t=os.clock()
	
	for k,v in pairs(advtrains.trains) do
		advtrains.atprint_context_tid=k
		advtrains.train_ensure_init(k, v)
	end
	
	for k,v in pairs(advtrains.trains) do
		advtrains.atprint_context_tid=k
		advtrains.train_step_b(k, v, dtime)
	end
	
	for k,v in pairs(advtrains.trains) do
		advtrains.atprint_context_tid=k
		advtrains.train_step_c(k, v, dtime)
	end
	
	advtrains.atprint_context_tid=nil
	
	atprintbm("trainsteps", t)
	endstep()
end

function advtrains.tp_player_to_train(player)
	local pname = player:get_player_name()
	local id=advtrains.player_to_train_mapping[pname]
	if id then
		local train=advtrains.trains[id]
		if not train then advtrains.player_to_train_mapping[pname]=nil return end
		--set the player to the train position.
		--minetest will emerge the area and load the objects, which then will call reattach_all().
		--because player is in mapping, it will not be subject to dying.
		player:setpos(train.last_pos_prev)
	end
end
minetest.register_on_joinplayer(function()
	return advtrains.pcall(function()
		--independent of this, cause all wagons of the train which are loaded to reattach their players
		--needed because already loaded wagons won't call reattach_all()
		for _,wagon in pairs(minetest.luaentities) do
			if wagon.is_wagon and wagon.initialized and wagon.train_id==id then
				wagon:reattach_all()
			end
		end
	end)
end)


minetest.register_on_dieplayer(function(player)
	return advtrains.pcall(function()
		local pname=player:get_player_name()
		local id=advtrains.player_to_train_mapping[pname]
		if id then
			local train=advtrains.trains[id]
			if not train then advtrains.player_to_train_mapping[pname]=nil return end
			for _,wagon in pairs(minetest.luaentities) do
				if wagon.is_wagon and wagon.initialized and wagon.train_id==id then
					--when player dies, detach him from the train
					--call get_off_plr on every wagon since we don't know which one he's on.
					wagon:get_off_plr(pname)
				end
			end
		end
	end)
end)

--[[

Zone diagram of a train (copy from occupation.lua!):
              |___| |___| --> Direction of travel
              oo oo+oo oo
=|=======|===|===========|===|=======|===================|========|===
 |SafetyB|CpB|   Train   |CpF|SafetyF|        Brake      |Aware   |
[1]     [2] [3]         [4] [5]     [6]                 [7]      [8]
This mapping from indices in occwindows to zone ids is contained in WINDOW_ZONE_IDS


The occupation system has been abandoned. The constants will still be used
to determine the couple distance
(because of the reverse lookup, the couple system simplifies a lot...)

]]--
-- unless otherwise stated, in meters.
local SAFETY_ZONE = 10
local COUPLE_ZONE = 2 --value in index positions!
local BRAKE_SPACE = 10
local AWARE_ZONE = 10
local WINDOW_ZONE_IDS = {
	2, -- 1 - SafetyB
	4, -- 2 - CpB
	1, -- 3 - Train
	5, -- 4 - CpF
	3, -- 5 - SafetyF
	6, -- 6 - Brake
	7, -- 7 - Aware
}


-- If a variable does not exist in the table, it is assigned the default value
local function assertdef(tbl, var, def)
	if not tbl[var] then
		tbl[var] = def
	end
end

function advtrains.get_acceleration(train, lever)
	local acc_all = t_accel_all[lever]
	local acc_eng = t_accel_eng[lever]
	local nwagons = #train.trainparts
	local acc = acc_all + (acc_eng*train.locomotives_in_train)/nwagons
	return acc
end

-- Small local util function to recalculate train's end index
local function recalc_end_index(train)
	train.end_index = advtrains.path_get_index_by_offset(train, train.index, -train.trainlen)
end

-- Occupation Callback system
-- see occupation.lua
-- signature is advtrains.te_register_on_<?>(function(id, train) ... end)

local function mkcallback(name)
	local callt = {}
	advtrains["te_register_on_"..name] = function(func)
		assertt(func, "function")
		table.insert(callt, func)
	end
	return callt, function(id, train)
		for _,f in ipairs(callt) do
			f(id, train)
		end
	end
end

local callbacks_new_path, run_callbacks_new_path = mkcallback("new_path")
local callbacks_update, run_callbacks_update = mkcallback("update")
local callbacks_create, run_callbacks_create = mkcallback("create")
local callbacks_remove, run_callbacks_remove = mkcallback("remove")


-- train_ensure_init: responsible for creating a state that we can work on, after one of the following events has happened:
-- - the train's path got cleared
-- - save files were loaded
-- Additionally, this gets called outside the step cycle to initialize and/or remove a train, then occ_write_mode is set.
function advtrains.train_ensure_init(id, train)
	train.dirty = true
	if train.no_step then return nil end

	assertdef(train, "velocity", 0)
	--assertdef(train, "tarvelocity", 0)
	assertdef(train, "acceleration", 0)
	assertdef(train, "id", id)
	assertdef(train, "ctrl", {})
	
	
	if not train.drives_on or not train.max_speed then
		advtrains.update_trainpart_properties(id)
	end
	
	--restore path
	if not train.path then
		if not train.last_pos then
			atwarn("Train",id,": Restoring path failed, no last_pos set! Train will be disabled. You can try to fix the issue in the save file.")
			train.no_step = true
			return nil
		end
		if not train.last_connid then
			atwarn("Train",id,": Restoring path: no last_connid set! Will assume 1")
			train.last_connid = 1
			--[[
			Why this fix was necessary:
			Issue: Migration problems on Grand Theft Auto Minetest
			1. Run of this code, warning printed.
			2. path_create failed with result==nil (there was an unloaded node, wait_for_path set)
			3. in consequence, the supposed call to path_setrestore does not happen
			4. train.last_connid is still unset
			5. next step, warning is printed again
			Result: log flood.
			]]
		end
		
		local result = advtrains.path_create(train, train.last_pos, train.last_connid or 1, train.last_frac or 0)
		
		if result==false then
			atwarn("Train",id,": Restoring path failed, node at",train.last_pos,"is gone! Train will be disabled. You can try to place a rail at this position and restart the server.")
			train.no_step = true
			return nil
		elseif result==nil then
			if not train.wait_for_path then
				atwarn("Train",id,": Can't initialize: Waiting for the (yet unloaded) node at",train.last_pos," to be loaded.")
			end
			train.wait_for_path = true
			return false
		end
		-- by now, we should have a working initial path
		train.wait_for_path = false
		
		advtrains.update_trainpart_properties(id)
		recalc_end_index(train)
		
		--atdebug("Train",id,": Successfully restored path at",train.last_pos," connid",train.last_connid," frac",train.last_frac)
		
		-- run on_new_path callbacks
		run_callbacks_new_path(id, train)
	end
	
	train.dirty = false -- TODO einbauen!
	return true
end

function advtrains.train_step_b(id, train, dtime)
	if train.no_step or train.wait_for_path then return end
	
	-- in this code, we check variables such as path_trk_? and path_dist. We need to ensure that the path is known for the whole 'Train' zone
	advtrains.path_get(train, atfloor(train.index + 2))
	advtrains.path_get(train, atfloor(train.end_index - 1))
	
	--- 3. handle velocity influences ---
	local train_moves=(train.velocity~=0)
	local tarvel_cap = train.speed_restriction
	
	if train.recently_collided_with_env then
		tarvel_cap=0
		if not train_moves then
			train.recently_collided_with_env=nil--reset status when stopped
		end
	end
	if train.locomotives_in_train==0 then
		tarvel_cap=0
	end
	
	--- 3a. this can be useful for debugs/warnings and is used for check_trainpartload ---
	local t_info, train_pos=sid(id), advtrains.path_get(train, atfloor(train.index))
	if train_pos then
		t_info=t_info.." @"..minetest.pos_to_string(train_pos)
		--atprint("train_pos:",train_pos)
	end
	
	--apply off-track handling:
	local front_off_track = train.index>train.path_trk_f
	local back_off_track=train.end_index<train.path_trk_b
	train.off_track = front_off_track or back_off_track
	
	if front_off_track then
		tarvel_cap=0
	end
	if back_off_track then -- eventually overrides front_off_track restriction
		tarvel_cap=1
	end
	
	-- Driving control rework:
	--[[
	Items are only defined when something is controlling them.
	In order of precedence.
	train.ctrl = {
		lzb  = restrictive override from LZB
		user = User input from driverstand
		atc  = ATC command override (determined here)
	}
	The code here determines the precedence and writes the final control into train.lever
	]]
	
	--interpret ATC command and apply auto-lever control when not actively controlled
	local trainvelocity = train.velocity
	
	if train.ctrl.user then
		advtrains.atc.train_reset_command(train)
	else
		local braketar = train.atc_brake_target
		local emerg = false -- atc_brake_target==-1 means emergency brake (BB command)
		if braketar == -1 then
			braketar = 0
			emerg = true
		end
		if braketar and braketar>=trainvelocity then
			train.atc_brake_target=nil
			braketar = nil
		end
		--if train.tarvelocity and train.velocity==train.tarvelocity then
		--	train.tarvelocity = nil
		--end
		if train.atc_wait_finish then
			if not train.atc_brake_target and (not train.tarvelocity or train.velocity==train.tarvelocity) then
				train.atc_wait_finish=nil
			end
		end
		if train.atc_command then
			if (not train.atc_delay or 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
		elseif train.atc_delay then
			train.atc_delay = nil
		end
		
		train.ctrl.atc = nil
		if train.tarvelocity and train.tarvelocity>trainvelocity then
			train.ctrl.atc=4
		end
		if train.tarvelocity and train.tarvelocity<trainvelocity then
			if (braketar and braketar<trainvelocity) then
				if emerg then
					train.ctrl.atc = 0
				else
					train.ctrl.atc=1
				end
			else
				train.ctrl.atc=2
			end
		end
	end
	
	if tarvel_cap and train.tarvelocity and tarvel_cap<train.tarvelocity then
		train.tarvelocity=tarvel_cap
	end
	
	local tmp_lever
	
	for _, lev in pairs(train.ctrl) do
		-- use the most restrictive of all control overrides
		tmp_lever = math.min(tmp_lever or 4, lev)
	end
	
	if not tmp_lever then
		-- if there was no control at all, default to 3
		tmp_lever = 3
	end
	
	if tarvel_cap and trainvelocity>tarvel_cap then
		tmp_lever = 0
	end
	
	train.lever = tmp_lever