Changeset - r10207:a1fc2f2a33db
[Not reviewed]
master
! ! !
rubidium - 16 years ago 2008-09-30 20:39:50
rubidium@openttd.org
(svn r14421) -Codechange: rename all player variables/types to company *or* client so it is immediatelly clear which one you are working with.
18 files changed:
0 comments (0 inline, 0 general)
src/ai/ai.cpp
Show inline comments
 
@@ -16,16 +16,16 @@
 
#include "../signal_func.h"
 

	
 
AIStruct _ai;
 
AIPlayer _ai_player[MAX_PLAYERS];
 
AICompany _ai_company[MAX_COMPANIES];
 

	
 
/**
 
 * Dequeues commands put in the queue via AI_PutCommandInQueue.
 
 */
 
static void AI_DequeueCommands(PlayerID player)
 
static void AI_DequeueCommands(CompanyID company)
 
{
 
	AICommand *com, *entry_com;
 

	
 
	entry_com = _ai_player[player].queue;
 
	entry_com = _ai_company[company].queue;
 

	
 
	/* It happens that DoCommandP issues a new DoCommandAI which adds a new command
 
	 *  to this very same queue (don't argue about this, if it currently doesn't
 
@@ -33,12 +33,12 @@ static void AI_DequeueCommands(PlayerID 
 
	 *  do not make the queue NULL, that commands will be dequeued immediatly.
 
	 *  Therefor we safe the entry-point to entry_com, and make the queue NULL, so
 
	 *  the new queue can be safely built up. */
 
	_ai_player[player].queue = NULL;
 
	_ai_player[player].queue_tail = NULL;
 
	_ai_company[company].queue = NULL;
 
	_ai_company[company].queue_tail = NULL;
 

	
 
	/* Dequeue all commands */
 
	while ((com = entry_com) != NULL) {
 
		_current_player = player;
 
		_current_company = company;
 

	
 
		_cmd_text = com->text;
 
		DoCommandP(com->tile, com->p1, com->p2, com->callback, com->procc);
 
@@ -54,22 +54,22 @@ static void AI_DequeueCommands(PlayerID 
 
 * Needed for SP; we need to delay DoCommand with 1 tick, because else events
 
 *  will make infinite loops (AIScript).
 
 */
 
static void AI_PutCommandInQueue(PlayerID player, TileIndex tile, uint32 p1, uint32 p2, uint32 procc, CommandCallback* callback)
 
static void AI_PutCommandInQueue(CompanyID company, TileIndex tile, uint32 p1, uint32 p2, uint32 procc, CommandCallback* callback)
 
{
 
	AICommand *com;
 

	
 
	if (_ai_player[player].queue_tail == NULL) {
 
	if (_ai_company[company].queue_tail == NULL) {
 
		/* There is no item in the queue yet, create the queue */
 
		_ai_player[player].queue = MallocT<AICommand>(1);
 
		_ai_player[player].queue_tail = _ai_player[player].queue;
 
		_ai_company[company].queue = MallocT<AICommand>(1);
 
		_ai_company[company].queue_tail = _ai_company[company].queue;
 
	} else {
 
		/* Add an item at the end */
 
		_ai_player[player].queue_tail->next = MallocT<AICommand>(1);
 
		_ai_player[player].queue_tail = _ai_player[player].queue_tail->next;
 
		_ai_company[company].queue_tail->next = MallocT<AICommand>(1);
 
		_ai_company[company].queue_tail = _ai_company[company].queue_tail->next;
 
	}
 

	
 
	/* This is our new item */
 
	com = _ai_player[player].queue_tail;
 
	com = _ai_company[company].queue_tail;
 

	
 
	/* Assign the info */
 
	com->tile  = tile;
 
@@ -92,7 +92,7 @@ static void AI_PutCommandInQueue(PlayerI
 
 */
 
CommandCost AI_DoCommandCc(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint32 procc, CommandCallback* callback)
 
{
 
	PlayerID old_lp;
 
	CompanyID old_local_company;
 
	CommandCost res;
 
	const char* tmp_cmdtext;
 

	
 
@@ -113,10 +113,10 @@ CommandCost AI_DoCommandCc(TileIndex til
 
	/* Restore _cmd_text */
 
	_cmd_text = tmp_cmdtext;
 

	
 
	/* NetworkSend_Command needs _local_player to be set correctly, so
 
	/* NetworkSend_Command needs _local_company to be set correctly, so
 
	 * adjust it, and put it back right after the function */
 
	old_lp = _local_player;
 
	_local_player = _current_player;
 
	old_local_company = _local_company;
 
	_local_company = _current_company;
 

	
 
#ifdef ENABLE_NETWORK
 
	/* Send the command */
 
@@ -129,11 +129,11 @@ CommandCost AI_DoCommandCc(TileIndex til
 
#endif
 
		/* If we execute BuildCommands directly in SP, we have a big problem with events
 
		 *  so we need to delay is for 1 tick */
 
		AI_PutCommandInQueue(_current_player, tile, p1, p2, procc, callback);
 
		AI_PutCommandInQueue(_current_company, tile, p1, p2, procc, callback);
 
	}
 

	
 
	/* Set _local_player back */
 
	_local_player = old_lp;
 
	/* Set _local_company back */
 
	_local_company = old_local_company;
 

	
 
	return res;
 
}
 
@@ -148,20 +148,20 @@ CommandCost AI_DoCommand(TileIndex tile,
 
/**
 
 * Run 1 tick of the AI. Don't overdo it, keep it realistic.
 
 */
 
static void AI_RunTick(PlayerID player)
 
static void AI_RunTick(CompanyID company)
 
{
 
	extern void AiNewDoGameLoop(Player *p);
 
	extern void AiNewDoGameLoop(Company *c);
 

	
 
	Player *p = GetPlayer(player);
 
	_current_player = player;
 
	Company *c = GetCompany(company);
 
	_current_company = company;
 

	
 
	if (_settings_game.ai.ainew_active) {
 
		AiNewDoGameLoop(p);
 
		AiNewDoGameLoop(c);
 
	} else {
 
		/* Enable all kind of cheats the old AI needs in order to operate correctly... */
 
		_is_old_ai_player = true;
 
		AiDoGameLoop(p);
 
		_is_old_ai_player = false;
 
		_is_old_ai_company = true;
 
		AiDoGameLoop(c);
 
		_is_old_ai_company = false;
 
	}
 

	
 
	/* AI could change some track, so update signals */
 
@@ -191,47 +191,47 @@ void AI_RunGameLoop()
 
	/* Check for AI-client (so joining a network with an AI) */
 
	if (!_networking || _network_server) {
 
		/* Check if we want to run AIs (server or SP only) */
 
		const Player* p;
 
		const Company *c;
 

	
 
		FOR_ALL_PLAYERS(p) {
 
			if (p->is_ai) {
 
		FOR_ALL_COMPANIES(c) {
 
			if (c->is_ai) {
 
				/* This should always be true, else something went wrong... */
 
				assert(_ai_player[p->index].active);
 
				assert(_ai_company[c->index].active);
 

	
 
				/* Run the script */
 
				AI_DequeueCommands(p->index);
 
				AI_RunTick(p->index);
 
				AI_DequeueCommands(c->index);
 
				AI_RunTick(c->index);
 
			}
 
		}
 
	}
 

	
 
	_current_player = OWNER_NONE;
 
	_current_company = OWNER_NONE;
 
}
 

	
 
/**
 
 * A new AI sees the day of light. You can do here what ever you think is needed.
 
 */
 
void AI_StartNewAI(PlayerID player)
 
void AI_StartNewAI(CompanyID company)
 
{
 
	assert(IsValidPlayerID(player));
 
	assert(IsValidCompanyID(company));
 

	
 
	/* Called if a new AI is booted */
 
	_ai_player[player].active = true;
 
	_ai_company[company].active = true;
 
}
 

	
 
/**
 
 * This AI player died. Give it some chance to make a final puf.
 
 * This AI company died. Give it some chance to make a final puf.
 
 */
 
void AI_PlayerDied(PlayerID player)
 
void AI_CompanyDied(CompanyID company)
 
{
 
	/* Called if this AI died */
 
	_ai_player[player].active = false;
 
	_ai_company[company].active = false;
 

	
 
	if (_players_ainew[player].pathfinder == NULL) return;
 
	if (_companies_ainew[company].pathfinder == NULL) return;
 

	
 
	AyStarMain_Free(_players_ainew[player].pathfinder);
 
	delete _players_ainew[player].pathfinder;
 
	_players_ainew[player].pathfinder = NULL;
 
	AyStarMain_Free(_companies_ainew[company].pathfinder);
 
	delete _companies_ainew[company].pathfinder;
 
	_companies_ainew[company].pathfinder = NULL;
 

	
 
}
 

	
 
@@ -244,7 +244,7 @@ void AI_Initialize()
 
	AI_Uninitialize();
 

	
 
	memset(&_ai, 0, sizeof(_ai));
 
	memset(&_ai_player, 0, sizeof(_ai_player));
 
	memset(&_ai_company, 0, sizeof(_ai_company));
 

	
 
	_ai.enabled = true;
 
}
 
@@ -254,5 +254,5 @@ void AI_Initialize()
 
 */
 
void AI_Uninitialize()
 
{
 
	for (PlayerID p = PLAYER_FIRST; p < MAX_PLAYERS; p++) AI_PlayerDied(p);
 
	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) AI_CompanyDied(c);
 
}
src/ai/ai.h
Show inline comments
 
@@ -24,8 +24,8 @@ struct AICommand {
 
	AICommand *next;
 
};
 

	
 
/* The struct for an AIScript Player */
 
struct AIPlayer {
 
/* The struct for an AIScript Company */
 
struct AICompany {
 
	bool active;            ///< Is this AI active?
 
	AICommand *queue;       ///< The commands that he has in his queue
 
	AICommand *queue_tail;  ///< The tail of this queue
 
@@ -39,11 +39,11 @@ struct AIStruct {
 
};
 

	
 
extern AIStruct _ai;
 
extern AIPlayer _ai_player[MAX_PLAYERS];
 
extern AICompany _ai_company[MAX_COMPANIES];
 

	
 
// ai.c
 
void AI_StartNewAI(PlayerID player);
 
void AI_PlayerDied(PlayerID player);
 
void AI_StartNewAI(CompanyID company);
 
void AI_CompanyDied(CompanyID company);
 
void AI_RunGameLoop();
 
void AI_Initialize();
 
void AI_Uninitialize();
src/ai/default/default.cpp
Show inline comments
 
@@ -37,9 +37,9 @@
 

	
 
// remove some day perhaps?
 
static uint _ai_service_interval;
 
PlayerAI _players_ai[MAX_PLAYERS];
 

	
 
typedef void AiStateAction(Player *p);
 
CompanyAI _companies_ai[MAX_COMPANIES];
 

	
 
typedef void AiStateAction(Company *c);
 

	
 
enum {
 
	AIS_0                            =  0,
 
@@ -75,27 +75,27 @@ static inline TrackBits GetRailTrackStat
 
}
 

	
 

	
 
static void AiCase0(Player *p)
 
static void AiCase0(Company *c)
 
{
 
	_players_ai[p->index].state = AIS_REMOVE_TRACK;
 
	_players_ai[p->index].state_counter = 0;
 
	_companies_ai[c->index].state = AIS_REMOVE_TRACK;
 
	_companies_ai[c->index].state_counter = 0;
 
}
 

	
 
static void AiCase1(Player *p)
 
static void AiCase1(Company *c)
 
{
 
	_players_ai[p->index].cur_veh = NULL;
 
	_players_ai[p->index].state = AIS_VEH_LOOP;
 
	_companies_ai[c->index].cur_veh = NULL;
 
	_companies_ai[c->index].state = AIS_VEH_LOOP;
 
}
 

	
 
static void AiStateVehLoop(Player *p)
 
static void AiStateVehLoop(Company *c)
 
{
 
	Vehicle *v;
 
	uint index;
 

	
 
	index = (_players_ai[p->index].cur_veh == NULL) ? 0 : _players_ai[p->index].cur_veh->index + 1;
 
	index = (_companies_ai[c->index].cur_veh == NULL) ? 0 : _companies_ai[c->index].cur_veh->index + 1;
 

	
 
	FOR_ALL_VEHICLES_FROM(v, index) {
 
		if (v->owner != _current_player) continue;
 
		if (v->owner != _current_company) continue;
 

	
 
		if ((v->type == VEH_TRAIN && v->subtype == 0) ||
 
				v->type == VEH_ROAD ||
 
@@ -103,9 +103,9 @@ static void AiStateVehLoop(Player *p)
 
				v->type == VEH_SHIP) {
 
			/* replace engine? */
 
			if (v->type == VEH_TRAIN && v->engine_type < 3 &&
 
					(_price.build_railvehicle >> 3) < p->player_money) {
 
				_players_ai[p->index].state = AIS_VEH_CHECK_REPLACE_VEHICLE;
 
				_players_ai[p->index].cur_veh = v;
 
					(_price.build_railvehicle >> 3) < c->money) {
 
				_companies_ai[c->index].state = AIS_VEH_CHECK_REPLACE_VEHICLE;
 
				_companies_ai[c->index].cur_veh = v;
 
				return;
 
			}
 

	
 
@@ -113,9 +113,9 @@ static void AiStateVehLoop(Player *p)
 
			if (v->age >= 730 &&
 
					v->profit_last_year < _price.station_value * 5 * 256 &&
 
					v->profit_this_year < _price.station_value * 5 * 256) {
 
				_players_ai[p->index].state_counter = 0;
 
				_players_ai[p->index].state = AIS_SELL_VEHICLE;
 
				_players_ai[p->index].cur_veh = v;
 
				_companies_ai[c->index].state_counter = 0;
 
				_companies_ai[c->index].state = AIS_SELL_VEHICLE;
 
				_companies_ai[c->index].cur_veh = v;
 
				return;
 
			}
 

	
 
@@ -124,15 +124,15 @@ static void AiStateVehLoop(Player *p)
 
						v->age != 0 &&
 
						GetEngine(v->engine_type)->reliability < 35389
 
					)) {
 
				_players_ai[p->index].state = AIS_VEH_CHECK_REPLACE_VEHICLE;
 
				_players_ai[p->index].cur_veh = v;
 
				_companies_ai[c->index].state = AIS_VEH_CHECK_REPLACE_VEHICLE;
 
				_companies_ai[c->index].cur_veh = v;
 
				return;
 
			}
 
		}
 
	}
 

	
 
	_players_ai[p->index].state = AIS_WANT_NEW_ROUTE;
 
	_players_ai[p->index].state_counter = 0;
 
	_companies_ai[c->index].state = AIS_WANT_NEW_ROUTE;
 
	_companies_ai[c->index].state_counter = 0;
 
}
 

	
 
static EngineID AiChooseTrainToBuild(RailType railtype, Money money, byte flag, TileIndex tile)
 
@@ -148,7 +148,7 @@ static EngineID AiChooseTrainToBuild(Rai
 
		if (!IsCompatibleRail(rvi->railtype, railtype) ||
 
				rvi->railveh_type == RAILVEH_WAGON ||
 
				(rvi->railveh_type == RAILVEH_MULTIHEAD && flag & 1) ||
 
				!HasBit(e->player_avail, _current_player) ||
 
				!HasBit(e->company_avail, _current_company) ||
 
				e->reliability < 0x8A3D) {
 
			continue;
 
		}
 
@@ -176,7 +176,7 @@ static EngineID AiChooseRoadVehToBuild(C
 
		EngineID i = e->index;
 
		const RoadVehicleInfo *rvi = &e->u.road;
 

	
 
		if (!HasBit(e->player_avail, _current_player) || e->reliability < 0x8A3D) {
 
		if (!HasBit(e->company_avail, _current_company) || e->reliability < 0x8A3D) {
 
			continue;
 
		}
 

	
 
@@ -217,7 +217,7 @@ static EngineID AiChooseAircraftToBuild(
 
		EngineID i = e->index;
 
		const AircraftVehicleInfo *avi = &e->u.air;
 

	
 
		if (!HasBit(e->player_avail, _current_player) || e->reliability < 0x8A3D) {
 
		if (!HasBit(e->company_avail, _current_company) || e->reliability < 0x8A3D) {
 
			continue;
 
		}
 

	
 
@@ -233,12 +233,12 @@ static EngineID AiChooseAircraftToBuild(
 
	return best_veh_index;
 
}
 

	
 
static Money AiGetBasePrice(const Player* p)
 
static Money AiGetBasePrice(const Company *c)
 
{
 
	Money base = _price.station_value;
 

	
 
	// adjust base price when more expensive vehicles are available
 
	switch (_players_ai[p->index].railtype_to_use) {
 
	switch (_companies_ai[c->index].railtype_to_use) {
 
		default: NOT_REACHED();
 
		case RAILTYPE_RAIL:     break;
 
		case RAILTYPE_ELECTRIC: break;
 
@@ -249,15 +249,15 @@ static Money AiGetBasePrice(const Player
 
	return base;
 
}
 

	
 
static EngineID AiChooseRoadVehToReplaceWith(const Player* p, const Vehicle* v)
 
static EngineID AiChooseRoadVehToReplaceWith(const Company *c, const Vehicle *v)
 
{
 
	Money avail_money = p->player_money + v->value;
 
	Money avail_money = c->money + v->value;
 
	return AiChooseRoadVehToBuild(v->cargo_type, avail_money, v->tile);
 
}
 

	
 
static EngineID AiChooseAircraftToReplaceWith(const Player* p, const Vehicle* v)
 
static EngineID AiChooseAircraftToReplaceWith(const Company *c, const Vehicle *v)
 
{
 
	Money avail_money = p->player_money + v->value;
 
	Money avail_money = c->money + v->value;
 

	
 
	/* determine forbidden aircraft bits */
 
	byte forbidden = 0;
 
@@ -279,10 +279,10 @@ static EngineID AiChooseAircraftToReplac
 
	);
 
}
 

	
 
static EngineID AiChooseTrainToReplaceWith(const Player* p, const Vehicle* v)
 
static EngineID AiChooseTrainToReplaceWith(const Company *c, const Vehicle *v)
 
{
 
	Money avail_money = p->player_money + v->value;
 
	const Vehicle* u = v;
 
	Money avail_money = c->money + v->value;
 
	const Vehicle *u = v;
 
	int num = 0;
 

	
 
	while (++num, u->Next() != NULL) {
 
@@ -293,25 +293,25 @@ static EngineID AiChooseTrainToReplaceWi
 
	return AiChooseTrainToBuild(v->u.rail.railtype, avail_money, 0, v->tile);
 
}
 

	
 
static EngineID AiChooseShipToReplaceWith(const Player* p, const Vehicle* v)
 
static EngineID AiChooseShipToReplaceWith(const Company *p, const Vehicle *v)
 
{
 
	/* Ships are not implemented in this (broken) AI */
 
	return INVALID_ENGINE;
 
}
 

	
 
static void AiHandleGotoDepot(Player *p, int cmd)
 
static void AiHandleGotoDepot(Company *c, int cmd)
 
{
 
	if (!_players_ai[p->index].cur_veh->current_order.IsType(OT_GOTO_DEPOT))
 
		DoCommand(0, _players_ai[p->index].cur_veh->index, 0, DC_EXEC, cmd);
 

	
 
	if (++_players_ai[p->index].state_counter <= 1387) {
 
		_players_ai[p->index].state = AIS_VEH_DO_REPLACE_VEHICLE;
 
	if (!_companies_ai[c->index].cur_veh->current_order.IsType(OT_GOTO_DEPOT))
 
		DoCommand(0, _companies_ai[c->index].cur_veh->index, 0, DC_EXEC, cmd);
 

	
 
	if (++_companies_ai[c->index].state_counter <= 1387) {
 
		_companies_ai[c->index].state = AIS_VEH_DO_REPLACE_VEHICLE;
 
		return;
 
	}
 

	
 
	if (_players_ai[p->index].cur_veh->current_order.IsType(OT_GOTO_DEPOT)) {
 
		_players_ai[p->index].cur_veh->current_order.MakeDummy();
 
		InvalidateWindow(WC_VEHICLE_VIEW, _players_ai[p->index].cur_veh->index);
 
	if (_companies_ai[c->index].cur_veh->current_order.IsType(OT_GOTO_DEPOT)) {
 
		_companies_ai[c->index].cur_veh->current_order.MakeDummy();
 
		InvalidateWindow(WC_VEHICLE_VIEW, _companies_ai[c->index].cur_veh->index);
 
	}
 
}
 

	
 
@@ -325,19 +325,19 @@ static void AiRestoreVehicleOrders(Vehic
 
	}
 
}
 

	
 
static void AiHandleReplaceTrain(Player *p)
 
static void AiHandleReplaceTrain(Company *c)
 
{
 
	const Vehicle* v = _players_ai[p->index].cur_veh;
 
	const Vehicle* v = _companies_ai[c->index].cur_veh;
 
	BackuppedOrders orderbak;
 
	EngineID veh;
 

	
 
	// wait until the vehicle reaches the depot.
 
	if (!IsRailDepotTile(v->tile) || v->u.rail.track != TRACK_BIT_DEPOT || !(v->vehstatus & VS_STOPPED)) {
 
		AiHandleGotoDepot(p, CMD_SEND_TRAIN_TO_DEPOT);
 
		AiHandleGotoDepot(c, CMD_SEND_TRAIN_TO_DEPOT);
 
		return;
 
	}
 

	
 
	veh = AiChooseTrainToReplaceWith(p, v);
 
	veh = AiChooseTrainToReplaceWith(c, v);
 
	if (veh != INVALID_ENGINE) {
 
		TileIndex tile;
 

	
 
@@ -355,18 +355,18 @@ static void AiHandleReplaceTrain(Player 
 
	}
 
}
 

	
 
static void AiHandleReplaceRoadVeh(Player *p)
 
static void AiHandleReplaceRoadVeh(Company *c)
 
{
 
	const Vehicle* v = _players_ai[p->index].cur_veh;
 
	const Vehicle* v = _companies_ai[c->index].cur_veh;
 
	BackuppedOrders orderbak;
 
	EngineID veh;
 

	
 
	if (!v->IsStoppedInDepot()) {
 
		AiHandleGotoDepot(p, CMD_SEND_ROADVEH_TO_DEPOT);
 
		AiHandleGotoDepot(c, CMD_SEND_ROADVEH_TO_DEPOT);
 
		return;
 
	}
 

	
 
	veh = AiChooseRoadVehToReplaceWith(p, v);
 
	veh = AiChooseRoadVehToReplaceWith(c, v);
 
	if (veh != INVALID_ENGINE) {
 
		TileIndex tile;
 

	
 
@@ -384,18 +384,18 @@ static void AiHandleReplaceRoadVeh(Playe
 
	}
 
}
 

	
 
static void AiHandleReplaceAircraft(Player *p)
 
static void AiHandleReplaceAircraft(Company *c)
 
{
 
	const Vehicle* v = _players_ai[p->index].cur_veh;
 
	const Vehicle* v = _companies_ai[c->index].cur_veh;
 
	BackuppedOrders orderbak;
 
	EngineID veh;
 

	
 
	if (!v->IsStoppedInDepot()) {
 
		AiHandleGotoDepot(p, CMD_SEND_AIRCRAFT_TO_HANGAR);
 
		AiHandleGotoDepot(c, CMD_SEND_AIRCRAFT_TO_HANGAR);
 
		return;
 
	}
 

	
 
	veh = AiChooseAircraftToReplaceWith(p, v);
 
	veh = AiChooseAircraftToReplaceWith(c, v);
 
	if (veh != INVALID_ENGINE) {
 
		TileIndex tile;
 

	
 
@@ -413,12 +413,12 @@ static void AiHandleReplaceAircraft(Play
 
	}
 
}
 

	
 
static void AiHandleReplaceShip(Player *p)
 
static void AiHandleReplaceShip(Company *c)
 
{
 
	/* Ships are not implemented in this (broken) AI */
 
}
 

	
 
typedef EngineID CheckReplaceProc(const Player* p, const Vehicle* v);
 
typedef EngineID CheckReplaceProc(const Company *c, const Vehicle* v);
 

	
 
static CheckReplaceProc* const _veh_check_replace_proc[] = {
 
	AiChooseTrainToReplaceWith,
 
@@ -427,7 +427,7 @@ static CheckReplaceProc* const _veh_chec
 
	AiChooseAircraftToReplaceWith,
 
};
 

	
 
typedef void DoReplaceProc(Player *p);
 
typedef void DoReplaceProc(Company *c);
 
static DoReplaceProc* const _veh_do_replace_proc[] = {
 
	AiHandleReplaceTrain,
 
	AiHandleReplaceRoadVeh,
 
@@ -435,29 +435,29 @@ static DoReplaceProc* const _veh_do_repl
 
	AiHandleReplaceAircraft
 
};
 

	
 
static void AiStateCheckReplaceVehicle(Player *p)
 
static void AiStateCheckReplaceVehicle(Company *c)
 
{
 
	const Vehicle* v = _players_ai[p->index].cur_veh;
 
	const Vehicle* v = _companies_ai[c->index].cur_veh;
 

	
 
	if (!v->IsValid() ||
 
			v->owner != _current_player ||
 
			v->owner != _current_company ||
 
			v->type > VEH_SHIP ||
 
			_veh_check_replace_proc[v->type - VEH_TRAIN](p, v) == INVALID_ENGINE) {
 
		_players_ai[p->index].state = AIS_VEH_LOOP;
 
			_veh_check_replace_proc[v->type - VEH_TRAIN](c, v) == INVALID_ENGINE) {
 
		_companies_ai[c->index].state = AIS_VEH_LOOP;
 
	} else {
 
		_players_ai[p->index].state_counter = 0;
 
		_players_ai[p->index].state = AIS_VEH_DO_REPLACE_VEHICLE;
 
		_companies_ai[c->index].state_counter = 0;
 
		_companies_ai[c->index].state = AIS_VEH_DO_REPLACE_VEHICLE;
 
	}
 
}
 

	
 
static void AiStateDoReplaceVehicle(Player *p)
 
static void AiStateDoReplaceVehicle(Company *c)
 
{
 
	const Vehicle* v = _players_ai[p->index].cur_veh;
 

	
 
	_players_ai[p->index].state = AIS_VEH_LOOP;
 
	// vehicle is not owned by the player anymore, something went very wrong.
 
	if (!v->IsValid() || v->owner != _current_player) return;
 
	_veh_do_replace_proc[v->type - VEH_TRAIN](p);
 
	const Vehicle* v = _companies_ai[c->index].cur_veh;
 

	
 
	_companies_ai[c->index].state = AIS_VEH_LOOP;
 
	// vehicle is not owned by the company anymore, something went very wrong.
 
	if (!v->IsValid() || v->owner != _current_company) return;
 
	_veh_do_replace_proc[v->type - VEH_TRAIN](c);
 
}
 

	
 
struct FoundRoute {
 
@@ -620,7 +620,7 @@ static void AiFindRandomPassengerRoute(F
 
// Warn: depends on 'xy' being the first element in both Town and Industry
 
#define GET_TOWN_OR_INDUSTRY_TILE(p) (((Town*)(p))->xy)
 

	
 
static bool AiCheckIfRouteIsGood(Player *p, FoundRoute *fr, byte bitmask)
 
static bool AiCheckIfRouteIsGood(Company *c, FoundRoute *fr, byte bitmask)
 
{
 
	TileIndex from_tile, to_tile;
 
	Station *st;
 
@@ -634,7 +634,7 @@ static bool AiCheckIfRouteIsGood(Player 
 
	FOR_ALL_STATIONS(st) {
 
		int cur;
 

	
 
		if (st->owner != _current_player) continue;
 
		if (st->owner != _current_company) continue;
 
		cur = DistanceMax(from_tile, st->xy);
 
		if (cur < dist) dist = cur;
 
		cur = DistanceMax(to_tile, st->xy);
 
@@ -664,8 +664,8 @@ static bool AiCheckIfRouteIsGood(Player 
 
	/* Make sure distance to closest station is < min_distance tiles. */
 
	if (dist != 0xFFFF && dist > min_distance) return false;
 

	
 
	if (_players_ai[p->index].route_type_mask != 0 &&
 
			!(_players_ai[p->index].route_type_mask & bitmask) &&
 
	if (_companies_ai[c->index].route_type_mask != 0 &&
 
			!(_companies_ai[c->index].route_type_mask & bitmask) &&
 
			!Chance16(1, 5)) {
 
		return false;
 
	}
 
@@ -680,8 +680,8 @@ static bool AiCheckIfRouteIsGood(Player 
 
		}
 

	
 
		// Make sure it has a reasonably good rating
 
		if (from->ratings[_current_player] < -100 ||
 
				to->ratings[_current_player] < -100) {
 
		if (from->ratings[_current_company] < -100 ||
 
				to->ratings[_current_company] < -100) {
 
			return false;
 
		}
 
	} else {
 
@@ -693,7 +693,7 @@ static bool AiCheckIfRouteIsGood(Player 
 
		}
 
	}
 

	
 
	_players_ai[p->index].route_type_mask |= bitmask;
 
	_companies_ai[c->index].route_type_mask |= bitmask;
 
	return true;
 
}
 

	
 
@@ -712,7 +712,7 @@ static TileIndex AiGetPctTileBetween(Til
 
	);
 
}
 

	
 
static void AiWantLongIndustryRoute(Player *p)
 
static void AiWantLongIndustryRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -731,91 +731,91 @@ static void AiWantLongIndustryRoute(Play
 
		if (--i == 0) return;
 
	}
 

	
 
	if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 1)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 

	
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 9;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.unk6 = 1;
 
	_players_ai[p->index].src.unk7 = 0;
 
	_players_ai[p->index].src.buildcmd_a = 0x24;
 
	_players_ai[p->index].src.buildcmd_b = 0xFF;
 
	_players_ai[p->index].src.direction = AiGetDirectionBetweenTiles(
 
		_players_ai[p->index].src.spec_tile,
 
		_players_ai[p->index].dst.spec_tile
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 

	
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 9;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.unk6 = 1;
 
	_companies_ai[c->index].src.unk7 = 0;
 
	_companies_ai[c->index].src.buildcmd_a = 0x24;
 
	_companies_ai[c->index].src.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].src.direction = AiGetDirectionBetweenTiles(
 
		_companies_ai[c->index].src.spec_tile,
 
		_companies_ai[c->index].dst.spec_tile
 
	);
 
	_players_ai[p->index].src.cargo = fr.cargo | 0x80;
 
	_companies_ai[c->index].src.cargo = fr.cargo | 0x80;
 

	
 
	// Fill the dest field
 

	
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 9;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.unk6 = 1;
 
	_players_ai[p->index].dst.unk7 = 0;
 
	_players_ai[p->index].dst.buildcmd_a = 0x34;
 
	_players_ai[p->index].dst.buildcmd_b = 0xFF;
 
	_players_ai[p->index].dst.direction = AiGetDirectionBetweenTiles(
 
		_players_ai[p->index].dst.spec_tile,
 
		_players_ai[p->index].src.spec_tile
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 9;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.unk6 = 1;
 
	_companies_ai[c->index].dst.unk7 = 0;
 
	_companies_ai[c->index].dst.buildcmd_a = 0x34;
 
	_companies_ai[c->index].dst.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].dst.direction = AiGetDirectionBetweenTiles(
 
		_companies_ai[c->index].dst.spec_tile,
 
		_companies_ai[c->index].src.spec_tile
 
	);
 
	_players_ai[p->index].dst.cargo = fr.cargo;
 
	_companies_ai[c->index].dst.cargo = fr.cargo;
 

	
 
	// Fill middle field 1
 
	_players_ai[p->index].mid1.spec_tile = AiGetPctTileBetween(
 
		_players_ai[p->index].src.spec_tile,
 
		_players_ai[p->index].dst.spec_tile,
 
	_companies_ai[c->index].mid1.spec_tile = AiGetPctTileBetween(
 
		_companies_ai[c->index].src.spec_tile,
 
		_companies_ai[c->index].dst.spec_tile,
 
		0x55
 
	);
 
	_players_ai[p->index].mid1.use_tile = 0;
 
	_players_ai[p->index].mid1.rand_rng = 6;
 
	_players_ai[p->index].mid1.cur_building_rule = 0xFF;
 
	_players_ai[p->index].mid1.unk6 = 2;
 
	_players_ai[p->index].mid1.unk7 = 1;
 
	_players_ai[p->index].mid1.buildcmd_a = 0x30;
 
	_players_ai[p->index].mid1.buildcmd_b = 0xFF;
 
	_players_ai[p->index].mid1.direction = _players_ai[p->index].src.direction;
 
	_players_ai[p->index].mid1.cargo = fr.cargo;
 
	_companies_ai[c->index].mid1.use_tile = 0;
 
	_companies_ai[c->index].mid1.rand_rng = 6;
 
	_companies_ai[c->index].mid1.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].mid1.unk6 = 2;
 
	_companies_ai[c->index].mid1.unk7 = 1;
 
	_companies_ai[c->index].mid1.buildcmd_a = 0x30;
 
	_companies_ai[c->index].mid1.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].mid1.direction = _companies_ai[c->index].src.direction;
 
	_companies_ai[c->index].mid1.cargo = fr.cargo;
 

	
 
	// Fill middle field 2
 
	_players_ai[p->index].mid2.spec_tile = AiGetPctTileBetween(
 
		_players_ai[p->index].src.spec_tile,
 
		_players_ai[p->index].dst.spec_tile,
 
	_companies_ai[c->index].mid2.spec_tile = AiGetPctTileBetween(
 
		_companies_ai[c->index].src.spec_tile,
 
		_companies_ai[c->index].dst.spec_tile,
 
		0xAA
 
	);
 
	_players_ai[p->index].mid2.use_tile = 0;
 
	_players_ai[p->index].mid2.rand_rng = 6;
 
	_players_ai[p->index].mid2.cur_building_rule = 0xFF;
 
	_players_ai[p->index].mid2.unk6 = 2;
 
	_players_ai[p->index].mid2.unk7 = 1;
 
	_players_ai[p->index].mid2.buildcmd_a = 0xFF;
 
	_players_ai[p->index].mid2.buildcmd_b = 0xFF;
 
	_players_ai[p->index].mid2.direction = _players_ai[p->index].dst.direction;
 
	_players_ai[p->index].mid2.cargo = fr.cargo;
 
	_companies_ai[c->index].mid2.use_tile = 0;
 
	_companies_ai[c->index].mid2.rand_rng = 6;
 
	_companies_ai[c->index].mid2.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].mid2.unk6 = 2;
 
	_companies_ai[c->index].mid2.unk7 = 1;
 
	_companies_ai[c->index].mid2.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].mid2.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].mid2.direction = _companies_ai[c->index].dst.direction;
 
	_companies_ai[c->index].mid2.cargo = fr.cargo;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = fr.cargo;
 
	_players_ai[p->index].num_wagons = 3;
 
	_players_ai[p->index].build_kind = 2;
 
	_players_ai[p->index].num_build_rec = 4;
 
	_players_ai[p->index].num_loco_to_build = 2;
 
	_players_ai[p->index].num_want_fullload = 2;
 
	_players_ai[p->index].wagon_list[0] = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 

	
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = fr.cargo;
 
	_companies_ai[c->index].num_wagons = 3;
 
	_companies_ai[c->index].build_kind = 2;
 
	_companies_ai[c->index].num_build_rec = 4;
 
	_companies_ai[c->index].num_loco_to_build = 2;
 
	_companies_ai[c->index].num_want_fullload = 2;
 
	_companies_ai[c->index].wagon_list[0] = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 

	
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantMediumIndustryRoute(Player *p)
 
static void AiWantMediumIndustryRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -834,56 +834,56 @@ static void AiWantMediumIndustryRoute(Pl
 
		if (--i == 0) return;
 
	}
 

	
 
	if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 1)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 9;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.unk6 = 1;
 
	_players_ai[p->index].src.unk7 = 0;
 
	_players_ai[p->index].src.buildcmd_a = 0x10;
 
	_players_ai[p->index].src.buildcmd_b = 0xFF;
 
	_players_ai[p->index].src.direction = AiGetDirectionBetweenTiles(
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 9;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.unk6 = 1;
 
	_companies_ai[c->index].src.unk7 = 0;
 
	_companies_ai[c->index].src.buildcmd_a = 0x10;
 
	_companies_ai[c->index].src.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].src.direction = AiGetDirectionBetweenTiles(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to)
 
	);
 
	_players_ai[p->index].src.cargo = fr.cargo | 0x80;
 
	_companies_ai[c->index].src.cargo = fr.cargo | 0x80;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 9;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.unk6 = 1;
 
	_players_ai[p->index].dst.unk7 = 0;
 
	_players_ai[p->index].dst.buildcmd_a = 0xFF;
 
	_players_ai[p->index].dst.buildcmd_b = 0xFF;
 
	_players_ai[p->index].dst.direction = AiGetDirectionBetweenTiles(
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 9;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.unk6 = 1;
 
	_companies_ai[c->index].dst.unk7 = 0;
 
	_companies_ai[c->index].dst.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].dst.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].dst.direction = AiGetDirectionBetweenTiles(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from)
 
	);
 
	_players_ai[p->index].dst.cargo = fr.cargo;
 
	_companies_ai[c->index].dst.cargo = fr.cargo;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = fr.cargo;
 
	_players_ai[p->index].num_wagons = 3;
 
	_players_ai[p->index].build_kind = 1;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 1;
 
	_players_ai[p->index].num_want_fullload = 1;
 
	_players_ai[p->index].wagon_list[0] = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = fr.cargo;
 
	_companies_ai[c->index].num_wagons = 3;
 
	_companies_ai[c->index].build_kind = 1;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 1;
 
	_companies_ai[c->index].num_want_fullload = 1;
 
	_companies_ai[c->index].wagon_list[0] = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantShortIndustryRoute(Player *p)
 
static void AiWantShortIndustryRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -902,56 +902,56 @@ static void AiWantShortIndustryRoute(Pla
 
		if (--i == 0) return;
 
	}
 

	
 
	if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 1)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 9;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.unk6 = 1;
 
	_players_ai[p->index].src.unk7 = 0;
 
	_players_ai[p->index].src.buildcmd_a = 0x10;
 
	_players_ai[p->index].src.buildcmd_b = 0xFF;
 
	_players_ai[p->index].src.direction = AiGetDirectionBetweenTiles(
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 9;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.unk6 = 1;
 
	_companies_ai[c->index].src.unk7 = 0;
 
	_companies_ai[c->index].src.buildcmd_a = 0x10;
 
	_companies_ai[c->index].src.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].src.direction = AiGetDirectionBetweenTiles(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to)
 
	);
 
	_players_ai[p->index].src.cargo = fr.cargo | 0x80;
 
	_companies_ai[c->index].src.cargo = fr.cargo | 0x80;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 9;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.unk6 = 1;
 
	_players_ai[p->index].dst.unk7 = 0;
 
	_players_ai[p->index].dst.buildcmd_a = 0xFF;
 
	_players_ai[p->index].dst.buildcmd_b = 0xFF;
 
	_players_ai[p->index].dst.direction = AiGetDirectionBetweenTiles(
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 9;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.unk6 = 1;
 
	_companies_ai[c->index].dst.unk7 = 0;
 
	_companies_ai[c->index].dst.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].dst.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].dst.direction = AiGetDirectionBetweenTiles(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from)
 
	);
 
	_players_ai[p->index].dst.cargo = fr.cargo;
 
	_companies_ai[c->index].dst.cargo = fr.cargo;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = fr.cargo;
 
	_players_ai[p->index].num_wagons = 2;
 
	_players_ai[p->index].build_kind = 1;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 1;
 
	_players_ai[p->index].num_want_fullload = 1;
 
	_players_ai[p->index].wagon_list[0] = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = fr.cargo;
 
	_companies_ai[c->index].num_wagons = 2;
 
	_companies_ai[c->index].build_kind = 1;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 1;
 
	_companies_ai[c->index].num_want_fullload = 1;
 
	_companies_ai[c->index].wagon_list[0] = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantMailRoute(Player *p)
 
static void AiWantMailRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -971,88 +971,88 @@ static void AiWantMailRoute(Player *p)
 
	}
 

	
 
	fr.cargo = CT_MAIL;
 
	if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 1)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 7;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.unk6 = 1;
 
	_players_ai[p->index].src.unk7 = 0;
 
	_players_ai[p->index].src.buildcmd_a = 0x24;
 
	_players_ai[p->index].src.buildcmd_b = 0xFF;
 
	_players_ai[p->index].src.direction = AiGetDirectionBetweenTiles(
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 7;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.unk6 = 1;
 
	_companies_ai[c->index].src.unk7 = 0;
 
	_companies_ai[c->index].src.buildcmd_a = 0x24;
 
	_companies_ai[c->index].src.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].src.direction = AiGetDirectionBetweenTiles(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to)
 
	);
 
	_players_ai[p->index].src.cargo = fr.cargo;
 
	_companies_ai[c->index].src.cargo = fr.cargo;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 7;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.unk6 = 1;
 
	_players_ai[p->index].dst.unk7 = 0;
 
	_players_ai[p->index].dst.buildcmd_a = 0x34;
 
	_players_ai[p->index].dst.buildcmd_b = 0xFF;
 
	_players_ai[p->index].dst.direction = AiGetDirectionBetweenTiles(
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 7;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.unk6 = 1;
 
	_companies_ai[c->index].dst.unk7 = 0;
 
	_companies_ai[c->index].dst.buildcmd_a = 0x34;
 
	_companies_ai[c->index].dst.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].dst.direction = AiGetDirectionBetweenTiles(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from)
 
	);
 
	_players_ai[p->index].dst.cargo = fr.cargo;
 
	_companies_ai[c->index].dst.cargo = fr.cargo;
 

	
 
	// Fill middle field 1
 
	_players_ai[p->index].mid1.spec_tile = AiGetPctTileBetween(
 
	_companies_ai[c->index].mid1.spec_tile = AiGetPctTileBetween(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to),
 
		0x55
 
	);
 
	_players_ai[p->index].mid1.use_tile = 0;
 
	_players_ai[p->index].mid1.rand_rng = 6;
 
	_players_ai[p->index].mid1.cur_building_rule = 0xFF;
 
	_players_ai[p->index].mid1.unk6 = 2;
 
	_players_ai[p->index].mid1.unk7 = 1;
 
	_players_ai[p->index].mid1.buildcmd_a = 0x30;
 
	_players_ai[p->index].mid1.buildcmd_b = 0xFF;
 
	_players_ai[p->index].mid1.direction = _players_ai[p->index].src.direction;
 
	_players_ai[p->index].mid1.cargo = fr.cargo;
 
	_companies_ai[c->index].mid1.use_tile = 0;
 
	_companies_ai[c->index].mid1.rand_rng = 6;
 
	_companies_ai[c->index].mid1.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].mid1.unk6 = 2;
 
	_companies_ai[c->index].mid1.unk7 = 1;
 
	_companies_ai[c->index].mid1.buildcmd_a = 0x30;
 
	_companies_ai[c->index].mid1.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].mid1.direction = _companies_ai[c->index].src.direction;
 
	_companies_ai[c->index].mid1.cargo = fr.cargo;
 

	
 
	// Fill middle field 2
 
	_players_ai[p->index].mid2.spec_tile = AiGetPctTileBetween(
 
	_companies_ai[c->index].mid2.spec_tile = AiGetPctTileBetween(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to),
 
		0xAA
 
	);
 
	_players_ai[p->index].mid2.use_tile = 0;
 
	_players_ai[p->index].mid2.rand_rng = 6;
 
	_players_ai[p->index].mid2.cur_building_rule = 0xFF;
 
	_players_ai[p->index].mid2.unk6 = 2;
 
	_players_ai[p->index].mid2.unk7 = 1;
 
	_players_ai[p->index].mid2.buildcmd_a = 0xFF;
 
	_players_ai[p->index].mid2.buildcmd_b = 0xFF;
 
	_players_ai[p->index].mid2.direction = _players_ai[p->index].dst.direction;
 
	_players_ai[p->index].mid2.cargo = fr.cargo;
 
	_companies_ai[c->index].mid2.use_tile = 0;
 
	_companies_ai[c->index].mid2.rand_rng = 6;
 
	_companies_ai[c->index].mid2.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].mid2.unk6 = 2;
 
	_companies_ai[c->index].mid2.unk7 = 1;
 
	_companies_ai[c->index].mid2.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].mid2.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].mid2.direction = _companies_ai[c->index].dst.direction;
 
	_companies_ai[c->index].mid2.cargo = fr.cargo;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = fr.cargo;
 
	_players_ai[p->index].num_wagons = 3;
 
	_players_ai[p->index].build_kind = 2;
 
	_players_ai[p->index].num_build_rec = 4;
 
	_players_ai[p->index].num_loco_to_build = 2;
 
	_players_ai[p->index].num_want_fullload = 0;
 
	_players_ai[p->index].wagon_list[0] = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = fr.cargo;
 
	_companies_ai[c->index].num_wagons = 3;
 
	_companies_ai[c->index].build_kind = 2;
 
	_companies_ai[c->index].num_build_rec = 4;
 
	_companies_ai[c->index].num_loco_to_build = 2;
 
	_companies_ai[c->index].num_want_fullload = 0;
 
	_companies_ai[c->index].wagon_list[0] = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantPassengerRoute(Player *p)
 
static void AiWantPassengerRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -1072,75 +1072,75 @@ static void AiWantPassengerRoute(Player 
 
	}
 

	
 
	fr.cargo = CT_PASSENGERS;
 
	if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 1)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 7;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.unk6 = 1;
 
	_players_ai[p->index].src.unk7 = 0;
 
	_players_ai[p->index].src.buildcmd_a = 0x10;
 
	_players_ai[p->index].src.buildcmd_b = 0xFF;
 
	_players_ai[p->index].src.direction = AiGetDirectionBetweenTiles(
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 7;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.unk6 = 1;
 
	_companies_ai[c->index].src.unk7 = 0;
 
	_companies_ai[c->index].src.buildcmd_a = 0x10;
 
	_companies_ai[c->index].src.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].src.direction = AiGetDirectionBetweenTiles(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to)
 
	);
 
	_players_ai[p->index].src.cargo = fr.cargo;
 
	_companies_ai[c->index].src.cargo = fr.cargo;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 7;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.unk6 = 1;
 
	_players_ai[p->index].dst.unk7 = 0;
 
	_players_ai[p->index].dst.buildcmd_a = 0xFF;
 
	_players_ai[p->index].dst.buildcmd_b = 0xFF;
 
	_players_ai[p->index].dst.direction = AiGetDirectionBetweenTiles(
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 7;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.unk6 = 1;
 
	_companies_ai[c->index].dst.unk7 = 0;
 
	_companies_ai[c->index].dst.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].dst.buildcmd_b = 0xFF;
 
	_companies_ai[c->index].dst.direction = AiGetDirectionBetweenTiles(
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.to),
 
		GET_TOWN_OR_INDUSTRY_TILE(fr.from)
 
	);
 
	_players_ai[p->index].dst.cargo = fr.cargo;
 
	_companies_ai[c->index].dst.cargo = fr.cargo;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = fr.cargo;
 
	_players_ai[p->index].num_wagons = 2;
 
	_players_ai[p->index].build_kind = 1;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 1;
 
	_players_ai[p->index].num_want_fullload = 0;
 
	_players_ai[p->index].wagon_list[0] = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = fr.cargo;
 
	_companies_ai[c->index].num_wagons = 2;
 
	_companies_ai[c->index].build_kind = 1;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 1;
 
	_companies_ai[c->index].num_want_fullload = 0;
 
	_companies_ai[c->index].wagon_list[0] = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantTrainRoute(Player *p)
 
static void AiWantTrainRoute(Company *c)
 
{
 
	uint16 r = GB(Random(), 0, 16);
 

	
 
	_players_ai[p->index].railtype_to_use = GetBestRailtype(p->index);
 
	_companies_ai[c->index].railtype_to_use = GetBestRailtype(c->index);
 

	
 
	if (r > 0xD000) {
 
		AiWantLongIndustryRoute(p);
 
		AiWantLongIndustryRoute(c);
 
	} else if (r > 0x6000) {
 
		AiWantMediumIndustryRoute(p);
 
		AiWantMediumIndustryRoute(c);
 
	} else if (r > 0x1000) {
 
		AiWantShortIndustryRoute(p);
 
		AiWantShortIndustryRoute(c);
 
	} else if (r > 0x800) {
 
		AiWantPassengerRoute(p);
 
		AiWantPassengerRoute(c);
 
	} else {
 
		AiWantMailRoute(p);
 
		AiWantMailRoute(c);
 
	}
 
}
 

	
 
static void AiWantLongRoadIndustryRoute(Player *p)
 
static void AiWantLongRoadIndustryRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -1159,44 +1159,44 @@ static void AiWantLongRoadIndustryRoute(
 
		if (--i == 0) return;
 
	}
 

	
 
	if (!AiCheckIfRouteIsGood(p, &fr, 2)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 2)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 9;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.buildcmd_a = 1;
 
	_players_ai[p->index].src.direction = 0;
 
	_players_ai[p->index].src.cargo = fr.cargo | 0x80;
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 9;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.buildcmd_a = 1;
 
	_companies_ai[c->index].src.direction = 0;
 
	_companies_ai[c->index].src.cargo = fr.cargo | 0x80;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 9;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.buildcmd_a = 0xFF;
 
	_players_ai[p->index].dst.direction = 0;
 
	_players_ai[p->index].dst.cargo = fr.cargo;
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 9;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].dst.direction = 0;
 
	_companies_ai[c->index].dst.cargo = fr.cargo;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = fr.cargo;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 5;
 
	_players_ai[p->index].num_want_fullload = 5;
 

	
 
