Changeset - r8143:59f1aeab7b39
[Not reviewed]
master
0 1 0
smatz - 17 years ago 2007-12-27 13:25:23
smatz@openttd.org
(svn r11705) -Fix [FS#1557]: trains could have sprites with wrong direction when reversing, also was inconsistent with save/load process (possible desyncs)
1 file changed with 12 insertions and 14 deletions:
0 comments (0 inline, 0 general)
src/train_cmd.cpp
Show inline comments
 
@@ -1381,437 +1381,441 @@ CommandCost CmdSellRailWagon(TileIndex t
 

	
 
							if (flags & DC_EXEC) {
 
								first = UnlinkWagon(rear, first);
 
								DeleteDepotHighlightOfVehicle(rear);
 
								delete rear;
 
							}
 
						}
 
					} else if (v->u.rail.other_multiheaded_part != NULL) {
 
						/* The front to this engine is earlier in this train. Do nothing */
 
						continue;
 
					}
 
				}
 

	
 
				cost.AddCost(-v->value);
 
				if (flags & DC_EXEC) {
 
					first = UnlinkWagon(v, first);
 
					DeleteDepotHighlightOfVehicle(v);
 
					delete v;
 
				}
 
			}
 

	
 
			/* 3. If it is still a valid train after selling, update its acceleration and cached values */
 
			if (flags & DC_EXEC && first != NULL) {
 
				NormaliseTrainConsist(first);
 
				TrainConsistChanged(first);
 
				UpdateTrainGroupID(first);
 
				if (IsFrontEngine(first)) UpdateTrainAcceleration(first);
 
				InvalidateWindow(WC_VEHICLE_DETAILS, first->index);
 
				InvalidateWindow(WC_VEHICLE_REFIT, first->index);
 
			}
 
		} break;
 
	}
 
	return cost;
 
}
 

	
 
void Train::UpdateDeltaXY(Direction direction)
 
{
 
#define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
 
	static const uint32 _delta_xy_table[8] = {
 
		MKIT(3, 3, -1, -1),
 
		MKIT(3, 7, -1, -3),
 
		MKIT(3, 3, -1, -1),
 
		MKIT(7, 3, -3, -1),
 
		MKIT(3, 3, -1, -1),
 
		MKIT(3, 7, -1, -3),
 
		MKIT(3, 3, -1, -1),
 
		MKIT(7, 3, -3, -1),
 
	};
 
#undef MKIT
 

	
 
	uint32 x = _delta_xy_table[direction];
 
	this->x_offs        = GB(x,  0, 8);
 
	this->y_offs        = GB(x,  8, 8);
 
	this->sprite_width  = GB(x, 16, 8);
 
	this->sprite_height = GB(x, 24, 8);
 
	this->z_height      = 6;
 
}
 

	
 
static void UpdateVarsAfterSwap(Vehicle *v)
 
{
 
	v->UpdateDeltaXY(v->direction);
 
	v->cur_image = v->GetImage(v->direction);
 
	BeginVehicleMove(v);
 
	VehiclePositionChanged(v);
 
	EndVehicleMove(v);
 
}
 

	
 
static void SetLastSpeed(Vehicle* v, int spd)
 
{
 
	int old = v->u.rail.last_speed;
 
	if (spd != old) {
 
		v->u.rail.last_speed = spd;
 
		if (_patches.vehicle_speed || (old == 0) != (spd == 0))
 
			InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR);
 
	}
 
}
 

	
 
static void SwapTrainFlags(byte *swap_flag1, byte *swap_flag2)
 
{
 
	byte flag1 = *swap_flag1;
 
	byte flag2 = *swap_flag2;
 

	
 
	/* Clear the flags */
 
	ClrBit(*swap_flag1, VRF_GOINGUP);
 
	ClrBit(*swap_flag1, VRF_GOINGDOWN);
 
	ClrBit(*swap_flag2, VRF_GOINGUP);
 
	ClrBit(*swap_flag2, VRF_GOINGDOWN);
 

	
 
	/* Reverse the rail-flags (if needed) */
 
	if (HasBit(flag1, VRF_GOINGUP)) {
 
		SetBit(*swap_flag2, VRF_GOINGDOWN);
 
	} else if (HasBit(flag1, VRF_GOINGDOWN)) {
 
		SetBit(*swap_flag2, VRF_GOINGUP);
 
	}
 
	if (HasBit(flag2, VRF_GOINGUP)) {
 
		SetBit(*swap_flag1, VRF_GOINGDOWN);
 
	} else if (HasBit(flag2, VRF_GOINGDOWN)) {
 
		SetBit(*swap_flag1, VRF_GOINGUP);
 
	}
 
}
 

	
 
static void ReverseTrainSwapVeh(Vehicle *v, int l, int r)
 
