src/vehicle.cpp
branchNewGRF_ports
changeset 6719 4cc327ad39d5
parent 6676 30aea9ac89bc
child 6720 35756db7e577
--- a/src/vehicle.cpp	Tue Mar 27 23:27:27 2007 +0000
+++ b/src/vehicle.cpp	Sat Jun 02 19:59:29 2007 +0000
@@ -1,5 +1,7 @@
 /* $Id$ */
 
+/** @file vehicle.cpp */
+
 #include "stdafx.h"
 #include "openttd.h"
 #include "road_map.h"
@@ -9,6 +11,7 @@
 #include "table/sprites.h"
 #include "table/strings.h"
 #include "functions.h"
+#include "landscape.h"
 #include "map.h"
 #include "tile.h"
 #include "vehicle.h"
@@ -37,6 +40,8 @@
 #include "newgrf_engine.h"
 #include "newgrf_sound.h"
 #include "helpers.hpp"
+#include "group.h"
+#include "economy.h"
 
 #define INVALID_COORD (-0x8000)
 #define GEN_HASH(x, y) ((GB((y), 6, 6) << 6) + GB((x), 7, 6))
@@ -86,7 +91,7 @@
 	 * TODO - This is just a temporary stage, this will be removed. */
 	for (v = GetVehicle(start_item); v != NULL; v = (v->index + 1U < GetVehiclePoolSize()) ? GetVehicle(v->index + 1) : NULL) {
 		v->index = start_item++;
-		v->type  = VEH_INVALID;
+		v = new (v) InvalidVehicle();
 	}
 }
 
