aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/network/serverpackethandler.cpp379
1 files changed, 180 insertions, 199 deletions
diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp
index abd9deff0..d133b4ff9 100644
--- a/src/network/serverpackethandler.cpp
+++ b/src/network/serverpackethandler.cpp
@@ -986,10 +986,6 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
// Update wielded item
playersao->getPlayer()->setWieldIndex(item_i);
- // Get pointed to node (undefined if not POINTEDTYPE_NODE)
- v3s16 p_under = pointed.node_undersurface;
- v3s16 p_above = pointed.node_abovesurface;
-
// Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
ServerActiveObject *pointed_object = NULL;
if (pointed.type == POINTEDTHING_OBJECT) {
@@ -1002,17 +998,6 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
}
- v3f pointed_pos_under = player_pos;
- v3f pointed_pos_above = player_pos;
- if (pointed.type == POINTEDTHING_NODE) {
- pointed_pos_under = intToFloat(p_under, BS);
- pointed_pos_above = intToFloat(p_above, BS);
- }
- else if (pointed.type == POINTEDTHING_OBJECT) {
- pointed_pos_under = pointed_object->getBasePosition();
- pointed_pos_above = pointed_pos_under;
- }
-
/*
Make sure the player is allowed to do it
*/
@@ -1020,16 +1005,19 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
actionstream << player->getName() << " attempted to interact with " <<
pointed.dump() << " without 'interact' privilege" << std::endl;
+ if (pointed.type != POINTEDTHING_NODE)
+ return;
+
// Re-send block to revert change on client-side
RemoteClient *client = getClient(peer_id);
// Digging completed -> under
if (action == INTERACT_DIGGING_COMPLETED) {
- v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
+ v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
client->SetBlockNotSent(blockpos);
}
// Placement -> above
else if (action == INTERACT_PLACE) {
- v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
+ v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
client->SetBlockNotSent(blockpos);
}
return;
@@ -1037,7 +1025,6 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
/*
Check that target is reasonably close
- (only when digging or placing things)
*/
static thread_local const bool enable_anticheat =
!g_settings->getBool("disable_anticheat");
@@ -1045,12 +1032,19 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
action == INTERACT_PLACE || action == INTERACT_USE) &&
enable_anticheat && !isSingleplayer()) {
- float d = playersao->getEyePosition().getDistanceFrom(pointed_pos_under);
+ v3f target_pos = player_pos;
+ if (pointed.type == POINTEDTHING_NODE) {
+ target_pos = intToFloat(pointed.node_undersurface, BS);
+ } else if (pointed.type == POINTEDTHING_OBJECT) {
+ target_pos = pointed_object->getBasePosition();
+ }
+ float d = playersao->getEyePosition().getDistanceFrom(target_pos);
- if (!checkInteractDistance(player, d, pointed.dump())) {
+ if (!checkInteractDistance(player, d, pointed.dump())
+ && pointed.type == POINTEDTHING_NODE) {
// Re-send block to revert change on client-side
RemoteClient *client = getClient(peer_id);
- v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
+ v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
client->SetBlockNotSent(blockpos);
return;
}
@@ -1062,20 +1056,20 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
RollbackScopeActor rollback_scope(m_rollback,
std::string("player:")+player->getName());
- /*
- 0: start digging or punch object
- */
- if (action == INTERACT_START_DIGGING) {
+ switch (action) {
+ // Start digging or punch object
+ case INTERACT_START_DIGGING: {
if (pointed.type == POINTEDTHING_NODE) {
MapNode n(CONTENT_IGNORE);
bool pos_ok;
+ v3s16 p_under = pointed.node_undersurface;
n = m_env->getMap().getNode(p_under, &pos_ok);
if (!pos_ok) {
infostream << "Server: Not punching: Node not found. "
"Adding block to emerge queue." << std::endl;
- m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above),
- false);
+ m_emerge->enqueueBlockEmerge(peer_id,
+ getNodeBlockPos(pointed.node_abovesurface), false);
}
if (n.getContent() != CONTENT_IGNORE)
@@ -1083,159 +1077,155 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
// Cheat prevention
playersao->noCheatDigStart(p_under);
+
+ return;
}
- else if (pointed.type == POINTEDTHING_OBJECT) {
- // Skip if object can't be interacted with anymore
- if (pointed_object->isGone())
- return;
- ItemStack selected_item, hand_item;
- ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
- ToolCapabilities toolcap =
- tool_item.getToolCapabilities(m_itemdef);
- v3f dir = (pointed_object->getBasePosition() -
- (playersao->getBasePosition() + playersao->getEyeOffset())
- ).normalize();
- float time_from_last_punch =
- playersao->resetTimeFromLastPunch();
-
- u16 src_original_hp = pointed_object->getHP();
- u16 dst_origin_hp = playersao->getHP();
-
- u16 wear = pointed_object->punch(dir, &toolcap, playersao,
- time_from_last_punch);
-
- // Callback may have changed item, so get it again
- playersao->getWieldedItem(&selected_item);
- bool changed = selected_item.addWear(wear, m_itemdef);
- if (changed)
- playersao->setWieldedItem(selected_item);
-
- // If the object is a player and its HP changed
- if (src_original_hp != pointed_object->getHP() &&
- pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
- SendPlayerHPOrDie((PlayerSAO *)pointed_object,
- PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
- }
+ // Skip if the object can't be interacted with anymore
+ if (pointed.type != POINTEDTHING_OBJECT || pointed_object->isGone())
+ return;
- // If the puncher is a player and its HP changed
- if (dst_origin_hp != playersao->getHP())
- SendPlayerHPOrDie(playersao,
- PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
+ ItemStack selected_item, hand_item;
+ ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
+ ToolCapabilities toolcap =
+ tool_item.getToolCapabilities(m_itemdef);
+ v3f dir = (pointed_object->getBasePosition() -
+ (playersao->getBasePosition() + playersao->getEyeOffset())
+ ).normalize();
+ float time_from_last_punch =
+ playersao->resetTimeFromLastPunch();
+
+ u16 src_original_hp = pointed_object->getHP();
+ u16 dst_origin_hp = playersao->getHP();
+
+ u16 wear = pointed_object->punch(dir, &toolcap, playersao,
+ time_from_last_punch);
+
+ // Callback may have changed item, so get it again
+ playersao->getWieldedItem(&selected_item);
+ bool changed = selected_item.addWear(wear, m_itemdef);
+ if (changed)
+ playersao->setWieldedItem(selected_item);
+
+ // If the object is a player and its HP changed
+ if (src_original_hp != pointed_object->getHP() &&
+ pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
+ SendPlayerHPOrDie((PlayerSAO *)pointed_object,
+ PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
}
+ // If the puncher is a player and its HP changed
+ if (dst_origin_hp != playersao->getHP())
+ SendPlayerHPOrDie(playersao,
+ PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
+
+ return;
} // action == INTERACT_START_DIGGING
- /*
- 1: stop digging
- */
- else if (action == INTERACT_STOP_DIGGING) {
- } // action == INTERACT_STOP_DIGGING
+ case INTERACT_STOP_DIGGING:
+ // Nothing to do
+ return;
- /*
- 2: Digging completed
- */
- else if (action == INTERACT_DIGGING_COMPLETED) {
+ case INTERACT_DIGGING_COMPLETED: {
// Only digging of nodes
- if (pointed.type == POINTEDTHING_NODE) {
- bool pos_ok;
- MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
- if (!pos_ok) {
- infostream << "Server: Not finishing digging: Node not found. "
- "Adding block to emerge queue." << std::endl;
- m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above),
- false);
- }
-
- /* Cheat prevention */
- bool is_valid_dig = true;
- if (enable_anticheat && !isSingleplayer()) {
- v3s16 nocheat_p = playersao->getNoCheatDigPos();
- float nocheat_t = playersao->getNoCheatDigTime();
- playersao->noCheatDigEnd();
- // If player didn't start digging this, ignore dig
- if (nocheat_p != p_under) {
- infostream << "Server: " << player->getName()
- << " started digging "
- << PP(nocheat_p) << " and completed digging "
- << PP(p_under) << "; not digging." << std::endl;
- is_valid_dig = false;
- // Call callbacks
- m_script->on_cheat(playersao, "finished_unknown_dig");
- }
+ if (pointed.type != POINTEDTHING_NODE)
+ return;
+ bool pos_ok;
+ v3s16 p_under = pointed.node_undersurface;
+ MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
+ if (!pos_ok) {
+ infostream << "Server: Not finishing digging: Node not found. "
+ "Adding block to emerge queue." << std::endl;
+ m_emerge->enqueueBlockEmerge(peer_id,
+ getNodeBlockPos(pointed.node_abovesurface), false);
+ }
- // Get player's wielded item
- // See also: Game::handleDigging
- ItemStack selected_item, hand_item;
- playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
-
- // Get diggability and expected digging time
- DigParams params = getDigParams(m_nodedef->get(n).groups,
- &selected_item.getToolCapabilities(m_itemdef));
- // If can't dig, try hand
- if (!params.diggable) {
- params = getDigParams(m_nodedef->get(n).groups,
- &hand_item.getToolCapabilities(m_itemdef));
- }
- // If can't dig, ignore dig
- if (!params.diggable) {
- infostream << "Server: " << player->getName()
- << " completed digging " << PP(p_under)
- << ", which is not diggable with tool; not digging."
- << std::endl;
- is_valid_dig = false;
- // Call callbacks
- m_script->on_cheat(playersao, "dug_unbreakable");
- }
- // Check digging time
- // If already invalidated, we don't have to
- if (!is_valid_dig) {
- // Well not our problem then
- }
- // Clean and long dig
- else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
- // All is good, but grab time from pool; don't care if
- // it's actually available
- playersao->getDigPool().grab(params.time);
- }
- // Short or laggy dig
- // Try getting the time from pool
- else if (playersao->getDigPool().grab(params.time)) {
- // All is good
- }
- // Dig not possible
- else {
- infostream << "Server: " << player->getName()
- << " completed digging " << PP(p_under)
- << "too fast; not digging." << std::endl;
- is_valid_dig = false;
- // Call callbacks
- m_script->on_cheat(playersao, "dug_too_fast");
- }
+ /* Cheat prevention */
+ bool is_valid_dig = true;
+ if (enable_anticheat && !isSingleplayer()) {
+ v3s16 nocheat_p = playersao->getNoCheatDigPos();
+ float nocheat_t = playersao->getNoCheatDigTime();
+ playersao->noCheatDigEnd();
+ // If player didn't start digging this, ignore dig
+ if (nocheat_p != p_under) {
+ infostream << "Server: " << player->getName()
+ << " started digging "
+ << PP(nocheat_p) << " and completed digging "
+ << PP(p_under) << "; not digging." << std::endl;
+ is_valid_dig = false;
+ // Call callbacks
+ m_script->on_cheat(playersao, "finished_unknown_dig");
}
- /* Actually dig node */
-
- if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
- m_script->node_on_dig(p_under, n, playersao);
-
- v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
- RemoteClient *client = getClient(peer_id);
- // Send unusual result (that is, node not being removed)
- if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR) {
- // Re-send block to revert change on client-side
- client->SetBlockNotSent(blockpos);
+ // Get player's wielded item
+ // See also: Game::handleDigging
+ ItemStack selected_item, hand_item;
+ playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
+
+ // Get diggability and expected digging time
+ DigParams params = getDigParams(m_nodedef->get(n).groups,
+ &selected_item.getToolCapabilities(m_itemdef));
+ // If can't dig, try hand
+ if (!params.diggable) {
+ params = getDigParams(m_nodedef->get(n).groups,
+ &hand_item.getToolCapabilities(m_itemdef));
+ }
+ // If can't dig, ignore dig
+ if (!params.diggable) {
+ infostream << "Server: " << player->getName()
+ << " completed digging " << PP(p_under)
+ << ", which is not diggable with tool; not digging."
+ << std::endl;
+ is_valid_dig = false;
+ // Call callbacks
+ m_script->on_cheat(playersao, "dug_unbreakable");
+ }
+ // Check digging time
+ // If already invalidated, we don't have to
+ if (!is_valid_dig) {
+ // Well not our problem then
+ }
+ // Clean and long dig
+ else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
+ // All is good, but grab time from pool; don't care if
+ // it's actually available
+ playersao->getDigPool().grab(params.time);
}
+ // Short or laggy dig
+ // Try getting the time from pool
+ else if (playersao->getDigPool().grab(params.time)) {
+ // All is good
+ }
+ // Dig not possible
else {
- client->ResendBlockIfOnWire(blockpos);
+ infostream << "Server: " << player->getName()
+ << " completed digging " << PP(p_under)
+ << "too fast; not digging." << std::endl;
+ is_valid_dig = false;
+ // Call callbacks
+ m_script->on_cheat(playersao, "dug_too_fast");
}
}
+
+ /* Actually dig node */
+
+ if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
+ m_script->node_on_dig(p_under, n, playersao);
+
+ v3s16 blockpos = getNodeBlockPos(p_under);
+ RemoteClient *client = getClient(peer_id);
+ // Send unusual result (that is, node not being removed)
+ if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
+ // Re-send block to revert change on client-side
+ client->SetBlockNotSent(blockpos);
+ else
+ client->ResendBlockIfOnWire(blockpos);
+
+ return;
} // action == INTERACT_DIGGING_COMPLETED
- /*
- 3: place block or right-click object
- */
- else if (action == INTERACT_PLACE) {
+ // Place block or right-click object
+ case INTERACT_PLACE: {
ItemStack selected_item;
playersao->getWieldedItem(&selected_item, nullptr);
@@ -1264,59 +1254,54 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
}
pointed_object->rightClick(playersao);
- } else if (m_script->item_OnPlace(
- selected_item, playersao, pointed)) {
+ } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) {
// Placement was handled in lua
// Apply returned ItemStack
- if (playersao->setWieldedItem(selected_item)) {
+ if (playersao->setWieldedItem(selected_item))
SendInventory(playersao, true);
- }
}
+ if (pointed.type != POINTEDTHING_NODE)
+ return;
+
// If item has node placement prediction, always send the
// blocks to make sure the client knows what exactly happened
RemoteClient *client = getClient(peer_id);
- v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
- v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
- if (!selected_item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
+ v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
+ v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
+ if (!selected_item.getDefinition(m_itemdef
+ ).node_placement_prediction.empty()) {
client->SetBlockNotSent(blockpos);
- if (blockpos2 != blockpos) {
+ if (blockpos2 != blockpos)
client->SetBlockNotSent(blockpos2);
- }
- }
- else {
+ } else {
client->ResendBlockIfOnWire(blockpos);
- if (blockpos2 != blockpos) {
+ if (blockpos2 != blockpos)
client->ResendBlockIfOnWire(blockpos2);
- }
}
+
+ return;
} // action == INTERACT_PLACE
- /*
- 4: use
- */
- else if (action == INTERACT_USE) {
+ case INTERACT_USE: {
ItemStack selected_item;
playersao->getWieldedItem(&selected_item, nullptr);
actionstream << player->getName() << " uses " << selected_item.name
<< ", pointing at " << pointed.dump() << std::endl;
- if (m_script->item_OnUse(
- selected_item, playersao, pointed)) {
+ if (m_script->item_OnUse(selected_item, playersao, pointed)) {
// Apply returned ItemStack
- if (playersao->setWieldedItem(selected_item)) {
+ if (playersao->setWieldedItem(selected_item))
SendInventory(playersao, true);
- }
}
- } // action == INTERACT_USE
+ return;
+ }
- /*
- 5: rightclick air
- */
- else if (action == INTERACT_ACTIVATE) {
+ // Rightclick air
+ case INTERACT_ACTIVATE: {
ItemStack selected_item;
playersao->getWieldedItem(&selected_item, nullptr);
@@ -1325,21 +1310,17 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
- if (m_script->item_OnSecondaryUse(
- selected_item, playersao, pointed)) {
- if (playersao->setWieldedItem(selected_item)) {
+ if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) {
+ if (playersao->setWieldedItem(selected_item))
SendInventory(playersao, true);
- }
}
- } // action == INTERACT_ACTIVATE
+ return;
+ }
+
+ default:
+ warningstream << "Server: Invalid action " << action << std::endl;
- /*
- Catch invalid actions
- */
- else {
- warningstream << "Server: Invalid action "
- << action << std::endl;
}
}
'#n947'>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
--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.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
	--regular train step
	-- do in two steps: 
	--  a: predict path and add all nodes to the advtrains.detector.on_node table
	--  b: check for collisions based on these data
	--  (and more)
	local t=os.clock()
	advtrains.detector.on_node={}
	for k,v in pairs(advtrains.trains) do
		advtrains.atprint_context_tid=sid(k)
		advtrains.atprint_context_tid_full=k
		advtrains.train_step_a(k, v, dtime)
	end
	for k,v in pairs(advtrains.trains) do
		advtrains.atprint_context_tid=sid(k)
		advtrains.atprint_context_tid_full=k
		advtrains.train_step_b(k, v, dtime)
	end
	
	advtrains.atprint_context_tid=nil
	advtrains.atprint_context_tid_full=nil
	
	atprintbm("trainsteps", t)
	endstep()
end

minetest.register_on_joinplayer(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
			--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)
			--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)
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)
--[[
train step structure:


- legacy stuff
- preparing the initial path and creating index
- setting node coverage old indices
- handle velocity influences:
	- off-track
	- atc
	- player controls
	- environment collision
- update index = move
- create path
- call stay_node on all old positions to register train there, for collision system
- do less important stuff such as checking trainpartload or removing

-- break --
- Call enter_node and leave_node callbacks (required here because stay_node needs to be called on all trains first)
- handle train collisions

]]

function advtrains.train_step_a(id, train, dtime)
	--atprint("--- runcnt ",advtrains.mainloop_runcnt,": index",train.index,"end_index", train.end_index,"| max_iot", train.max_index_on_track, "min_iot", train.min_index_on_track, "<> pe_min", train.path_extent_min,"pe_max", train.path_extent_max)
	if train.min_index_on_track then
		assert(math.floor(train.min_index_on_track)==train.min_index_on_track)
	end
	--- 1. LEGACY STUFF ---
	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
	--- 2. prepare initial path and index if needed ---
	if not train.index then train.index=0 end
	if not train.path then
		if not train.last_pos then
			--no chance to recover
			atwarn("Unable to restore train ",id,": missing last_pos")
			advtrains.trains[id]=nil
			return false
		end
		
		local node_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(train.last_pos), train.drives_on)
		
		if node_ok==nil then
			--block not loaded, do nothing
			atprint("last_pos", advtrains.round_vector_floor_y(train.last_pos), "not loaded and not in ndb, waiting")
			return nil
		elseif node_ok==false then
			atprint("Unable to restore train ",id,": No rail at train's position")
			return false
		end
		
		if not train.last_pos_prev then
			--no chance to recover
			atwarn("Unable to restore train ",id,": missing last_pos_prev")
			advtrains.trains[id]=nil
			return false
		end
		
		local prevnode_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(train.last_pos_prev), train.drives_on)
		
		if prevnode_ok==nil then
			--block not loaded, do nothing
			atprint("last_pos_prev", advtrains.round_vector_floor_y(train.last_pos_prev), "not loaded and not in ndb, waiting")
			return nil
		elseif prevnode_ok==false then
			atprint("Unable to restore train ",id,": No rail at train's position")
			return false
		end
		
		train.index=(train.restore_add_index or 0)+(train.savedpos_off_track_index_offset or 0)
		--restore_add_index is set by save() to prevent trains hopping to next round index. should be between -0.5 and 0.5
		--savedpos_off_track_index_offset is set if train went off track. see below.
		train.path={}
		train.path_dist={}
		train.path[0]=train.last_pos
		train.path[-1]=train.last_pos_prev
		train.path_dist[-1]=vector.distance(train.last_pos, train.last_pos_prev)
		train.path_extent_min=-1
		train.path_extent_max=0
		train.min_index_on_track=-1
		train.max_index_on_track=0
		
		--[[
		Bugfix for trains randomly ignoring ATC rails:
		- Paths have been invalidated. 1 gets executed and ensures an initial path
		- 2a sets train end index. The problem is that path_dist is not known for the whole path, so train end index will be nearly trainlen
		- Since the detector indices are also unknown, they get set to the new (wrong) train_end_index. Enter_node calls are not executed for the nodes that lie in between real end_index and trainlen.
		- The next step, mistake is recognized, train leaves some positions. From there, everything works again.
		To overcome this, we will generate the full required path here so that path_dist is available for get_train_end_index(). 
		]]
		advtrains.pathpredict(id, train)
	end
	
	--- 2a. set train.end_index which is required in different places, IF IT IS NOT SET YET by STMT afterwards. ---
	---   table entry to avoid triple recalculation ---
	if not train.end_index then
		train.end_index=advtrains.get_train_end_index(train)
	end
	
	--- 2b. set node coverage old indices ---
	
	train.detector_old_index = atround(train.index)
	train.detector_old_end_index = atround(train.end_index)
	
	--- 3. handle velocity influences ---
	local train_moves=(train.velocity~=0)
	
	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