{
 
	Vehicle *a, *b;
 

	
 
	/* locate vehicles to swap */
 
	for (a = v; l != 0; l--) a = a->Next();
 
	for (b = v; r != 0; r--) b = b->Next();
 

	
 
	if (a != b) {
 
		/* swap the hidden bits */
 
		{
 
			uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus&VS_HIDDEN);
 
			b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus&VS_HIDDEN);
 
			a->vehstatus = tmp;
 
		}
 

	
 
		Swap(a->u.rail.track, b->u.rail.track);
 
		Swap(a->direction,    b->direction);
 

	
 
		/* toggle direction */
 
		if (a->u.rail.track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
 
		if (b->u.rail.track != TRACK_BIT_DEPOT) b->direction = ReverseDir(b->direction);
 

	
 
		Swap(a->x_pos, b->x_pos);
 
		Swap(a->y_pos, b->y_pos);
 
		Swap(a->tile,  b->tile);
 
		Swap(a->z_pos, b->z_pos);
 

	
 
		SwapTrainFlags(&a->u.rail.flags, &b->u.rail.flags);
 

	
 
		/* update other vars */
 
		UpdateVarsAfterSwap(a);
 
		UpdateVarsAfterSwap(b);
 

	
 
		/* call the proper EnterTile function unless we are in a wormhole */
 
		if (a->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
 
		if (b->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(b, b->tile, b->x_pos, b->y_pos);
 
	} else {
 
		if (a->u.rail.track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
 
		UpdateVarsAfterSwap(a);
 

	
 
		if (a->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
 
	}
 

	
 
	/* Update train's power incase tiles were different rail type */
 
	TrainPowerChanged(v);
 
}
 

	
 
/* Check if the vehicle is a train and is on the tile we are testing */
 
static void *TestTrainOnCrossing(Vehicle *v, void *data)
 
{
 
	if (v->type != VEH_TRAIN) return NULL;
 
	return v;
 
}
 

	
 
static void DisableTrainCrossing(TileIndex tile)
 
{
 
	if (IsLevelCrossingTile(tile) &&
 
			IsCrossingBarred(tile) &&
 
			VehicleFromPos(tile, NULL, &TestTrainOnCrossing) == NULL) { // empty?
 
		UnbarCrossing(tile);
 
		MarkTileDirtyByTile(tile);
 
	}
 
}
 

	
 
/**
 
 * Advances wagons for train reversing, needed for variable length wagons.
 
 * Needs to be called once before the train is reversed, and once after it.
 
 * @param v First vehicle in chain
 
 * @param before Set to true for the call before reversing, false otherwise
 
 */
 
static void AdvanceWagons(Vehicle *v, bool before)
 
{
 
	Vehicle *base = v;
 
	Vehicle *first = base->Next();
 
	uint length = CountVehiclesInChain(v);
 

	
 
	while (length > 2) {
 
		/* find pairwise matching wagon
 
		 * start<>end, start+1<>end-1, ... */
 
		Vehicle *last = first;
 
		for (uint i = length - 3; i > 0; i--) last = last->Next();
 

	
 
		int differential = last->u.rail.cached_veh_length - base->u.rail.cached_veh_length;
 
		if (before) differential *= -1;
 

	
 
		if (differential > 0) {
 
			/* disconnect last car to make sure only this subset moves */
 
			Vehicle *tempnext = last->Next();
 
			last->SetNext(NULL);
 

	
 
			/* do not update images now because the wagons are disconnected
 
			 * and that could cause problems with NewGRFs */
 
			for (int i = 0; i < differential; i++) TrainController(first, false);
 

	
 
			last->SetNext(tempnext);
 
		}
 

	
 
		base = first;
 
		first = first->Next();
 
		length -= 2;
 
	}
 
}
 

	
 

	
 
static void ReverseTrainDirection(Vehicle *v)
 
{
 
	if (IsTileDepotType(v->tile, TRANSPORT_RAIL)) {
 
		InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
 
	}
 

	
 
	/* Check if we were approaching a rail/road-crossing */
 
	{
 
		TileIndex tile = v->tile;
 
		DiagDirection dir = DirToDiagDir(v->direction);
 

	
 
		/* Determine the diagonal direction in which we will exit this tile */
 
		if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[dir]) {
 
			dir = ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT);
 
		}
 
		/* Calculate next tile */
 
		tile += TileOffsByDiagDir(dir);
 

	
 
		/* Check if the train left a rail/road-crossing */
 
		DisableTrainCrossing(tile);
 
	}
 

	
 
	/* count number of vehicles */
 
	int r = -1;
 
	const Vehicle *u = v;
 
	do r++; while ((u = u->Next()) != NULL);
 
	int r = 0;  ///< number of vehicles - 1
 
	for (const Vehicle *u = v; (u = u->Next()) != NULL;) { r++; }
 

	
 
	AdvanceWagons(v, true);
 

	
 
	/* swap start<>end, start+1<>end-1, ... */
 
	int l = 0;
 
	do {
 
		ReverseTrainSwapVeh(v, l++, r--);
 
	} while (l <= r);
 

	
 
	AdvanceWagons(v, false);
 

	
 
	if (IsTileDepotType(v->tile, TRANSPORT_RAIL)) {
 
		InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
 
	}
 

	
 
	/* update all images */
 
	for (Vehicle *u = v; u != NULL; u = u->Next()) { u->cur_image = u->GetImage(u->direction); }
 

	
 
	ClrBit(v->u.rail.flags, VRF_REVERSING);
 
}
 

	
 
/** Reverse train.
 
 * @param tile unused
 
 * @param flags type of operation
 
 * @param p1 train to reverse
 
 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
 
 */
 
CommandCost CmdReverseTrainDirection(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	if (!IsValidVehicleID(p1)) return CMD_ERROR;
 

	
 
	Vehicle *v = GetVehicle(p1);
 

	
 
	if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
 

	
 
	if (p2) {
 
		/* turn a single unit around */
 

	
 
		if (IsMultiheaded(v) || HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) {
 
			return_cmd_error(STR_ONLY_TURN_SINGLE_UNIT);
 
		}
 

	
 
		Vehicle *front = v->First();
 
		/* make sure the vehicle is stopped in the depot */
 
		if (CheckTrainStoppedInDepot(front) < 0) {
 
			return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
 
		}
 

	
 
		if (flags & DC_EXEC) {
 
			ToggleBit(v->u.rail.flags, VRF_REVERSE_DIRECTION);
 
			InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
 
			InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
 
		}
 
	} else {
 
		/* turn the whole train around */
 
		if (v->vehstatus & VS_CRASHED || v->breakdown_ctr != 0) return CMD_ERROR;
 

	
 
		if (flags & DC_EXEC) {
 
			if (_patches.realistic_acceleration && v->cur_speed != 0) {
 
				ToggleBit(v->u.rail.flags, VRF_REVERSING);
 
			} else {
 
				v->cur_speed = 0;
 
				SetLastSpeed(v, 0);
 
				ReverseTrainDirection(v);
 
			}
 
		}
 
	}
 
	return CommandCost();
 
}
 

	
 
/** Force a train through a red signal
 
 * @param tile unused
 
 * @param flags type of operation
 
 * @param p1 train to ignore the red signal
 
 * @param p2 unused
 
 */
 
CommandCost CmdForceTrainProceed(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	if (!IsValidVehicleID(p1)) return CMD_ERROR;
 

	
 
	Vehicle *v = GetVehicle(p1);
 

	
 
	if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
 

	
 
	if (flags & DC_EXEC) v->u.rail.force_proceed = 0x50;
 

	
 
	return CommandCost();
 
}
 

	
 
/** Refits a train to the specified cargo type.
 
 * @param tile unused
 
 * @param flags type of operation
 
 * @param p1 vehicle ID of the train to refit
 
 * param p2 various bitstuffed elements
 
 * - p2 = (bit 0-7) - the new cargo type to refit to
 
 * - p2 = (bit 8-15) - the new cargo subtype to refit to
 
 * - p2 = (bit 16) - refit only this vehicle
 
 * @return cost of refit or error
 
 */
 
CommandCost CmdRefitRailVehicle(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	CargoID new_cid = GB(p2, 0, 8);
 
	byte new_subtype = GB(p2, 8, 8);
 
	bool only_this = HasBit(p2, 16);
 

	
 
	if (!IsValidVehicleID(p1)) return CMD_ERROR;
 

	
 
	Vehicle *v = GetVehicle(p1);
 

	
 
	if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
 
	if (CheckTrainStoppedInDepot(v) < 0) return_cmd_error(STR_TRAIN_MUST_BE_STOPPED);
 

	
 
	/* Check cargo */
 
	if (new_cid >= NUM_CARGO) return CMD_ERROR;
 

	
 
	SET_EXPENSES_TYPE(EXPENSES_TRAIN_RUN);
 

	
 
	CommandCost cost;
 
	uint num = 0;
 

	
 
	do {
 
		/* XXX: We also refit all the attached wagons en-masse if they
 
		 * can be refitted. This is how TTDPatch does it.  TODO: Have
 
		 * some nice [Refit] button near each wagon. --pasky */
 
		if (!CanRefitTo(v->engine_type, new_cid)) continue;
 

	
 
		if (v->cargo_cap != 0) {
 
			uint16 amount = CALLBACK_FAILED;
 

	
 
			if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
 
				/* Back up the vehicle's cargo type */
 
				CargoID temp_cid = v->cargo_type;
 
				byte temp_subtype = v->cargo_subtype;
 
				v->cargo_type = new_cid;
 
				v->cargo_subtype = new_subtype;
 
				/* Check the refit capacity callback */
 
				amount = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
 
				/* Restore the original cargo type */
 
				v->cargo_type = temp_cid;
 
				v->cargo_subtype = temp_subtype;
 
			}
 

	
 
			if (amount == CALLBACK_FAILED) { // callback failed or not used, use default
 
				const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
 
				CargoID old_cid = rvi->cargo_type;
 
				/* normally, the capacity depends on the cargo type, a rail vehicle can
 
				 * carry twice as much mail/goods as normal cargo, and four times as
 
				 * many passengers
 
				 */
 
				amount = rvi->capacity;
 
				switch (old_cid) {
 
					case CT_PASSENGERS: break;
 
					case CT_MAIL:
 
					case CT_GOODS: amount *= 2; break;
 
					default:       amount *= 4; break;
 
				}
 
				switch (new_cid) {
 
					case CT_PASSENGERS: break;
 
					case CT_MAIL:
 
					case CT_GOODS: amount /= 2; break;
 
					default:       amount /= 4; break;
 
				}
 
			}
 

	
 
			if (amount != 0) {
 
				if (new_cid != v->cargo_type) {
 
					cost.AddCost(GetRefitCost(v->engine_type));
 
				}
 

	
 
				num += amount;
 
				if (flags & DC_EXEC) {
 
					v->cargo.Truncate((v->cargo_type == new_cid) ? amount : 0);
 
					v->cargo_type = new_cid;
 
					v->cargo_cap = amount;
 
					v->cargo_subtype = new_subtype;
 
					InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
 
					InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
 
					RebuildVehicleLists();
 
				}
 
			}
 
		}
 
	} while ((v = v->Next()) != NULL && !only_this);
 

	
 
	_returned_refit_capacity = num;
 

	
 
	/* Update the train's cached variables */
 
	if (flags & DC_EXEC) TrainConsistChanged(GetVehicle(p1)->First());
 

	
 
	return cost;
 
}
 

	
 