@@ -104,10 +109,10 @@
 bool VehicleNeedsService(const Vehicle *v)
 {
 	if (v->vehstatus & VS_CRASHED)
-		return false; /* Crashed vehicles don't need service anymore */
+		return false; // Crashed vehicles don't need service anymore
 
 	if (_patches.no_servicing_if_no_breakdowns && _opt.diff.vehicle_breakdowns == 0) {
-		return EngineHasReplacementForPlayer(GetPlayer(v->owner), v->engine_type);  /* Vehicles set for autoreplacing needs to go to a depot even if breakdowns are turned off */
+		return EngineHasReplacementForPlayer(GetPlayer(v->owner), v->engine_type, v->group_id);  /* Vehicles set for autoreplacing needs to go to a depot even if breakdowns are turned off */
 	}
 
 	return _patches.servint_ispercent ?
@@ -185,9 +190,9 @@
 	}
 	FOR_ALL_VEHICLES(veh) {
 		if (without_crashed && (veh->vehstatus & VS_CRASHED) != 0) continue;
-		if ((veh->type == VEH_TRAIN || veh->type == VEH_ROAD) && (z==0xFF || veh->z_pos == z)) {
-			if ((veh->x_pos>>4) >= x1 && (veh->x_pos>>4) <= x2 &&
-					(veh->y_pos>>4) >= y1 && (veh->y_pos>>4) <= y2) {
+		if ((veh->type == VEH_TRAIN || veh->type == VEH_ROAD) && (z == 0xFF || veh->z_pos == z)) {
+			if ((veh->x_pos >> 4) >= x1 && (veh->x_pos >> 4) <= x2 &&
+					(veh->y_pos >> 4) >= y1 && (veh->y_pos >> 4) <= y2) {
 				return veh;
 			}
 		}
@@ -215,12 +220,14 @@
 	v->bottom_coord = pt.y + spr->height + 2;
 }
 
-// Called after load to update coordinates
+/** Called after load to update coordinates */
 void AfterLoadVehicles()
 {
 	Vehicle *v;
 
 	FOR_ALL_VEHICLES(v) {
+		v->UpdateDeltaXY(v->direction);
+
 		v->first = NULL;
 		if (v->type == VEH_TRAIN) v->u.rail.first_engine = INVALID_ENGINE;
 	}
@@ -232,8 +239,13 @@
 
 	FOR_ALL_VEHICLES(v) {
 		switch (v->type) {
+			case VEH_ROAD:
+				v->cur_image = GetRoadVehImage(v, v->direction);
+				v->u.road.roadtype = HASBIT(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
+				v->u.road.compatible_roadtypes = RoadTypeToRoadTypes(v->u.road.roadtype);
+				break;
+
 			case VEH_TRAIN: v->cur_image = GetTrainImage(v, v->direction); break;
-			case VEH_ROAD: v->cur_image = GetRoadVehImage(v, v->direction); break;
 			case VEH_SHIP: v->cur_image = GetShipImage(v, v->direction); break;
 			case VEH_AIRCRAFT:
 				if (IsNormalAircraft(v)) {
@@ -248,6 +260,8 @@
 						Vehicle *rotor = shadow->next;
 						rotor->cur_image = GetRotorImage(v);
 					}
+
+					UpdateAircraftCache(v);
 				}
 				break;
 			default: break;
@@ -266,7 +280,7 @@
 
 	assert(v->orders == NULL);
 
-	v->type = VEH_INVALID;
+	v = new (v) InvalidVehicle();
 	v->left_coord = INVALID_COORD;
 	v->first = NULL;
 	v->next = NULL;
@@ -276,6 +290,8 @@
 	v->prev_shared = NULL;
 	v->depot_list  = NULL;
 	v->random_bits = 0;
+	v->group_id = DEFAULT_GROUP;
+
 	return v;
 }
 
@@ -311,7 +327,7 @@
 	return NULL;
 }
 
-/*
+/**
  * finds a free vehicle in the memory or allocates a new one
  * returns a pointer to the first free vehicle or NULL if all vehicles are in use
  * *skip_vehicles is an offset to where in the array we should begin looking
@@ -327,7 +343,7 @@
 	const int offset = (1 << Vehicle_POOL_BLOCK_SIZE_BITS) * BLOCKS_FOR_SPECIAL_VEHICLES;
 
 	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
+	 * @todo - This is just a temporary stage, this will be removed. */
 	if (*skip_vehicles < (_Vehicle_pool.total_items - offset)) { // make sure the offset in the array is not larger than the array itself
 		for (v = GetVehicle(offset + *skip_vehicles); v != NULL; v = (v->index + 1U < GetVehiclePoolSize()) ? GetVehicle(v->index + 1) : NULL) {
 			(*skip_vehicles)++;
@@ -381,7 +397,7 @@
 {
 	Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, 0);
 
-	// The hash area to scan
+	/* The hash area to scan */
 	const int xl = GB(pt.x - 174, 7, 6);
 	const int xu = GB(pt.x + 104, 7, 6);
 	const int yl = GB(pt.y - 294, 6, 6) << 6;
@@ -416,7 +432,7 @@
 	int old_x = v->left_coord;
 	int old_y = v->top_coord;
 
-	new_hash = (x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(x,y)];
+	new_hash = (x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(x, y)];
 	old_hash = (old_x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(old_x, old_y)];
 
 	if (old_hash == new_hash) return;
@@ -498,7 +514,7 @@
 
 	u = GetFirstVehicleInChain(v);
 
-	// Check to see if this is the first
+	/* Check to see if this is the first */
 	if (v == u) return NULL;
 
 	for (; u->next != v; u = u->next) assert(u->next != NULL);
@@ -565,9 +581,16 @@
 
 void DestroyVehicle(Vehicle *v)
 {
+	if (IsValidStationID(v->last_station_visited)) {
+		GetStation(v->last_station_visited)->loading_vehicles.remove(v);
+	}
+
 	if (IsEngineCountable(v)) {
 		GetPlayer(v->owner)->num_engines[v->engine_type]--;
 		if (v->owner == _local_player) InvalidateAutoreplaceWindow(v->engine_type);
+
+		if (IsValidGroupID(v->group_id)) GetGroup(v->group_id)->num_engines[v->engine_type]--;
+		if (v->IsPrimaryVehicle()) DecreaseGroupNumVehicle(v->group_id);
 	}
 
 	DeleteVehicleNews(v->index, INVALID_STRING_ID);
@@ -586,14 +609,23 @@
 	/* Now remove any artic part. This will trigger an other
 	 *  destroy vehicle, which on his turn can remove any
 	 *  other artic parts. */
-	if (EngineHasArticPart(v)) DeleteVehicle(v->next);
+	if (v->type == VEH_TRAIN && EngineHasArticPart(v)) DeleteVehicle(v->next);
 }
 
+/**
+ * Deletes all vehicles in a chain.
+ * @param v The first vehicle in the chain.
+ *
+ * @warning This function is not valid for any vehicle containing articulated
+ * parts.
+ */
 void DeleteVehicleChain(Vehicle *v)
 {
+	assert(v->type != VEH_TRAIN);
+
 	do {
 		Vehicle *u = v;
-		v = GetNextVehicle(v);
+		v = v->next;
 		DeleteVehicle(u);
 	} while (v != NULL);
 }
@@ -606,7 +638,7 @@
 static void EffectVehicle_Tick(Vehicle *v);
 void DisasterVehicle_Tick(Vehicle *v);
 
-// head of the linked list to tell what vehicles that visited a depot in a tick
+/** head of the linked list to tell what vehicles that visited a depot in a tick */
 static Vehicle* _first_veh_in_depot_list;
 
 /** Adds a vehicle to the list of vehicles, that visited a depot this tick
@@ -614,14 +646,14 @@
  */
 void VehicleEnteredDepotThisTick(Vehicle *v)
 {
-	// we need to set v->leave_depot_instantly as we have no control of it's contents at this time
+	/* we need to set v->leave_depot_instantly as we have no control of it's contents at this time */
 	if (HASBIT(v->current_order.flags, OFB_HALT_IN_DEPOT) && !HASBIT(v->current_order.flags, OFB_PART_OF_ORDERS) && v->current_order.type == OT_GOTO_DEPOT) {
-		// we keep the vehicle in the depot since the user ordered it to stay
+		/* we keep the vehicle in the depot since the user ordered it to stay */
 		v->leave_depot_instantly = false;
 	} else {
-		// the vehicle do not plan on stopping in the depot, so we stop it to ensure that it will not reserve the path
-		// out of the depot before we might autoreplace it to a different engine. The new engine would not own the reserved path
-		// we store that we stopped the vehicle, so autoreplace can start it again
+		/* the vehicle do not plan on stopping in the depot, so we stop it to ensure that it will not reserve the path
+		 * out of the depot before we might autoreplace it to a different engine. The new engine would not own the reserved path
+		 * we store that we stopped the vehicle, so autoreplace can start it again */
 		v->vehstatus |= VS_STOPPED;
 		v->leave_depot_instantly = true;
 	}
@@ -647,11 +679,9 @@
 
 void CallVehicleTicks()
 {
-	Vehicle *v;
-
 #ifdef ENABLE_NETWORK
-	// hotfix for desync problem:
-	//  for MP games invalidate the YAPF cache every tick to keep it exactly the same on the server and all clients
+	/* hotfix for desync problem:
+	 *  for MP games invalidate the YAPF cache every tick to keep it exactly the same on the server and all clients */
 	if (_networking) {
 		YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
 	}
@@ -659,10 +689,16 @@
 
 	_first_veh_in_depot_list = NULL; // now we are sure it's initialized at the start of each tick
 
+	Station *st;
+	FOR_ALL_STATIONS(st) LoadUnloadStation(st);
+
+	Vehicle *v;
 	FOR_ALL_VEHICLES(v) {
 		_vehicle_tick_procs[v->type](v);
 
 		switch (v->type) {
+			default: break;
+
 			case VEH_TRAIN:
 			case VEH_ROAD:
 			case VEH_AIRCRAFT:
@@ -679,7 +715,7 @@
 		}
 	}
 
-	// now we handle all the vehicles that entered a depot this tick
+	/* now we handle all the vehicles that entered a depot this tick */
 	v = _first_veh_in_depot_list;
 	while (v != NULL) {
 		Vehicle *w = v->depot_list;
@@ -689,70 +725,6 @@
 	}
 }
 
-static bool CanFillVehicle_FullLoadAny(Vehicle *v)
-{
-	uint32 full = 0, not_full = 0;
-	bool keep_loading = false;
-	const GoodsEntry *ge = GetStation(v->last_station_visited)->goods;
-
-	//special handling of aircraft
-
-	//if the aircraft carries passengers and is NOT full, then
-	//continue loading, no matter how much mail is in
-	if (v->type == VEH_AIRCRAFT &&
-			IsCargoInClass(v->cargo_type, CC_PASSENGERS) &&
-			v->cargo_cap != v->cargo_count) {
-		return true;
-	}
-
-	// patch should return "true" to continue loading, i.e. when there is no cargo type that is fully loaded.
-	do {
-		//Should never happen, but just in case future additions change this
-		assert(v->cargo_type<32);
-
-		if (v->cargo_cap != 0) {
-			uint32 mask = 1 << v->cargo_type;
-
-			if (v->cargo_cap == v->cargo_count) {
-				full |= mask;
-			} else if (GB(ge[v->cargo_type].waiting_acceptance, 0, 12) > 0 ||
-					(HASBIT(v->vehicle_flags, VF_CARGO_UNLOADING) && (ge[v->cargo_type].waiting_acceptance & 0x8000))) {
-				/* If there is any cargo waiting, or this vehicle is still unloading
-				 * and the station accepts the cargo, don't leave the station. */
-				keep_loading = true;
-			} else {
-				not_full |= mask;
-			}
-		}
-	} while ((v = v->next) != NULL);
-
-	// continue loading if there is a non full cargo type and no cargo type that is full
-	return keep_loading || (not_full && (full & ~not_full) == 0);
-}
-
-bool CanFillVehicle(Vehicle *v)
-{
-	TileIndex tile = v->tile;
-
-	if (IsTileType(tile, MP_STATION) ||
-			(v->type == VEH_SHIP && (
-				IsTileType(TILE_ADDXY(tile,  1,  0), MP_STATION) ||
-				IsTileType(TILE_ADDXY(tile, -1,  0), MP_STATION) ||
-				IsTileType(TILE_ADDXY(tile,  0,  1), MP_STATION) ||
-				IsTileType(TILE_ADDXY(tile,  0, -1), MP_STATION) ||
-				IsTileType(TILE_ADDXY(tile, -2,  0), MP_STATION)
-			))) {
-
-		// If patch is active, use alternative CanFillVehicle-function
-		if (_patches.full_load_any && v->current_order.flags & OF_FULL_LOAD) return CanFillVehicle_FullLoadAny(v);
-
-		do {
-			if (v->cargo_count != v->cargo_cap) return true;
-		} while ((v = v->next) != NULL);
-	}
-	return false;
-}
-
 /** Check if a given engine type can be refitted to a given cargo
  * @param engine_type Engine type to check
  * @param cid_to check refit to this cargo-type
@@ -764,7 +736,7 @@
 }
 
 /** Find the first cargo type that an engine can be refitted to.
- * @param engine Which engine to find cargo for.
+ * @param engine_type Which engine to find cargo for.
  * @return A climate dependent cargo type. CT_INVALID is returned if not refittable.
  */
 CargoID FindFirstRefittableCargo(EngineID engine_type)
@@ -781,7 +753,7 @@
 }
 
 /** Learn the price of refitting a certain engine
-* @param engine Which engine to refit
+* @param engine_type Which engine to refit
 * @return Price for refitting
 */
 int32 GetRefitCost(EngineID engine_type)
@@ -821,13 +793,13 @@
 
 void ViewportAddVehicles(DrawPixelInfo *dpi)
 {
-	// The bounding rectangle
+	/* The bounding rectangle */
 	const int l = dpi->left;
 	const int r = dpi->left + dpi->width;
 	const int t = dpi->top;
 	const int b = dpi->top + dpi->height;
 
-	// The hash area to scan
+	/* The hash area to scan */
 	const int xl = GB(l - 70, 7, 6);
 	const int xu = GB(r,      7, 6);
 	const int yl = GB(t - 70, 6, 6) << 6;
@@ -1429,14 +1401,13 @@
 
 	v = ForceAllocateSpecialVehicle();
 	if (v != NULL) {
-		v->type = VEH_SPECIAL;
+		v = new (v) SpecialVehicle();
 		v->subtype = type;
 		v->x_pos = x;
 		v->y_pos = y;
 		v->z_pos = z;
-		v->z_height = v->sprite_width = v->sprite_height = 1;
-		v->x_offs = v->y_offs = 0;
 		v->tile = 0;
+		v->UpdateDeltaXY(INVALID_DIR);
 		v->vehstatus = VS_UNCLICKABLE;
 
 		_effect_init_procs[type](v);
@@ -1474,8 +1445,8 @@
 			 (uint)(y -= vp->top) >= (uint)vp->height)
 				return NULL;
 
-	x = (x << vp->zoom) + vp->virtual_left;
-	y = (y << vp->zoom) + vp->virtual_top;
+	x = ScaleByZoom(x, vp->zoom) + vp->virtual_left;
+	y = ScaleByZoom(y, vp->zoom) + vp->virtual_top;
 
 	FOR_ALL_VEHICLES(v) {
 		if ((v->vehstatus & (VS_HIDDEN|VS_UNCLICKABLE)) == 0 &&
@@ -1567,7 +1538,7 @@
 {
 	if (v->owner != _local_player) return;
 
-	// Do not show getting-old message if autorenew is active
+	/* Do not show getting-old message if autorenew is active */
 	if (GetPlayer(v->owner)->engine_renew) return;
 
 	SetDParam(0, _vehicle_type_names[v->type]);
@@ -1599,6 +1570,7 @@
 
 /** Starts or stops a lot of vehicles
  * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
+ * @param flags type of operation
  * @param p1 Station/Order/Depot ID (only used for vehicle list windows)
  * @param p2 bitmask
  *   - bit 0-4 Vehicle type
@@ -1614,7 +1586,7 @@
 	int32 return_value = CMD_ERROR;
 	uint i;
 	uint stop_command;
-	byte vehicle_type = GB(p2, 0, 5);
+	VehicleType vehicle_type = (VehicleType)GB(p2, 0, 5);
 	bool start_stop = HASBIT(p2, 5);
 	bool vehicle_list_window = HASBIT(p2, 6);
 
@@ -1665,10 +1637,11 @@
 }
 
 /** Sells all vehicles in a depot
-* @param tile Tile of the depot where the depot is
-* @param p1 Vehicle type
-* @param p2 unused
-*/
+ * @param tile Tile of the depot where the depot is
+ * @param flags type of operation
+ * @param p1 Vehicle type
+ * @param p2 unused
+ */
 int32 CmdDepotSellAllVehicles(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 {
 	Vehicle **engines = NULL;
@@ -1680,7 +1653,7 @@
 
 	int32 cost = 0;
 	uint i, sell_command, total_number_vehicles;
-	byte vehicle_type = GB(p1, 0, 8);
+	VehicleType vehicle_type = (VehicleType)GB(p1, 0, 8);
 
 	switch (vehicle_type) {
 		case VEH_TRAIN:    sell_command = CMD_SELL_RAIL_WAGON; break;
@@ -1717,10 +1690,11 @@
 }
 
 /** Autoreplace all vehicles in the depot
-* @param tile Tile of the depot where the vehicles are
-* @param p1 Type of vehicle
-* @param p2 Unused
-*/
+ * @param tile Tile of the depot where the vehicles are
+ * @param flags type of operation
+ * @param p1 Type of vehicle
+ * @param p2 Unused
+ */
 int32 CmdDepotMassAutoReplace(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 {
 	Vehicle **vl = NULL;
@@ -1728,8 +1702,7 @@
 	uint16 engine_count = 0;
 	uint i, x = 0, y = 0, z = 0;
 	int32 cost = 0;
-	byte vehicle_type = GB(p1, 0, 8);
-
+	VehicleType vehicle_type = (VehicleType)GB(p1, 0, 8);
 
 	if (!IsTileOwner(tile, _current_player)) return CMD_ERROR;
 
@@ -1784,6 +1757,7 @@
 
 /** Clone a vehicle. If it is a train, it will clone all the cars too
  * @param tile tile of the depot where the cloned vehicle is build
+ * @param flags type of operation
  * @param p1 the original vehicle's index
  * @param p2 1 = shared orders, else copied orders
  */
@@ -1791,7 +1765,7 @@
 {
 	Vehicle *v_front, *v;
 	Vehicle *w_front, *w, *w_rear;
-	int cost, total_cost = 0;
+	int32 cost, total_cost = 0;
 	uint32 build_argument = 2;
 
 	if (!IsValidVehicleID(p1)) return CMD_ERROR;
@@ -1814,7 +1788,7 @@
 
 	if (v->type == VEH_TRAIN && (!IsFrontEngine(v) || v->u.rail.crash_anim_pos >= 4400)) return CMD_ERROR;
 
-	// check that we can allocate enough vehicles
+	/* check that we can allocate enough vehicles */
 	if (!(flags & DC_EXEC)) {
 		int veh_counter = 0;
 		do {
@@ -1829,8 +1803,7 @@
 	v = v_front;
 
 	do {
-
-		if (IsMultiheaded(v) && !IsTrainEngine(v)) {
+		if (v->type == VEH_TRAIN && IsMultiheaded(v) && !IsTrainEngine(v)) {
 			/* we build the rear ends of multiheaded trains with the front ones */
 			continue;
 		}
@@ -1845,28 +1818,16 @@
 		if (flags & DC_EXEC) {
 			w = GetVehicle(_new_vehicle_id);
 
-			Vehicle *w2 = w;
-			Vehicle *v2 = v;
-			do {
-				if (v2->cargo_type != w2->cargo_type || v2->cargo_subtype != w2->cargo_subtype) {
-					/* We can't pay for refitting because we can't estimate refitting costs for a vehicle before it's build.
-					 * If we pay for it anyway, the cost and the estimated cost will not be the same and we will have an assert.
-					 * We need to check the whole chain if it is a train because some newgrf articulated engines can refit some units only (and not the front) */
-					DoCommand(0, w->index, v2->cargo_type | (v2->cargo_subtype << 8), flags, GetCmdRefitVeh(v));
-					break; // We learned that the engine in question needed a refit. No need to check anymore
-				}
-			} while (v->type == VEH_TRAIN && (w2 = w2->next) != NULL && (v2 = v2->next) != NULL);
-
 			if (v->type == VEH_TRAIN && HASBIT(v->u.rail.flags, VRF_REVERSE_DIRECTION)) {
 				SETBIT(w->u.rail.flags, VRF_REVERSE_DIRECTION);
 			}
 
 			if (v->type == VEH_TRAIN && !IsFrontEngine(v)) {
-				// this s a train car
-				// add this unit to the end of the train
+				/* this s a train car
+				 * add this unit to the end of the train */
 				DoCommand(0, (w_rear->index << 16) | w->index, 1, flags, CMD_MOVE_RAIL_VEHICLE);
 			} else {
-				// this is a front engine or not a train. It need orders
+				/* this is a front engine or not a train. It need orders */
 				w_front = w;
 				w->service_interval = v->service_interval;
 				DoCommand(0, (v->index << 16) | w->index, p2 & 1 ? CO_SHARE : CO_COPY, flags, CMD_CLONE_ORDER);
@@ -1876,10 +1837,63 @@
 	} while (v->type == VEH_TRAIN && (v = GetNextVehicle(v)) != NULL);
 
 	if (flags & DC_EXEC && v_front->type == VEH_TRAIN) {
-		// for trains this needs to be the front engine due to the callback function
+		/* for trains this needs to be the front engine due to the callback function */
 		_new_vehicle_id = w_front->index;
 	}
 
+	if (flags & DC_EXEC) {
+		/* Cloned vehicles belong to the same group */
+		DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
+	}
+
+
+	/* Take care of refitting. */
+	w = w_front;
+	v = v_front;
+
+	/* Both building and refitting are influenced by newgrf callbacks, which
+	 * makes it impossible to accurately estimate the cloning costs. In
+	 * particular, it is possible for engines of the same type to be built with
+	 * different numbers of articulated parts, so when refitting we have to
+	 * loop over real vehicles first, and then the articulated parts of those
+	 * vehicles in a different loop. */
+	do {
+		do {
+			if (flags & DC_EXEC) {
+				assert(w != NULL);
+
+				if (w->cargo_type != v->cargo_type || w->cargo_subtype != v->cargo_type) {
+					cost = DoCommand(0, w->index, v->cargo_type | (v->cargo_subtype << 8) | 1U << 16 , flags, GetCmdRefitVeh(v));
+					if (!CmdFailed(cost)) total_cost += cost;
+				}
+
+				if (w->type == VEH_TRAIN && EngineHasArticPart(w)) {
+					w = GetNextArticPart(w);
+				} else {
+					break;
+				}
+			} else {
+				CargoID initial_cargo = GetEngineCargoType(v->engine_type);
+
+				if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
+					total_cost += GetRefitCost(v->engine_type);
+				}
+			}
+		} while (v->type == VEH_TRAIN && EngineHasArticPart(v) && (v = GetNextArticPart(v)) != NULL);
+
+		if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = GetNextVehicle(w);
+	} while (v->type == VEH_TRAIN && (v = GetNextVehicle(v)) != NULL);
+
+	/* Since we can't estimate the cost of cloning a vehicle accurately we must
+	 * check whether the player has enough money manually. */
+	if (!CheckPlayerHasMoney(total_cost)) {
+		if (flags & DC_EXEC) {
+			/* The vehicle has already been bought, so now it must be sold again. */
+			DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
+		}
+		return CMD_ERROR;
+	}
+
 	/* Set the expense type last as refitting will make the cost go towards
 	 * running costs... */
 	SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES);
@@ -1897,7 +1911,7 @@
 /** Generates a list of vehicles inside a depot
  * Will enlarge allocated space for the list if they are too small, so it's ok to call with (pointer to NULL array, pointer to uninitised uint16, pointer to 0)
  * If one of the lists is not needed (say wagons when finding ships), all the pointers regarding that list should be set to NULL
- * @param Type type of vehicle
+ * @param type Type of vehicle
  * @param tile The tile the depot is located in
  * @param ***engine_list Pointer to a pointer to an array of vehicles in the depot (old list is freed and a new one is malloced)
  * @param *engine_list_length Allocated size of engine_list. Needs to be set to 0 when engine_list points to a NULL array
@@ -1906,7 +1920,7 @@
  * @param *wagon_list_length Allocated size of wagon_list. Needs to be set to 0 when wagon_list points to a NULL array
  * @param *wagon_count The number of engines stored in the list
  */
-void BuildDepotVehicleList(byte type, TileIndex tile, Vehicle ***engine_list, uint16 *engine_list_length, uint16 *engine_count, Vehicle ***wagon_list, uint16 *wagon_list_length, uint16 *wagon_count)
+void BuildDepotVehicleList(VehicleType type, TileIndex tile, Vehicle ***engine_list, uint16 *engine_list_length, uint16 *engine_count, Vehicle ***wagon_list, uint16 *wagon_list_length, uint16 *wagon_count)
 {
 	Vehicle *v;
 
@@ -1979,26 +1993,26 @@
 * @param length_of_array informs the length allocated for sort_list. This is not the same as the number of vehicles in the list. Needs to be 0 when sort_list is NULL
 * @param type type of vehicle
 * @param owner PlayerID of owner to generate a list for
-* @param index This parameter got different meanings depending on window_type
-			VLW_STATION_LIST:  index of station to generate a list for
-			VLW_SHARED_ORDERS: index of order to generate a list for
-			VLW_STANDARD: not used
-			VLW_DEPOT_LIST: TileIndex of the depot/hangar to make the list for
+* @param index This parameter has different meanings depending on window_type
+    <ul>
+      <li>VLW_STATION_LIST:  index of station to generate a list for</li>
+      <li>VLW_SHARED_ORDERS: index of order to generate a list for<li>
+      <li>VLW_STANDARD: not used<li>
+      <li>VLW_DEPOT_LIST: TileIndex of the depot/hangar to make the list for</li>
+      <li>VLW_GROUP_LIST: index of group to generate a list for</li>
+    </ul>
 * @param window_type tells what kind of window the list is for. Use the VLW flags in vehicle_gui.h
 * @return the number of vehicles added to the list
 */
-uint GenerateVehicleSortList(const Vehicle ***sort_list, uint16 *length_of_array, byte type, PlayerID owner, uint32 index, uint16 window_type)
+uint GenerateVehicleSortList(const Vehicle ***sort_list, uint16 *length_of_array, VehicleType type, PlayerID owner, uint32 index, uint16 window_type)
 {
-	const byte subtype = (type != VEH_AIRCRAFT) ? (byte)Train_Front : (byte)AIR_AIRCRAFT;
 	uint n = 0;
 	const Vehicle *v;
 
 	switch (window_type) {
 		case VLW_STATION_LIST: {
 			FOR_ALL_VEHICLES(v) {
-				if (v->type == type && (
-					(type == VEH_TRAIN && IsFrontEngine(v)) ||
-					(type != VEH_TRAIN && v->subtype <= subtype))) {
+				if (v->type == type && v->IsPrimaryVehicle()) {
 					const Order *order;
 
 					FOR_VEHICLE_ORDERS(v, order) {
@@ -2031,9 +2045,7 @@
 
 		case VLW_STANDARD: {
 			FOR_ALL_VEHICLES(v) {
-				if (v->type == type && v->owner == owner && (
-					(type == VEH_TRAIN && IsFrontEngine(v)) ||
-					(type != VEH_TRAIN && v->subtype <= subtype))) {
+				if (v->type == type && v->owner == owner && v->IsPrimaryVehicle()) {
 					/* TODO find a better estimate on the total number of vehicles for current player */
 					if (n == *length_of_array) ExtendVehicleListSize(sort_list, length_of_array, GetNumVehicles()/4);
 					(*sort_list)[n++] = v;
@@ -2044,9 +2056,7 @@
 
 		case VLW_DEPOT_LIST: {
 			FOR_ALL_VEHICLES(v) {
-				if (v->type == type && (
-					(type == VEH_TRAIN && IsFrontEngine(v)) ||
-					(type != VEH_TRAIN && v->subtype <= subtype))) {
+				if (v->type == type && v->IsPrimaryVehicle()) {
 					const Order *order;
 
 					FOR_VEHICLE_ORDERS(v, order) {
@@ -2061,6 +2071,17 @@
 			break;
 		}
 
+ 		case VLW_GROUP_LIST:
+			FOR_ALL_VEHICLES(v) {
+				if (v->type == type && v->IsPrimaryVehicle() &&
+						v->owner == owner && v->group_id == index) {
+					if (n == *length_of_array) ExtendVehicleListSize(sort_list, length_of_array, GetNumVehicles() / 4);
+
+					(*sort_list)[n++] = v;
+				}
+			}
+			break;
+
 		default: NOT_REACHED(); break;
 	}
 
@@ -2081,10 +2102,10 @@
  * @param flags the flags used for DoCommand()
  * @param service should the vehicles only get service in the depots
  * @param owner PlayerID of owner of the vehicles to send
- * @param VLW_flag tells what kind of list requested the goto depot
+ * @param vlw_flag tells what kind of list requested the goto depot
  * @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
  */
-int32 SendAllVehiclesToDepot(byte type, uint32 flags, bool service, PlayerID owner, uint16 vlw_flag, uint32 id)
+int32 SendAllVehiclesToDepot(VehicleType type, uint32 flags, bool service, PlayerID owner, uint16 vlw_flag, uint32 id)
 {
 	const Vehicle **sort_list = NULL;
 	uint n, i;
@@ -2195,7 +2216,6 @@
 
 		if (HASBIT(t.flags, OFB_PART_OF_ORDERS)) {
 			/* Part of orders */
-			if (v->type == VEH_TRAIN) v->u.rail.days_since_order_progr = 0;
 			v->cur_order_index++;
 		} else if (HASBIT(t.flags, OFB_HALT_IN_DEPOT)) {
 			/* Force depot visit */
@@ -2212,7 +2232,7 @@
 				}
 
 				SetDParam(0, v->unitnumber);
-				AddNewsItem(string, NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0),	v->index, 0);
+				AddNewsItem(string, NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0), v->index, 0);
 			}
 		}
 	}
@@ -2220,6 +2240,7 @@
 
 /** Give a custom name to your vehicle
  * @param tile unused
+ * @param flags type of operation
  * @param p1 vehicle ID to name
  * @param p2 unused
  */
@@ -2253,6 +2274,7 @@
 
 /** Change the service interval of a vehicle
  * @param tile unused
+ * @param flags type of operation
  * @param p1 vehicle ID that is being service-interval-changed
  * @param p2 new service interval
  */
@@ -2349,27 +2371,27 @@
 
 	switch (v->type) {
 		case VEH_TRAIN:
-			if (v->u.rail.track == TRACK_BIT_DEPOT) /* We'll assume the train is facing outwards */
-				return DiagdirToDiagTrackdir(GetRailDepotDirection(v->tile)); /* Train in depot */
-
-			if (v->u.rail.track == TRACK_BIT_WORMHOLE) /* train in tunnel, so just use his direction and assume a diagonal track */
+			if (v->u.rail.track == TRACK_BIT_DEPOT) // We'll assume the train is facing outwards
+				return DiagdirToDiagTrackdir(GetRailDepotDirection(v->tile)); // Train in depot
+
+			if (v->u.rail.track == TRACK_BIT_WORMHOLE) // train in tunnel, so just use his direction and assume a diagonal track
 				return DiagdirToDiagTrackdir(DirToDiagDir(v->direction));
 
 			return TrackDirectionToTrackdir(FindFirstTrack(v->u.rail.track), v->direction);
 
 		case VEH_SHIP:
 			if (IsShipInDepot(v))
-				/* We'll assume the ship is facing outwards */
+				// We'll assume the ship is facing outwards
 				return DiagdirToDiagTrackdir(GetShipDepotDirection(v->tile));
 
 			return TrackDirectionToTrackdir(FindFirstTrack(v->u.ship.state), v->direction);
 
 		case VEH_ROAD:
-			if (IsRoadVehInDepot(v)) /* We'll assume the road vehicle is facing outwards */
+			if (IsRoadVehInDepot(v)) // We'll assume the road vehicle is facing outwards
 				return DiagdirToDiagTrackdir(GetRoadDepotDirection(v->tile));
 
-			if (IsStandardRoadStopTile(v->tile)) /* We'll assume the road vehicle is facing outwards */
-				return DiagdirToDiagTrackdir(GetRoadStopDir(v->tile)); /* Road vehicle in a station */
+			if (IsStandardRoadStopTile(v->tile)) // We'll assume the road vehicle is facing outwards
+				return DiagdirToDiagTrackdir(GetRoadStopDir(v->tile)); // Road vehicle in a station
 
 			if (IsDriveThroughStopTile(v->tile)) return DiagdirToDiagTrackdir(DirToDiagDir(v->direction));
 
@@ -2393,7 +2415,7 @@
 	return _tile_type_procs[GetTileType(tile)]->vehicle_enter_tile_proc(v, tile, x, y);
 }
 
-UnitID GetFreeUnitNumber(byte type)
+UnitID GetFreeUnitNumber(VehicleType type)
 {
 	UnitID unit, max = 0;
 	const Vehicle *u;
@@ -2422,16 +2444,16 @@
 		cache = MallocT<bool>(max + 1);
 	}
 
-	// Clear the cache
+	/* Clear the cache */
 	memset(cache, 0, (max + 1) * sizeof(*cache));
 
-	// Fill the cache
+	/* Fill the cache */
 	FOR_ALL_VEHICLES(u) {
 		if (u->type == type && u->owner == _current_player && u->unitnumber != 0 && u->unitnumber <= max)
 			cache[u->unitnumber] = true;
 	}
 
-	// Find the first unused unit number
+	/* Find the first unused unit number */
 	for (unit = 1; unit <= max; unit++) {
 		if (!cache[unit]) break;
 	}
@@ -2439,31 +2461,19 @@
 	return unit;
 }
 
-static SpriteID GetEngineColourMap(EngineID engine_type, PlayerID player, EngineID parent_engine_type, const Vehicle *v)
+
+const Livery *GetEngineLivery(EngineID engine_type, PlayerID player, EngineID parent_engine_type, const Vehicle *v)
 {
-	SpriteID map = PAL_NONE;
 	const Player *p = GetPlayer(player);
 	LiveryScheme scheme = LS_DEFAULT;
 	CargoID cargo_type = v == NULL ? (CargoID)CT_INVALID : v->cargo_type;
 
-	/* Check if we should use the colour map callback */
-	if (HASBIT(EngInfo(engine_type)->callbackmask, CBM_COLOUR_REMAP)) {
-		uint16 callback = GetVehicleCallback(CBID_VEHICLE_COLOUR_MAPPING, 0, 0, engine_type, v);
-		/* A return value of 0xC000 is stated to "use the default two-color
-		 * maps" which happens to be the failure action too... */
-		if (callback != CALLBACK_FAILED && callback != 0xC000) {
-			map = GB(callback, 0, 14);
-			/* If bit 14 is set, then the company colours are applied to the
-			 * map else it's returned as-is. */
-			if (!HASBIT(callback, 14)) return map;
-		}
-	}
-
 	/* The default livery is always available for use, but its in_use flag determines
 	 * whether any _other_ liveries are in use. */
 	if (p->livery[LS_DEFAULT].in_use && (_patches.liveries == 2 || (_patches.liveries == 1 && player == _local_player))) {
 		/* Determine the livery scheme to use */
 		switch (GetEngine(engine_type)->type) {
+			default: NOT_REACHED();
 			case VEH_TRAIN: {
 				const RailVehicleInfo *rvi = RailVehInfo(engine_type);
 
@@ -2474,14 +2484,15 @@
 					{
 						if (cargo_type == CT_INVALID) cargo_type = rvi->cargo_type;
 						if (rvi->railveh_type == RAILVEH_WAGON) {
-							if (cargo_type == CT_PASSENGERS || cargo_type == CT_MAIL || cargo_type == CT_VALUABLES) {
+							if (!GetCargo(cargo_type)->is_freight) {
 								if (parent_engine_type == INVALID_ENGINE) {
 									scheme = LS_PASSENGER_WAGON_STEAM;
 								} else {
 									switch (RailVehInfo(parent_engine_type)->engclass) {
-										case 0: scheme = LS_PASSENGER_WAGON_STEAM; break;
-										case 1: scheme = LS_PASSENGER_WAGON_DIESEL; break;
-										case 2: scheme = LS_PASSENGER_WAGON_ELECTRIC; break;
+										default: NOT_REACHED();
+										case EC_STEAM:    scheme = LS_PASSENGER_WAGON_STEAM;    break;
+										case EC_DIESEL:   scheme = LS_PASSENGER_WAGON_DIESEL;   break;
+										case EC_ELECTRIC: scheme = LS_PASSENGER_WAGON_ELECTRIC; break;
 									}
 								}
 							} else {
@@ -2491,9 +2502,10 @@
 							bool is_mu = HASBIT(_engine_info[engine_type].misc_flags, EF_RAIL_IS_MU);
 
 							switch (rvi->engclass) {
-								case 0: scheme = LS_STEAM; break;
-								case 1: scheme = is_mu ? LS_DMU : LS_DIESEL; break;
-								case 2: scheme = is_mu ? LS_EMU : LS_ELECTRIC; break;
+								default: NOT_REACHED();
+								case EC_STEAM:    scheme = LS_STEAM; break;
+								case EC_DIESEL:   scheme = is_mu ? LS_DMU : LS_DIESEL;   break;
+								case EC_ELECTRIC: scheme = is_mu ? LS_EMU : LS_ELECTRIC; break;
 							}
 						}
 						break;
@@ -2508,7 +2520,13 @@
 			case VEH_ROAD: {
 				const RoadVehicleInfo *rvi = RoadVehInfo(engine_type);
 				if (cargo_type == CT_INVALID) cargo_type = rvi->cargo_type;
-				scheme = IsCargoInClass(cargo_type, CC_PASSENGERS) ? LS_BUS : LS_TRUCK;
+				if (HASBIT(EngInfo(engine_type)->misc_flags, EF_ROAD_TRAM)) {
+					/* Tram */
+					scheme = IsCargoInClass(cargo_type, CC_PASSENGERS) ? LS_PASSENGER_TRAM : LS_FREIGHT_TRAM;
+				} else {
+					/* Bus or truck */
+					scheme = IsCargoInClass(cargo_type, CC_PASSENGERS) ? LS_BUS : LS_TRUCK;
+				}
 				break;
 			}
 
@@ -2535,12 +2553,35 @@
 		if (!p->livery[scheme].in_use) scheme = LS_DEFAULT;
 	}
 
+	return &p->livery[scheme];
+}
+
+
+static SpriteID GetEngineColourMap(EngineID engine_type, PlayerID player, EngineID parent_engine_type, const Vehicle *v)
+{
+	SpriteID map = PAL_NONE;
+
+	/* Check if we should use the colour map callback */
+	if (HASBIT(EngInfo(engine_type)->callbackmask, CBM_COLOUR_REMAP)) {
+		uint16 callback = GetVehicleCallback(CBID_VEHICLE_COLOUR_MAPPING, 0, 0, engine_type, v);
+		/* A return value of 0xC000 is stated to "use the default two-color
+		 * maps" which happens to be the failure action too... */
+		if (callback != CALLBACK_FAILED && callback != 0xC000) {
+			map = GB(callback, 0, 14);
+			/* If bit 14 is set, then the company colours are applied to the
+			 * map else it's returned as-is. */
+			if (!HASBIT(callback, 14)) return map;
+		}
+	}
+
 	bool twocc = HASBIT(EngInfo(engine_type)->misc_flags, EF_USES_2CC);
 
 	if (map == PAL_NONE) map = twocc ? (SpriteID)SPR_2CCMAP_BASE : (SpriteID)PALETTE_RECOLOR_START;
 
-	map += p->livery[scheme].colour1;
-	if (twocc) map += p->livery[scheme].colour2 * 16;
+	const Livery *livery = GetEngineLivery(engine_type, player, parent_engine_type, v);
+
+	map += livery->colour1;
+	if (twocc) map += livery->colour2 * 16;
 
 	return map;
 }
@@ -2562,7 +2603,7 @@
 	return GetEngineColourMap(v->engine_type, v->owner, INVALID_ENGINE, v);
 }
 
-// Save and load of vehicles
+/** Save and load of vehicles */
 extern const SaveLoad _common_veh_desc[] = {
 	    SLE_VAR(Vehicle, subtype,              SLE_UINT8),
 
@@ -2583,13 +2624,9 @@
 	    SLE_VAR(Vehicle, z_pos,                SLE_UINT8),
 	    SLE_VAR(Vehicle, direction,            SLE_UINT8),
 
-	    SLE_VAR(Vehicle, cur_image,            SLE_UINT16),
+	SLE_CONDNULL(2,                                                         0, 57),
 	    SLE_VAR(Vehicle, spritenum,            SLE_UINT8),
-	    SLE_VAR(Vehicle, sprite_width,         SLE_UINT8),
-	    SLE_VAR(Vehicle, sprite_height,        SLE_UINT8),
-	    SLE_VAR(Vehicle, z_height,             SLE_UINT8),
-	    SLE_VAR(Vehicle, x_offs,               SLE_INT8),
-	    SLE_VAR(Vehicle, y_offs,               SLE_INT8),
+	SLE_CONDNULL(5,                                                         0, 57),
 	    SLE_VAR(Vehicle, engine_type,          SLE_UINT16),
 
 	    SLE_VAR(Vehicle, max_speed,            SLE_UINT16),
@@ -2620,17 +2657,17 @@
 	/* This next line is for version 4 and prior compatibility.. it temporarily reads
 	    type and flags (which were both 4 bits) into type. Later on this is
 	    converted correctly */
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, type), SLE_UINT8,                 0, 4),
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, dest), SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, type), SLE_UINT8,                 0, 4),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, dest), SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
 
 	/* Orders for version 5 and on */
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, type),  SLE_UINT8,  5, SL_MAX_VERSION),
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, flags), SLE_UINT8,  5, SL_MAX_VERSION),
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, dest),  SLE_UINT16, 5, SL_MAX_VERSION),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, type),  SLE_UINT8,  5, SL_MAX_VERSION),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, flags), SLE_UINT8,  5, SL_MAX_VERSION),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, dest),  SLE_UINT16, 5, SL_MAX_VERSION),
 
 	/* Refit in current order */
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, refit_cargo),    SLE_UINT8, 36, SL_MAX_VERSION),
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, refit_subtype),  SLE_UINT8, 36, SL_MAX_VERSION),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, refit_cargo),    SLE_UINT8, 36, SL_MAX_VERSION),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, refit_subtype),  SLE_UINT8, 36, SL_MAX_VERSION),
 
 	    SLE_REF(Vehicle, orders,               REF_ORDER),
 
@@ -2667,7 +2704,9 @@
 	    SLE_REF(Vehicle, next_shared,          REF_VEHICLE),
 	    SLE_REF(Vehicle, prev_shared,          REF_VEHICLE),
 
-	// reserve extra space in savegame here. (currently 10 bytes)
+	SLE_CONDVAR(Vehicle, group_id,             SLE_UINT16,                60, SL_MAX_VERSION),
+
+	/* reserve extra space in savegame here. (currently 10 bytes) */
 	SLE_CONDNULL(10,                                                       2, SL_MAX_VERSION),
 
 	SLE_END()
@@ -2677,16 +2716,16 @@
 static const SaveLoad _train_desc[] = {
 	SLE_WRITEBYTE(Vehicle, type, VEH_TRAIN, 0), // Train type. VEH_TRAIN in mem, 0 in file.
 	SLE_INCLUDEX(0, INC_VEHICLE_COMMON),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRail, crash_anim_pos),         SLE_UINT16),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRail, force_proceed),          SLE_UINT8),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRail, railtype),               SLE_UINT8),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRail, track),                  SLE_UINT8),
