src/economy.cpp
branchgamebalance
changeset 9911 0b8b245a2391
parent 9910 0b2aebc8283e
child 9912 1ac8aac92385
equal deleted inserted replaced
9910:0b2aebc8283e 9911:0b8b245a2391
    36 #include "newgrf_callbacks.h"
    36 #include "newgrf_callbacks.h"
    37 #include "unmovable.h"
    37 #include "unmovable.h"
    38 #include "date.h"
    38 #include "date.h"
    39 #include "cargotype.h"
    39 #include "cargotype.h"
    40 #include "player_face.h"
    40 #include "player_face.h"
       
    41 #include "group.h"
    41 
    42 
    42 /* Score info */
    43 /* Score info */
    43 const ScoreInfo _score_info[] = {
    44 const ScoreInfo _score_info[] = {
    44 	{ SCORE_VEHICLES,        120, 100 },
    45 	{ SCORE_VEHICLES,        120, 100 },
    45 	{ SCORE_STATIONS,         80, 100 },
    46 	{ SCORE_STATIONS,         80, 100 },
   357 					DeleteWindowById(WC_VEHICLE_DETAILS, v->index);
   358 					DeleteWindowById(WC_VEHICLE_DETAILS, v->index);
   358 					DeleteWindowById(WC_VEHICLE_ORDERS, v->index);
   359 					DeleteWindowById(WC_VEHICLE_ORDERS, v->index);
   359 					DeleteVehicle(v);
   360 					DeleteVehicle(v);
   360 				} else {
   361 				} else {
   361 					v->owner = new_player;
   362 					v->owner = new_player;
       
   363 					v->group_id = DEFAULT_GROUP;
   362 					if (IsEngineCountable(v)) GetPlayer(new_player)->num_engines[v->engine_type]++;
   364 					if (IsEngineCountable(v)) GetPlayer(new_player)->num_engines[v->engine_type]++;
   363 					switch (v->type) {
   365 					switch (v->type) {
   364 						case VEH_TRAIN:    if (IsFrontEngine(v)) v->unitnumber = ++num_train; break;
   366 						case VEH_TRAIN:    if (IsFrontEngine(v)) v->unitnumber = ++num_train; break;
   365 						case VEH_ROAD:     v->unitnumber = ++num_road; break;
   367 						case VEH_ROAD:     v->unitnumber = ++num_road; break;
   366 						case VEH_SHIP:     v->unitnumber = ++num_ship; break;
   368 						case VEH_SHIP:     v->unitnumber = ++num_ship; break;
   367 						case VEH_AIRCRAFT: if (IsNormalAircraft(v)) v->unitnumber = ++num_aircraft; break;
   369 						case VEH_AIRCRAFT: if (IsNormalAircraft(v)) v->unitnumber = ++num_aircraft; break;
       
   370 						default: NOT_REACHED();
   368 					}
   371 					}
   369 				}
   372 				}
   370 			}
   373 			}
   371 		}
   374 		}
   372 	}
   375 	}
   802 }
   805 }
   803 
   806 
   804 static void FindSubsidyCargoRoute(FoundRoute *fr)
   807 static void FindSubsidyCargoRoute(FoundRoute *fr)
   805 {
   808 {
   806 	Industry *i;
   809 	Industry *i;
       
   810 	const IndustrySpec *ind;
   807 	int trans, total;
   811 	int trans, total;
   808 	CargoID cargo;
   812 	CargoID cargo;
   809 
   813 
   810 	fr->distance = (uint)-1;
   814 	fr->distance = (uint)-1;
   811 
   815 
   812 	fr->from = i = GetRandomIndustry();
   816 	fr->from = i = GetRandomIndustry();
   813 	if (i == NULL) return;
   817 	if (i == NULL) return;
       
   818 	ind = GetIndustrySpec(i->type);
   814 
   819 
   815 	/* Randomize cargo type */
   820 	/* Randomize cargo type */
   816 	if (Random()&1 && i->produced_cargo[1] != CT_INVALID) {
   821 	if (HASBIT(Random(), 0) && ind->produced_cargo[1] != CT_INVALID) {
   817 		cargo = i->produced_cargo[1];
   822 		cargo = ind->produced_cargo[1];
   818 		trans = i->pct_transported[1];
   823 		trans = i->pct_transported[1];
   819 		total = i->total_production[1];
   824 		total = i->total_production[1];
   820 	} else {
   825 	} else {
   821 		cargo = i->produced_cargo[0];
   826 		cargo = ind->produced_cargo[0];
   822 		trans = i->pct_transported[0];
   827 		trans = i->pct_transported[0];
   823 		total = i->total_production[0];
   828 		total = i->total_production[0];
   824 	}
   829 	}
   825 
   830 
   826 	/* Quit if no production in this industry
   831 	/* Quit if no production in this industry
   843 		fr->distance = DistanceManhattan(i->xy, t->xy);
   848 		fr->distance = DistanceManhattan(i->xy, t->xy);
   844 		fr->to = t;
   849 		fr->to = t;
   845 	} else {
   850 	} else {
   846 		/* The destination is an industry */
   851 		/* The destination is an industry */
   847 		Industry *i2 = GetRandomIndustry();
   852 		Industry *i2 = GetRandomIndustry();
       
   853 		if (i2 == NULL) {
       
   854 			return;
       
   855 		}
       
   856 
       
   857 		ind = GetIndustrySpec(i2->type);
   848 
   858 
   849 		/* The industry must accept the cargo */
   859 		/* The industry must accept the cargo */
   850 		if (i == i2 || i == NULL ||
   860 		if (i == i2 ||
   851 				(cargo != i2->accepts_cargo[0] &&
   861 				(cargo != ind->accepts_cargo[0] &&
   852 				cargo != i2->accepts_cargo[1] &&
   862 				cargo != ind->accepts_cargo[1] &&
   853 				cargo != i2->accepts_cargo[2]))
   863 				cargo != ind->accepts_cargo[2])) {
   854 			return;
   864 			return;
       
   865 		}
   855 		fr->distance = DistanceManhattan(i->xy, i2->xy);
   866 		fr->distance = DistanceManhattan(i->xy, i2->xy);
   856 		fr->to = i2;
   867 		fr->to = i2;
   857 	}
   868 	}
   858 }
   869 }
   859 
   870 
  1023 	return BIGMULSS(dist * f * num_pieces, _cargo_payment_rates[cargo_type], 21);
  1034 	return BIGMULSS(dist * f * num_pieces, _cargo_payment_rates[cargo_type], 21);
  1024 }
  1035 }
  1025 
  1036 
  1026 static void DeliverGoodsToIndustry(TileIndex xy, CargoID cargo_type, int num_pieces)
  1037 static void DeliverGoodsToIndustry(TileIndex xy, CargoID cargo_type, int num_pieces)
  1027 {
  1038 {
  1028 	Industry* best = NULL;
  1039 	Industry *best = NULL;
  1029 	Industry* ind;
  1040 	Industry *ind;
  1030 	uint u;
  1041 	const IndustrySpec *indspec;
       
  1042 	uint best_dist;
       
  1043 	uint accepted_cargo_index = 0;  ///< unlikely value, just for warning removing
  1031 
  1044 
  1032 	/* Check if there's an industry close to the station that accepts the cargo
  1045 	/* Check if there's an industry close to the station that accepts the cargo
  1033 	 * XXX - Think of something better to
  1046 	 * XXX - Think of something better to
  1034 	 *       1) Only deliver to industries which are withing the catchment radius
  1047 	 *       1) Only deliver to industries which are withing the catchment radius
  1035 	 *       2) Distribute between industries if more then one is present */
  1048 	 *       2) Distribute between industries if more then one is present */
  1036 	u = (_patches.station_spread + 8) * 2;
  1049 	best_dist = (_patches.station_spread + 8) * 2;
  1037 	FOR_ALL_INDUSTRIES(ind) {
  1050 	FOR_ALL_INDUSTRIES(ind) {
  1038 		uint t;
  1051 		indspec = GetIndustrySpec(ind->type);
  1039 
  1052 		uint i;
  1040 		if (( cargo_type == ind->accepts_cargo[0] ||
  1053 
  1041 					cargo_type == ind->accepts_cargo[1] ||
  1054 		if (indspec->produced_cargo[0] == CT_INVALID) continue;
  1042 					cargo_type == ind->accepts_cargo[2]
  1055 
  1043 				) &&
  1056 		for (i = 0; i < lengthof(indspec->accepts_cargo); i++) {
  1044 				ind->produced_cargo[0] != CT_INVALID &&
  1057 			if (cargo_type == indspec->accepts_cargo[i] &&
  1045 				ind->produced_cargo[0] != cargo_type &&
  1058 					(indspec->input_cargo_multiplier[i][0] != 0 || indspec->input_cargo_multiplier[i][1] != 0)) {
  1046 				(t = DistanceManhattan(ind->xy, xy)) < u) {
  1059 				break;
  1047 			u = t;
  1060 			}
       
  1061 		}
       
  1062 
       
  1063 		/* Check if matching cargo has been found */
       
  1064 		if (i == lengthof(indspec->accepts_cargo)) continue;
       
  1065 
       
  1066 		uint dist = DistanceManhattan(ind->xy, xy);
       
  1067 
       
  1068 		if (dist < best_dist) {
  1048 			best = ind;
  1069 			best = ind;
       
  1070 			best_dist = dist;
       
  1071 			accepted_cargo_index = i;
  1049 		}
  1072 		}
  1050 	}
  1073 	}
  1051 
  1074 
  1052 	/* Found one? */
  1075 	/* Found one? */
  1053 	if (best != NULL) {
  1076 	if (best != NULL) {
       
  1077 		indspec = GetIndustrySpec(best->type);
  1054 		best->was_cargo_delivered = true;
  1078 		best->was_cargo_delivered = true;
  1055 		best->cargo_waiting[0] = min(best->cargo_waiting[0] + num_pieces, 0xFFFF);
  1079 		best->cargo_waiting[0] = min(best->cargo_waiting[0] + (num_pieces * indspec->input_cargo_multiplier[accepted_cargo_index][0] / 256), 0xFFFF);
       
  1080 		best->cargo_waiting[1] = min(best->cargo_waiting[1] + (num_pieces * indspec->input_cargo_multiplier[accepted_cargo_index][1] / 256), 0xFFFF);
  1056 	}
  1081 	}
  1057 }
  1082 }
  1058 
  1083 
  1059 static bool CheckSubsidised(Station *from, Station *to, CargoID cargo_type)
  1084 static bool CheckSubsidised(Station *from, Station *to, CargoID cargo_type)
  1060 {
  1085 {
  1169 	}
  1194 	}
  1170 
  1195 
  1171 	return profit;
  1196 	return profit;
  1172 }
  1197 }
  1173 
  1198 
  1174 /*
  1199 /**
  1175  * Returns true if Vehicle v should wait loading because other vehicle is
  1200  * Performs the vehicle payment _and_ marks the vehicle to be unloaded.
  1176  * already loading the same cargo type
  1201  * @param front_v the vehicle to be unloaded
  1177  * v = vehicle to load, u = GetFirstInChain(v)
       
  1178  */
  1202  */
  1179 static bool LoadWait(const Vehicle* v, const Vehicle* u)
  1203 void VehiclePayment(Vehicle *front_v)
  1180 {
  1204 {
  1181 	const Vehicle *w;
  1205 	int result = 0;
  1182 	bool has_any_cargo = false;
  1206 
  1183 
       
  1184 	if (!(u->current_order.flags & OF_FULL_LOAD)) return false;
       
  1185 
       
  1186 	for (w = u; w != NULL; w = w->next) {
       
  1187 		if (w->cargo_count != 0) {
       
  1188 			if (v->cargo_type == w->cargo_type &&
       
  1189 					u->last_station_visited == w->cargo_source) {
       
  1190 				return false;
       
  1191 			}
       
  1192 			has_any_cargo = true;
       
  1193 		}
       
  1194 	}
       
  1195 
       
  1196 	const Station *st = GetStation(u->last_station_visited);
       
  1197 	std::list<Vehicle *>::const_iterator iter;
       
  1198 	for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
       
  1199 		const Vehicle *x = *iter;
       
  1200 		if (!(x->vehstatus & (VS_STOPPED | VS_CRASHED)) && u != x) {
       
  1201 			bool other_has_any_cargo = false;
       
  1202 			bool has_space_for_same_type = false;
       
  1203 			bool other_has_same_type = false;
       
  1204 
       
  1205 			for (w = x; w != NULL; w = w->next) {
       
  1206 				if (w->cargo_count < w->cargo_cap && v->cargo_type == w->cargo_type) {
       
  1207 					has_space_for_same_type = true;
       
  1208 				}
       
  1209 
       
  1210 				if (w->cargo_count != 0) {
       
  1211 					if (v->cargo_type == w->cargo_type &&
       
  1212 							u->last_station_visited == w->cargo_source) {
       
  1213 						other_has_same_type = true;
       
  1214 					}
       
  1215 					other_has_any_cargo = true;
       
  1216 				}
       
  1217 			}
       
  1218 
       
  1219 			if (has_space_for_same_type) {
       
  1220 				if (other_has_same_type) return true;
       
  1221 				if (other_has_any_cargo && !has_any_cargo) return true;
       
  1222 			}
       
  1223 		}
       
  1224 	}
       
  1225 
       
  1226 	return false;
       
  1227 }
       
  1228 
       
  1229 int LoadUnloadVehicle(Vehicle *v, bool just_arrived)
       
  1230 {
       
  1231 	int profit = 0;
  1207 	int profit = 0;
  1232 	int total_veh_profit = 0;      // accumulates the profit across the vehicle chain (used by trains)
  1208 	int total_veh_profit = 0;         // accumulates the profit across the vehicle chain (used by trains)
  1233 	int32 route_profit = 0;        // the grand total amount for the route. A-D of transfer chain A-B-C-D
  1209 	int32 route_profit = 0;           // the grand total amount for the route. A-D of transfer chain A-B-C-D
  1234 	int virtual_profit = 0;        // virtual profit of one vehicle element for feeder systems
  1210 	int virtual_profit = 0;           // virtual profit of one vehicle element for feeder systems
  1235 	int virtual_profit_total = 0;  // virtual profit for entire vehicle chain
  1211 	int virtual_profit_total = 0;     // virtual profit for entire vehicle chain
  1236 	int total_cargo_feeder_share = 0;  // the feeder cash amount for the goods being loaded/unloaded in this load step
  1212 	int total_cargo_feeder_share = 0; // the feeder cash amount for the goods being loaded/unloaded in this load step
  1237 
  1213 
  1238 	int unloading_time = 20;
  1214 	int all_vehicles_cargo_feeder_share = front_v->cargo_feeder_share; // used to hold transfer value of complete vehicle chain - used by trains
       
  1215 
       
  1216 	StationID last_visited = front_v->last_station_visited;
       
  1217 	Station *st = GetStation(last_visited);
       
  1218 
       
  1219 	/* The owner of the train wants to be paid */
       
  1220 	PlayerID old_player = _current_player;
       
  1221 	_current_player = front_v->owner;
       
  1222 
       
  1223 	/* At this moment loading cannot be finished */
       
  1224 	CLRBIT(front_v->vehicle_flags, VF_LOADING_FINISHED);
       
  1225 
       
  1226 	/* Start unloading in at the first possible moment */
       
  1227 	front_v->load_unload_time_rem = 1;
       
  1228 
       
  1229 	for (Vehicle *v = front_v; v != NULL; v = v->next) {
       
  1230 		/* No cargo to unload */
       
  1231 		if (v->cargo_cap == 0 || v->cargo_count == 0) continue;
       
  1232 
       
  1233 		SETBIT(v->vehicle_flags, VF_CARGO_UNLOADING);
       
  1234 		/* All cargo has already been paid for, no need to pay again */
       
  1235 		if (v->cargo_count == v->cargo_paid_for) continue;
       
  1236 
       
  1237 		GoodsEntry *ge = &st->goods[v->cargo_type];
       
  1238 
       
  1239 		if (v->cargo_source != last_visited &&
       
  1240 				HASBIT(ge->waiting_acceptance, 15) &&
       
  1241 				(front_v->current_order.flags & OF_TRANSFER) == 0) {
       
  1242 			/* Deliver goods to the station */
       
  1243 			st->time_since_unload = 0;
       
  1244 
       
  1245 			/* handle end of route payment */
       
  1246 			profit += DeliverGoods(v->cargo_count - v->cargo_paid_for, v->cargo_type, v->cargo_source, last_visited, v->cargo_source_xy, v->cargo_days);
       
  1247 			v->cargo_paid_for        = v->cargo_count;
       
  1248 			route_profit             = profit;                                   // display amount paid for final route delivery, A-D of a chain A-B-C-D
       
  1249 			total_veh_profit         = profit - all_vehicles_cargo_feeder_share; // whole vehicle is not payed for transfers picked up earlier
       
  1250 			total_cargo_feeder_share = -all_vehicles_cargo_feeder_share;         // total of transfer fees in vehicle chain needs to be zero at end of unload
       
  1251 
       
  1252 			v->cargo_feeder_share = 0;   // clear transfer cost per vehicle
       
  1253 			result |= 1;
       
  1254 		} else if (front_v->current_order.flags & (OF_UNLOAD | OF_TRANSFER)) {
       
  1255 			if ((front_v->current_order.flags & OF_TRANSFER) != 0) {
       
  1256 				virtual_profit = GetTransportedGoodsIncome(
       
  1257 					v->cargo_count - v->cargo_paid_for,
       
  1258 					/* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
       
  1259 					DistanceManhattan(v->cargo_loaded_at_xy, GetStation(last_visited)->xy),
       
  1260 					v->cargo_days,
       
  1261 					v->cargo_type);
       
  1262 
       
  1263 				front_v->profit_this_year += virtual_profit;
       
  1264 				ge->feeder_profit         += v->cargo_feeder_share + virtual_profit; // transfer cargo transfer fees to station
       
  1265 				total_cargo_feeder_share  -= v->cargo_feeder_share; // accumulate deduction of feeder shares
       
  1266 				v->cargo_feeder_share      = 0;                     // clear transfer cost
       
  1267 
       
  1268 				/* keep total of cargo unloaded (pending) for accurate cargoshare calculation on load */
       
  1269 				SB(ge->unload_pending, 0, 12, GB(ge->unload_pending, 0, 12) + v->cargo_count);
       
  1270 
       
  1271 				virtual_profit_total += virtual_profit;   // accumulate transfer profits for whole vehicle
       
  1272 				v->cargo_paid_for = v->cargo_count;       // record how much of the cargo has been paid for to eliminate double counting
       
  1273 			}
       
  1274 			result |= 2;
       
  1275 		}
       
  1276 	}
       
  1277 
       
  1278 	/* Ensure a negative total is only applied to the vehicle if there is value to reduce. */
       
  1279 	front_v->cargo_feeder_share = max(front_v->cargo_feeder_share + total_cargo_feeder_share, 0);
       
  1280 
       
  1281 	if (virtual_profit_total > 0) {
       
  1282 		ShowFeederIncomeAnimation(front_v->x_pos, front_v->y_pos, front_v->z_pos, virtual_profit_total);
       
  1283 	}
       
  1284 
       
  1285 	if (route_profit != 0) {
       
  1286 		front_v->profit_this_year += total_veh_profit;
       
  1287 		SubtractMoneyFromPlayer(-route_profit);
       
  1288 
       
  1289 		if (IsLocalPlayer() && !PlayVehicleSound(front_v, VSE_LOAD_UNLOAD)) {
       
  1290 			SndPlayVehicleFx(SND_14_CASHTILL, front_v);
       
  1291 		}
       
  1292 
       
  1293 		ShowCostOrIncomeAnimation(front_v->x_pos, front_v->y_pos, front_v->z_pos, -total_veh_profit);
       
  1294 	}
       
  1295 
       
  1296 	_current_player = old_player;
       
  1297 }
       
  1298 
       
  1299 /**
       
  1300  * Loads/unload the vehicle if possible.
       
  1301  * @param v the vehicle to be (un)loaded
       
  1302  * @param cargo_left the amount of each cargo type that is
       
  1303  *                   virtually left on the platform to be
       
  1304  *                   picked up by another vehicle when all
       
  1305  *                   previous vehicles have loaded.
       
  1306  */
       
  1307 static void LoadUnloadVehicle(Vehicle *v, int *cargo_left)
       
  1308 {
       
  1309 	assert(v->current_order.type == OT_LOADING);
       
  1310 
       
  1311 	/* We have not waited enough time till the next round of loading/unloading */
       
  1312 	if (--v->load_unload_time_rem != 0) {
       
  1313 		if (_patches.improved_load && HASBIT(v->current_order.flags, OFB_FULL_LOAD)) {
       
  1314 			/* 'Reserve' this cargo for this vehicle, because we were first. */
       
  1315 			for (; v != NULL; v = v->next) {
       
  1316 				if (v->cargo_cap != 0) cargo_left[v->cargo_type] -= v->cargo_cap - v->cargo_count;
       
  1317 			}
       
  1318 		}
       
  1319 		return;
       
  1320 	}
       
  1321 
       
  1322 	int unloading_time = 0;
  1239 	Vehicle *u = v;
  1323 	Vehicle *u = v;
  1240 	int result = 0;
  1324 	int result = 0;
  1241 	int t;
  1325 	int cap;
  1242 	uint count, cap;
  1326 
  1243 	PlayerID old_player;
  1327 	bool completely_empty  = true;
  1244 	bool completely_empty = true;
  1328 	bool anything_unloaded = false;
  1245 	byte load_amount;
  1329 	bool anything_loaded   = false;
  1246 	bool anything_loaded = false;
  1330 	uint32 cargo_not_full  = 0;
  1247 
  1331 	uint32 cargo_full      = 0;
  1248 	assert(v->current_order.type == OT_LOADING);
  1332 	int total_cargo_feeder_share = 0; // the feeder cash amount for the goods being loaded/unloaded in this load step
  1249 
  1333 
  1250 	v->cur_speed = 0;
  1334 	v->cur_speed = 0;
  1251 
       
  1252 	/* Loading can only have finished when all the cargo has been unloaded, and
       
  1253 	 * there is nothing left to load. It's easier to clear this if the
       
  1254 	 * conditions haven't been met than attempting to check them all before
       
  1255 	 * enabling though. */
       
  1256 	SETBIT(v->vehicle_flags, VF_LOADING_FINISHED);
       
  1257 
       
  1258 	old_player = _current_player;
       
  1259 	_current_player = v->owner;
       
  1260 
  1335 
  1261 	StationID last_visited = v->last_station_visited;
  1336 	StationID last_visited = v->last_station_visited;
  1262 	Station *st = GetStation(last_visited);
  1337 	Station *st = GetStation(last_visited);
  1263 
  1338 
  1264 	int all_vehicles_cargo_feeder_share = v->cargo_feeder_share; // used to hold transfer value of complete vehicle chain - used by trains
       
  1265 
       
  1266 	for (; v != NULL; v = v->next) {
  1339 	for (; v != NULL; v = v->next) {
  1267 		GoodsEntry* ge;
  1340 		if (v->cargo_cap == 0) continue;
  1268 		load_amount = EngInfo(v->engine_type)->load_amount;
  1341 
       
  1342 		byte load_amount = EngInfo(v->engine_type)->load_amount;
  1269 		if (_patches.gradual_loading && HASBIT(EngInfo(v->engine_type)->callbackmask, CBM_LOAD_AMOUNT)) {
  1343 		if (_patches.gradual_loading && HASBIT(EngInfo(v->engine_type)->callbackmask, CBM_LOAD_AMOUNT)) {
  1270 			uint16 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
  1344 			uint16 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
  1271 			if (cb_load_amount != CALLBACK_FAILED) load_amount = cb_load_amount & 0xFF;
  1345 			if (cb_load_amount != CALLBACK_FAILED) load_amount = cb_load_amount & 0xFF;
  1272 		}
  1346 		}
  1273 
  1347 
  1274 		if (v->cargo_cap == 0) continue;
  1348 		GoodsEntry *ge = &st->goods[v->cargo_type];
  1275 
  1349 		int count = GB(ge->waiting_acceptance, 0, 12);
  1276 		/* If the vehicle has just arrived, set it to unload. */
  1350 
  1277 		if (just_arrived) SETBIT(v->vehicle_flags, VF_CARGO_UNLOADING);
  1351 		if (HASBIT(v->vehicle_flags, VF_CARGO_UNLOADING)) {
  1278 
       
  1279 		ge = &st->goods[v->cargo_type];
       
  1280 		count = GB(ge->waiting_acceptance, 0, 12);
       
  1281 
       
  1282 		/* unload? */
       
  1283 		if (v->cargo_count != 0 && HASBIT(v->vehicle_flags, VF_CARGO_UNLOADING)) {
       
  1284 			uint16 amount_unloaded = _patches.gradual_loading ? min(v->cargo_count, load_amount) : v->cargo_count;
  1352 			uint16 amount_unloaded = _patches.gradual_loading ? min(v->cargo_count, load_amount) : v->cargo_count;
  1285 
  1353 
  1286 			CLRBIT(u->vehicle_flags, VF_LOADING_FINISHED);
       
  1287 
       
  1288 			if (v->cargo_source != last_visited && ge->waiting_acceptance & 0x8000 && !(u->current_order.flags & OF_TRANSFER)) {
  1354 			if (v->cargo_source != last_visited && ge->waiting_acceptance & 0x8000 && !(u->current_order.flags & OF_TRANSFER)) {
  1289 				/* deliver goods to the station */
       
  1290 				st->time_since_unload = 0;
       
  1291 
       
  1292 				unloading_time += v->cargo_count; // TTDBUG: bug in original TTD
       
  1293 
       
  1294 				/* handle end of route payment */
       
  1295 				if (just_arrived && v->cargo_paid_for < v->cargo_count) {
       
  1296 					profit += DeliverGoods(v->cargo_count - v->cargo_paid_for, v->cargo_type, v->cargo_source, last_visited, v->cargo_source_xy, v->cargo_days);
       
  1297 					v->cargo_paid_for = v->cargo_count;
       
  1298 					route_profit = profit;       // display amount paid for final route delivery, A-D of a chain A-B-C-D
       
  1299 					total_veh_profit = profit - all_vehicles_cargo_feeder_share;  // whole vehicle is not payed for transfers picked up earlier
       
  1300 					total_cargo_feeder_share = -all_vehicles_cargo_feeder_share;  // total of transfer fees in vehicle chain needs to be zero at end of unload
       
  1301 					v->cargo_feeder_share = 0;   // clear transfer cost per vehicle
       
  1302 				}
       
  1303 				result |= 1;
  1355 				result |= 1;
  1304 				v->cargo_count -= amount_unloaded;
       
  1305 				v->cargo_paid_for -= min(amount_unloaded, v->cargo_paid_for);
       
  1306 				if (_patches.gradual_loading) continue;
       
  1307 
       
  1308 			} else if (u->current_order.flags & (OF_UNLOAD | OF_TRANSFER)) {
  1356 			} else if (u->current_order.flags & (OF_UNLOAD | OF_TRANSFER)) {
  1309 
  1357 				if (count == 0) {
  1310 				/* unload goods and let it wait at the station */
       
  1311 				st->time_since_unload = 0;
       
  1312 
       
  1313 				/* handle transfer */
       
  1314 				if (just_arrived && (u->current_order.flags & OF_TRANSFER) && v->cargo_paid_for < v->cargo_count) {
       
  1315 					virtual_profit = GetTransportedGoodsIncome(
       
  1316 						v->cargo_count - v->cargo_paid_for,
       
  1317 						/* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
       
  1318 						DistanceManhattan(v->cargo_loaded_at_xy, GetStation(last_visited)->xy),
       
  1319 						v->cargo_days,
       
  1320 						v->cargo_type);
       
  1321 
       
  1322 					ge->feeder_profit += v->cargo_feeder_share;         // transfer cargo transfer fees to station
       
  1323 					total_cargo_feeder_share -= v->cargo_feeder_share;  // accumulate deduction of feeder shares
       
  1324 					v->cargo_feeder_share = 0;                          // clear transfer cost
       
  1325 
       
  1326 					/* keep total of cargo unloaded (pending) for accurate cargoshare calculation on load */
       
  1327 					SB(ge->unload_pending, 0, 12, GB(ge->unload_pending, 0, 12) + v->cargo_count);
       
  1328 
       
  1329 					virtual_profit_total += virtual_profit;   // accumulate transfer profits for whole vehicle
       
  1330 					v->cargo_paid_for = v->cargo_count;       // record how much of the cargo has been paid for to eliminate double counting
       
  1331 				}
       
  1332 
       
  1333 				unloading_time += v->cargo_count;
       
  1334 				t = GB(ge->waiting_acceptance, 0, 12);
       
  1335 				if (t == 0) {
       
  1336 					/* No goods waiting at station */
  1358 					/* No goods waiting at station */
  1337 					ge->enroute_time = v->cargo_days;
  1359 					ge->enroute_time    = v->cargo_days;
  1338 					ge->enroute_from = v->cargo_source;
  1360 					ge->enroute_from    = v->cargo_source;
  1339 					ge->enroute_from_xy = v->cargo_source_xy;
  1361 					ge->enroute_from_xy = v->cargo_source_xy;
  1340 				} else {
  1362 				} else {
  1341 					/* Goods already waiting at station. Set counters to the worst value. */
  1363 					/* Goods already waiting at station. Set counters to the worst value. */
  1342 					if (v->cargo_days >= ge->enroute_time) ge->enroute_time = v->cargo_days;
  1364 					if (v->cargo_days >= ge->enroute_time) ge->enroute_time = v->cargo_days;
  1343 
  1365 
  1344 					if (last_visited != ge->enroute_from) {
  1366 					if (last_visited != ge->enroute_from) {
  1345 						ge->enroute_from = v->cargo_source;
  1367 						ge->enroute_from    = v->cargo_source;
  1346 						ge->enroute_from_xy = v->cargo_source_xy;
  1368 						ge->enroute_from_xy = v->cargo_source_xy;
  1347 					}
  1369 					}
  1348 				}
  1370 				}
  1349 				/* Update amount of waiting cargo */
  1371 				/* Update amount of waiting cargo. There is, however, no sense in
  1350 				SB(ge->waiting_acceptance, 0, 12, min(amount_unloaded + t, 0xFFF));
  1372 				 * updating the count variable because this vehicle will not be
       
  1373 				 * able to take the cargo. */
       
  1374 				SB(ge->waiting_acceptance, 0, 12, min(amount_unloaded + count, 0xFFF));
  1351 
  1375 
  1352 				/* if there is not enough to unload from pending, ensure it does not go -ve
  1376 				/* if there is not enough to unload from pending, ensure it does not go -ve
  1353 				 * else deduct amount actually unloaded from unload_pending */
  1377 				 * else deduct amount actually unloaded from unload_pending */
  1354 				SB(ge->unload_pending, 0, 12, max(GB(ge->unload_pending, 0, 12) - amount_unloaded, 0U));
  1378 				SB(ge->unload_pending, 0, 12, max(GB(ge->unload_pending, 0, 12) - amount_unloaded, 0U));
  1355 
  1379 
  1356 				if (u->current_order.flags & OF_TRANSFER) {
       
  1357 					ge->feeder_profit += virtual_profit;
       
  1358 					u->profit_this_year += virtual_profit;
       
  1359 				}
       
  1360 				result |= 2;
  1380 				result |= 2;
  1361 				v->cargo_count -= amount_unloaded;
  1381 			} else {
  1362 				v->cargo_paid_for -= min(amount_unloaded, v->cargo_paid_for);
  1382 				/* The order changed while unloading (unset unload/transfer) or the
  1363 				if (_patches.gradual_loading) continue;
  1383 				 * station does not accept goods anymore. */
  1364 			}
  1384 				CLRBIT(v->vehicle_flags, VF_CARGO_UNLOADING);
  1365 
  1385 				continue;
  1366 			if (v->cargo_count != 0) completely_empty = false;
  1386 			}
  1367 		}
  1387 
  1368 
  1388 			/* Deliver goods to the station */
  1369 		/* The vehicle must have been unloaded because it is either empty, or
  1389 			st->time_since_unload = 0;
  1370 		 * the UNLOADING bit is already clear in v->vehicle_flags. */
  1390 
  1371 		CLRBIT(v->vehicle_flags, VF_CARGO_UNLOADING);
  1391 			unloading_time += amount_unloaded;
       
  1392 
       
  1393 			v->cargo_count -= amount_unloaded;
       
  1394 			v->cargo_paid_for -= min(amount_unloaded, v->cargo_paid_for);
       
  1395 
       
  1396 			anything_unloaded = true;
       
  1397 			if (_patches.gradual_loading && v->cargo_count != 0) {
       
  1398 				completely_empty = false;
       
  1399 			} else {
       
  1400 				/* We have finished unloading (cargo count == 0) */
       
  1401 				CLRBIT(v->vehicle_flags, VF_CARGO_UNLOADING);
       
  1402 			}
       
  1403 
       
  1404 			continue;
       
  1405 		}
  1372 
  1406 
  1373 		/* We cannot have paid for more cargo than there is on board. */
  1407 		/* We cannot have paid for more cargo than there is on board. */
  1374 		assert(v->cargo_paid_for <= v->cargo_count);
  1408 		assert(v->cargo_paid_for <= v->cargo_count);
  1375 
  1409 
  1376 		/* don't pick up goods that we unloaded */
  1410 		/* Do not pick up goods that we unloaded */
  1377 		if (u->current_order.flags & OF_UNLOAD) continue;
  1411 		if (u->current_order.flags & OF_UNLOAD) continue;
  1378 
  1412 
  1379 		/* update stats */
  1413 		/* update stats */
  1380 		ge->days_since_pickup = 0;
  1414 		int t;
  1381 		switch (u->type) {
  1415 		switch (u->type) {
  1382 			case VEH_TRAIN: t = u->u.rail.cached_max_speed; break;
  1416 			case VEH_TRAIN: t = u->u.rail.cached_max_speed; break;
  1383 			case VEH_ROAD:  t = u->max_speed / 2;           break;
  1417 			case VEH_ROAD:  t = u->max_speed / 2;           break;
  1384 			default:        t = u->max_speed;               break;
  1418 			default:        t = u->max_speed;               break;
  1385 		}
  1419 		}
  1386 
  1420 
  1387 		/* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
  1421 		/* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
       
  1422 		ge->days_since_pickup = 0;
  1388 		ge->last_speed = min(t, 255);
  1423 		ge->last_speed = min(t, 255);
  1389 		ge->last_age = _cur_year - v->build_year;
  1424 		ge->last_age = _cur_year - v->build_year;
  1390 
  1425 
  1391 		/* If there's goods waiting at the station, and the vehicle
  1426 		/* If there's goods waiting at the station, and the vehicle
  1392 		 * has capacity for it, load it on the vehicle. */
  1427 		 * has capacity for it, load it on the vehicle. */
  1393 		if (count != 0 &&
  1428 		if (count != 0 &&
  1394 				(cap = v->cargo_cap - v->cargo_count) != 0) {
  1429 				(cap = v->cargo_cap - v->cargo_count) != 0) {
  1395 
  1430 
  1396 			if (v->cargo_count == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
       
  1397 
       
  1398 			/* Skip loading this vehicle if another train/vehicle is already handling
  1431 			/* Skip loading this vehicle if another train/vehicle is already handling
  1399 			 * the same cargo type at this station */
  1432 			 * the same cargo type at this station */
  1400 			if (_patches.improved_load && (u->current_order.flags & OF_FULL_LOAD) && LoadWait(v,u)) continue;
  1433 			if (_patches.improved_load && cargo_left[v->cargo_type] < 0) {
       
  1434 				SETBIT(cargo_not_full, v->cargo_type);
       
  1435 				continue;
       
  1436 			}
       
  1437 
       
  1438 			if (cap > count) cap = count;
       
  1439 			if (_patches.gradual_loading) cap = min(cap, load_amount);
       
  1440 			if (_patches.improved_load) {
       
  1441 				/* Don't load stuff that is already 'reserved' for other vehicles */
       
  1442 				cap = min(cargo_left[v->cargo_type], cap);
       
  1443 				cargo_left[v->cargo_type] -= cap;
       
  1444 			}
       
  1445 
       
  1446 			if (v->cargo_count == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
  1401 
  1447 
  1402 			/* TODO: Regarding this, when we do gradual loading, we
  1448 			/* TODO: Regarding this, when we do gradual loading, we
  1403 			 * should first unload all vehicles and then start
  1449 			 * should first unload all vehicles and then start
  1404 			 * loading them. Since this will cause
  1450 			 * loading them. Since this will cause
  1405 			 * VEHICLE_TRIGGER_EMPTY to be called at the time when
  1451 			 * VEHICLE_TRIGGER_EMPTY to be called at the time when
  1407 			 * completely_empty assignment can then be safely
  1453 			 * completely_empty assignment can then be safely
  1408 			 * removed; that's how TTDPatch behaves too. --pasky */
  1454 			 * removed; that's how TTDPatch behaves too. --pasky */
  1409 			completely_empty = false;
  1455 			completely_empty = false;
  1410 			anything_loaded = true;
  1456 			anything_loaded = true;
  1411 
  1457 
  1412 			if (cap > count) cap = count;
       
  1413 			if (_patches.gradual_loading) cap = min(cap, load_amount);
       
  1414 			if (cap < count) CLRBIT(u->vehicle_flags, VF_LOADING_FINISHED);
       
  1415 
       
  1416 			/* cargoshare is proportioned by the amount due to unload
  1458 			/* cargoshare is proportioned by the amount due to unload
  1417 			 * Otherwise, with gradual loading, 100% of credits would be taken immediately,
  1459 			 * Otherwise, with gradual loading, 100% of credits would be taken immediately,
  1418 			 * even if the cargo volume represents a tiny percent of the whole.
  1460 			 * even if the cargo volume represents a tiny percent of the whole.
  1419 			 * ge->unload_pending holds the amount that has been credited, but has not yet been unloaded.
  1461 			 * ge->unload_pending holds the amount that has been credited, but has not yet been unloaded.
  1420 			 */
  1462 			 */
  1435 			v->cargo_source_xy = ge->enroute_from_xy;
  1477 			v->cargo_source_xy = ge->enroute_from_xy;
  1436 			v->cargo_days = ge->enroute_time;
  1478 			v->cargo_days = ge->enroute_time;
  1437 			result |= 2;
  1479 			result |= 2;
  1438 			st->last_vehicle_type = v->type;
  1480 			st->last_vehicle_type = v->type;
  1439 		}
  1481 		}
       
  1482 
       
  1483 		if (v->cargo_count == v->cargo_cap) {
       
  1484 			SETBIT(cargo_full, v->cargo_type);
       
  1485 		} else {
       
  1486 			SETBIT(cargo_not_full, v->cargo_type);
       
  1487 		}
       
  1488 	}
       
  1489 
       
  1490 	/* We update these variables here, so gradual loading still fills
       
  1491 	 * all wagons at the same time instead of using the same 'improved'
       
  1492 	 * loading algorithm for the wagons (only fill wagon when there is
       
  1493 	 * enough to fill the previous wagons) */
       
  1494 	if (_patches.improved_load && HASBIT(u->current_order.flags, OFB_FULL_LOAD)) {
       
  1495 		/* Update left cargo */
       
  1496 		for (v = u; v != NULL; v = v->next) {
       
  1497 			if (v->cargo_cap != 0) cargo_left[v->cargo_type] -= v->cargo_cap - v->cargo_count;
       
  1498 		}
  1440 	}
  1499 	}
  1441 
  1500 
  1442 	v = u;
  1501 	v = u;
  1443 
  1502 
  1444 	/* Ensure a negative total is only applied to the vehicle if there is value to reduce. */
  1503 	v->cargo_feeder_share += total_cargo_feeder_share;
  1445 	if (!((v->cargo_feeder_share == 0) && (total_cargo_feeder_share < 0)))
  1504 
  1446 		v->cargo_feeder_share += total_cargo_feeder_share;
  1505 	if (anything_loaded || anything_unloaded) {
  1447 
  1506 		if (_patches.gradual_loading) {
  1448 	if (_patches.gradual_loading) {
  1507 			/* The time it takes to load one 'slice' of cargo or passengers depends
  1449 		/* The time it takes to load one 'slice' of cargo or passengers depends
  1508 			* on the vehicle type - the values here are those found in TTDPatch */
  1450 		 * on the vehicle type - the values here are those found in TTDPatch */
  1509 			const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
  1451 		uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
  1510 
  1452 
  1511 			unloading_time = gradual_loading_wait_time[v->type];
  1453 		unloading_time = gradual_loading_wait_time[v->type];
  1512 		}
  1454 		if (HASBIT(v->vehicle_flags, VF_LOADING_FINISHED)) {
  1513 	} else {
  1455 			if (anything_loaded) {
  1514 		bool finished_loading = true;
  1456 				unloading_time += 20;
  1515 		if (HASBIT(v->current_order.flags, OFB_FULL_LOAD)) {
  1457 			} else {
  1516 			if (_patches.full_load_any) {
  1458 				unloading_time = 20;
  1517 				/* if the aircraft carries passengers and is NOT full, then
  1459 			}
  1518 				 * continue loading, no matter how much mail is in */
  1460 		}
  1519 				if ((v->type == VEH_AIRCRAFT && IsCargoInClass(v->cargo_type, CC_PASSENGERS) && v->cargo_cap != v->cargo_count) ||
  1461 	}
  1520 						(cargo_not_full && (cargo_full & ~cargo_not_full) == 0)) { // There are stull non-full cargos
  1462 
  1521 					finished_loading = false;
  1463 	if (virtual_profit_total > 0) {
  1522 				}
  1464 		ShowFeederIncomeAnimation(v->x_pos, v->y_pos, v->z_pos, virtual_profit_total);
  1523 			} else if (cargo_not_full != 0) {
       
  1524 				finished_loading = false;
       
  1525 			}
       
  1526 		}
       
  1527 		unloading_time = 20;
       
  1528 
       
  1529 		SB(v->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
  1465 	}
  1530 	}
  1466 
  1531 
  1467 	if (v->type == VEH_TRAIN) {
  1532 	if (v->type == VEH_TRAIN) {
  1468 		/* Each platform tile is worth 2 rail vehicles. */
  1533 		/* Each platform tile is worth 2 rail vehicles. */
  1469 		int overhang = v->u.rail.cached_total_length - st->GetPlatformLength(v->tile) * TILE_SIZE;
  1534 		int overhang = v->u.rail.cached_total_length - st->GetPlatformLength(v->tile) * TILE_SIZE;
  1478 	if (completely_empty) {
  1543 	if (completely_empty) {
  1479 		TriggerVehicle(v, VEHICLE_TRIGGER_EMPTY);
  1544 		TriggerVehicle(v, VEHICLE_TRIGGER_EMPTY);
  1480 	}
  1545 	}
  1481 
  1546 
  1482 	if (result != 0) {
  1547 	if (result != 0) {
       
  1548 		InvalidateWindow(v->GetVehicleListWindowClass(), v->owner);
  1483 		InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
  1549 		InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
       
  1550 
  1484 		st->MarkTilesDirty();
  1551 		st->MarkTilesDirty();
       
  1552 		v->MarkDirty();
  1485 
  1553 
  1486 		if (result & 2) InvalidateWindow(WC_STATION_VIEW, last_visited);
  1554 		if (result & 2) InvalidateWindow(WC_STATION_VIEW, last_visited);
  1487 
  1555 	}
  1488 		if (route_profit != 0) {
  1556 }
  1489 			v->profit_this_year += total_veh_profit;
  1557 
  1490 			SubtractMoneyFromPlayer(-route_profit);
  1558 /**
  1491 
  1559  * Load/unload the vehicles in this station according to the order
  1492 			if (IsLocalPlayer() && !PlayVehicleSound(v, VSE_LOAD_UNLOAD)) {
  1560  * they entered.
  1493 				SndPlayVehicleFx(SND_14_CASHTILL, v);
  1561  * @param st the station to do the loading/unloading for
  1494 			}
  1562  */
  1495 
  1563 void LoadUnloadStation(Station *st)
  1496 			ShowCostOrIncomeAnimation(v->x_pos, v->y_pos, v->z_pos, -total_veh_profit);
  1564 {
  1497 		}
  1565 	int cargo_left[NUM_CARGO];
  1498 	}
  1566 
  1499 
  1567 	for (uint i = 0; i < NUM_CARGO; i++) cargo_left[i] = GB(st->goods[i].waiting_acceptance, 0, 12);
  1500 	_current_player = old_player;
  1568 
  1501 	return result;
  1569 	std::list<Vehicle *>::iterator iter;
       
  1570 	for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
       
  1571 		Vehicle *v = *iter;
       
  1572 		if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v, cargo_left);
       
  1573 	}
  1502 }
  1574 }
  1503 
  1575 
  1504 void PlayersMonthlyLoop()
  1576 void PlayersMonthlyLoop()
  1505 {
  1577 {
  1506 	PlayersGenStatistics();
  1578 	PlayersGenStatistics();