struct TrainFindDepotData {
 
	uint best_length;
 
	TileIndex tile;
 
	PlayerID owner;
 
	/**
 
	 * true if reversing is necessary for the train to get to this depot
 
	 * This value is unused when new depot finding and NPF are both disabled
 
	 */
 
	bool reverse;
 
};
 

	
 
static bool NtpCallbFindDepot(TileIndex tile, TrainFindDepotData *tfdd, int track, uint length)
 
{
 
	if (IsTileType(tile, MP_RAILWAY) &&
 
			IsTileOwner(tile, tfdd->owner) &&
 
			IsRailDepot(tile)) {
 
		/* approximate number of tiles by dividing by DIAG_FACTOR */
 
		tfdd->best_length = length / DIAG_FACTOR;
 
		tfdd->tile = tile;
 
@@ -2408,775 +2412,769 @@ static bool ProcessTrainOrder(Vehicle *v
 
		default: break;
 
	}
 

	
 
	/**
 
	 * Reversing because of order change is allowed only just after leaving a
 
	 * station (and the difficulty setting to allowed, of course)
 
	 * this can be detected because only after OT_LEAVESTATION, current_order
 
	 * will be reset to nothing. (That also happens if no order, but in that case
 
	 * it won't hit the point in code where may_reverse is checked)
 
	 */
 
	bool may_reverse = v->current_order.type == OT_NOTHING;
 

	
 
	/* check if we've reached the waypoint? */
 
	if (v->current_order.type == OT_GOTO_WAYPOINT && v->tile == v->dest_tile) {
 
		UpdateVehicleTimetable(v, true);
 
		v->cur_order_index++;
 
	}
 

	
 
	/* check if we've reached a non-stop station while TTDPatch nonstop is enabled.. */
 
	if (_patches.new_nonstop &&
 
			v->current_order.flags & OF_NON_STOP &&
 
			IsTileType(v->tile, MP_STATION) &&
 
			v->current_order.dest == GetStationIndex(v->tile)) {
 
		UpdateVehicleTimetable(v, true);
 
		v->cur_order_index++;
 
	}
 

	
 
	/* Get the current order */
 
	if (v->cur_order_index >= v->num_orders) v->cur_order_index = 0;
 

	
 
	const Order *order = GetVehicleOrder(v, v->cur_order_index);
 

	
 
	/* If no order, do nothing. */
 
	if (order == NULL) {
 
		v->current_order.Free();
 
		v->dest_tile = 0;
 
		return false;
 
	}
 

	
 
	/* If it is unchanged, keep it. */
 
	if (order->type  == v->current_order.type &&
 
			order->flags == v->current_order.flags &&
 
			order->dest  == v->current_order.dest)
 
		return false;
 

	
 
	/* Otherwise set it, and determine the destination tile. */
 
	v->current_order = *order;
 

	
 
	v->dest_tile = 0;
 

	
 
	InvalidateVehicleOrder(v);
 

	
 
	switch (order->type) {
 
		case OT_GOTO_STATION:
 
			if (order->dest == v->last_station_visited)
 
				v->last_station_visited = INVALID_STATION;
 
			v->dest_tile = GetStation(order->dest)->xy;
 
			break;
 

	
 
		case OT_GOTO_DEPOT:
 
			v->dest_tile = GetDepot(order->dest)->xy;
 
			break;
 

	
 
		case OT_GOTO_WAYPOINT:
 
			v->dest_tile = GetWaypoint(order->dest)->xy;
 
			break;
 

	
 
		default:
 
			return false;
 
	}
 

	
 
	return may_reverse && CheckReverseTrain(v);
 
}
 

	
 
void Train::MarkDirty()
 
{
 
	Vehicle *v = this;
 
	do {
 
		v->cur_image = v->GetImage(v->direction);
 
		MarkAllViewportsDirty(v->left_coord, v->top_coord, v->right_coord + 1, v->bottom_coord + 1);
 
	} while ((v = v->Next()) != NULL);
 

	
 
	/* need to update acceleration and cached values since the goods on the train changed. */
 
	TrainCargoChanged(this);
 
	UpdateTrainAcceleration(this);
 
}
 

	
 
static int UpdateTrainSpeed(Vehicle *v)
 
{
 
	uint accel;
 

	
 
	if (v->vehstatus & VS_STOPPED || HasBit(v->u.rail.flags, VRF_REVERSING)) {
 
		if (_patches.realistic_acceleration) {
 
			accel = GetTrainAcceleration(v, AM_BRAKE) * 2;
 
		} else {
 
			accel = v->acceleration * -2;
 
		}
 
	} else {
 
		if (_patches.realistic_acceleration) {
 
			accel = GetTrainAcceleration(v, AM_ACCEL);
 
		} else {
 
			accel = v->acceleration;
 
		}
 
	}
 

	
 
	uint spd = v->subspeed + accel * 2;
 
	v->subspeed = (byte)spd;
 
	{
 
		int tempmax = v->max_speed;
 
		if (v->cur_speed > v->max_speed)
 
			tempmax = v->cur_speed - (v->cur_speed / 10) - 1;
 
		v->cur_speed = spd = Clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax);
 
	}
 

	
 
	if (!(v->direction & 1)) spd = spd * 3 >> 2;
 

	
 
	spd += v->progress;
 
	v->progress = (byte)spd;
 
	return (spd >> 8);
 
}
 

	
 