-
-	SLE_CONDVARX(offsetof(Vehicle, u) + offsetof(VehicleRail, flags),                  SLE_UINT8,  2, SL_MAX_VERSION),
-	SLE_CONDVARX(offsetof(Vehicle, u) + offsetof(VehicleRail, days_since_order_progr), SLE_UINT16, 2, SL_MAX_VERSION),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, crash_anim_pos),         SLE_UINT16),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, force_proceed),          SLE_UINT8),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, railtype),               SLE_UINT8),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, track),                  SLE_UINT8),
+
+	SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, flags),                  SLE_UINT8,  2, SL_MAX_VERSION),
+	SLE_CONDNULL(2, 2, 59),
 
 	SLE_CONDNULL(2, 2, 19),
-	// reserve extra space in savegame here. (currently 11 bytes)
+	/* reserve extra space in savegame here. (currently 11 bytes) */
 	SLE_CONDNULL(11, 2, SL_MAX_VERSION),
 
 	SLE_END()
@@ -2695,18 +2734,18 @@
 static const SaveLoad _roadveh_desc[] = {
 	SLE_WRITEBYTE(Vehicle, type, VEH_ROAD, 1), // Road type. VEH_ROAD in mem, 1 in file.
 	SLE_INCLUDEX(0, INC_VEHICLE_COMMON),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRoad, state),          SLE_UINT8),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRoad, frame),          SLE_UINT8),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRoad, blocked_ctr),    SLE_UINT16),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRoad, overtaking),     SLE_UINT8),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRoad, overtaking_ctr), SLE_UINT8),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRoad, crashed_ctr),    SLE_UINT16),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleRoad, reverse_ctr),    SLE_UINT8),