//	_players_ai[p->index].loco_id = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 

	
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = fr.cargo;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 5;
 
	_companies_ai[c->index].num_want_fullload = 5;
 

	
 
//	_companies_ai[c->index].loco_id = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 

	
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantMediumRoadIndustryRoute(Player *p)
 
static void AiWantMediumRoadIndustryRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -1215,44 +1215,44 @@ static void AiWantMediumRoadIndustryRout
 
		if (--i == 0) return;
 
	}
 

	
 
	if (!AiCheckIfRouteIsGood(p, &fr, 2)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 2)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 9;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.buildcmd_a = 1;
 
	_players_ai[p->index].src.direction = 0;
 
	_players_ai[p->index].src.cargo = fr.cargo | 0x80;
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 9;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.buildcmd_a = 1;
 
	_companies_ai[c->index].src.direction = 0;
 
	_companies_ai[c->index].src.cargo = fr.cargo | 0x80;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 9;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.buildcmd_a = 0xFF;
 
	_players_ai[p->index].dst.direction = 0;
 
	_players_ai[p->index].dst.cargo = fr.cargo;
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 9;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].dst.direction = 0;
 
	_companies_ai[c->index].dst.cargo = fr.cargo;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = fr.cargo;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 3;
 
	_players_ai[p->index].num_want_fullload = 3;
 

	
 
//	_players_ai[p->index].loco_id = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 

	
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = fr.cargo;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 3;
 
	_companies_ai[c->index].num_want_fullload = 3;
 

	
 
//	_companies_ai[c->index].loco_id = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 

	
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantLongRoadPassengerRoute(Player *p)
 
static void AiWantLongRoadPassengerRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -1273,44 +1273,44 @@ static void AiWantLongRoadPassengerRoute
 

	
 
	fr.cargo = CT_PASSENGERS;
 

	
 
	if (!AiCheckIfRouteIsGood(p, &fr, 2)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 2)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 10;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.buildcmd_a = 1;
 
	_players_ai[p->index].src.direction = 0;
 
	_players_ai[p->index].src.cargo = CT_PASSENGERS;
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 10;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.buildcmd_a = 1;
 
	_companies_ai[c->index].src.direction = 0;
 
	_companies_ai[c->index].src.cargo = CT_PASSENGERS;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 10;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.buildcmd_a = 0xFF;
 
	_players_ai[p->index].dst.direction = 0;
 
	_players_ai[p->index].dst.cargo = CT_PASSENGERS;
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 10;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].dst.direction = 0;
 
	_companies_ai[c->index].dst.cargo = CT_PASSENGERS;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = CT_PASSENGERS;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 4;
 
	_players_ai[p->index].num_want_fullload = 0;
 

	
 
//	_players_ai[p->index].loco_id = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 

	
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = CT_PASSENGERS;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 4;
 
	_companies_ai[c->index].num_want_fullload = 0;
 

	
 
//	_companies_ai[c->index].loco_id = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 

	
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantPassengerRouteInsideTown(Player *p)
 
static void AiWantPassengerRouteInsideTown(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -1329,59 +1329,59 @@ static void AiWantPassengerRouteInsideTo
 
	fr.cargo = CT_PASSENGERS;
 
	fr.from = fr.to = t;
 

	
 
	if (!AiCheckIfRouteIsGood(p, &fr, 2)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 2)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = t->xy;
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 10;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.buildcmd_a = 1;
 
	_players_ai[p->index].src.direction = 0;
 
	_players_ai[p->index].src.cargo = CT_PASSENGERS;
 
	_companies_ai[c->index].src.spec_tile = t->xy;
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 10;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.buildcmd_a = 1;
 
	_companies_ai[c->index].src.direction = 0;
 
	_companies_ai[c->index].src.cargo = CT_PASSENGERS;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = t->xy;
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 10;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.buildcmd_a = 0xFF;
 
	_players_ai[p->index].dst.direction = 0;
 
	_players_ai[p->index].dst.cargo = CT_PASSENGERS;
 
	_companies_ai[c->index].dst.spec_tile = t->xy;
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 10;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.buildcmd_a = 0xFF;
 
	_companies_ai[c->index].dst.direction = 0;
 
	_companies_ai[c->index].dst.cargo = CT_PASSENGERS;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = CT_PASSENGERS;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 2;
 
	_players_ai[p->index].num_want_fullload = 0;
 

	
 
//	_players_ai[p->index].loco_id = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 

	
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
 
	_players_ai[p->index].state_mode = UCHAR_MAX;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = CT_PASSENGERS;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 2;
 
	_companies_ai[c->index].num_want_fullload = 0;
 

	
 
//	_companies_ai[c->index].loco_id = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 

	
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
 
	_companies_ai[c->index].state_mode = UCHAR_MAX;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantRoadRoute(Player *p)
 
static void AiWantRoadRoute(Company *c)
 
{
 
	uint16 r = GB(Random(), 0, 16);
 

	
 
	if (r > 0x4000) {
 
		AiWantLongRoadIndustryRoute(p);
 
		AiWantLongRoadIndustryRoute(c);
 
	} else if (r > 0x2000) {
 
		AiWantMediumRoadIndustryRoute(p);
 
		AiWantMediumRoadIndustryRoute(c);
 
	} else if (r > 0x1000) {
 
		AiWantLongRoadPassengerRoute(p);
 
		AiWantLongRoadPassengerRoute(c);
 
	} else {
 
		AiWantPassengerRouteInsideTown(p);
 
		AiWantPassengerRouteInsideTown(c);
 
	}
 
}
 

	
 
static void AiWantPassengerAircraftRoute(Player *p)
 
static void AiWantPassengerAircraftRoute(Company *c)
 
{
 
	FoundRoute fr;
 
	int i;
 
@@ -1389,7 +1389,7 @@ static void AiWantPassengerAircraftRoute
 
	/* Get aircraft that would be bought for this route
 
	 * (probably, as conditions may change before the route is fully built,
 
	 * like running out of money and having to select different aircraft, etc ...) */
 
	EngineID veh = AiChooseAircraftToBuild(p->player_money, _players_ai[p->index].build_kind != 0 ? AIR_CTOL : 0);
 
	EngineID veh = AiChooseAircraftToBuild(c->money, _companies_ai[c->index].build_kind != 0 ? AIR_CTOL : 0);
 

	
 
	/* No aircraft buildable mean no aircraft route */
 
	if (veh == INVALID_ENGINE) return;
 
@@ -1441,28 +1441,28 @@ static void AiWantPassengerAircraftRoute
 
	}
 

	
 
	fr.cargo = CT_PASSENGERS;
 
	if (!AiCheckIfRouteIsGood(p, &fr, 4)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 4)) return;
 

	
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 12;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.cargo = fr.cargo;
 
	_companies_ai[c->index].src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 12;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.cargo = fr.cargo;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 12;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.cargo = fr.cargo;
 
	_companies_ai[c->index].dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 12;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.cargo = fr.cargo;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = fr.cargo;
 
	_players_ai[p->index].build_kind = 0;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 1;
 
	_companies_ai[c->index].cargo_type = fr.cargo;
 
	_companies_ai[c->index].build_kind = 0;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 1;
 
	/* Using full load always may not be the best.
 
	 * Pick random value and rely on selling the vehicle & route
 
	 * afterwards if the choice was utterly wrong (or maybe altering the value if AI is improved)
 
@@ -1475,17 +1475,17 @@ static void AiWantPassengerAircraftRoute
 
	 * Also, non-full load is more resistant against starving (by building better stations
 
	 * or using exclusive rights)
 
	 */
 
	_players_ai[p->index].num_want_fullload = Chance16(1, 5); // 20% chance
 
//	_players_ai[p->index].loco_id = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 

	
 
	_players_ai[p->index].state = AIS_AIRPORT_STUFF;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].num_want_fullload = Chance16(1, 5); // 20% chance
 
//	_companies_ai[c->index].loco_id = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 

	
 
	_companies_ai[c->index].state = AIS_AIRPORT_STUFF;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantOilRigAircraftRoute(Player *p)
 
static void AiWantOilRigAircraftRoute(Company *c)
 
{
 
	int i;
 
	FoundRoute fr;
 
@@ -1512,57 +1512,57 @@ static void AiWantOilRigAircraftRoute(Pl
 
	fr.cargo = CT_PASSENGERS;
 
	fr.from = fr.to = t;
 

	
 
	if (!AiCheckIfRouteIsGood(p, &fr, 4)) return;
 
	if (!AiCheckIfRouteIsGood(c, &fr, 4)) return;
 

	
 
	// Fill the source field
 
	_players_ai[p->index].src.spec_tile = t->xy;
 
	_players_ai[p->index].src.use_tile = 0;
 
	_players_ai[p->index].src.rand_rng = 12;
 
	_players_ai[p->index].src.cur_building_rule = 0xFF;
 
	_players_ai[p->index].src.cargo = CT_PASSENGERS;
 
	_companies_ai[c->index].src.spec_tile = t->xy;
 
	_companies_ai[c->index].src.use_tile = 0;
 
	_companies_ai[c->index].src.rand_rng = 12;
 
	_companies_ai[c->index].src.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].src.cargo = CT_PASSENGERS;
 

	
 
	// Fill the dest field
 
	_players_ai[p->index].dst.spec_tile = in->xy;
 
	_players_ai[p->index].dst.use_tile = 0;
 
	_players_ai[p->index].dst.rand_rng = 5;
 
	_players_ai[p->index].dst.cur_building_rule = 0xFF;
 
	_players_ai[p->index].dst.cargo = CT_PASSENGERS;
 
	_companies_ai[c->index].dst.spec_tile = in->xy;
 
	_companies_ai[c->index].dst.use_tile = 0;
 
	_companies_ai[c->index].dst.rand_rng = 5;
 
	_companies_ai[c->index].dst.cur_building_rule = 0xFF;
 
	_companies_ai[c->index].dst.cargo = CT_PASSENGERS;
 

	
 
	// Fill common fields
 
	_players_ai[p->index].cargo_type = CT_PASSENGERS;
 
	_players_ai[p->index].build_kind = 1;
 
	_players_ai[p->index].num_build_rec = 2;
 
	_players_ai[p->index].num_loco_to_build = 1;
 
	_players_ai[p->index].num_want_fullload = 0;
 
//	_players_ai[p->index].loco_id = INVALID_VEHICLE;
 
	_players_ai[p->index].order_list_blocks[0] = 0;
 
	_players_ai[p->index].order_list_blocks[1] = 1;
 
	_players_ai[p->index].order_list_blocks[2] = 255;
 

	
 
	_players_ai[p->index].state = AIS_AIRPORT_STUFF;
 
	_players_ai[p->index].timeout_counter = 0;
 
	_companies_ai[c->index].cargo_type = CT_PASSENGERS;
 
	_companies_ai[c->index].build_kind = 1;
 
	_companies_ai[c->index].num_build_rec = 2;
 
	_companies_ai[c->index].num_loco_to_build = 1;
 
	_companies_ai[c->index].num_want_fullload = 0;
 
//	_companies_ai[c->index].loco_id = INVALID_VEHICLE;
 
	_companies_ai[c->index].order_list_blocks[0] = 0;
 
	_companies_ai[c->index].order_list_blocks[1] = 1;
 
	_companies_ai[c->index].order_list_blocks[2] = 255;
 

	
 
	_companies_ai[c->index].state = AIS_AIRPORT_STUFF;
 
	_companies_ai[c->index].timeout_counter = 0;
 
}
 

	
 
static void AiWantAircraftRoute(Player *p)
 
static void AiWantAircraftRoute(Company *c)
 
{
 
	uint16 r = (uint16)Random();
 

	
 
	if (r >= 0x2AAA || _date < 0x3912 + DAYS_TILL_ORIGINAL_BASE_YEAR) {
 
		AiWantPassengerAircraftRoute(p);
 
		AiWantPassengerAircraftRoute(c);
 
	} else {
 
		AiWantOilRigAircraftRoute(p);
 
		AiWantOilRigAircraftRoute(c);
 
	}
 
}
 

	
 

	
 

	
 
static void AiStateWantNewRoute(Player *p)
 
static void AiStateWantNewRoute(Company *c)
 