static void TrainEnterStation(Vehicle *v, StationID station)
 
{
 
	v->last_station_visited = station;
 

	
 
	/* check if a train ever visited this station before */
 
	Station *st = GetStation(station);
 
	if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
 
		st->had_vehicle_of_type |= HVOT_TRAIN;
 
		SetDParam(0, st->index);
 
		uint32 flags = v->owner == _local_player ?
 
			NEWS_FLAGS(NM_THIN, NF_VIEWPORT | NF_VEHICLE, NT_ARRIVAL_PLAYER, 0) :
 
			NEWS_FLAGS(NM_THIN, NF_VIEWPORT | NF_VEHICLE, NT_ARRIVAL_OTHER,  0);
 
		AddNewsItem(
 
			STR_8801_CITIZENS_CELEBRATE_FIRST,
 
			flags,
 
			v->index,
 
			0
 
		);
 
	}
 

	
 
	v->BeginLoading();
 
	v->current_order.dest = 0;
 
}
 

	
 
static byte AfterSetTrainPos(Vehicle *v, bool new_tile)
 
{
 
	byte old_z = v->z_pos;
 
	v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
 

	
 
	if (new_tile) {
 
		ClrBit(v->u.rail.flags, VRF_GOINGUP);
 
		ClrBit(v->u.rail.flags, VRF_GOINGDOWN);
 

	
 
		if (v->u.rail.track == TRACK_BIT_X || v->u.rail.track == TRACK_BIT_Y) {
 
			/* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped.
 
			 * To check whether the current tile is sloped, and in which
 
			 * direction it is sloped, we get the 'z' at the center of
 
			 * the tile (middle_z) and the edge of the tile (old_z),
 
			 * which we then can compare. */
 
			static const int HALF_TILE_SIZE = TILE_SIZE / 2;
 
			static const int INV_TILE_SIZE_MASK = ~(TILE_SIZE - 1);
 

	
 
			byte middle_z = GetSlopeZ((v->x_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE, (v->y_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE);
 

	
 
			/* For some reason tunnel tiles are always given as sloped :(
 
			 * But they are not sloped... */
 
			if (middle_z != v->z_pos && !IsTunnelTile(TileVirtXY(v->x_pos, v->y_pos))) {
 
				SetBit(v->u.rail.flags, (middle_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN);
 
			}
 
		}
 
	}
 

	
 
	VehiclePositionChanged(v);
 
	EndVehicleMove(v);
 
	return old_z;
 
}
 

	
 
static const Direction _new_vehicle_direction_table[11] = {
 
	DIR_N , DIR_NW, DIR_W , INVALID_DIR,
 
	DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
 
	DIR_E , DIR_SE, DIR_S
 
};
 

	
 
static Direction GetNewVehicleDirectionByTile(TileIndex new_tile, TileIndex old_tile)
 
{
 
	uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
 
							TileX(new_tile) - TileX(old_tile) + 1;
 
	assert(offs < 11);
 
	return _new_vehicle_direction_table[offs];
 
}
 

	
 
static Direction GetNewVehicleDirection(const Vehicle *v, int x, int y)
 
{
 
	uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
 
	assert(offs < 11);
 
	return _new_vehicle_direction_table[offs];
 
}
 

	
 
static int GetDirectionToVehicle(const Vehicle *v, int x, int y)
 
{
 
	byte offs;
 

	
 
	x -= v->x_pos;
 
	if (x >= 0) {
 
		offs = (x > 2) ? 0 : 1;
 
	} else {
 
		offs = (x < -2) ? 2 : 1;
 
	}
 

	
 
	y -= v->y_pos;
 
	if (y >= 0) {
 
		offs += ((y > 2) ? 0 : 1) * 4;
 
	} else {
 
		offs += ((y < -2) ? 2 : 1) * 4;
 
	}
 

	
 
	assert(offs < 11);
 
	return _new_vehicle_direction_table[offs];
 
}
 

	
 
/* Check if the vehicle is compatible with the specified tile */
 
static bool CheckCompatibleRail(const Vehicle *v, TileIndex tile)
 
{
 
	return
 
		IsTileOwner(tile, v->owner) && (
 
			!IsFrontEngine(v) ||
 
			HasBit(v->u.rail.compatible_railtypes, GetRailType(tile))
 
		);
 
}
 

	
 
struct RailtypeSlowdownParams {
 
	byte small_turn, large_turn;
 
	byte z_up; // fraction to remove when moving up
 
	byte z_down; // fraction to remove when moving down
 
};
 

	
 
static const RailtypeSlowdownParams _railtype_slowdown[] = {
 
	// normal accel
 
	{256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
 
	{256 / 4, 256 / 2, 256 / 4, 2}, ///< electrified
 
	{256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
 
	{0,       256 / 2, 256 / 4, 2}, ///< maglev
 
};
 

	
 
/** Modify the speed of the vehicle due to a turn */
 
static void AffectSpeedByDirChange(Vehicle* v, Direction new_dir)
 
{
 
	if (_patches.realistic_acceleration) return;
 

	
 
	DirDiff diff = DirDifference(v->direction, new_dir);
 
	if (diff == DIRDIFF_SAME) return;
 

	
 
	const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->u.rail.railtype];
 
	v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
 
}
 

	
 
/** Modify the speed of the vehicle due to a change in altitude */
 
static void AffectSpeedByZChange(Vehicle *v, byte old_z)
 
{
 
	if (old_z == v->z_pos || _patches.realistic_acceleration) return;
 

	
 
	const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->u.rail.railtype];
 

	
 
	if (old_z < v->z_pos) {
 
		v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
 
	} else {
 
		uint16 spd = v->cur_speed + rsp->z_down;
 
		if (spd <= v->max_speed) v->cur_speed = spd;
 
	}
 
}
 

	
 
static const DiagDirection _otherside_signal_directions[] = {
 
	DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, INVALID_DIAGDIR, INVALID_DIAGDIR,
 
	DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE
 
};
 

	
 
static void TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
 
{
 
	if (IsTileType(tile, MP_RAILWAY) &&
 
			GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
 
		uint i = FindFirstBit2x64(GetTrackBits(tile) * 0x101 & _reachable_tracks[dir]);
 
		UpdateSignalsOnSegment(tile, _otherside_signal_directions[i]);
 
	}
 
}
 

	
 

	
 
static void SetVehicleCrashed(Vehicle *v)
 
{
 
	if (v->u.rail.crash_anim_pos != 0) return;
 

	
 
	v->u.rail.crash_anim_pos++;
 

	
 
	Vehicle *u = v;
 
	BEGIN_ENUM_WAGONS(v)
 
		v->vehstatus |= VS_CRASHED;
 
	END_ENUM_WAGONS(v)
 

	
 
	InvalidateWindowWidget(WC_VEHICLE_VIEW, u->index, STATUS_BAR);
 
}
 

	
 
static uint CountPassengersInTrain(const Vehicle* v)
 
{
 
	uint num = 0;
 
	BEGIN_ENUM_WAGONS(v)
 
		if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) num += v->cargo.Count();
 
	END_ENUM_WAGONS(v)
 
	return num;
 
}
 

	
 
struct TrainCollideChecker {
 
	Vehicle *v;
 
	const Vehicle *v_skip;
 
	uint num;
 
};
 

	
 
static void *FindTrainCollideEnum(Vehicle *v, void *data)
 
{
 
	TrainCollideChecker* tcc = (TrainCollideChecker*)data;
 

	
 
	if (v != tcc->v &&
 
			v != tcc->v_skip &&
 
			v->type == VEH_TRAIN &&
 
			v->u.rail.track != TRACK_BIT_DEPOT &&
 
			abs(v->z_pos - tcc->v->z_pos) < 6 &&
 
			abs(v->x_pos - tcc->v->x_pos) < 6 &&
 
			abs(v->y_pos - tcc->v->y_pos) < 6 ) {
 

	
 
		Vehicle *coll = v->First();
 

	
 
		/* it can't collide with its own wagons */
 
		if (tcc->v == coll ||
 
			(tcc->v->u.rail.track == TRACK_BIT_WORMHOLE && (tcc->v->direction & 2) != (v->direction & 2)))
 
			return NULL;
 

	
 
		/* two drivers + passengers killed in train tcc->v (if it was not crashed already) */
 
		if (!(tcc->v->vehstatus & VS_CRASHED)) {
 
			tcc->num += 2 + CountPassengersInTrain(tcc->v);
 
			SetVehicleCrashed(tcc->v);
 
		}
 

	
 
		if (!(coll->vehstatus & VS_CRASHED)) {
 
			/* two drivers + passengers killed in train coll (if it was not crashed already) */
 
			tcc->num += 2 + CountPassengersInTrain(coll);
 
			SetVehicleCrashed(coll);
 
		}
 
	}
 

	
 
	return NULL;
 
}
 

	
 
/**
 
 * Checks whether the specified train has a collision with another vehicle. If
 
 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
 
 * Reports the incident in a flashy news item, modifies station ratings and
 
 * plays a sound.
 
 */
 
static void CheckTrainCollision(Vehicle *v)
 
{
 
	/* can't collide in depot */
 
	if (v->u.rail.track == TRACK_BIT_DEPOT) return;
 

	
 
	assert(v->u.rail.track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
 

	
 
	TrainCollideChecker tcc;
 
	tcc.v = v;
 
	tcc.v_skip = v->Next();
 
	tcc.num = 0;
 

	
 
	/* find colliding vehicles */
 
	if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
 
		VehicleFromPos(v->tile, &tcc, FindTrainCollideEnum);
 
		if (IsBridgeTile(v->tile)) {
 
			VehicleFromPos(GetOtherBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
 
		} else {
 
			VehicleFromPos(GetOtherTunnelEnd(v->tile), &tcc, FindTrainCollideEnum);
 
		}
 
	} else {
 
		VehicleFromPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
 
	}
 

	
 
	/* any dead -> no crash */
 
	if (tcc.num == 0) return;
 

	
 
	SetDParam(0, tcc.num);
 
	AddNewsItem(STR_8868_TRAIN_CRASH_DIE_IN_FIREBALL,
 
		NEWS_FLAGS(NM_THIN, NF_VIEWPORT | NF_VEHICLE, NT_ACCIDENT, 0),
 
		v->index,
 
		0
 
	);
 

	
 
	ModifyStationRatingAround(v->tile, v->owner, -160, 30);
 
	SndPlayVehicleFx(SND_13_BIG_CRASH, v);
 
}
 

	
 
static void *CheckVehicleAtSignal(Vehicle *v, void *data)
 
{
 
	Direction dir = *(Direction*)data;
 

	
 
	if (v->type == VEH_TRAIN && IsFrontEngine(v)) {
 
		DirDiff diff = ChangeDirDiff(DirDifference(v->direction, dir), DIRDIFF_90RIGHT);
 

	
 
		if (diff == DIRDIFF_90RIGHT || (v->cur_speed <= 5 && diff <= DIRDIFF_REVERSE)) return v;
 
	}
 
	return NULL;
 
}
 

	
 
static void TrainController(Vehicle *v, bool update_image)
 
{
 
	Vehicle *prev;
 

	
 
	/* For every vehicle after and including the given vehicle */
 
	for (prev = v->Previous(); v != NULL; prev = v, v = v->Next()) {
 
		DiagDirection enterdir = DIAGDIR_BEGIN;
 
		bool update_signals = false;
 
		BeginVehicleMove(v);
 

	
 
		GetNewVehiclePosResult gp = GetNewVehiclePos(v);
 
		if (v->u.rail.track != TRACK_BIT_WORMHOLE) {
 
			/* Not inside tunnel */
 
			if (gp.old_tile == gp.new_tile) {
 
				/* Staying in the old tile */
 
				if (v->u.rail.track == TRACK_BIT_DEPOT) {
 
					/* Inside depot */
 
					gp.x = v->x_pos;
 
					gp.y = v->y_pos;
 
				} else {
 
					/* Not inside depot */
 

	
 
					if (IsFrontEngine(v) && !TrainCheckIfLineEnds(v)) return;
 

	
 
					uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
 
					if (HasBit(r, VETS_CANNOT_ENTER)) {
 
						goto invalid_rail;
 
					}
 
					if (HasBit(r, VETS_ENTERED_STATION)) {
 
						TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
 
						return;
 
					}
 

	
 
					if (v->current_order.type == OT_LEAVESTATION) {
 
						v->current_order.Free();
 
						InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR);
 
					}
 
				}
 
			} else {
 
				/* A new tile is about to be entered. */
 

	
 
				/* Determine what direction we're entering the new tile from */
 
				Direction dir = GetNewVehicleDirectionByTile(gp.new_tile, gp.old_tile);
 
				enterdir = DirToDiagDir(dir);
 
				assert(IsValidDiagDirection(enterdir));
 

	
 
				/* Get the status of the tracks in the new tile and mask
 
				 * away the bits that aren't reachable. */
 
				uint32 ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0) & _reachable_tracks[enterdir];
 

	
 
				/* Combine the from & to directions.
 
				 * Now, the lower byte contains the track status, and the byte at bit 16 contains
 
				 * the signal status. */
 
				uint32 tracks = ts | (ts >> 8);
 
				TrackBits bits = (TrackBits)(tracks & TRACK_BIT_MASK);
 
				if ((_patches.new_pathfinding_all || _patches.yapf.rail_use_yapf) && _patches.forbid_90_deg && prev == NULL) {
 
					/* We allow wagons to make 90 deg turns, because forbid_90_deg
 
					 * can be switched on halfway a turn */
 
					bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track));
 
				}
 

	
 
				if (bits == TRACK_BIT_NONE) goto invalid_rail;
 

	
 
				/* Check if the new tile contrains tracks that are compatible
 
				 * with the current train, if not, bail out. */
 
				if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
 

	
 
				TrackBits chosen_track;
 
				if (prev == NULL) {
 
					/* Currently the locomotive is active. Determine which one of the
 
					 * available tracks to choose */
 
					chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits));
 
					assert(chosen_track & tracks);
 

	
 
					/* Check if it's a red signal and that force proceed is not clicked. */
 
					if ((tracks >> 16) & chosen_track && v->u.rail.force_proceed == 0) {
 
						/* In front of a red signal
 
						 * find the first set bit in ts. need to do it in 2 steps, since
 
						 * FIND_FIRST_BIT only handles 6 bits at a time. */
 
						Trackdir i = FindFirstTrackdir((TrackdirBits)(uint16)ts);
 

	
 
						if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
 
							v->cur_speed = 0;
 
							v->subspeed = 0;
 
							v->progress = 255 - 100;
 
							if (++v->load_unload_time_rem < _patches.wait_oneway_signal * 20) return;
 
						} else if (HasSignalOnTrackdir(gp.new_tile, i)) {
 
							v->cur_speed = 0;
 
							v->subspeed = 0;
 
							v->progress = 255 - 10;
 
							if (++v->load_unload_time_rem < _patches.wait_twoway_signal * 73) {
 
								TileIndex o_tile = gp.new_tile + TileOffsByDiagDir(enterdir);
 
								Direction rdir = ReverseDir(dir);
 

	
 
								/* check if a train is waiting on the other side */
 
								if (VehicleFromPos(o_tile, &rdir, &CheckVehicleAtSignal) == NULL) return;
 
							}
 
						}
 
						goto reverse_train_direction;
 
					}
 
				} else {
 
					static const TrackBits _matching_tracks[8] = {
 
							TRACK_BIT_LEFT  | TRACK_BIT_RIGHT, TRACK_BIT_X,
 
							TRACK_BIT_UPPER | TRACK_BIT_LOWER, TRACK_BIT_Y,
 
							TRACK_BIT_LEFT  | TRACK_BIT_RIGHT, TRACK_BIT_X,
 
							TRACK_BIT_UPPER | TRACK_BIT_LOWER, TRACK_BIT_Y
 
					};
 

	
 
					/* The wagon is active, simply follow the prev vehicle. */
 
					chosen_track = (TrackBits)(byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits);
 
				}
 

	
 
				/* Make sure chosen track is a valid track */
 
				assert(
 
						chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
 
						chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
 
						chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
 

	
 
				/* Update XY to reflect the entrance to the new tile, and select the direction to use */
 
				const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
 
				gp.x = (gp.x & ~0xF) | b[0];
 
				gp.y = (gp.y & ~0xF) | b[1];
 
				Direction chosen_dir = (Direction)b[2];
 

	
 
				/* Call the landscape function and tell it that the vehicle entered the tile */
 
				uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
 
				if (HasBit(r, VETS_CANNOT_ENTER)) {
 
					goto invalid_rail;
 
				}
 

	
 
				if (IsLevelCrossingTile(v->tile) && v->Next() == NULL) {
 
					UnbarCrossing(v->tile);
 
					MarkTileDirtyByTile(v->tile);
 
				}
 

	
 
				if (IsFrontEngine(v)) v->load_unload_time_rem = 0;
 

	
 
				if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
 
					v->tile = gp.new_tile;
 

	
 
					if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
 
						TrainPowerChanged(v->First());
 
					}
 

	
 
					v->u.rail.track = chosen_track;
 
					assert(v->u.rail.track);
 
				}
 

	
 
				/* We need to update signal status, but after the vehicle position hash
 
				 * has been updated by AfterSetTrainPos() */
 
				update_signals = true;
 

	
 
				if (prev == NULL) AffectSpeedByDirChange(v, chosen_dir);
 

	
 
				v->direction = chosen_dir;
 
			}
 
		} else {
 
			/* In tunnel or on a bridge */
 
			/* In a tunnel or on a bridge
 
			 * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
 
			 * - for bridges, only the middle part - without the bridge heads */
 
			if (!(v->vehstatus & VS_HIDDEN)) {
 
				v->cur_speed =
 
					min(v->cur_speed, GetBridge(GetBridgeType(v->tile))->speed);
 
			}
 

	
 
			if (!(IsTunnelTile(gp.new_tile) || IsBridgeTile(gp.new_tile)) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
 
				v->x_pos = gp.x;
 
				v->y_pos = gp.y;
 
				VehiclePositionChanged(v);
 
				if (!(v->vehstatus & VS_HIDDEN)) EndVehicleMove(v);
 
				continue;
 
			}
 
		}
 

	
 
		/* update image of train, as well as delta XY */
 
		Direction newdir = GetNewVehicleDirection(v, gp.x, gp.y);
 
		v->UpdateDeltaXY(newdir);
 
		if (update_image) v->cur_image = v->GetImage(newdir);
 
		v->UpdateDeltaXY(v->direction);
 
		if (update_image) v->cur_image = v->GetImage(v->direction);
 

	
 
		v->x_pos = gp.x;
 
		v->y_pos = gp.y;
 

	
 
		/* update the Z position of the vehicle */
 
		byte old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile));
 

	
 
		if (prev == NULL) {
 
			/* This is the first vehicle in the train */
 
			AffectSpeedByZChange(v, old_z);
 
		}
 

	
 
		if (update_signals) {
 
			if (IsFrontEngine(v)) TrainMovedChangeSignals(gp.new_tile, enterdir);
 

	
 
			/* Signals can only change when the first
 
			 * (above) or the last vehicle moves. */
 
			if (v->Next() == NULL) TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
 
		}
 
	}
 
	return;
 

	
 