-
-	SLE_CONDREFX(offsetof(Vehicle, u) + offsetof(VehicleRoad, slot),     REF_ROADSTOPS, 6, SL_MAX_VERSION),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, state),          SLE_UINT8),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, frame),          SLE_UINT8),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, blocked_ctr),    SLE_UINT16),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, overtaking),     SLE_UINT8),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, overtaking_ctr), SLE_UINT8),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, crashed_ctr),    SLE_UINT16),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, reverse_ctr),    SLE_UINT8),
+
+	SLE_CONDREFX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, slot),     REF_ROADSTOPS, 6, SL_MAX_VERSION),
 	SLE_CONDNULL(1,                                                                     6, SL_MAX_VERSION),
-	SLE_CONDVARX(offsetof(Vehicle, u) + offsetof(VehicleRoad, slot_age), SLE_UINT8,     6, SL_MAX_VERSION),
-	// reserve extra space in savegame here. (currently 16 bytes)
+	SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, slot_age), SLE_UINT8,     6, SL_MAX_VERSION),
+	/* reserve extra space in savegame here. (currently 16 bytes) */
 	SLE_CONDNULL(16,                                                                    2, SL_MAX_VERSION),
 
 	SLE_END()
@@ -2715,9 +2754,9 @@
 static const SaveLoad _ship_desc[] = {
 	SLE_WRITEBYTE(Vehicle, type, VEH_SHIP, 2), // Ship type. VEH_SHIP in mem, 2 in file.
 	SLE_INCLUDEX(0, INC_VEHICLE_COMMON),
-	SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleShip, state), SLE_UINT8),
-
-	// reserve extra space in savegame here. (currently 16 bytes)
+	SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleShip, state), SLE_UINT8),
+
+	/* reserve extra space in savegame here. (currently 16 bytes) */
 	SLE_CONDNULL(16, 2, SL_MAX_VERSION),
 
 	SLE_END()