{
 
	uint16 r;
 
	int i;
 

	
 
	if (p->player_money < AiGetBasePrice(p) * 500) {
 
		_players_ai[p->index].state = AIS_0;
 
	if (c->money < AiGetBasePrice(c) * 500) {
 
		_companies_ai[c->index].state = AIS_0;
 
		return;
 
	}
 

	
 
@@ -1579,23 +1579,23 @@ static void AiStateWantNewRoute(Player *
 

	
 
		if (r < 0x7626) {
 
			if (_settings_game.ai.ai_disable_veh_train) continue;
 
			AiWantTrainRoute(p);
 
			AiWantTrainRoute(c);
 
		} else if (r < 0xC4EA) {
 
			if (_settings_game.ai.ai_disable_veh_roadveh) continue;
 
			AiWantRoadRoute(p);
 
			AiWantRoadRoute(c);
 
		} else if (r < 0xD89B) {
 
			if (_settings_game.ai.ai_disable_veh_aircraft) continue;
 
			AiWantAircraftRoute(p);
 
			AiWantAircraftRoute(c);
 
		} else {
 
			/* Ships are not implemented in this (broken) AI */
 
		}
 

	
 
		// got a route?
 
		if (_players_ai[p->index].state != AIS_WANT_NEW_ROUTE) break;
 
		if (_companies_ai[c->index].state != AIS_WANT_NEW_ROUTE) break;
 

	
 
		// time out?
 
		if (--i == 0) {
 
			if (++_players_ai[p->index].state_counter == 556) _players_ai[p->index].state = AIS_0;
 
			if (++_companies_ai[c->index].state_counter == 556) _companies_ai[c->index].state = AIS_0;
 
			break;
 
		}
 
	}
 
@@ -1725,7 +1725,7 @@ clear_town_stuff:;
 
	}
 

	
 
	if (!(flag & DC_EXEC)) {
 
		if (t != NULL && rating > t->ratings[_current_player]) {
 
		if (t != NULL && rating > t->ratings[_current_company]) {
 
			return CMD_ERROR;
 
		}
 
	}
 
@@ -1775,13 +1775,13 @@ static const byte _terraform_down_flags[
 

	
 
static void AiDoTerraformLand(TileIndex tile, DiagDirection dir, int unk, int mode)
 
{
 
	PlayerID old_player;
 
	CompanyID old_company;
 
	uint32 r;
 
	Slope slope;
 
	uint h;
 

	
 
	old_player = _current_player;
 
	_current_player = OWNER_NONE;
 
	old_company = _current_company;
 
	_current_company = OWNER_NONE;
 

	
 
	r = Random();
 

	
 
@@ -1810,10 +1810,10 @@ static void AiDoTerraformLand(TileIndex 
 
		}
 
	}
 

	
 
	_current_player = old_player;
 
	_current_company = old_company;
 
}
 

	
 
static void AiStateBuildDefaultRailBlocks(Player *p)
 
static void AiStateBuildDefaultRailBlocks(Company *c)
 
{
 
	uint i;
 
	int j;
 
@@ -1822,16 +1822,16 @@ static void AiStateBuildDefaultRailBlock
 
	CommandCost cost;
 

	
 
	// time out?
 
	if (++_players_ai[p->index].timeout_counter == 1388) {
 
		_players_ai[p->index].state = AIS_DELETE_RAIL_BLOCKS;
 
	if (++_companies_ai[c->index].timeout_counter == 1388) {
 
		_companies_ai[c->index].state = AIS_DELETE_RAIL_BLOCKS;
 
		return;
 
	}
 

	
 
	// do the following 8 times
 
	for (i = 0; i < 8; i++) {
 
		// check if we can build the default track
 
		aib = &_players_ai[p->index].src;
 
		j = _players_ai[p->index].num_build_rec;
 
		aib = &_companies_ai[c->index].src;
 
		j = _companies_ai[c->index].num_build_rec;
 
		do {
 
			// this item has already been built?
 
			if (aib->cur_building_rule != 255) continue;
 
@@ -1842,31 +1842,31 @@ static void AiStateBuildDefaultRailBlock
 

	
 
			// check if the track can be build there.
 
			rule = AiBuildDefaultRailTrack(aib->use_tile,
 
				_players_ai[p->index].build_kind, _players_ai[p->index].num_wagons,
 
				_companies_ai[c->index].build_kind, _companies_ai[c->index].num_wagons,
 
				aib->unk6, aib->unk7,
 
				aib->direction, aib->cargo,
 
				_players_ai[p->index].railtype_to_use,
 
				_companies_ai[c->index].railtype_to_use,
 
				&cost
 
			);
 

	
 
			if (rule == -1) {
 
				// cannot build, terraform after a while
 
				if (_players_ai[p->index].state_counter >= 600) {
 
					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)_players_ai[p->index].state_mode);
 
				if (_companies_ai[c->index].state_counter >= 600) {
 
					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)_companies_ai[c->index].state_mode);
 
				}
 
				// also try the other terraform direction
 
				if (++_players_ai[p->index].state_counter >= 1000) {
 
					_players_ai[p->index].state_counter = 0;
 
					_players_ai[p->index].state_mode = -_players_ai[p->index].state_mode;
 
				if (++_companies_ai[c->index].state_counter >= 1000) {
 
					_companies_ai[c->index].state_counter = 0;
 
					_companies_ai[c->index].state_mode = -_companies_ai[c->index].state_mode;
 
				}
 
			} else if (CheckPlayerHasMoney(cost)) {
 
				// player has money, build it.
 
			} else if (CheckCompanyHasMoney(cost)) {
 
				// company has money, build it.
 
				aib->cur_building_rule = rule;
 

	
 
				AiDoBuildDefaultRailTrack(
 
					aib->use_tile,
 
					_default_rail_track_data[rule]->data,
 
					_players_ai[p->index].railtype_to_use,
 
					_companies_ai[c->index].railtype_to_use,
 
					DC_EXEC | DC_NO_TOWN_RATING
 
				);
 
			}
 
@@ -1874,15 +1874,15 @@ static void AiStateBuildDefaultRailBlock
 
	}
 

	
 
	// check if we're done with all of them
 
	aib = &_players_ai[p->index].src;
 
	j = _players_ai[p->index].num_build_rec;
 
	aib = &_companies_ai[c->index].src;
 
	j = _companies_ai[c->index].num_build_rec;
 
	do {
 
		if (aib->cur_building_rule == 255) return;
 
	} while (++aib, --j);
 

	
 
	// yep, all are done. switch state to the rail building state.
 
	_players_ai[p->index].state = AIS_BUILD_RAIL;
 
	_players_ai[p->index].state_mode = 255;
 
	_companies_ai[c->index].state = AIS_BUILD_RAIL;
 
	_companies_ai[c->index].state_mode = 255;
 
}
 

	
 
static TileIndex AiGetEdgeOfDefaultRailBlock(byte rule, TileIndex tile, byte cmd, DiagDirection *dir)
 
@@ -1915,15 +1915,15 @@ static bool AiEnumFollowTrack(TileIndex 
 
	return false;
 
}
 

	
 
static bool AiDoFollowTrack(const Player* p)
 
static bool AiDoFollowTrack(const Company *c)
 
{
 
	AiRailPathFindData arpfd;
 

	
 
	arpfd.tile = _players_ai[p->index].start_tile_a;
 
	arpfd.tile2 = _players_ai[p->index].cur_tile_a;
 
	arpfd.tile = _companies_ai[c->index].start_tile_a;
 
	arpfd.tile2 = _companies_ai[c->index].cur_tile_a;
 
	arpfd.flag = false;
 
	arpfd.count = 0;
 
	FollowTrack(_players_ai[p->index].cur_tile_a + TileOffsByDiagDir(_players_ai[p->index].cur_dir_a), PATHFIND_FLAGS_NONE, TRANSPORT_RAIL, 0, ReverseDiagDir(_players_ai[p->index].cur_dir_a),
 
	FollowTrack(_companies_ai[c->index].cur_tile_a + TileOffsByDiagDir(_companies_ai[c->index].cur_dir_a), PATHFIND_FLAGS_NONE, TRANSPORT_RAIL, 0, ReverseDiagDir(_companies_ai[c->index].cur_dir_a),
 
		(TPFEnumProc*)AiEnumFollowTrack, NULL, &arpfd);
 
	return arpfd.count > 8;
 
}
 
@@ -1942,7 +1942,7 @@ struct AiRailFinder {
 
	uint best_dist;
 
	TileIndex cur_best_tile, best_tile;
 
	TileIndex bridge_end_tile;
 
	Player *player;
 
	Company *company;
 
};
 

	
 
static const byte _ai_table_15[4][8] = {
 
@@ -1953,32 +1953,32 @@ static const byte _ai_table_15[4][8] = {
 
};
 

	
 

	
 
static bool AiIsTileBanned(const Player* p, TileIndex tile, byte val)
 
static bool AiIsTileBanned(const Company *c, TileIndex tile, byte val)
 
{
 
	int i;
 

	
 
	for (i = 0; i != _players_ai[p->index].banned_tile_count; i++) {
 
		if (_players_ai[p->index].banned_tiles[i] == tile && _players_ai[p->index].banned_val[i] == val) {
 
	for (i = 0; i != _companies_ai[c->index].banned_tile_count; i++) {
 
		if (_companies_ai[c->index].banned_tiles[i] == tile && _companies_ai[c->index].banned_val[i] == val) {
 
			return true;
 
		}
 
	}
 
	return false;
 
}
 

	
 
static void AiBanTile(Player* p, TileIndex tile, byte val)
 
static void AiBanTile(Company *c, TileIndex tile, byte val)
 
{
 
	uint i;
 

	
 
	for (i = lengthof(_players_ai[p->index].banned_tiles) - 1; i != 0; i--) {
 
		_players_ai[p->index].banned_tiles[i] = _players_ai[p->index].banned_tiles[i - 1];
 
		_players_ai[p->index].banned_val[i] = _players_ai[p->index].banned_val[i - 1];
 
	for (i = lengthof(_companies_ai[c->index].banned_tiles) - 1; i != 0; i--) {
 
		_companies_ai[c->index].banned_tiles[i] = _companies_ai[c->index].banned_tiles[i - 1];
 
		_companies_ai[c->index].banned_val[i] = _companies_ai[c->index].banned_val[i - 1];
 
	}
 

	
 
	_players_ai[p->index].banned_tiles[0] = tile;
 
	_players_ai[p->index].banned_val[0] = val;
 

	
 
	if (_players_ai[p->index].banned_tile_count != lengthof(_players_ai[p->index].banned_tiles)) {
 
		_players_ai[p->index].banned_tile_count++;
 
	_companies_ai[c->index].banned_tiles[0] = tile;
 
	_companies_ai[c->index].banned_val[0] = val;
 

	
 
	if (_companies_ai[c->index].banned_tile_count != lengthof(_companies_ai[c->index].banned_tiles)) {
 
		_companies_ai[c->index].banned_tile_count++;
 
	}
 
}
 

	
 
@@ -2045,7 +2045,7 @@ static inline void AiCheckBuildRailBridg
 
		}
 

	
 
		// Is building a (rail)bridge possible at this place (type doesn't matter)?
 
		if (CmdFailed(DoCommand(tile_new, tile, _players_ai[arf->player->index].railtype_to_use << 8 | TRANSPORT_RAIL << 15, DC_AUTO, CMD_BUILD_BRIDGE))) {
 
		if (CmdFailed(DoCommand(tile_new, tile, _companies_ai[arf->company->index].railtype_to_use << 8 | TRANSPORT_RAIL << 15, DC_AUTO, CMD_BUILD_BRIDGE))) {
 
			return;
 
		}
 
		AiBuildRailRecursive(arf, tile_new, dir2);
 
@@ -2062,9 +2062,9 @@ static inline void AiCheckBuildRailTunne
 
	uint z;
 

	
 
	if (GetTileSlope(tile, &z) == InclinedSlope((DiagDirection)(p[0] & 3)) && z != 0) {
 
		CommandCost cost = DoCommand(tile, _players_ai[arf->player->index].railtype_to_use, 0, DC_AUTO, CMD_BUILD_TUNNEL);
 

	
 
		if (CmdSucceeded(cost) && cost.GetCost() <= (arf->player->player_money >> 4)) {
 
		CommandCost cost = DoCommand(tile, _companies_ai[arf->company->index].railtype_to_use, 0, DC_AUTO, CMD_BUILD_TUNNEL);
 

	
 
		if (CmdSucceeded(cost) && cost.GetCost() <= (arf->company->money >> 4)) {
 
			AiBuildRailRecursive(arf, _build_tunnel_endtile, (DiagDirection)(p[0] & 3));
 
			if (arf->depth == 1) AiCheckRailPathBetter(arf, p);
 
		}
 
@@ -2117,8 +2117,8 @@ static void AiBuildRailRecursive(AiRailF
 
	} else {
 
		do {
 
			// Make sure the tile is not in the list of banned tiles and that a rail can be built here.
 
			if (!AiIsTileBanned(arf->player, tile, p[0]) &&
 
					CmdSucceeded(DoCommand(tile, _players_ai[arf->player->index].railtype_to_use, p[0], DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL))) {
 
			if (!AiIsTileBanned(arf->company, tile, p[0]) &&
 
					CmdSucceeded(DoCommand(tile, _companies_ai[arf->company->index].railtype_to_use, p[0], DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL))) {
 
				AiBuildRailRecursive(arf, tile, (DiagDirection)p[1]);
 
			}
 

	
 
@@ -2136,25 +2136,25 @@ static void AiBuildRailRecursive(AiRailF
 
}
 

	
 

	
 
static void AiBuildRailConstruct(Player *p)
 
static void AiBuildRailConstruct(Company *c)
 
{
 
	AiRailFinder arf;
 
	int i;
 

	
 
	// Check too much lookahead?
 
	if (AiDoFollowTrack(p)) {
 
		_players_ai[p->index].state_counter = (Random()&0xE)+6; // Destruct this amount of blocks
 
		_players_ai[p->index].state_mode = 1; // Start destruct
 
	if (AiDoFollowTrack(c)) {
 
		_companies_ai[c->index].state_counter = (Random()&0xE)+6; // Destruct this amount of blocks
 
		_companies_ai[c->index].state_mode = 1; // Start destruct
 

	
 
		// Ban this tile and don't reach it for a while.
 
		AiBanTile(p, _players_ai[p->index].cur_tile_a, FindFirstBit(GetRailTrackStatus(_players_ai[p->index].cur_tile_a)));
 
		AiBanTile(c, _companies_ai[c->index].cur_tile_a, FindFirstBit(GetRailTrackStatus(_companies_ai[c->index].cur_tile_a)));
 
		return;
 
	}
 

	
 
	// Setup recursive finder and call it.
 
	arf.player = p;
 
	arf.final_tile = _players_ai[p->index].cur_tile_b;
 
	arf.final_dir = _players_ai[p->index].cur_dir_b;
 
	arf.company = c;
 
	arf.final_tile = _companies_ai[c->index].cur_tile_b;
 
	arf.final_dir = _companies_ai[c->index].cur_dir_b;
 
	arf.depth = 0;
 
	arf.recursive_mode = 0;
 
	arf.best_ptr = NULL;
 
@@ -2164,11 +2164,11 @@ static void AiBuildRailConstruct(Player 
 
	arf.best_depth = 0xff;
 
	arf.cur_best_tile = 0;
 
	arf.best_tile = 0;
 
	AiBuildRailRecursive(&arf, _players_ai[p->index].cur_tile_a, _players_ai[p->index].cur_dir_a);
 
	AiBuildRailRecursive(&arf, _companies_ai[c->index].cur_tile_a, _companies_ai[c->index].cur_dir_a);
 

	
 
	// Reached destination?
 
	if (arf.recursive_mode == 2 && arf.cur_best_depth == 0) {
 
		_players_ai[p->index].state_mode = 255;
 
		_companies_ai[c->index].state_mode = 255;
 
		return;
 
	}
 

	
 
@@ -2176,23 +2176,23 @@ static void AiBuildRailConstruct(Player 
 
	if (arf.best_ptr == NULL) {
 
		// Terraform some
 
		for (i = 0; i != 5; i++) {
 
			AiDoTerraformLand(_players_ai[p->index].cur_tile_a, _players_ai[p->index].cur_dir_a, 3, 0);
 
			AiDoTerraformLand(_companies_ai[c->index].cur_tile_a, _companies_ai[c->index].cur_dir_a, 3, 0);
 
		}
 

	
 
		if (++_players_ai[p->index].state_counter == 21) {
 
			_players_ai[p->index].state_counter = 40;
 
			_players_ai[p->index].state_mode = 1;
 
		if (++_companies_ai[c->index].state_counter == 21) {
 
			_companies_ai[c->index].state_counter = 40;
 
			_companies_ai[c->index].state_mode = 1;
 

	
 
			// Ban this tile
 
			AiBanTile(p, _players_ai[p->index].cur_tile_a, FindFirstBit(GetRailTrackStatus(_players_ai[p->index].cur_tile_a)));
 
			AiBanTile(c, _companies_ai[c->index].cur_tile_a, FindFirstBit(GetRailTrackStatus(_companies_ai[c->index].cur_tile_a)));
 
		}
 
		return;
 
	}
 

	
 
	_players_ai[p->index].cur_tile_a += TileOffsByDiagDir(_players_ai[p->index].cur_dir_a);
 
	_companies_ai[c->index].cur_tile_a += TileOffsByDiagDir(_companies_ai[c->index].cur_dir_a);
 

	
 
	if (arf.best_ptr[0] & 0x80) {
 
		TileIndex t1 = _players_ai[p->index].cur_tile_a;
 
		TileIndex t1 = _companies_ai[c->index].cur_tile_a;
 
		TileIndex t2 = arf.bridge_end_tile;
 

	
 
		int32 bridge_len = GetTunnelBridgeLength(t1, t2);
 
@@ -2209,7 +2209,7 @@ static void AiBuildRailConstruct(Player 
 

	
 
		/* try to build one rail on each tile - can't use CMD_BUILD_RAILROAD_TRACK now, it can build one part of track without failing */
 
		do {
 
			cost = DoCommand(t, _players_ai[p->index].railtype_to_use, track, DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL);
 
			cost = DoCommand(t, _companies_ai[c->index].railtype_to_use, track, DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL);
 
			/* do not allow building over existing track */
 
			if (CmdFailed(cost) || IsTileType(t, MP_RAILWAY)) {
 
				fail = true;
 
@@ -2219,10 +2219,10 @@ static void AiBuildRailConstruct(Player 
 
		} while (t != t2);
 

	
 
		/* can we build long track? */
 
		if (!fail) cost = DoCommand(t1, t2, _players_ai[p->index].railtype_to_use | (track << 4), DC_AUTO | DC_NO_WATER, CMD_BUILD_RAILROAD_TRACK);
 

	
 
		if (!fail && CmdSucceeded(cost) && cost.GetCost() <= p->player_money) {
 
			DoCommand(t1, t2, _players_ai[p->index].railtype_to_use | (track << 4), DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_BUILD_RAILROAD_TRACK);
 
		if (!fail) cost = DoCommand(t1, t2, _companies_ai[c->index].railtype_to_use | (track << 4), DC_AUTO | DC_NO_WATER, CMD_BUILD_RAILROAD_TRACK);
 

	
 
		if (!fail && CmdSucceeded(cost) && cost.GetCost() <= c->money) {
 
			DoCommand(t1, t2, _companies_ai[c->index].railtype_to_use | (track << 4), DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_BUILD_RAILROAD_TRACK);
 
		} else {
 

	
 
			/* Figure out which (rail)bridge type to build
 
@@ -2231,28 +2231,28 @@ static void AiBuildRailConstruct(Player 
 
			int i;
 
			for (i = MAX_BRIDGES - 1; i != 0; i--) {
 
				if (CheckBridge_Stuff(i, bridge_len)) {
 
					CommandCost cost = DoCommand(t1, t2, i | _players_ai[p->index].railtype_to_use << 8 | TRANSPORT_RAIL << 15, DC_AUTO, CMD_BUILD_BRIDGE);
 
					if (CmdSucceeded(cost) && cost.GetCost() < (p->player_money >> 1) && cost.GetCost() < ((p->player_money + _economy.max_loan - p->current_loan) >> 5)) break;
 
					CommandCost cost = DoCommand(t1, t2, i | _companies_ai[c->index].railtype_to_use << 8 | TRANSPORT_RAIL << 15, DC_AUTO, CMD_BUILD_BRIDGE);
 
					if (CmdSucceeded(cost) && cost.GetCost() < (c->money >> 1) && cost.GetCost() < ((c->money + _economy.max_loan - c->current_loan) >> 5)) break;
 
				}
 
			}
 

	
 
			/* Build it */
 
			DoCommand(t1, t2, i | _players_ai[p->index].railtype_to_use << 8 | TRANSPORT_RAIL << 15, DC_AUTO | DC_EXEC, CMD_BUILD_BRIDGE);
 
			DoCommand(t1, t2, i | _companies_ai[c->index].railtype_to_use << 8 | TRANSPORT_RAIL << 15, DC_AUTO | DC_EXEC, CMD_BUILD_BRIDGE);
 
		}
 

	
 
		_players_ai[p->index].cur_tile_a = t2;
 
		_players_ai[p->index].state_counter = 0;
 
		_companies_ai[c->index].cur_tile_a = t2;
 
		_companies_ai[c->index].state_counter = 0;
 
	} else if (arf.best_ptr[0] & 0x40) {
 
		// tunnel
 
		DoCommand(_players_ai[p->index].cur_tile_a, _players_ai[p->index].railtype_to_use, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
 
		_players_ai[p->index].cur_tile_a = _build_tunnel_endtile;
 
		_players_ai[p->index].state_counter = 0;
 
		DoCommand(_companies_ai[c->index].cur_tile_a, _companies_ai[c->index].railtype_to_use, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
 
		_companies_ai[c->index].cur_tile_a = _build_tunnel_endtile;
 
		_companies_ai[c->index].state_counter = 0;
 
	} else {
 
		// rail
 
		_players_ai[p->index].cur_dir_a = (DiagDirection)(arf.best_ptr[1] & 3);
 
		DoCommand(_players_ai[p->index].cur_tile_a, _players_ai[p->index].railtype_to_use, arf.best_ptr[0],
 
		_companies_ai[c->index].cur_dir_a = (DiagDirection)(arf.best_ptr[1] & 3);
 
		DoCommand(_companies_ai[c->index].cur_tile_a, _companies_ai[c->index].railtype_to_use, arf.best_ptr[0],
 
			DC_EXEC | DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL);
 
		_players_ai[p->index].state_counter = 0;
 
		_companies_ai[c->index].state_counter = 0;
 
	}
 

	
 
	if (arf.best_tile != 0) {
 
@@ -2262,10 +2262,10 @@ static void AiBuildRailConstruct(Player 
 
	}
 
}
 

	
 
static bool AiRemoveTileAndGoForward(Player *p)
 
static bool AiRemoveTileAndGoForward(Company *c)
 
{
 
	const byte *ptr;
 
	TileIndex tile = _players_ai[p->index].cur_tile_a;
 
	TileIndex tile = _companies_ai[c->index].cur_tile_a;
 
	TileIndex tilenew;
 

	
 
	if (IsTileType(tile, MP_TUNNELBRIDGE)) {
 
@@ -2273,26 +2273,26 @@ static bool AiRemoveTileAndGoForward(Pla
 
			// Clear the tunnel and continue at the other side of it.
 
			if (CmdFailed(DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR)))
 
				return false;
 
			_players_ai[p->index].cur_tile_a = TILE_MASK(_build_tunnel_endtile - TileOffsByDiagDir(_players_ai[p->index].cur_dir_a));
 
			_companies_ai[c->index].cur_tile_a = TILE_MASK(_build_tunnel_endtile - TileOffsByDiagDir(_companies_ai[c->index].cur_dir_a));
 
			return true;
 
		} else { // IsBridge(tile)
 
			// Check if the bridge points in the right direction.
 
			// This is not really needed the first place AiRemoveTileAndGoForward is called.
 
			if (DiagDirToAxis(GetTunnelBridgeDirection(tile)) != (_players_ai[p->index].cur_dir_a & 1)) return false;
 
			if (DiagDirToAxis(GetTunnelBridgeDirection(tile)) != (_companies_ai[c->index].cur_dir_a & 1)) return false;
 

	
 
			tile = GetOtherBridgeEnd(tile);
 

	
 
			tilenew = TILE_MASK(tile - TileOffsByDiagDir(_players_ai[p->index].cur_dir_a));
 
			tilenew = TILE_MASK(tile - TileOffsByDiagDir(_companies_ai[c->index].cur_dir_a));
 
			// And clear the bridge.
 
			if (CmdFailed(DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR)))
 
				return false;
 
			_players_ai[p->index].cur_tile_a = tilenew;
 
			_companies_ai[c->index].cur_tile_a = tilenew;
 
			return true;
 
		}
 
	}
 

	
 
	// Find the railtype at the position. Quit if no rail there.
 
	TrackBits bits = GetRailTrackStatus(tile) & DiagdirReachesTracks(ReverseDiagDir(_players_ai[p->index].cur_dir_a));
 
	TrackBits bits = GetRailTrackStatus(tile) & DiagdirReachesTracks(ReverseDiagDir(_companies_ai[c->index].cur_dir_a));
 
	if (bits == TRACK_BIT_NONE) return false;
 

	
 
	// Convert into a bit position that CMD_REMOVE_SINGLE_RAIL expects.
 
@@ -2309,41 +2309,41 @@ static bool AiRemoveTileAndGoForward(Pla
 
		return false;
 

	
 
	// Find the direction at the other edge of the rail.
 
	ptr = _ai_table_15[ReverseDiagDir(_players_ai[p->index].cur_dir_a)];
 
	ptr = _ai_table_15[ReverseDiagDir(_companies_ai[c->index].cur_dir_a)];
 
	while (ptr[0] != track) ptr += 2;
 
	_players_ai[p->index].cur_dir_a = ReverseDiagDir((DiagDirection)ptr[1]);
 
	_companies_ai[c->index].cur_dir_a = ReverseDiagDir((DiagDirection)ptr[1]);
 

	
 
	// And then also switch tile.
 
	_players_ai[p->index].cur_tile_a = TILE_MASK(_players_ai[p->index].cur_tile_a - TileOffsByDiagDir(_players_ai[p->index].cur_dir_a));
 
	_companies_ai[c->index].cur_tile_a = TILE_MASK(_companies_ai[c->index].cur_tile_a - TileOffsByDiagDir(_companies_ai[c->index].cur_dir_a));
 

	
 
	return true;
 
}
 

	
 

	
 
static void AiBuildRailDestruct(Player *p)
 
static void AiBuildRailDestruct(Company *c)
 
{
 
	// Decrease timeout.
 
	if (!--_players_ai[p->index].state_counter) {
 
		_players_ai[p->index].state_mode = 2;
 
		_players_ai[p->index].state_counter = 0;
 
	if (!--_companies_ai[c->index].state_counter) {
 
		_companies_ai[c->index].state_mode = 2;
 
		_companies_ai[c->index].state_counter = 0;
 
	}
 

	
 
	// Don't do anything if the destination is already reached.
 
	if (_players_ai[p->index].cur_tile_a == _players_ai[p->index].start_tile_a) return;
 

	
 
	AiRemoveTileAndGoForward(p);
 
	if (_companies_ai[c->index].cur_tile_a == _companies_ai[c->index].start_tile_a) return;
 

	
 
	AiRemoveTileAndGoForward(c);
 
}
 

	
 

	
 
static void AiBuildRail(Player *p)
 
static void AiBuildRail(Company *c)
 
{
 
	switch (_players_ai[p->index].state_mode) {
 
	switch (_companies_ai[c->index].state_mode) {
 
		case 0: // Construct mode, build new rail.
 
			AiBuildRailConstruct(p);
 
			AiBuildRailConstruct(c);
 
			break;
 

	
 
		case 1: // Destruct mode, destroy the rail currently built.
 
			AiBuildRailDestruct(p);
 
			AiBuildRailDestruct(c);
 
			break;
 

	
 
		case 2: {
 
@@ -2351,12 +2351,12 @@ static void AiBuildRail(Player *p)
 

	
 
			// Terraform some and then try building again.
 
			for (i = 0; i != 4; i++) {
 
				AiDoTerraformLand(_players_ai[p->index].cur_tile_a, _players_ai[p->index].cur_dir_a, 3, 0);
 
				AiDoTerraformLand(_companies_ai[c->index].cur_tile_a, _companies_ai[c->index].cur_dir_a, 3, 0);
 
			}
 

	
 
			if (++_players_ai[p->index].state_counter == 4) {
 
				_players_ai[p->index].state_counter = 0;
 
				_players_ai[p->index].state_mode = 0;
 
			if (++_companies_ai[c->index].state_counter == 4) {
 
				_companies_ai[c->index].state_counter = 0;
 
				_companies_ai[c->index].state_mode = 0;
 
			}
 
		}
 

	
 
@@ -2364,7 +2364,7 @@ static void AiBuildRail(Player *p)
 
	}
 
}
 

	
 
static void AiStateBuildRail(Player *p)
 
static void AiStateBuildRail(Company *c)
 
{
 
	int num;
 
	AiBuildRec *aib;
 
@@ -2373,26 +2373,26 @@ static void AiStateBuildRail(Player *p)
 
	DiagDirection dir;
 

	
 
	// time out?
 
	if (++_players_ai[p->index].timeout_counter == 1388) {
 
		_players_ai[p->index].state = AIS_DELETE_RAIL_BLOCKS;
 
	if (++_companies_ai[c->index].timeout_counter == 1388) {
 
		_companies_ai[c->index].state = AIS_DELETE_RAIL_BLOCKS;
 
		return;
 
	}
 

	
 
	// Currently building a rail between two points?
 
	if (_players_ai[p->index].state_mode != 255) {
 
		AiBuildRail(p);
 
	if (_companies_ai[c->index].state_mode != 255) {
 
		AiBuildRail(c);
 

	
 
		// Alternate between edges
 
		Swap(_players_ai[p->index].start_tile_a, _players_ai[p->index].start_tile_b);
 
		Swap(_players_ai[p->index].cur_tile_a,   _players_ai[p->index].cur_tile_b);
 
		Swap(_players_ai[p->index].start_dir_a,  _players_ai[p->index].start_dir_b);
 
		Swap(_players_ai[p->index].cur_dir_a,    _players_ai[p->index].cur_dir_b);
 
		Swap(_companies_ai[c->index].start_tile_a, _companies_ai[c->index].start_tile_b);
 
		Swap(_companies_ai[c->index].cur_tile_a,   _companies_ai[c->index].cur_tile_b);
 
		Swap(_companies_ai[c->index].start_dir_a,  _companies_ai[c->index].start_dir_b);
 
		Swap(_companies_ai[c->index].cur_dir_a,    _companies_ai[c->index].cur_dir_b);
 
		return;
 
	}
 

	
 
	// Now, find two new points to build between
 
	num = _players_ai[p->index].num_build_rec;
 
	aib = &_players_ai[p->index].src;
 
	num = _companies_ai[c->index].num_build_rec;
 
	aib = &_companies_ai[c->index].src;
 

	
 
	for (;;) {
 
		cmd = aib->buildcmd_a;
 
@@ -2405,37 +2405,37 @@ static void AiStateBuildRail(Player *p)
 

	
 
		aib++;
 
		if (--num == 0) {
 
			_players_ai[p->index].state = AIS_BUILD_RAIL_VEH;
 
			_players_ai[p->index].state_counter = 0; // timeout
 
			_companies_ai[c->index].state = AIS_BUILD_RAIL_VEH;
 
			_companies_ai[c->index].state_counter = 0; // timeout
 
			return;
 
		}
 
	}
 

	
 
	// Find first edge to build from.
 
	tile = AiGetEdgeOfDefaultRailBlock(aib->cur_building_rule, aib->use_tile, cmd & 3, &dir);
 
	_players_ai[p->index].start_tile_a = tile;
 
	_players_ai[p->index].cur_tile_a = tile;
 
	_players_ai[p->index].start_dir_a = dir;
 
	_players_ai[p->index].cur_dir_a = dir;
 
	_companies_ai[c->index].start_tile_a = tile;
 
	_companies_ai[c->index].cur_tile_a = tile;
 
	_companies_ai[c->index].start_dir_a = dir;
 
	_companies_ai[c->index].cur_dir_a = dir;
 
	DoCommand(TILE_MASK(tile + TileOffsByDiagDir(dir)), 0, (dir & 1) ? 1 : 0, DC_EXEC, CMD_REMOVE_SINGLE_RAIL);
 

	
 
	assert(TILE_MASK(tile) != 0xFF00);
 

	
 
	// Find second edge to build to
 
	aib = (&_players_ai[p->index].src) + ((cmd >> 4) & 0xF);
 
	aib = (&_companies_ai[c->index].src) + ((cmd >> 4) & 0xF);
 
	tile = AiGetEdgeOfDefaultRailBlock(aib->cur_building_rule, aib->use_tile, (cmd >> 2) & 3, &dir);
 
	_players_ai[p->index].start_tile_b = tile;
 
	_players_ai[p->index].cur_tile_b = tile;
 
	_players_ai[p->index].start_dir_b = dir;
 
	_players_ai[p->index].cur_dir_b = dir;
 
	_companies_ai[c->index].start_tile_b = tile;
 
	_companies_ai[c->index].cur_tile_b = tile;
 
	_companies_ai[c->index].start_dir_b = dir;
 
	_companies_ai[c->index].cur_dir_b = dir;
 
	DoCommand(TILE_MASK(tile + TileOffsByDiagDir(dir)), 0, (dir & 1) ? 1 : 0, DC_EXEC, CMD_REMOVE_SINGLE_RAIL);
 

	
 
	assert(TILE_MASK(tile) != 0xFF00);
 

	
 
	// And setup state.
 
	_players_ai[p->index].state_mode = 2;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].banned_tile_count = 0;
 
	_companies_ai[c->index].state_mode = 2;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].banned_tile_count = 0;
 
}
 

	
 
static StationID AiGetStationIdByDef(TileIndex tile, int id)
 
@@ -2459,7 +2459,7 @@ static EngineID AiFindBestWagon(CargoID 
 

	
 
		if (!IsCompatibleRail(rvi->railtype, railtype) ||
 
				rvi->railveh_type != RAILVEH_WAGON ||
 
				!HasBit(e->player_avail, _current_player)) {
 
				!HasBit(e->company_avail, _current_company)) {
 
			continue;
 
		}
 

	
 
@@ -2478,7 +2478,7 @@ static EngineID AiFindBestWagon(CargoID 
 
	return best_veh_index;
 
}
 

	
 
static void AiStateBuildRailVeh(Player *p)
 
static void AiStateBuildRailVeh(Company *c)
 
{
 
	const AiDefaultBlockData *ptr;
 
	TileIndex tile;
 
@@ -2489,40 +2489,40 @@ static void AiStateBuildRailVeh(Player *
 
	Vehicle *v;
 
	VehicleID loco_id;
 

	
 
	ptr = _default_rail_track_data[_players_ai[p->index].src.cur_building_rule]->data;
 
	ptr = _default_rail_track_data[_companies_ai[c->index].src.cur_building_rule]->data;
 
	while (ptr->mode != 0) ptr++;
 

	
 
	tile = TILE_ADD(_players_ai[p->index].src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 

	
 

	
 
	cargo = _players_ai[p->index].cargo_type;
 
	tile = TILE_ADD(_companies_ai[c->index].src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 

	
 

	
 
	cargo = _companies_ai[c->index].cargo_type;
 
	for (i = 0;;) {
 
		if (_players_ai[p->index].wagon_list[i] == INVALID_VEHICLE) {
 
			veh = AiFindBestWagon(cargo, _players_ai[p->index].railtype_to_use);
 
		if (_companies_ai[c->index].wagon_list[i] == INVALID_VEHICLE) {
 
			veh = AiFindBestWagon(cargo, _companies_ai[c->index].railtype_to_use);
 
			/* veh will return INVALID_ENGINE if no suitable wagon is available.
 
			 * We shall treat this in the same way as having no money */
 
			if (veh == INVALID_ENGINE) goto handle_nocash;
 
			cost = DoCommand(tile, veh, 0, DC_EXEC, CMD_BUILD_RAIL_VEHICLE);
 
			if (CmdFailed(cost)) goto handle_nocash;
 
			_players_ai[p->index].wagon_list[i] = _new_vehicle_id;
 
			_players_ai[p->index].wagon_list[i + 1] = INVALID_VEHICLE;
 
			_companies_ai[c->index].wagon_list[i] = _new_vehicle_id;
 
			_companies_ai[c->index].wagon_list[i + 1] = INVALID_VEHICLE;
 
			return;
 
		}
 
		if (cargo == CT_MAIL) cargo = CT_PASSENGERS;
 
		if (++i == _players_ai[p->index].num_wagons * 2 - 1) break;
 
		if (++i == _companies_ai[c->index].num_wagons * 2 - 1) break;
 
	}
 

	
 
	// Which locomotive to build?
 
	veh = AiChooseTrainToBuild(_players_ai[p->index].railtype_to_use, p->player_money, cargo != CT_PASSENGERS ? 1 : 0, tile);
 
	veh = AiChooseTrainToBuild(_companies_ai[c->index].railtype_to_use, c->money, cargo != CT_PASSENGERS ? 1 : 0, tile);
 
	if (veh == INVALID_ENGINE) {
 
handle_nocash:
 
		// after a while, if AI still doesn't have cash, get out of this block by selling the wagons.
 
		if (++_players_ai[p->index].state_counter == 1000) {
 
			for (i = 0; _players_ai[p->index].wagon_list[i] != INVALID_VEHICLE; i++) {
 
				cost = DoCommand(tile, _players_ai[p->index].wagon_list[i], 0, DC_EXEC, CMD_SELL_RAIL_WAGON);
 
		if (++_companies_ai[c->index].state_counter == 1000) {
 
			for (i = 0; _companies_ai[c->index].wagon_list[i] != INVALID_VEHICLE; i++) {
 
				cost = DoCommand(tile, _companies_ai[c->index].wagon_list[i], 0, DC_EXEC, CMD_SELL_RAIL_WAGON);
 
				assert(CmdSucceeded(cost));
 
			}
 
			_players_ai[p->index].state = AIS_0;
 
			_companies_ai[c->index].state = AIS_0;
 
		}
 
		return;
 
	}
 
@@ -2535,29 +2535,29 @@ handle_nocash:
 
	// Sell a vehicle if the train is double headed.
 
	v = GetVehicle(loco_id);
 
	if (v->Next() != NULL) {
 
		i = _players_ai[p->index].wagon_list[_players_ai[p->index].num_wagons * 2 - 2];
 
		_players_ai[p->index].wagon_list[_players_ai[p->index].num_wagons * 2 - 2] = INVALID_VEHICLE;
 
		i = _companies_ai[c->index].wagon_list[_companies_ai[c->index].num_wagons * 2 - 2];
 
		_companies_ai[c->index].wagon_list[_companies_ai[c->index].num_wagons * 2 - 2] = INVALID_VEHICLE;
 
		DoCommand(tile, i, 0, DC_EXEC, CMD_SELL_RAIL_WAGON);
 
	}
 

	
 
	// Move the wagons onto the train
 
	for (i = 0; _players_ai[p->index].wagon_list[i] != INVALID_VEHICLE; i++) {
 
		DoCommand(tile, _players_ai[p->index].wagon_list[i] | (loco_id << 16), 0, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
 
	for (i = 0; _companies_ai[c->index].wagon_list[i] != INVALID_VEHICLE; i++) {
 
		DoCommand(tile, _companies_ai[c->index].wagon_list[i] | (loco_id << 16), 0, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
 
	}
 

	
 
	for (i = 0; _players_ai[p->index].order_list_blocks[i] != 0xFF; i++) {
 
		const AiBuildRec* aib = &_players_ai[p->index].src + _players_ai[p->index].order_list_blocks[i];
 
	for (i = 0; _companies_ai[c->index].order_list_blocks[i] != 0xFF; i++) {
 
		const AiBuildRec* aib = &_companies_ai[c->index].src + _companies_ai[c->index].order_list_blocks[i];
 
		bool is_pass = (
 
			_players_ai[p->index].cargo_type == CT_PASSENGERS ||
 
			_players_ai[p->index].cargo_type == CT_MAIL ||
 
			(_settings_game.game_creation.landscape == LT_TEMPERATE && _players_ai[p->index].cargo_type == CT_VALUABLES)
 
			_companies_ai[c->index].cargo_type == CT_PASSENGERS ||
 
			_companies_ai[c->index].cargo_type == CT_MAIL ||
 
			(_settings_game.game_creation.landscape == LT_TEMPERATE && _companies_ai[c->index].cargo_type == CT_VALUABLES)
 
		);
 
		Order order;
 

	
 
		order.MakeGoToStation(AiGetStationIdByDef(aib->use_tile, aib->cur_building_rule));
 

	
 
		if (!is_pass && i == 1) order.SetUnloadType(OUFB_UNLOAD);
 
		if (_players_ai[p->index].num_want_fullload != 0 && (is_pass || i == 0))
 
		if (_companies_ai[c->index].num_want_fullload != 0 && (is_pass || i == 0))
 
			order.SetLoadType(OLFB_FULL_LOAD);
 

	
 
		DoCommand(0, loco_id + (i << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 
@@ -2567,20 +2567,20 @@ handle_nocash:
 

	
 
	DoCommand(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_SERVICE_INT);
 

	
 
	if (_players_ai[p->index].num_want_fullload != 0) _players_ai[p->index].num_want_fullload--;
 

	
 
	if (--_players_ai[p->index].num_loco_to_build != 0) {
 
//		_players_ai[p->index].loco_id = INVALID_VEHICLE;
 
		_players_ai[p->index].wagon_list[0] = INVALID_VEHICLE;
 
	if (_companies_ai[c->index].num_want_fullload != 0) _companies_ai[c->index].num_want_fullload--;
 

	
 
	if (--_companies_ai[c->index].num_loco_to_build != 0) {
 
//		_companies_ai[c->index].loco_id = INVALID_VEHICLE;
 
		_companies_ai[c->index].wagon_list[0] = INVALID_VEHICLE;
 
	} else {
 
		_players_ai[p->index].state = AIS_0;
 
		_companies_ai[c->index].state = AIS_0;
 
	}
 
}
 

	
 
static void AiStateDeleteRailBlocks(Player *p)
 
static void AiStateDeleteRailBlocks(Company *c)
 
{
 
	const AiBuildRec* aib = &_players_ai[p->index].src;
 
	uint num = _players_ai[p->index].num_build_rec;
 
	const AiBuildRec* aib = &_companies_ai[c->index].src;
 
	uint num = _companies_ai[c->index].num_build_rec;
 

	
 
	do {
 
		const AiDefaultBlockData* b;
 
@@ -2591,7 +2591,7 @@ static void AiStateDeleteRailBlocks(Play
 
		}
 
	} while (++aib, --num);
 

	
 
	_players_ai[p->index].state = AIS_0;
 
	_companies_ai[c->index].state = AIS_0;
 
}
 

	
 
static bool AiCheckRoadResources(TileIndex tile, const AiDefaultBlockData *p, byte cargo)
 
@@ -2711,16 +2711,16 @@ clear_town_stuff:;
 
	if (!_want_road_truck_station && !(roadflag & 2)) return CMD_ERROR;
 

	
 
	if (!(flag & DC_EXEC)) {
 
		if (t != NULL && rating > t->ratings[_current_player]) return CMD_ERROR;
 
		if (t != NULL && rating > t->ratings[_current_company]) return CMD_ERROR;
 
	}
 
	return total_cost;
 
}
 

	
 
// Make sure the blocks are not too close to each other
 
static bool AiCheckBlockDistances(Player *p, TileIndex tile)
 
static bool AiCheckBlockDistances(Company *c, TileIndex tile)
 
{
 
	const AiBuildRec* aib = &_players_ai[p->index].src;
 
	uint num = _players_ai[p->index].num_build_rec;
 
	const AiBuildRec* aib = &_companies_ai[c->index].src;
 
	uint num = _companies_ai[c->index].num_build_rec;
 

	
 
	do {
 
		if (aib->cur_building_rule != 255) {
 
@@ -2732,7 +2732,7 @@ static bool AiCheckBlockDistances(Player
 
}
 

	
 

	
 
static void AiStateBuildDefaultRoadBlocks(Player *p)
 
static void AiStateBuildDefaultRoadBlocks(Company *c)
 
{
 
	uint i;
 
	int j;
 
@@ -2741,16 +2741,16 @@ static void AiStateBuildDefaultRoadBlock
 
	CommandCost cost;
 

	
 
	// time out?
 
	if (++_players_ai[p->index].timeout_counter == 1388) {
 
		_players_ai[p->index].state = AIS_DELETE_RAIL_BLOCKS;
 
	if (++_companies_ai[c->index].timeout_counter == 1388) {
 
		_companies_ai[c->index].state = AIS_DELETE_RAIL_BLOCKS;
 
		return;
 
	}
 

	
 
	// do the following 8 times
 
	for (i = 0; i != 8; i++) {
 
		// check if we can build the default track
 
		aib = &_players_ai[p->index].src;
 
		j = _players_ai[p->index].num_build_rec;
 
		aib = &_companies_ai[c->index].src;
 
		j = _companies_ai[c->index].num_build_rec;
 
		do {
 
			// this item has already been built?
 
			if (aib->cur_building_rule != 255) continue;
 
@@ -2766,18 +2766,18 @@ static void AiStateBuildDefaultRoadBlock
 

	
 
			if (rule == -1) {
 
				// cannot build, terraform after a while
 
				if (_players_ai[p->index].state_counter >= 600) {
 
					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)_players_ai[p->index].state_mode);
 
				if (_companies_ai[c->index].state_counter >= 600) {
 
					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)_companies_ai[c->index].state_mode);
 
				}
 
				// also try the other terraform direction
 
				if (++_players_ai[p->index].state_counter >= 1000) {
 
					_players_ai[p->index].state_counter = 0;
 
					_players_ai[p->index].state_mode = -_players_ai[p->index].state_mode;
 
				if (++_companies_ai[c->index].state_counter >= 1000) {
 
					_companies_ai[c->index].state_counter = 0;
 
					_companies_ai[c->index].state_mode = -_companies_ai[c->index].state_mode;
 
				}
 
			} else if (CheckPlayerHasMoney(cost) && AiCheckBlockDistances(p, aib->use_tile)) {
 
			} else if (CheckCompanyHasMoney(cost) && AiCheckBlockDistances(c, aib->use_tile)) {
 
				CommandCost r;
 

	
 
				// player has money, build it.
 
				// company has money, build it.
 
				aib->cur_building_rule = rule;
 

	
 
				r = AiDoBuildDefaultRoadBlock(
 
@@ -2791,15 +2791,15 @@ static void AiStateBuildDefaultRoadBlock
 
	}
 

	
 
	// check if we're done with all of them
 
	aib = &_players_ai[p->index].src;
 
	j = _players_ai[p->index].num_build_rec;
 
	aib = &_companies_ai[c->index].src;
 
	j = _companies_ai[c->index].num_build_rec;
 
	do {
 
		if (aib->cur_building_rule == 255) return;
 
	} while (++aib, --j);
 

	
 
	// yep, all are done. switch state to the rail building state.
 
	_players_ai[p->index].state = AIS_BUILD_ROAD;
 
	_players_ai[p->index].state_mode = 255;
 
	_companies_ai[c->index].state = AIS_BUILD_ROAD;
 
	_companies_ai[c->index].state_mode = 255;
 
}
 

	
 
struct AiRoadFinder {
 
@@ -2816,7 +2816,7 @@ struct AiRoadFinder {
 
	uint best_dist;
 
	TileIndex cur_best_tile, best_tile;
 
	TileIndex bridge_end_tile;
 
	Player *player;
 
	Company *company;
 
};
 

	
 
struct AiRoadEnum {
 
@@ -2879,14 +2879,14 @@ static bool AiEnumFollowRoad(TileIndex t
 
	return false;
 
}
 

	
 
static bool AiCheckRoadFinished(Player *p)
 
static bool AiCheckRoadFinished(Company *c)
 
{
 
	AiRoadEnum are;
 
	TileIndex tile;
 
	DiagDirection dir = _players_ai[p->index].cur_dir_a;
 

	
 
	are.dest = _players_ai[p->index].cur_tile_b;
 
	tile = TILE_MASK(_players_ai[p->index].cur_tile_a + TileOffsByDiagDir(dir));
 
	DiagDirection dir = _companies_ai[c->index].cur_dir_a;
 

	
 
	are.dest = _companies_ai[c->index].cur_tile_b;
 
	tile = TILE_MASK(_companies_ai[c->index].cur_tile_a + TileOffsByDiagDir(dir));
 

	
 
	if (IsRoadStopTile(tile) || IsRoadDepotTile(tile)) return false;
 
	TrackdirBits bits = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_ROAD, ROADTYPES_ROAD)) & DiagdirReachesTrackdirs(dir);
 
@@ -2903,8 +2903,8 @@ static bool AiCheckRoadFinished(Player *
 

	
 
	if (are.best_dist == 0) return true;
 

	
 
	_players_ai[p->index].cur_tile_a = are.best_tile;
 
	_players_ai[p->index].cur_dir_a = TrackdirToExitdir(are.best_track);
 
	_companies_ai[c->index].cur_tile_a = are.best_tile;
 
	_companies_ai[c->index].cur_dir_a = TrackdirToExitdir(are.best_track);
 
	return false;
 
}
 

	
 
@@ -2972,7 +2972,7 @@ static inline void AiCheckBuildRoadTunne
 
	if (GetTileSlope(tile, &z) == InclinedSlope((DiagDirection)(p[0] & 3)) && z != 0) {
 
		CommandCost cost = DoCommand(tile, 0x200, 0, DC_AUTO, CMD_BUILD_TUNNEL);
 

	
 
		if (CmdSucceeded(cost) && cost.GetCost() <= (arf->player->player_money >> 4)) {
 
		if (CmdSucceeded(cost) && cost.GetCost() <= (arf->company->money >> 4)) {
 
			AiBuildRoadRecursive(arf, _build_tunnel_endtile, (DiagDirection)(p[0] & 3));
 
			if (arf->depth == 1)  AiCheckRoadPathBetter(arf, p);
 
		}
 
@@ -3039,22 +3039,22 @@ static void AiBuildRoadRecursive(AiRoadF
 
}
 

	
 

	
 
static void AiBuildRoadConstruct(Player *p)
 
static void AiBuildRoadConstruct(Company *c)
 
{
 
	AiRoadFinder arf;
 
	int i;
 
	TileIndex tile;
 

	
 
	// Reached destination?
 
	if (AiCheckRoadFinished(p)) {
 
		_players_ai[p->index].state_mode = 255;
 
	if (AiCheckRoadFinished(c)) {
 
		_companies_ai[c->index].state_mode = 255;
 
		return;
 
	}
 

	
 
	// Setup recursive finder and call it.
 
	arf.player = p;
 
	arf.final_tile = _players_ai[p->index].cur_tile_b;
 
	arf.final_dir = _players_ai[p->index].cur_dir_b;
 
	arf.company = c;
 
	arf.final_tile = _companies_ai[c->index].cur_tile_b;
 
	arf.final_dir = _companies_ai[c->index].cur_dir_b;
 
	arf.depth = 0;
 
	arf.recursive_mode = 0;
 
	arf.best_ptr = NULL;
 
@@ -3064,11 +3064,11 @@ static void AiBuildRoadConstruct(Player 
 
	arf.best_depth =  0xff;
 
	arf.cur_best_tile = 0;
 
	arf.best_tile = 0;
 
	AiBuildRoadRecursive(&arf, _players_ai[p->index].cur_tile_a, _players_ai[p->index].cur_dir_a);
 
	AiBuildRoadRecursive(&arf, _companies_ai[c->index].cur_tile_a, _companies_ai[c->index].cur_dir_a);
 

	
 
	// Reached destination?
 
	if (arf.recursive_mode == 2 && arf.cur_best_depth == 0) {
 
		_players_ai[p->index].state_mode = 255;
 
		_companies_ai[c->index].state_mode = 255;
 
		return;
 
	}
 

	
 
@@ -3077,19 +3077,19 @@ static void AiBuildRoadConstruct(Player 
 
		// Terraform some
 
do_some_terraform:
 
		for (i = 0; i != 5; i++)
 
			AiDoTerraformLand(_players_ai[p->index].cur_tile_a, _players_ai[p->index].cur_dir_a, 3, 0);
 

	
 
		if (++_players_ai[p->index].state_counter == 21) {
 
			_players_ai[p->index].state_mode = 1;
 

	
 
			_players_ai[p->index].cur_tile_a = TILE_MASK(_players_ai[p->index].cur_tile_a + TileOffsByDiagDir(_players_ai[p->index].cur_dir_a));
 
			_players_ai[p->index].cur_dir_a = ReverseDiagDir(_players_ai[p->index].cur_dir_a);
 
			_players_ai[p->index].state_counter = 0;
 
			AiDoTerraformLand(_companies_ai[c->index].cur_tile_a, _companies_ai[c->index].cur_dir_a, 3, 0);
 

	
 
		if (++_companies_ai[c->index].state_counter == 21) {
 
			_companies_ai[c->index].state_mode = 1;
 

	
 
			_companies_ai[c->index].cur_tile_a = TILE_MASK(_companies_ai[c->index].cur_tile_a + TileOffsByDiagDir(_companies_ai[c->index].cur_dir_a));
 
			_companies_ai[c->index].cur_dir_a = ReverseDiagDir(_companies_ai[c->index].cur_dir_a);
 
			_companies_ai[c->index].state_counter = 0;
 
		}
 
		return;
 
	}
 

	
 
	tile = TILE_MASK(_players_ai[p->index].cur_tile_a + TileOffsByDiagDir(_players_ai[p->index].cur_dir_a));
 
	tile = TILE_MASK(_companies_ai[c->index].cur_tile_a + TileOffsByDiagDir(_companies_ai[c->index].cur_dir_a));
 

	
 
	if (arf.best_ptr[0] & 0x80) {
 
		TileIndex t1 = tile;
 
@@ -3102,7 +3102,7 @@ do_some_terraform:
 
		/* try to build a long road instead of bridge - CMD_BUILD_LONG_ROAD has to fail if it couldn't build at least one piece! */
 
		CommandCost cost = DoCommand(t2, t1, (t2 < t1 ? 1 : 2) | (axis << 2) | (ROADTYPE_ROAD << 3), DC_AUTO | DC_NO_WATER, CMD_BUILD_LONG_ROAD);
 

	
 
		if (CmdSucceeded(cost) && cost.GetCost() <= p->player_money) {
 
		if (CmdSucceeded(cost) && cost.GetCost() <= c->money) {
 
			DoCommand(t2, t1, (t2 < t1 ? 1 : 2) | (axis << 2) | (ROADTYPE_ROAD << 3), DC_AUTO | DC_EXEC | DC_NO_WATER, CMD_BUILD_LONG_ROAD);
 
		} else {
 
			int i;
 
@@ -3113,7 +3113,7 @@ do_some_terraform:
 
			for (i = MAX_BRIDGES - 1; i != 0; i--) {
 
				if (CheckBridge_Stuff(i, bridge_len)) {
 
					CommandCost cost = DoCommand(t1, t2, i | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE);
 
					if (CmdSucceeded(cost) && cost.GetCost() < (p->player_money >> 1) && cost.GetCost() < ((p->player_money + _economy.max_loan - p->current_loan) >> 5)) break;
 
					if (CmdSucceeded(cost) && cost.GetCost() < (c->money >> 1) && cost.GetCost() < ((c->money + _economy.max_loan - c->current_loan) >> 5)) break;
 
				}
 
			}
 

	
 
@@ -3121,21 +3121,21 @@ do_some_terraform:
 
			DoCommand(t1, t2, i | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO | DC_EXEC, CMD_BUILD_BRIDGE);
 
		}
 

	
 
		_players_ai[p->index].cur_tile_a = t2;
 
		_players_ai[p->index].state_counter = 0;
 
		_companies_ai[c->index].cur_tile_a = t2;
 
		_companies_ai[c->index].state_counter = 0;
 
	} else if (arf.best_ptr[0] & 0x40) {
 
		// tunnel
 
		DoCommand(tile, 0x200, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
 
		_players_ai[p->index].cur_tile_a = _build_tunnel_endtile;
 
		_players_ai[p->index].state_counter = 0;
 
		_companies_ai[c->index].cur_tile_a = _build_tunnel_endtile;
 
		_companies_ai[c->index].state_counter = 0;
 
	} else {
 
		// road
 
		if (!AiBuildRoadHelper(tile, DC_EXEC | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, arf.best_ptr[0]))
 
			goto do_some_terraform;
 

	
 
		_players_ai[p->index].cur_dir_a = (DiagDirection)(arf.best_ptr[1] & 3);
 
		_players_ai[p->index].cur_tile_a = tile;
 
		_players_ai[p->index].state_counter = 0;
 
		_companies_ai[c->index].cur_dir_a = (DiagDirection)(arf.best_ptr[1] & 3);
 
		_companies_ai[c->index].cur_tile_a = tile;
 
		_companies_ai[c->index].state_counter = 0;
 
	}
 

	
 
	if (arf.best_tile != 0) {
 
@@ -3145,26 +3145,26 @@ do_some_terraform:
 
}
 

	
 

	
 
static void AiBuildRoad(Player *p)
 
static void AiBuildRoad(Company *c)
 
{
 
	if (_players_ai[p->index].state_mode < 1) {
 
	if (_companies_ai[c->index].state_mode < 1) {
 
		// Construct mode, build new road.
 
		AiBuildRoadConstruct(p);
 
	} else if (_players_ai[p->index].state_mode == 1) {
 
		AiBuildRoadConstruct(c);
 
	} else if (_companies_ai[c->index].state_mode == 1) {
 
		// Destruct mode, not implemented for roads.
 
		_players_ai[p->index].state_mode = 2;
 
		_players_ai[p->index].state_counter = 0;
 
	} else if (_players_ai[p->index].state_mode == 2) {
 
		_companies_ai[c->index].state_mode = 2;
 
		_companies_ai[c->index].state_counter = 0;
 
	} else if (_companies_ai[c->index].state_mode == 2) {
 
		uint i;
 

	
 
		// Terraform some and then try building again.
 
		for (i = 0; i != 4; i++) {
 
			AiDoTerraformLand(_players_ai[p->index].cur_tile_a, _players_ai[p->index].cur_dir_a, 3, 0);
 
			AiDoTerraformLand(_companies_ai[c->index].cur_tile_a, _companies_ai[c->index].cur_dir_a, 3, 0);
 
		}
 

	
 
		if (++_players_ai[p->index].state_counter == 4) {
 
			_players_ai[p->index].state_counter = 0;
 
			_players_ai[p->index].state_mode = 0;
 
		if (++_companies_ai[c->index].state_counter == 4) {
 
			_companies_ai[c->index].state_counter = 0;
 
			_companies_ai[c->index].state_mode = 0;
 
		}
 
	}
 
}
 
@@ -3178,7 +3178,7 @@ static TileIndex AiGetRoadBlockEdge(byte
 
}
 

	
 

	
 
static void AiStateBuildRoad(Player *p)
 
static void AiStateBuildRoad(Company *c)
 
{
 
	int num;
 
	AiBuildRec *aib;
 
@@ -3187,27 +3187,27 @@ static void AiStateBuildRoad(Player *p)
 
	DiagDirection dir;
 

	
 
	// time out?
 
	if (++_players_ai[p->index].timeout_counter == 1388) {
 
		_players_ai[p->index].state = AIS_DELETE_ROAD_BLOCKS;
 
	if (++_companies_ai[c->index].timeout_counter == 1388) {
 
		_companies_ai[c->index].state = AIS_DELETE_ROAD_BLOCKS;
 
		return;
 
	}
 

	
 
	// Currently building a road between two points?
 
	if (_players_ai[p->index].state_mode != 255) {
 
		AiBuildRoad(p);
 
	if (_companies_ai[c->index].state_mode != 255) {
 
		AiBuildRoad(c);
 

	
 
		// Alternate between edges
 
		Swap(_players_ai[p->index].start_tile_a, _players_ai[p->index].start_tile_b);
 
		Swap(_players_ai[p->index].cur_tile_a,   _players_ai[p->index].cur_tile_b);
 
		Swap(_players_ai[p->index].start_dir_a,  _players_ai[p->index].start_dir_b);
 
		Swap(_players_ai[p->index].cur_dir_a,    _players_ai[p->index].cur_dir_b);
 
		Swap(_companies_ai[c->index].start_tile_a, _companies_ai[c->index].start_tile_b);
 
		Swap(_companies_ai[c->index].cur_tile_a,   _companies_ai[c->index].cur_tile_b);
 
		Swap(_companies_ai[c->index].start_dir_a,  _companies_ai[c->index].start_dir_b);
 
		Swap(_companies_ai[c->index].cur_dir_a,    _companies_ai[c->index].cur_dir_b);
 

	
 
		return;
 
	}
 

	
 
	// Now, find two new points to build between
 
	num = _players_ai[p->index].num_build_rec;
 
	aib = &_players_ai[p->index].src;
 
	num = _companies_ai[c->index].num_build_rec;
 
	aib = &_companies_ai[c->index].src;
 

	
 
	for (;;) {
 
		cmd = aib->buildcmd_a;
 
@@ -3216,30 +3216,30 @@ static void AiStateBuildRoad(Player *p)
 

	
 
		aib++;
 
		if (--num == 0) {
 
			_players_ai[p->index].state = AIS_BUILD_ROAD_VEHICLES;
 
			_companies_ai[c->index].state = AIS_BUILD_ROAD_VEHICLES;
 
			return;
 
		}
 
	}
 

	
 
	// Find first edge to build from.
 
	tile = AiGetRoadBlockEdge(aib->cur_building_rule, aib->use_tile, &dir);
 
	_players_ai[p->index].start_tile_a = tile;
 
	_players_ai[p->index].cur_tile_a = tile;
 
	_players_ai[p->index].start_dir_a = dir;
 
	_players_ai[p->index].cur_dir_a = dir;
 
	_companies_ai[c->index].start_tile_a = tile;
 
	_companies_ai[c->index].cur_tile_a = tile;
 
	_companies_ai[c->index].start_dir_a = dir;
 
	_companies_ai[c->index].cur_dir_a = dir;
 

	
 
	// Find second edge to build to
 
	aib = (&_players_ai[p->index].src) + (cmd & 0xF);
 
	aib = (&_companies_ai[c->index].src) + (cmd & 0xF);
 
	tile = AiGetRoadBlockEdge(aib->cur_building_rule, aib->use_tile, &dir);
 
	_players_ai[p->index].start_tile_b = tile;
 
	_players_ai[p->index].cur_tile_b = tile;
 
	_players_ai[p->index].start_dir_b = dir;
 
	_players_ai[p->index].cur_dir_b = dir;
 
	_companies_ai[c->index].start_tile_b = tile;
 
	_companies_ai[c->index].cur_tile_b = tile;
 
	_companies_ai[c->index].start_dir_b = dir;
 
	_companies_ai[c->index].cur_dir_b = dir;
 

	
 
	// And setup state.
 
	_players_ai[p->index].state_mode = 2;
 
	_players_ai[p->index].state_counter = 0;
 
	_players_ai[p->index].banned_tile_count = 0;
 
	_companies_ai[c->index].state_mode = 2;
 
	_companies_ai[c->index].state_counter = 0;
 
	_companies_ai[c->index].banned_tile_count = 0;
 
}
 

	
 
static StationID AiGetStationIdFromRoadBlock(TileIndex tile, int id)
 
@@ -3249,7 +3249,7 @@ static StationID AiGetStationIdFromRoadB
 
	return GetStationIndex(TILE_ADD(tile, ToTileIndexDiff(p->tileoffs)));
 
}
 

	
 
static void AiStateBuildRoadVehicles(Player *p)
 
static void AiStateBuildRoadVehicles(Company *c)
 
{
 
	const AiDefaultBlockData *ptr;
 
	TileIndex tile;
 
@@ -3257,13 +3257,13 @@ static void AiStateBuildRoadVehicles(Pla
 
	EngineID veh;
 
	uint i;
 

	
 
	ptr = _road_default_block_data[_players_ai[p->index].src.cur_building_rule]->data;
 
	ptr = _road_default_block_data[_companies_ai[c->index].src.cur_building_rule]->data;
 
	for (; ptr->mode != 0; ptr++) {}
 
	tile = TILE_ADD(_players_ai[p->index].src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 

	
 
	veh = AiChooseRoadVehToBuild(_players_ai[p->index].cargo_type, p->player_money, tile);
 
	tile = TILE_ADD(_companies_ai[c->index].src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 

	
 
	veh = AiChooseRoadVehToBuild(_companies_ai[c->index].cargo_type, c->money, tile);
 
	if (veh == INVALID_ENGINE) {
 
		_players_ai[p->index].state = AIS_0;
 
		_companies_ai[c->index].state = AIS_0;
 
		return;
 
	}
 

	
 
@@ -3271,28 +3271,28 @@ static void AiStateBuildRoadVehicles(Pla
 

	
 
	loco_id = _new_vehicle_id;
 

	
 
	if (GetVehicle(loco_id)->cargo_type != _players_ai[p->index].cargo_type) {
 
	if (GetVehicle(loco_id)->cargo_type != _companies_ai[c->index].cargo_type) {
 
		/* Cargo type doesn't match, so refit it */
 
		if (CmdFailed(DoCommand(tile, loco_id, _players_ai[p->index].cargo_type, DC_EXEC, CMD_REFIT_ROAD_VEH))) {
 
		if (CmdFailed(DoCommand(tile, loco_id, _companies_ai[c->index].cargo_type, DC_EXEC, CMD_REFIT_ROAD_VEH))) {
 
			/* Refit failed... sell the vehicle */
 
			DoCommand(tile, loco_id, 0, DC_EXEC, CMD_SELL_ROAD_VEH);
 
			return;
 
		}
 
	}
 

	
 
	for (i = 0; _players_ai[p->index].order_list_blocks[i] != 0xFF; i++) {
 
		const AiBuildRec* aib = &_players_ai[p->index].src + _players_ai[p->index].order_list_blocks[i];
 
	for (i = 0; _companies_ai[c->index].order_list_blocks[i] != 0xFF; i++) {
 
		const AiBuildRec* aib = &_companies_ai[c->index].src + _companies_ai[c->index].order_list_blocks[i];
 
		bool is_pass = (
 
			_players_ai[p->index].cargo_type == CT_PASSENGERS ||
 
			_players_ai[p->index].cargo_type == CT_MAIL ||
 
			(_settings_game.game_creation.landscape == LT_TEMPERATE && _players_ai[p->index].cargo_type == CT_VALUABLES)
 
			_companies_ai[c->index].cargo_type == CT_PASSENGERS ||
 
			_companies_ai[c->index].cargo_type == CT_MAIL ||
 
			(_settings_game.game_creation.landscape == LT_TEMPERATE && _companies_ai[c->index].cargo_type == CT_VALUABLES)
 
		);
 
		Order order;
 

	
 
		order.MakeGoToStation(AiGetStationIdFromRoadBlock(aib->use_tile, aib->cur_building_rule));
 

	
 
		if (!is_pass && i == 1) order.SetUnloadType(OUFB_UNLOAD);
 
		if (_players_ai[p->index].num_want_fullload != 0 && (is_pass || i == 0))
 
		if (_companies_ai[c->index].num_want_fullload != 0 && (is_pass || i == 0))
 
			order.SetLoadType(OLFB_FULL_LOAD);
 

	
 
		DoCommand(0, loco_id + (i << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 
@@ -3301,14 +3301,14 @@ static void AiStateBuildRoadVehicles(Pla
 
	DoCommand(0, loco_id, 0, DC_EXEC, CMD_START_STOP_VEHICLE);
 
	DoCommand(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_SERVICE_INT);
 

	
 
	if (_players_ai[p->index].num_want_fullload != 0) _players_ai[p->index].num_want_fullload--;
 
	if (--_players_ai[p->index].num_loco_to_build == 0) _players_ai[p->index].state = AIS_0;
 
	if (_companies_ai[c->index].num_want_fullload != 0) _companies_ai[c->index].num_want_fullload--;
 
	if (--_companies_ai[c->index].num_loco_to_build == 0) _companies_ai[c->index].state = AIS_0;
 
}
 

	
 
static void AiStateDeleteRoadBlocks(Player *p)
 
static void AiStateDeleteRoadBlocks(Company *c)
 
{
 
	const AiBuildRec* aib = &_players_ai[p->index].src;
 
	uint num = _players_ai[p->index].num_build_rec;
 
	const AiBuildRec* aib = &_companies_ai[c->index].src;
 
	uint num = _companies_ai[c->index].num_build_rec;
 

	
 
	do {
 
		const AiDefaultBlockData* b;
 
@@ -3320,11 +3320,11 @@ static void AiStateDeleteRoadBlocks(Play
 
		}
 
	} while (++aib, --num);
 

	
 
	_players_ai[p->index].state = AIS_0;
 
	_companies_ai[c->index].state = AIS_0;
 
}
 

	
 

	
 
static void AiStateAirportStuff(Player *p)
 
static void AiStateAirportStuff(Company *c)
 
{
 
	const Station* st;
 
	int i;
 
@@ -3341,19 +3341,19 @@ static void AiStateAirportStuff(Player *
 
		// We do this all twice - once for the source (town in the case
 
		// of oilrig route) and then for the destination (oilrig in the
 
		// case of oilrig route).
 
		aib = &_players_ai[p->index].src + i;
 
		aib = &_companies_ai[c->index].src + i;
 

	
 
		FOR_ALL_STATIONS(st) {
 
			// Is this an airport?
 
			if (!(st->facilities & FACIL_AIRPORT)) continue;
 

	
 
			// Do we own the airport? (Oilrigs aren't owned, though.)
 
			if (st->owner != OWNER_NONE && st->owner != _current_player) continue;
 
			if (st->owner != OWNER_NONE && st->owner != _current_company) continue;
 

	
 
			AirportFTAClass::Flags flags = st->Airport()->flags;
 

	
 
			/* if airport doesn't accept our kind of plane, dismiss it */
 
			if (!(flags & (_players_ai[p->index].build_kind == 1 ? AirportFTAClass::HELICOPTERS : AirportFTAClass::AIRPLANES))) {
 
			if (!(flags & (_companies_ai[c->index].build_kind == 1 ? AirportFTAClass::HELICOPTERS : AirportFTAClass::AIRPLANES))) {
 
				continue;
 
			}
 

	
 
@@ -3392,11 +3392,11 @@ static void AiStateAirportStuff(Player *
 
			aib->use_tile = st->airport_tile;
 
			break;
 
		}
 
	} while (++i != _players_ai[p->index].num_build_rec);
 

	
 
	_players_ai[p->index].state = AIS_BUILD_DEFAULT_AIRPORT_BLOCKS;
 
	_players_ai[p->index].state_mode = 255;
 
	_players_ai[p->index].state_counter = 0;
 
	} while (++i != _companies_ai[c->index].num_build_rec);
 

	
 
	_companies_ai[c->index].state = AIS_BUILD_DEFAULT_AIRPORT_BLOCKS;
 
	_companies_ai[c->index].state_mode = 255;
 
	_companies_ai[c->index].state_counter = 0;
 
}
 

	
 
static CommandCost AiDoBuildDefaultAirportBlock(TileIndex tile, const AiDefaultBlockData *p, byte flag)
 
@@ -3470,7 +3470,7 @@ static int AiFindBestDefaultAirportBlock
 
	return -1;
 
}
 

	
 
static void AiStateBuildDefaultAirportBlocks(Player *p)
 
static void AiStateBuildDefaultAirportBlocks(Company *c)
 
{
 
	int i, j;
 
	AiBuildRec *aib;
 
@@ -3478,8 +3478,8 @@ static void AiStateBuildDefaultAirportBl
 
	CommandCost cost;
 

	
 
	// time out?
 
	if (++_players_ai[p->index].timeout_counter == 1388) {
 
		_players_ai[p->index].state = AIS_0;
 
	if (++_companies_ai[c->index].timeout_counter == 1388) {
 
		_companies_ai[c->index].state = AIS_0;
 
		return;
 
	}
 

	
 
@@ -3487,8 +3487,8 @@ static void AiStateBuildDefaultAirportBl
 
	i = 8;
 
	do {
 
		// check if we can build the default
 
		aib = &_players_ai[p->index].src;
 
		j = _players_ai[p->index].num_build_rec;
 
		aib = &_companies_ai[c->index].src;
 
		j = _companies_ai[c->index].num_build_rec;
 
		do {
 
			// this item has already been built?
 
			if (aib->cur_building_rule != 255) continue;
 
@@ -3498,22 +3498,22 @@ static void AiStateBuildDefaultAirportBl
 
			aib->use_tile = AdjustTileCoordRandomly(aib->spec_tile, aib->rand_rng);
 

	
 
			// check if the aircraft stuff can be built there.
 
			rule = AiFindBestDefaultAirportBlock(aib->use_tile, aib->cargo, _players_ai[p->index].build_kind, &cost);
 
			rule = AiFindBestDefaultAirportBlock(aib->use_tile, aib->cargo, _companies_ai[c->index].build_kind, &cost);
 

	
 
//			SetRedErrorSquare(aib->use_tile);
 

	
 
			if (rule == -1) {
 
				// cannot build, terraform after a while
 
				if (_players_ai[p->index].state_counter >= 600) {
 
					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)_players_ai[p->index].state_mode);
 
				if (_companies_ai[c->index].state_counter >= 600) {
 
					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)_companies_ai[c->index].state_mode);
 
				}
 
				// also try the other terraform direction
 
				if (++_players_ai[p->index].state_counter >= 1000) {
 
					_players_ai[p->index].state_counter = 0;
 
					_players_ai[p->index].state_mode = -_players_ai[p->index].state_mode;
 
				if (++_companies_ai[c->index].state_counter >= 1000) {
 
					_companies_ai[c->index].state_counter = 0;
 
					_companies_ai[c->index].state_mode = -_companies_ai[c->index].state_mode;
 
				}
 
			} else if (CheckPlayerHasMoney(cost) && AiCheckBlockDistances(p, aib->use_tile)) {
 
				// player has money, build it.
 
			} else if (CheckCompanyHasMoney(cost) && AiCheckBlockDistances(c, aib->use_tile)) {
 
				// company has money, build it.
 
				CommandCost r;
 

	
 
				aib->cur_building_rule = rule;
 
@@ -3529,14 +3529,14 @@ static void AiStateBuildDefaultAirportBl
 
	} while (--i);
 

	
 
	// check if we're done with all of them
 
	aib = &_players_ai[p->index].src;
 
	j = _players_ai[p->index].num_build_rec;
 
	aib = &_companies_ai[c->index].src;
 
	j = _companies_ai[c->index].num_build_rec;
 
	do {
 
		if (aib->cur_building_rule == 255) return;
 
	} while (++aib, --j);
 

	
 
	// yep, all are done. switch state.
 
	_players_ai[p->index].state = AIS_BUILD_AIRCRAFT_VEHICLES;
 
	_companies_ai[c->index].state = AIS_BUILD_AIRCRAFT_VEHICLES;
 
}
 

	
 
static StationID AiGetStationIdFromAircraftBlock(TileIndex tile, int id)
 
@@ -3546,7 +3546,7 @@ static StationID AiGetStationIdFromAircr
 
	return GetStationIndex(TILE_ADD(tile, ToTileIndexDiff(p->tileoffs)));
 
}
 

	
 
static void AiStateBuildAircraftVehicles(Player *p)
 
static void AiStateBuildAircraftVehicles(Company *c)
 
{
 
	const AiDefaultBlockData *ptr;
 
	TileIndex tile;
 
@@ -3554,15 +3554,15 @@ static void AiStateBuildAircraftVehicles
 
	int i;
 
	VehicleID loco_id;
 

	
 
	ptr = _airport_default_block_data[_players_ai[p->index].src.cur_building_rule];
 
	ptr = _airport_default_block_data[_companies_ai[c->index].src.cur_building_rule];
 
	for (; ptr->mode != 0; ptr++) {}
 

	
 
	tile = TILE_ADD(_players_ai[p->index].src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 
	tile = TILE_ADD(_companies_ai[c->index].src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 

	
 
	/* determine forbidden aircraft bits */
 
	byte forbidden = 0;
 
	for (i = 0; _players_ai[p->index].order_list_blocks[i] != 0xFF; i++) {
 
		const AiBuildRec *aib = (&_players_ai[p->index].src) + _players_ai[p->index].order_list_blocks[i];
 
	for (i = 0; _companies_ai[c->index].order_list_blocks[i] != 0xFF; i++) {
 
		const AiBuildRec *aib = (&_companies_ai[c->index].src) + _companies_ai[c->index].order_list_blocks[i];
 
		const Station *st = GetStationByTile(aib->use_tile);
 

	
 
		if (st == NULL || !(st->facilities & FACIL_AIRPORT)) continue;
 
@@ -3572,7 +3572,7 @@ static void AiStateBuildAircraftVehicles
 
		if (flags & AirportFTAClass::SHORT_STRIP) forbidden |= AIR_FAST; // no fast planes for small airports
 
	}
 

	
 
	veh = AiChooseAircraftToBuild(p->player_money, forbidden);
 
	veh = AiChooseAircraftToBuild(c->money, forbidden);
 
	if (veh == INVALID_ENGINE) return;
 
	if (GetStationByTile(tile)->Airport()->nof_depots == 0) return;
 

	
 
@@ -3582,15 +3582,15 @@ static void AiStateBuildAircraftVehicles
 
	if (CmdFailed(DoCommand(tile, veh, 0, DC_EXEC, CMD_BUILD_AIRCRAFT))) return;
 
	loco_id = _new_vehicle_id;
 

	
 
	for (i = 0; _players_ai[p->index].order_list_blocks[i] != 0xFF; i++) {
 
		AiBuildRec *aib = (&_players_ai[p->index].src) + _players_ai[p->index].order_list_blocks[i];
 
		bool is_pass = (_players_ai[p->index].cargo_type == CT_PASSENGERS || _players_ai[p->index].cargo_type == CT_MAIL);
 
	for (i = 0; _companies_ai[c->index].order_list_blocks[i] != 0xFF; i++) {
 
		AiBuildRec *aib = (&_companies_ai[c->index].src) + _companies_ai[c->index].order_list_blocks[i];
 
		bool is_pass = (_companies_ai[c->index].cargo_type == CT_PASSENGERS || _companies_ai[c->index].cargo_type == CT_MAIL);
 
		Order order;
 

	
 
		order.MakeGoToStation(AiGetStationIdFromAircraftBlock(aib->use_tile, aib->cur_building_rule));
 

	
 
		if (!is_pass && i == 1) order.SetUnloadType(OUFB_UNLOAD);
 
		if (_players_ai[p->index].num_want_fullload != 0 && (is_pass || i == 0))
 
		if (_companies_ai[c->index].num_want_fullload != 0 && (is_pass || i == 0))
 
			order.SetLoadType(OLFB_FULL_LOAD);
 

	
 
		DoCommand(0, loco_id + (i << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 
@@ -3600,31 +3600,31 @@ static void AiStateBuildAircraftVehicles
 

	
 
	DoCommand(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_SERVICE_INT);
 

	
 
	if (_players_ai[p->index].num_want_fullload != 0) _players_ai[p->index].num_want_fullload--;
 

	
 
	if (--_players_ai[p->index].num_loco_to_build == 0) _players_ai[p->index].state = AIS_0;
 
	if (_companies_ai[c->index].num_want_fullload != 0) _companies_ai[c->index].num_want_fullload--;
 

	
 
	if (--_companies_ai[c->index].num_loco_to_build == 0) _companies_ai[c->index].state = AIS_0;
 
}
 

	
 
static void AiStateCheckShipStuff(Player *p)
 
static void AiStateCheckShipStuff(Company *c)
 
{
 
	/* Ships are not implemented in this (broken) AI */
 
}
 

	
 
static void AiStateBuildDefaultShipBlocks(Player *p)
 
static void AiStateBuildDefaultShipBlocks(Company *c)
 
{
 
	/* Ships are not implemented in this (broken) AI */
 
}
 

	
 
static void AiStateDoShipStuff(Player *p)
 
static void AiStateDoShipStuff(Company *c)
 
{
 
	/* Ships are not implemented in this (broken) AI */
 
}
 

	
 
static void AiStateSellVeh(Player *p)
 
static void AiStateSellVeh(Company *c)
 
{
 
	Vehicle *v = _players_ai[p->index].cur_veh;
 

	
 
	if (v->owner == _current_player) {
 
	Vehicle *v = _companies_ai[c->index].cur_veh;
 

	
 
	if (v->owner == _current_company) {
 
		if (v->type == VEH_TRAIN) {
 

	
 
			if (!IsRailDepotTile(v->tile) || v->u.rail.track != TRACK_BIT_DEPOT || !(v->vehstatus & VS_STOPPED)) {
 
@@ -3659,17 +3659,17 @@ static void AiStateSellVeh(Player *p)
 

	
 
	goto return_to_loop;
 
going_to_depot:;
 
	if (++_players_ai[p->index].state_counter <= 832) return;
 
	if (++_companies_ai[c->index].state_counter <= 832) return;
 

	
 
	if (v->current_order.IsType(OT_GOTO_DEPOT)) {
 
		v->current_order.MakeDummy();
 
		InvalidateWindow(WC_VEHICLE_VIEW, v->index);
 
	}
 
return_to_loop:;
 
	_players_ai[p->index].state = AIS_VEH_LOOP;
 
	_companies_ai[c->index].state = AIS_VEH_LOOP;
 
}
 

	
 
static void AiStateRemoveStation(Player *p)
 
static void AiStateRemoveStation(Company *c)
 
{
 
	// Remove stations that aren't in use by any vehicle
 
	const Order *ord;
 
@@ -3677,7 +3677,7 @@ static void AiStateRemoveStation(Player 
 
	TileIndex tile;
 

	
 
	// Go to this state when we're done.
 
	_players_ai[p->index].state = AIS_1;
 
	_companies_ai[c->index].state = AIS_1;
 

	
 
	// Get a list of all stations that are in use by a vehicle
 
	byte *in_use = MallocT<byte>(GetMaxStationIndex() + 1);
 
@@ -3688,7 +3688,7 @@ static void AiStateRemoveStation(Player 
 

	
 
	// Go through all stations and delete those that aren't in use
 
	FOR_ALL_STATIONS(st) {
 
		if (st->owner == _current_player && !in_use[st->index] &&
 
		if (st->owner == _current_company && !in_use[st->index] &&
 
				( (st->bus_stops != NULL && (tile = st->bus_stops->xy) != 0) ||
 
					(st->truck_stops != NULL && (tile = st->truck_stops->xy)) != 0 ||
 
					(tile = st->train_tile) != 0 ||
 
@@ -3701,12 +3701,12 @@ static void AiStateRemoveStation(Player 
 
	free(in_use);
 
}
 

	
 
static void AiRemovePlayerRailOrRoad(Player *p, TileIndex tile)
 
static void AiRemoveCompanyRailOrRoad(Company *c, TileIndex tile)
 
{
 
	TrackBits rails;
 

	
 
	if (IsTileType(tile, MP_RAILWAY)) {
 
		if (!IsTileOwner(tile, _current_player)) return;
 
		if (!IsTileOwner(tile, _current_company)) return;
 

	
 
		if (IsPlainRailTile(tile)) {
 
is_rail_crossing:;
 
@@ -3717,9 +3717,9 @@ is_rail_crossing:;
 
			if (rails & TRACK_BIT_3WAY_NE) {
 
pos_0:
 
				if ((GetRailTrackStatus(TILE_MASK(tile - TileDiffXY(1, 0))) & TRACK_BIT_3WAY_SW) == 0) {
 
					_players_ai[p->index].cur_dir_a = DIAGDIR_NE;
 
					_players_ai[p->index].cur_tile_a = tile;
 
					_players_ai[p->index].state = AIS_REMOVE_SINGLE_RAIL_TILE;
 
					_companies_ai[c->index].cur_dir_a = DIAGDIR_NE;
 
					_companies_ai[c->index].cur_tile_a = tile;
 
					_companies_ai[c->index].state = AIS_REMOVE_SINGLE_RAIL_TILE;
 
					return;
 
				}
 
			}
 
@@ -3727,9 +3727,9 @@ pos_0:
 
			if (rails & TRACK_BIT_3WAY_SE) {
 
pos_1:
 
				if ((GetRailTrackStatus(TILE_MASK(tile + TileDiffXY(0, 1))) & TRACK_BIT_3WAY_NW) == 0) {
 
					_players_ai[p->index].cur_dir_a = DIAGDIR_SE;
 
					_players_ai[p->index].cur_tile_a = tile;
 
					_players_ai[p->index].state = AIS_REMOVE_SINGLE_RAIL_TILE;
 
					_companies_ai[c->index].cur_dir_a = DIAGDIR_SE;
 
					_companies_ai[c->index].cur_tile_a = tile;
 
					_companies_ai[c->index].state = AIS_REMOVE_SINGLE_RAIL_TILE;
 
					return;
 
				}
 
			}
 
@@ -3737,9 +3737,9 @@ pos_1:
 
			if (rails & TRACK_BIT_3WAY_SW) {
 
pos_2:
 
				if ((GetRailTrackStatus(TILE_MASK(tile + TileDiffXY(1, 0))) & TRACK_BIT_3WAY_NE) == 0) {
 
					_players_ai[p->index].cur_dir_a = DIAGDIR_SW;
 
					_players_ai[p->index].cur_tile_a = tile;
 
					_players_ai[p->index].state = AIS_REMOVE_SINGLE_RAIL_TILE;
 
					_companies_ai[c->index].cur_dir_a = DIAGDIR_SW;
 
					_companies_ai[c->index].cur_tile_a = tile;
 
					_companies_ai[c->index].state = AIS_REMOVE_SINGLE_RAIL_TILE;
 
					return;
 
				}
 
			}
 
@@ -3747,9 +3747,9 @@ pos_2:
 
			if (rails & TRACK_BIT_3WAY_NW) {
 
pos_3:
 
				if ((GetRailTrackStatus(TILE_MASK(tile - TileDiffXY(0, 1))) & TRACK_BIT_3WAY_SE) == 0) {
 
					_players_ai[p->index].cur_dir_a = DIAGDIR_NW;
 
					_players_ai[p->index].cur_tile_a = tile;
 
					_players_ai[p->index].state = AIS_REMOVE_SINGLE_RAIL_TILE;
 
					_companies_ai[c->index].cur_dir_a = DIAGDIR_NW;
 
					_companies_ai[c->index].cur_tile_a = tile;
 
					_companies_ai[c->index].state = AIS_REMOVE_SINGLE_RAIL_TILE;
 
					return;
 
				}
 
			}
 
@@ -3767,23 +3767,23 @@ pos_3:
 
		if (IsLevelCrossing(tile)) goto is_rail_crossing;
 

	
 
		if (IsRoadDepot(tile)) {
 
			if (!IsTileOwner(tile, _current_player)) return;
 
			if (!IsTileOwner(tile, _current_company)) return;
 

	
 
			DiagDirection dir;
 
			TileIndex t;
 

	
 
			// Check if there are any stations around.
 
			t = tile + TileDiffXY(-1, 0);
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_company)) return;
 

	
 
			t = tile + TileDiffXY(1, 0);
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_company)) return;
 

	
 
			t = tile + TileDiffXY(0, -1);
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_company)) return;
 

	
 
			t = tile + TileDiffXY(0, 1);
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_company)) return;
 

	
 
			dir = GetRoadDepotDirection(tile);
 

	
 
@@ -3796,7 +3796,7 @@ pos_3:
 
				CMD_REMOVE_ROAD);
 
		}
 
	} else if (IsTileType(tile, MP_TUNNELBRIDGE)) {
 
		if (!IsTileOwner(tile, _current_player) ||
 
		if (!IsTileOwner(tile, _current_company) ||
 
				!IsBridge(tile) ||
 
				GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) {
 
			return;
 
@@ -3814,30 +3814,30 @@ pos_3:
 
	}
 
}
 

	
 
static void AiStateRemoveTrack(Player *p)
 
static void AiStateRemoveTrack(Company *c)
 
{
 
	/* Was 1000 for standard 8x8 maps. */
 
	int num = MapSizeX() * 4;
 

	
 
	do {
 
		TileIndex tile = ++_players_ai[p->index].state_counter;
 
		TileIndex tile = ++_companies_ai[c->index].state_counter;
 

	
 
		// Iterated all tiles?
 
		if (tile >= MapSize()) {
 
			_players_ai[p->index].state = AIS_REMOVE_STATION;
 
			_companies_ai[c->index].state = AIS_REMOVE_STATION;
 
			return;
 
		}
 

	
 
		// Remove player stuff in that tile
 
		AiRemovePlayerRailOrRoad(p, tile);
 
		if (_players_ai[p->index].state != AIS_REMOVE_TRACK) return;
 
		// Remove company stuff in that tile
 
		AiRemoveCompanyRailOrRoad(c, tile);
 
		if (_companies_ai[c->index].state != AIS_REMOVE_TRACK) return;
 
	} while (--num);
 
}
 

	
 
static void AiStateRemoveSingleRailTile(Player *p)
 
static void AiStateRemoveSingleRailTile(Company *c)
 
{
 
	// Remove until we can't remove more.
 
	if (!AiRemoveTileAndGoForward(p)) _players_ai[p->index].state = AIS_REMOVE_TRACK;
 
	if (!AiRemoveTileAndGoForward(c)) _companies_ai[c->index].state = AIS_REMOVE_TRACK;
 
}
 

	
 
static AiStateAction * const _ai_actions[] = {
 
@@ -3873,101 +3873,101 @@ static AiStateAction * const _ai_actions
 
	AiStateRemoveSingleRailTile
 
};
 

	
 
extern void ShowBuyCompanyDialog(uint player);
 

	
 
static void AiHandleTakeover(Player *p)
 
extern void ShowBuyCompanyDialog(CompanyID company);
 

	
 
static void AiHandleTakeover(Company *c)
 
{
 
	if (p->bankrupt_timeout != 0) {
 
		p->bankrupt_timeout -= 8;
 
		if (p->bankrupt_timeout > 0) return;
 
		p->bankrupt_timeout = 0;
 
		DeleteWindowById(WC_BUY_COMPANY, _current_player);
 
		if (IsLocalPlayer()) {
 
	if (c->bankrupt_timeout != 0) {
 
		c->bankrupt_timeout -= 8;
 
		if (c->bankrupt_timeout > 0) return;
 
		c->bankrupt_timeout = 0;
 
		DeleteWindowById(WC_BUY_COMPANY, _current_company);
 
		if (IsLocalCompany()) {
 
			AskExitToGameMenu();
 
			return;
 
		}
 
		if (IsHumanPlayer(_current_player)) return;
 
		if (IsHumanCompany(_current_company)) return;
 
	}
 

	
 
	if (p->bankrupt_asked == 255) return;
 
	if (c->bankrupt_asked == 255) return;
 

	
 
	{
 
		uint asked = p->bankrupt_asked;
 
		Player *pp, *best_pl = NULL;
 
		uint asked = c->bankrupt_asked;
 
		Company *company, *best_company = NULL;
 
		int32 best_val = -1;
 

	
 
		// Ask the guy with the highest performance hist.
 
		FOR_ALL_PLAYERS(pp) {
 
		FOR_ALL_COMPANIES(company) {
 
			if (!(asked & 1) &&
 
					pp->bankrupt_asked == 0 &&
 
					best_val < pp->old_economy[1].performance_history) {
 
				best_val = pp->old_economy[1].performance_history;
 
				best_pl = pp;
 
					company->bankrupt_asked == 0 &&
 
					best_val < company->old_economy[1].performance_history) {
 
				best_val = company->old_economy[1].performance_history;
 
				best_company = company;
 
			}
 
			asked >>= 1;
 
		}
 

	
 
		// Asked all players?
 
		// Asked all companies?
 
		if (best_val == -1) {
 
			p->bankrupt_asked = 255;
 
			c->bankrupt_asked = 255;
 
			return;
 
		}
 

	
 
		SetBit(p->bankrupt_asked, best_pl->index);
 

	
 
		if (best_pl->index == _local_player) {
 
			p->bankrupt_timeout = 4440;
 
			ShowBuyCompanyDialog(_current_player);
 
		SetBit(c->bankrupt_asked, best_company->index);
 

	
 
		if (best_company->index == _local_company) {
 
			c->bankrupt_timeout = 4440;
 
			ShowBuyCompanyDialog(_current_company);
 
			return;
 
		}
 
		if (IsHumanPlayer(best_pl->index)) return;
 
		if (IsHumanCompany(best_company->index)) return;
 

	
 
		// Too little money for computer to buy it?
 
		if (best_pl->player_money >> 1 >= p->bankrupt_value) {
 
		if (best_company->money >> 1 >= c->bankrupt_value) {
 
			// Computer wants to buy it.
 
			PlayerID old_p = _current_player;
 
			_current_player = best_pl->index;
 
			DoCommand(0, old_p, 0, DC_EXEC, CMD_BUY_COMPANY);
 
			_current_player = old_p;
 
			CompanyID old_company = _current_company;
 
			_current_company = best_company->index;
 
			DoCommand(0, old_company, 0, DC_EXEC, CMD_BUY_COMPANY);
 
			_current_company = old_company;
 
		}
 
	}
 
}
 

	
 
static void AiAdjustLoan(const Player* p)
 
static void AiAdjustLoan(const Company *c)
 
{
 
	Money base = AiGetBasePrice(p);
 

	
 
	if (p->player_money > base * 1400) {
 
	Money base = AiGetBasePrice(c);
 

	
 
	if (c->money > base * 1400) {
 
		// Decrease loan
 
		if (p->current_loan != 0) {
 
		if (c->current_loan != 0) {
 
			DoCommand(0, 0, 0, DC_EXEC, CMD_DECREASE_LOAN);
 
		}
 
	} else if (p->player_money < base * 500) {
 
	} else if (c->money < base * 500) {
 
		// Increase loan
 
		if (p->current_loan < _economy.max_loan &&
 
				p->num_valid_stat_ent >= 2 &&
 
				-(p->old_economy[0].expenses + p->old_economy[1].expenses) < base * 60) {
 
		if (c->current_loan < _economy.max_loan &&
 
				c->num_valid_stat_ent >= 2 &&
 
				-(c->old_economy[0].expenses + c->old_economy[1].expenses) < base * 60) {
 
			DoCommand(0, 0, 0, DC_EXEC, CMD_INCREASE_LOAN);
 
		}
 
	}
 
}
 

	
 
static void AiBuildCompanyHQ(Player *p)
 
static void AiBuildCompanyHQ(Company *c)
 
{
 
	TileIndex tile;
 

	
 
	if (p->location_of_HQ == 0 &&
 
			p->last_build_coordinate != 0) {
 
		tile = AdjustTileCoordRandomly(p->last_build_coordinate, 8);
 
	if (c->location_of_HQ == 0 &&
 
			c->last_build_coordinate != 0) {
 
		tile = AdjustTileCoordRandomly(c->last_build_coordinate, 8);
 
		DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ);
 
	}
 
}
 

	
 

	
 
void AiDoGameLoop(Player *p)
 
void AiDoGameLoop(Company *c)
 
{
 
	if (p->bankrupt_asked != 0) {
 
		AiHandleTakeover(p);
 
	if (c->bankrupt_asked != 0) {
 
		AiHandleTakeover(c);
 
		return;
 
	}
 

	
 
@@ -3977,10 +3977,10 @@ void AiDoGameLoop(Player *p)
 
	//  or in %
 
	_ai_service_interval = _settings_game.vehicle.servint_ispercent ? 80 : 180;
 

	
 
	if (IsHumanPlayer(_current_player)) return;
 

	
 
	AiAdjustLoan(p);
 
	AiBuildCompanyHQ(p);
 
	if (IsHumanCompany(_current_company)) return;
 

	
 
	AiAdjustLoan(c);
 
	AiBuildCompanyHQ(c);
 

	
 
#if 0
 
	{
 
@@ -4013,11 +4013,11 @@ void AiDoGameLoop(Player *p)
 
			"AiStateRemoveSingleRailTile"
 
		};
 

	
 
		if (_players_ai[p->index].state != old_state) {
 
		if (_companies_ai[c->index].state != old_state) {
 
			if (hasdots)
 
				printf("\n");
 
			hasdots = false;
 
			printf("AiState: %s\n", _ai_state_names[old_state=_players_ai[p->index].state]);
 
			printf("AiState: %s\n", _ai_state_names[old_state=_companies_ai[c->index].state]);
 
		} else {
 
			printf(".");
 
			hasdots = true;
 
@@ -4025,55 +4025,55 @@ void AiDoGameLoop(Player *p)
 
	}
 
#endif
 

	
 
	_ai_actions[_players_ai[p->index].state](p);
 
	_ai_actions[_companies_ai[c->index].state](c);
 
}
 

	
 

	
 
static const SaveLoad _player_ai_desc[] = {
 
	    SLE_VAR(PlayerAI, state,             SLE_UINT8),
 
	    SLE_VAR(PlayerAI, tick,              SLE_UINT8),
 
	SLE_CONDVAR(PlayerAI, state_counter,     SLE_FILE_U16 | SLE_VAR_U32,  0, 12),
 
	SLE_CONDVAR(PlayerAI, state_counter,     SLE_UINT32,                 13, SL_MAX_VERSION),
 
	    SLE_VAR(PlayerAI, timeout_counter,   SLE_UINT16),
 

	
 
	    SLE_VAR(PlayerAI, state_mode,        SLE_UINT8),
 
	    SLE_VAR(PlayerAI, banned_tile_count, SLE_UINT8),
 
	    SLE_VAR(PlayerAI, railtype_to_use,   SLE_UINT8),
 

	
 
	    SLE_VAR(PlayerAI, cargo_type,        SLE_UINT8),
 
	    SLE_VAR(PlayerAI, num_wagons,        SLE_UINT8),
 
	    SLE_VAR(PlayerAI, build_kind,        SLE_UINT8),
 
	    SLE_VAR(PlayerAI, num_build_rec,     SLE_UINT8),
 
	    SLE_VAR(PlayerAI, num_loco_to_build, SLE_UINT8),
 
	    SLE_VAR(PlayerAI, num_want_fullload, SLE_UINT8),
 

	
 
	    SLE_VAR(PlayerAI, route_type_mask,   SLE_UINT8),
 

	
 
	SLE_CONDVAR(PlayerAI, start_tile_a,      SLE_FILE_U16 | SLE_VAR_U32,  0,  5),
 
	SLE_CONDVAR(PlayerAI, start_tile_a,      SLE_UINT32,                  6, SL_MAX_VERSION),
 
	SLE_CONDVAR(PlayerAI, cur_tile_a,        SLE_FILE_U16 | SLE_VAR_U32,  0,  5),
 
	SLE_CONDVAR(PlayerAI, cur_tile_a,        SLE_UINT32,                  6, SL_MAX_VERSION),
 
	    SLE_VAR(PlayerAI, start_dir_a,       SLE_UINT8),
 
	    SLE_VAR(PlayerAI, cur_dir_a,         SLE_UINT8),
 

	
 
	SLE_CONDVAR(PlayerAI, start_tile_b,      SLE_FILE_U16 | SLE_VAR_U32,  0,  5),
 
	SLE_CONDVAR(PlayerAI, start_tile_b,      SLE_UINT32,                  6, SL_MAX_VERSION),
 
	SLE_CONDVAR(PlayerAI, cur_tile_b,        SLE_FILE_U16 | SLE_VAR_U32,  0,  5),
 
	SLE_CONDVAR(PlayerAI, cur_tile_b,        SLE_UINT32,                  6, SL_MAX_VERSION),
 
	    SLE_VAR(PlayerAI, start_dir_b,       SLE_UINT8),
 
	    SLE_VAR(PlayerAI, cur_dir_b,         SLE_UINT8),
 

	
 
	    SLE_REF(PlayerAI, cur_veh,           REF_VEHICLE),
 

	
 
	    SLE_ARR(PlayerAI, wagon_list,        SLE_UINT16, 9),
 
	    SLE_ARR(PlayerAI, order_list_blocks, SLE_UINT8, 20),
 
	    SLE_ARR(PlayerAI, banned_tiles,      SLE_UINT16, 16),
 
static const SaveLoad _company_ai_desc[] = {
 
	    SLE_VAR(CompanyAI, state,             SLE_UINT8),
 
	    SLE_VAR(CompanyAI, tick,              SLE_UINT8),
 
	SLE_CONDVAR(CompanyAI, state_counter,     SLE_FILE_U16 | SLE_VAR_U32,  0, 12),
 
	SLE_CONDVAR(CompanyAI, state_counter,     SLE_UINT32,                 13, SL_MAX_VERSION),
 
	    SLE_VAR(CompanyAI, timeout_counter,   SLE_UINT16),
 

	
 
	    SLE_VAR(CompanyAI, state_mode,        SLE_UINT8),
 
	    SLE_VAR(CompanyAI, banned_tile_count, SLE_UINT8),
 
	    SLE_VAR(CompanyAI, railtype_to_use,   SLE_UINT8),
 

	
 
	    SLE_VAR(CompanyAI, cargo_type,        SLE_UINT8),
 
	    SLE_VAR(CompanyAI, num_wagons,        SLE_UINT8),
 
	    SLE_VAR(CompanyAI, build_kind,        SLE_UINT8),
 
	    SLE_VAR(CompanyAI, num_build_rec,     SLE_UINT8),
 
	    SLE_VAR(CompanyAI, num_loco_to_build, SLE_UINT8),
 
	    SLE_VAR(CompanyAI, num_want_fullload, SLE_UINT8),
 

	
 
	    SLE_VAR(CompanyAI, route_type_mask,   SLE_UINT8),
 

	
 
	SLE_CONDVAR(CompanyAI, start_tile_a,      SLE_FILE_U16 | SLE_VAR_U32,  0,  5),
 
	SLE_CONDVAR(CompanyAI, start_tile_a,      SLE_UINT32,                  6, SL_MAX_VERSION),
 
	SLE_CONDVAR(CompanyAI, cur_tile_a,        SLE_FILE_U16 | SLE_VAR_U32,  0,  5),
 
	SLE_CONDVAR(CompanyAI, cur_tile_a,        SLE_UINT32,                  6, SL_MAX_VERSION),
 
	    SLE_VAR(CompanyAI, start_dir_a,       SLE_UINT8),
 
	    SLE_VAR(CompanyAI, cur_dir_a,         SLE_UINT8),
 

	
 
	SLE_CONDVAR(CompanyAI, start_tile_b,      SLE_FILE_U16 | SLE_VAR_U32,  0,  5),
 
	SLE_CONDVAR(CompanyAI, start_tile_b,      SLE_UINT32,                  6, SL_MAX_VERSION),
 
	SLE_CONDVAR(CompanyAI, cur_tile_b,        SLE_FILE_U16 | SLE_VAR_U32,  0,  5),
 
	SLE_CONDVAR(CompanyAI, cur_tile_b,        SLE_UINT32,                  6, SL_MAX_VERSION),
 
	    SLE_VAR(CompanyAI, start_dir_b,       SLE_UINT8),
 
	    SLE_VAR(CompanyAI, cur_dir_b,         SLE_UINT8),
 

	
 
	    SLE_REF(CompanyAI, cur_veh,           REF_VEHICLE),
 

	
 
	    SLE_ARR(CompanyAI, wagon_list,        SLE_UINT16, 9),
 
	    SLE_ARR(CompanyAI, order_list_blocks, SLE_UINT8, 20),
 
	    SLE_ARR(CompanyAI, banned_tiles,      SLE_UINT16, 16),
 

	
 
	SLE_CONDNULL(64, 2, SL_MAX_VERSION),
 
	SLE_END()
 
};
 

	
 
static const SaveLoad _player_ai_build_rec_desc[] = {
 
static const SaveLoad _company_ai_build_rec_desc[] = {
 
	SLE_CONDVAR(AiBuildRec, spec_tile,         SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
 
	SLE_CONDVAR(AiBuildRec, spec_tile,         SLE_UINT32,                 6, SL_MAX_VERSION),
 
	SLE_CONDVAR(AiBuildRec, use_tile,          SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
 
@@ -4090,11 +4090,11 @@ static const SaveLoad _player_ai_build_r
 
};
 

	
 

	
 
void SaveLoad_AI(PlayerID id)
 
void SaveLoad_AI(CompanyID company)
 
{
 
	PlayerAI *pai = &_players_ai[id];
 
	SlObject(pai, _player_ai_desc);
 
	for (int i = 0; i != pai->num_build_rec; i++) {
 
		SlObject(&pai->src + i, _player_ai_build_rec_desc);
 
	CompanyAI *cai = &_companies_ai[company];
 
	SlObject(cai, _company_ai_desc);
 
	for (int i = 0; i != cai->num_build_rec; i++) {
 
		SlObject(&cai->src + i, _company_ai_build_rec_desc);
 
	}
 
}
src/ai/default/default.h
Show inline comments
 
@@ -9,8 +9,8 @@
 
#include "../../vehicle_type.h"
 
#include "../../rail_type.h"
 

	
 
void AiDoGameLoop(Player*);
 
void SaveLoad_AI(PlayerID id);
 
void AiDoGameLoop(Company *c);
 
void SaveLoad_AI(CompanyID company);
 

	
 
struct AiBuildRec {
 
	TileIndex spec_tile;
 
@@ -25,7 +25,7 @@ struct AiBuildRec {
 
	CargoID cargo;
 
};
 

	
 
struct PlayerAI {
 
struct CompanyAI {
 
	byte state;
 
	byte tick;            ///< Used to determine how often to move
 
	uint32 state_counter; ///< Can hold tile index!
 
@@ -65,6 +65,6 @@ struct PlayerAI {
 
	byte banned_val[16];
 
};
 

	
 
extern PlayerAI _players_ai[MAX_PLAYERS];
 
extern CompanyAI _companies_ai[MAX_COMPANIES];
 

	
 
#endif
src/ai/trolly/build.cpp
Show inline comments
 
@@ -23,7 +23,7 @@
 
// Build HQ
 
//  Params:
 
//    tile : tile where HQ is going to be build
 
bool AiNew_Build_CompanyHQ(Player *p, TileIndex tile)
 
bool AiNew_Build_CompanyHQ(Company *c, TileIndex tile)
 
{
 
	if (CmdFailed(AI_DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ)))
 
		return false;
 
@@ -40,7 +40,7 @@ bool AiNew_Build_CompanyHQ(Player *p, Ti
 
//    numtracks : in case of AI_TRAIN: tracks of station
 
//    direction : the direction of the station
 
//    flag : flag passed to DoCommand (normally 0 to get the cost or DC_EXEC to build it)
 
CommandCost AiNew_Build_Station(Player *p, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag)
 
CommandCost AiNew_Build_Station(Company *c, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag)
 
{
 
	if (type == AI_TRAIN)
 
		return AI_DoCommand(tile, direction + (numtracks << 8) + (length << 16), 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_RAILROAD_STATION);
 
@@ -52,12 +52,12 @@ CommandCost AiNew_Build_Station(Player *
 
}
 

	
 

	
 
// Builds a brdige. The second best out of the ones available for this player
 
// Builds a brdige. The second best out of the ones available for this company
 
//  Params:
 
//   tile_a : starting point
 
//   tile_b : end point
 
//   flag : flag passed to DoCommand
 
CommandCost AiNew_Build_Bridge(Player *p, TileIndex tile_a, TileIndex tile_b, byte flag)
 
CommandCost AiNew_Build_Bridge(Company *c, TileIndex tile_a, TileIndex tile_b, byte flag)
 
{
 
	int bridge_type, bridge_len, type, type2;
 

	
 
@@ -76,7 +76,7 @@ CommandCost AiNew_Build_Bridge(Player *p
 
	if (type2 == 0 && type != 0) type2 = type;
 

	
 
	// Now, simply, build the bridge!
 
	if (_players_ainew[p->index].tbt == AI_TRAIN) {
 
	if (_companies_ainew[c->index].tbt == AI_TRAIN) {
 
		return AI_DoCommand(tile_a, tile_b, type2 | RAILTYPE_RAIL  << 8 | TRANSPORT_RAIL << 15, flag | DC_AUTO, CMD_BUILD_BRIDGE);
 
	} else {
 
		return AI_DoCommand(tile_a, tile_b, type2 | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, flag | DC_AUTO, CMD_BUILD_BRIDGE);
 
@@ -94,7 +94,7 @@ CommandCost AiNew_Build_Bridge(Player *p
 
//   part : Which part we need to build
 
//
 
// TODO: skip already builded road-pieces (e.g.: cityroad)
 
CommandCost AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte flag)
 
CommandCost AiNew_Build_RoutePart(Company *c, Ai_PathFinderInfo *PathFinderInfo, byte flag)
 
{
 
	int part = PathFinderInfo->position;
 
	byte *route_extra = PathFinderInfo->route_extra;
 
@@ -127,7 +127,7 @@ CommandCost AiNew_Build_RoutePart(Player
 
		}
 
		// Bridge code
 
		if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
 
			cost.AddCost(AiNew_Build_Bridge(p, route[part], route[part - 1], flag));
 
			cost.AddCost(AiNew_Build_Bridge(c, route[part], route[part - 1], flag));
 
			PathFinderInfo->position++;
 
			// TODO: problems!
 
			if (CmdFailed(cost)) {
 
@@ -150,7 +150,7 @@ CommandCost AiNew_Build_RoutePart(Player
 
				res = AI_DoCommand(route[part], 0, dir, flag, CMD_BUILD_SINGLE_RAIL);
 
				if (CmdFailed(res)) {
 
					// Problem.. let's just abort it all!
 
					_players_ainew[p->index].state = AI_STATE_NOTHING;
 
					_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
					return CommandCost();
 
				}
 
				cost.AddCost(res);
 
@@ -177,7 +177,7 @@ CommandCost AiNew_Build_RoutePart(Player
 
		}
 
		// Bridge code
 
		if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
 
			cost.AddCost(AiNew_Build_Bridge(p, route[part], route[part + 1], flag));
 
			cost.AddCost(AiNew_Build_Bridge(c, route[part], route[part + 1], flag));
 
			PathFinderInfo->position++;
 
			// TODO: problems!
 
			if (CmdFailed(cost)) {
 
@@ -206,7 +206,7 @@ CommandCost AiNew_Build_RoutePart(Player
 
					if (CmdFailed(res) && flag == DC_EXEC && !IsTileType(route[part], MP_ROAD) && !EnsureNoVehicleOnGround(route[part])) {
 
						// Problem.. let's just abort it all!
 
						DEBUG(ai, 0, "[BuidPath] route building failed at tile 0x%X, aborting", route[part]);
 
						_players_ainew[p->index].state = AI_STATE_NOTHING;
 
						_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
						return CommandCost();
 
					}
 

	
 
@@ -230,9 +230,9 @@ CommandCost AiNew_Build_RoutePart(Player
 

	
 
// This functions tries to find the best vehicle for this type of cargo
 
// It returns INVALID_ENGINE if not suitable engine is found
 
EngineID AiNew_PickVehicle(Player *p)
 
EngineID AiNew_PickVehicle(Company *c)
 
{
 
	if (_players_ainew[p->index].tbt == AI_TRAIN) {
 
	if (_companies_ainew[c->index].tbt == AI_TRAIN) {
 
		// Not supported yet
 
		return INVALID_ENGINE;
 
	} else {
 
@@ -246,14 +246,14 @@ EngineID AiNew_PickVehicle(Player *p)
 
			const RoadVehicleInfo *rvi = &e->u.road;
 

	
 
			/* Skip vehicles which can't take our cargo type */
 
			if (rvi->cargo_type != _players_ainew[p->index].cargo && !CanRefitTo(i, _players_ainew[p->index].cargo)) continue;
 
			if (rvi->cargo_type != _companies_ainew[c->index].cargo && !CanRefitTo(i, _companies_ainew[c->index].cargo)) continue;
 

	
 
			/* Skip trams */
 
			if (HasBit(EngInfo(i)->misc_flags, EF_ROAD_TRAM)) continue;
 

	
 
			// Is it availiable?
 
			// Also, check if the reliability of the vehicle is above the AI_VEHICLE_MIN_RELIABILTY
 
			if (!HasBit(e->player_avail, _current_player) || e->reliability * 100 < AI_VEHICLE_MIN_RELIABILTY << 16) continue;
 
			if (!HasBit(e->company_avail, _current_company) || e->reliability * 100 < AI_VEHICLE_MIN_RELIABILTY << 16) continue;
 

	
 
			/* Rate and compare the engine by speed & capacity */
 
			int rating = rvi->max_speed * rvi->capacity;
 
@@ -274,34 +274,34 @@ EngineID AiNew_PickVehicle(Player *p)
 

	
 
void CcAI(bool success, TileIndex tile, uint32 p1, uint32 p2)
 
{
 
	Player* p = GetPlayer(_current_player);
 
	Company *c = GetCompany(_current_company);
 

	
 
	if (success) {
 
		_players_ainew[p->index].state = AI_STATE_GIVE_ORDERS;
 
		_players_ainew[p->index].veh_id = _new_vehicle_id;
 
		_companies_ainew[c->index].state = AI_STATE_GIVE_ORDERS;
 
		_companies_ainew[c->index].veh_id = _new_vehicle_id;
 

	
 
		if (GetVehicle(_players_ainew[p->index].veh_id)->cargo_type != _players_ainew[p->index].cargo) {
 
		if (GetVehicle(_companies_ainew[c->index].veh_id)->cargo_type != _companies_ainew[c->index].cargo) {
 
			/* Cargo type doesn't match, so refit it */
 
			if (CmdFailed(DoCommand(tile, _players_ainew[p->index].veh_id, _players_ainew[p->index].cargo, DC_EXEC, CMD_REFIT_ROAD_VEH))) {
 
			if (CmdFailed(DoCommand(tile, _companies_ainew[c->index].veh_id, _companies_ainew[c->index].cargo, DC_EXEC, CMD_REFIT_ROAD_VEH))) {
 
				/* Refit failed, so sell the vehicle */
 
				DoCommand(tile, _players_ainew[p->index].veh_id, 0, DC_EXEC, CMD_SELL_ROAD_VEH);
 
				_players_ainew[p->index].state = AI_STATE_NOTHING;
 
				DoCommand(tile, _companies_ainew[c->index].veh_id, 0, DC_EXEC, CMD_SELL_ROAD_VEH);
 
				_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
			}
 
		}
 
	} else {
 
		/* XXX this should be handled more gracefully */
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
	}
 
}
 

	
 

	
 
// Builds the best vehicle possible
 
CommandCost AiNew_Build_Vehicle(Player *p, TileIndex tile, byte flag)
 
CommandCost AiNew_Build_Vehicle(Company *c, TileIndex tile, byte flag)
 
{
 
	EngineID i = AiNew_PickVehicle(p);
 
	EngineID i = AiNew_PickVehicle(c);
 

	
 
	if (i == INVALID_ENGINE) return CMD_ERROR;
 
	if (_players_ainew[p->index].tbt == AI_TRAIN) return CMD_ERROR;
 
	if (_companies_ainew[c->index].tbt == AI_TRAIN) return CMD_ERROR;
 

	
 
	if (flag & DC_EXEC) {
 
		return AI_DoCommandCc(tile, i, 0, flag, CMD_BUILD_ROAD_VEH, CcAI);
 
@@ -310,10 +310,10 @@ CommandCost AiNew_Build_Vehicle(Player *
 
	}
 
}
 

	
 
CommandCost AiNew_Build_Depot(Player* p, TileIndex tile, DiagDirection direction, byte flag)
 
CommandCost AiNew_Build_Depot(Company *c, TileIndex tile, DiagDirection direction, byte flag)
 
{
 
	CommandCost ret, ret2;
 
	if (_players_ainew[p->index].tbt == AI_TRAIN) {
 
	if (_companies_ainew[c->index].tbt == AI_TRAIN) {
 
		return AI_DoCommand(tile, 0, direction, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_TRAIN_DEPOT);
 
	} else {
 
		ret = AI_DoCommand(tile, direction, 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_DEPOT);
src/ai/trolly/pathfinder.cpp
Show inline comments
 
@@ -24,21 +24,21 @@
 
// TODO: make it train compatible
 
static bool TestCanBuildStationHere(TileIndex tile, byte dir)
 
{
 
	Player *p = GetPlayer(_current_player);
 
	Company *c = GetCompany(_current_company);
 

	
 
	if (dir == TEST_STATION_NO_DIR) {
 
		CommandCost ret;
 
		// TODO: currently we only allow spots that can be access from al 4 directions...
 
		//  should be fixed!!!
 
		for (dir = 0; dir < 4; dir++) {
 
			ret = AiNew_Build_Station(p, _players_ainew[p->index].tbt, tile, 1, 1, dir, DC_QUERY_COST);
 
			ret = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, tile, 1, 1, dir, DC_QUERY_COST);
 
			if (CmdSucceeded(ret)) return true;
 
		}
 
		return false;
 
	}
 

	
 
	// return true if command succeeded, so the inverse of CmdFailed()
 
	return CmdSucceeded(AiNew_Build_Station(p, _players_ainew[p->index].tbt, tile, 1, 1, dir, DC_QUERY_COST));
 
	return CmdSucceeded(AiNew_Build_Station(c, _companies_ainew[c->index].tbt, tile, 1, 1, dir, DC_QUERY_COST));
 
}
 

	
 

	
src/ai/trolly/shared.cpp
Show inline comments
 
@@ -78,13 +78,13 @@ DiagDirection AiNew_GetDirection(TileInd
 

	
 
// This functions looks up if this vehicle is special for this AI
 
//  and returns his flag
 
uint AiNew_GetSpecialVehicleFlag(Player* p, Vehicle* v)
 
uint AiNew_GetSpecialVehicleFlag(Company *c, Vehicle *v)
 
{
 
	uint i;
 

	
 
	for (i = 0; i < AI_MAX_SPECIAL_VEHICLES; i++) {
 
		if (_players_ainew[p->index].special_vehicles[i].veh_id == v->index) {
 
			return _players_ainew[p->index].special_vehicles[i].flag;
 
		if (_companies_ainew[c->index].special_vehicles[i].veh_id == v->index) {
 
			return _companies_ainew[c->index].special_vehicles[i].flag;
 
		}
 
	}
 

	
 
@@ -93,19 +93,19 @@ uint AiNew_GetSpecialVehicleFlag(Player*
 
}
 

	
 

	
 
bool AiNew_SetSpecialVehicleFlag(Player* p, Vehicle* v, uint flag)
 
bool AiNew_SetSpecialVehicleFlag(Company *c, Vehicle *v, uint flag)
 
{
 
	int new_id = -1;
 
	uint i;
 

	
 
	for (i = 0; i < AI_MAX_SPECIAL_VEHICLES; i++) {
 
		if (_players_ainew[p->index].special_vehicles[i].veh_id == v->index) {
 
			_players_ainew[p->index].special_vehicles[i].flag |= flag;
 
		if (_companies_ainew[c->index].special_vehicles[i].veh_id == v->index) {
 
			_companies_ainew[c->index].special_vehicles[i].flag |= flag;
 
			return true;
 
		}
 
		if (new_id == -1 &&
 
				_players_ainew[p->index].special_vehicles[i].veh_id == 0 &&
 
				_players_ainew[p->index].special_vehicles[i].flag == 0) {
 
				_companies_ainew[c->index].special_vehicles[i].veh_id == 0 &&
 
				_companies_ainew[c->index].special_vehicles[i].flag == 0) {
 
			new_id = i;
 
		}
 
	}
 
@@ -115,7 +115,7 @@ bool AiNew_SetSpecialVehicleFlag(Player*
 
		DEBUG(ai, 1, "special_vehicles list is too small");
 
		return false;
 
	}
 
	_players_ainew[p->index].special_vehicles[new_id].veh_id = v->index;
 
	_players_ainew[p->index].special_vehicles[new_id].flag = flag;
 
	_companies_ainew[c->index].special_vehicles[new_id].veh_id = v->index;
 
	_companies_ainew[c->index].special_vehicles[new_id].flag = flag;
 
	return true;
 
}
src/ai/trolly/trolly.cpp
Show inline comments
 
@@ -43,37 +43,37 @@
 

	
 
#include "table/strings.h"
 

	
 
PlayerAiNew _players_ainew[MAX_PLAYERS];
 
CompanyAiNew _companies_ainew[MAX_COMPANIES];
 

	
 
// This function is called after StartUp. It is the init of an AI
 
static void AiNew_State_FirstTime(Player *p)
 
static void AiNew_State_FirstTime(Company *c)
 
{
 
	// This assert is used to protect those function from misuse
 
	//   You have quickly a small mistake in the state-array
 
	//   With that, everything would go wrong. Finding that, is almost impossible
 
	//   With this assert, that problem can never happen.
 
	assert(_players_ainew[p->index].state == AI_STATE_FIRST_TIME);
 
	assert(_companies_ainew[c->index].state == AI_STATE_FIRST_TIME);
 
	// We first have to init some things
 

	
 
	if (_current_player == 1) ShowErrorMessage(INVALID_STRING_ID, TEMP_AI_IN_PROGRESS, 0, 0);
 
	if (_current_company == 1) ShowErrorMessage(INVALID_STRING_ID, TEMP_AI_IN_PROGRESS, 0, 0);
 

	
 
	// The PathFinder (AyStar)
 
	// TODO: Maybe when an AI goes bankrupt, this is de-init
 
	//  or when coming from a savegame.. should be checked out!
 
	_players_ainew[p->index].path_info.start_tile_tl = 0;
 
	_players_ainew[p->index].path_info.start_tile_br = 0;
 
	_players_ainew[p->index].path_info.end_tile_tl = 0;
 
	_players_ainew[p->index].path_info.end_tile_br = 0;
 
	_players_ainew[p->index].pathfinder = new_AyStar_AiPathFinder(12, &_players_ainew[p->index].path_info);
 
	_companies_ainew[c->index].path_info.start_tile_tl = 0;
 
	_companies_ainew[c->index].path_info.start_tile_br = 0;
 
	_companies_ainew[c->index].path_info.end_tile_tl = 0;
 
	_companies_ainew[c->index].path_info.end_tile_br = 0;
 
	_companies_ainew[c->index].pathfinder = new_AyStar_AiPathFinder(12, &_companies_ainew[c->index].path_info);
 

	
 
	_players_ainew[p->index].idle = 0;
 
	_players_ainew[p->index].last_vehiclecheck_date = _date;
 
	_companies_ainew[c->index].idle = 0;
 
	_companies_ainew[c->index].last_vehiclecheck_date = _date;
 

	
 
	// We ALWAYS start with a bus route.. just some basic money ;)
 
	_players_ainew[p->index].action = AI_ACTION_BUS_ROUTE;
 
	_companies_ainew[c->index].action = AI_ACTION_BUS_ROUTE;
 

	
 
	// Let's popup the news, and after that, start building..
 
	_players_ainew[p->index].state = AI_STATE_WAKE_UP;
 
	_companies_ainew[c->index].state = AI_STATE_WAKE_UP;
 
}
 

	
 

	
 
@@ -84,15 +84,15 @@ static void AiNew_State_FirstTime(Player
 
//
 
// Let's say, we sleep between one and three days if the AI is put on Very Fast.
 
//  This means that on Very Slow it will be between 16 and 48 days.. slow enough?
 
static void AiNew_State_Nothing(Player *p)
 
static void AiNew_State_Nothing(Company *c)
 
{
 
	assert(_players_ainew[p->index].state == AI_STATE_NOTHING);
 
	assert(_companies_ainew[c->index].state == AI_STATE_NOTHING);
 
	// If we are done idling, start over again
 
	if (_players_ainew[p->index].idle == 0) _players_ainew[p->index].idle = AI_RandomRange(DAY_TICKS * 2) + DAY_TICKS;
 
	if (--_players_ainew[p->index].idle == 0) {
 
	if (_companies_ainew[c->index].idle == 0) _companies_ainew[c->index].idle = AI_RandomRange(DAY_TICKS * 2) + DAY_TICKS;
 
	if (--_companies_ainew[c->index].idle == 0) {
 
		// We are done idling.. what you say? Let's do something!
 
		// I mean.. the next tick ;)
 
		_players_ainew[p->index].state = AI_STATE_WAKE_UP;
 
		_companies_ainew[c->index].state = AI_STATE_WAKE_UP;
 
	}
 
}
 

	
 
@@ -102,118 +102,117 @@ static void AiNew_State_Nothing(Player *
 
//    - Make new route
 
//    - Check route
 
//    - Build HQ
 
static void AiNew_State_WakeUp(Player *p)
 
static void AiNew_State_WakeUp(Company *c)
 
{
 
	int c;
 
	assert(_players_ainew[p->index].state == AI_STATE_WAKE_UP);
 
	assert(_companies_ainew[c->index].state == AI_STATE_WAKE_UP);
 
	// First, check if we have a HQ
 
	if (p->location_of_HQ == 0) {
 
	if (c->location_of_HQ == 0) {
 
		// We have no HQ yet, build one on a random place
 
		// Random till we found a place for it!
 
		// TODO: this should not be on a random place..
 
		AiNew_Build_CompanyHQ(p, AI_Random() % MapSize());
 
		AiNew_Build_CompanyHQ(c, AI_Random() % MapSize());
 
		// Enough for now, but we want to come back here the next time
 
		//  so we do not change any status
 
		return;
 
	}
 

	
 
	Money money = p->player_money - AI_MINIMUM_MONEY;
 
	Money money = c->money - AI_MINIMUM_MONEY;
 

	
 
	// Let's pick an action!
 
	if (_players_ainew[p->index].action == AI_ACTION_NONE) {
 
		c = AI_Random() & 0xFF;
 
		if (p->current_loan > 0 &&
 
				p->old_economy[1].income > AI_MINIMUM_INCOME_FOR_LOAN &&
 
				c < 10) {
 
			_players_ainew[p->index].action = AI_ACTION_REPAY_LOAN;
 
		} else if (_players_ainew[p->index].last_vehiclecheck_date + AI_DAYS_BETWEEN_VEHICLE_CHECKS < _date) {
 
	if (_companies_ainew[c->index].action == AI_ACTION_NONE) {
 
		int r = AI_Random() & 0xFF;
 
		if (c->current_loan > 0 &&
 
				c->old_economy[1].income > AI_MINIMUM_INCOME_FOR_LOAN &&
 
				r < 10) {
 
			_companies_ainew[c->index].action = AI_ACTION_REPAY_LOAN;
 
		} else if (_companies_ainew[c->index].last_vehiclecheck_date + AI_DAYS_BETWEEN_VEHICLE_CHECKS < _date) {
 
			// Check all vehicles once in a while
 
			_players_ainew[p->index].action = AI_ACTION_CHECK_ALL_VEHICLES;
 
			_players_ainew[p->index].last_vehiclecheck_date = _date;
 
		} else if (c < 100 && !_settings_game.ai.ai_disable_veh_roadveh) {
 
			_companies_ainew[c->index].action = AI_ACTION_CHECK_ALL_VEHICLES;
 
			_companies_ainew[c->index].last_vehiclecheck_date = _date;
 
		} else if (r < 100 && !_settings_game.ai.ai_disable_veh_roadveh) {
 
			// Do we have any spots for road-vehicles left open?
 
			if (GetFreeUnitNumber(VEH_ROAD) <= _settings_game.vehicle.max_roadveh) {
 
				if (c < 85) {
 
					_players_ainew[p->index].action = AI_ACTION_TRUCK_ROUTE;
 
				if (r < 85) {
 
					_companies_ainew[c->index].action = AI_ACTION_TRUCK_ROUTE;
 
				} else {
 
					_players_ainew[p->index].action = AI_ACTION_BUS_ROUTE;
 
					_companies_ainew[c->index].action = AI_ACTION_BUS_ROUTE;
 
				}
 
			}
 
#if 0
 
		} else if (c < 200 && !_settings_game.ai.ai_disable_veh_train) {
 
		} else if (r < 200 && !_settings_game.ai.ai_disable_veh_train) {
 
			if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) {
 
				_players_ainew[p->index].action = AI_ACTION_TRAIN_ROUTE;
 
				_companies_ainew[c->index].action = AI_ACTION_TRAIN_ROUTE;
 
			}
 
#endif
 
		}
 

	
 
		_players_ainew[p->index].counter = 0;
 
		_companies_ainew[c->index].counter = 0;
 
	}
 

	
 
	if (_players_ainew[p->index].counter++ > AI_MAX_TRIES_FOR_SAME_ROUTE) {
 
		_players_ainew[p->index].action = AI_ACTION_NONE;
 
	if (_companies_ainew[c->index].counter++ > AI_MAX_TRIES_FOR_SAME_ROUTE) {
 
		_companies_ainew[c->index].action = AI_ACTION_NONE;
 
		return;
 
	}
 

	
 
	if (_settings_game.ai.ai_disable_veh_roadveh && (
 
				_players_ainew[p->index].action == AI_ACTION_BUS_ROUTE ||
 
				_players_ainew[p->index].action == AI_ACTION_TRUCK_ROUTE
 
				_companies_ainew[c->index].action == AI_ACTION_BUS_ROUTE ||
 
				_companies_ainew[c->index].action == AI_ACTION_TRUCK_ROUTE
 
			)) {
 
		_players_ainew[p->index].action = AI_ACTION_NONE;
 
		_companies_ainew[c->index].action = AI_ACTION_NONE;
 
		return;
 
	}
 

	
 
	if (_players_ainew[p->index].action == AI_ACTION_REPAY_LOAN &&
 
	if (_companies_ainew[c->index].action == AI_ACTION_REPAY_LOAN &&
 
			money > AI_MINIMUM_LOAN_REPAY_MONEY) {
 
		// We start repaying some money..
 
		_players_ainew[p->index].state = AI_STATE_REPAY_MONEY;
 
		_companies_ainew[c->index].state = AI_STATE_REPAY_MONEY;
 
		return;
 
	}
 

	
 
	if (_players_ainew[p->index].action == AI_ACTION_CHECK_ALL_VEHICLES) {
 
		_players_ainew[p->index].state = AI_STATE_CHECK_ALL_VEHICLES;
 
	if (_companies_ainew[c->index].action == AI_ACTION_CHECK_ALL_VEHICLES) {
 
		_companies_ainew[c->index].state = AI_STATE_CHECK_ALL_VEHICLES;
 
		return;
 
	}
 

	
 
	// It is useless to start finding a route if we don't have enough money
 
	//  to build the route anyway..
 
	if (_players_ainew[p->index].action == AI_ACTION_BUS_ROUTE &&
 
	if (_companies_ainew[c->index].action == AI_ACTION_BUS_ROUTE &&
 
			money > AI_MINIMUM_BUS_ROUTE_MONEY) {
 
		if (GetFreeUnitNumber(VEH_ROAD) > _settings_game.vehicle.max_roadveh) {
 
			_players_ainew[p->index].action = AI_ACTION_NONE;
 
			_companies_ainew[c->index].action = AI_ACTION_NONE;
 
			return;
 
		}
 
		_players_ainew[p->index].cargo = AI_NEED_CARGO;
 
		_players_ainew[p->index].state = AI_STATE_LOCATE_ROUTE;
 
		_players_ainew[p->index].tbt = AI_BUS; // Bus-route
 
		_companies_ainew[c->index].cargo = AI_NEED_CARGO;
 
		_companies_ainew[c->index].state = AI_STATE_LOCATE_ROUTE;
 
		_companies_ainew[c->index].tbt = AI_BUS; // Bus-route
 
		return;
 
	}
 
	if (_players_ainew[p->index].action == AI_ACTION_TRUCK_ROUTE &&
 
	if (_companies_ainew[c->index].action == AI_ACTION_TRUCK_ROUTE &&
 
			money > AI_MINIMUM_TRUCK_ROUTE_MONEY) {
 
		if (GetFreeUnitNumber(VEH_ROAD) > _settings_game.vehicle.max_roadveh) {
 
			_players_ainew[p->index].action = AI_ACTION_NONE;
 
			_companies_ainew[c->index].action = AI_ACTION_NONE;
 
			return;
 
		}
 
		_players_ainew[p->index].cargo = AI_NEED_CARGO;
 
		_players_ainew[p->index].last_id = 0;
 
		_players_ainew[p->index].state = AI_STATE_LOCATE_ROUTE;
 
		_players_ainew[p->index].tbt = AI_TRUCK;
 
		_companies_ainew[c->index].cargo = AI_NEED_CARGO;
 
		_companies_ainew[c->index].last_id = 0;
 
		_companies_ainew[c->index].state = AI_STATE_LOCATE_ROUTE;
 
		_companies_ainew[c->index].tbt = AI_TRUCK;
 
		return;
 
	}
 

	
 
	_players_ainew[p->index].state = AI_STATE_NOTHING;
 
	_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
}
 

	
 

	
 
static void AiNew_State_ActionDone(Player *p)
 
static void AiNew_State_ActionDone(Company *c)
 
{
 
	_players_ainew[p->index].action = AI_ACTION_NONE;
 
	_players_ainew[p->index].state = AI_STATE_NOTHING;
 
	_companies_ainew[c->index].action = AI_ACTION_NONE;
 
	_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
}
 

	
 

	
 
// Check if a city or industry is good enough to start a route there
 
static bool AiNew_Check_City_or_Industry(Player *p, int ic, byte type)
 
static bool AiNew_Check_City_or_Industry(Company *c, int ic, byte type)
 
{
 
	if (type == AI_CITY) {
 
		const Town* t = GetTown(ic);
 
@@ -226,7 +225,7 @@ static bool AiNew_Check_City_or_Industry
 

	
 
		// Check if the rating in a city is high enough
 
		//  If not, take a chance if we want to continue
 
		if (t->ratings[_current_player] < 0 && AI_CHANCE16(1, 4)) return false;
 
		if (t->ratings[_current_company] < 0 && AI_CHANCE16(1, 4)) return false;
 

	
 
		if (t->max_pass - t->act_pass < AI_CHECKCITY_NEEDED_CARGO && !AI_CHANCE16(1, AI_CHECKCITY_CITY_CHANCE)) return false;
 

	
 
@@ -236,9 +235,9 @@ static bool AiNew_Check_City_or_Industry
 
		//  This way we don't get 12 busstations in one city of 100 population ;)
 
		FOR_ALL_STATIONS(st) {
 
			// Do we own it?
 
			if (st->owner == _current_player) {
 
			if (st->owner == _current_company) {
 
				// Are we talking busses?
 
				if (_players_ainew[p->index].tbt == AI_BUS && (FACIL_BUS_STOP & st->facilities) != FACIL_BUS_STOP) continue;
 
				if (_companies_ainew[c->index].tbt == AI_BUS && (FACIL_BUS_STOP & st->facilities) != FACIL_BUS_STOP) continue;
 
				// Is it the same city as we are in now?
 
				if (st->town != t) continue;
 
				// When was this station build?
 
@@ -281,7 +280,7 @@ static bool AiNew_Check_City_or_Industry
 
		int count = 0;
 
		int j = 0;
 

	
 
		if (i->town != NULL && i->town->ratings[_current_player] < 0 && AI_CHANCE16(1, 4)) return false;
 
		if (i->town != NULL && i->town->ratings[_current_company] < 0 && AI_CHANCE16(1, 4)) return false;
 

	
 
		// No limits on delevering stations!
 
		//  Or for industry that does not give anything yet
 
@@ -294,9 +293,9 @@ static bool AiNew_Check_City_or_Industry
 
		//  and sometimes it takes up to 4 months before the stats are corectly.
 
		FOR_ALL_STATIONS(st) {
 
			// Do we own it?
 
			if (st->owner == _current_player) {
 
			if (st->owner == _current_company) {
 
				// Are we talking trucks?
 
				if (_players_ainew[p->index].tbt == AI_TRUCK && (FACIL_TRUCK_STOP & st->facilities) != FACIL_TRUCK_STOP) continue;
 
				if (_companies_ainew[c->index].tbt == AI_TRUCK && (FACIL_TRUCK_STOP & st->facilities) != FACIL_TRUCK_STOP) continue;
 
				// Is it the same city as we are in now?
 
				if (st->town != i->town) continue;
 
				// When was this station build?
 
@@ -338,32 +337,32 @@ static bool AiNew_Check_City_or_Industry
 

	
 

	
 
// This functions tries to locate a good route
 
static void AiNew_State_LocateRoute(Player *p)
 
static void AiNew_State_LocateRoute(Company *c)
 
{
 
	assert(_players_ainew[p->index].state == AI_STATE_LOCATE_ROUTE);
 
	assert(_companies_ainew[c->index].state == AI_STATE_LOCATE_ROUTE);
 
	// For now, we only support PASSENGERS, CITY and BUSSES
 

	
 
	// We don't have a route yet
 
	if (_players_ainew[p->index].cargo == AI_NEED_CARGO) {
 
		_players_ainew[p->index].new_cost = 0; // No cost yet
 
		_players_ainew[p->index].temp = -1;
 
	if (_companies_ainew[c->index].cargo == AI_NEED_CARGO) {
 
		_companies_ainew[c->index].new_cost = 0; // No cost yet
 
		_companies_ainew[c->index].temp = -1;
 
		// Reset the counter
 
		_players_ainew[p->index].counter = 0;
 
		_companies_ainew[c->index].counter = 0;
 

	
 
		_players_ainew[p->index].from_ic = -1;
 
		_players_ainew[p->index].to_ic = -1;
 
		if (_players_ainew[p->index].tbt == AI_BUS) {
 
		_companies_ainew[c->index].from_ic = -1;
 
		_companies_ainew[c->index].to_ic = -1;
 
		if (_companies_ainew[c->index].tbt == AI_BUS) {
 
			// For now we only have a passenger route
 
			_players_ainew[p->index].cargo = CT_PASSENGERS;
 
			_companies_ainew[c->index].cargo = CT_PASSENGERS;
 

	
 
			// Find a route to cities
 
			_players_ainew[p->index].from_type = AI_CITY;
 
			_players_ainew[p->index].to_type = AI_CITY;
 
		} else if (_players_ainew[p->index].tbt == AI_TRUCK) {
 
			_players_ainew[p->index].cargo = AI_NO_CARGO;
 
			_companies_ainew[c->index].from_type = AI_CITY;
 
			_companies_ainew[c->index].to_type = AI_CITY;
 
		} else if (_companies_ainew[c->index].tbt == AI_TRUCK) {
 
			_companies_ainew[c->index].cargo = AI_NO_CARGO;
 

	
 
			_players_ainew[p->index].from_type = AI_INDUSTRY;
 
			_players_ainew[p->index].to_type = AI_INDUSTRY;
 
			_companies_ainew[c->index].from_type = AI_INDUSTRY;
 
			_companies_ainew[c->index].to_type = AI_INDUSTRY;
 
		}
 

	
 
		// Now we are doing initing, we wait one tick
 
@@ -371,63 +370,63 @@ static void AiNew_State_LocateRoute(Play
 
	}
 

	
 
	// Increase the counter and abort if it is taking too long!
 
	_players_ainew[p->index].counter++;
 
	if (_players_ainew[p->index].counter > AI_LOCATE_ROUTE_MAX_COUNTER) {
 
	_companies_ainew[c->index].counter++;
 
	if (_companies_ainew[c->index].counter > AI_LOCATE_ROUTE_MAX_COUNTER) {
 
		// Switch back to doing nothing!
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
		return;
 
	}
 

	
 
	// We are going to locate a city from where we are going to connect
 
	if (_players_ainew[p->index].from_ic == -1) {
 
		if (_players_ainew[p->index].temp == -1) {
 
	if (_companies_ainew[c->index].from_ic == -1) {
 
		if (_companies_ainew[c->index].temp == -1) {
 
			// First, we pick a random spot to search from
 
			if (_players_ainew[p->index].from_type == AI_CITY) {
 
				_players_ainew[p->index].temp = AI_RandomRange(GetMaxTownIndex() + 1);
 
			if (_companies_ainew[c->index].from_type == AI_CITY) {
 
				_companies_ainew[c->index].temp = AI_RandomRange(GetMaxTownIndex() + 1);
 
			} else {
 
				_players_ainew[p->index].temp = AI_RandomRange(GetMaxIndustryIndex() + 1);
 
				_companies_ainew[c->index].temp = AI_RandomRange(GetMaxIndustryIndex() + 1);
 
			}
 
		}
 

	
 
		if (!AiNew_Check_City_or_Industry(p, _players_ainew[p->index].temp, _players_ainew[p->index].from_type)) {
 
		if (!AiNew_Check_City_or_Industry(c, _companies_ainew[c->index].temp, _companies_ainew[c->index].from_type)) {
 
			// It was not a valid city
 
			//  increase the temp with one, and return. We will come back later here
 
			//  to try again
 
			_players_ainew[p->index].temp++;
 
			if (_players_ainew[p->index].from_type == AI_CITY) {
 
				if (_players_ainew[p->index].temp > GetMaxTownIndex()) _players_ainew[p->index].temp = 0;
 
			_companies_ainew[c->index].temp++;
 
			if (_companies_ainew[c->index].from_type == AI_CITY) {
 
				if (_companies_ainew[c->index].temp > GetMaxTownIndex()) _companies_ainew[c->index].temp = 0;
 
			} else {
 
				if (_players_ainew[p->index].temp > GetMaxIndustryIndex()) _players_ainew[p->index].temp = 0;
 
				if (_companies_ainew[c->index].temp > GetMaxIndustryIndex()) _companies_ainew[c->index].temp = 0;
 
			}
 

	
 
			// Don't do an attempt if we are trying the same id as the last time...
 
			if (_players_ainew[p->index].last_id == _players_ainew[p->index].temp) return;
 
			_players_ainew[p->index].last_id = _players_ainew[p->index].temp;
 
			if (_companies_ainew[c->index].last_id == _companies_ainew[c->index].temp) return;
 
			_companies_ainew[c->index].last_id = _companies_ainew[c->index].temp;
 

	
 
			return;
 
		}
 

	
 
		// We found a good city/industry, save the data of it
 
		_players_ainew[p->index].from_ic = _players_ainew[p->index].temp;
 
		_companies_ainew[c->index].from_ic = _companies_ainew[c->index].temp;
 

	
 
		// Start the next tick with finding a to-city
 
		_players_ainew[p->index].temp = -1;
 
		_companies_ainew[c->index].temp = -1;
 
		return;
 
	}
 

	
 
	// Find a to-city
 
	if (_players_ainew[p->index].temp == -1) {
 
	if (_companies_ainew[c->index].temp == -1) {
 
		// First, we pick a random spot to search to
 
		if (_players_ainew[p->index].to_type == AI_CITY) {
 
			_players_ainew[p->index].temp = AI_RandomRange(GetMaxTownIndex() + 1);
 
		if (_companies_ainew[c->index].to_type == AI_CITY) {
 
			_companies_ainew[c->index].temp = AI_RandomRange(GetMaxTownIndex() + 1);
 
		} else {
 
			_players_ainew[p->index].temp = AI_RandomRange(GetMaxIndustryIndex() + 1);
 
			_companies_ainew[c->index].temp = AI_RandomRange(GetMaxIndustryIndex() + 1);
 
		}
 
	}
 

	
 
	// The same city is not allowed
 
	// Also check if the city is valid
 
	if (_players_ainew[p->index].temp != _players_ainew[p->index].from_ic && AiNew_Check_City_or_Industry(p, _players_ainew[p->index].temp, _players_ainew[p->index].to_type)) {
 
	if (_companies_ainew[c->index].temp != _companies_ainew[c->index].from_ic && AiNew_Check_City_or_Industry(c, _companies_ainew[c->index].temp, _companies_ainew[c->index].to_type)) {
 
		// Maybe it is valid..
 

	
 
		/* We need to know if they are not to far apart from eachother..
 
@@ -435,9 +434,9 @@ static void AiNew_State_LocateRoute(Play
 
		 * route is.
 
		 */
 

	
 
		if (_players_ainew[p->index].from_type == AI_CITY && _players_ainew[p->index].tbt == AI_BUS) {
 
			const Town* town_from = GetTown(_players_ainew[p->index].from_ic);
 
			const Town* town_temp = GetTown(_players_ainew[p->index].temp);
 
		if (_companies_ainew[c->index].from_type == AI_CITY && _companies_ainew[c->index].tbt == AI_BUS) {
 
			const Town* town_from = GetTown(_companies_ainew[c->index].from_ic);
 
			const Town* town_temp = GetTown(_companies_ainew[c->index].temp);
 
			uint distance = DistanceManhattan(town_from->xy, town_temp->xy);
 
			int max_cargo;
 

	
 
@@ -448,23 +447,23 @@ static void AiNew_State_LocateRoute(Play
 
			// If it is more than the distance, we allow it
 
			if (distance <= max_cargo * AI_LOCATEROUTE_BUS_CARGO_DISTANCE) {
 
				// We found a good city/industry, save the data of it
 
				_players_ainew[p->index].to_ic = _players_ainew[p->index].temp;
 
				_players_ainew[p->index].state = AI_STATE_FIND_STATION;
 
				_companies_ainew[c->index].to_ic = _companies_ainew[c->index].temp;
 
				_companies_ainew[c->index].state = AI_STATE_FIND_STATION;
 

	
 
				DEBUG(ai, 1, "[LocateRoute] found bus-route of %d tiles long (from %d to %d)",
 
					distance,
 
					_players_ainew[p->index].from_ic,
 
					_players_ainew[p->index].temp
 
					_companies_ainew[c->index].from_ic,
 
					_companies_ainew[c->index].temp
 
				);
 

	
 
				_players_ainew[p->index].from_tile = 0;
 
				_players_ainew[p->index].to_tile = 0;
 
				_companies_ainew[c->index].from_tile = 0;
 
				_companies_ainew[c->index].to_tile = 0;
 

	
 
				return;
 
			}
 
		} else if (_players_ainew[p->index].tbt == AI_TRUCK) {
 
			const Industry* ind_from = GetIndustry(_players_ainew[p->index].from_ic);
 
			const Industry* ind_temp = GetIndustry(_players_ainew[p->index].temp);
 
		} else if (_companies_ainew[c->index].tbt == AI_TRUCK) {
 
			const Industry* ind_from = GetIndustry(_companies_ainew[c->index].from_ic);
 
			const Industry* ind_temp = GetIndustry(_companies_ainew[c->index].temp);
 
			bool found = false;
 
			int max_cargo = 0;
 
			uint i;
 
@@ -478,8 +477,8 @@ static void AiNew_State_LocateRoute(Play
 
						// Found a compatible industry
 
						max_cargo = ind_from->last_month_production[0] - ind_from->last_month_transported[0];
 
						found = true;
 
						_players_ainew[p->index].from_deliver = true;
 
						_players_ainew[p->index].to_deliver = false;
 
						_companies_ainew[c->index].from_deliver = true;
 
						_companies_ainew[c->index].to_deliver = false;
 
						break;
 
					}
 
				}
 
@@ -492,8 +491,8 @@ static void AiNew_State_LocateRoute(Play
 
						// Found a compatbiel industry
 
						found = true;
 
						max_cargo = ind_temp->last_month_production[0] - ind_temp->last_month_transported[0];
 
						_players_ainew[p->index].from_deliver = false;
 
						_players_ainew[p->index].to_deliver = true;
 
						_companies_ainew[c->index].from_deliver = false;
 
						_companies_ainew[c->index].to_deliver = true;
 
						break;
 
					}
 
				}
 
@@ -505,22 +504,22 @@ static void AiNew_State_LocateRoute(Play
 

	
 
				if (distance > AI_LOCATEROUTE_TRUCK_MIN_DISTANCE &&
 
						distance <= max_cargo * AI_LOCATEROUTE_TRUCK_CARGO_DISTANCE) {
 
					_players_ainew[p->index].to_ic = _players_ainew[p->index].temp;
 
					if (_players_ainew[p->index].from_deliver) {
 
						_players_ainew[p->index].cargo = ind_from->produced_cargo[0];
 
					_companies_ainew[c->index].to_ic = _companies_ainew[c->index].temp;
 
					if (_companies_ainew[c->index].from_deliver) {
 
						_companies_ainew[c->index].cargo = ind_from->produced_cargo[0];
 
					} else {
 
						_players_ainew[p->index].cargo = ind_temp->produced_cargo[0];
 
						_companies_ainew[c->index].cargo = ind_temp->produced_cargo[0];
 
					}
 
					_players_ainew[p->index].state = AI_STATE_FIND_STATION;
 
					_companies_ainew[c->index].state = AI_STATE_FIND_STATION;
 

	
 
					DEBUG(ai, 1, "[LocateRoute] found truck-route of %d tiles long (from %d to %d)",
 
						distance,
 
						_players_ainew[p->index].from_ic,
 
						_players_ainew[p->index].temp
 
						_companies_ainew[c->index].from_ic,
 
						_companies_ainew[c->index].temp
 
					);
 

	
 
					_players_ainew[p->index].from_tile = 0;
 
					_players_ainew[p->index].to_tile = 0;
 
					_companies_ainew[c->index].from_tile = 0;
 
					_companies_ainew[c->index].to_tile = 0;
 

	
 
					return;
 
				}
 
@@ -531,29 +530,29 @@ static void AiNew_State_LocateRoute(Play
 
	// It was not a valid city
 
	//  increase the temp with one, and return. We will come back later here
 
	//  to try again
 
	_players_ainew[p->index].temp++;
 
	if (_players_ainew[p->index].to_type == AI_CITY) {
 
		if (_players_ainew[p->index].temp > GetMaxTownIndex()) _players_ainew[p->index].temp = 0;
 
	_companies_ainew[c->index].temp++;
 
	if (_companies_ainew[c->index].to_type == AI_CITY) {
 
		if (_companies_ainew[c->index].temp > GetMaxTownIndex()) _companies_ainew[c->index].temp = 0;
 
	} else {
 
		if (_players_ainew[p->index].temp > GetMaxIndustryIndex()) _players_ainew[p->index].temp = 0;
 
		if (_companies_ainew[c->index].temp > GetMaxIndustryIndex()) _companies_ainew[c->index].temp = 0;
 
	}
 

	
 
	// Don't do an attempt if we are trying the same id as the last time...
 
	if (_players_ainew[p->index].last_id == _players_ainew[p->index].temp) return;
 
	_players_ainew[p->index].last_id = _players_ainew[p->index].temp;
 
	if (_companies_ainew[c->index].last_id == _companies_ainew[c->index].temp) return;
 
	_companies_ainew[c->index].last_id = _companies_ainew[c->index].temp;
 
}
 

	
 

	
 
// Check if there are not more than a certain amount of vehicles pointed to a certain
 
//  station. This to prevent 10 busses going to one station, which gives... problems ;)
 
static bool AiNew_CheckVehicleStation(Player *p, Station *st)
 
static bool AiNew_CheckVehicleStation(Company *c, Station *st)
 
{
 
	int count = 0;
 
	Vehicle *v;
 

	
 
	// Also check if we don't have already a lot of busses to this city...
 
	FOR_ALL_VEHICLES(v) {
 
		if (v->owner == _current_player) {
 
		if (v->owner == _current_company) {
 
			const Order *order;
 

	
 
			FOR_VEHICLE_ORDERS(v, order) {
 
@@ -570,7 +569,7 @@ static bool AiNew_CheckVehicleStation(Pl
 
}
 

	
 
// This function finds a good spot for a station
 
static void AiNew_State_FindStation(Player *p)
 
static void AiNew_State_FindStation(Company *c)
 
{
 
	TileIndex tile;
 
	Station *st;
 
@@ -579,50 +578,50 @@ static void AiNew_State_FindStation(Play
 
	TileIndex new_tile = 0;
 
	DiagDirection direction = DIAGDIR_NE;
 
	Town *town = NULL;
 
	assert(_players_ainew[p->index].state == AI_STATE_FIND_STATION);
 
	assert(_companies_ainew[c->index].state == AI_STATE_FIND_STATION);
 

	
 
	if (_players_ainew[p->index].from_tile == 0) {
 
	if (_companies_ainew[c->index].from_tile == 0) {
 
		// First we scan for a station in the from-city
 
		if (_players_ainew[p->index].from_type == AI_CITY) {
 
			town = GetTown(_players_ainew[p->index].from_ic);
 
		if (_companies_ainew[c->index].from_type == AI_CITY) {
 
			town = GetTown(_companies_ainew[c->index].from_ic);
 
			tile = town->xy;
 
		} else {
 
			tile = GetIndustry(_players_ainew[p->index].from_ic)->xy;
 
			tile = GetIndustry(_companies_ainew[c->index].from_ic)->xy;
 
		}
 
	} else if (_players_ainew[p->index].to_tile == 0) {
 
	} else if (_companies_ainew[c->index].to_tile == 0) {
 
		// Second we scan for a station in the to-city
 
		if (_players_ainew[p->index].to_type == AI_CITY) {
 
			town = GetTown(_players_ainew[p->index].to_ic);
 
		if (_companies_ainew[c->index].to_type == AI_CITY) {
 
			town = GetTown(_companies_ainew[c->index].to_ic);
 
			tile = town->xy;
 
		} else {
 
			tile = GetIndustry(_players_ainew[p->index].to_ic)->xy;
 
			tile = GetIndustry(_companies_ainew[c->index].to_ic)->xy;
 
		}
 
	} else {
 
		// Unsupported request
 
		// Go to FIND_PATH
 
		_players_ainew[p->index].temp = -1;
 
		_players_ainew[p->index].state = AI_STATE_FIND_PATH;
 
		_companies_ainew[c->index].temp = -1;
 
		_companies_ainew[c->index].state = AI_STATE_FIND_PATH;
 
		return;
 
	}
 

	
 
	// First, we are going to look at the stations that already exist inside the city
 
	//  If there is enough cargo left in the station, we take that station
 
	//  If that is not possible, and there are more than 2 stations in the city, abort
 
	i = AiNew_PickVehicle(p);
 
	i = AiNew_PickVehicle(c);
 
	// Euhmz, this should not happen _EVER_
 
	// Quit finding a route...
 
	if (i == INVALID_ENGINE) {
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
		return;
 
	}
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->owner == _current_player) {
 
			if (_players_ainew[p->index].tbt == AI_BUS && (FACIL_BUS_STOP & st->facilities) == FACIL_BUS_STOP) {
 
		if (st->owner == _current_company) {
 
			if (_companies_ainew[c->index].tbt == AI_BUS && (FACIL_BUS_STOP & st->facilities) == FACIL_BUS_STOP) {
 
				if (st->town == town) {
 
					// Check how much cargo there is left in the station
 
					if ((int)st->goods[_players_ainew[p->index].cargo].cargo.Count() > RoadVehInfo(i)->capacity * AI_STATION_REUSE_MULTIPLER) {
 
						if (AiNew_CheckVehicleStation(p, st)) {
 
					if ((int)st->goods[_companies_ainew[c->index].cargo].cargo.Count() > RoadVehInfo(i)->capacity * AI_STATION_REUSE_MULTIPLER) {
 
						if (AiNew_CheckVehicleStation(c, st)) {
 
							// We did found a station that was good enough!
 
							new_tile = st->xy;
 
							direction = GetRoadStopDir(st->xy);
 
@@ -639,11 +638,11 @@ static void AiNew_State_FindStation(Play
 
	// No more than 2 stations allowed in a city
 
	//  This is because only the best 2 stations of one cargo do get any cargo
 
	if (count > 2) {
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
		return;
 
	}
 

	
 
	if (new_tile == 0 && _players_ainew[p->index].tbt == AI_BUS) {
 
	if (new_tile == 0 && _companies_ainew[c->index].tbt == AI_BUS) {
 
		uint x, y, i = 0;
 
		CommandCost r;
 
		uint best;
 
@@ -663,20 +662,20 @@ static void AiNew_State_FindStation(Play
 
					// XXX - Get the catchment area
 
					GetAcceptanceAroundTiles(accepts, new_tile, 1, 1, 4);
 
					// >> 3 == 0 means no cargo
 
					if (accepts[_players_ainew[p->index].cargo] >> 3 == 0) continue;
 
					if (accepts[_companies_ainew[c->index].cargo] >> 3 == 0) continue;
 
					// See if we can build the station
 
					r = AiNew_Build_Station(p, _players_ainew[p->index].tbt, new_tile, 0, 0, 0, DC_QUERY_COST);
 
					r = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, new_tile, 0, 0, 0, DC_QUERY_COST);
 
					if (CmdFailed(r)) continue;
 
					// We can build it, so add it to found_spot
 
					found_spot[i] = new_tile;
 
					found_best[i++] = accepts[_players_ainew[p->index].cargo];
 
					found_best[i++] = accepts[_companies_ainew[c->index].cargo];
 
				}
 
			}
 
		}
 

	
 
		// If i is still zero, we did not find anything
 
		if (i == 0) {
 
			_players_ainew[p->index].state = AI_STATE_NOTHING;
 
			_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
			return;
 
		}
 

	
 
@@ -693,11 +692,11 @@ static void AiNew_State_FindStation(Play
 
		}
 

	
 
		// See how much it is going to cost us...
 
		r = AiNew_Build_Station(p, _players_ainew[p->index].tbt, new_tile, 0, 0, 0, DC_QUERY_COST);
 
		_players_ainew[p->index].new_cost += r.GetCost();
 
		r = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, new_tile, 0, 0, 0, DC_QUERY_COST);
 
		_companies_ainew[c->index].new_cost += r.GetCost();
 

	
 
		direction = (DiagDirection)AI_PATHFINDER_NO_DIRECTION;
 
	} else if (new_tile == 0 && _players_ainew[p->index].tbt == AI_TRUCK) {
 
	} else if (new_tile == 0 && _companies_ainew[c->index].tbt == AI_TRUCK) {
 
		// Truck station locater works differently.. a station can be on any place
 
		//  as long as it is in range. So we give back code AI_STATION_RANGE
 
		//  so the pathfinder routine can work it out!
 
@@ -705,76 +704,76 @@ static void AiNew_State_FindStation(Play
 
		direction = (DiagDirection)AI_PATHFINDER_NO_DIRECTION;
 
	}
 

	
 
	if (_players_ainew[p->index].from_tile == 0) {
 
		_players_ainew[p->index].from_tile = new_tile;
 
		_players_ainew[p->index].from_direction = direction;
 
	if (_companies_ainew[c->index].from_tile == 0) {
 
		_companies_ainew[c->index].from_tile = new_tile;
 
		_companies_ainew[c->index].from_direction = direction;
 
		// Now we found thisone, go in for to_tile
 
		return;
 
	} else if (_players_ainew[p->index].to_tile == 0) {
 
		_players_ainew[p->index].to_tile = new_tile;
 
		_players_ainew[p->index].to_direction = direction;
 
	} else if (_companies_ainew[c->index].to_tile == 0) {
 
		_companies_ainew[c->index].to_tile = new_tile;
 
		_companies_ainew[c->index].to_direction = direction;
 
		// K, done placing stations!
 
		_players_ainew[p->index].temp = -1;
 
		_players_ainew[p->index].state = AI_STATE_FIND_PATH;
 
		_companies_ainew[c->index].temp = -1;
 
		_companies_ainew[c->index].state = AI_STATE_FIND_PATH;
 
		return;
 
	}
 
}
 

	
 

	
 
// We try to find a path between 2 points
 
static void AiNew_State_FindPath(Player *p)
 
static void AiNew_State_FindPath(Company *c)
 
{
 
	int r;
 
	assert(_players_ainew[p->index].state == AI_STATE_FIND_PATH);
 
	assert(_companies_ainew[c->index].state == AI_STATE_FIND_PATH);
 

	
 
	// First time, init some data
 
	if (_players_ainew[p->index].temp == -1) {
 
	if (_companies_ainew[c->index].temp == -1) {
 
		// Init path_info
 
		if (_players_ainew[p->index].from_tile == AI_STATION_RANGE) {
 
			const Industry* i = GetIndustry(_players_ainew[p->index].from_ic);
 
		if (_companies_ainew[c->index].from_tile == AI_STATION_RANGE) {
 
			const Industry* i = GetIndustry(_companies_ainew[c->index].from_ic);
 

	
 
			// For truck routes we take a range around the industry
 
			_players_ainew[p->index].path_info.start_tile_tl = i->xy - TileDiffXY(1, 1);
 
			_players_ainew[p->index].path_info.start_tile_br = i->xy + TileDiffXY(i->width + 1, i->height + 1);
 
			_players_ainew[p->index].path_info.start_direction = _players_ainew[p->index].from_direction;
 
			_companies_ainew[c->index].path_info.start_tile_tl = i->xy - TileDiffXY(1, 1);
 
			_companies_ainew[c->index].path_info.start_tile_br = i->xy + TileDiffXY(i->width + 1, i->height + 1);
 
			_companies_ainew[c->index].path_info.start_direction = _companies_ainew[c->index].from_direction;
 
		} else {
 
			_players_ainew[p->index].path_info.start_tile_tl = _players_ainew[p->index].from_tile;
 
			_players_ainew[p->index].path_info.start_tile_br = _players_ainew[p->index].from_tile;
 
			_players_ainew[p->index].path_info.start_direction = _players_ainew[p->index].from_direction;
 
			_companies_ainew[c->index].path_info.start_tile_tl = _companies_ainew[c->index].from_tile;
 
			_companies_ainew[c->index].path_info.start_tile_br = _companies_ainew[c->index].from_tile;
 
			_companies_ainew[c->index].path_info.start_direction = _companies_ainew[c->index].from_direction;
 
		}
 

	
 
		if (_players_ainew[p->index].to_tile == AI_STATION_RANGE) {
 
			const Industry* i = GetIndustry(_players_ainew[p->index].to_ic);
 
		if (_companies_ainew[c->index].to_tile == AI_STATION_RANGE) {
 
			const Industry* i = GetIndustry(_companies_ainew[c->index].to_ic);
 

	
 
			_players_ainew[p->index].path_info.end_tile_tl = i->xy - TileDiffXY(1, 1);
 
			_players_ainew[p->index].path_info.end_tile_br = i->xy + TileDiffXY(i->width + 1, i->height + 1);
 
			_players_ainew[p->index].path_info.end_direction = _players_ainew[p->index].to_direction;
 
			_companies_ainew[c->index].path_info.end_tile_tl = i->xy - TileDiffXY(1, 1);
 
			_companies_ainew[c->index].path_info.end_tile_br = i->xy + TileDiffXY(i->width + 1, i->height + 1);
 
			_companies_ainew[c->index].path_info.end_direction = _companies_ainew[c->index].to_direction;
 
		} else {
 
			_players_ainew[p->index].path_info.end_tile_tl = _players_ainew[p->index].to_tile;
 
			_players_ainew[p->index].path_info.end_tile_br = _players_ainew[p->index].to_tile;
 
			_players_ainew[p->index].path_info.end_direction = _players_ainew[p->index].to_direction;
 
			_companies_ainew[c->index].path_info.end_tile_tl = _companies_ainew[c->index].to_tile;
 
			_companies_ainew[c->index].path_info.end_tile_br = _companies_ainew[c->index].to_tile;
 
			_companies_ainew[c->index].path_info.end_direction = _companies_ainew[c->index].to_direction;
 
		}
 

	
 
		_players_ainew[p->index].path_info.rail_or_road = (_players_ainew[p->index].tbt == AI_TRAIN);
 
		_companies_ainew[c->index].path_info.rail_or_road = (_companies_ainew[c->index].tbt == AI_TRAIN);
 

	
 
		// First, clean the pathfinder with our new begin and endpoints
 
		clean_AyStar_AiPathFinder(_players_ainew[p->index].pathfinder, &_players_ainew[p->index].path_info);
 
		clean_AyStar_AiPathFinder(_companies_ainew[c->index].pathfinder, &_companies_ainew[c->index].path_info);
 

	
 
		_players_ainew[p->index].temp = 0;
 
		_companies_ainew[c->index].temp = 0;
 
	}
 

	
 
	// Start the pathfinder
 
	r = _players_ainew[p->index].pathfinder->main(_players_ainew[p->index].pathfinder);
 
	r = _companies_ainew[c->index].pathfinder->main(_companies_ainew[c->index].pathfinder);
 
	switch (r) {
 
		case AYSTAR_NO_PATH:
 
			DEBUG(ai, 1, "No route found by pathfinder");
 
			// Start all over again
 
			_players_ainew[p->index].state = AI_STATE_NOTHING;
 
			_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
			break;
 

	
 
		case AYSTAR_FOUND_END_NODE: // We found the end-point
 
			_players_ainew[p->index].temp = -1;
 
			_players_ainew[p->index].state = AI_STATE_FIND_DEPOT;
 
			_companies_ainew[c->index].temp = -1;
 
			_companies_ainew[c->index].state = AI_STATE_FIND_DEPOT;
 
			break;
 

	
 
		// In any other case, we are still busy finding the route
 
@@ -784,7 +783,7 @@ static void AiNew_State_FindPath(Player 
 

	
 

	
 
// This function tries to locate a good place for a depot!
 
static void AiNew_State_FindDepot(Player *p)
 
static void AiNew_State_FindDepot(Company *c)
 
{
 
	// To place the depot, we walk through the route, and if we find a lovely spot (MP_CLEAR, MP_TREES), we place it there..
 
	// Simple, easy, works!
 
@@ -795,21 +794,21 @@ static void AiNew_State_FindDepot(Player
 
	CommandCost r;
 
	DiagDirection j;
 
	TileIndex tile;
 
	assert(_players_ainew[p->index].state == AI_STATE_FIND_DEPOT);
 
	assert(_companies_ainew[c->index].state == AI_STATE_FIND_DEPOT);
 

	
 
	_players_ainew[p->index].depot_tile = 0;
 
	_companies_ainew[c->index].depot_tile = 0;
 

	
 
	for (i = 2; i < _players_ainew[p->index].path_info.route_length - 2; i++) {
 
		tile = _players_ainew[p->index].path_info.route[i];
 
	for (i = 2; i < _companies_ainew[c->index].path_info.route_length - 2; i++) {
 
		tile = _companies_ainew[c->index].path_info.route[i];
 
		for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) {
 
			TileIndex t = tile + TileOffsByDiagDir(j);
 

	
 
			if (IsRoadDepotTile(t) &&
 
					IsTileOwner(t, _current_player) &&
 
					IsTileOwner(t, _current_company) &&
 
					GetRoadDepotDirection(t) == ReverseDiagDir(j)) {
 
				_players_ainew[p->index].depot_tile = t;
 
				_players_ainew[p->index].depot_direction = ReverseDiagDir(j);
 
				_players_ainew[p->index].state = AI_STATE_VERIFY_ROUTE;
 
				_companies_ainew[c->index].depot_tile = t;
 
				_companies_ainew[c->index].depot_direction = ReverseDiagDir(j);
 
				_companies_ainew[c->index].state = AI_STATE_VERIFY_ROUTE;
 
				return;
 
			}
 
		}
 
@@ -817,19 +816,19 @@ static void AiNew_State_FindDepot(Player
 

	
 
	// This routine let depot finding start in the middle, and work his way to the stations
 
	// It makes depot placing nicer :)
 
	i = _players_ainew[p->index].path_info.route_length / 2;
 
	i = _companies_ainew[c->index].path_info.route_length / 2;
 
	g = 1;
 
	while (i > 1 && i < _players_ainew[p->index].path_info.route_length - 2) {
 
	while (i > 1 && i < _companies_ainew[c->index].path_info.route_length - 2) {
 
		i += g;
 
		g *= -1;
 
		(g < 0 ? g-- : g++);
 

	
 
		if (_players_ainew[p->index].path_info.route_extra[i] != 0 || _players_ainew[p->index].path_info.route_extra[i + 1] != 0) {
 
		if (_companies_ainew[c->index].path_info.route_extra[i] != 0 || _companies_ainew[c->index].path_info.route_extra[i + 1] != 0) {
 
			// Bridge or tunnel.. we can't place a depot there
 
			continue;
 
		}
 

	
 
		tile = _players_ainew[p->index].path_info.route[i];
 
		tile = _companies_ainew[c->index].path_info.route[i];
 

	
 
		for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) {
 
			TileIndex t = tile + TileOffsByDiagDir(j);
 
@@ -837,32 +836,32 @@ static void AiNew_State_FindDepot(Player
 
			// It may not be placed on the road/rail itself
 
			// And because it is not build yet, we can't see it on the tile..
 
			// So check the surrounding tiles :)
 
			if (t == _players_ainew[p->index].path_info.route[i - 1] ||
 
					t == _players_ainew[p->index].path_info.route[i + 1]) {
 
			if (t == _companies_ainew[c->index].path_info.route[i - 1] ||
 
					t == _companies_ainew[c->index].path_info.route[i + 1]) {
 
				continue;
 
			}
 
			// Not around a bridge?
 
			if (_players_ainew[p->index].path_info.route_extra[i] != 0) continue;
 
			if (_companies_ainew[c->index].path_info.route_extra[i] != 0) continue;
 
			if (IsTileType(tile, MP_TUNNELBRIDGE)) continue;
 
			// Is the terrain clear?
 
			if (IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)) {
 
				// If the current tile is on a slope then we do not allow this
 
				if (GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
 
				// Check if everything went okay..
 
				r = AiNew_Build_Depot(p, t, ReverseDiagDir(j), 0);
 
				r = AiNew_Build_Depot(c, t, ReverseDiagDir(j), 0);
 
				if (CmdFailed(r)) continue;
 
				// Found a spot!
 
				_players_ainew[p->index].new_cost += r.GetCost();
 
				_players_ainew[p->index].depot_tile = t;
 
				_players_ainew[p->index].depot_direction = ReverseDiagDir(j); // Reverse direction
 
				_players_ainew[p->index].state = AI_STATE_VERIFY_ROUTE;
 
				_companies_ainew[c->index].new_cost += r.GetCost();
 
				_companies_ainew[c->index].depot_tile = t;
 
				_companies_ainew[c->index].depot_direction = ReverseDiagDir(j); // Reverse direction
 
				_companies_ainew[c->index].state = AI_STATE_VERIFY_ROUTE;
 
				return;
 
			}
 
		}
 
	}
 

	
 
	// Failed to find a depot?
 
	_players_ainew[p->index].state = AI_STATE_NOTHING;
 
	_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
}
 

	
 

	
 
@@ -871,17 +870,17 @@ static void AiNew_State_FindDepot(Player
 
// It works pretty simple: get the length, see how much we move around
 
//  and hussle that, and you know how many vehicles there are needed.
 
// It returns the cost for the vehicles
 
static int AiNew_HowManyVehicles(Player *p)
 
static int AiNew_HowManyVehicles(Company *c)
 
{
 
	if (_players_ainew[p->index].tbt == AI_BUS) {
 
	if (_companies_ainew[c->index].tbt == AI_BUS) {
 
		// For bus-routes we look at the time before we are back in the station
 
		EngineID i;
 
		int length, tiles_a_day;
 
		int amount;
 
		i = AiNew_PickVehicle(p);
 
		i = AiNew_PickVehicle(c);
 
		if (i == INVALID_ENGINE) return 0;
 
		// Passenger run.. how long is the route?
 
		length = _players_ainew[p->index].path_info.route_length;
 
		length = _companies_ainew[c->index].path_info.route_length;
 
		// Calculating tiles a day a vehicle moves is not easy.. this is how it must be done!
 
		tiles_a_day = RoadVehInfo(i)->max_speed * DAY_TICKS / 256 / 16;
 
		if (tiles_a_day == 0) tiles_a_day = 1;
 
@@ -890,22 +889,22 @@ static int AiNew_HowManyVehicles(Player 
 
		amount = length * 2 * 2 / tiles_a_day / 30;
 
		if (amount == 0) amount = 1;
 
		return amount;
 
	} else if (_players_ainew[p->index].tbt == AI_TRUCK) {
 
	} else if (_companies_ainew[c->index].tbt == AI_TRUCK) {
 
		// For truck-routes we look at the cargo
 
		EngineID i;
 
		int length, amount, tiles_a_day;
 
		int max_cargo;
 
		i = AiNew_PickVehicle(p);
 
		i = AiNew_PickVehicle(c);
 
		if (i == INVALID_ENGINE) return 0;
 
		// Passenger run.. how long is the route?
 
		length = _players_ainew[p->index].path_info.route_length;
 
		length = _companies_ainew[c->index].path_info.route_length;
 
		// Calculating tiles a day a vehicle moves is not easy.. this is how it must be done!
 
		tiles_a_day = RoadVehInfo(i)->max_speed * DAY_TICKS / 256 / 16;
 
		if (tiles_a_day == 0) tiles_a_day = 1;
 
		if (_players_ainew[p->index].from_deliver) {
 
			max_cargo = GetIndustry(_players_ainew[p->index].from_ic)->last_month_production[0];
 
		if (_companies_ainew[c->index].from_deliver) {
 
			max_cargo = GetIndustry(_companies_ainew[c->index].from_ic)->last_month_production[0];
 
		} else {
 
			max_cargo = GetIndustry(_players_ainew[p->index].to_ic)->last_month_production[0];
 
			max_cargo = GetIndustry(_companies_ainew[c->index].to_ic)->last_month_production[0];
 
		}
 

	
 
		// This is because moving 60% is more than we can dream of!
 
@@ -928,116 +927,116 @@ static int AiNew_HowManyVehicles(Player 
 
//   - If the route went okay
 
//   - Calculates the amount of money needed to build the route
 
//   - Calculates how much vehicles needed for the route
 
static void AiNew_State_VerifyRoute(Player *p)
 
static void AiNew_State_VerifyRoute(Company *c)
 
{
 
	int res, i;
 
	assert(_players_ainew[p->index].state == AI_STATE_VERIFY_ROUTE);
 
	assert(_companies_ainew[c->index].state == AI_STATE_VERIFY_ROUTE);
 

	
 
	// Let's calculate the cost of the path..
 
	//  new_cost already contains the cost of the stations
 
	_players_ainew[p->index].path_info.position = -1;
 
	_companies_ainew[c->index].path_info.position = -1;
 

	
 
	do {
 
		_players_ainew[p->index].path_info.position++;
 
		_players_ainew[p->index].new_cost += AiNew_Build_RoutePart(p, &_players_ainew[p->index].path_info, DC_QUERY_COST).GetCost();
 
	} while (_players_ainew[p->index].path_info.position != -2);
 
		_companies_ainew[c->index].path_info.position++;
 
		_companies_ainew[c->index].new_cost += AiNew_Build_RoutePart(c, &_companies_ainew[c->index].path_info, DC_QUERY_COST).GetCost();
 
	} while (_companies_ainew[c->index].path_info.position != -2);
 

	
 
	// Now we know the price of build station + path. Now check how many vehicles
 
	//  we need and what the price for that will be
 
	res = AiNew_HowManyVehicles(p);
 
	res = AiNew_HowManyVehicles(c);
 
	// If res == 0, no vehicle was found, or an other problem did occour
 
	if (res == 0) {
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
		return;
 
	}
 
	_players_ainew[p->index].amount_veh = res;
 
	_players_ainew[p->index].cur_veh = 0;
 
	_companies_ainew[c->index].amount_veh = res;
 
	_companies_ainew[c->index].cur_veh = 0;
 

	
 
	// Check how much it it going to cost us..
 
	for (i = 0; i < res; i++) {
 
		_players_ainew[p->index].new_cost += AiNew_Build_Vehicle(p, 0, DC_QUERY_COST).GetCost();
 
		_companies_ainew[c->index].new_cost += AiNew_Build_Vehicle(c, 0, DC_QUERY_COST).GetCost();
 
	}
 

	
 
	// Now we know how much the route is going to cost us
 
	//  Check if we have enough money for it!
 
	if (_players_ainew[p->index].new_cost > p->player_money - AI_MINIMUM_MONEY) {
 
	if (_companies_ainew[c->index].new_cost > c->money - AI_MINIMUM_MONEY) {
 
		// Too bad..
 
		DEBUG(ai, 1, "Insufficient funds to build route (%" OTTD_PRINTF64 "d)", (int64)_players_ainew[p->index].new_cost);
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		DEBUG(ai, 1, "Insufficient funds to build route (%" OTTD_PRINTF64 "d)", (int64)_companies_ainew[c->index].new_cost);
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
		return;
 
	}
 

	
 
	// Now we can build the route, check the direction of the stations!
 
	if (_players_ainew[p->index].from_direction == AI_PATHFINDER_NO_DIRECTION) {
 
		_players_ainew[p->index].from_direction = AiNew_GetDirection(_players_ainew[p->index].path_info.route[_players_ainew[p->index].path_info.route_length - 1], _players_ainew[p->index].path_info.route[_players_ainew[p->index].path_info.route_length - 2]);
 
	if (_companies_ainew[c->index].from_direction == AI_PATHFINDER_NO_DIRECTION) {
 
		_companies_ainew[c->index].from_direction = AiNew_GetDirection(_companies_ainew[c->index].path_info.route[_companies_ainew[c->index].path_info.route_length - 1], _companies_ainew[c->index].path_info.route[_companies_ainew[c->index].path_info.route_length - 2]);
 
	}
 
	if (_players_ainew[p->index].to_direction == AI_PATHFINDER_NO_DIRECTION) {
 
		_players_ainew[p->index].to_direction = AiNew_GetDirection(_players_ainew[p->index].path_info.route[0], _players_ainew[p->index].path_info.route[1]);
 
	if (_companies_ainew[c->index].to_direction == AI_PATHFINDER_NO_DIRECTION) {
 
		_companies_ainew[c->index].to_direction = AiNew_GetDirection(_companies_ainew[c->index].path_info.route[0], _companies_ainew[c->index].path_info.route[1]);
 
	}
 
	if (_players_ainew[p->index].from_tile == AI_STATION_RANGE)
 
		_players_ainew[p->index].from_tile = _players_ainew[p->index].path_info.route[_players_ainew[p->index].path_info.route_length - 1];
 
	if (_players_ainew[p->index].to_tile == AI_STATION_RANGE)
 
		_players_ainew[p->index].to_tile = _players_ainew[p->index].path_info.route[0];
 
	if (_companies_ainew[c->index].from_tile == AI_STATION_RANGE)
 
		_companies_ainew[c->index].from_tile = _companies_ainew[c->index].path_info.route[_companies_ainew[c->index].path_info.route_length - 1];
 
	if (_companies_ainew[c->index].to_tile == AI_STATION_RANGE)
 
		_companies_ainew[c->index].to_tile = _companies_ainew[c->index].path_info.route[0];
 

	
 
	_players_ainew[p->index].state = AI_STATE_BUILD_STATION;
 
	_players_ainew[p->index].temp = 0;
 
	_companies_ainew[c->index].state = AI_STATE_BUILD_STATION;
 
	_companies_ainew[c->index].temp = 0;
 

	
 
	DEBUG(ai, 1, "The route is set and buildable, building 0x%X to 0x%X...", _players_ainew[p->index].from_tile, _players_ainew[p->index].to_tile);
 
	DEBUG(ai, 1, "The route is set and buildable, building 0x%X to 0x%X...", _companies_ainew[c->index].from_tile, _companies_ainew[c->index].to_tile);
 
}
 

	
 

	
 
// Build the stations
 
static void AiNew_State_BuildStation(Player *p)
 
static void AiNew_State_BuildStation(Company *c)
 
{
 
	CommandCost res;
 
	assert(_players_ainew[p->index].state == AI_STATE_BUILD_STATION);
 
	if (_players_ainew[p->index].temp == 0) {
 
		if (!IsTileType(_players_ainew[p->index].from_tile, MP_STATION))
 
			res = AiNew_Build_Station(p, _players_ainew[p->index].tbt, _players_ainew[p->index].from_tile, 0, 0, _players_ainew[p->index].from_direction, DC_EXEC);
 
	assert(_companies_ainew[c->index].state == AI_STATE_BUILD_STATION);
 
	if (_companies_ainew[c->index].temp == 0) {
 
		if (!IsTileType(_companies_ainew[c->index].from_tile, MP_STATION))
 
			res = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, _companies_ainew[c->index].from_tile, 0, 0, _companies_ainew[c->index].from_direction, DC_EXEC);
 
	} else {
 
		if (!IsTileType(_players_ainew[p->index].to_tile, MP_STATION))
 
			res = AiNew_Build_Station(p, _players_ainew[p->index].tbt, _players_ainew[p->index].to_tile, 0, 0, _players_ainew[p->index].to_direction, DC_EXEC);
 
		_players_ainew[p->index].state = AI_STATE_BUILD_PATH;
 
		if (!IsTileType(_companies_ainew[c->index].to_tile, MP_STATION))
 
			res = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, _companies_ainew[c->index].to_tile, 0, 0, _companies_ainew[c->index].to_direction, DC_EXEC);
 
		_companies_ainew[c->index].state = AI_STATE_BUILD_PATH;
 
	}
 
	if (CmdFailed(res)) {
 
		DEBUG(ai, 0, "[BuildStation] station could not be built (0x%X)", _players_ainew[p->index].to_tile);
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		DEBUG(ai, 0, "[BuildStation] station could not be built (0x%X)", _companies_ainew[c->index].to_tile);
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
		// If the first station _was_ build, destroy it
 
		if (_players_ainew[p->index].temp != 0)
 
			AI_DoCommand(_players_ainew[p->index].from_tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
 
		if (_companies_ainew[c->index].temp != 0)
 
			AI_DoCommand(_companies_ainew[c->index].from_tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
 
		return;
 
	}
 
	_players_ainew[p->index].temp++;
 
	_companies_ainew[c->index].temp++;
 
}
 

	
 

	
 
// Build the path
 
static void AiNew_State_BuildPath(Player *p)
 
static void AiNew_State_BuildPath(Company *c)
 
{
 
	assert(_players_ainew[p->index].state == AI_STATE_BUILD_PATH);
 
	// _players_ainew[p->index].temp is set to -1 when this function is called for the first time
 
	if (_players_ainew[p->index].temp == -1) {
 
	assert(_companies_ainew[c->index].state == AI_STATE_BUILD_PATH);
 
	// _companies_ainew[c->index].temp is set to -1 when this function is called for the first time
 
	if (_companies_ainew[c->index].temp == -1) {
 
		DEBUG(ai, 1, "Starting to build new path");
 
		// Init the counter
 
		_players_ainew[p->index].counter = (4 - _settings_game.difficulty.competitor_speed) * AI_BUILDPATH_PAUSE + 1;
 
		_companies_ainew[c->index].counter = (4 - _settings_game.difficulty.competitor_speed) * AI_BUILDPATH_PAUSE + 1;
 
		// Set the position to the startingplace (-1 because in a minute we do ++)
 
		_players_ainew[p->index].path_info.position = -1;
 
		_companies_ainew[c->index].path_info.position = -1;
 
		// And don't do this again
 
		_players_ainew[p->index].temp = 0;
 
		_companies_ainew[c->index].temp = 0;
 
	}
 
	// Building goes very fast on normal rate, so we are going to slow it down..
 
	//  By let the counter count from AI_BUILDPATH_PAUSE to 0, we have a nice way :)
 
	if (--_players_ainew[p->index].counter != 0) return;
 
	_players_ainew[p->index].counter = (4 - _settings_game.difficulty.competitor_speed) * AI_BUILDPATH_PAUSE + 1;
 
	if (--_companies_ainew[c->index].counter != 0) return;
 
	_companies_ainew[c->index].counter = (4 - _settings_game.difficulty.competitor_speed) * AI_BUILDPATH_PAUSE + 1;
 

	
 
	// Increase the building position
 
	_players_ainew[p->index].path_info.position++;
 
	_companies_ainew[c->index].path_info.position++;
 
	// Build route
 
	AiNew_Build_RoutePart(p, &_players_ainew[p->index].path_info, DC_EXEC);
 
	if (_players_ainew[p->index].path_info.position == -2) {
 
	AiNew_Build_RoutePart(c, &_companies_ainew[c->index].path_info, DC_EXEC);
 
	if (_companies_ainew[c->index].path_info.position == -2) {
 
		// This means we are done building!
 

	
 
		if (_players_ainew[p->index].tbt == AI_TRUCK && !_settings_game.pf.roadveh_queue) {
 
		if (_companies_ainew[c->index].tbt == AI_TRUCK && !_settings_game.pf.roadveh_queue) {
 
			// If they not queue, they have to go up and down to try again at a station...
 
			// We don't want that, so try building some road left or right of the station
 
			DiagDirection dir1, dir2, dir3;
 
@@ -1045,15 +1044,15 @@ static void AiNew_State_BuildPath(Player
 
			CommandCost ret;
 
			for (int i = 0; i < 2; i++) {
 
				if (i == 0) {
 
					tile = _players_ainew[p->index].from_tile + TileOffsByDiagDir(_players_ainew[p->index].from_direction);
 
					dir1 = ChangeDiagDir(_players_ainew[p->index].from_direction, DIAGDIRDIFF_90LEFT);
 
					dir2 = ChangeDiagDir(_players_ainew[p->index].from_direction, DIAGDIRDIFF_90RIGHT);
 
					dir3 = _players_ainew[p->index].from_direction;
 
					tile = _companies_ainew[c->index].from_tile + TileOffsByDiagDir(_companies_ainew[c->index].from_direction);
 
					dir1 = ChangeDiagDir(_companies_ainew[c->index].from_direction, DIAGDIRDIFF_90LEFT);
 
					dir2 = ChangeDiagDir(_companies_ainew[c->index].from_direction, DIAGDIRDIFF_90RIGHT);
 
					dir3 = _companies_ainew[c->index].from_direction;
 
				} else {
 
					tile = _players_ainew[p->index].to_tile + TileOffsByDiagDir(_players_ainew[p->index].to_direction);
 
					dir1 = ChangeDiagDir(_players_ainew[p->index].to_direction, DIAGDIRDIFF_90LEFT);
 
					dir2 = ChangeDiagDir(_players_ainew[p->index].to_direction, DIAGDIRDIFF_90RIGHT);
 
					dir3 = _players_ainew[p->index].to_direction;
 
					tile = _companies_ainew[c->index].to_tile + TileOffsByDiagDir(_companies_ainew[c->index].to_direction);
 
					dir1 = ChangeDiagDir(_companies_ainew[c->index].to_direction, DIAGDIRDIFF_90LEFT);
 
					dir2 = ChangeDiagDir(_companies_ainew[c->index].to_direction, DIAGDIRDIFF_90RIGHT);
 
					dir3 = _companies_ainew[c->index].to_direction;
 
				}
 

	
 
				ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir1)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 
@@ -1094,152 +1093,152 @@ static void AiNew_State_BuildPath(Player
 
			}
 
		}
 

	
 
		DEBUG(ai, 1, "Finished building path, cost: %" OTTD_PRINTF64 "d", (int64)_players_ainew[p->index].new_cost);
 
		_players_ainew[p->index].state = AI_STATE_BUILD_DEPOT;
 
		DEBUG(ai, 1, "Finished building path, cost: %" OTTD_PRINTF64 "d", (int64)_companies_ainew[c->index].new_cost);
 
		_companies_ainew[c->index].state = AI_STATE_BUILD_DEPOT;
 
	}
 
}
 

	
 

	
 
// Builds the depot
 
static void AiNew_State_BuildDepot(Player *p)
 
static void AiNew_State_BuildDepot(Company *c)
 
{
 
	CommandCost res;
 
	assert(_players_ainew[p->index].state == AI_STATE_BUILD_DEPOT);
 
	assert(_companies_ainew[c->index].state == AI_STATE_BUILD_DEPOT);
 

	
 
	if (IsRoadDepotTile(_players_ainew[p->index].depot_tile)) {
 
		if (IsTileOwner(_players_ainew[p->index].depot_tile, _current_player)) {
 
	if (IsRoadDepotTile(_companies_ainew[c->index].depot_tile)) {
 
		if (IsTileOwner(_companies_ainew[c->index].depot_tile, _current_company)) {
 
			// The depot is already built
 
			_players_ainew[p->index].state = AI_STATE_BUILD_VEHICLE;
 
			_companies_ainew[c->index].state = AI_STATE_BUILD_VEHICLE;
 
			return;
 
		} else {
 
			// There is a depot, but not of our team! :(
 
			_players_ainew[p->index].state = AI_STATE_NOTHING;
 
			_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
			return;
 
		}
 
	}
 

	
 
	// There is a bus on the tile we want to build road on... idle till he is gone! (BAD PERSON! :p)
 
	if (!EnsureNoVehicleOnGround(_players_ainew[p->index].depot_tile + TileOffsByDiagDir(_players_ainew[p->index].depot_direction)))
 
	if (!EnsureNoVehicleOnGround(_companies_ainew[c->index].depot_tile + TileOffsByDiagDir(_companies_ainew[c->index].depot_direction)))
 
		return;
 

	
 
	res = AiNew_Build_Depot(p, _players_ainew[p->index].depot_tile, _players_ainew[p->index].depot_direction, DC_EXEC);
 
	res = AiNew_Build_Depot(c, _companies_ainew[c->index].depot_tile, _companies_ainew[c->index].depot_direction, DC_EXEC);
 
	if (CmdFailed(res)) {
 
		DEBUG(ai, 0, "[BuildDepot] depot could not be built (0x%X)", _players_ainew[p->index].depot_tile);
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		DEBUG(ai, 0, "[BuildDepot] depot could not be built (0x%X)", _companies_ainew[c->index].depot_tile);
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
		return;
 
	}
 

	
 
	_players_ainew[p->index].state = AI_STATE_BUILD_VEHICLE;
 
	_players_ainew[p->index].idle = 10;
 
	_players_ainew[p->index].veh_main_id = INVALID_VEHICLE;
 
	_companies_ainew[c->index].state = AI_STATE_BUILD_VEHICLE;
 
	_companies_ainew[c->index].idle = 10;
 
	_companies_ainew[c->index].veh_main_id = INVALID_VEHICLE;
 
}
 

	
 

	
 
// Build vehicles
 
static void AiNew_State_BuildVehicle(Player *p)
 
static void AiNew_State_BuildVehicle(Company *c)
 
{
 
	CommandCost res;
 
	assert(_players_ainew[p->index].state == AI_STATE_BUILD_VEHICLE);
 
	assert(_companies_ainew[c->index].state == AI_STATE_BUILD_VEHICLE);
 

	
 
	// Check if we need to build a vehicle
 
	if (_players_ainew[p->index].amount_veh == 0) {
 
	if (_companies_ainew[c->index].amount_veh == 0) {
 
		// Nope, we are done!
 
		// This means: we are all done! The route is open.. go back to NOTHING
 
		//  He will idle some time and it will all start over again.. :)
 
		_players_ainew[p->index].state = AI_STATE_ACTION_DONE;
 
		_companies_ainew[c->index].state = AI_STATE_ACTION_DONE;
 
		return;
 
	}
 
	if (--_players_ainew[p->index].idle != 0) return;
 
	if (--_companies_ainew[c->index].idle != 0) return;
 
	// It is realistic that the AI can only build 1 vehicle a day..
 
	// This makes sure of that!
 
	_players_ainew[p->index].idle = AI_BUILD_VEHICLE_TIME_BETWEEN;
 
	_companies_ainew[c->index].idle = AI_BUILD_VEHICLE_TIME_BETWEEN;
 

	
 
	// Build the vehicle
 
	res = AiNew_Build_Vehicle(p, _players_ainew[p->index].depot_tile, DC_EXEC);
 
	res = AiNew_Build_Vehicle(c, _companies_ainew[c->index].depot_tile, DC_EXEC);
 
	if (CmdFailed(res)) {
 
		// This happens when the AI can't build any more vehicles!
 
		_players_ainew[p->index].state = AI_STATE_NOTHING;
 
		_companies_ainew[c->index].state = AI_STATE_NOTHING;
 
		return;
 
	}
 
	// Increase the current counter
 
	_players_ainew[p->index].cur_veh++;
 
	_companies_ainew[c->index].cur_veh++;
 
	// Decrease the total counter
 
	_players_ainew[p->index].amount_veh--;
 
	_companies_ainew[c->index].amount_veh--;
 
	// Go give some orders!
 
	_players_ainew[p->index].state = AI_STATE_WAIT_FOR_BUILD;
 
	_companies_ainew[c->index].state = AI_STATE_WAIT_FOR_BUILD;
 
}
 

	
 

	
 
// Put the stations in the order list
 
static void AiNew_State_GiveOrders(Player *p)
 
static void AiNew_State_GiveOrders(Company *c)
 
{
 
	int idx;
 
	Order order;
 

	
 
	assert(_players_ainew[p->index].state == AI_STATE_GIVE_ORDERS);
 
	assert(_companies_ainew[c->index].state == AI_STATE_GIVE_ORDERS);
 

	
 
	if (_players_ainew[p->index].veh_main_id != INVALID_VEHICLE) {
 
		AI_DoCommand(0, _players_ainew[p->index].veh_id + (_players_ainew[p->index].veh_main_id << 16), CO_SHARE, DC_EXEC, CMD_CLONE_ORDER);
 
	if (_companies_ainew[c->index].veh_main_id != INVALID_VEHICLE) {
 
		AI_DoCommand(0, _companies_ainew[c->index].veh_id + (_companies_ainew[c->index].veh_main_id << 16), CO_SHARE, DC_EXEC, CMD_CLONE_ORDER);
 

	
 
		_players_ainew[p->index].state = AI_STATE_START_VEHICLE;
 
		_companies_ainew[c->index].state = AI_STATE_START_VEHICLE;
 
		return;
 
	} else {
 
		_players_ainew[p->index].veh_main_id = _players_ainew[p->index].veh_id;
 
		_companies_ainew[c->index].veh_main_id = _companies_ainew[c->index].veh_id;
 
	}
 

	
 
	// Very handy for AI, goto depot.. but yeah, it needs to be activated ;)
 
	if (_settings_game.order.gotodepot) {
 
		idx = 0;
 
		order.MakeGoToDepot(GetDepotByTile(_players_ainew[p->index].depot_tile)->index, ODTFB_PART_OF_ORDERS);
 
		AI_DoCommand(0, _players_ainew[p->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 
		order.MakeGoToDepot(GetDepotByTile(_companies_ainew[c->index].depot_tile)->index, ODTFB_PART_OF_ORDERS);
 
		AI_DoCommand(0, _companies_ainew[c->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 
	}
 

	
 
	idx = 0;
 
	order.MakeGoToStation(GetStationIndex(_players_ainew[p->index].to_tile));
 
	if (_players_ainew[p->index].tbt == AI_TRUCK && _players_ainew[p->index].to_deliver) order.SetLoadType(OLFB_FULL_LOAD);
 
	AI_DoCommand(0, _players_ainew[p->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 
	order.MakeGoToStation(GetStationIndex(_companies_ainew[c->index].to_tile));
 
	if (_companies_ainew[c->index].tbt == AI_TRUCK && _companies_ainew[c->index].to_deliver) order.SetLoadType(OLFB_FULL_LOAD);
 
	AI_DoCommand(0, _companies_ainew[c->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 

	
 
	idx = 0;
 
	order.MakeGoToStation(GetStationIndex(_players_ainew[p->index].from_tile));
 
	if (_players_ainew[p->index].tbt == AI_TRUCK && _players_ainew[p->index].from_deliver) order.SetLoadType(OLFB_FULL_LOAD);
 
	AI_DoCommand(0, _players_ainew[p->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 
	order.MakeGoToStation(GetStationIndex(_companies_ainew[c->index].from_tile));
 
	if (_companies_ainew[c->index].tbt == AI_TRUCK && _companies_ainew[c->index].from_deliver) order.SetLoadType(OLFB_FULL_LOAD);
 
	AI_DoCommand(0, _companies_ainew[c->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER);
 

	
 
	// Start the engines!
 
	_players_ainew[p->index].state = AI_STATE_START_VEHICLE;
 
	_companies_ainew[c->index].state = AI_STATE_START_VEHICLE;
 
}
 

	
 

	
 
// Start the vehicle
 
static void AiNew_State_StartVehicle(Player *p)
 
static void AiNew_State_StartVehicle(Company *c)
 
{
 
	assert(_players_ainew[p->index].state == AI_STATE_START_VEHICLE);
 
	assert(_companies_ainew[c->index].state == AI_STATE_START_VEHICLE);
 

	
 
	// Skip the first order if it is a second vehicle
 
	//  This to make vehicles go different ways..
 
	if (_players_ainew[p->index].cur_veh & 1)
 
		AI_DoCommand(0, _players_ainew[p->index].veh_id, 1, DC_EXEC, CMD_SKIP_TO_ORDER);
 
	if (_companies_ainew[c->index].cur_veh & 1)
 
		AI_DoCommand(0, _companies_ainew[c->index].veh_id, 1, DC_EXEC, CMD_SKIP_TO_ORDER);
 

	
 
	// 3, 2, 1... go! (give START_STOP command ;))
 
	AI_DoCommand(0, _players_ainew[p->index].veh_id, 0, DC_EXEC, CMD_START_STOP_VEHICLE);
 
	AI_DoCommand(0, _companies_ainew[c->index].veh_id, 0, DC_EXEC, CMD_START_STOP_VEHICLE);
 
	// Try to build an other vehicle (that function will stop building when needed)
 
	_players_ainew[p->index].idle  = 10;
 
	_players_ainew[p->index].state = AI_STATE_BUILD_VEHICLE;
 
	_companies_ainew[c->index].idle  = 10;
 
	_companies_ainew[c->index].state = AI_STATE_BUILD_VEHICLE;
 
}
 

	
 

	
 
// Repays money
 
static void AiNew_State_RepayMoney(Player *p)
 
static void AiNew_State_RepayMoney(Company *c)
 
{
 
	uint i;
 

	
 
	for (i = 0; i < AI_LOAN_REPAY; i++) {
 
		AI_DoCommand(0, 0, 0, DC_EXEC, CMD_DECREASE_LOAN);
 
	}
 
	_players_ainew[p->index].state = AI_STATE_ACTION_DONE;
 
	_companies_ainew[c->index].state = AI_STATE_ACTION_DONE;
 
}
 

	
 

	
 
static void AiNew_CheckVehicle(Player *p, Vehicle *v)
 
static void AiNew_CheckVehicle(Company *c, Vehicle *v)
 
{
 
	// When a vehicle is under the 6 months, we don't check for anything
 
	if (v->age < 180) return;
 
@@ -1259,7 +1258,7 @@ static void AiNew_CheckVehicle(Player *p
 

	
 

	
 
			// We are already sending him back
 
			if (AiNew_GetSpecialVehicleFlag(p, v) & AI_VEHICLEFLAG_SELL) {
 
			if (AiNew_GetSpecialVehicleFlag(c, v) & AI_VEHICLEFLAG_SELL) {
 
				if (v->type == VEH_ROAD && IsRoadDepotTile(v->tile) &&
 
						(v->vehstatus & VS_STOPPED)) {
 
					// We are at the depot, sell the vehicle
 
@@ -1268,7 +1267,7 @@ static void AiNew_CheckVehicle(Player *p
 
				return;
 
			}
 

	
 
			if (!AiNew_SetSpecialVehicleFlag(p, v, AI_VEHICLEFLAG_SELL)) return;
 
			if (!AiNew_SetSpecialVehicleFlag(c, v, AI_VEHICLEFLAG_SELL)) return;
 
			{
 
				CommandCost ret;
 
				if (v->type == VEH_ROAD)
 
@@ -1282,19 +1281,19 @@ static void AiNew_CheckVehicle(Player *p
 

	
 

	
 
// Checks all vehicles if they are still valid and make money and stuff
 
static void AiNew_State_CheckAllVehicles(Player *p)
 
static void AiNew_State_CheckAllVehicles(Company *c)
 
{
 
	Vehicle *v;
 

	
 
	FOR_ALL_VEHICLES(v) {
 
		if (v->owner != p->index) continue;
 
		if (v->owner != c->index) continue;
 
		// Currently, we only know how to handle road-vehicles
 
		if (v->type != VEH_ROAD) continue;
 

	
 
		AiNew_CheckVehicle(p, v);
 
		AiNew_CheckVehicle(c, v);
 
	}
 

	
 
	_players_ainew[p->index].state = AI_STATE_ACTION_DONE;
 
	_companies_ainew[c->index].state = AI_STATE_ACTION_DONE;
 
}
 

	
 

	
 
@@ -1324,27 +1323,27 @@ static AiNew_StateFunction* const _ainew
 
	NULL,
 
};
 

	
 
static void AiNew_OnTick(Player *p)
 
static void AiNew_OnTick(Company *c)
 
{
 
	if (_ainew_state[_players_ainew[p->index].state] != NULL)
 
		_ainew_state[_players_ainew[p->index].state](p);
 
	if (_ainew_state[_companies_ainew[c->index].state] != NULL)
 
		_ainew_state[_companies_ainew[c->index].state](c);
 
}
 

	
 

	
 
void AiNewDoGameLoop(Player *p)
 
void AiNewDoGameLoop(Company *c)
 
{
 
	if (_players_ainew[p->index].state == AI_STATE_STARTUP) {
 
	if (_companies_ainew[c->index].state == AI_STATE_STARTUP) {
 
		// The AI just got alive!
 
		_players_ainew[p->index].state = AI_STATE_FIRST_TIME;
 
		_players_ainew[p->index].tick = 0;
 
		_companies_ainew[c->index].state = AI_STATE_FIRST_TIME;
 
		_companies_ainew[c->index].tick = 0;
 

	
 
		// Only startup the AI
 
		return;
 
	}
 

	
 
	// We keep a ticker. We use it for competitor_speed
 
	_players_ainew[p->index].tick++;
 
	_companies_ainew[c->index].tick++;
 

	
 
	// If we come here, we can do a tick.. do so!
 
	AiNew_OnTick(p);
 
	AiNew_OnTick(c);
 
}
src/ai/trolly/trolly.h
Show inline comments
 
@@ -120,7 +120,7 @@
 
// Minimum % of reliabilty a vehicle has to have before the AI buys it
 
#define AI_VEHICLE_MIN_RELIABILTY 60
 

	
 
// The minimum amount of money a player should always have
 
// The minimum amount of money a company should always have
 
#define AI_MINIMUM_MONEY 15000
 

	
 
// If the most cheap route is build, how much is it going to cost..
 
@@ -148,7 +148,7 @@
 

	
 
// How many days must there between vehicle checks
 
//  The more often, the less non-money-making lines there will be
 
//   but the unfair it may seem to a human player
 
//   but the unfair it may seem to a human company
 
#define AI_DAYS_BETWEEN_VEHICLE_CHECKS 30
 

	
 
// How money profit does a vehicle needs to make to stay in order
 
@@ -239,10 +239,10 @@ enum {
 
#define AI_PATHFINDER_FLAG_BRIDGE 1
 
#define AI_PATHFINDER_FLAG_TUNNEL 2
 

	
 
typedef void AiNew_StateFunction(Player *p);
 
typedef void AiNew_StateFunction(Company *c);
 

	
 
// ai_new.c
 
void AiNewDoGameLoop(Player *p);
 
void AiNewDoGameLoop(Company *c);
 

	
 
struct Ai_PathFinderInfo {
 
	TileIndex start_tile_tl; ///< tl = top-left
 
@@ -268,17 +268,17 @@ void clean_AyStar_AiPathFinder(AyStar *a
 
int AiNew_GetRailDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c);
 
int AiNew_GetRoadDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c);
 
DiagDirection AiNew_GetDirection(TileIndex tile_a, TileIndex tile_b);
 
bool AiNew_SetSpecialVehicleFlag(Player *p, Vehicle *v, uint flag);
 
uint AiNew_GetSpecialVehicleFlag(Player *p, Vehicle *v);
 
bool AiNew_SetSpecialVehicleFlag(Company *c, Vehicle *v, uint flag);
 
uint AiNew_GetSpecialVehicleFlag(Company *c, Vehicle *v);
 

	
 
// ai_build.c
 
bool AiNew_Build_CompanyHQ(Player *p, TileIndex tile);
 
CommandCost AiNew_Build_Station(Player *p, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag);
 
CommandCost AiNew_Build_Bridge(Player *p, TileIndex tile_a, TileIndex tile_b, byte flag);
 
CommandCost AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte flag);
 
EngineID AiNew_PickVehicle(Player *p);
 
CommandCost AiNew_Build_Vehicle(Player *p, TileIndex tile, byte flag);
 
CommandCost AiNew_Build_Depot(Player* p, TileIndex tile, DiagDirection direction, byte flag);
 
bool AiNew_Build_CompanyHQ(Company *c, TileIndex tile);
 
CommandCost AiNew_Build_Station(Company *c, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag);
 
CommandCost AiNew_Build_Bridge(Company *c, TileIndex tile_a, TileIndex tile_b, byte flag);
 
CommandCost AiNew_Build_RoutePart(Company *c, Ai_PathFinderInfo *PathFinderInfo, byte flag);
 
EngineID AiNew_PickVehicle(Company *c);
 
CommandCost AiNew_Build_Vehicle(Company *c, TileIndex tile, byte flag);
 
CommandCost AiNew_Build_Depot(Company *c, TileIndex tile, DiagDirection direction, byte flag);
 

	
 
/* The amount of memory reserved for the AI-special-vehicles */
 
#define AI_MAX_SPECIAL_VEHICLES 100
 
@@ -288,7 +288,7 @@ struct Ai_SpecialVehicle {
 
	uint32 flag;
 
};
 

	
 
struct PlayerAiNew {
 
struct CompanyAiNew {
 
	uint8 state;
 
	uint tick;
 
	uint idle;
 
@@ -338,6 +338,6 @@ struct PlayerAiNew {
 
	int to_ic;
 
	byte to_type;
 
};
 
extern PlayerAiNew _players_ainew[MAX_PLAYERS];
 
extern CompanyAiNew _companies_ainew[MAX_COMPANIES];
 

	
 
#endif /* AI_TROLLY_H */
src/aircraft_cmd.cpp
Show inline comments
 
@@ -104,7 +104,7 @@ enum HelicopterRotorStates {
 
};
 

	
 
/** Find the nearest hangar to v
 
 * INVALID_STATION is returned, if the player does not have any suitable
 
 * INVALID_STATION is returned, if the company does not have any suitable
 
 * airports (like helipads only)
 
 * @param v vehicle looking for a hangar
 
 * @return the StationID if one is found, otherwise, INVALID_STATION
 
@@ -266,7 +266,7 @@ uint16 AircraftDefaultCargoCapacity(Carg
 
 */
 
CommandCost CmdBuildAircraft(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	if (!IsEngineBuildable(p1, VEH_AIRCRAFT, _current_player)) return_cmd_error(STR_AIRCRAFT_NOT_AVAILABLE);
 
	if (!IsEngineBuildable(p1, VEH_AIRCRAFT, _current_company)) return_cmd_error(STR_AIRCRAFT_NOT_AVAILABLE);
 

	
 
	const AircraftVehicleInfo *avi = AircraftVehInfo(p1);
 
	CommandCost value = EstimateAircraftCost(p1, avi);
 
@@ -274,7 +274,7 @@ CommandCost CmdBuildAircraft(TileIndex t
 
	/* to just query the cost, it is not neccessary to have a valid tile (automation/AI) */
 
	if (flags & DC_QUERY_COST) return value;
 

	
 
	if (!IsHangarTile(tile) || !IsTileOwner(tile, _current_player)) return CMD_ERROR;
 
	if (!IsHangarTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
 

	
 
	/* Prevent building aircraft types at places which can't handle them */
 
	if (!CanAircraftUseStation(p1, tile)) return CMD_ERROR;
 
@@ -299,7 +299,7 @@ CommandCost CmdBuildAircraft(TileIndex t
 
		v->unitnumber = unit_num;
 
		v->direction = DIR_SE;
 

	
 
		v->owner = u->owner = _current_player;
 
		v->owner = u->owner = _current_company;
 

	
 
		v->tile = tile;
 
//		u->tile = 0;
 
@@ -428,7 +428,7 @@ CommandCost CmdBuildAircraft(TileIndex t
 

	
 
			w = new (w) Aircraft();
 
			w->direction = DIR_N;
 
			w->owner = _current_player;
 
			w->owner = _current_company;
 
			w->x_pos = v->x_pos;
 
			w->y_pos = v->y_pos;
 
			w->z_pos = v->z_pos + 5;
 
@@ -448,10 +448,10 @@ CommandCost CmdBuildAircraft(TileIndex t
 
		InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
 
		InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
 
		InvalidateWindow(WC_COMPANY, v->owner);
 
		if (IsLocalPlayer())
 
		if (IsLocalCompany())
 
			InvalidateAutoreplaceWindow(v->engine_type, v->group_id); //updates the replace Aircraft window
 

	
 
		GetPlayer(_current_player)->num_engines[p1]++;
 
		GetCompany(_current_company)->num_engines[p1]++;
 
	}
 

	
 
	return value;
 
@@ -529,7 +529,7 @@ CommandCost CmdSendAircraftToHangar(Tile
 
	if (p2 & DEPOT_MASS_SEND) {
 
		/* Mass goto depot requested */
 
		if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
 
		return SendAllVehiclesToDepot(VEH_AIRCRAFT, flags, p2 & DEPOT_SERVICE, _current_player, (p2 & VLW_MASK), p1);
 
		return SendAllVehiclesToDepot(VEH_AIRCRAFT, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
 
	}
 

	
 
	if (!IsValidVehicleID(p1)) return CMD_ERROR;
 
@@ -597,7 +597,7 @@ CommandCost CmdRefitAircraft(TileIndex t
 
	_returned_refit_capacity = pass;
 

	
 
	CommandCost cost;
 
	if (IsHumanPlayer(v->owner) && new_cid != v->cargo_type) {
 
	if (IsHumanCompany(v->owner) && new_cid != v->cargo_type) {
 
		cost = GetRefitCost(v->engine_type);
 
	}
 

	
 
@@ -660,7 +660,7 @@ void Aircraft::OnNewDay()
 
	this->profit_this_year -= cost.GetCost();
 
	this->running_ticks = 0;
 

	
 
	SubtractMoneyFromPlayerFract(this->owner, cost);
 
	SubtractMoneyFromCompanyFract(this->owner, cost);
 

	
 
	InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
 
	InvalidateWindowClasses(WC_AIRCRAFT_LIST);
 
@@ -1312,11 +1312,11 @@ void HandleMissingAircraftOrders(Vehicle
 
	const Station *st = GetTargetAirportIfValid(v);
 
	if (st == NULL) {
 
		CommandCost ret;
 
		PlayerID old_player = _current_player;
 
		CompanyID old_company = _current_company;
 

	
 
		_current_player = v->owner;
 
		_current_company = v->owner;
 
		ret = DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_SEND_AIRCRAFT_TO_HANGAR);
 
		_current_player = old_player;
 
		_current_company = old_company;
 

	
 
		if (CmdFailed(ret)) CrashAirplane(v);
 
	} else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
 
@@ -1413,7 +1413,7 @@ static void AircraftEntersTerminal(Vehic
 
		/* show newsitem of celebrating citizens */
 
		AddNewsItem(
 
			STR_A033_CITIZENS_CELEBRATE_FIRST,
 
			(v->owner == _local_player) ? NS_ARRIVAL_PLAYER : NS_ARRIVAL_OTHER,
 
			(v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
 
			v->index,
 
			st->index
 
		);
 
@@ -1477,28 +1477,28 @@ static void AircraftLeaveHangar(Vehicle 
 
static inline bool CheckSendAircraftToHangarForReplacement(const Vehicle *v)
 
{
 
	EngineID new_engine;
 
	Player *p = GetPlayer(v->owner);
 
	Company *c = GetCompany(v->owner);
 

	
 
	if (VehicleHasDepotOrders(v)) return false; // The aircraft will end up in the hangar eventually on it's own
 

	
 
	new_engine = EngineReplacementForPlayer(p, v->engine_type, v->group_id);
 
	new_engine = EngineReplacementForCompany(c, v->engine_type, v->group_id);
 

	
 
	if (new_engine == INVALID_ENGINE) {
 
		/* There is no autoreplace assigned to this EngineID so we will set it to renew to the same type if needed */
 
		new_engine = v->engine_type;
 

	
 
		if (!v->NeedsAutorenewing(p)) {
 
		if (!v->NeedsAutorenewing(c)) {
 
			/* No need to replace the aircraft */
 
			return false;
 
		}
 
	}
 

	
 
	if (!HasBit(GetEngine(new_engine)->player_avail, v->owner)) {
 
	if (!HasBit(GetEngine(new_engine)->company_avail, v->owner)) {
 
		/* Engine is not buildable anymore */
 
		return false;
 
	}
 

	
 
	if (p->player_money < (p->engine_renew_money + (2 * DoCommand(0, new_engine, 0, DC_QUERY_COST, CMD_BUILD_AIRCRAFT).GetCost()))) {
 
	if (c->money < (c->engine_renew_money + (2 * DoCommand(0, new_engine, 0, DC_QUERY_COST, CMD_BUILD_AIRCRAFT).GetCost()))) {
 
		/* We lack enough money to request the replacement right away.
 
		 * We want 2*(the price of the new vehicle) and not looking at the value of the vehicle we are going to sell.
 
		 * The reason is that we don't want to send a whole lot of vehicles to the hangars when we only have enough money to replace a single one.
 
@@ -1652,9 +1652,9 @@ static void AircraftEventHandler_HeliTak
 

	
 
	/* Send the helicopter to a hangar if needed for replacement */
 
	if (CheckSendAircraftToHangarForReplacement(v)) {
 
		_current_player = v->owner;
 
		_current_company = v->owner;
 
		DoCommand(v->tile, v->index, DEPOT_SERVICE | DEPOT_LOCATE_HANGAR, DC_EXEC, CMD_SEND_AIRCRAFT_TO_HANGAR);
 
		_current_player = OWNER_NONE;
 
		_current_company = OWNER_NONE;
 
	}
 
}
 

	
 
@@ -1704,9 +1704,9 @@ static void AircraftEventHandler_Landing
 

	
 
	/* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
 
	if (CheckSendAircraftToHangarForReplacement(v)) {
 
		_current_player = v->owner;
 
		_current_company = v->owner;
 
		DoCommand(v->tile, v->index, DEPOT_SERVICE, DC_EXEC, CMD_SEND_AIRCRAFT_TO_HANGAR);
 
		_current_player = OWNER_NONE;
 
		_current_company = OWNER_NONE;
 
	}
 
}
 

	
src/airport_gui.cpp
Show inline comments
 
@@ -146,7 +146,7 @@ static const WindowDesc _air_toolbar_des
 

	
 
void ShowBuildAirToolbar()
 
{
 
	if (!IsValidPlayerID(_current_player)) return;
 
	if (!IsValidCompanyID(_current_company)) return;
 

	
 
	DeleteWindowByClass(WC_BUILD_TOOLBAR);
 
	AllocateWindowDescFront<BuildAirToolbarWindow>(&_air_toolbar_desc, TRANSPORT_AIR);
src/autoreplace_cmd.cpp
Show inline comments
 
@@ -39,10 +39,10 @@ static bool EnginesGotCargoInCommon(Engi
 
 * Checks some basic properties whether autoreplace is allowed
 
 * @param from Origin engine
 
 * @param to Destination engine
 
 * @param player Player to check for
 
 * @param company Company to check for
 
 * @return true if autoreplace is allowed
 
 */
 
bool CheckAutoreplaceValidity(EngineID from, EngineID to, PlayerID player)
 
bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
 
{
 
	/* First we make sure that it's a valid type the user requested
 
	 * check that it's an engine that is in the engine array */
 
@@ -53,8 +53,8 @@ bool CheckAutoreplaceValidity(EngineID f
 

	
 
	VehicleType type = GetEngine(from)->type;
 

	
 
	/* check that the new vehicle type is available to the player and its type is the same as the original one */
 
	if (!IsEngineBuildable(to, type, player)) return false;
 
	/* check that the new vehicle type is available to the company and its type is the same as the original one */
 
	if (!IsEngineBuildable(to, type, company)) return false;
 

	
 
	switch (type) {
 
		case VEH_TRAIN: {
 
@@ -213,10 +213,10 @@ static CargoID GetNewCargoTypeForReplace
 

	
 
/** Get the EngineID of the replacement for a vehicle
 
 * @param v The vehicle to find a replacement for
 
 * @param p The vehicle's owner (it's faster to forward the pointer than refinding it)
 
 * @param c The vehicle's owner (it's faster to forward the pointer than refinding it)
 
 * @return the EngineID of the replacement. INVALID_ENGINE if no buildable replacement is found
 
 */
 
static EngineID GetNewEngineType(const Vehicle *v, const Player *p)
 
static EngineID GetNewEngineType(const Vehicle *v, const Company *c)
 
{
 
	assert(v->type != VEH_TRAIN || !IsArticulatedPart(v));
 

	
 
@@ -225,14 +225,14 @@ static EngineID GetNewEngineType(const V
 
		return INVALID_ENGINE;
 
	}
 

	
 
	EngineID e = EngineReplacementForPlayer(p, v->engine_type, v->group_id);
 
	EngineID e = EngineReplacementForCompany(c, v->engine_type, v->group_id);
 

	
 
	if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_player)) {
 
	if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
 
		return e;
 
	}
 

	
 
	if (v->NeedsAutorenewing(p) && // replace if engine is too old
 
	    IsEngineBuildable(v->engine_type, v->type, _current_player)) { // engine can still be build
 
	if (v->NeedsAutorenewing(c) && // replace if engine is too old
 
	    IsEngineBuildable(v->engine_type, v->type, _current_company)) { // engine can still be build
 
		return v->engine_type;
 
	}
 

	
 
@@ -251,8 +251,8 @@ static CommandCost BuildReplacementVehic
 
	*new_vehicle = NULL;
 

	
 
	/* Shall the vehicle be replaced? */
 
	const Player *p = GetPlayer(_current_player);
 
	EngineID e = GetNewEngineType(old_veh, p);
 
	const Company *c = GetCompany(_current_company);
 
	EngineID e = GetNewEngineType(old_veh, c);
 
	if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
 

	
 
	/* Does it need to be refitted */
 
@@ -627,14 +627,14 @@ CommandCost CmdAutoreplaceVehicle(TileIn
 
		if (!v->IsPrimaryVehicle()) return CMD_ERROR;
 
	}
 

	
 
	const Player *p = GetPlayer(_current_player);
 
	bool wagon_removal = p->renew_keep_length;
 
	const Company *c = GetCompany(_current_company);
 
	bool wagon_removal = c->renew_keep_length;
 

	
 
	/* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
 
	Vehicle *w = v;
 
	bool any_replacements = false;
 
	while (w != NULL && !any_replacements) {
 
		any_replacements = (GetNewEngineType(w, p) != INVALID_ENGINE);
 
		any_replacements = (GetNewEngineType(w, c) != INVALID_ENGINE);
 
		w = (!free_wagon && w->type == VEH_TRAIN ? GetNextUnit(w) : NULL);
 
	}
 

	
src/autoreplace_func.h
Show inline comments
 
@@ -9,9 +9,9 @@
 
#include "player_base.h"
 

	
 
/**
 
 * Remove all engine replacement settings for the player.
 
 * @param  erl The renewlist for a given player.
 
 * @return The new renewlist for the player.
 
 * Remove all engine replacement settings for the company.
 
 * @param  erl The renewlist for a given company.
 
 * @return The new renewlist for the company.
 
 */
 
void RemoveAllEngineReplacement(EngineRenewList *erl);
 

	
 
@@ -44,62 +44,62 @@ CommandCost AddEngineReplacement(EngineR
 
CommandCost RemoveEngineReplacement(EngineRenewList *erl, EngineID engine, GroupID group, uint32 flags);
 

	
 
/**
 
 * Remove all engine replacement settings for the given player.
 
 * @param p Player.
 
 * Remove all engine replacement settings for the given company.
 
 * @param c the company.
 
 */
 
static inline void RemoveAllEngineReplacementForPlayer(Player *p)
 
static inline void RemoveAllEngineReplacementForCompany(Company *c)
 
{
 
	RemoveAllEngineReplacement(&p->engine_renew_list);
 
	RemoveAllEngineReplacement(&c->engine_renew_list);
 
}
 

	
 
/**
 
 * Retrieve the engine replacement for the given player and original engine type.
 
 * @param p Player.
 
 * Retrieve the engine replacement for the given company and original engine type.
 
 * @param c company.
 
 * @param engine Engine type.
 
 * @return The engine type to replace with, or INVALID_ENGINE if no
 
 * replacement is in the list.
 
 */
 
static inline EngineID EngineReplacementForPlayer(const Player *p, EngineID engine, GroupID group)
 
static inline EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group)
 
{
 
	return EngineReplacement(p->engine_renew_list, engine, group);
 
	return EngineReplacement(c->engine_renew_list, engine, group);
 
}
 

	
 
/**
 
 * Check if a player has a replacement set up for the given engine.
 
 * @param p Player.
 
 * Check if a company has a replacement set up for the given engine.
 
 * @param c Company.
 
 * @param  engine Engine type to be replaced.
 
 * @return true if a replacement was set up, false otherwise.
 
 */
 
static inline bool EngineHasReplacementForPlayer(const Player *p, EngineID engine, GroupID group)
 
static inline bool EngineHasReplacementForCompany(const Company *c, EngineID engine, GroupID group)
 
{
 
	return EngineReplacementForPlayer(p, engine, group) != INVALID_ENGINE;
 
	return EngineReplacementForCompany(c, engine, group) != INVALID_ENGINE;
 
}
 

	
 
/**
 
 * Add an engine replacement for the player.
 
 * @param p Player.
 
 * Add an engine replacement for the company.
 
 * @param c Company.
 
 * @param old_engine The original engine type.
 
 * @param new_engine The replacement engine type.
 
 * @param flags The calling command flags.
 
 * @return 0 on success, CMD_ERROR on failure.
 
 */
 
static inline CommandCost AddEngineReplacementForPlayer(Player *p, EngineID old_engine, EngineID new_engine, GroupID group, uint32 flags)
 
static inline CommandCost AddEngineReplacementForCompany(Company *c, EngineID old_engine, EngineID new_engine, GroupID group, uint32 flags)
 
{
 
	return AddEngineReplacement(&p->engine_renew_list, old_engine, new_engine, group, flags);
 
	return AddEngineReplacement(&c->engine_renew_list, old_engine, new_engine, group, flags);
 
}
 

	
 
/**
 
 * Remove an engine replacement for the player.
 
 * @param p Player.
 
 * Remove an engine replacement for the company.
 
 * @param c Company.
 
 * @param engine The original engine type.
 
 * @param flags The calling command flags.
 
 * @return 0 on success, CMD_ERROR on failure.
 
 */
 
static inline CommandCost RemoveEngineReplacementForPlayer(Player *p, EngineID engine, GroupID group, uint32 flags)
 
static inline CommandCost RemoveEngineReplacementForCompany(Company *c, EngineID engine, GroupID group, uint32 flags)
 
{
 
	return RemoveEngineReplacement(&p->engine_renew_list, engine, group, flags);
 
	return RemoveEngineReplacement(&c->engine_renew_list, engine, group, flags);
 
}
 

	
 
bool CheckAutoreplaceValidity(EngineID from, EngineID to, PlayerID player);
 
bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company);
 

	
 
#endif /* AUTOREPLACE_FUNC_H */
src/autoreplace_gui.cpp
Show inline comments
 
@@ -71,10 +71,10 @@ static int CDECL EngineNumberSorter(cons
 
 */
 
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
 
{
 
	Player *p = GetPlayer(_local_player);
 
	uint num_engines = GetGroupNumEngines(_local_player, id_g, e);
 
	Company *c = GetCompany(_local_company);
 
	uint num_engines = GetGroupNumEngines(_local_company, id_g, e);
 

	
 
	if (num_engines == 0 || p->num_engines[e] == 0) {
 
	if (num_engines == 0 || c->num_engines[e] == 0) {
 
		/* We don't have any of this engine type.
 
		 * Either we just sold the last one, we build a new one or we stopped replacing it.
 
		 * In all cases, we need to update the left list */
 
@@ -147,12 +147,12 @@ class ReplaceVehicleWindow : public Wind
 

	
 
			if (draw_left) {
 
				const GroupID selected_group = this->sel_group;
 
				const uint num_engines = GetGroupNumEngines(_local_player, selected_group, eid);
 
				const uint num_engines = GetGroupNumEngines(_local_company, selected_group, eid);
 

	
 
				/* Skip drawing the engines we don't have any of and haven't set for replacement */
 
				if (num_engines == 0 && EngineReplacementForPlayer(GetPlayer(_local_player), eid, selected_group) == INVALID_ENGINE) continue;
 
				if (num_engines == 0 && EngineReplacementForCompany(GetCompany(_local_company), eid, selected_group) == INVALID_ENGINE) continue;
 
			} else {
 
				if (!CheckAutoreplaceValidity(this->sel_engine[0], eid, _local_player)) continue;
 
				if (!CheckAutoreplaceValidity(this->sel_engine[0], eid, _local_company)) continue;
 
			}
 

	
 
			*list->Append() = eid;
 
@@ -244,7 +244,7 @@ public:
 
		this->resize.width  = this->width;
 
		this->resize.height = this->height;
 

	
 
		this->caption_color = _local_player;
 
		this->caption_color = _local_company;
 
		this->sel_group = id_g;
 
		this->vscroll2.cap = this->vscroll.cap;   // these two are always the same
 

	
 
@@ -262,7 +262,7 @@ public:
 

	
 
		if (this->update_left || this->update_right) this->GenerateLists();
 

	
 
		Player *p = GetPlayer(_local_player);
 
		Company *c = GetCompany(_local_company);
 
		EngineID selected_id[2];
 
		const GroupID selected_group = this->sel_group;
 

	
 
@@ -276,29 +276,29 @@ public:
 
		this->SetWidgetDisabledState(RVW_WIDGET_START_REPLACE,
 
										selected_id[0] == INVALID_ENGINE ||
 
										selected_id[1] == INVALID_ENGINE ||
 
										EngineReplacementForPlayer(p, selected_id[1], selected_group) != INVALID_ENGINE ||
 
										EngineReplacementForPlayer(p, selected_id[0], selected_group) == selected_id[1]);
 
										EngineReplacementForCompany(c, selected_id[1], selected_group) != INVALID_ENGINE ||
 
										EngineReplacementForCompany(c, selected_id[0], selected_group) == selected_id[1]);
 

	
 
		/* Disable the "Stop Replacing" button if:
 
		 *   The left list (existing vehicle) is empty
 
		 *   or The selected vehicle has no replacement set up */
 
		this->SetWidgetDisabledState(RVW_WIDGET_STOP_REPLACE,
 
										selected_id[0] == INVALID_ENGINE ||
 
										!EngineHasReplacementForPlayer(p, selected_id[0], selected_group));
 
										!EngineHasReplacementForCompany(c, selected_id[0], selected_group));
 

	
 
		/* now the actual drawing of the window itself takes place */
 
		SetDParam(0, _vehicle_type_names[this->window_number]);
 

	
 
		if (this->window_number == VEH_TRAIN) {
 
			/* set on/off for renew_keep_length */
 
			SetDParam(1, p->renew_keep_length ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF);
 
			SetDParam(1, c->renew_keep_length ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF);
 

	
 
			/* set wagon/engine button */
 
			SetDParam(2, this->wagon_btnstate ? STR_ENGINES : STR_WAGONS);
 

	
 
			/* sets the colour of that art thing */
 
			this->widget[RVW_WIDGET_TRAIN_FLUFF_LEFT].color  = _player_colors[_local_player];
 
			this->widget[RVW_WIDGET_TRAIN_FLUFF_RIGHT].color = _player_colors[_local_player];
 
			this->widget[RVW_WIDGET_TRAIN_FLUFF_LEFT].color  = _company_colours[_local_company];
 
			this->widget[RVW_WIDGET_TRAIN_FLUFF_RIGHT].color = _company_colours[_local_company];
 
		}
 

	
 
		if (this->window_number == VEH_TRAIN) {
 
@@ -311,11 +311,11 @@ public:
 

	
 
		/* sets up the string for the vehicle that is being replaced to */
 
		if (selected_id[0] != INVALID_ENGINE) {
 
			if (!EngineHasReplacementForPlayer(p, selected_id[0], selected_group)) {
 
			if (!EngineHasReplacementForCompany(c, selected_id[0], selected_group)) {
 
				SetDParam(0, STR_NOT_REPLACING);
 
			} else {
 
				SetDParam(0, STR_ENGINE_NAME);
 
				SetDParam(1, EngineReplacementForPlayer(p, selected_id[0], selected_group));
 
				SetDParam(1, EngineReplacementForCompany(c, selected_id[0], selected_group));
 
			}
 
		} else {
 
			SetDParam(0, STR_NOT_REPLACING_VEHICLE_SELECTED);
 
@@ -358,19 +358,19 @@ public:
 
				break;
 

	
 
			case RVW_WIDGET_TRAIN_RAILTYPE_DROPDOWN: { /* Railtype selection dropdown menu */
 
				const Player *p = GetPlayer(_local_player);
 
				const Company *c = GetCompany(_local_company);
 
				DropDownList *list = new DropDownList();
 
				for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
 
					const RailtypeInfo *rti = GetRailTypeInfo(rt);
 

	
 
					list->push_back(new DropDownListStringItem(rti->strings.replace_text, rt, !HasBit(p->avail_railtypes, rt)));
 
					list->push_back(new DropDownListStringItem(rti->strings.replace_text, rt, !HasBit(c->avail_railtypes, rt)));
 
				}
 
				ShowDropDownList(this, list, sel_railtype, RVW_WIDGET_TRAIN_RAILTYPE_DROPDOWN);
 
				break;
 
			}
 

	
 
			case RVW_WIDGET_TRAIN_WAGONREMOVE_TOGGLE: /* toggle renew_keep_length */
 
				DoCommandP(0, 5, GetPlayer(_local_player)->renew_keep_length ? 0 : 1, NULL, CMD_SET_AUTOREPLACE);
 
				DoCommandP(0, 5, GetCompany(_local_company)->renew_keep_length ? 0 : 1, NULL, CMD_SET_AUTOREPLACE);
 
				break;
 

	
 
			case RVW_WIDGET_START_REPLACE: { /* Start replacing */
src/autoreplace_type.h
Show inline comments
 
@@ -8,8 +8,8 @@
 
struct EngineRenew;
 

	
 
/**
 
 * A list to group EngineRenew directives together (such as per-player).
 
 * A list to group EngineRenew directives together (such as per-company).
 
 */
 
typedef EngineRenew* EngineRenewList;
 
typedef EngineRenew *EngineRenewList;
 

	
 
#endif /* AUTOREPLACE_TYPE_H */
src/autoslope.h
Show inline comments
 
@@ -30,17 +30,17 @@ static inline bool AutoslopeCheckForEntr
 
}
 

	
 
/**
 
 * Tests if autoslope is enabled for _current_player.
 
 * Tests if autoslope is enabled for _current_company.
 
 *
 
 * Autoslope is disabled for town/industry construction and old ai players.
 
 * Autoslope is disabled for town/industry construction and old ai companies.
 
 *
 
 * @return true iff autoslope is enabled.
 
 */
 
static inline bool AutoslopeEnabled()
 
{
 
	return (_settings_game.construction.autoslope &&
 
	        ((_current_player < MAX_PLAYERS && !_is_old_ai_player) ||
 
	         (_current_player == OWNER_NONE && _game_mode == GM_EDITOR)));
 
	        ((_current_company < MAX_COMPANIES && !_is_old_ai_company) ||
 
	         (_current_company == OWNER_NONE && _game_mode == GM_EDITOR)));
 
}
 

	
 
#endif /* AUTOSLOPE_H */
src/build_vehicle_gui.cpp
Show inline comments
 
@@ -776,12 +776,12 @@ void DrawEngineList(VehicleType type, in
 

	
 
	for (; min < max; min++, y += step_size) {
 
		const EngineID engine = (*eng_list)[min];
 
		/* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_player here. */
 
		const uint num_engines = GetGroupNumEngines(_local_player, selected_group, engine);
 
		/* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_company here. */
 
		const uint num_engines = GetGroupNumEngines(_local_company, selected_group, engine);
 

	
 
		SetDParam(0, engine);
 
		DrawStringTruncated(x + x_offset, y, STR_ENGINE_NAME, engine == selected_id ? TC_WHITE : TC_BLACK, maxw);
 
		DrawVehicleEngine(type, x, y + y_offset, engine, (count_location != 0 && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_player));
 
		DrawVehicleEngine(type, x, y + y_offset, engine, (count_location != 0 && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_company));
 
		if (count_location != 0) {
 
			SetDParam(0, num_engines);
 
			DrawStringRightAligned(count_location, y + (GetVehicleListHeight(type) == 14 ? 3 : 8), STR_TINY_BLACK, TC_FROMSTRING);
 
@@ -818,7 +818,7 @@ struct BuildVehicleWindow : Window {
 
		this->resize.width  = this->width;
 
		this->resize.height = this->height;
 

	
 
		this->caption_color = (tile != 0) ? GetTileOwner(tile) : _local_player;
 
		this->caption_color = (tile != 0) ? GetTileOwner(tile) : _local_company;
 

	
 
		this->sel_engine      = INVALID_ENGINE;
 
		this->regenerate_list = false;
 
@@ -925,7 +925,7 @@ struct BuildVehicleWindow : Window {
 
			const RailVehicleInfo *rvi = &e->u.rail;
 

	
 
			if (this->filter.railtype != RAILTYPE_END && !HasPowerOnRail(rvi->railtype, this->filter.railtype)) continue;
 
			if (!IsEngineBuildable(eid, VEH_TRAIN, _local_player)) continue;
 
			if (!IsEngineBuildable(eid, VEH_TRAIN, _local_company)) continue;
 

	
 
			*this->eng_list.Append() = eid;
 

	
 
@@ -962,7 +962,7 @@ struct BuildVehicleWindow : Window {
 
		const Engine *e;
 
		FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) {
 
			EngineID eid = e->index;
 
			if (!IsEngineBuildable(eid, VEH_ROAD, _local_player)) continue;
 
			if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue;
 
			if (!HasBit(this->filter.roadtypes, HasBit(EngInfo(eid)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD)) continue;
 
			*this->eng_list.Append() = eid;
 

	
 
@@ -980,7 +980,7 @@ struct BuildVehicleWindow : Window {
 
		const Engine *e;
 
		FOR_ALL_ENGINES_OF_TYPE(e, VEH_SHIP) {
 
			EngineID eid = e->index;
 
			if (!IsEngineBuildable(eid, VEH_SHIP, _local_player)) continue;
 
			if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue;
 
			*this->eng_list.Append() = eid;
 

	
 
			if (eid == this->sel_engine) sel_id = eid;
 
@@ -1002,7 +1002,7 @@ struct BuildVehicleWindow : Window {
 
		const Engine *e;
 
		FOR_ALL_ENGINES_OF_TYPE(e, VEH_AIRCRAFT) {
 
			EngineID eid = e->index;
 
			if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_player)) continue;
 
			if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue;
 
			/* First VEH_END window_numbers are fake to allow a window open for all different types at once */
 
			if (!this->listview_mode && !CanAircraftUseStation(eid, this->window_number)) continue;
 

	
 
@@ -1207,7 +1207,7 @@ void ShowBuildVehicleWindow(TileIndex ti
 
	 *  number. */
 
	uint num = (tile == 0) ? (int)type : tile;
 

	
 
	assert(IsPlayerBuildableVehicleType(type));
 
	assert(IsCompanyBuildableVehicleType(type));
 

	
 
	DeleteWindowById(WC_BUILD_VEHICLE, num);
 

	
src/cheat_gui.cpp
Show inline comments
 
@@ -39,22 +39,22 @@ static int32 ClickMoneyCheat(int32 p1, i
 
}
 

	
 
/**
 
 * @param p1 player to set to
 
 * @param p1 company to set to
 
 * @param p2 is -1 or +1 (down/up)
 
 */
 
static int32 ClickChangePlayerCheat(int32 p1, int32 p2)
 
static int32 ClickChangeCompanyCheat(int32 p1, int32 p2)
 
{
 
	while ((uint)p1 < GetPlayerPoolSize()) {
 
		if (IsValidPlayerID((PlayerID)p1)) {
 
			SetLocalPlayer((PlayerID)p1);
 
	while ((uint)p1 < GetCompanyPoolSize()) {
 
		if (IsValidCompanyID((CompanyID)p1)) {
 
			SetLocalCompany((CompanyID)p1);
 

	
 
			MarkWholeScreenDirty();
 
			return _local_player;
 
			return _local_company;
 
		}
 
		p1 += p2;
 
	}
 

	
 
	return _local_player;
 
	return _local_company;
 
}
 

	
 
/**
 
@@ -106,15 +106,15 @@ struct CheatEntry {
 
};
 

	
 
static const CheatEntry _cheats_ui[] = {
 
	{SLE_INT32, STR_CHEAT_MONEY,           &_money_cheat_amount,               &_cheats.money.been_used,            &ClickMoneyCheat        },
 
	{SLE_UINT8, STR_CHEAT_CHANGE_PLAYER,   &_local_player,                     &_cheats.switch_player.been_used,    &ClickChangePlayerCheat },
 
	{SLE_BOOL,  STR_CHEAT_EXTRA_DYNAMITE,  &_cheats.magic_bulldozer.value,     &_cheats.magic_bulldozer.been_used,  NULL                    },
 
	{SLE_BOOL,  STR_CHEAT_CROSSINGTUNNELS, &_cheats.crossing_tunnels.value,    &_cheats.crossing_tunnels.been_used, NULL                    },
 
	{SLE_BOOL,  STR_CHEAT_BUILD_IN_PAUSE,  &_cheats.build_in_pause.value,      &_cheats.build_in_pause.been_used,   NULL                    },
 
	{SLE_BOOL,  STR_CHEAT_NO_JETCRASH,     &_cheats.no_jetcrash.value,         &_cheats.no_jetcrash.been_used,      NULL                    },
 
	{SLE_BOOL,  STR_CHEAT_SETUP_PROD,      &_cheats.setup_prod.value,          &_cheats.setup_prod.been_used,       NULL                    },
 
	{SLE_UINT8, STR_CHEAT_SWITCH_CLIMATE,  &_settings_game.game_creation.landscape, &_cheats.switch_climate.been_used,   &ClickChangeClimateCheat},
 
	{SLE_INT32, STR_CHEAT_CHANGE_DATE,     &_cur_year,                         &_cheats.change_date.been_used,      &ClickChangeDateCheat   },
 
	{SLE_INT32, STR_CHEAT_MONEY,           &_money_cheat_amount,                    &_cheats.money.been_used,            &ClickMoneyCheat         },
 
	{SLE_UINT8, STR_CHEAT_CHANGE_PLAYER,   &_local_company,                         &_cheats.switch_company.been_used,   &ClickChangeCompanyCheat },
 
	{SLE_BOOL,  STR_CHEAT_EXTRA_DYNAMITE,  &_cheats.magic_bulldozer.value,          &_cheats.magic_bulldozer.been_used,  NULL                     },
 
	{SLE_BOOL,  STR_CHEAT_CROSSINGTUNNELS, &_cheats.crossing_tunnels.value,         &_cheats.crossing_tunnels.been_used, NULL                     },
 
	{SLE_BOOL,  STR_CHEAT_BUILD_IN_PAUSE,  &_cheats.build_in_pause.value,           &_cheats.build_in_pause.been_used,   NULL                     },
 
	{SLE_BOOL,  STR_CHEAT_NO_JETCRASH,     &_cheats.no_jetcrash.value,              &_cheats.no_jetcrash.been_used,      NULL                     },
 
	{SLE_BOOL,  STR_CHEAT_SETUP_PROD,      &_cheats.setup_prod.value,               &_cheats.setup_prod.been_used,       NULL                     },
 
	{SLE_UINT8, STR_CHEAT_SWITCH_CLIMATE,  &_settings_game.game_creation.landscape, &_cheats.switch_climate.been_used,   &ClickChangeClimateCheat },
 
	{SLE_INT32, STR_CHEAT_CHANGE_DATE,     &_cur_year,                              &_cheats.change_date.been_used,      &ClickChangeDateCheat    },
 
};
 

	
 

	
 
@@ -163,11 +163,11 @@ struct CheatWindow : Window {
 
						/* Display date for change date cheat */
 
						case STR_CHEAT_CHANGE_DATE: SetDParam(0, _date); break;
 

	
 
						/* Draw colored flag for change player cheat */
 
						/* Draw colored flag for change company cheat */
 
						case STR_CHEAT_CHANGE_PLAYER:
 
							SetDParam(0, val);
 
							GetString(buf, STR_CHEAT_CHANGE_PLAYER, lastof(buf));
 
							DrawPlayerIcon(_current_player, 60 + GetStringBoundingBox(buf).width, y + 2);
 
							DrawCompanyIcon(_current_company, 60 + GetStringBoundingBox(buf).width, y + 2);
 
							break;
 

	
 
						/* Set correct string for switch climate cheat */

Changeset was too big and was cut off... Show full diff anyway

0 comments (0 inline, 0 general)