invalid_rail:
 
	/* We've reached end of line?? */
 
	if (prev != NULL) error("!Disconnecting train");
 

	
 
reverse_train_direction:
 
	v->load_unload_time_rem = 0;
 
	v->cur_speed = 0;
 
	v->subspeed = 0;
 
	ReverseTrainDirection(v);
 
}
 

	
 
/**
 
 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
 
 * train, then goes to the last wagon and deletes that. Each call to this function
 
 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
 
 * or inside a tunnel/bridge, recalculate the signals as they might need updating
 
 * @param v the Vehicle of which last wagon is to be removed
 
 */
 
static void DeleteLastWagon(Vehicle *v)
 
{
 
	/* Go to the last wagon and delete the link pointing there
 
	 * *u is then the one-before-last wagon, and *v the last
 
	 * one which will physicially be removed */
 
	Vehicle *u = v;
 
	for (; v->Next() != NULL; v = v->Next()) u = v;
 
	u->SetNext(NULL);
 

	
 
	InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
 
	DeleteWindowById(WC_VEHICLE_VIEW, v->index);
 
	RebuildVehicleLists();
 
	InvalidateWindow(WC_COMPANY, v->owner);
 

	
 
	BeginVehicleMove(v);
 
	EndVehicleMove(v);
 

	
 
	delete v;
 

	
 
	if (v->u.rail.track != TRACK_BIT_DEPOT && v->u.rail.track != TRACK_BIT_WORMHOLE)
 
		SetSignalsOnBothDir(v->tile, FIND_FIRST_BIT(v->u.rail.track));
 

	
 
	/* Check if the wagon was on a road/rail-crossing and disable it if no
 
	 * others are on it */
 
	DisableTrainCrossing(v->tile);
 

	
 
	if (v->u.rail.track == TRACK_BIT_WORMHOLE) { // inside a tunnel / bridge
 
		TileIndex endtile = IsTunnel(v->tile) ? GetOtherTunnelEnd(v->tile) : GetOtherBridgeEnd(v->tile);
 

	
 
		if (GetVehicleTunnelBridge(v->tile, endtile) != NULL) return; // tunnel / bridge is busy
 

	
 
		DiagDirection dir = GetTunnelBridgeDirection(v->tile);
 

	
 
		/* v->direction is "random", so it cannot be used to determine the direction of the track */
 
		UpdateSignalsOnSegment(v->tile, dir);
 
		UpdateSignalsOnSegment(endtile, ReverseDiagDir(dir));
 
	}
 
}
 

	
 