@@ -2726,17 +2765,17 @@
 static const SaveLoad _aircraft_desc[] = {
 	SLE_WRITEBYTE(Vehicle, type, VEH_AIRCRAFT, 3), // Aircraft type. VEH_AIRCRAFT in mem, 3 in file.
 	SLE_INCLUDEX(0, INC_VEHICLE_COMMON),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleAir, crashed_counter), SLE_UINT16),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleAir, pos),             SLE_UINT8),
-
-	SLE_CONDVARX(offsetof(Vehicle, u) + offsetof(VehicleAir, targetairport),   SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
-	SLE_CONDVARX(offsetof(Vehicle, u) + offsetof(VehicleAir, targetairport),   SLE_UINT16,                5, SL_MAX_VERSION),
-
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleAir, state),           SLE_UINT8),
-
-	SLE_CONDVARX(offsetof(Vehicle, u) + offsetof(VehicleAir, previous_pos),    SLE_UINT8,                 2, SL_MAX_VERSION),
-
-	// reserve extra space in savegame here. (currently 15 bytes)
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, crashed_counter), SLE_UINT16),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, pos),             SLE_UINT8),
+
+	SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, targetairport),   SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, targetairport),   SLE_UINT16,                5, SL_MAX_VERSION),
+
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, state),           SLE_UINT8),
+
+	SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, previous_pos),    SLE_UINT8,                 2, SL_MAX_VERSION),
+
+	/* reserve extra space in savegame here. (currently 15 bytes) */
 	SLE_CONDNULL(15,                                                                                      2, SL_MAX_VERSION),
 
 	SLE_END()
@@ -2757,18 +2796,14 @@
 	    SLE_VAR(Vehicle, z_pos,         SLE_UINT8),
 
 	    SLE_VAR(Vehicle, cur_image,     SLE_UINT16),
-	    SLE_VAR(Vehicle, sprite_width,  SLE_UINT8),
-	    SLE_VAR(Vehicle, sprite_height, SLE_UINT8),
-	    SLE_VAR(Vehicle, z_height,      SLE_UINT8),
-	    SLE_VAR(Vehicle, x_offs,        SLE_INT8),
-	    SLE_VAR(Vehicle, y_offs,        SLE_INT8),
+	SLE_CONDNULL(5,                                                 0, 57),
 	    SLE_VAR(Vehicle, progress,      SLE_UINT8),
 	    SLE_VAR(Vehicle, vehstatus,     SLE_UINT8),
 
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleSpecial, unk0), SLE_UINT16),
-	    SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleSpecial, unk2), SLE_UINT8),
-
-	// reserve extra space in savegame here. (currently 16 bytes)
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleSpecial, unk0), SLE_UINT16),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleSpecial, unk2), SLE_UINT8),
+
+	/* reserve extra space in savegame here. (currently 16 bytes) */
 	SLE_CONDNULL(16, 2, SL_MAX_VERSION),
 
 	SLE_END()