static void ChangeTrainDirRandomly(Vehicle *v)
 
{
 
	static const DirDiff delta[] = {
 
		DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
 
	};
 

	
 
	do {
 
		/* We don't need to twist around vehicles if they're not visible */
 
		if (!(v->vehstatus & VS_HIDDEN)) {
 
			v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
 
			BeginVehicleMove(v);
 
			v->UpdateDeltaXY(v->direction);
 
			v->cur_image = v->GetImage(v->direction);
 
			/* Refrain from updating the z position of the vehicle when on
 
			   a bridge, because AfterSetTrainPos will put the vehicle under
 
			   the bridge in that case */
 
			if (v->u.rail.track != TRACK_BIT_WORMHOLE) AfterSetTrainPos(v, false);
 
		}
 
	} while ((v = v->Next()) != NULL);
 
}
 

	
 
static void HandleCrashedTrain(Vehicle *v)
 
{
 
	int state = ++v->u.rail.crash_anim_pos;
 

	
 
	if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
 
		CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
 
	}
 

	
 
	uint32 r;
 
	if (state <= 200 && Chance16R(1, 7, r)) {
 
		int index = (r * 10 >> 16);
 

	
 
		Vehicle *u = v;
 
		do {
 
			if (--index < 0) {
 
				r = Random();
 

	
 
				CreateEffectVehicleRel(u,
 
					GB(r,  8, 3) + 2,
 
					GB(r, 16, 3) + 2,
 
					GB(r,  0, 3) + 5,
 
					EV_EXPLOSION_SMALL);
 
				break;
 
			}
 
		} while ((u = u->Next()) != NULL);
 
	}
 

	
 
	if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
 

	
 
	if (state >= 4440 && !(v->tick_counter&0x1F)) {
 
		DeleteLastWagon(v);
 
		InvalidateWindow(WC_REPLACE_VEHICLE, (v->group_id << 16) | VEH_TRAIN);
 
	}
 
}
 

	
 
static void HandleBrokenTrain(Vehicle *v)
 
{
 
	if (v->breakdown_ctr != 1) {
 
		v->breakdown_ctr = 1;
 
		v->cur_speed = 0;
 

	
 
		if (v->breakdowns_since_last_service != 255)
 
			v->breakdowns_since_last_service++;
 

	
 
		InvalidateWindow(WC_VEHICLE_VIEW, v->index);
 
		InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
 

	
 
		if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
 
			SndPlayVehicleFx((_opt.landscape != LT_TOYLAND) ?
 
				SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
 
		}
 

	
 
		if (!(v->vehstatus & VS_HIDDEN)) {
 
			Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
 
			if (u != NULL) u->u.special.animation_state = v->breakdown_delay * 2;
 
		}
 
	}
 

	
 
	if (!(v->tick_counter & 3)) {
 
		if (!--v->breakdown_delay) {
 
			v->breakdown_ctr = 0;
 
			InvalidateWindow(WC_VEHICLE_VIEW, v->index);
 
		}
 
	}
 
}
 

	
 
static const byte _breakdown_speeds[16] = {
 
	225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
 
};
 

	
 
static bool TrainCheckIfLineEnds(Vehicle *v)
 
{
 
	int t = v->breakdown_ctr;
 
	if (t > 1) {
 
		v->vehstatus |= VS_TRAIN_SLOWING;
 

	
 
		uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
 
		if (break_speed < v->cur_speed) v->cur_speed = break_speed;
 
	} else {
 
		v->vehstatus &= ~VS_TRAIN_SLOWING;
 
	}
 

	
 
	if (v->u.rail.track == TRACK_BIT_WORMHOLE) return true; // exit if inside a tunnel
 
	if (v->u.rail.track == TRACK_BIT_DEPOT) return true; // exit if inside a depot
 

	
 
	TileIndex tile = v->tile;
 

	
 
	if (IsTileType(tile, MP_TUNNELBRIDGE)) {
 
		DiagDirection dir = GetTunnelBridgeDirection(tile);
 
		if (DiagDirToDir(dir) == v->direction) return true;
 
	}
 

	
0 comments (0 inline, 0 general)