@@ -2792,25 +2827,21 @@
 	    SLE_VAR(Vehicle, z_pos,         SLE_UINT8),
 	    SLE_VAR(Vehicle, direction,     SLE_UINT8),
 
-	    SLE_VAR(Vehicle, x_offs,        SLE_INT8),
-	    SLE_VAR(Vehicle, y_offs,        SLE_INT8),
-	    SLE_VAR(Vehicle, sprite_width,  SLE_UINT8),
-	    SLE_VAR(Vehicle, sprite_height, SLE_UINT8),
-	    SLE_VAR(Vehicle, z_height,      SLE_UINT8),
+	SLE_CONDNULL(5,                                                  0, 57),
 	    SLE_VAR(Vehicle, owner,         SLE_UINT8),
 	    SLE_VAR(Vehicle, vehstatus,     SLE_UINT8),
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, dest), SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
-	SLE_CONDVARX(offsetof(Vehicle, current_order) + offsetof(Order, dest), SLE_UINT16,                5, SL_MAX_VERSION),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, dest), SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
+	SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, dest), SLE_UINT16,                5, SL_MAX_VERSION),
 
 	    SLE_VAR(Vehicle, cur_image,     SLE_UINT16),
 	SLE_CONDVAR(Vehicle, age,           SLE_FILE_U16 | SLE_VAR_I32,  0, 30),
 	SLE_CONDVAR(Vehicle, age,           SLE_INT32,                  31, SL_MAX_VERSION),
 	    SLE_VAR(Vehicle, tick_counter,  SLE_UINT8),
 
-	   SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleDisaster, image_override), SLE_UINT16),
-	   SLE_VARX(offsetof(Vehicle, u) + offsetof(VehicleDisaster, unk2),           SLE_UINT16),
-
-	// reserve extra space in savegame here. (currently 16 bytes)
+	   SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleDisaster, image_override), SLE_UINT16),
+	   SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleDisaster, unk2),           SLE_UINT16),
+
+	/* reserve extra space in savegame here. (currently 16 bytes) */
 	SLE_CONDNULL(16,                                                 2, SL_MAX_VERSION),
 
 	SLE_END()
@@ -2826,18 +2857,18 @@
 	_disaster_desc,
 };
 
-// Will be called when the vehicles need to be saved.
+/** Will be called when the vehicles need to be saved. */
 static void Save_VEHS()
 {
 	Vehicle *v;
-	// Write the vehicles
+	/* Write the vehicles */
 	FOR_ALL_VEHICLES(v) {
 		SlSetArrayIndex(v->index);
 		SlObject(v, (SaveLoad*)_veh_descs[v->type]);
 	}
 }
 
-// Will be called when vehicles need to be loaded.
+/** Will be called when vehicles need to be loaded. */
 static void Load_VEHS()
 {
 	int index;
@@ -2852,6 +2883,17 @@
 		v = GetVehicle(index);
 		SlObject(v, (SaveLoad*)_veh_descs[SlReadByte()]);
 
+		switch (v->type) {
+			case VEH_TRAIN:    v = new (v) Train();           break;
+			case VEH_ROAD:     v = new (v) RoadVehicle();     break;
+			case VEH_SHIP:     v = new (v) Ship();            break;
+			case VEH_AIRCRAFT: v = new (v) Aircraft();        break;
+			case VEH_SPECIAL:  v = new (v) SpecialVehicle();  break;
+			case VEH_DISASTER: v = new (v) DisasterVehicle(); break;
+			case VEH_INVALID:  v = new (v) InvalidVehicle();  break;
+			default: NOT_REACHED();
+		}
+
 		/* Old savegames used 'last_station_visited = 0xFF' */
 		if (CheckSavegameVersion(5) && v->last_station_visited == 0xFF)
 			v->last_station_visited = INVALID_STATION;
@@ -2862,6 +2904,9 @@
 			v->current_order.flags = (v->current_order.type & 0xF0) >> 4;
 			v->current_order.type.m_val &= 0x0F;
 		}
+
+		/* Advanced vehicle lists got added */
+		if (CheckSavegameVersion(60)) v->group_id = DEFAULT_GROUP;
 	}
 
 	/* Check for shared order-lists (we now use pointers for that) */
@@ -2889,13 +2934,80 @@
 void Vehicle::BeginLoading()
 {
 	assert(IsTileType(tile, MP_STATION) || type == VEH_SHIP);
+
+	if (this->current_order.type == OT_GOTO_STATION &&
+			this->current_order.dest == this->last_station_visited) {
+		/* Arriving at the ordered station.
+		 * Keep the load/unload flags, as we (obviously) still need them. */
+		this->current_order.flags &= OF_FULL_LOAD | OF_UNLOAD | OF_TRANSFER;
+
+		/* Furthermore add the Non Stop flag to mark that this station
+		 * is the actual destination of the vehicle, which is (for example)
+		 * necessary to be known for HandleTrainLoading to determine
+		 * whether the train is lost or not; not marking a train lost
+		 * that arrives at random stations is bad. */
+		this->current_order.flags |= OF_NON_STOP;
+	} else {
+		/* This is just an unordered intermediate stop */
+		this->current_order.flags = 0;
+	}
+
 	current_order.type = OT_LOADING;
+	GetStation(this->last_station_visited)->loading_vehicles.push_back(this);
+
+	SET_EXPENSES_TYPE(this->GetExpenseType(true));
+	VehiclePayment(this);
+
+	InvalidateWindow(this->GetVehicleListWindowClass(), this->owner);
+	InvalidateWindowWidget(WC_VEHICLE_VIEW, this->index, STATUS_BAR);
+	InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
+	InvalidateWindow(WC_STATION_VIEW, this->last_station_visited);
+
+	GetStation(this->last_station_visited)->MarkTilesDirty();
+	this->MarkDirty();
 }
 
 void Vehicle::LeaveStation()
 {
-	assert(IsTileType(tile, MP_STATION) || type == VEH_SHIP);
 	assert(current_order.type == OT_LOADING);
 	current_order.type = OT_LEAVESTATION;
 	current_order.flags = 0;
+	GetStation(this->last_station_visited)->loading_vehicles.remove(this);
 }
+
+
+void Vehicle::HandleLoading(bool mode)
+{
+	switch (this->current_order.type) {
+		case OT_LOADING: {
+			/* Not the first call for this tick, or still loading */
+			if (mode || !HASBIT(this->vehicle_flags, VF_LOADING_FINISHED)) return;
+
+			this->PlayLeaveStationSound();
+
+			Order b = this->current_order;
+			this->LeaveStation();
+
+			/* If this was not the final order, don't remove it from the list. */
+			if (!(b.flags & OF_NON_STOP)) return;
+			break;
+		}
+
+		case OT_DUMMY: break;
+
+		default: return;
+	}
+
+	this->cur_order_index++;
+	InvalidateVehicleOrder(this);
+}
+
+
+void SpecialVehicle::UpdateDeltaXY(Direction direction)
+{
+	this->x_offs        = 0;
+	this->y_offs        = 0;
+	this->sprite_width  = 1;
+	this->sprite_height = 1;
+	this->z_height      = 1;
+}