summaryrefslogtreecommitdiff
path: root/ai
diff options
context:
space:
mode:
authortruelight <truelight@openttd.org>2005-09-02 19:10:45 +0000
committertruelight <truelight@openttd.org>2005-09-02 19:10:45 +0000
commitd05f504c01fb88eb8b88d28b5fd5da664e31cd95 (patch)
treed01e499f40fb0d5d315c7530b74c76569fae0840 /ai
parenta181446829c3de933ccccffcc652c0c7b19f9968 (diff)
downloadopenttd-d05f504c01fb88eb8b88d28b5fd5da664e31cd95.tar.xz
(svn r2907) -Codechange: splitted the AIs to their own directory. AINew becomes 'trolly', AIOld becomes 'default', both in their own dir in the 'ai' dir. More AIs to come.
Diffstat (limited to 'ai')
-rw-r--r--ai/default/default.c4003
-rw-r--r--ai/trolly/build.c273
-rw-r--r--ai/trolly/pathfinder.c514
-rw-r--r--ai/trolly/shared.c124
-rw-r--r--ai/trolly/trolly.c1379
-rw-r--r--ai/trolly/trolly.h261
6 files changed, 6554 insertions, 0 deletions
diff --git a/ai/default/default.c b/ai/default/default.c
new file mode 100644
index 000000000..b8160d2bd
--- /dev/null
+++ b/ai/default/default.c
@@ -0,0 +1,4003 @@
+/* $Id: ai_old.c 2701 2005-07-24 14:12:37Z tron $ */
+
+#include "../../stdafx.h"
+#include "../../openttd.h"
+#include "../../functions.h"
+#include "../../map.h"
+#include "../../tile.h"
+#include "../../player.h"
+#include "../../vehicle.h"
+#include "../../engine.h"
+#include "../../command.h"
+#include "../../town.h"
+#include "../../industry.h"
+#include "../../station.h"
+#include "../../pathfind.h"
+#include "../../economy.h"
+#include "../../airport.h"
+#include "../../depot.h"
+#include "../../variables.h"
+
+// remove some day perhaps?
+static Player *_cur_ai_player;
+static uint _ai_service_interval;
+
+typedef void AiStateAction(Player *p);
+
+enum {
+ AIS_0 = 0,
+ AIS_1 = 1,
+ AIS_VEH_LOOP = 2,
+ AIS_VEH_CHECK_REPLACE_VEHICLE = 3,
+ AIS_VEH_DO_REPLACE_VEHICLE = 4,
+ AIS_WANT_NEW_ROUTE = 5,
+ AIS_BUILD_DEFAULT_RAIL_BLOCKS = 6,
+ AIS_BUILD_RAIL = 7,
+ AIS_BUILD_RAIL_VEH = 8,
+ AIS_DELETE_RAIL_BLOCKS = 9,
+ AIS_BUILD_DEFAULT_ROAD_BLOCKS = 10,
+ AIS_BUILD_ROAD = 11,
+ AIS_BUILD_ROAD_VEHICLES = 12,
+ AIS_DELETE_ROAD_BLOCKS = 13,
+ AIS_AIRPORT_STUFF = 14,
+ AIS_BUILD_DEFAULT_AIRPORT_BLOCKS = 15,
+ AIS_BUILD_AIRCRAFT_VEHICLES = 16,
+ AIS_CHECK_SHIP_STUFF = 17,
+ AIS_BUILD_DEFAULT_SHIP_BLOCKS = 18,
+ AIS_DO_SHIP_STUFF = 19,
+ AIS_SELL_VEHICLE = 20,
+ AIS_REMOVE_STATION = 21,
+ AIS_REMOVE_TRACK = 22,
+ AIS_REMOVE_SINGLE_RAIL_TILE = 23
+};
+
+
+#include "../../table/ai_rail.h"
+
+static byte GetRailTrackStatus(TileIndex tile) {
+ uint32 r = GetTileTrackStatus(tile, TRANSPORT_RAIL);
+ return (byte) (r | r >> 8);
+}
+
+
+static void AiCase0(Player *p)
+{
+ p->ai.state = AIS_REMOVE_TRACK;
+ p->ai.state_counter = 0;
+}
+
+static void AiCase1(Player *p)
+{
+ p->ai.cur_veh = NULL;
+ p->ai.state = AIS_VEH_LOOP;
+}
+
+static void AiStateVehLoop(Player *p)
+{
+ Vehicle *v;
+ uint index;
+
+ index = (p->ai.cur_veh == NULL) ? 0 : p->ai.cur_veh->index + 1;
+
+ FOR_ALL_VEHICLES_FROM(v, index) {
+ if (v->type == 0 || v->owner != _current_player)
+ continue;
+
+ if ((v->type == VEH_Train && v->subtype==0) ||
+ v->type == VEH_Road ||
+ (v->type == VEH_Aircraft && v->subtype <= 2) ||
+ v->type == VEH_Ship) {
+
+ /* replace engine? */
+ if (v->type == VEH_Train && v->engine_type < 3 &&
+ (_price.build_railvehicle >> 3) < p->player_money) {
+ p->ai.state = AIS_VEH_CHECK_REPLACE_VEHICLE;
+ p->ai.cur_veh = v;
+ return;
+ }
+
+ /* not profitable? */
+ if (v->age >= 730 &&
+ v->profit_last_year < _price.station_value*5 &&
+ v->profit_this_year < _price.station_value*5) {
+ p->ai.state_counter = 0;
+ p->ai.state = AIS_SELL_VEHICLE;
+ p->ai.cur_veh = v;
+ return;
+ }
+
+ /* not reliable? */
+ if ((v->age != 0 &&
+ GetEngine(v->engine_type)->reliability < 35389) ||
+ v->age >= v->max_age) {
+ p->ai.state = AIS_VEH_CHECK_REPLACE_VEHICLE;
+ p->ai.cur_veh = v;
+ return;
+ }
+ }
+ }
+
+ p->ai.state = AIS_WANT_NEW_ROUTE;
+ p->ai.state_counter = 0;
+}
+
+static int AiChooseTrainToBuild(byte railtype, int32 money, byte flag, TileIndex tile)
+{
+ int best_veh_index = -1;
+ byte best_veh_score = 0;
+ int32 ret;
+ int i;
+
+ for (i = 0; i < NUM_TRAIN_ENGINES; i++) {
+ const RailVehicleInfo *rvi = RailVehInfo(i);
+ const Engine* e = GetEngine(i);
+
+ if (e->railtype != railtype || rvi->flags & RVI_WAGON
+ || !HASBIT(e->player_avail, _current_player) || e->reliability < 0x8A3D)
+ continue;
+
+ ret = DoCommandByTile(tile, i, 0, 0, CMD_BUILD_RAIL_VEHICLE);
+ if (!CmdFailed(ret) && (!(_cmd_build_rail_veh_var1&1) || !(flag&1)) && ret <= money &&
+ _cmd_build_rail_veh_score >= best_veh_score) {
+ best_veh_score = _cmd_build_rail_veh_score;
+ best_veh_index = i;
+ }
+ }
+
+ return best_veh_index;
+}
+
+static int AiChooseRoadVehToBuild(byte cargo, int32 money, TileIndex tile)
+{
+ int best_veh_index = -1;
+ int32 best_veh_cost = 0;
+ int32 ret;
+
+ int i = _cargoc.ai_roadveh_start[cargo];
+ int end = i + _cargoc.ai_roadveh_count[cargo];
+ const Engine* e = GetEngine(i);
+
+ do {
+ if (!HASBIT(e->player_avail, _current_player) || e->reliability < 0x8A3D)
+ continue;
+
+ ret = DoCommandByTile(tile, i, 0, 0, CMD_BUILD_ROAD_VEH);
+ if (!CmdFailed(ret) && ret <= money && ret >= best_veh_cost) {
+ best_veh_cost = ret;
+ best_veh_index = i;
+ }
+ } while (++e, ++i != end);
+
+ return best_veh_index;
+}
+
+static int AiChooseAircraftToBuild(int32 money, byte flag)
+{
+ int best_veh_index = -1;
+ int32 best_veh_cost = 0;
+ int32 ret;
+
+ int i = AIRCRAFT_ENGINES_INDEX;
+ int end = i + NUM_AIRCRAFT_ENGINES;
+ const Engine* e = GetEngine(i);
+
+ do {
+ if (!HASBIT(e->player_avail, _current_player) || e->reliability < 0x8A3D)
+ continue;
+
+ if (flag&1) {
+ if (i<253) continue;
+ } else {
+ if (i>=253) continue;
+ }
+
+ ret = DoCommandByTile(0, i, 0, 0, CMD_BUILD_AIRCRAFT);
+ if (!CmdFailed(ret) && ret <= money && ret >= best_veh_cost) {
+ best_veh_cost = ret;
+ best_veh_index = i;
+ }
+ } while (++e, ++i != end);
+
+ return best_veh_index;
+}
+
+static int32 AiGetBasePrice(Player *p)
+{
+ int32 base = _price.station_value;
+
+ // adjust base price when more expensive vehicles are available
+ if (p->ai.railtype_to_use == 1) base = (base * 3) >> 1;
+ else if (p->ai.railtype_to_use == 2) base *= 2;
+
+ return base;
+}
+
+#if 0
+static int AiChooseShipToBuild(byte cargo, int32 money)
+{
+ // XXX: not done
+ return 0;
+}
+#endif
+
+static int AiChooseRoadVehToReplaceWith(Player *p, Vehicle *v)
+{
+ int32 avail_money = p->player_money + v->value;
+ return AiChooseRoadVehToBuild(v->cargo_type, avail_money, v->tile);
+}
+
+static int AiChooseAircraftToReplaceWith(Player *p, Vehicle *v)
+{
+ int32 avail_money = p->player_money + v->value;
+ return AiChooseAircraftToBuild(avail_money, v->engine_type>=253?1:0);
+}
+
+static int AiChooseTrainToReplaceWith(Player *p, Vehicle *v)
+{
+ int32 avail_money = p->player_money + v->value;
+ int num=0;
+ Vehicle *u = v;
+
+ while (++num, u->next != NULL) {
+ u = u->next;
+ }
+
+ // XXX: check if a wagon
+ return AiChooseTrainToBuild(v->u.rail.railtype, avail_money, 0, v->tile);
+}
+
+static int AiChooseShipToReplaceWith(Player *p, Vehicle *v)
+{
+ error("!AiChooseShipToReplaceWith");
+
+ /* maybe useless, but avoids compiler warning this way */
+ return 0;
+}
+
+static void AiHandleGotoDepot(Player *p, int cmd)
+{
+ if (p->ai.cur_veh->current_order.type != OT_GOTO_DEPOT)
+ DoCommandByTile(0, p->ai.cur_veh->index, 0, DC_EXEC, cmd);
+
+ if (++p->ai.state_counter <= 1387) {
+ p->ai.state = AIS_VEH_DO_REPLACE_VEHICLE;
+ return;
+ }
+
+ if (p->ai.cur_veh->current_order.type == OT_GOTO_DEPOT) {
+ p->ai.cur_veh->current_order.type = OT_DUMMY;
+ p->ai.cur_veh->current_order.flags = 0;
+ InvalidateWindow(WC_VEHICLE_VIEW, p->ai.cur_veh->index);
+ }
+}
+
+static void AiRestoreVehicleOrders(Vehicle *v, BackuppedOrders *bak)
+{
+ int i;
+
+ for (i = 0; bak->order[i].type != OT_NOTHING; i++)
+ if (CmdFailed(DoCommandP(0, v->index + (i << 16), PackOrder(&bak->order[i]), NULL, CMD_INSERT_ORDER | CMD_NO_TEST_IF_IN_NETWORK)))
+ break;
+}
+
+static void AiHandleReplaceTrain(Player *p)
+{
+ Vehicle *v = p->ai.cur_veh;
+ BackuppedOrders orderbak[1];
+ int veh;
+
+ // wait until the vehicle reaches the depot.
+ if (!IsTileDepotType(v->tile, TRANSPORT_RAIL) || v->u.rail.track != 0x80 || !(v->vehstatus&VS_STOPPED)) {
+ AiHandleGotoDepot(p, CMD_TRAIN_GOTO_DEPOT);
+ return;
+ }
+
+ veh = AiChooseTrainToReplaceWith(p, v);
+ if (veh != -1) {
+ TileIndex tile;
+
+ BackupVehicleOrders(v, orderbak);
+ tile = v->tile;
+
+ if (!CmdFailed(DoCommandByTile(0, v->index, 2, DC_EXEC, CMD_SELL_RAIL_WAGON)) &&
+ !CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_RAIL_VEHICLE)) ) {
+ veh = _new_train_id;
+ AiRestoreVehicleOrders(GetVehicle(veh), orderbak);
+ DoCommandByTile(0, veh, 0, DC_EXEC, CMD_START_STOP_TRAIN);
+
+ DoCommandByTile(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
+ }
+ }
+}
+
+static void AiHandleReplaceRoadVeh(Player *p)
+{
+ Vehicle *v = p->ai.cur_veh;
+ BackuppedOrders orderbak[1];
+ int veh;
+
+ if (!IsTileDepotType(v->tile, TRANSPORT_ROAD) || v->u.road.state != 254 || !(v->vehstatus&VS_STOPPED)) {
+ AiHandleGotoDepot(p, CMD_SEND_ROADVEH_TO_DEPOT);
+ return;
+ }
+
+ veh = AiChooseRoadVehToReplaceWith(p, v);
+ if (veh != -1) {
+ TileIndex tile;
+
+ BackupVehicleOrders(v, orderbak);
+ tile = v->tile;
+
+ if (!CmdFailed(DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH)) &&
+ !CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_ROAD_VEH)) ) {
+ veh = _new_roadveh_id;
+ AiRestoreVehicleOrders(GetVehicle(veh), orderbak);
+ DoCommandByTile(0, veh, 0, DC_EXEC, CMD_START_STOP_ROADVEH);
+
+ DoCommandByTile(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
+ }
+ }
+}
+
+static void AiHandleReplaceAircraft(Player *p)
+{
+ Vehicle *v = p->ai.cur_veh;
+ int veh;
+ BackuppedOrders orderbak[1];
+
+ if (!IsAircraftHangarTile(v->tile) && !(v->vehstatus&VS_STOPPED)) {
+ AiHandleGotoDepot(p, CMD_SEND_AIRCRAFT_TO_HANGAR);
+ return;
+ }
+
+ veh = AiChooseAircraftToReplaceWith(p, v);
+ if (veh != -1) {
+ TileIndex tile;
+
+ BackupVehicleOrders(v, orderbak);
+ tile = v->tile;
+
+ if (!CmdFailed(DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_AIRCRAFT)) &&
+ !CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_AIRCRAFT)) ) {
+ veh = _new_aircraft_id;
+ AiRestoreVehicleOrders(GetVehicle(veh), orderbak);
+ DoCommandByTile(0, veh, 0, DC_EXEC, CMD_START_STOP_AIRCRAFT);
+
+ DoCommandByTile(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
+ }
+ }
+}
+
+static void AiHandleReplaceShip(Player *p)
+{
+ error("!AiHandleReplaceShip");
+}
+
+typedef int CheckReplaceProc(Player *p, Vehicle *v);
+
+static CheckReplaceProc * const _veh_check_replace_proc[] = {
+ AiChooseTrainToReplaceWith,
+ AiChooseRoadVehToReplaceWith,
+ AiChooseShipToReplaceWith,
+ AiChooseAircraftToReplaceWith,
+};
+
+typedef void DoReplaceProc(Player *p);
+static DoReplaceProc * const _veh_do_replace_proc[] = {
+ AiHandleReplaceTrain,
+ AiHandleReplaceRoadVeh,
+ AiHandleReplaceShip,
+ AiHandleReplaceAircraft
+};
+
+static void AiStateCheckReplaceVehicle(Player *p)
+{
+ Vehicle *v = p->ai.cur_veh;
+
+ if (v->type == 0 || v->owner != _current_player || v->type > VEH_Ship || _veh_check_replace_proc[v->type - VEH_Train](p, v) == -1) {
+ p->ai.state = AIS_VEH_LOOP;
+ } else {
+ p->ai.state_counter = 0;
+ p->ai.state = AIS_VEH_DO_REPLACE_VEHICLE;
+ }
+}
+
+static void AiStateDoReplaceVehicle(Player *p)
+{
+ Vehicle *v = p->ai.cur_veh;
+ p->ai.state = AIS_VEH_LOOP;
+ // vehicle is not owned by the player anymore, something went very wrong.
+ if (v->type == 0 || v->owner != _current_player)
+ return;
+ _veh_do_replace_proc[v->type - VEH_Train](p);
+}
+
+typedef struct FoundRoute {
+ int distance;
+ byte cargo;
+ void *from;
+ void *to;
+} FoundRoute;
+
+static Town *AiFindRandomTown(void)
+{
+ Town *t = GetTown(RandomRange(_total_towns));
+ return (t->xy != 0) ? t : NULL;
+}
+
+static Industry *AiFindRandomIndustry(void)
+{
+ Industry *i = GetIndustry(RandomRange(_total_industries));
+ return (i->xy != 0) ? i : NULL;
+}
+
+static void AiFindSubsidyIndustryRoute(FoundRoute *fr)
+{
+ uint i;
+ byte cargo;
+ Subsidy *s;
+ Industry *from, *to_ind;
+ Town *to_tow;
+ TileIndex to_xy;
+
+ // initially error
+ fr->distance = -1;
+
+ // Randomize subsidy index..
+ i = RandomRange(lengthof(_subsidies) * 3);
+ if (i >= lengthof(_subsidies))
+ return;
+
+ s = &_subsidies[i];
+
+ // Don't want passengers or mail
+ cargo = s->cargo_type;
+ if (cargo == 0xFF || cargo == CT_PASSENGERS || cargo == CT_MAIL || s->age > 7)
+ return;
+ fr->cargo = cargo;
+
+ fr->from = from = GetIndustry(s->from);
+
+ if (cargo == CT_GOODS || cargo == CT_FOOD) {
+ to_tow = GetTown(s->to);
+ if (to_tow->population < (uint32)(cargo == CT_FOOD ? 200 : 900))
+ return; // error
+ fr->to = to_tow;
+ to_xy = to_tow->xy;
+ } else {
+ to_ind = GetIndustry(s->to);
+ fr->to = to_ind;
+ to_xy = to_ind->xy;
+ }
+
+ fr->distance = DistanceManhattan(from->xy, to_xy);
+}
+
+static void AiFindSubsidyPassengerRoute(FoundRoute *fr)
+{
+ uint i;
+ Subsidy *s;
+ Town *from,*to;
+
+ // initially error
+ fr->distance = -1;
+
+ // Randomize subsidy index..
+ i = RandomRange(lengthof(_subsidies) * 3);
+ if (i >= lengthof(_subsidies))
+ return;
+
+ s = &_subsidies[i];
+
+ // Only want passengers
+ if (s->cargo_type != CT_PASSENGERS || s->age > 7)
+ return;
+ fr->cargo = s->cargo_type;
+
+ fr->from = from = GetTown(s->from);
+ fr->to = to = GetTown(s->to);
+
+ // They must be big enough
+ if (from->population < 400 || to->population < 400)
+ return;
+
+ fr->distance = DistanceManhattan(from->xy, to->xy);
+}
+
+static void AiFindRandomIndustryRoute(FoundRoute *fr)
+{
+ Industry *i,*i2;
+ Town *t;
+ uint32 r;
+ byte cargo;
+
+ // initially error
+ fr->distance = -1;
+
+ r = Random();
+
+ // pick a source
+ fr->from = i = AiFindRandomIndustry();
+ if (i == NULL)
+ return;
+
+ // pick a random produced cargo
+ cargo = i->produced_cargo[0];
+ if (r&1 && i->produced_cargo[1] != 0xFF)
+ cargo = i->produced_cargo[1];
+
+ fr->cargo = cargo;
+
+ // don't allow passengers
+ if (cargo == 0xFF || cargo == CT_PASSENGERS)
+ return;
+
+ if (cargo != CT_GOODS && cargo != CT_FOOD) {
+ // pick a dest, and see if it can receive
+ i2 = AiFindRandomIndustry();
+ if (i2 == NULL || i == i2 || !(i2->accepts_cargo[0] == cargo || i2->accepts_cargo[1] == cargo || i2->accepts_cargo[2] == cargo))
+ return;
+
+ fr->to = i2;
+ fr->distance = DistanceManhattan(i->xy, i2->xy);
+ } else {
+ // pick a dest town, and see if it's big enough
+ t = AiFindRandomTown();
+ if (t == NULL || t->population < (uint32)(cargo == CT_FOOD ? 200 : 900))
+ return;
+
+ fr->to = t;
+ fr->distance = DistanceManhattan(i->xy, t->xy);
+ }
+}
+
+static void AiFindRandomPassengerRoute(FoundRoute *fr)
+{
+ uint32 r;
+ Town *source, *dest;
+
+ // initially error
+ fr->distance = -1;
+
+ r = Random();
+
+ fr->from = source = AiFindRandomTown();
+ if (source == NULL || source->population < 400)
+ return;
+
+ fr->to = dest = AiFindRandomTown();
+ if (dest == NULL || source == dest || dest->population < 400)
+ return;
+
+ fr->distance = DistanceManhattan(source->xy, dest->xy);
+}
+
+// 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)
+{
+ TileIndex from_tile, to_tile;
+ Station *st;
+ int dist, cur;
+ uint same_station = 0;
+
+ // Make sure distance to closest station is < 37 pixels.
+ from_tile = GET_TOWN_OR_INDUSTRY_TILE(fr->from);
+ to_tile = GET_TOWN_OR_INDUSTRY_TILE(fr->to);
+
+ dist = 0xFFFF;
+ FOR_ALL_STATIONS(st) if (st->xy != 0 && st->owner == _current_player) {
+ cur = DistanceMax(from_tile, st->xy);
+ if (cur < dist) dist = cur;
+ cur = DistanceMax(to_tile, st->xy);
+ if (cur < dist) dist = cur;
+ if (to_tile == from_tile && st->xy == to_tile)
+ same_station++;
+ }
+
+ // To prevent the AI from building ten busstations in the same town, do some calculations
+ // For each road or airport station, we want 350 of population!
+ if ((bitmask == 2 || bitmask == 4) && same_station > 2 && ((Town *)(fr->from))->population < same_station * 350)
+ return false;
+
+ if (dist != 0xFFFF && dist > 37)
+ return false;
+
+ if (p->ai.route_type_mask != 0 && !(p->ai.route_type_mask&bitmask) && !CHANCE16(1,5))
+ return false;
+
+ if (fr->cargo == CT_PASSENGERS || fr->cargo == CT_MAIL) {
+ if (((Town*)fr->from)->pct_pass_transported > 0x99 ||
+ ((Town*)fr->to)->pct_pass_transported > 0x99)
+ return false;
+
+ // Make sure it has a reasonably good rating
+ if ( ((Town*)fr->from)->ratings[_current_player] < -100 ||
+ ((Town*)fr->to)->ratings[_current_player] < -100)
+ return false;
+ } else {
+ Industry *i = (Industry*)fr->from;
+
+ if (i->pct_transported[fr->cargo != i->produced_cargo[0]] > 0x99 ||
+ i->total_production[fr->cargo != i->produced_cargo[0]] == 0)
+ return false;
+ }
+
+ p->ai.route_type_mask |= bitmask;
+ return true;
+}
+
+static byte AiGetDirectionBetweenTiles(TileIndex a, TileIndex b)
+{
+ byte i = (TileX(a) < TileX(b)) ? 1 : 0;
+ if (TileY(a) >= TileY(b)) i ^= 3;
+ return i;
+}
+
+static TileIndex AiGetPctTileBetween(TileIndex a, TileIndex b, byte pct)
+{
+ return TileXY(
+ TileX(a) + ((TileX(b) - TileX(a)) * pct >> 8),
+ TileY(a) + ((TileY(b) - TileY(a)) * pct >> 8)
+ );
+}
+
+static void AiWantLongIndustryRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+
+ i = 60;
+ for(;;) {
+ // look for one from the subsidy list
+ AiFindSubsidyIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 60, 90+1))
+ break;
+
+ // try a random one
+ AiFindRandomIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 60, 90+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ if (!AiCheckIfRouteIsGood(p, &fr, 1))
+ return;
+
+ // Fill the source field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 9;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.unk6 = 1;
+ p->ai.src.unk7 = 0;
+ p->ai.src.buildcmd_a = 0x24;
+ p->ai.src.buildcmd_b = 0xFF;
+ p->ai.src.direction = AiGetDirectionBetweenTiles(
+ p->ai.src.spec_tile,
+ p->ai.dst.spec_tile
+ );
+ p->ai.src.cargo = fr.cargo | 0x80;
+
+ // Fill the dest field
+
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 9;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.unk6 = 1;
+ p->ai.dst.unk7 = 0;
+ p->ai.dst.buildcmd_a = 0x34;
+ p->ai.dst.buildcmd_b = 0xFF;
+ p->ai.dst.direction = AiGetDirectionBetweenTiles(
+ p->ai.dst.spec_tile,
+ p->ai.src.spec_tile
+ );
+ p->ai.dst.cargo = fr.cargo;
+
+ // Fill middle field 1
+ p->ai.mid1.spec_tile = AiGetPctTileBetween(
+ p->ai.src.spec_tile,
+ p->ai.dst.spec_tile,
+ 0x55
+ );
+ p->ai.mid1.use_tile = 0;
+ p->ai.mid1.rand_rng = 6;
+ p->ai.mid1.cur_building_rule = 0xFF;
+ p->ai.mid1.unk6 = 2;
+ p->ai.mid1.unk7 = 1;
+ p->ai.mid1.buildcmd_a = 0x30;
+ p->ai.mid1.buildcmd_b = 0xFF;
+ p->ai.mid1.direction = p->ai.src.direction;
+ p->ai.mid1.cargo = fr.cargo;
+
+ // Fill middle field 2
+ p->ai.mid2.spec_tile = AiGetPctTileBetween(
+ p->ai.src.spec_tile,
+ p->ai.dst.spec_tile,
+ 0xAA
+ );
+ p->ai.mid2.use_tile = 0;
+ p->ai.mid2.rand_rng = 6;
+ p->ai.mid2.cur_building_rule = 0xFF;
+ p->ai.mid2.unk6 = 2;
+ p->ai.mid2.unk7 = 1;
+ p->ai.mid2.buildcmd_a = 0xFF;
+ p->ai.mid2.buildcmd_b = 0xFF;
+ p->ai.mid2.direction = p->ai.dst.direction;
+ p->ai.mid2.cargo = fr.cargo;
+
+ // Fill common fields
+ p->ai.cargo_type = fr.cargo;
+ p->ai.num_wagons = 3;
+ p->ai.build_kind = 2;
+ p->ai.num_build_rec = 4;
+ p->ai.num_loco_to_build = 2;
+ p->ai.num_want_fullload = 2;
+ p->ai.wagon_list[0] = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+
+ p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantMediumIndustryRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+
+ i = 60;
+ for(;;) {
+
+ // look for one from the subsidy list
+ AiFindSubsidyIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 40, 60+1))
+ break;
+
+ // try a random one
+ AiFindRandomIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 40, 60+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ if (!AiCheckIfRouteIsGood(p, &fr, 1))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 9;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.unk6 = 1;
+ p->ai.src.unk7 = 0;
+ p->ai.src.buildcmd_a = 0x10;
+ p->ai.src.buildcmd_b = 0xFF;
+ p->ai.src.direction = AiGetDirectionBetweenTiles(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to)
+ );
+ p->ai.src.cargo = fr.cargo | 0x80;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 9;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.unk6 = 1;
+ p->ai.dst.unk7 = 0;
+ p->ai.dst.buildcmd_a = 0xFF;
+ p->ai.dst.buildcmd_b = 0xFF;
+ p->ai.dst.direction = AiGetDirectionBetweenTiles(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from)
+ );
+ p->ai.dst.cargo = fr.cargo;
+
+ // Fill common fields
+ p->ai.cargo_type = fr.cargo;
+ p->ai.num_wagons = 3;
+ p->ai.build_kind = 1;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 1;
+ p->ai.num_want_fullload = 1;
+ p->ai.wagon_list[0] = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+ p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantShortIndustryRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+
+ i = 60;
+ for(;;) {
+
+ // look for one from the subsidy list
+ AiFindSubsidyIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 15, 40+1))
+ break;
+
+ // try a random one
+ AiFindRandomIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 15, 40+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ if (!AiCheckIfRouteIsGood(p, &fr, 1))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 9;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.unk6 = 1;
+ p->ai.src.unk7 = 0;
+ p->ai.src.buildcmd_a = 0x10;
+ p->ai.src.buildcmd_b = 0xFF;
+ p->ai.src.direction = AiGetDirectionBetweenTiles(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to)
+ );
+ p->ai.src.cargo = fr.cargo | 0x80;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 9;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.unk6 = 1;
+ p->ai.dst.unk7 = 0;
+ p->ai.dst.buildcmd_a = 0xFF;
+ p->ai.dst.buildcmd_b = 0xFF;
+ p->ai.dst.direction = AiGetDirectionBetweenTiles(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from)
+ );
+ p->ai.dst.cargo = fr.cargo;
+
+ // Fill common fields
+ p->ai.cargo_type = fr.cargo;
+ p->ai.num_wagons = 2;
+ p->ai.build_kind = 1;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 1;
+ p->ai.num_want_fullload = 1;
+ p->ai.wagon_list[0] = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+ p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantMailRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+
+ i = 60;
+ for(;;) {
+
+ // look for one from the subsidy list
+ AiFindSubsidyPassengerRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 60, 110+1))
+ break;
+
+ // try a random one
+ AiFindRandomPassengerRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 60, 110+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ fr.cargo = CT_MAIL;
+ if (!AiCheckIfRouteIsGood(p, &fr, 1))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 7;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.unk6 = 1;
+ p->ai.src.unk7 = 0;
+ p->ai.src.buildcmd_a = 0x24;
+ p->ai.src.buildcmd_b = 0xFF;
+ p->ai.src.direction = AiGetDirectionBetweenTiles(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to)
+ );
+ p->ai.src.cargo = fr.cargo;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 7;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.unk6 = 1;
+ p->ai.dst.unk7 = 0;
+ p->ai.dst.buildcmd_a = 0x34;
+ p->ai.dst.buildcmd_b = 0xFF;
+ p->ai.dst.direction = AiGetDirectionBetweenTiles(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from)
+ );
+ p->ai.dst.cargo = fr.cargo;
+
+ // Fill middle field 1
+ p->ai.mid1.spec_tile = AiGetPctTileBetween(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to),
+ 0x55
+ );
+ p->ai.mid1.use_tile = 0;
+ p->ai.mid1.rand_rng = 6;
+ p->ai.mid1.cur_building_rule = 0xFF;
+ p->ai.mid1.unk6 = 2;
+ p->ai.mid1.unk7 = 1;
+ p->ai.mid1.buildcmd_a = 0x30;
+ p->ai.mid1.buildcmd_b = 0xFF;
+ p->ai.mid1.direction = p->ai.src.direction;
+ p->ai.mid1.cargo = fr.cargo;
+
+ // Fill middle field 2
+ p->ai.mid2.spec_tile = AiGetPctTileBetween(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to),
+ 0xAA
+ );
+ p->ai.mid2.use_tile = 0;
+ p->ai.mid2.rand_rng = 6;
+ p->ai.mid2.cur_building_rule = 0xFF;
+ p->ai.mid2.unk6 = 2;
+ p->ai.mid2.unk7 = 1;
+ p->ai.mid2.buildcmd_a = 0xFF;
+ p->ai.mid2.buildcmd_b = 0xFF;
+ p->ai.mid2.direction = p->ai.dst.direction;
+ p->ai.mid2.cargo = fr.cargo;
+
+ // Fill common fields
+ p->ai.cargo_type = fr.cargo;
+ p->ai.num_wagons = 3;
+ p->ai.build_kind = 2;
+ p->ai.num_build_rec = 4;
+ p->ai.num_loco_to_build = 2;
+ p->ai.num_want_fullload = 0;
+ p->ai.wagon_list[0] = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+ p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantPassengerRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+
+ i = 60;
+ for(;;) {
+
+ // look for one from the subsidy list
+ AiFindSubsidyPassengerRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 0, 55+1))
+ break;
+
+ // try a random one
+ AiFindRandomPassengerRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 0, 55+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ fr.cargo = CT_PASSENGERS;
+ if (!AiCheckIfRouteIsGood(p, &fr, 1))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 7;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.unk6 = 1;
+ p->ai.src.unk7 = 0;
+ p->ai.src.buildcmd_a = 0x10;
+ p->ai.src.buildcmd_b = 0xFF;
+ p->ai.src.direction = AiGetDirectionBetweenTiles(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to)
+ );
+ p->ai.src.cargo = fr.cargo;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 7;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.unk6 = 1;
+ p->ai.dst.unk7 = 0;
+ p->ai.dst.buildcmd_a = 0xFF;
+ p->ai.dst.buildcmd_b = 0xFF;
+ p->ai.dst.direction = AiGetDirectionBetweenTiles(
+ GET_TOWN_OR_INDUSTRY_TILE(fr.to),
+ GET_TOWN_OR_INDUSTRY_TILE(fr.from)
+ );
+ p->ai.dst.cargo = fr.cargo;
+
+ // Fill common fields
+ p->ai.cargo_type = fr.cargo;
+ p->ai.num_wagons = 2;
+ p->ai.build_kind = 1;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 1;
+ p->ai.num_want_fullload = 0;
+ p->ai.wagon_list[0] = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+ p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantTrainRoute(Player *p)
+{
+ uint16 r;
+ p->ai.railtype_to_use = GetBestRailtype(p);
+ r = (uint16)Random();
+
+ if (r > 0xD000) {
+ AiWantLongIndustryRoute(p);
+ } else if (r > 0x6000) {
+ AiWantMediumIndustryRoute(p);
+ } else if (r > 0x1000) {
+ AiWantShortIndustryRoute(p);
+ } else if (r > 0x800) {
+ AiWantPassengerRoute(p);
+ } else {
+ AiWantMailRoute(p);
+ }
+}
+
+static void AiWantLongRoadIndustryRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+
+ i = 60;
+ for(;;) {
+
+ // look for one from the subsidy list
+ AiFindSubsidyIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 35, 55+1))
+ break;
+
+ // try a random one
+ AiFindRandomIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 35, 55+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ if (!AiCheckIfRouteIsGood(p, &fr, 2))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 9;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.buildcmd_a = 1;
+ p->ai.src.direction = 0;
+ p->ai.src.cargo = fr.cargo | 0x80;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 9;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.buildcmd_a = 0xFF;
+ p->ai.dst.direction = 0;
+ p->ai.dst.cargo = fr.cargo;
+
+ // Fill common fields
+ p->ai.cargo_type = fr.cargo;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 5;
+ p->ai.num_want_fullload = 5;
+
+// p->ai.loco_id = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+
+ p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantMediumRoadIndustryRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+
+ i = 60;
+ for(;;) {
+
+ // look for one from the subsidy list
+ AiFindSubsidyIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 15, 40+1))
+ break;
+
+ // try a random one
+ AiFindRandomIndustryRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 15, 40+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ if (!AiCheckIfRouteIsGood(p, &fr, 2))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 9;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.buildcmd_a = 1;
+ p->ai.src.direction = 0;
+ p->ai.src.cargo = fr.cargo | 0x80;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 9;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.buildcmd_a = 0xFF;
+ p->ai.dst.direction = 0;
+ p->ai.dst.cargo = fr.cargo;
+
+ // Fill common fields
+ p->ai.cargo_type = fr.cargo;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 3;
+ p->ai.num_want_fullload = 3;
+
+// p->ai.loco_id = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+
+ p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantLongRoadPassengerRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+
+ i = 60;
+ for(;;) {
+
+ // look for one from the subsidy list
+ AiFindSubsidyPassengerRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 55, 180+1))
+ break;
+
+ // try a random one
+ AiFindRandomPassengerRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance, 55, 180+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ fr.cargo = CT_PASSENGERS;
+
+ if (!AiCheckIfRouteIsGood(p, &fr, 2))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 10;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.buildcmd_a = 1;
+ p->ai.src.direction = 0;
+ p->ai.src.cargo = CT_PASSENGERS;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 10;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.buildcmd_a = 0xFF;
+ p->ai.dst.direction = 0;
+ p->ai.dst.cargo = CT_PASSENGERS;
+
+ // Fill common fields
+ p->ai.cargo_type = CT_PASSENGERS;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 4;
+ p->ai.num_want_fullload = 0;
+
+// p->ai.loco_id = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+
+ p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantPassengerRouteInsideTown(Player *p)
+{
+ int i;
+ FoundRoute fr;
+ Town *t;
+
+ i = 60;
+ for(;;) {
+ // Find a town big enough
+ t = AiFindRandomTown();
+ if (t != NULL && t->population >= 700)
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ fr.cargo = CT_PASSENGERS;
+ fr.from = fr.to = t;
+
+ if (!AiCheckIfRouteIsGood(p, &fr, 2))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = t->xy;
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 10;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.buildcmd_a = 1;
+ p->ai.src.direction = 0;
+ p->ai.src.cargo = CT_PASSENGERS;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = t->xy;
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 10;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.buildcmd_a = 0xFF;
+ p->ai.dst.direction = 0;
+ p->ai.dst.cargo = CT_PASSENGERS;
+
+ // Fill common fields
+ p->ai.cargo_type = CT_PASSENGERS;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 2;
+ p->ai.num_want_fullload = 0;
+
+// p->ai.loco_id = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+
+ p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
+ p->ai.state_mode = -1;
+ p->ai.state_counter = 0;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantRoadRoute(Player *p)
+{
+ uint16 r = (uint16)Random();
+
+ if (r > 0x4000) {
+ AiWantLongRoadIndustryRoute(p);
+ } else if (r > 0x2000) {
+ AiWantMediumRoadIndustryRoute(p);
+ } else if (r > 0x1000) {
+ AiWantLongRoadPassengerRoute(p);
+ } else {
+ AiWantPassengerRouteInsideTown(p);
+ }
+
+}
+
+static void AiWantPassengerAircraftRoute(Player *p)
+{
+ FoundRoute fr;
+ int i;
+
+ i = 60;
+ for(;;) {
+
+ // look for one from the subsidy list
+ AiFindSubsidyPassengerRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance,0,95+1))
+ break;
+
+ // try a random one
+ AiFindRandomPassengerRoute(&fr);
+ if (IS_INT_INSIDE(fr.distance,0,95+1))
+ break;
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ fr.cargo = CT_PASSENGERS;
+ if (!AiCheckIfRouteIsGood(p, &fr, 4))
+ return;
+
+
+ // Fill the source field
+ p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 12;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.cargo = fr.cargo;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 12;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.cargo = fr.cargo;
+
+ // Fill common fields
+ p->ai.cargo_type = fr.cargo;
+ p->ai.build_kind = 0;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 1;
+ p->ai.num_want_fullload = 1;
+// p->ai.loco_id = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+
+ p->ai.state = AIS_AIRPORT_STUFF;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantOilRigAircraftRoute(Player *p)
+{
+ int i;
+ FoundRoute fr;
+ Town *t;
+ Industry *in;
+
+ i = 60;
+ for(;;) {
+ // Find a town
+ t = AiFindRandomTown();
+ if (t != NULL) {
+ // Find a random oil rig industry
+ in = GetIndustry(RandomRange(_total_industries));
+ if (in != NULL && in->type == IT_OIL_RIG) {
+ if (DistanceManhattan(t->xy, in->xy) < 60)
+ break;
+ }
+ }
+
+ // only test 60 times
+ if (--i == 0)
+ return;
+ }
+
+ fr.cargo = CT_PASSENGERS;
+ fr.from = fr.to = t;
+
+ if (!AiCheckIfRouteIsGood(p, &fr, 4))
+ return;
+
+ // Fill the source field
+ p->ai.src.spec_tile = t->xy;
+ p->ai.src.use_tile = 0;
+ p->ai.src.rand_rng = 12;
+ p->ai.src.cur_building_rule = 0xFF;
+ p->ai.src.cargo = CT_PASSENGERS;
+
+ // Fill the dest field
+ p->ai.dst.spec_tile = in->xy;
+ p->ai.dst.use_tile = 0;
+ p->ai.dst.rand_rng = 5;
+ p->ai.dst.cur_building_rule = 0xFF;
+ p->ai.dst.cargo = CT_PASSENGERS;
+
+ // Fill common fields
+ p->ai.cargo_type = CT_PASSENGERS;
+ p->ai.build_kind = 1;
+ p->ai.num_build_rec = 2;
+ p->ai.num_loco_to_build = 1;
+ p->ai.num_want_fullload = 0;
+// p->ai.loco_id = INVALID_VEHICLE;
+ p->ai.order_list_blocks[0] = 0;
+ p->ai.order_list_blocks[1] = 1;
+ p->ai.order_list_blocks[2] = 255;
+
+ p->ai.state = AIS_AIRPORT_STUFF;
+ p->ai.timeout_counter = 0;
+}
+
+static void AiWantAircraftRoute(Player *p)
+{
+ uint16 r = (uint16)Random();
+
+ if (r >= 0x2AAA || _date < 0x3912) {
+ AiWantPassengerAircraftRoute(p);
+ } else {
+ AiWantOilRigAircraftRoute(p);
+ }
+}
+
+static void AiWantShipRoute(Player *p)
+{
+ // XXX
+// error("AiWaitShipRoute");
+}
+
+
+
+static void AiStateWantNewRoute(Player *p)
+{
+ uint16 r;
+ int i;
+
+ if (p->player_money < AiGetBasePrice(p) * 500) {
+ p->ai.state = AIS_0;
+ return;
+ }
+
+ i = 200;
+ for(;;) {
+ r = (uint16)Random();
+
+ if (_patches.ai_disable_veh_train && _patches.ai_disable_veh_roadveh &&
+ _patches.ai_disable_veh_aircraft && _patches.ai_disable_veh_ship)
+ return;
+
+ if (r < 0x7626) {
+ if (_patches.ai_disable_veh_train) continue;
+ AiWantTrainRoute(p);
+ } else if (r < 0xC4EA) {
+ if (_patches.ai_disable_veh_roadveh) continue;
+ AiWantRoadRoute(p);
+ } else if (r < 0xD89B) {
+ if (_patches.ai_disable_veh_aircraft) continue;
+ AiWantAircraftRoute(p);
+ } else {
+ if (_patches.ai_disable_veh_ship) continue;
+ AiWantShipRoute(p);
+ }
+
+ // got a route?
+ if (p->ai.state != AIS_WANT_NEW_ROUTE)
+ break;
+
+ // time out?
+ if (--i == 0) {
+ if (++p->ai.state_counter == 556) p->ai.state = AIS_0;
+ break;
+ }
+ }
+}
+
+static bool AiCheckTrackResources(TileIndex tile, const AiDefaultBlockData *p, byte cargo)
+{
+ uint values[NUM_CARGO];
+ int rad;
+
+ for(;p->mode != 4;p++) if (p->mode == 1) {
+ TileIndex tile2 = TILE_ADD(tile, ToTileIndexDiff(p->tileoffs));
+ uint w;
+ uint h;
+
+ w = GB(p->attr, 1, 3);
+ h = GB(p->attr, 4, 3);
+ if (p->attr & 1) uintswap(w, h);
+
+
+ if (_patches.modified_catchment) {
+ rad = CA_TRAIN;
+ } else {
+ rad = 4;
+ }
+
+ if (cargo & 0x80) {
+ GetProductionAroundTiles(values, tile2, w, h, rad);
+ return values[cargo & 0x7F] != 0;
+ } else {
+ GetAcceptanceAroundTiles(values, tile2, w, h, rad);
+ if (!(values[cargo] & ~7))
+ return false;
+ if (cargo != CT_MAIL)
+ return true;
+ return !!((values[cargo]>>1) & ~7);
+ }
+ }
+
+ return true;
+}
+
+static int32 AiDoBuildDefaultRailTrack(TileIndex tile, const AiDefaultBlockData *p, byte flag)
+{
+ int32 ret;
+ int32 total_cost = 0;
+ Town *t = NULL;
+ int rating = 0;
+ int i,j,k;
+
+ for(;;) {
+ // This will seldomly overflow for valid reasons. Mask it to be on the safe side.
+ uint c = TILE_MASK(tile + ToTileIndexDiff(p->tileoffs));
+
+ _cleared_town = NULL;
+
+ if (p->mode < 2) {
+ if (p->mode == 0) {
+ // Depot
+ ret = DoCommandByTile(c, _cur_ai_player->ai.railtype_to_use, p->attr, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_TRAIN_DEPOT);
+ } else {
+ // Station
+ ret = DoCommandByTile(c, (p->attr&1) | (p->attr>>4)<<8 | (p->attr>>1&7)<<16, _cur_ai_player->ai.railtype_to_use, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_RAILROAD_STATION);
+ }
+
+ if (CmdFailed(ret)) return CMD_ERROR;
+ total_cost += ret;
+
+clear_town_stuff:;
+ if (_cleared_town != NULL) {
+ if (t != NULL && t != _cleared_town)
+ return CMD_ERROR;
+ t = _cleared_town;
+ rating += _cleared_town_rating;
+ }
+ } else if (p->mode == 2) {
+ // Rail
+ if (IsTileType(c, MP_RAILWAY))
+ return CMD_ERROR;
+
+ j = p->attr;
+ k = 0;
+
+ // Build the rail
+ for(i=0; i!=6; i++,j>>=1) {
+ if (j&1) {
+ k = i;
+ ret = DoCommandByTile(c, _cur_ai_player->ai.railtype_to_use, i, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL);
+ if (CmdFailed(ret)) return CMD_ERROR;
+ total_cost += ret;
+ }
+ }
+
+ /* signals too? */
+ if (j&3) {
+ // Can't build signals on a road.
+ if (IsTileType(c, MP_STREET)) return CMD_ERROR;
+
+ if (flag & DC_EXEC) {
+ j = 4 - j;
+ do {
+ ret = DoCommandByTile(c, k, 0, flag, CMD_BUILD_SIGNALS);
+ } while (--j);
+ } else {
+ ret = _price.build_signals;
+ }
+ if (CmdFailed(ret)) return CMD_ERROR;
+ total_cost += ret;
+ }
+ } else if (p->mode == 3) {
+ //Clear stuff and then build single rail.
+ if (GetTileSlope(c,NULL) != 0)
+ return CMD_ERROR;
+ ret = DoCommandByTile(c, 0, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_LANDSCAPE_CLEAR);
+ if (CmdFailed(ret)) return CMD_ERROR;
+ total_cost += ret + _price.build_rail;
+
+ if (flag & DC_EXEC) {
+ DoCommandByTile(c, _cur_ai_player->ai.railtype_to_use, p->attr&1, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_SINGLE_RAIL);
+ }
+
+ goto clear_town_stuff;
+ } else {
+ // Unk
+ break;
+ }
+
+ p++;
+ }
+
+ if (!(flag & DC_EXEC)) {
+ if (t != NULL && rating > t->ratings[_current_player]) {
+ return CMD_ERROR;
+ }
+ }
+
+ return total_cost;
+}
+
+// Returns rule and cost
+static int AiBuildDefaultRailTrack(TileIndex tile, byte p0, byte p1, byte p2, byte p3, byte dir, byte cargo, int32 *cost)
+{
+ int i;
+ const AiDefaultRailBlock *p;
+
+ for(i=0; (p = _default_rail_track_data[i]) != NULL; i++) {
+ if (p->p0 == p0 && p->p1 == p1 && p->p2 == p2 && p->p3 == p3 &&
+ (p->dir == 0xFF || p->dir == dir || ((p->dir-1)&3) == dir)) {
+ *cost = AiDoBuildDefaultRailTrack(tile, p->data, DC_NO_TOWN_RATING);
+ if (*cost != CMD_ERROR && AiCheckTrackResources(tile, p->data, cargo))
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+static const byte _terraform_up_flags[] = {
+ 14, 13, 12, 11,
+ 10, 9, 8, 7,
+ 6, 5, 4, 3,
+ 2, 1, 0, 1,
+ 2, 1, 4, 1,
+ 2, 1, 8, 1,
+ 2, 1, 4, 2,
+ 2, 1
+};
+
+static const byte _terraform_down_flags[] = {
+ 1, 2, 3, 4,
+ 5, 6, 1, 8,
+ 9, 10, 8, 12,
+ 4, 2, 0, 0,
+ 1, 2, 3, 4,
+ 5, 6, 2, 8,
+ 9, 10, 1, 12,
+ 8, 4
+};
+
+static void AiDoTerraformLand(TileIndex tile, int dir, int unk, int mode)
+{
+ byte old_player;
+ uint32 r;
+ uint slope;
+ uint h;
+
+ old_player = _current_player;
+ _current_player = OWNER_NONE;
+
+ r = Random();
+
+ unk &= (int)r;
+
+ do {
+ tile = TILE_MASK(tile + TileOffsByDir(dir));
+
+ r >>= 2;
+ if (r&2) {
+ dir++;
+ if (r&1)
+ dir -= 2;
+ }
+ dir &= 3;
+ } while (--unk >= 0);
+
+ slope = GetTileSlope(tile, &h);
+
+ if (slope != 0) {
+ if (mode > 0 || (mode == 0 && !(r&0xC))) {
+ // Terraform up
+ DoCommandByTile(tile, _terraform_up_flags[slope-1], 1,
+ DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
+ } else if (h != 0) {
+ // Terraform down
+ DoCommandByTile(tile, _terraform_down_flags[slope-1], 0,
+ DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
+ }
+ }
+
+ _current_player = old_player;
+}
+
+static void AiStateBuildDefaultRailBlocks(Player *p)
+{
+ int i, j;
+ AiBuildRec *aib;
+ int rule;
+ int32 cost;
+
+ // time out?
+ if (++p->ai.timeout_counter == 1388) {
+ p->ai.state = AIS_DELETE_RAIL_BLOCKS;
+ return;
+ }
+
+ // do the following 8 times
+ i = 8;
+ do {
+ // check if we can build the default track
+ aib = &p->ai.src;
+ j = p->ai.num_build_rec;
+ do {
+ // this item has already been built?
+ if (aib->cur_building_rule != 255)
+ continue;
+
+ // adjust the coordinate randomly,
+ // to make sure that we find a position.
+ aib->use_tile = AdjustTileCoordRandomly(aib->spec_tile, aib->rand_rng);
+
+ // check if the track can be build there.
+ rule = AiBuildDefaultRailTrack(aib->use_tile,
+ p->ai.build_kind, p->ai.num_wagons,
+ aib->unk6, aib->unk7,
+ aib->direction, aib->cargo, &cost);
+
+ if (rule == -1) {
+ // cannot build, terraform after a while
+ if (p->ai.state_counter >= 600) {
+ AiDoTerraformLand(aib->use_tile, Random()&3, 3, (int8)p->ai.state_mode);
+ }
+ // also try the other terraform direction
+ if (++p->ai.state_counter >= 1000) {
+ p->ai.state_counter = 0;
+ p->ai.state_mode = -p->ai.state_mode;
+ }
+ } else if (CheckPlayerHasMoney(cost)) {
+ int32 r;
+ // player has money, build it.
+ aib->cur_building_rule = rule;
+
+ r = AiDoBuildDefaultRailTrack(
+ aib->use_tile,
+ _default_rail_track_data[rule]->data,
+ DC_EXEC | DC_NO_TOWN_RATING
+ );
+ assert(r != CMD_ERROR);
+ }
+ } while (++aib,--j);
+ } while (--i);
+
+ // check if we're done with all of them
+ aib = &p->ai.src;
+ j = p->ai.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.
+ p->ai.state = AIS_BUILD_RAIL;
+ p->ai.state_mode = 255;
+}
+
+static TileIndex AiGetEdgeOfDefaultRailBlock(byte rule, TileIndex tile, byte cmd, int *dir)
+{
+ const AiDefaultBlockData *p = _default_rail_track_data[rule]->data;
+
+ while (p->mode != 3 || !((--cmd) & 0x80)) p++;
+
+ return tile + ToTileIndexDiff(p->tileoffs) - TileOffsByDir(*dir = p->attr);
+}
+
+typedef struct AiRailPathFindData {
+ TileIndex tile;
+ TileIndex tile2;
+ int count;
+ bool flag;
+} AiRailPathFindData;
+
+static bool AiEnumFollowTrack(TileIndex tile, AiRailPathFindData *a, int track, uint length, byte *state)
+{
+ if (a->flag)
+ return true;
+
+ if (length > 20 || tile == a->tile) {
+ a->flag = true;
+ return true;
+ }
+
+ if (DistanceMax(tile, a->tile2) < 4)
+ a->count++;
+
+ return false;
+}
+
+static bool AiDoFollowTrack(Player *p)
+{
+ AiRailPathFindData arpfd;
+ arpfd.tile = p->ai.start_tile_a;
+ arpfd.tile2 = p->ai.cur_tile_a;
+ arpfd.flag = false;
+ arpfd.count = 0;
+ FollowTrack(p->ai.cur_tile_a + TileOffsByDir(p->ai.cur_dir_a), 0x2000 | TRANSPORT_RAIL, p->ai.cur_dir_a^2,
+ (TPFEnumProc*)AiEnumFollowTrack, NULL, &arpfd);
+ return arpfd.count > 8;
+}
+
+typedef struct AiRailFinder {
+ TileIndex final_tile;
+ byte final_dir;
+ byte depth;
+ byte recursive_mode;
+ byte cur_best_dir;
+ byte best_dir;
+ byte cur_best_depth;
+ byte best_depth;
+ uint cur_best_dist;
+ const byte *best_ptr;
+ uint best_dist;
+ TileIndex cur_best_tile, best_tile;
+ TileIndex bridge_end_tile;
+ Player *player;
+ TileInfo ti;
+} AiRailFinder;
+
+static const byte _ai_table_15[4][8] = {
+ {0, 0, 4, 3, 3, 1, 128+0, 64},
+ {1, 1, 2, 0, 4, 2, 128+1, 65},
+ {0, 2, 2, 3, 5, 1, 128+2, 66},
+ {1, 3, 5, 0, 3, 2, 128+3, 67}
+};
+
+static const byte _dir_table_1[] = {3, 9, 12, 6};
+static const byte _dir_table_2[] = {12, 6, 3, 9};
+
+
+static bool AiIsTileBanned(Player *p, TileIndex tile, byte val) {
+ int i;
+
+ for(i=0; i!=p->ai.banned_tile_count; i++)
+ if (p->ai.banned_tiles[i] == tile &&
+ p->ai.banned_val[i] == val)
+ return true;
+ return false;
+}
+
+static void AiBanTile(Player *p, TileIndex tile, byte val) {
+ int i;
+
+ for(i=lengthof(p->ai.banned_tiles)-1; i!=0; i--) {
+ p->ai.banned_tiles[i] = p->ai.banned_tiles[i-1];
+ p->ai.banned_val[i] = p->ai.banned_val[i-1];
+ }
+
+ p->ai.banned_tiles[0] = tile;
+ p->ai.banned_val[0] = val;
+
+ if (p->ai.banned_tile_count != lengthof(p->ai.banned_tiles))
+ p->ai.banned_tile_count++;
+}
+
+static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir);
+
+static bool AiCheckRailPathBetter(AiRailFinder *arf, const byte *p)
+{
+ bool better = false;
+
+ if (arf->recursive_mode < 1) {
+ // Mode is 0. This means destination has not been found yet.
+ // If the found path is shorter than the current one, remember it.
+ if (arf->cur_best_dist < arf->best_dist) {
+ arf->best_dir = arf->cur_best_dir;
+ arf->best_dist = arf->cur_best_dist;
+ arf->best_ptr = p;
+ arf->best_tile = arf->cur_best_tile;
+ better = true;
+ }
+ } else if (arf->recursive_mode > 1) {
+ // Mode is 2.
+ if (arf->best_dist != 0 || arf->cur_best_depth < arf->best_depth) {
+ arf->best_depth = arf->cur_best_depth;
+ arf->best_dist = 0;
+ arf->best_ptr = p;
+ arf->best_tile = 0;
+ better = true;
+ }
+ }
+ arf->recursive_mode = 0;
+ arf->cur_best_dist = (uint)-1;
+ arf->cur_best_depth = 0xff;
+
+ return better;
+}
+
+static inline void AiCheckBuildRailBridgeHere(AiRailFinder *arf, TileIndex tile, const byte *p)
+{
+ TileIndex tile_new;
+ bool flag;
+
+ int dir2 = p[0] & 3;
+
+ FindLandscapeHeightByTile(&arf->ti, tile);
+
+ if (arf->ti.tileh == _dir_table_1[dir2] || (arf->ti.tileh==0 && arf->ti.z!=0)) {
+ tile_new = tile;
+ // Allow bridges directly over bottom tiles
+ flag = arf->ti.z == 0;
+ for(;;) {
+ if ((TileIndexDiff)tile_new < -TileOffsByDir(dir2)) return; // Wraping around map, no bridge possible!
+ tile_new = TILE_MASK(tile_new + TileOffsByDir(dir2));
+ FindLandscapeHeightByTile(&arf->ti, tile_new);
+ if (arf->ti.tileh != 0 || arf->ti.type == MP_CLEAR || arf->ti.type == MP_TREES) {
+ if (!flag) return;
+ break;
+ }
+ if (arf->ti.type != MP_WATER && arf->ti.type != MP_RAILWAY && arf->ti.type != MP_STREET)
+ return;
+ flag = true;
+ }
+
+ // Is building a (rail)bridge possible at this place (type doesn't matter)?
+ if (CmdFailed(DoCommandByTile(tile_new, tile, 0 | arf->player->ai.railtype_to_use << 8,
+ DC_AUTO, CMD_BUILD_BRIDGE)) )
+ return;
+ AiBuildRailRecursive(arf, tile_new, dir2);
+
+ // At the bottom depth, check if the new path is better than the old one.
+ if (arf->depth == 1) {
+ if (AiCheckRailPathBetter(arf, p))
+ arf->bridge_end_tile = tile_new;
+ }
+ }
+}
+
+static inline void AiCheckBuildRailTunnelHere(AiRailFinder *arf, TileIndex tile, const byte *p)
+{
+ FindLandscapeHeightByTile(&arf->ti, tile);
+
+ if (arf->ti.tileh == _dir_table_2[p[0]&3] && arf->ti.z!=0) {
+ int32 cost = DoCommandByTile(tile, arf->player->ai.railtype_to_use, 0, DC_AUTO, CMD_BUILD_TUNNEL);
+
+ if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) {
+ AiBuildRailRecursive(arf, _build_tunnel_endtile, p[0]&3);
+ if (arf->depth == 1) {
+ AiCheckRailPathBetter(arf, p);
+ }
+ }
+ }
+}
+
+
+static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir)
+{
+ const byte *p;
+
+ tile = TILE_MASK(tile + TileOffsByDir(dir));
+
+ // Reached destination?
+ if (tile == arf->final_tile) {
+ if (arf->final_dir != (dir^2)) {
+ if (arf->recursive_mode != 2)
+ arf->recursive_mode = 1;
+ } else if (arf->recursive_mode != 2) {
+ arf->recursive_mode = 2;
+ arf->cur_best_depth = arf->depth;
+ } else {
+ if (arf->depth < arf->cur_best_depth)
+ arf->cur_best_depth = arf->depth;
+ }
+ return;
+ }
+
+ // Depth too deep?
+ if (arf->depth >= 4) {
+ uint dist = DistanceMaxPlusManhattan(tile, arf->final_tile);
+ if (dist < arf->cur_best_dist) {
+ // Store the tile that is closest to the final position.
+ arf->cur_best_depth = arf->depth;
+ arf->cur_best_dist = dist;
+ arf->cur_best_tile = tile;
+ arf->cur_best_dir = dir;
+ }
+ return;
+ }
+
+ // Increase recursion depth
+ arf->depth++;
+
+ // Grab pointer to list of stuff that is possible to build
+ p = _ai_table_15[dir];
+
+ // Try to build a single rail in all directions.
+ FindLandscapeHeightByTile(&arf->ti, tile);
+ if (arf->ti.z == 0) {
+ p += 6;
+ } 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]) &&
+ !CmdFailed(DoCommandByTile(tile, arf->player->ai.railtype_to_use, p[0], DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL))) {
+ AiBuildRailRecursive(arf, tile, p[1]);
+ }
+
+ // At the bottom depth?
+ if (arf->depth == 1) {
+ AiCheckRailPathBetter(arf, p);
+ }
+
+ p += 2;
+ } while (!(p[0]&0x80));
+ }
+
+ AiCheckBuildRailBridgeHere(arf, tile, p);
+ AiCheckBuildRailTunnelHere(arf, tile, p+1);
+
+ arf->depth--;
+}
+
+
+static const byte _dir_table_3[]= {0x25, 0x2A, 0x19, 0x16};
+
+static void AiBuildRailConstruct(Player *p)
+{
+ AiRailFinder arf;
+ int i;
+
+ // Check too much lookahead?
+ if (AiDoFollowTrack(p)) {
+ p->ai.state_counter = (Random()&0xE)+6; // Destruct this amount of blocks
+ p->ai.state_mode = 1; // Start destruct
+
+ // Ban this tile and don't reach it for a while.
+ AiBanTile(p, p->ai.cur_tile_a, FindFirstBit(GetRailTrackStatus(p->ai.cur_tile_a)));
+ return;
+ }
+
+ // Setup recursive finder and call it.
+ arf.player = p;
+ arf.final_tile = p->ai.cur_tile_b;
+ arf.final_dir = p->ai.cur_dir_b;
+ arf.depth = 0;
+ arf.recursive_mode = 0;
+ arf.best_ptr = NULL;
+ arf.cur_best_dist = (uint)-1;
+ arf.cur_best_depth = 0xff;
+ arf.best_dist = (uint)-1;
+ arf.best_depth = 0xff;
+ arf.cur_best_tile = 0;
+ arf.best_tile = 0;
+ AiBuildRailRecursive(&arf, p->ai.cur_tile_a, p->ai.cur_dir_a);
+
+ // Reached destination?
+ if (arf.recursive_mode == 2 && arf.cur_best_depth == 0) {
+ p->ai.state_mode = 255;
+ return;
+ }
+
+ // Didn't find anything to build?
+ if (arf.best_ptr == NULL) {
+ // Terraform some
+ for(i=0; i!=5; i++)
+ AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);
+
+ if (++p->ai.state_counter == 21) {
+ p->ai.state_counter = 40;
+ p->ai.state_mode = 1;
+
+ // Ban this tile
+ AiBanTile(p, p->ai.cur_tile_a, FindFirstBit(GetRailTrackStatus(p->ai.cur_tile_a)));
+ }
+ return;
+ }
+
+ p->ai.cur_tile_a += TileOffsByDir(p->ai.cur_dir_a);
+
+ if (arf.best_ptr[0]&0x80) {
+ int i;
+ int32 bridge_len = GetBridgeLength(arf.bridge_end_tile, p->ai.cur_tile_a);
+
+ /* Figure out what (rail)bridge type to build
+ start with best bridge, then go down to worse and worse bridges
+ unnecessary to check for worse bridge (i=0), since AI will always build that.
+ AI is so fucked up that fixing this small thing will probably not solve a thing
+ */
+ for (i = MAX_BRIDGES - 1; i != 0; i--) {
+ if (CheckBridge_Stuff(i, bridge_len)) {
+ int32 cost = DoCommandByTile(arf.bridge_end_tile, p->ai.cur_tile_a, i | (p->ai.railtype_to_use << 8), DC_AUTO, CMD_BUILD_BRIDGE);
+ if (!CmdFailed(cost) && cost < (p->player_money >> 5))
+ break;
+ }
+ }
+
+ // Build it
+ DoCommandByTile(arf.bridge_end_tile, p->ai.cur_tile_a, i | (p->ai.railtype_to_use << 8), DC_AUTO | DC_EXEC, CMD_BUILD_BRIDGE);
+
+ p->ai.cur_tile_a = arf.bridge_end_tile;
+ p->ai.state_counter = 0;
+ } else if (arf.best_ptr[0]&0x40) {
+ // tunnel
+ DoCommandByTile(p->ai.cur_tile_a, p->ai.railtype_to_use, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
+ p->ai.cur_tile_a = _build_tunnel_endtile;
+ p->ai.state_counter = 0;
+ } else {
+ // rail
+ p->ai.cur_dir_a = arf.best_ptr[1];
+ DoCommandByTile(p->ai.cur_tile_a, p->ai.railtype_to_use, arf.best_ptr[0],
+ DC_EXEC | DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL);
+ p->ai.state_counter = 0;
+ }
+
+ if (arf.best_tile != 0) {
+ for(i=0; i!=2; i++)
+ AiDoTerraformLand(arf.best_tile, arf.best_dir, 3, 0);
+ }
+}
+
+static bool AiRemoveTileAndGoForward(Player *p)
+{
+ byte b;
+ int bit;
+ const byte *ptr;
+ TileIndex tile = p->ai.cur_tile_a;
+ int offs;
+ TileIndex tilenew;
+
+ if (IsTileType(tile, MP_TUNNELBRIDGE)) {
+ if (!(_m[tile].m5 & 0x80)) {
+ // Clear the tunnel and continue at the other side of it.
+ if (CmdFailed(DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR)) )
+ return false;
+ p->ai.cur_tile_a = TILE_MASK(_build_tunnel_endtile - TileOffsByDir(p->ai.cur_dir_a));
+ return true;
+ }
+
+ if (!(_m[tile].m5 & 0x40)) {
+
+ // Check if the bridge points in the right direction.
+ // This is not really needed the first place AiRemoveTileAndGoForward is called.
+ if ((_m[tile].m5&1) != (p->ai.cur_dir_a&1))
+ return false;
+
+ // Find other side of bridge.
+ offs = TileOffsByDir(p->ai.cur_dir_a);
+ do {
+ tile = TILE_MASK(tile - offs);
+ } while (_m[tile].m5 & 0x40);
+
+ tilenew = TILE_MASK(tile - offs);
+ // And clear the bridge.
+ if (CmdFailed(DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR)) )
+ return false;
+ p->ai.cur_tile_a = tilenew;
+ return true;
+ }
+ }
+
+ // Find the railtype at the position. Quit if no rail there.
+ b = GetRailTrackStatus(tile) & _dir_table_3[p->ai.cur_dir_a];
+ if (b == 0)
+ return false;
+
+ // Convert into a bit position that CMD_REMOVE_SINGLE_RAIL expects.
+ bit = FindFirstBit(b);
+
+ // Then remove and signals if there are any.
+ if (IsTileType(tile, MP_RAILWAY) &&
+ (_m[tile].m5&0xC0) == 0x40) {
+ DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_REMOVE_SIGNALS);
+ }
+
+ // And also remove the rail.
+ if (CmdFailed(DoCommandByTile(tile, 0, bit, DC_EXEC, CMD_REMOVE_SINGLE_RAIL)) )
+ return false;
+
+ // Find the direction at the other edge of the rail.
+ ptr = _ai_table_15[p->ai.cur_dir_a^2];
+ while (ptr[0] != bit) ptr+=2;
+ p->ai.cur_dir_a = ptr[1] ^ 2;
+
+ // And then also switch tile.
+ p->ai.cur_tile_a = TILE_MASK(p->ai.cur_tile_a - TileOffsByDir(p->ai.cur_dir_a));
+
+ return true;
+}
+
+
+static void AiBuildRailDestruct(Player *p)
+{
+ // Decrease timeout.
+ if (!--p->ai.state_counter) {
+ p->ai.state_mode = 2;
+ p->ai.state_counter = 0;
+ }
+
+ // Don't do anything if the destination is already reached.
+ if (p->ai.cur_tile_a == p->ai.start_tile_a)
+ return;
+
+ AiRemoveTileAndGoForward(p);
+}
+
+
+static void AiBuildRail(Player *p)
+{
+ int i;
+
+ if (p->ai.state_mode < 1) {
+ // Construct mode, build new rail.
+ AiBuildRailConstruct(p);
+ } else if (p->ai.state_mode == 1) {
+
+ // Destruct mode, destroy the rail currently built.
+ AiBuildRailDestruct(p);
+ } else if (p->ai.state_mode == 2) {
+
+ // Terraform some and then try building again.
+ for(i=0; i!=4; i++)
+ AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);
+
+ if (++p->ai.state_counter == 4) {
+ p->ai.state_counter = 0;
+ p->ai.state_mode = 0;
+ }
+ }
+}
+
+static void AiStateBuildRail(Player *p)
+{
+ int num;
+ AiBuildRec *aib;
+ byte cmd;
+ TileIndex tile;
+ int dir;
+
+ // time out?
+ if (++p->ai.timeout_counter == 1388) {
+ p->ai.state = AIS_DELETE_RAIL_BLOCKS;
+ return;
+ }
+
+ // Currently building a rail between two points?
+ if (p->ai.state_mode != 255) {
+ AiBuildRail(p);
+
+ // Alternate between edges
+ swap_tile(&p->ai.start_tile_a, &p->ai.start_tile_b);
+ swap_tile(&p->ai.cur_tile_a, &p->ai.cur_tile_b);
+ swap_byte(&p->ai.start_dir_a, &p->ai.start_dir_b);
+ swap_byte(&p->ai.cur_dir_a, &p->ai.cur_dir_b);
+ return;
+ }
+
+ // Now, find two new points to build between
+ num = p->ai.num_build_rec;
+ aib = &p->ai.src;
+
+ for(;;) {
+ cmd = aib->buildcmd_a;
+ aib->buildcmd_a = 255;
+ if (cmd != 255) break;
+
+ cmd = aib->buildcmd_b;
+ aib->buildcmd_b = 255;
+ if (cmd != 255) break;
+
+ aib++;
+ if (--num == 0) {
+ p->ai.state = AIS_BUILD_RAIL_VEH;
+ p->ai.state_counter = 0; // timeout
+ return;
+ }
+ }
+
+ // Find first edge to build from.
+ tile = AiGetEdgeOfDefaultRailBlock(aib->cur_building_rule, aib->use_tile, cmd&3, &dir);
+ p->ai.start_tile_a = tile;
+ p->ai.cur_tile_a = tile;
+ p->ai.start_dir_a = dir;
+ p->ai.cur_dir_a = dir;
+ DoCommandByTile(TILE_MASK(tile + TileOffsByDir(dir)), 0, (dir&1)?1:0, DC_EXEC, CMD_REMOVE_SINGLE_RAIL);
+
+ assert(TILE_MASK(tile) != 0xFF00);
+
+ // Find second edge to build to
+ aib = (&p->ai.src) + ((cmd >> 4)&0xF);
+ tile = AiGetEdgeOfDefaultRailBlock(aib->cur_building_rule, aib->use_tile, (cmd>>2)&3, &dir);
+ p->ai.start_tile_b = tile;
+ p->ai.cur_tile_b = tile;
+ p->ai.start_dir_b = dir;
+ p->ai.cur_dir_b = dir;
+ DoCommandByTile(TILE_MASK(tile + TileOffsByDir(dir)), 0, (dir&1)?1:0, DC_EXEC, CMD_REMOVE_SINGLE_RAIL);
+
+ assert(TILE_MASK(tile) != 0xFF00);
+
+ // And setup state.
+ p->ai.state_mode = 2;
+ p->ai.state_counter = 0;
+ p->ai.banned_tile_count = 0;
+}
+
+static int AiGetStationIdByDef(TileIndex tile, int id)
+{
+ const AiDefaultBlockData *p = _default_rail_track_data[id]->data;
+ while (p->mode != 1) p++;
+ return _m[TILE_ADD(tile, ToTileIndexDiff(p->tileoffs))].m2;
+}
+
+static void AiStateBuildRailVeh(Player *p)
+{
+ const AiDefaultBlockData *ptr;
+ TileIndex tile;
+ int i, veh;
+ int cargo;
+ int32 cost;
+ Vehicle *v;
+ uint loco_id;
+
+ ptr = _default_rail_track_data[p->ai.src.cur_building_rule]->data;
+ while (ptr->mode != 0) { ptr++; }
+
+ tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));
+
+ cargo = p->ai.cargo_type;
+ for(i=0;;) {
+ if (p->ai.wagon_list[i] == INVALID_VEHICLE) {
+ veh = _cargoc.ai_railwagon[p->ai.railtype_to_use][cargo];
+ cost = DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_RAIL_VEHICLE);
+ if (CmdFailed(cost)) goto handle_nocash;
+ p->ai.wagon_list[i] = _new_wagon_id;
+ p->ai.wagon_list[i+1] = INVALID_VEHICLE;
+ return;
+ }
+ if (cargo == CT_MAIL)
+ cargo = CT_PASSENGERS;
+ if (++i == p->ai.num_wagons * 2 - 1)
+ break;
+ }
+
+ // Which locomotive to build?
+ veh = AiChooseTrainToBuild(p->ai.railtype_to_use, p->player_money, (cargo!=CT_PASSENGERS)?1:0, tile);
+ if (veh == -1) {
+handle_nocash:
+ // after a while, if AI still doesn't have cash, get out of this block by selling the wagons.
+ if (++p->ai.state_counter == 1000) {
+ for(i=0; p->ai.wagon_list[i] != INVALID_VEHICLE; i++) {
+ cost = DoCommandByTile(tile, p->ai.wagon_list[i], 0, DC_EXEC, CMD_SELL_RAIL_WAGON);
+ assert(!CmdFailed(cost));
+ }
+ p->ai.state = AIS_0;
+ }
+ return;
+ }
+
+ // Try to build the locomotive
+ cost = DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_RAIL_VEHICLE);
+ assert(!CmdFailed(cost));
+ loco_id = _new_train_id;
+
+ // Sell a vehicle if the train is double headed.
+ v = GetVehicle(loco_id);
+ if (v->next != NULL) {
+ i = p->ai.wagon_list[p->ai.num_wagons*2-2];
+ p->ai.wagon_list[p->ai.num_wagons*2-2] = INVALID_VEHICLE;
+ DoCommandByTile(tile, i, 0, DC_EXEC, CMD_SELL_RAIL_WAGON);
+ }
+
+ // Move the wagons onto the train
+ for(i=0; p->ai.wagon_list[i] != INVALID_VEHICLE; i++) {
+ DoCommandByTile(tile, p->ai.wagon_list[i] | (loco_id << 16), 0, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
+ }
+
+ for(i=0; p->ai.order_list_blocks[i] != 0xFF; i++) {
+ AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i];
+ bool is_pass = (p->ai.cargo_type == CT_PASSENGERS ||
+ p->ai.cargo_type == CT_MAIL ||
+ (_opt.landscape==LT_NORMAL && p->ai.cargo_type == CT_VALUABLES));
+ Order order;
+
+ order.type = OT_GOTO_STATION;
+ order.flags = 0;
+ order.station = AiGetStationIdByDef(aib->use_tile, aib->cur_building_rule);
+
+ if (!is_pass && i == 1) order.flags |= OF_UNLOAD;
+ if (p->ai.num_want_fullload != 0 && (is_pass || i == 0))
+ order.flags |= OF_FULL_LOAD;
+
+ DoCommandByTile(0, loco_id + (i << 16), PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
+ }
+
+ DoCommandByTile(0, loco_id, 0, DC_EXEC, CMD_START_STOP_TRAIN);
+
+ DoCommandByTile(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
+
+ if (p->ai.num_want_fullload != 0)
+ p->ai.num_want_fullload--;
+
+ if (--p->ai.num_loco_to_build != 0) {
+// p->ai.loco_id = INVALID_VEHICLE;
+ p->ai.wagon_list[0] = INVALID_VEHICLE;
+ } else {
+ p->ai.state = AIS_0;
+ }
+}
+
+static void AiStateDeleteRailBlocks(Player *p)
+{
+ int num;
+ AiBuildRec *aib;
+ const AiDefaultBlockData *b;
+
+ num = p->ai.num_build_rec;
+ aib = &p->ai.src;
+ do {
+ if (aib->cur_building_rule != 255) {
+ b = _default_rail_track_data[aib->cur_building_rule]->data;
+ while (b->mode != 4) {
+ DoCommandByTile(TILE_ADD(aib->use_tile, ToTileIndexDiff(b->tileoffs)), 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
+ b++;
+ }
+ }
+ } while (++aib,--num);
+
+ p->ai.state = AIS_0;
+}
+
+static bool AiCheckRoadResources(TileIndex tile, const AiDefaultBlockData *p, byte cargo)
+{
+ uint values[NUM_CARGO];
+ int rad;
+
+ if (_patches.modified_catchment) {
+ rad = CA_TRUCK; //Same as CA_BUS at the moment?
+ } else { //change that at some point?
+ rad = 4;
+ }
+
+ for(;;p++) {
+ if (p->mode == 4) {
+ return true;
+ } else if (p->mode == 1) {
+ TileIndex tile2 = TILE_ADD(tile, ToTileIndexDiff(p->tileoffs));
+
+ if (cargo & 0x80) {
+ GetProductionAroundTiles(values, tile2, 1, 1, rad);
+ return values[cargo & 0x7F] != 0;
+ } else {
+ GetAcceptanceAroundTiles(values, tile2, 1, 1, rad);
+ return (values[cargo]&~7) != 0;
+ }
+ }
+ }
+}
+
+static bool _want_road_truck_station;
+static int32 AiDoBuildDefaultRoadBlock(TileIndex tile, const AiDefaultBlockData *p, byte flag);
+
+// Returns rule and cost
+static int AiFindBestDefaultRoadBlock(TileIndex tile, byte direction, byte cargo, int32 *cost)
+{
+ int i;
+ const AiDefaultRoadBlock *p;
+
+ _want_road_truck_station = (cargo & 0x7F) != CT_PASSENGERS;
+
+ for(i=0; (p = _road_default_block_data[i]) != NULL; i++) {
+ if (p->dir == direction) {
+ *cost = AiDoBuildDefaultRoadBlock(tile, p->data, 0);
+ if (*cost != CMD_ERROR && AiCheckRoadResources(tile, p->data, cargo))
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+static int32 AiDoBuildDefaultRoadBlock(TileIndex tile, const AiDefaultBlockData *p, byte flag)
+{
+ int32 ret;
+ int32 total_cost = 0;
+ Town *t = NULL;
+ int rating = 0;
+ int roadflag = 0;
+
+ for(;p->mode != 4;p++) {
+ uint c = TILE_MASK(tile + ToTileIndexDiff(p->tileoffs));
+
+ _cleared_town = NULL;
+
+ if (p->mode == 2) {
+ if (IsTileType(c, MP_STREET) &&
+ (_m[c].m5&0xF0)==0 &&
+ (_m[c].m5&p->attr)!=0) {
+ roadflag |= 2;
+
+ // all bits are already built?
+ if ((_m[c].m5&p->attr)==p->attr)
+ continue;
+ }
+
+ ret = DoCommandByTile(c, p->attr, 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD);
+ if (CmdFailed(ret)) return CMD_ERROR;
+ total_cost += ret;
+
+ continue;
+ }
+
+ if (p->mode == 0) {
+ // Depot
+ ret = DoCommandByTile(c, p->attr, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_ROAD_DEPOT);
+ goto clear_town_stuff;
+ } else if (p->mode == 1) {
+ if (_want_road_truck_station) {
+ // Truck station
+ ret = DoCommandByTile(c, p->attr, RS_TRUCK, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_ROAD_STOP);
+ } else {
+ // Bus station
+ ret = DoCommandByTile(c, p->attr, RS_BUS, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_ROAD_STOP);
+ }
+clear_town_stuff:;
+
+ if (CmdFailed(ret)) return CMD_ERROR;
+ total_cost += ret;
+
+ if (_cleared_town != NULL) {
+ if (t != NULL && t != _cleared_town)
+ return CMD_ERROR;
+ t = _cleared_town;
+ rating += _cleared_town_rating;
+ }
+ } else if (p->mode == 3) {
+ if (flag & DC_EXEC)
+ continue;
+
+ if (GetTileSlope(c, NULL) != 0)
+ return CMD_ERROR;
+
+ if (!(IsTileType(c, MP_STREET) && (_m[c].m5 & 0xF0) == 0)) {
+ ret = DoCommandByTile(c, 0, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_LANDSCAPE_CLEAR);
+ if (CmdFailed(ret)) return CMD_ERROR;
+ }
+
+ }
+ }
+
+ 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;
+ }
+ }
+ return total_cost;
+}
+
+// Make sure the blocks are not too close to each other
+static bool AiCheckBlockDistances(Player *p, TileIndex tile)
+{
+ AiBuildRec *aib;
+ int num;
+
+ num = p->ai.num_build_rec;
+ aib = &p->ai.src;
+
+ do {
+ if (aib->cur_building_rule != 255) {
+ if (DistanceManhattan(aib->use_tile, tile) < 9)
+ return false;
+ }
+ } while (++aib, --num);
+
+ return true;
+}
+
+
+static void AiStateBuildDefaultRoadBlocks(Player *p)
+{
+ int i, j;
+ AiBuildRec *aib;
+ int rule;
+ int32 cost;
+
+ // time out?
+ if (++p->ai.timeout_counter == 1388) {
+ p->ai.state = AIS_DELETE_RAIL_BLOCKS;
+ return;
+ }
+
+ // do the following 8 times
+ i = 8;
+ do {
+ // check if we can build the default track
+ aib = &p->ai.src;
+ j = p->ai.num_build_rec;
+ do {
+ // this item has already been built?
+ if (aib->cur_building_rule != 255)
+ continue;
+
+ // adjust the coordinate randomly,
+ // to make sure that we find a position.
+ aib->use_tile = AdjustTileCoordRandomly(aib->spec_tile, aib->rand_rng);
+
+ // check if the road can be built there.
+ rule = AiFindBestDefaultRoadBlock(aib->use_tile,
+ aib->direction, aib->cargo, &cost);
+
+ if (rule == -1) {
+ // cannot build, terraform after a while
+ if (p->ai.state_counter >= 600) {
+ AiDoTerraformLand(aib->use_tile, Random()&3, 3, (int8)p->ai.state_mode);
+ }
+ // also try the other terraform direction
+ if (++p->ai.state_counter >= 1000) {
+ p->ai.state_counter = 0;
+ p->ai.state_mode = -p->ai.state_mode;
+ }
+ } else if (CheckPlayerHasMoney(cost) && AiCheckBlockDistances(p,aib->use_tile)) {
+ int32 r;
+
+ // player has money, build it.
+ aib->cur_building_rule = rule;
+
+ r = AiDoBuildDefaultRoadBlock(
+ aib->use_tile,
+ _road_default_block_data[rule]->data,
+ DC_EXEC | DC_NO_TOWN_RATING
+ );
+ assert(r != CMD_ERROR);
+ }
+ } while (++aib,--j);
+ } while (--i);
+
+ // check if we're done with all of them
+ aib = &p->ai.src;
+ j = p->ai.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.
+ p->ai.state = AIS_BUILD_ROAD;
+ p->ai.state_mode = 255;
+}
+
+typedef struct {
+ TileIndex final_tile;
+ byte final_dir;
+ byte depth;
+ byte recursive_mode;
+ byte cur_best_dir;
+ byte best_dir;
+ byte cur_best_depth;
+ byte best_depth;
+ uint cur_best_dist;
+ const byte *best_ptr;
+ uint best_dist;
+ TileIndex cur_best_tile, best_tile;
+ TileIndex bridge_end_tile;
+ Player *player;
+ TileInfo ti;
+} AiRoadFinder;
+
+typedef struct AiRoadEnum {
+ TileIndex dest;
+ TileIndex best_tile;
+ int best_track;
+ uint best_dist;
+} AiRoadEnum;
+
+static const byte _dir_by_track[] = {
+ 0,1,0,1,2,1, 0,0,
+ 2,3,3,2,3,0,
+};
+
+static void AiBuildRoadRecursive(AiRoadFinder *arf, TileIndex tile, int dir);
+
+static bool AiCheckRoadPathBetter(AiRoadFinder *arf, const byte *p)
+{
+ bool better = false;
+
+ if (arf->recursive_mode < 1) {
+ // Mode is 0. This means destination has not been found yet.
+ // If the found path is shorter than the current one, remember it.
+ if (arf->cur_best_dist < arf->best_dist ||
+ (arf->cur_best_dist == arf->best_dist && arf->cur_best_depth < arf->best_depth)) {
+ arf->best_depth = arf->cur_best_depth;
+ arf->best_dist = arf->cur_best_dist;
+ arf->best_dir = arf->cur_best_dir;
+ arf->best_ptr = p;
+ arf->best_tile = arf->cur_best_tile;
+ better = true;
+ }
+ } else if (arf->recursive_mode > 1) {
+ // Mode is 2.
+ if (arf->best_dist != 0 || arf->cur_best_depth < arf->best_depth) {
+ arf->best_depth = arf->cur_best_depth;
+ arf->best_dist = 0;
+ arf->best_ptr = p;
+ arf->best_tile = 0;
+ better = true;
+ }
+ }
+ arf->recursive_mode = 0;
+ arf->cur_best_dist = (uint)-1;
+ arf->cur_best_depth = 0xff;
+
+ return better;
+}
+
+
+static bool AiEnumFollowRoad(TileIndex tile, AiRoadEnum *a, int track, uint length, byte *state)
+{
+ uint dist = DistanceManhattan(tile, a->dest);
+
+ if (dist <= a->best_dist) {
+ TileIndex tile2 = TILE_MASK(tile + TileOffsByDir(_dir_by_track[track]));
+
+ if (IsTileType(tile2, MP_STREET) &&
+ (_m[tile2].m5&0xF0) == 0) {
+ a->best_dist = dist;
+ a->best_tile = tile;
+ a->best_track = track;
+ }
+ }
+
+ return false;
+}
+
+static const uint16 _ai_road_table_and[4] = {
+ 0x1009,
+ 0x16,
+ 0x520,
+ 0x2A00,
+};
+
+static bool AiCheckRoadFinished(Player *p)
+{
+ AiRoadEnum are;
+ TileIndex tile;
+ int dir = p->ai.cur_dir_a;
+ uint32 bits;
+ int i;
+
+ are.dest = p->ai.cur_tile_b;
+ tile = TILE_MASK(p->ai.cur_tile_a + TileOffsByDir(dir));
+
+ bits = GetTileTrackStatus(tile, TRANSPORT_ROAD) & _ai_road_table_and[dir];
+ if (bits == 0) {
+ return false;
+ }
+
+ are.best_dist = (uint)-1;
+
+ for_each_bit(i, bits) {
+ FollowTrack(tile, 0x3000 | TRANSPORT_ROAD, _dir_by_track[i], (TPFEnumProc*)AiEnumFollowRoad, NULL, &are);
+ }
+
+ if (DistanceManhattan(tile, are.dest) <= are.best_dist)
+ return false;
+
+ if (are.best_dist == 0)
+ return true;
+
+ p->ai.cur_tile_a = are.best_tile;
+ p->ai.cur_dir_a = _dir_by_track[are.best_track];
+ return false;
+}
+
+
+static bool AiBuildRoadHelper(TileIndex tile, int flags, int type)
+{
+ static const byte _road_bits[] = {
+ 8+2,
+ 1+4,
+ 1+8,
+ 4+2,
+ 1+2,
+ 8+4,
+ };
+ return !CmdFailed(DoCommandByTile(tile, _road_bits[type], 0, flags, CMD_BUILD_ROAD));
+}
+
+static inline void AiCheckBuildRoadBridgeHere(AiRoadFinder *arf, TileIndex tile, const byte *p)
+{
+ TileIndex tile_new;
+ bool flag;
+
+ int dir2 = p[0] & 3;
+
+ FindLandscapeHeightByTile(&arf->ti, tile);
+ if (arf->ti.tileh == _dir_table_1[dir2] || (arf->ti.tileh==0 && arf->ti.z!=0)) {
+ tile_new = tile;
+ // Allow bridges directly over bottom tiles
+ flag = arf->ti.z == 0;
+ for(;;) {
+ if ((TileIndexDiff)tile_new < -TileOffsByDir(dir2)) return; // Wraping around map, no bridge possible!
+ tile_new = TILE_MASK(tile_new + TileOffsByDir(dir2));
+ FindLandscapeHeightByTile(&arf->ti, tile_new);
+ if (arf->ti.tileh != 0 || arf->ti.type == MP_CLEAR || arf->ti.type == MP_TREES) {
+ // Allow a bridge if either we have a tile that's water, rail or street,
+ // or if we found an up tile.
+ if (!flag) return;
+ break;
+ }
+ if (arf->ti.type != MP_WATER && arf->ti.type != MP_RAILWAY && arf->ti.type != MP_STREET)
+ return;
+ flag = true;
+ }
+
+ // Is building a (rail)bridge possible at this place (type doesn't matter)?
+ if (CmdFailed(DoCommandByTile(tile_new, tile, 0x8000, DC_AUTO, CMD_BUILD_BRIDGE)))
+ return;
+ AiBuildRoadRecursive(arf, tile_new, dir2);
+
+ // At the bottom depth, check if the new path is better than the old one.
+ if (arf->depth == 1) {
+ if (AiCheckRoadPathBetter(arf, p))
+ arf->bridge_end_tile = tile_new;
+ }
+ }
+}
+
+static inline void AiCheckBuildRoadTunnelHere(AiRoadFinder *arf, TileIndex tile, const byte *p)
+{
+ FindLandscapeHeightByTile(&arf->ti, tile);
+
+ if (arf->ti.tileh == _dir_table_2[p[0]&3] && arf->ti.z!=0) {
+ int32 cost = DoCommandByTile(tile, 0x200, 0, DC_AUTO, CMD_BUILD_TUNNEL);
+
+ if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) {
+ AiBuildRoadRecursive(arf, _build_tunnel_endtile, p[0]&3);
+ if (arf->depth == 1) {
+ AiCheckRoadPathBetter(arf, p);
+ }
+ }
+ }
+}
+
+
+
+static void AiBuildRoadRecursive(AiRoadFinder *arf, TileIndex tile, int dir)
+{
+ const byte *p;
+
+ tile = TILE_MASK(tile + TileOffsByDir(dir));
+
+ // Reached destination?
+ if (tile == arf->final_tile) {
+ if ((arf->final_dir^2) == dir) {
+ arf->recursive_mode = 2;
+ arf->cur_best_depth = arf->depth;
+ }
+ return;
+ }
+
+ // Depth too deep?
+ if (arf->depth >= 4) {
+ uint dist = DistanceMaxPlusManhattan(tile, arf->final_tile);
+ if (dist < arf->cur_best_dist) {
+ // Store the tile that is closest to the final position.
+ arf->cur_best_dist = dist;
+ arf->cur_best_tile = tile;
+ arf->cur_best_dir = dir;
+ arf->cur_best_depth = arf->depth;
+ }
+ return;
+ }
+
+ // Increase recursion depth
+ arf->depth++;
+
+ // Grab pointer to list of stuff that is possible to build
+ p = _ai_table_15[dir];
+
+ // Try to build a single rail in all directions.
+ FindLandscapeHeightByTile(&arf->ti, tile);
+ if (arf->ti.z == 0) {
+ p += 6;
+ } else {
+ do {
+ // Make sure that a road can be built here.
+ if (AiBuildRoadHelper(tile, DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, p[0])) {
+ AiBuildRoadRecursive(arf, tile, p[1]);
+ }
+
+ // At the bottom depth?
+ if (arf->depth == 1) {
+ AiCheckRoadPathBetter(arf, p);
+ }
+
+ p += 2;
+ } while (!(p[0]&0x80));
+ }
+
+ AiCheckBuildRoadBridgeHere(arf, tile, p);
+ AiCheckBuildRoadTunnelHere(arf, tile, p+1);
+
+ arf->depth--;
+}
+
+int sw;
+
+
+static void AiBuildRoadConstruct(Player *p)
+{
+ AiRoadFinder arf;
+ int i;
+ TileIndex tile;
+
+ // Reached destination?
+ if (AiCheckRoadFinished(p)) {
+ p->ai.state_mode = 255;
+ return;
+ }
+
+ // Setup recursive finder and call it.
+ arf.player = p;
+ arf.final_tile = p->ai.cur_tile_b;
+ arf.final_dir = p->ai.cur_dir_b;
+ arf.depth = 0;
+ arf.recursive_mode = 0;
+ arf.best_ptr = NULL;
+ arf.cur_best_dist = (uint)-1;
+ arf.cur_best_depth = 0xff;
+ arf.best_dist = (uint)-1;
+ arf.best_depth = 0xff;
+ arf.cur_best_tile = 0;
+ arf.best_tile = 0;
+ AiBuildRoadRecursive(&arf, p->ai.cur_tile_a, p->ai.cur_dir_a);
+
+ // Reached destination?
+ if (arf.recursive_mode == 2 && arf.cur_best_depth == 0) {
+ p->ai.state_mode = 255;
+ return;
+ }
+
+ // Didn't find anything to build?
+ if (arf.best_ptr == NULL) {
+ // Terraform some
+do_some_terraform:
+ for(i=0; i!=5; i++)
+ AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);
+
+ if (++p->ai.state_counter == 21) {
+ p->ai.state_mode = 1;
+
+ p->ai.cur_tile_a = TILE_MASK(p->ai.cur_tile_a + TileOffsByDir(p->ai.cur_dir_a));
+ p->ai.cur_dir_a ^= 2;
+ p->ai.state_counter = 0;
+ }
+ return;
+ }
+
+ tile = TILE_MASK(p->ai.cur_tile_a + TileOffsByDir(p->ai.cur_dir_a));
+
+ if (arf.best_ptr[0]&0x80) {
+ int i;
+ int32 bridge_len;
+ p->ai.cur_tile_a = arf.bridge_end_tile;
+ bridge_len = GetBridgeLength(tile, p->ai.cur_tile_a); // tile
+
+ /* Figure out what (road)bridge type to build
+ start with best bridge, then go down to worse and worse bridges
+ unnecessary to check for worse bridge (i=0), since AI will always build that.
+ AI is so fucked up that fixing this small thing will probably not solve a thing
+ */
+ for(i = 10; i != 0; i--) {
+ if (CheckBridge_Stuff(i, bridge_len)) {
+ int32 cost = DoCommandByTile(tile, p->ai.cur_tile_a, i + (0x80 << 8), DC_AUTO, CMD_BUILD_BRIDGE);
+ if (!CmdFailed(cost) && cost < (p->player_money >> 5))
+ break;
+ }
+ }
+
+ // Build it
+ DoCommandByTile(tile, p->ai.cur_tile_a, i + (0x80 << 8), DC_AUTO | DC_EXEC, CMD_BUILD_BRIDGE);
+
+ p->ai.state_counter = 0;
+ } else if (arf.best_ptr[0]&0x40) {
+ // tunnel
+ DoCommandByTile(tile, 0x200, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
+ p->ai.cur_tile_a = _build_tunnel_endtile;
+ p->ai.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;
+
+ p->ai.cur_dir_a = arf.best_ptr[1];
+ p->ai.cur_tile_a = tile;
+ p->ai.state_counter = 0;
+ }
+
+ if (arf.best_tile != 0) {
+ for(i=0; i!=2; i++)
+ AiDoTerraformLand(arf.best_tile, arf.best_dir, 3, 0);
+ }
+}
+
+
+static void AiBuildRoad(Player *p)
+{
+ int i;
+
+ if (p->ai.state_mode < 1) {
+ // Construct mode, build new road.
+ AiBuildRoadConstruct(p);
+ } else if (p->ai.state_mode == 1) {
+ // Destruct mode, not implemented for roads.
+ p->ai.state_mode = 2;
+ p->ai.state_counter = 0;
+ } else if (p->ai.state_mode == 2) {
+
+ // Terraform some and then try building again.
+ for(i=0; i!=4; i++)
+ AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);
+
+ if (++p->ai.state_counter == 4) {
+ p->ai.state_counter = 0;
+ p->ai.state_mode = 0;
+ }
+ }
+}
+
+static TileIndex AiGetRoadBlockEdge(byte rule, TileIndex tile, int *dir)
+{
+ const AiDefaultBlockData *p = _road_default_block_data[rule]->data;
+ while (p->mode != 1) p++;
+ *dir = p->attr;
+ return TILE_ADD(tile, ToTileIndexDiff(p->tileoffs));
+}
+
+
+static void AiStateBuildRoad(Player *p)
+{
+ int num;
+ AiBuildRec *aib;
+ byte cmd;
+ TileIndex tile;
+ int dir;
+
+ // time out?
+ if (++p->ai.timeout_counter == 1388) {
+ p->ai.state = AIS_DELETE_ROAD_BLOCKS;
+ return;
+ }
+
+ // Currently building a road between two points?
+ if (p->ai.state_mode != 255) {
+ AiBuildRoad(p);
+
+ // Alternate between edges
+ swap_tile(&p->ai.start_tile_a, &p->ai.start_tile_b);
+ swap_tile(&p->ai.cur_tile_a, &p->ai.cur_tile_b);
+ swap_byte(&p->ai.start_dir_a, &p->ai.start_dir_b);
+ swap_byte(&p->ai.cur_dir_a, &p->ai.cur_dir_b);
+
+ sw ^= 1;
+ return;
+ }
+
+ // Now, find two new points to build between
+ num = p->ai.num_build_rec;
+ aib = &p->ai.src;
+
+ for(;;) {
+ cmd = aib->buildcmd_a;
+ aib->buildcmd_a = 255;
+ if (cmd != 255) break;
+
+ aib++;
+ if (--num == 0) {
+ p->ai.state = AIS_BUILD_ROAD_VEHICLES;
+ return;
+ }
+ }
+
+ // Find first edge to build from.
+ tile = AiGetRoadBlockEdge(aib->cur_building_rule, aib->use_tile, &dir);
+ p->ai.start_tile_a = tile;
+ p->ai.cur_tile_a = tile;
+ p->ai.start_dir_a = dir;
+ p->ai.cur_dir_a = dir;
+
+ // Find second edge to build to
+ aib = (&p->ai.src) + (cmd&0xF);
+ tile = AiGetRoadBlockEdge(aib->cur_building_rule, aib->use_tile, &dir);
+ p->ai.start_tile_b = tile;
+ p->ai.cur_tile_b = tile;
+ p->ai.start_dir_b = dir;
+ p->ai.cur_dir_b = dir;
+
+ // And setup state.
+ p->ai.state_mode = 2;
+ p->ai.state_counter = 0;
+ p->ai.banned_tile_count = 0;
+}
+
+static int AiGetStationIdFromRoadBlock(TileIndex tile, int id)
+{
+ const AiDefaultBlockData *p = _road_default_block_data[id]->data;
+ while (p->mode != 1) p++;
+ return _m[TILE_ADD(tile, ToTileIndexDiff(p->tileoffs))].m2;
+}
+
+static void AiStateBuildRoadVehicles(Player *p)
+{
+ const AiDefaultBlockData *ptr;
+ TileIndex tile;
+ uint loco_id;
+ int veh, i;
+
+ ptr = _road_default_block_data[p->ai.src.cur_building_rule]->data;
+ for(;ptr->mode != 0;ptr++) {}
+ tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));
+
+ veh = AiChooseRoadVehToBuild(p->ai.cargo_type, p->player_money, tile);
+ if (veh == -1) {
+ p->ai.state = AIS_0;
+ return;
+ }
+
+ if (CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_ROAD_VEH))) return;
+
+ loco_id = _new_roadveh_id;
+
+ for(i=0; p->ai.order_list_blocks[i] != 0xFF; i++) {
+ AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i];
+ bool is_pass = (p->ai.cargo_type == CT_PASSENGERS ||
+ p->ai.cargo_type == CT_MAIL ||
+ (_opt.landscape==LT_NORMAL && p->ai.cargo_type == CT_VALUABLES));
+ Order order;
+
+ order.type = OT_GOTO_STATION;
+ order.flags = 0;
+ order.station = AiGetStationIdFromRoadBlock(aib->use_tile, aib->cur_building_rule);
+
+ if (!is_pass && i == 1) order.flags |= OF_UNLOAD;
+ if (p->ai.num_want_fullload != 0 && (is_pass || i == 0))
+ order.flags |= OF_FULL_LOAD;
+
+ DoCommandByTile(0, loco_id + (i << 16), PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
+ }
+
+ DoCommandByTile(0, loco_id, 0, DC_EXEC, CMD_START_STOP_ROADVEH);
+
+ DoCommandByTile(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
+
+ if (p->ai.num_want_fullload != 0)
+ p->ai.num_want_fullload--;
+
+ if (--p->ai.num_loco_to_build == 0) {
+ p->ai.state = AIS_0;
+ }
+}
+
+static void AiStateDeleteRoadBlocks(Player *p)
+{
+ int num;
+ AiBuildRec *aib;
+ const AiDefaultBlockData *b;
+
+ num = p->ai.num_build_rec;
+ aib = &p->ai.src;
+ do {
+ if (aib->cur_building_rule != 255) {
+ b = _road_default_block_data[aib->cur_building_rule]->data;
+ while (b->mode != 4) {
+ if (b->mode <= 1) {
+ DoCommandByTile(TILE_ADD(aib->use_tile, ToTileIndexDiff(b->tileoffs)), 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
+ }
+ b++;
+ }
+ }
+ } while (++aib,--num);
+
+ p->ai.state = AIS_0;
+}
+
+static bool AiCheckIfHangar(Station *st)
+{
+ TileIndex tile = st->airport_tile;
+
+ // HANGAR of airports
+ // 0x20 - hangar large airport (32)
+ // 0x41 - hangar small airport (65)
+ return (_m[tile].m5 == 32 || _m[tile].m5 == 65);
+}
+
+static void AiStateAirportStuff(Player *p)
+{
+ Station *st;
+ byte acc_planes;
+ int i;
+ AiBuildRec *aib;
+ byte rule;
+
+ // Here we look for an airport we could use instead of building a new
+ // one. If we find such an aiport for any waypoint,
+ // AiStateBuildDefaultAirportBlocks() will kindly skip that one when
+ // building the waypoints.
+
+ i = 0;
+ do {
+ // 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 = &p->ai.src + i;
+
+ FOR_ALL_STATIONS(st) {
+ // Dismiss ghost stations.
+ if (st->xy == 0)
+ continue;
+
+ // 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;
+
+ acc_planes = GetAirport(st->airport_type)->acc_planes;
+
+ // Dismiss heliports, unless we are checking an oilrig.
+ if (acc_planes == HELICOPTERS_ONLY && !(p->ai.build_kind == 1 && i == 1))
+ continue;
+
+ // Dismiss country airports if we are doing the other
+ // endpoint of an oilrig route.
+ if (acc_planes == AIRCRAFT_ONLY && (p->ai.build_kind == 1 && i == 0))
+ continue;
+
+ // Dismiss airports too far away.
+ if (DistanceMax(st->airport_tile, aib->spec_tile) > aib->rand_rng)
+ continue;
+
+ // It's ideal airport, let's take it!
+
+ /* XXX: This part is utterly broken - rule should
+ * contain number of the rule appropriate for the
+ * airport type (country, town, ...), see
+ * _airport_default_block_data (rule is just an index
+ * in this array). But the only difference between the
+ * currently existing two rules (rule 0 - town and rule
+ * 1 - country) is the attr field which is used only
+ * when building new airports - and that's irrelevant
+ * for us. So using just about any rule will suffice
+ * here for now (some of the new airport types would be
+ * broken because they will probably need different
+ * tileoff values etc), no matter that
+ * AiCheckIfHangar() makes no sense. --pasky */
+ if (acc_planes == HELICOPTERS_ONLY) {
+ /* Heliports should have maybe own rulesets but
+ * OTOH we don't want AI to pick them up when
+ * looking for a suitable airport type to build.
+ * So any of rules 0 or 1 would do for now. The
+ * original rule number was 2 but that's a bug
+ * because we have no such rule. */
+ rule = 1;
+ } else {
+ rule = AiCheckIfHangar(st);
+ }
+
+ aib->cur_building_rule = rule;
+ aib->use_tile = st->airport_tile;
+ break;
+ }
+ } while (++i != p->ai.num_build_rec);
+
+ p->ai.state = AIS_BUILD_DEFAULT_AIRPORT_BLOCKS;
+ p->ai.state_mode = 255;
+ p->ai.state_counter = 0;
+}
+
+static int32 AiDoBuildDefaultAirportBlock(TileIndex tile, const AiDefaultBlockData *p, byte flag)
+{
+ int32 total_cost = 0, ret;
+
+ for(;p->mode == 0;p++) {
+ if (!HASBIT(_avail_aircraft, p->attr))
+ return CMD_ERROR;
+ ret = DoCommandByTile(TILE_MASK(tile + ToTileIndexDiff(p->tileoffs)), p->attr,0,flag | DC_AUTO | DC_NO_WATER,CMD_BUILD_AIRPORT);
+ if (CmdFailed(ret)) return CMD_ERROR;
+ total_cost += ret;
+ }
+
+ return total_cost;
+}
+
+static bool AiCheckAirportResources(TileIndex tile, const AiDefaultBlockData *p, byte cargo)
+{
+ uint values[NUM_CARGO];
+ int w,h;
+ int rad;
+
+ if (_patches.modified_catchment) {
+ rad = CA_AIR_LARGE; //I Have NFI what airport the
+ } else { //AI is going to build here
+ rad = 4;
+ }
+
+ for(;p->mode==0;p++) {
+ TileIndex tile2 = TILE_ADD(tile, ToTileIndexDiff(p->tileoffs));
+
+ w = _airport_size_x[p->attr];
+ h = _airport_size_y[p->attr];
+ if (cargo & 0x80) {
+ GetProductionAroundTiles(values, tile2, w, h, rad);
+ return values[cargo & 0x7F] != 0;
+ } else {
+ GetAcceptanceAroundTiles(values, tile2, w, h, rad);
+ return values[cargo] >= 8;
+ }
+ }
+ return true;
+}
+
+static int AiFindBestDefaultAirportBlock(TileIndex tile, byte cargo, byte heli, int32 *cost)
+{
+ int i;
+ const AiDefaultBlockData *p;
+ for(i=0; (p = _airport_default_block_data[i]) != NULL; i++) {
+ // If we are doing a helicopter service, avoid building
+ // airports where they can't land.
+ if (heli && GetAirport(p->attr)->acc_planes == AIRCRAFT_ONLY)
+ continue;
+
+ *cost = AiDoBuildDefaultAirportBlock(tile, p, 0);
+ if (*cost != CMD_ERROR && AiCheckAirportResources(tile, p, cargo))
+ return i;
+ }
+ return -1;
+}
+
+static void AiStateBuildDefaultAirportBlocks(Player *p)
+{
+ int i, j;
+ AiBuildRec *aib;
+ int rule;
+ int32 cost;
+
+ // time out?
+ if (++p->ai.timeout_counter == 1388) {
+ p->ai.state = AIS_0;
+ return;
+ }
+
+ // do the following 8 times
+ i = 8;
+ do {
+ // check if we can build the default
+ aib = &p->ai.src;
+ j = p->ai.num_build_rec;
+ do {
+ // this item has already been built?
+ if (aib->cur_building_rule != 255)
+ continue;
+
+ // adjust the coordinate randomly,
+ // to make sure that we find a position.
+ 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, p->ai.build_kind, &cost);
+
+#if 0
+ if (!IsTileType(aib->use_tile, MP_STREET) &&
+ !IsTileType(aib->use_tile, MP_RAILWAY) &&
+ !IsTileType(aib->use_tile, MP_STATION)
+ ) {
+
+ _m[aib->use_tile].type_height = 0xa1;
+ _m[aib->use_tile].m5 = 0x80;
+ MarkTileDirtyByTile(aib->use_tile);
+ }
+#endif
+// SetRedErrorSquare(aib->use_tile);
+
+ if (rule == -1) {
+ // cannot build, terraform after a while
+ if (p->ai.state_counter >= 600) {
+ AiDoTerraformLand(aib->use_tile, Random()&3, 3, (int8)p->ai.state_mode);
+ }
+ // also try the other terraform direction
+ if (++p->ai.state_counter >= 1000) {
+ p->ai.state_counter = 0;
+ p->ai.state_mode = -p->ai.state_mode;
+ }
+ } else if (CheckPlayerHasMoney(cost) && AiCheckBlockDistances(p,aib->use_tile)) {
+ // player has money, build it.
+ int32 r;
+
+ aib->cur_building_rule = rule;
+
+ r = AiDoBuildDefaultAirportBlock(
+ aib->use_tile,
+ _airport_default_block_data[rule],
+ DC_EXEC | DC_NO_TOWN_RATING
+ );
+ assert(r != CMD_ERROR);
+ }
+ } while (++aib,--j);
+ } while (--i);
+
+ // check if we're done with all of them
+ aib = &p->ai.src;
+ j = p->ai.num_build_rec;
+ do {
+ if (aib->cur_building_rule == 255)
+ return;
+ } while (++aib,--j);
+
+ // yep, all are done. switch state.
+ p->ai.state = AIS_BUILD_AIRCRAFT_VEHICLES;
+}
+
+static int AiGetStationIdFromAircraftBlock(TileIndex tile, int id)
+{
+ const AiDefaultBlockData *p = _airport_default_block_data[id];
+ while (p->mode != 1) p++;
+ return _m[TILE_ADD(tile, ToTileIndexDiff(p->tileoffs))].m2;
+}
+
+static void AiStateBuildAircraftVehicles(Player *p)
+{
+ const AiDefaultBlockData *ptr;
+ TileIndex tile;
+ int veh;
+ int i;
+ uint loco_id;
+
+ ptr = _airport_default_block_data[p->ai.src.cur_building_rule];
+ for(;ptr->mode!=0;ptr++) {}
+
+ tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));
+
+ veh = AiChooseAircraftToBuild(p->player_money, p->ai.build_kind!=0 ? 1 : 0);
+ if (veh == -1) {
+ return;
+ }
+
+ if (CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_AIRCRAFT))) return;
+ loco_id = _new_aircraft_id;
+
+ for(i=0; p->ai.order_list_blocks[i] != 0xFF; i++) {
+ AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i];
+ bool is_pass = (p->ai.cargo_type == CT_PASSENGERS || p->ai.cargo_type == CT_MAIL);
+ Order order;
+
+ order.type = OT_GOTO_STATION;
+ order.flags = 0;
+ order.station = AiGetStationIdFromAircraftBlock(aib->use_tile, aib->cur_building_rule);
+
+ if (!is_pass && i == 1) order.flags |= OF_UNLOAD;
+ if (p->ai.num_want_fullload != 0 && (is_pass || i == 0))
+ order.flags |= OF_FULL_LOAD;
+
+ DoCommandByTile(0, loco_id + (i << 16), PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
+ }
+
+ DoCommandByTile(0, loco_id, 0, DC_EXEC, CMD_START_STOP_AIRCRAFT);
+
+ DoCommandByTile(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
+
+ if (p->ai.num_want_fullload != 0)
+ p->ai.num_want_fullload--;
+
+ if (--p->ai.num_loco_to_build == 0) {
+ p->ai.state = AIS_0;
+ }
+}
+
+static void AiStateCheckShipStuff(Player *p)
+{
+ // XXX
+ error("!AiStateCheckShipStuff");
+}
+
+static void AiStateBuildDefaultShipBlocks(Player *p)
+{
+ // XXX
+ error("!AiStateBuildDefaultShipBlocks");
+}
+
+static void AiStateDoShipStuff(Player *p)
+{
+ // XXX
+ error("!AiStateDoShipStuff");
+}
+
+static void AiStateSellVeh(Player *p)
+{
+ Vehicle *v = p->ai.cur_veh;
+
+ if (v->owner == _current_player) {
+ if (v->type == VEH_Train) {
+
+ if (!IsTileDepotType(v->tile, TRANSPORT_RAIL) || v->u.rail.track != 0x80 || !(v->vehstatus&VS_STOPPED)) {
+ if (v->current_order.type != OT_GOTO_DEPOT)
+ DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_TRAIN_GOTO_DEPOT);
+ goto going_to_depot;
+ }
+
+ // Sell whole train
+ DoCommandByTile(v->tile, v->index, 1, DC_EXEC, CMD_SELL_RAIL_WAGON);
+
+ } else if (v->type == VEH_Road) {
+ if (!IsTileDepotType(v->tile, TRANSPORT_ROAD) || v->u.road.state != 254 || !(v->vehstatus&VS_STOPPED)) {
+ if (v->current_order.type != OT_GOTO_DEPOT)
+ DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SEND_ROADVEH_TO_DEPOT);
+ goto going_to_depot;
+ }
+
+ DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH);
+ } else if (v->type == VEH_Aircraft) {
+ if (!IsAircraftHangarTile(v->tile) && !(v->vehstatus&VS_STOPPED)) {
+ if (v->current_order.type != OT_GOTO_DEPOT)
+ DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SEND_AIRCRAFT_TO_HANGAR);
+ goto going_to_depot;
+ }
+
+ DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_AIRCRAFT);
+ } else if (v->type == VEH_Ship) {
+ // XXX: not implemented
+ error("!v->type == VEH_Ship");
+ }
+ }
+
+ goto return_to_loop;
+going_to_depot:;
+ if (++p->ai.state_counter <= 832)
+ return;
+
+ if (v->current_order.type == OT_GOTO_DEPOT) {
+ v->current_order.type = OT_DUMMY;
+ v->current_order.flags = 0;
+ InvalidateWindow(WC_VEHICLE_VIEW, v->index);
+ }
+return_to_loop:;
+ p->ai.state = AIS_VEH_LOOP;
+}
+
+static void AiStateRemoveStation(Player *p)
+{
+ // Remove stations that aren't in use by any vehicle
+ byte *in_use;
+ const byte *used;
+ const Order *ord;
+ const Station *st;
+ TileIndex tile;
+
+ // Go to this state when we're done.
+ p->ai.state = AIS_1;
+
+ // Get a list of all stations that are in use by a vehicle
+ in_use = malloc(GetStationPoolSize());
+ memset(in_use, 0, GetStationPoolSize());
+ FOR_ALL_ORDERS(ord) {
+ if (ord->type == OT_GOTO_STATION)
+ in_use[ord->station] = 1;
+ }
+
+ // Go through all stations and delete those that aren't in use
+ used = in_use;
+ FOR_ALL_STATIONS(st) {
+ if (st->xy != 0 && st->owner == _current_player && !*used &&
+ ( (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 ||
+ (tile = st->dock_tile) != 0 ||
+ (tile = st->airport_tile) != 0)) {
+ DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
+ }
+ used++;
+ }
+
+ free(in_use);
+}
+
+static void AiRemovePlayerRailOrRoad(Player *p, TileIndex tile)
+{
+ byte m5;
+
+ if (IsTileType(tile, MP_RAILWAY)) {
+ if (!IsTileOwner(tile, _current_player)) return;
+
+ m5 = _m[tile].m5;
+ if ((m5&~0x3) != 0xC0) {
+is_rail_crossing:;
+ m5 = GetRailTrackStatus(tile);
+
+ if (m5 == 0xC || m5 == 0x30)
+ return;
+
+ if (m5&0x25) {
+pos_0:
+ if (!(GetRailTrackStatus(TILE_MASK(tile - TileDiffXY(1, 0))) & 0x19)) {
+ p->ai.cur_dir_a = 0;
+ p->ai.cur_tile_a = tile;
+ p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
+ return;
+ }
+ }
+
+ if (m5&0x2A) {
+pos_1:
+ if (!(GetRailTrackStatus(TILE_MASK(tile + TileDiffXY(0, 1))) & 0x16)) {
+ p->ai.cur_dir_a = 1;
+ p->ai.cur_tile_a = tile;
+ p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
+ return;
+ }
+ }
+
+ if (m5&0x19) {
+pos_2:
+ if (!(GetRailTrackStatus(TILE_MASK(tile + TileDiffXY(1, 0))) & 0x25)) {
+ p->ai.cur_dir_a = 2;
+ p->ai.cur_tile_a = tile;
+ p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
+ return;
+ }
+ }
+
+ if (m5&0x16) {
+pos_3:
+ if (!(GetRailTrackStatus(TILE_MASK(tile - TileDiffXY(0, 1))) & 0x2A)) {
+ p->ai.cur_dir_a = 3;
+ p->ai.cur_tile_a = tile;
+ p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
+ return;
+ }
+ }
+ } else {
+ static const byte _depot_bits[] = {0x19,0x16,0x25,0x2A};
+
+ m5 &= 3;
+ if (GetRailTrackStatus(tile + TileOffsByDir(m5)) & _depot_bits[m5])
+ return;
+
+ DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
+ }
+ } else if (IsTileType(tile, MP_STREET)) {
+ if (!IsTileOwner(tile, _current_player)) return;
+
+ if (IsLevelCrossing(tile))
+ goto is_rail_crossing;
+
+ if ( (_m[tile].m5&0xF0) == 0x20) {
+ int dir;
+
+ // Check if there are any stations around.
+ if (IsTileType(tile + TileDiffXY(-1, 0), MP_STATION) &&
+ IsTileOwner(tile + TileDiffXY(-1, 0), _current_player))
+ return;
+
+ if (IsTileType(tile + TileDiffXY(1, 0), MP_STATION) &&
+ IsTileOwner(tile + TileDiffXY(1, 0), _current_player))
+ return;
+
+ if (IsTileType(tile + TileDiffXY(0, -1), MP_STATION) &&
+ IsTileOwner(tile + TileDiffXY(0, -1), _current_player))
+ return;
+
+ if (IsTileType(tile + TileDiffXY(0, 1), MP_STATION) &&
+ IsTileOwner(tile + TileDiffXY(0, 1), _current_player))
+ return;
+
+ dir = _m[tile].m5 & 3;
+
+ DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
+ DoCommandByTile(
+ TILE_MASK(tile + TileOffsByDir(dir)),
+ 8 >> (dir ^ 2),
+ 0,
+ DC_EXEC,
+ CMD_REMOVE_ROAD);
+ }
+ } else if (IsTileType(tile, MP_TUNNELBRIDGE)) {
+ byte b;
+
+ if (!IsTileOwner(tile, _current_player) || (_m[tile].m5 & 0xC6) != 0x80)
+ return;
+
+ m5 = 0;
+
+ b = _m[tile].m5 & 0x21;
+ if (b == 0) goto pos_0;
+ if (b == 1) goto pos_3;
+ if (b == 0x20) goto pos_2;
+ goto pos_1;
+ }
+}
+
+static void AiStateRemoveTrack(Player *p)
+{
+ /* Was 1000 for standard 8x8 maps. */
+ int num = MapSizeX() * 4;
+
+ do {
+ TileIndex tile = ++p->ai.state_counter;
+
+ // Iterated all tiles?
+ if (tile >= MapSize()) {
+ p->ai.state = AIS_REMOVE_STATION;
+ return;
+ }
+
+ // Remove player stuff in that tile
+ AiRemovePlayerRailOrRoad(p, tile);
+ if (p->ai.state != AIS_REMOVE_TRACK)
+ return;
+ } while (--num);
+}
+
+static void AiStateRemoveSingleRailTile(Player *p)
+{
+ // Remove until we can't remove more.
+ if (!AiRemoveTileAndGoForward(p)) {
+ p->ai.state = AIS_REMOVE_TRACK;
+ }
+}
+
+static AiStateAction * const _ai_actions[] = {
+ AiCase0,
+ AiCase1,
+ AiStateVehLoop,
+ AiStateCheckReplaceVehicle,
+ AiStateDoReplaceVehicle,
+ AiStateWantNewRoute,
+
+ AiStateBuildDefaultRailBlocks,
+ AiStateBuildRail,
+ AiStateBuildRailVeh,
+ AiStateDeleteRailBlocks,
+
+ AiStateBuildDefaultRoadBlocks,
+ AiStateBuildRoad,
+ AiStateBuildRoadVehicles,
+ AiStateDeleteRoadBlocks,
+
+ AiStateAirportStuff,
+ AiStateBuildDefaultAirportBlocks,
+ AiStateBuildAircraftVehicles,
+
+ AiStateCheckShipStuff,
+ AiStateBuildDefaultShipBlocks,
+ AiStateDoShipStuff,
+
+ AiStateSellVeh,
+ AiStateRemoveStation,
+ AiStateRemoveTrack,
+
+ AiStateRemoveSingleRailTile
+};
+
+extern void ShowBuyCompanyDialog(uint player);
+
+static void AiHandleTakeover(Player *p)
+{
+ if (p->bankrupt_timeout != 0) {
+ if ((p->bankrupt_timeout-=8) > 0)
+ return;
+ p->bankrupt_timeout = 0;
+ DeleteWindowById(WC_BUY_COMPANY, _current_player);
+ if (_current_player == _local_player) {
+ AskExitToGameMenu();
+ return;
+ }
+ if (IS_HUMAN_PLAYER(_current_player))
+ return;
+ }
+
+ if (p->bankrupt_asked == 255)
+ return;
+
+ {
+ uint asked = p->bankrupt_asked;
+ Player *pp, *best_pl = NULL;
+ int32 best_val = -1;
+ uint old_p;
+
+ // Ask the guy with the highest performance hist.
+ FOR_ALL_PLAYERS(pp) {
+ if (pp->is_active &&
+ !(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;
+ }
+ asked>>=1;
+ }
+
+ // Asked all players?
+ if (best_val == -1) {
+ p->bankrupt_asked = 255;
+ return;
+ }
+
+ SETBIT(p->bankrupt_asked, best_pl->index);
+
+ if (best_pl->index == _local_player) {
+ p->bankrupt_timeout = 4440;
+ ShowBuyCompanyDialog(_current_player);
+ return;
+ }
+ if (IS_HUMAN_PLAYER(best_pl->index))
+ return;
+
+ // Too little money for computer to buy it?
+ if (best_pl->player_money >> 1 >= p->bankrupt_value) {
+ // Computer wants to buy it.
+ old_p = _current_player;
+ _current_player = p->index;
+ DoCommandByTile(0, old_p, 0, DC_EXEC, CMD_BUY_COMPANY);
+ _current_player = old_p;
+ }
+ }
+}
+
+static void AiAdjustLoan(Player *p)
+{
+ int32 base = AiGetBasePrice(p);
+
+ if (p->player_money > base * 1400) {
+ // Decrease loan
+ if (p->current_loan != 0) {
+ DoCommandByTile(0, 0, 0, DC_EXEC, CMD_DECREASE_LOAN);
+ }
+ } else if (p->player_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) {
+ DoCommandByTile(0, 0, 0, DC_EXEC, CMD_INCREASE_LOAN);
+ }
+ }
+}
+
+static void AiBuildCompanyHQ(Player *p)
+{
+ TileIndex tile;
+
+ if (p->location_of_house == 0 &&
+ p->last_build_coordinate != 0) {
+ tile = AdjustTileCoordRandomly(p->last_build_coordinate, 8);
+ DoCommandByTile(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ);
+ }
+}
+
+
+void AiDoGameLoop(Player *p)
+{
+ _cur_ai_player = p;
+
+ if (p->bankrupt_asked != 0) {
+ AiHandleTakeover(p);
+ return;
+ }
+
+ // Ugly hack to make sure the service interval of the AI is good, not looking
+ // to the patch-setting
+ // Also, it takes into account the setting if the service-interval is in days
+ // or in %
+ _ai_service_interval = _patches.servint_ispercent?80:180;
+
+ if (IS_HUMAN_PLAYER(_current_player))
+ return;
+
+ AiAdjustLoan(p);
+ AiBuildCompanyHQ(p);
+
+ if (_opt.diff.competitor_speed == 4) {
+ /* ultraspeed */
+ _ai_actions[p->ai.state](p);
+ if (p->bankrupt_asked != 0)
+ return;
+ } else if (_opt.diff.competitor_speed != 3) {
+ p->ai.tick++;
+ if (!(p->ai.tick&1))
+ return;
+ if (_opt.diff.competitor_speed != 2) {
+ if (!(p->ai.tick&2))
+ return;
+ if (_opt.diff.competitor_speed == 0) {
+ if (!(p->ai.tick&4))
+ return;
+ }
+ }
+ }
+#if 0
+ {
+ static byte old_state = 99;
+ static bool hasdots = false;
+ char *_ai_state_names[]={
+ "AiCase0",
+ "AiCase1",
+ "AiStateVehLoop",
+ "AiStateCheckReplaceVehicle",
+ "AiStateDoReplaceVehicle",
+ "AiStateWantNewRoute",
+ "AiStateBuildDefaultRailBlocks",
+ "AiStateBuildRail",
+ "AiStateBuildRailVeh",
+ "AiStateDeleteRailBlocks",
+ "AiStateBuildDefaultRoadBlocks",
+ "AiStateBuildRoad",
+ "AiStateBuildRoadVehicles",
+ "AiStateDeleteRoadBlocks",
+ "AiStateAirportStuff",
+ "AiStateBuildDefaultAirportBlocks",
+ "AiStateBuildAircraftVehicles",
+ "AiStateCheckShipStuff",
+ "AiStateBuildDefaultShipBlocks",
+ "AiStateDoShipStuff",
+ "AiStateSellVeh",
+ "AiStateRemoveStation",
+ "AiStateRemoveTrack",
+ "AiStateRemoveSingleRailTile"
+ };
+
+ if (p->ai.state != old_state) {
+ if (hasdots)
+ printf("\n");
+ hasdots=false;
+ printf("AiState: %s\n", _ai_state_names[old_state=p->ai.state]);
+ } else {
+ printf(".");
+ hasdots=true;
+ }
+ }
+#endif
+
+ _ai_actions[p->ai.state](p);
+}
diff --git a/ai/trolly/build.c b/ai/trolly/build.c
new file mode 100644
index 000000000..80f0fdf1b
--- /dev/null
+++ b/ai/trolly/build.c
@@ -0,0 +1,273 @@
+/* $Id$ */
+
+#include "../../stdafx.h"
+#include "../../openttd.h"
+#include "../../debug.h"
+#include "../../functions.h"
+#include "../../map.h"
+#include "../../tile.h"
+#include "../../command.h"
+#include "trolly.h"
+#include "../../engine.h"
+#include "../../station.h"
+#include "../../variables.h"
+
+// Build HQ
+// Params:
+// tile : tile where HQ is going to be build
+bool AiNew_Build_CompanyHQ(Player *p, TileIndex tile)
+{
+ if (CmdFailed(DoCommandByTile(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ)))
+ return false;
+ DoCommandByTile(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ);
+ return true;
+}
+
+
+// Build station
+// Params:
+// type : AI_TRAIN/AI_BUS/AI_TRUCK : indicates the type of station
+// tile : tile where station is going to be build
+// length : in case of AI_TRAIN: length of station
+// 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)
+int AiNew_Build_Station(Player *p, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag)
+{
+ if (type == AI_TRAIN)
+ return DoCommandByTile(tile, direction + (numtracks << 8) + (length << 16), 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_RAILROAD_STATION);
+
+ if (type == AI_BUS)
+ return DoCommandByTile(tile, direction, RS_BUS, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_STOP);
+
+ return DoCommandByTile(tile, direction, RS_TRUCK, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_STOP);
+}
+
+
+// Builds a brdige. The second best out of the ones available for this player
+// Params:
+// tile_a : starting point
+// tile_b : end point
+// flag : flag passed to DoCommand
+int AiNew_Build_Bridge(Player *p, TileIndex tile_a, TileIndex tile_b, byte flag)
+{
+ int bridge_type, bridge_len, type, type2;
+
+ // Find a good bridgetype (the best money can buy)
+ bridge_len = GetBridgeLength(tile_a, tile_b);
+ type = type2 = 0;
+ for (bridge_type = MAX_BRIDGES-1; bridge_type >= 0; bridge_type--) {
+ if (CheckBridge_Stuff(bridge_type, bridge_len)) {
+ type2 = type;
+ type = bridge_type;
+ // We found two bridges, exit
+ if (type2 != 0) break;
+ }
+ }
+ // There is only one bridge that can be build..
+ if (type2 == 0 && type != 0) type2 = type;
+
+ // Now, simply, build the bridge!
+ if (p->ainew.tbt == AI_TRAIN)
+ return DoCommandByTile(tile_a, tile_b, (0<<8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
+
+ return DoCommandByTile(tile_a, tile_b, (0x80 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
+}
+
+
+// Build the route part by part
+// Basicly what this function do, is build that amount of parts of the route
+// that go in the same direction. It sets 'part' to the last part of the route builded.
+// The return value is the cost for the builded parts
+//
+// Params:
+// PathFinderInfo : Pointer to the PathFinderInfo used for AiPathFinder
+// part : Which part we need to build
+//
+// TODO: skip already builded road-pieces (e.g.: cityroad)
+int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte flag)
+{
+ int part = PathFinderInfo->position;
+ byte *route_extra = PathFinderInfo->route_extra;
+ TileIndex *route = PathFinderInfo->route;
+ int dir;
+ int old_dir = -1;
+ int cost = 0;
+ int res;
+ // We need to calculate the direction with the parent of the parent.. so we skip
+ // the first pieces and the last piece
+ if (part < 1) part = 1;
+ // When we are done, stop it
+ if (part >= PathFinderInfo->route_length - 1) { PathFinderInfo->position = -2; return 0; }
+
+
+ if (PathFinderInfo->rail_or_road) {
+ // Tunnel code
+ if ((AI_PATHFINDER_FLAG_TUNNEL & route_extra[part]) != 0) {
+ cost += DoCommandByTile(route[part], 0, 0, flag, CMD_BUILD_TUNNEL);
+ PathFinderInfo->position++;
+ // TODO: problems!
+ if (CmdFailed(cost)) {
+ DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be build!");
+ return 0;
+ }
+ return cost;
+ }
+ // Bridge code
+ if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
+ cost += AiNew_Build_Bridge(p, route[part], route[part-1], flag);
+ PathFinderInfo->position++;
+ // TODO: problems!
+ if (CmdFailed(cost)) {
+ DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be build!");
+ return 0;
+ }
+ return cost;
+ }
+
+ // Build normal rail
+ // Keep it doing till we go an other way
+ if (route_extra[part-1] == 0 && route_extra[part] == 0) {
+ while (route_extra[part] == 0) {
+ // Get the current direction
+ dir = AiNew_GetRailDirection(route[part-1], route[part], route[part+1]);
+ // Is it the same as the last one?
+ if (old_dir != -1 && old_dir != dir) break;
+ old_dir = dir;
+ // Build the tile
+ res = DoCommandByTile(route[part], 0, dir, flag, CMD_BUILD_SINGLE_RAIL);
+ if (CmdFailed(res)) {
+ // Problem.. let's just abort it all!
+ p->ainew.state = AI_STATE_NOTHING;
+ return 0;
+ }
+ cost += res;
+ // Go to the next tile
+ part++;
+ // Check if it is still in range..
+ if (part >= PathFinderInfo->route_length - 1) break;
+ }
+ part--;
+ }
+ // We want to return the last position, so we go back one
+ PathFinderInfo->position = part;
+ } else {
+ // Tunnel code
+ if ((AI_PATHFINDER_FLAG_TUNNEL & route_extra[part]) != 0) {
+ cost += DoCommandByTile(route[part], 0x200, 0, flag, CMD_BUILD_TUNNEL);
+ PathFinderInfo->position++;
+ // TODO: problems!
+ if (CmdFailed(cost)) {
+ DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be build!");
+ return 0;
+ }
+ return cost;
+ }
+ // Bridge code
+ if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
+ cost += AiNew_Build_Bridge(p, route[part], route[part+1], flag);
+ PathFinderInfo->position++;
+ // TODO: problems!
+ if (CmdFailed(cost)) {
+ DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be build!");
+ return 0;
+ }
+ return cost;
+ }
+
+ // Build normal road
+ // Keep it doing till we go an other way
+ // EnsureNoVehicle makes sure we don't build on a tile where a vehicle is. This way
+ // it will wait till the vehicle is gone..
+ if (route_extra[part-1] == 0 && route_extra[part] == 0 && (flag != DC_EXEC || EnsureNoVehicle(route[part]))) {
+ while (route_extra[part] == 0 && (flag != DC_EXEC || EnsureNoVehicle(route[part]))) {
+ // Get the current direction
+ dir = AiNew_GetRoadDirection(route[part-1], route[part], route[part+1]);
+ // Is it the same as the last one?
+ if (old_dir != -1 && old_dir != dir) break;
+ old_dir = dir;
+ // There is already some road, and it is a bridge.. don't build!!!
+ if (!IsTileType(route[part], MP_TUNNELBRIDGE)) {
+ // Build the tile
+ res = DoCommandByTile(route[part], dir, 0, flag | DC_NO_WATER, CMD_BUILD_ROAD);
+ // Currently, we ignore CMD_ERRORs!
+ if (CmdFailed(res) && flag == DC_EXEC && !IsTileType(route[part], MP_STREET) && !EnsureNoVehicle(route[part])) {
+ // Problem.. let's just abort it all!
+ DEBUG(ai,0)("Darn, the route could not be builded.. aborting!");
+ p->ainew.state = AI_STATE_NOTHING;
+ return 0;
+ }
+
+ if (!CmdFailed(res)) cost += res;
+ }
+ // Go to the next tile
+ part++;
+ // Check if it is still in range..
+ if (part >= PathFinderInfo->route_length - 1) break;
+ }
+ part--;
+ // We want to return the last position, so we go back one
+ }
+ if (!EnsureNoVehicle(route[part]) && flag == DC_EXEC) part--;
+ PathFinderInfo->position = part;
+ }
+
+ return cost;
+}
+
+
+// This functions tries to find the best vehicle for this type of cargo
+// It returns vehicle_id or -1 if not found
+int AiNew_PickVehicle(Player *p)
+{
+ if (p->ainew.tbt == AI_TRAIN) {
+ // Not supported yet
+ return -1;
+ } else {
+ int start, count, i, ret = CMD_ERROR;
+ start = _cargoc.ai_roadveh_start[p->ainew.cargo];
+ count = _cargoc.ai_roadveh_count[p->ainew.cargo];
+
+ // Let's check it backwards.. we simply want to best engine available..
+ for (i=start+count-1;i>=start;i--) {
+ // Is it availiable?
+ // Also, check if the reliability of the vehicle is above the AI_VEHICLE_MIN_RELIABILTY
+ if (!HASBIT(GetEngine(i)->player_avail, _current_player) || GetEngine(i)->reliability * 100 < AI_VEHICLE_MIN_RELIABILTY << 16) continue;
+ // Can we build it?
+ ret = DoCommandByTile(0, i, 0, DC_QUERY_COST, CMD_BUILD_ROAD_VEH);
+ if (!CmdFailed(ret)) break;
+ }
+ // We did not find a vehicle :(
+ if (CmdFailed(ret)) { return -1; }
+ return i;
+ }
+}
+
+
+// Builds the best vehicle possible
+int AiNew_Build_Vehicle(Player *p, TileIndex tile, byte flag)
+{
+ int i = AiNew_PickVehicle(p);
+ if (i == -1) return CMD_ERROR;
+
+ if (p->ainew.tbt == AI_TRAIN)
+ return CMD_ERROR;
+
+ return DoCommandByTile(tile, i, 0, flag, CMD_BUILD_ROAD_VEH);
+}
+
+int AiNew_Build_Depot(Player *p, TileIndex tile, byte direction, byte flag)
+{
+ static const byte _roadbits_by_dir[4] = {2,1,8,4};
+ int ret, ret2;
+ if (p->ainew.tbt == AI_TRAIN)
+ return DoCommandByTile(tile, 0, direction, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_TRAIN_DEPOT);
+
+ ret = DoCommandByTile(tile, direction, 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_DEPOT);
+ if (CmdFailed(ret)) return ret;
+ // Try to build the road from the depot
+ ret2 = DoCommandByTile(tile + TileOffsByDir(direction), _roadbits_by_dir[direction], 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD);
+ // If it fails, ignore it..
+ if (CmdFailed(ret2)) return ret;
+ return ret + ret2;
+}
diff --git a/ai/trolly/pathfinder.c b/ai/trolly/pathfinder.c
new file mode 100644
index 000000000..aa44014f9
--- /dev/null
+++ b/ai/trolly/pathfinder.c
@@ -0,0 +1,514 @@
+/* $Id$ */
+
+#include "../../stdafx.h"
+#include "../../openttd.h"
+#include "../../debug.h"
+#include "../../functions.h"
+#include "../../map.h"
+#include "../../tile.h"
+#include "../../command.h"
+#include "trolly.h"
+#include "../../depot.h"
+#include "../../variables.h"
+
+#define TEST_STATION_NO_DIR 0xFF
+
+// Tests if a station can be build on the given spot
+// TODO: make it train compatible
+static bool TestCanBuildStationHere(TileIndex tile, byte dir)
+{
+ Player *p = GetPlayer(_current_player);
+
+ if (dir == TEST_STATION_NO_DIR) {
+ int32 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, p->ainew.tbt, tile, 1, 1, dir, DC_QUERY_COST);
+ if (!CmdFailed(ret)) return true;
+ }
+ return false;
+ }
+
+ // return true if command succeeded, so the inverse of CmdFailed()
+ return !CmdFailed(AiNew_Build_Station(p, p->ainew.tbt, tile, 1, 1, dir, DC_QUERY_COST));
+}
+
+
+static bool IsRoad(TileIndex tile)
+{
+ return
+ // MP_STREET, but not a road depot?
+ (IsTileType(tile, MP_STREET) && !IsTileDepotType(tile, TRANSPORT_ROAD)) ||
+ (IsTileType(tile, MP_TUNNELBRIDGE) && (
+ // road tunnel?
+ ((_m[tile].m5 & 0x80) == 0 && (_m[tile].m5 & 0x4) == 0x4) ||
+ // road bridge?
+ ((_m[tile].m5 & 0x80) != 0 && (_m[tile].m5 & 0x2) == 0x2)
+ ));
+}
+
+
+// Checks if a tile 'a' is between the tiles 'b' and 'c'
+#define TILES_BETWEEN(a, b, c) (TileX(a) >= TileX(b) && TileX(a) <= TileX(c) && TileY(a) >= TileY(b) && TileY(a) <= TileY(c))
+
+
+// Check if the current tile is in our end-area
+static int32 AyStar_AiPathFinder_EndNodeCheck(AyStar *aystar, OpenListNode *current)
+{
+ Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
+ // It is not allowed to have a station on the end of a bridge or tunnel ;)
+ if (current->path.node.user_data[0] != 0) return AYSTAR_DONE;
+ if (TILES_BETWEEN(current->path.node.tile, PathFinderInfo->end_tile_tl, PathFinderInfo->end_tile_br))
+ if (IsTileType(current->path.node.tile, MP_CLEAR) || IsTileType(current->path.node.tile, MP_TREES))
+ if (current->path.parent == NULL || TestCanBuildStationHere(current->path.node.tile, AiNew_GetDirection(current->path.parent->node.tile, current->path.node.tile)))
+ return AYSTAR_FOUND_END_NODE;
+
+ return AYSTAR_DONE;
+}
+
+
+// Calculates the hash
+// Currently it is a 10 bit hash, so the hash array has a max depth of 6 bits (so 64)
+static uint AiPathFinder_Hash(uint key1, uint key2)
+{
+ return (TileX(key1) & 0x1F) + ((TileY(key1) & 0x1F) << 5);
+}
+
+
+// Clear the memory of all the things
+static void AyStar_AiPathFinder_Free(AyStar *aystar)
+{
+ AyStarMain_Free(aystar);
+ free(aystar);
+}
+
+
+static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current, OpenListNode *parent);
+static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent);
+static void AyStar_AiPathFinder_FoundEndNode(AyStar *aystar, OpenListNode *current);
+static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *current);
+
+
+// This creates the AiPathFinder
+AyStar *new_AyStar_AiPathFinder(int max_tiles_around, Ai_PathFinderInfo *PathFinderInfo)
+{
+ PathNode start_node;
+ uint x;
+ uint y;
+ // Create AyStar
+ AyStar *result = malloc(sizeof(AyStar));
+ init_AyStar(result, AiPathFinder_Hash, 1 << 10);
+ // Set the function pointers
+ result->CalculateG = AyStar_AiPathFinder_CalculateG;
+ result->CalculateH = AyStar_AiPathFinder_CalculateH;
+ result->EndNodeCheck = AyStar_AiPathFinder_EndNodeCheck;
+ result->FoundEndNode = AyStar_AiPathFinder_FoundEndNode;
+ result->GetNeighbours = AyStar_AiPathFinder_GetNeighbours;
+
+ result->BeforeExit = NULL;
+
+ result->free = AyStar_AiPathFinder_Free;
+
+ // Set some information
+ result->loops_per_tick = AI_PATHFINDER_LOOPS_PER_TICK;
+ result->max_path_cost = 0;
+ result->max_search_nodes = AI_PATHFINDER_MAX_SEARCH_NODES;
+
+ // Set the user_data to the PathFinderInfo
+ result->user_target = PathFinderInfo;
+
+ // Set the start node
+ start_node.parent = NULL;
+ start_node.node.direction = 0;
+ start_node.node.user_data[0] = 0;
+
+ // Now we add all the starting tiles
+ for (x = TileX(PathFinderInfo->start_tile_tl); x <= TileX(PathFinderInfo->start_tile_br); x++) {
+ for (y = TileY(PathFinderInfo->start_tile_tl); y <= TileY(PathFinderInfo->start_tile_br); y++) {
+ start_node.node.tile = TileXY(x, y);
+ result->addstart(result, &start_node.node, 0);
+ }
+ }
+
+ return result;
+}
+
+
+// To reuse AyStar we sometimes have to clean all the memory
+void clean_AyStar_AiPathFinder(AyStar *aystar, Ai_PathFinderInfo *PathFinderInfo)
+{
+ PathNode start_node;
+ uint x;
+ uint y;
+
+ aystar->clear(aystar);
+
+ // Set the user_data to the PathFinderInfo
+ aystar->user_target = PathFinderInfo;
+
+ // Set the start node
+ start_node.parent = NULL;
+ start_node.node.direction = 0;
+ start_node.node.user_data[0] = 0;
+ start_node.node.tile = PathFinderInfo->start_tile_tl;
+
+ // Now we add all the starting tiles
+ for (x = TileX(PathFinderInfo->start_tile_tl); x <= TileX(PathFinderInfo->start_tile_br); x++) {
+ for (y = TileY(PathFinderInfo->start_tile_tl); y <= TileY(PathFinderInfo->start_tile_br); y++) {
+ if (!(IsTileType(TileXY(x, y), MP_CLEAR) || IsTileType(TileXY(x, y), MP_TREES))) continue;
+ if (!TestCanBuildStationHere(TileXY(x, y), TEST_STATION_NO_DIR)) continue;
+ start_node.node.tile = TileXY(x, y);
+ aystar->addstart(aystar, &start_node.node, 0);
+ }
+ }
+}
+
+
+// The h-value, simple calculation
+static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
+{
+ Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
+ int r, r2;
+ if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION) {
+ // The station is pointing to a direction, add a tile towards that direction, so the H-value is more accurate
+ r = DistanceManhattan(current->tile, PathFinderInfo->end_tile_tl + TileOffsByDir(PathFinderInfo->end_direction));
+ r2 = DistanceManhattan(current->tile, PathFinderInfo->end_tile_br + TileOffsByDir(PathFinderInfo->end_direction));
+ } else {
+ // No direction, so just get the fastest route to the station
+ r = DistanceManhattan(current->tile, PathFinderInfo->end_tile_tl);
+ r2 = DistanceManhattan(current->tile, PathFinderInfo->end_tile_br);
+ }
+ // See if the bottomright is faster than the topleft..
+ if (r2 < r) r = r2;
+ return r * AI_PATHFINDER_H_MULTIPLER;
+}
+
+
+// We found the end.. let's get the route back and put it in an array
+static void AyStar_AiPathFinder_FoundEndNode(AyStar *aystar, OpenListNode *current)
+{
+ Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
+ uint i = 0;
+ PathNode *parent = &current->path;
+
+ do {
+ PathFinderInfo->route_extra[i] = parent->node.user_data[0];
+ PathFinderInfo->route[i++] = parent->node.tile;
+ if (i > lengthof(PathFinderInfo->route)) {
+ // We ran out of space for the PathFinder
+ DEBUG(ai, 0)("[AiPathFinder] Ran out of space in the route[] array!!!");
+ PathFinderInfo->route_length = -1; // -1 indicates out of space
+ return;
+ }
+ parent = parent->parent;
+ } while (parent != NULL);
+ PathFinderInfo->route_length = i;
+ DEBUG(ai, 1)("[Ai-PathFinding] Found route of %d nodes long in %d nodes of searching", i, Hash_Size(&aystar->ClosedListHash));
+}
+
+
+// What tiles are around us.
+static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *current)
+{
+ uint i;
+ int ret;
+ int dir;
+
+ Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
+
+ aystar->num_neighbours = 0;
+
+ // Go through all surrounding tiles and check if they are within the limits
+ for (i = 0; i < 4; i++) {
+ TileIndex ctile = current->path.node.tile; // Current tile
+ TileIndex atile = ctile + TileOffsByDir(i); // Adjacent tile
+
+ if (TileX(atile) > 1 && TileX(atile) < MapMaxX() - 1 &&
+ TileY(atile) > 1 && TileY(atile) < MapMaxY() - 1) {
+ // We also directly test if the current tile can connect to this tile..
+ // We do this simply by just building the tile!
+
+ // If the next step is a bridge, we have to enter it the right way
+ if (!PathFinderInfo->rail_or_road && IsRoad(atile)) {
+ if (IsTileType(atile, MP_TUNNELBRIDGE)) {
+ // An existing bridge... let's test the direction ;)
+ if ((_m[atile].m5 & 1U) != (i & 1)) continue;
+ // This problem only is valid for tunnels:
+ // When the last tile was not yet a tunnel, check if we enter from the right side..
+ if ((_m[atile].m5 & 0x80) == 0) {
+ if (i != (_m[atile].m5 & 3U)) continue;
+ }
+ }
+ }
+ // But also if we are on a bridge, we can only move a certain direction
+ if (!PathFinderInfo->rail_or_road && IsRoad(ctile)) {
+ if (IsTileType(ctile, MP_TUNNELBRIDGE)) {
+ // An existing bridge/tunnel... let's test the direction ;)
+ if ((_m[ctile].m5 & 1U) != (i & 1)) continue;
+ }
+ }
+
+ if ((AI_PATHFINDER_FLAG_BRIDGE & current->path.node.user_data[0]) != 0 ||
+ (AI_PATHFINDER_FLAG_TUNNEL & current->path.node.user_data[0]) != 0) {
+ // We are a bridge/tunnel, how cool!!
+ // This means we can only point forward.. get the direction from the user_data
+ if (i != (current->path.node.user_data[0] >> 8)) continue;
+ }
+ dir = 0;
+
+ // First, check if we have a parent
+ if (current->path.parent == NULL && current->path.node.user_data[0] == 0) {
+ // If not, this means we are at the starting station
+ if (PathFinderInfo->start_direction != AI_PATHFINDER_NO_DIRECTION) {
+ // We do need a direction?
+ if (AiNew_GetDirection(ctile, atile) != PathFinderInfo->start_direction) {
+ // We are not pointing the right way, invalid tile
+ continue;
+ }
+ }
+ } else if (current->path.node.user_data[0] == 0) {
+ if (PathFinderInfo->rail_or_road) {
+ // Rail check
+ dir = AiNew_GetRailDirection(current->path.parent->node.tile, ctile, atile);
+ ret = DoCommandByTile(ctile, 0, dir, DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL);
+ if (CmdFailed(ret)) continue;
+#ifdef AI_PATHFINDER_NO_90DEGREES_TURN
+ if (current->path.parent->parent != NULL) {
+ // Check if we don't make a 90degree curve
+ int dir1 = AiNew_GetRailDirection(current->path.parent->parent->node.tile, current->path.parent->node.tile, ctile);
+ if (_illegal_curves[dir1] == dir || _illegal_curves[dir] == dir1) {
+ continue;
+ }
+ }
+#endif
+ } else {
+ // Road check
+ dir = AiNew_GetRoadDirection(current->path.parent->node.tile, ctile, atile);
+ if (IsRoad(ctile)) {
+ if (IsTileType(ctile, MP_TUNNELBRIDGE)) {
+ // We have a bridge, how nicely! We should mark it...
+ dir = 0;
+ } else {
+ // It already has road.. check if we miss any bits!
+ if ((_m[ctile].m5 & dir) != dir) {
+ // We do miss some pieces :(
+ dir &= ~_m[ctile].m5;
+ } else {
+ dir = 0;
+ }
+ }
+ }
+ // Only destruct things if it is MP_CLEAR of MP_TREES
+ if (dir != 0) {
+ ret = DoCommandByTile(ctile, dir, 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD);
+ if (CmdFailed(ret)) continue;
+ }
+ }
+ }
+
+ // The tile can be connected
+ aystar->neighbours[aystar->num_neighbours].tile = atile;
+ aystar->neighbours[aystar->num_neighbours].user_data[0] = 0;
+ aystar->neighbours[aystar->num_neighbours++].direction = 0;
+ }
+ }
+
+ // Next step, check for bridges and tunnels
+ if (current->path.parent != NULL && current->path.node.user_data[0] == 0) {
+ TileInfo ti;
+ // First we get the dir from this tile and his parent
+ int dir = AiNew_GetDirection(current->path.parent->node.tile, current->path.node.tile);
+ // It means we can only walk with the track, so the bridge has to be in the same direction
+ TileIndex tile = current->path.node.tile;
+ TileIndex new_tile = tile;
+
+ FindLandscapeHeightByTile(&ti, tile);
+
+ // Bridges can only be build on land that is not flat
+ // And if there is a road or rail blocking
+ if (ti.tileh != 0 ||
+ (PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDir(dir), MP_STREET)) ||
+ (!PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDir(dir), MP_RAILWAY))) {
+ for (;;) {
+ new_tile += TileOffsByDir(dir);
+
+ // Precheck, is the length allowed?
+ if (!CheckBridge_Stuff(0, GetBridgeLength(tile, new_tile))) break;
+
+ // Check if we hit the station-tile.. we don't like that!
+ if (TILES_BETWEEN(new_tile, PathFinderInfo->end_tile_tl, PathFinderInfo->end_tile_br)) break;
+
+ // Try building the bridge..
+ ret = DoCommandByTile(tile, new_tile, (0 << 8) + (MAX_BRIDGES / 2), DC_AUTO, CMD_BUILD_BRIDGE);
+ if (CmdFailed(ret)) continue;
+ // We can build a bridge here.. add him to the neighbours
+ aystar->neighbours[aystar->num_neighbours].tile = new_tile;
+ aystar->neighbours[aystar->num_neighbours].user_data[0] = AI_PATHFINDER_FLAG_BRIDGE + (dir << 8);
+ aystar->neighbours[aystar->num_neighbours++].direction = 0;
+ // We can only have 12 neighbours, and we need 1 left for tunnels
+ if (aystar->num_neighbours == 11) break;
+ }
+ }
+
+ // Next, check for tunnels!
+ // Tunnels can only be build with tileh of 3, 6, 9 or 12, depending on the direction
+ // For now, we check both sides for this tile.. terraforming gives fuzzy result
+ if ((dir == 0 && ti.tileh == 12) ||
+ (dir == 1 && ti.tileh == 6) ||
+ (dir == 2 && ti.tileh == 3) ||
+ (dir == 3 && ti.tileh == 9)) {
+ // Now simply check if a tunnel can be build
+ ret = DoCommandByTile(tile, (PathFinderInfo->rail_or_road?0:0x200), 0, DC_AUTO, CMD_BUILD_TUNNEL);
+ FindLandscapeHeightByTile(&ti, _build_tunnel_endtile);
+ if (!CmdFailed(ret) && (ti.tileh == 3 || ti.tileh == 6 || ti.tileh == 9 || ti.tileh == 12)) {
+ aystar->neighbours[aystar->num_neighbours].tile = _build_tunnel_endtile;
+ aystar->neighbours[aystar->num_neighbours].user_data[0] = AI_PATHFINDER_FLAG_TUNNEL + (dir << 8);
+ aystar->neighbours[aystar->num_neighbours++].direction = 0;
+ }
+ }
+ }
+}
+
+
+extern uint GetRailFoundation(uint tileh, uint bits);
+extern uint GetRoadFoundation(uint tileh, uint bits);
+extern uint GetBridgeFoundation(uint tileh, byte direction);
+enum {
+ BRIDGE_NO_FOUNDATION = 1 << 0 | 1 << 3 | 1 << 6 | 1 << 9 | 1 << 12,
+};
+
+// The most important function: it calculates the g-value
+static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
+{
+ Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
+ int r, res = 0;
+ TileInfo ti, parent_ti;
+
+ // Gather some information about the tile..
+ FindLandscapeHeightByTile(&ti, current->tile);
+ FindLandscapeHeightByTile(&parent_ti, parent->path.node.tile);
+
+ // Check if we hit the end-tile
+ if (TILES_BETWEEN(current->tile, PathFinderInfo->end_tile_tl, PathFinderInfo->end_tile_br)) {
+ // We are at the end-tile, check if we had a direction or something...
+ if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION && AiNew_GetDirection(current->tile, parent->path.node.tile) != PathFinderInfo->end_direction) {
+ // We are not pointing the right way, invalid tile
+ return AYSTAR_INVALID_NODE;
+ }
+ // If it was valid, drop out.. we don't build on the endtile
+ return 0;
+ }
+
+ // Give everything a small penalty
+ res += AI_PATHFINDER_PENALTY;
+
+ if (!PathFinderInfo->rail_or_road) {
+ // Road has the lovely advantage it can use other road... check if
+ // the current tile is road, and if so, give a good bonus
+ if (IsRoad(current->tile)) {
+ res -= AI_PATHFINDER_ROAD_ALREADY_EXISTS_BONUS;
+ }
+ }
+
+ // We should give a penalty when the tile is going up or down.. this is one way to do so!
+ // Too bad we have to count it from the parent.. but that is not so bad.
+ // We also dislike long routes on slopes, since they do not look too realistic
+ // when there is a flat land all around, they are more expensive to build, and
+ // especially they essentially block the ability to connect or cross the road
+ // from one side.
+ if (parent_ti.tileh != 0 && parent->path.parent != NULL) {
+ // Skip if the tile was from a bridge or tunnel
+ if (parent->path.node.user_data[0] == 0 && current->user_data[0] == 0) {
+ if (PathFinderInfo->rail_or_road) {
+ r = GetRailFoundation(parent_ti.tileh, 1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
+ // Maybe is BRIDGE_NO_FOUNDATION a bit strange here, but it contains just the right information..
+ if (r >= 15 || (r == 0 && (BRIDGE_NO_FOUNDATION & (1 << ti.tileh)))) {
+ res += AI_PATHFINDER_TILE_GOES_UP_PENALTY;
+ } else {
+ res += AI_PATHFINDER_FOUNDATION_PENALTY;
+ }
+ } else {
+ if (!(IsRoad(parent->path.node.tile) && IsTileType(parent->path.node.tile, MP_TUNNELBRIDGE))) {
+ r = GetRoadFoundation(parent_ti.tileh, AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
+ if (r >= 15 || r == 0)
+ res += AI_PATHFINDER_TILE_GOES_UP_PENALTY;
+ else
+ res += AI_PATHFINDER_FOUNDATION_PENALTY;
+ }
+ }
+ }
+ }
+
+ // Are we part of a tunnel?
+ if ((AI_PATHFINDER_FLAG_TUNNEL & current->user_data[0]) != 0) {
+ // Tunnels are very expensive when build on long routes..
+ // Ironicly, we are using BridgeCode here ;)
+ r = AI_PATHFINDER_TUNNEL_PENALTY * GetBridgeLength(current->tile, parent->path.node.tile);
+ res += r + (r >> 8);
+ }
+
+ // Are we part of a bridge?
+ if ((AI_PATHFINDER_FLAG_BRIDGE & current->user_data[0]) != 0) {
+ // That means for every length a penalty
+ res += AI_PATHFINDER_BRIDGE_PENALTY * GetBridgeLength(current->tile, parent->path.node.tile);
+ // Check if we are going up or down, first for the starting point
+ // In user_data[0] is at the 8th bit the direction
+ if (!(BRIDGE_NO_FOUNDATION & (1 << parent_ti.tileh))) {
+ if (GetBridgeFoundation(parent_ti.tileh, (current->user_data[0] >> 8) & 1) < 15)
+ res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
+ }
+ // Second for the end point
+ if (!(BRIDGE_NO_FOUNDATION & (1 << ti.tileh))) {
+ if (GetBridgeFoundation(ti.tileh, (current->user_data[0] >> 8) & 1) < 15)
+ res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
+ }
+ if (parent_ti.tileh == 0) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
+ if (ti.tileh == 0) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
+ }
+
+ // To prevent the AI from taking the fastest way in tiles, but not the fastest way
+ // in speed, we have to give a good penalty to direction changing
+ // This way, we get almost the fastest way in tiles, and a very good speed on the track
+ if (!PathFinderInfo->rail_or_road) {
+ if (parent->path.parent != NULL &&
+ AiNew_GetDirection(current->tile, parent->path.node.tile) != AiNew_GetDirection(parent->path.node.tile, parent->path.parent->node.tile)) {
+ // When road exists, we don't like turning, but its free, so don't be to piggy about it
+ if (IsRoad(parent->path.node.tile))
+ res += AI_PATHFINDER_DIRECTION_CHANGE_ON_EXISTING_ROAD_PENALTY;
+ else
+ res += AI_PATHFINDER_DIRECTION_CHANGE_PENALTY;
+ }
+ } else {
+ // For rail we have 1 exeption: diagonal rail..
+ // So we fetch 2 raildirection. That of the current one, and of the one before that
+ if (parent->path.parent != NULL && parent->path.parent->parent != NULL) {
+ int dir1 = AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile);
+ int dir2 = AiNew_GetRailDirection(parent->path.parent->parent->node.tile, parent->path.parent->node.tile, parent->path.node.tile);
+ // First, see if we are on diagonal path, that is better than straight path
+ if (dir1 > 1) { res -= AI_PATHFINDER_DIAGONAL_BONUS; }
+
+ // First see if they are different
+ if (dir1 != dir2) {
+ // dir 2 and 3 are 1 diagonal track, and 4 and 5.
+ if (!(((dir1 == 2 || dir1 == 3) && (dir2 == 2 || dir2 == 3)) || ((dir1 == 4 || dir1 == 5) && (dir2 == 4 || dir2 == 5)))) {
+ // It is not, so we changed of direction
+ res += AI_PATHFINDER_DIRECTION_CHANGE_PENALTY;
+ }
+ if (parent->path.parent->parent->parent != NULL) {
+ int dir3 = AiNew_GetRailDirection(parent->path.parent->parent->parent->node.tile, parent->path.parent->parent->node.tile, parent->path.parent->node.tile);
+ // Check if we changed 3 tiles of direction in 3 tiles.. bad!!!
+ if ((dir1 == 0 || dir1 == 1) && dir2 > 1 && (dir3 == 0 || dir3 == 1)) {
+ res += AI_PATHFINDER_CURVE_PENALTY;
+ }
+ }
+ }
+ }
+ }
+
+ // Res should never be below zero.. if so, make it zero!
+ if (res < 0) { res = 0; }
+
+ // Return our value
+ return res;
+}
diff --git a/ai/trolly/shared.c b/ai/trolly/shared.c
new file mode 100644
index 000000000..4b33a13a5
--- /dev/null
+++ b/ai/trolly/shared.c
@@ -0,0 +1,124 @@
+/* $Id$ */
+
+#include "../../stdafx.h"
+#include "../../openttd.h"
+#include "../../debug.h"
+#include "../../map.h"
+#include "trolly.h"
+#include "../../vehicle.h"
+
+int AiNew_GetRailDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c)
+{
+ // 0 = vert
+ // 1 = horz
+ // 2 = dig up-left
+ // 3 = dig down-right
+ // 4 = dig down-left
+ // 5 = dig up-right
+
+ int x1, x2, x3;
+ int y1, y2, y3;
+
+ x1 = TileX(tile_a);
+ x2 = TileX(tile_b);
+ x3 = TileX(tile_c);
+
+ y1 = TileY(tile_a);
+ y2 = TileY(tile_b);
+ y3 = TileY(tile_c);
+
+ if (y1 == y2 && y2 == y3) return 0;
+ if (x1 == x2 && x2 == x3) return 1;
+ if (y2 > y1) {
+ if (x2 > x3) return 2;
+ else return 4;
+ }
+ if (x2 > x1) {
+ if (y2 > y3) return 2;
+ else return 5;
+ }
+ if (y1 > y2) {
+ if (x2 > x3) return 5;
+ else return 3;
+ }
+ if (x1 > x2) {
+ if (y2 > y3) return 4;
+ else return 3;
+ }
+
+ return 0;
+}
+
+int AiNew_GetRoadDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c)
+{
+ int x1, x2, x3;
+ int y1, y2, y3;
+ int r;
+
+ x1 = TileX(tile_a);
+ x2 = TileX(tile_b);
+ x3 = TileX(tile_c);
+
+ y1 = TileY(tile_a);
+ y2 = TileY(tile_b);
+ y3 = TileY(tile_c);
+
+ r = 0;
+
+ if (x1 < x2) r += 8;
+ if (y1 < y2) r += 1;
+ if (x1 > x2) r += 2;
+ if (y1 > y2) r += 4;
+
+ if (x2 < x3) r += 2;
+ if (y2 < y3) r += 4;
+ if (x2 > x3) r += 8;
+ if (y2 > y3) r += 1;
+
+ return r;
+}
+
+// Get's the direction between 2 tiles seen from tile_a
+int AiNew_GetDirection(TileIndex tile_a, TileIndex tile_b)
+{
+ if (TileY(tile_a) < TileY(tile_b)) return 1;
+ if (TileY(tile_a) > TileY(tile_b)) return 3;
+ if (TileX(tile_a) < TileX(tile_b)) return 2;
+ return 0;
+}
+
+// This functions looks up if this vehicle is special for this AI
+// and returns his flag
+uint AiNew_GetSpecialVehicleFlag(Player *p, Vehicle *v) {
+ int i;
+ for (i=0;i<AI_MAX_SPECIAL_VEHICLES;i++) {
+ if (p->ainew.special_vehicles[i].veh_id == v->index) {
+ return p->ainew.special_vehicles[i].flag;
+ }
+ }
+
+ // Not found :(
+ return 0;
+}
+
+bool AiNew_SetSpecialVehicleFlag(Player *p, Vehicle *v, uint flag) {
+ int i, new_id = -1;
+ for (i=0;i<AI_MAX_SPECIAL_VEHICLES;i++) {
+ if (p->ainew.special_vehicles[i].veh_id == v->index) {
+ p->ainew.special_vehicles[i].flag |= flag;
+ return true;
+ }
+ if (new_id == -1 && p->ainew.special_vehicles[i].veh_id == 0 &&
+ p->ainew.special_vehicles[i].flag == 0)
+ new_id = i;
+ }
+
+ // Out of special_vehicle spots :s
+ if (new_id == -1) {
+ DEBUG(ai, 1)("special_vehicles list is too small :(");
+ return false;
+ }
+ p->ainew.special_vehicles[new_id].veh_id = v->index;
+ p->ainew.special_vehicles[new_id].flag = flag;
+ return true;
+}
diff --git a/ai/trolly/trolly.c b/ai/trolly/trolly.c
new file mode 100644
index 000000000..5e16c51a9
--- /dev/null
+++ b/ai/trolly/trolly.c
@@ -0,0 +1,1379 @@
+/* $Id: ai_new.c 2891 2005-08-26 20:26:34Z tron $ */
+
+/*
+ * This AI was created as a direct reaction to the big demand for some good AIs in OTTD.
+ * Too bad it never left alpha-stage, and it is considered dead in his current form.
+ * By the time of writing this, we, the creator of this AI and a good friend of mine,
+ * are designing a whole new AI-system that allows us to create AIs easier and without
+ * all the fuzz we encountered while I was working on this AI. By the time that system
+ * is finished, you can expect that this AI will dissapear, because it is pretty
+ * obselete and bad programmed.
+ *
+ * In the meanwhile I wish you all much fun with this AI; if you are interested as
+ * AI-developer in this AI, I advise you not stare too long to some code, some things in
+ * here really are... strange ;) But in either way: enjoy :)
+ *
+ * -- TrueLight :: 2005-09-01
+ */
+
+#include "../../stdafx.h"
+#include "../../openttd.h"
+#include "../../debug.h"
+#include "../../functions.h"
+#include "../../table/strings.h"
+#include "../../map.h"
+#include "../../tile.h"
+#include "../../command.h"
+#include "trolly.h"
+#include "../../town.h"
+#include "../../industry.h"
+#include "../../station.h"
+#include "../../engine.h"
+#include "../../gui.h"
+#include "../../depot.h"
+
+// This function is called after StartUp. It is the init of an AI
+static void AiNew_State_FirstTime(Player *p)
+{
+ // 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(p->ainew.state == AI_STATE_FIRST_TIME);
+ // We first have to init some things
+
+ if (_current_player == 1) {
+ ShowErrorMessage(-1, 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!
+ p->ainew.path_info.start_tile_tl = 0;
+ p->ainew.path_info.start_tile_br = 0;
+ p->ainew.path_info.end_tile_tl = 0;
+ p->ainew.path_info.end_tile_br = 0;
+ p->ainew.pathfinder = new_AyStar_AiPathFinder(12, &p->ainew.path_info);
+
+ p->ainew.idle = 0;
+ p->ainew.last_vehiclecheck_date = _date;
+
+ // We ALWAYS start with a bus route.. just some basic money ;)
+ p->ainew.action = AI_ACTION_BUS_ROUTE;
+
+ // Let's popup the news, and after that, start building..
+ p->ainew.state = AI_STATE_WAKE_UP;
+}
+
+
+// This function just waste some time
+// It keeps it more real. The AI can build on such tempo no normal user
+// can ever keep up with that. The competitor_speed already delays a bit
+// but after the AI finished a track it really needs to go to sleep.
+//
+// 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)
+{
+ assert(p->ainew.state == AI_STATE_NOTHING);
+ // If we are done idling, start over again
+ if (p->ainew.idle == 0) p->ainew.idle = RandomRange(DAY_TICKS * 2) + DAY_TICKS;
+ if (--p->ainew.idle == 0) {
+ // We are done idling.. what you say? Let's do something!
+ // I mean.. the next tick ;)
+ p->ainew.state = AI_STATE_WAKE_UP;
+ }
+}
+
+
+// This function picks out a task we are going to do.
+// Currently supported:
+// - Make new route
+// - Check route
+// - Build HQ
+static void AiNew_State_WakeUp(Player *p)
+{
+ int32 money;
+ int c;
+ assert(p->ainew.state == AI_STATE_WAKE_UP);
+ // First, check if we have a HQ
+ if (p->location_of_house == 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, Random() % MapSize());
+ // Enough for now, but we want to come back here the next time
+ // so we do not change any status
+ return;
+ }
+
+ money = p->player_money - AI_MINIMUM_MONEY;
+
+ // Let's pick an action!
+ if (p->ainew.action == AI_ACTION_NONE) {
+ c = Random() & 0xFF;
+ if (p->current_loan > 0 &&
+ p->old_economy[1].income > AI_MINIMUM_INCOME_FOR_LOAN &&
+ c < 10) {
+ p->ainew.action = AI_ACTION_REPAY_LOAN;
+ } else if (p->ainew.last_vehiclecheck_date + AI_DAYS_BETWEEN_VEHICLE_CHECKS < _date) {
+ // Check all vehicles once in a while
+ p->ainew.action = AI_ACTION_CHECK_ALL_VEHICLES;
+ p->ainew.last_vehiclecheck_date = _date;
+ } else if (c < 100 && !_patches.ai_disable_veh_roadveh) {
+ // Do we have any spots for road-vehicles left open?
+ if (GetFreeUnitNumber(VEH_Road) <= _patches.max_roadveh) {
+ if (c < 85)
+ p->ainew.action = AI_ACTION_TRUCK_ROUTE;
+ else
+ p->ainew.action = AI_ACTION_BUS_ROUTE;
+ }
+ }/* else if (c < 200 && !_patches.ai_disable_veh_train) {
+ if (GetFreeUnitNumber(VEH_Train) <= _patches.max_trains) {
+ p->ainew.action = AI_ACTION_TRAIN_ROUTE;
+ }
+ }*/
+
+ p->ainew.counter = 0;
+ }
+
+ if (p->ainew.counter++ > AI_MAX_TRIES_FOR_SAME_ROUTE) {
+ p->ainew.action = AI_ACTION_NONE;
+ return;
+ }
+
+ if (_patches.ai_disable_veh_roadveh && (
+ p->ainew.action == AI_ACTION_BUS_ROUTE ||
+ p->ainew.action == AI_ACTION_TRUCK_ROUTE
+ )) {
+ p->ainew.action = AI_ACTION_NONE;
+ return;
+ }
+
+ if (_patches.ai_disable_veh_roadveh && (
+ p->ainew.action == AI_ACTION_BUS_ROUTE ||
+ p->ainew.action == AI_ACTION_TRUCK_ROUTE
+ )) {
+ p->ainew.action = AI_ACTION_NONE;
+ return;
+ }
+
+ if (p->ainew.action == AI_ACTION_REPAY_LOAN &&
+ money > AI_MINIMUM_LOAN_REPAY_MONEY) {
+ // We start repaying some money..
+ p->ainew.state = AI_STATE_REPAY_MONEY;
+ return;
+ }
+
+ if (p->ainew.action == AI_ACTION_CHECK_ALL_VEHICLES) {
+ p->ainew.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 (p->ainew.action == AI_ACTION_BUS_ROUTE &&
+ money > AI_MINIMUM_BUS_ROUTE_MONEY) {
+ if (GetFreeUnitNumber(VEH_Road) > _patches.max_roadveh) {
+ p->ainew.action = AI_ACTION_NONE;
+ return;
+ }
+ p->ainew.cargo = AI_NEED_CARGO;
+ p->ainew.state = AI_STATE_LOCATE_ROUTE;
+ p->ainew.tbt = AI_BUS; // Bus-route
+ return;
+ }
+ if (p->ainew.action == AI_ACTION_TRUCK_ROUTE &&
+ money > AI_MINIMUM_TRUCK_ROUTE_MONEY) {
+ if (GetFreeUnitNumber(VEH_Road) > _patches.max_roadveh) {
+ p->ainew.action = AI_ACTION_NONE;
+ return;
+ }
+ p->ainew.cargo = AI_NEED_CARGO;
+ p->ainew.last_id = 0;
+ p->ainew.state = AI_STATE_LOCATE_ROUTE;
+ p->ainew.tbt = AI_TRUCK;
+ return;
+ }
+
+ p->ainew.state = AI_STATE_NOTHING;
+}
+
+
+static void AiNew_State_ActionDone(Player *p)
+{
+ p->ainew.action = AI_ACTION_NONE;
+ p->ainew.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)
+{
+ if (type == AI_CITY) {
+ Town *t = GetTown(ic);
+ Station *st;
+ uint count = 0;
+ int j = 0;
+
+ // We don't like roadconstructions, don't even true such a city
+ if (t->road_build_months != 0) return false;
+
+ // 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 && CHANCE16(1,4)) return false;
+
+ if (t->max_pass - t->act_pass < AI_CHECKCITY_NEEDED_CARGO && !CHANCE16(1,AI_CHECKCITY_CITY_CHANCE)) return false;
+
+ // Check if we have build a station in this town the last 6 months
+ // else we don't do it. This is done, because stat updates can be slow
+ // and sometimes it takes up to 4 months before the stats are corectly.
+ // This way we don't get 12 busstations in one city of 100 population ;)
+ FOR_ALL_STATIONS(st) {
+ // Is it an active station
+ if (st->xy == 0) continue;
+ // Do we own it?
+ if (st->owner == _current_player) {
+ // Are we talking busses?
+ if (p->ainew.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?
+ if (_date - st->build_date < AI_CHECKCITY_DATE_BETWEEN) return false;
+ // Cound the amount of stations in this city that we own
+ count++;
+ } else {
+ // We do not own it, request some info about the station
+ // we want to know if this station gets the same good. If so,
+ // we want to know its rating. If it is too high, we are not going
+ // to build there
+ if (!st->goods[CT_PASSENGERS].last_speed) continue;
+ // Is it around our city
+ if (DistanceManhattan(st->xy, t->xy) > 10) continue;
+ // It does take this cargo.. what is his rating?
+ if (st->goods[CT_PASSENGERS].rating < AI_CHECKCITY_CARGO_RATING) continue;
+ j++;
+ // When this is the first station, we build a second with no problem ;)
+ if (j == 1) continue;
+ // The rating is high.. second station...
+ // a little chance that we still continue
+ // But if there are 3 stations of this size, we never go on...
+ if (j == 2 && CHANCE16(1, AI_CHECKCITY_CARGO_RATING_CHANCE)) continue;
+ // We don't like this station :(
+ return false;
+ }
+ }
+
+ // We are about to add one...
+ count++;
+ // Check if we the city can provide enough cargo for this amount of stations..
+ if (count * AI_CHECKCITY_CARGO_PER_STATION > t->max_pass) return false;
+
+ // All check are okay, so we can build here!
+ return true;
+ }
+ if (type == AI_INDUSTRY) {
+ Industry *i = GetIndustry(ic);
+ Station *st;
+ int count = 0;
+ int j = 0;
+
+ if (i->town != NULL && i->town->ratings[_current_player] < 0 && CHANCE16(1,4)) return false;
+
+ // No limits on delevering stations!
+ // Or for industry that does not give anything yet
+ if (i->produced_cargo[0] == 0xFF || i->total_production[0] == 0) return true;
+
+ if (i->total_production[0] - i->total_transported[0] < AI_CHECKCITY_NEEDED_CARGO) return false;
+
+ // Check if we have build a station in this town the last 6 months
+ // else we don't do it. This is done, because stat updates can be slow
+ // and sometimes it takes up to 4 months before the stats are corectly.
+ FOR_ALL_STATIONS(st) {
+ // Is it an active station
+ if (st->xy == 0) continue;
+
+ // Do we own it?
+ if (st->owner == _current_player) {
+ // Are we talking trucks?
+ if (p->ainew.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?
+ if (_date - st->build_date < AI_CHECKCITY_DATE_BETWEEN) return false;
+ // Cound the amount of stations in this city that we own
+ count++;
+ } else {
+ // We do not own it, request some info about the station
+ // we want to know if this station gets the same good. If so,
+ // we want to know its rating. If it is too high, we are not going
+ // to build there
+ if (i->produced_cargo[0] == 0xFF) continue;
+ // It does not take this cargo
+ if (!st->goods[i->produced_cargo[0]].last_speed) continue;
+ // Is it around our industry
+ if (DistanceManhattan(st->xy, i->xy) > 5) continue;
+ // It does take this cargo.. what is his rating?
+ if (st->goods[i->produced_cargo[0]].rating < AI_CHECKCITY_CARGO_RATING) continue;
+ j++;
+ // The rating is high.. a little chance that we still continue
+ // But if there are 2 stations of this size, we never go on...
+ if (j == 1 && CHANCE16(1, AI_CHECKCITY_CARGO_RATING_CHANCE)) continue;
+ // We don't like this station :(
+ return false;
+ }
+ }
+
+ // We are about to add one...
+ count++;
+ // Check if we the city can provide enough cargo for this amount of stations..
+ if (count * AI_CHECKCITY_CARGO_PER_STATION > i->total_production[0]) return false;
+
+ // All check are okay, so we can build here!
+ return true;
+ }
+
+ return true;
+}
+
+
+// This functions tries to locate a good route
+static void AiNew_State_LocateRoute(Player *p)
+{
+ assert(p->ainew.state == AI_STATE_LOCATE_ROUTE);
+ // For now, we only support PASSENGERS, CITY and BUSSES
+
+ // We don't have a route yet
+ if (p->ainew.cargo == AI_NEED_CARGO) {
+ p->ainew.new_cost = 0; // No cost yet
+ p->ainew.temp = -1;
+ // Reset the counter
+ p->ainew.counter = 0;
+
+ p->ainew.from_ic = -1;
+ p->ainew.to_ic = -1;
+ if (p->ainew.tbt == AI_BUS) {
+ // For now we only have a passenger route
+ p->ainew.cargo = CT_PASSENGERS;
+
+ // Find a route to cities
+ p->ainew.from_type = AI_CITY;
+ p->ainew.to_type = AI_CITY;
+ } else if (p->ainew.tbt == AI_TRUCK) {
+ p->ainew.cargo = AI_NO_CARGO;
+
+ p->ainew.from_type = AI_INDUSTRY;
+ p->ainew.to_type = AI_INDUSTRY;
+ }
+
+ // Now we are doing initing, we wait one tick
+ return;
+ }
+
+ // Increase the counter and abort if it is taking too long!
+ p->ainew.counter++;
+ if (p->ainew.counter > AI_LOCATE_ROUTE_MAX_COUNTER) {
+ // Switch back to doing nothing!
+ p->ainew.state = AI_STATE_NOTHING;
+ return;
+ }
+
+ // We are going to locate a city from where we are going to connect
+ if (p->ainew.from_ic == -1) {
+ if (p->ainew.temp == -1) {
+ // First, we pick a random spot to search from
+ if (p->ainew.from_type == AI_CITY)
+ p->ainew.temp = RandomRange(_total_towns);
+ else
+ p->ainew.temp = RandomRange(_total_industries);
+ }
+
+ if (!AiNew_Check_City_or_Industry(p, p->ainew.temp, p->ainew.from_type)) {
+ // It was not a valid city
+ // increase the temp with one, and return. We will come back later here
+ // to try again
+ p->ainew.temp++;
+ if (p->ainew.from_type == AI_CITY) {
+ if (p->ainew.temp >= (int)_total_towns) p->ainew.temp = 0;
+ } else {
+ if (p->ainew.temp >= _total_industries) p->ainew.temp = 0;
+ }
+
+ // Don't do an attempt if we are trying the same id as the last time...
+ if (p->ainew.last_id == p->ainew.temp) return;
+ p->ainew.last_id = p->ainew.temp;
+
+ return;
+ }
+
+ // We found a good city/industry, save the data of it
+ p->ainew.from_ic = p->ainew.temp;
+
+ // Start the next tick with finding a to-city
+ p->ainew.temp = -1;
+ return;
+ }
+
+ // Find a to-city
+ if (p->ainew.temp == -1) {
+ // First, we pick a random spot to search to
+ if (p->ainew.to_type == AI_CITY)
+ p->ainew.temp = RandomRange(_total_towns);
+ else
+ p->ainew.temp = RandomRange(_total_industries);
+ }
+
+ // The same city is not allowed
+ // Also check if the city is valid
+ if (p->ainew.temp != p->ainew.from_ic && AiNew_Check_City_or_Industry(p, p->ainew.temp, p->ainew.to_type)) {
+ // Maybe it is valid..
+
+ // We need to know if they are not to far apart from eachother..
+ // We do that by checking how much cargo we have to move and how long the route
+ // is.
+
+ if (p->ainew.from_type == AI_CITY && p->ainew.tbt == AI_BUS) {
+ int max_cargo = GetTown(p->ainew.from_ic)->max_pass + GetTown(p->ainew.temp)->max_pass;
+ max_cargo -= GetTown(p->ainew.from_ic)->act_pass + GetTown(p->ainew.temp)->act_pass;
+ // max_cargo is now the amount of cargo we can move between the two cities
+ // If it is more than the distance, we allow it
+ if (DistanceManhattan(GetTown(p->ainew.from_ic)->xy, GetTown(p->ainew.temp)->xy) <= max_cargo * AI_LOCATEROUTE_BUS_CARGO_DISTANCE) {
+ // We found a good city/industry, save the data of it
+ p->ainew.to_ic = p->ainew.temp;
+ p->ainew.state = AI_STATE_FIND_STATION;
+
+ DEBUG(ai,1)(
+ "[AiNew - LocateRoute] Found bus-route of %d tiles long (from %d to %d)",
+ DistanceManhattan(GetTown(p->ainew.from_ic)->xy, GetTown(p->ainew.temp)->xy),
+ p->ainew.from_ic,
+ p->ainew.temp
+ );
+
+ p->ainew.from_tile = 0;
+ p->ainew.to_tile = 0;
+
+ return;
+ }
+ } else if (p->ainew.tbt == AI_TRUCK) {
+ bool found = false;
+ int max_cargo = 0;
+ int i;
+ // TODO: in max_cargo, also check other cargo (beside [0])
+ // First we check if the from_ic produces cargo that this ic accepts
+ if (GetIndustry(p->ainew.from_ic)->produced_cargo[0] != 0xFF && GetIndustry(p->ainew.from_ic)->total_production[0] != 0) {
+ for (i=0;i<3;i++) {
+ if (GetIndustry(p->ainew.temp)->accepts_cargo[i] == 0xFF) break;
+ if (GetIndustry(p->ainew.from_ic)->produced_cargo[0] == GetIndustry(p->ainew.temp)->accepts_cargo[i]) {
+ // Found a compatbiel industry
+ max_cargo = GetIndustry(p->ainew.from_ic)->total_production[0] - GetIndustry(p->ainew.from_ic)->total_transported[0];
+ found = true;
+ p->ainew.from_deliver = true;
+ p->ainew.to_deliver = false;
+ break;
+ }
+ }
+ }
+ if (!found && GetIndustry(p->ainew.temp)->produced_cargo[0] != 0xFF && GetIndustry(p->ainew.temp)->total_production[0] != 0) {
+ // If not check if the current ic produces cargo that the from_ic accepts
+ for (i=0;i<3;i++) {
+ if (GetIndustry(p->ainew.from_ic)->accepts_cargo[i] == 0xFF) break;
+ if (GetIndustry(p->ainew.temp)->produced_cargo[0] == GetIndustry(p->ainew.from_ic)->accepts_cargo[i]) {
+ // Found a compatbiel industry
+ found = true;
+ max_cargo = GetIndustry(p->ainew.temp)->total_production[0] - GetIndustry(p->ainew.from_ic)->total_transported[0];
+ p->ainew.from_deliver = false;
+ p->ainew.to_deliver = true;
+ break;
+ }
+ }
+ }
+ if (found) {
+ // Yeah, they are compatible!!!
+ // Check the length against the amount of goods
+ if (DistanceManhattan(GetIndustry(p->ainew.from_ic)->xy, GetIndustry(p->ainew.temp)->xy) > AI_LOCATEROUTE_TRUCK_MIN_DISTANCE &&
+ DistanceManhattan(GetIndustry(p->ainew.from_ic)->xy, GetIndustry(p->ainew.temp)->xy) <= max_cargo * AI_LOCATEROUTE_TRUCK_CARGO_DISTANCE) {
+ p->ainew.to_ic = p->ainew.temp;
+ if (p->ainew.from_deliver) {
+ p->ainew.cargo = GetIndustry(p->ainew.from_ic)->produced_cargo[0];
+ } else {
+ p->ainew.cargo = GetIndustry(p->ainew.temp)->produced_cargo[0];
+ }
+ p->ainew.state = AI_STATE_FIND_STATION;
+
+ DEBUG(ai,1)(
+ "[AiNew - LocateRoute] Found truck-route of %d tiles long (from %d to %d)",
+ DistanceManhattan(GetIndustry(p->ainew.from_ic)->xy, GetIndustry(p->ainew.temp)->xy),
+ p->ainew.from_ic,
+ p->ainew.temp
+ );
+
+ p->ainew.from_tile = 0;
+ p->ainew.to_tile = 0;
+
+ return;
+ }
+ }
+ }
+ }
+
+ // It was not a valid city
+ // increase the temp with one, and return. We will come back later here
+ // to try again
+ p->ainew.temp++;
+ if (p->ainew.to_type == AI_CITY) {
+ if (p->ainew.temp >= (int)_total_towns) p->ainew.temp = 0;
+ } else {
+ if (p->ainew.temp >= _total_industries) p->ainew.temp = 0;
+ }
+
+ // Don't do an attempt if we are trying the same id as the last time...
+ if (p->ainew.last_id == p->ainew.temp) return;
+ p->ainew.last_id = p->ainew.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)
+{
+ 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) {
+ const Order *order;
+
+ FOR_VEHICLE_ORDERS(v, order) {
+ if (order->type == OT_GOTO_STATION && GetStation(order->station) == st) {
+ // This vehicle has this city in its list
+ count++;
+ }
+ }
+ }
+ }
+
+ if (count > AI_CHECK_MAX_VEHICLE_PER_STATION) return false;
+ return true;
+}
+
+// This function finds a good spot for a station
+static void AiNew_State_FindStation(Player *p)
+{
+ TileIndex tile;
+ Station *st;
+ int i, count = 0;
+ TileIndex new_tile = 0;
+ byte direction = 0;
+ Town *town = NULL;
+ Industry *industry = NULL;
+ assert(p->ainew.state == AI_STATE_FIND_STATION);
+
+ if (p->ainew.from_tile == 0) {
+ // First we scan for a station in the from-city
+ if (p->ainew.from_type == AI_CITY) {
+ town = GetTown(p->ainew.from_ic);
+ tile = town->xy;
+ } else {
+ industry = GetIndustry(p->ainew.from_ic);
+ tile = industry->xy;
+ }
+ } else if (p->ainew.to_tile == 0) {
+ // Second we scan for a station in the to-city
+ if (p->ainew.to_type == AI_CITY) {
+ town = GetTown(p->ainew.to_ic);
+ tile = town->xy;
+ } else {
+ industry = GetIndustry(p->ainew.to_ic);
+ tile = industry->xy;
+ }
+ } else {
+ // Unsupported request
+ // Go to FIND_PATH
+ p->ainew.temp = -1;
+ p->ainew.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);
+ // Euhmz, this should not happen _EVER_
+ // Quit finding a route...
+ if (i == -1) { p->ainew.state = AI_STATE_NOTHING; return; }
+
+ FOR_ALL_STATIONS(st) {
+ if (st->xy != 0) {
+ if (st->owner == _current_player) {
+ if (p->ainew.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 ((st->goods[p->ainew.cargo].waiting_acceptance & 0xFFF) > RoadVehInfo(i)->capacity * AI_STATION_REUSE_MULTIPLER) {
+ if (AiNew_CheckVehicleStation(p, st)) {
+ // We did found a station that was good enough!
+ new_tile = st->xy;
+ // Cheap way to get the direction of the station...
+ // Bus stations save it as 0x47 .. 0x4A, so decrease it with 0x47, and tada!
+ direction = _m[st->xy].m5 - 0x47;
+ break;
+ }
+ }
+ count++;
+ }
+ }
+ }
+ }
+ }
+ // We are going to add a new station...
+ if (new_tile == 0) count++;
+ // 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) {
+ p->ainew.state = AI_STATE_NOTHING;
+ return;
+ }
+
+ if (new_tile == 0 && p->ainew.tbt == AI_BUS) {
+ uint x, y, i = 0;
+ int r;
+ uint best;
+ uint accepts[NUM_CARGO];
+ TileIndex found_spot[AI_FINDSTATION_TILE_RANGE*AI_FINDSTATION_TILE_RANGE*4];
+ uint found_best[AI_FINDSTATION_TILE_RANGE*AI_FINDSTATION_TILE_RANGE*4];
+ // To find a good spot we scan a range from the center, a get the point
+ // where we get the most cargo and where it is buildable.
+ // TODO: also check for station of myself and make sure we are not
+ // taking eachothers passangers away (bad result when it does not)
+ for (x = TileX(tile) - AI_FINDSTATION_TILE_RANGE; x <= TileX(tile) + AI_FINDSTATION_TILE_RANGE; x++) {
+ for (y = TileY(tile) - AI_FINDSTATION_TILE_RANGE; y <= TileY(tile) + AI_FINDSTATION_TILE_RANGE; y++) {
+ new_tile = TileXY(x, y);
+ if (IsTileType(new_tile, MP_CLEAR) || IsTileType(new_tile, MP_TREES)) {
+ // This tile we can build on!
+ // Check acceptance
+ // XXX - Get the catchment area
+ GetAcceptanceAroundTiles(accepts, new_tile, 1, 1, 4);
+ // >> 3 == 0 means no cargo
+ if (accepts[p->ainew.cargo] >> 3 == 0) continue;
+ // See if we can build the station
+ r = AiNew_Build_Station(p, p->ainew.tbt, new_tile, 0, 0, 0, DC_QUERY_COST);
+ if (r == CMD_ERROR) continue;
+ // We can build it, so add it to found_spot
+ found_spot[i] = new_tile;
+ found_best[i++] = accepts[p->ainew.cargo];
+ }
+ }
+ }
+
+ // If i is still zero, we did not found anything :(
+ if (i == 0) {
+ p->ainew.state = AI_STATE_NOTHING;
+ return;
+ }
+
+ // Go through all the found_best and check which has the highest value
+ best = 0;
+ new_tile = 0;
+
+ for (x=0;x<i;x++) {
+ if (found_best[x] > best ||
+ (found_best[x] == best && DistanceManhattan(tile, new_tile) > DistanceManhattan(tile, found_spot[x]))) {
+ new_tile = found_spot[x];
+ best = found_best[x];
+ }
+ }
+
+ // See how much it is going to cost us...
+ r = AiNew_Build_Station(p, p->ainew.tbt, new_tile, 0, 0, 0, DC_QUERY_COST);
+ p->ainew.new_cost += r;
+
+ direction = AI_PATHFINDER_NO_DIRECTION;
+ } else if (new_tile == 0 && p->ainew.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!
+ new_tile = AI_STATION_RANGE;
+ direction = AI_PATHFINDER_NO_DIRECTION;
+ }
+
+ if (p->ainew.from_tile == 0) {
+ p->ainew.from_tile = new_tile;
+ p->ainew.from_direction = direction;
+ // Now we found thisone, go in for to_tile
+ return;
+ } else if (p->ainew.to_tile == 0) {
+ p->ainew.to_tile = new_tile;
+ p->ainew.to_direction = direction;
+ // K, done placing stations!
+ p->ainew.temp = -1;
+ p->ainew.state = AI_STATE_FIND_PATH;
+ return;
+ }
+}
+
+
+// We try to find a path between 2 points
+static void AiNew_State_FindPath(Player *p)
+{
+ int r;
+ assert(p->ainew.state == AI_STATE_FIND_PATH);
+
+ // First time, init some data
+ if (p->ainew.temp == -1) {
+ // Init path_info
+ if (p->ainew.from_tile == AI_STATION_RANGE) {
+ // For truck routes we take a range around the industry
+ p->ainew.path_info.start_tile_tl = GetIndustry(p->ainew.from_ic)->xy - TileDiffXY(1, 1);
+ p->ainew.path_info.start_tile_br = GetIndustry(p->ainew.from_ic)->xy + TileDiffXY(GetIndustry(p->ainew.from_ic)->width, GetIndustry(p->ainew.from_ic)->height) + TileDiffXY(1, 1);
+ p->ainew.path_info.start_direction = p->ainew.from_direction;
+ } else {
+ p->ainew.path_info.start_tile_tl = p->ainew.from_tile;
+ p->ainew.path_info.start_tile_br = p->ainew.from_tile;
+ p->ainew.path_info.start_direction = p->ainew.from_direction;
+ }
+
+ if (p->ainew.to_tile == AI_STATION_RANGE) {
+ p->ainew.path_info.end_tile_tl = GetIndustry(p->ainew.to_ic)->xy - TileDiffXY(1, 1);
+ p->ainew.path_info.end_tile_br = GetIndustry(p->ainew.to_ic)->xy + TileDiffXY(GetIndustry(p->ainew.to_ic)->width, GetIndustry(p->ainew.to_ic)->height) + TileDiffXY(1, 1);
+ p->ainew.path_info.end_direction = p->ainew.to_direction;
+ } else {
+ p->ainew.path_info.end_tile_tl = p->ainew.to_tile;
+ p->ainew.path_info.end_tile_br = p->ainew.to_tile;
+ p->ainew.path_info.end_direction = p->ainew.to_direction;
+ }
+
+ if (p->ainew.tbt == AI_TRAIN)
+ p->ainew.path_info.rail_or_road = true;
+ else
+ p->ainew.path_info.rail_or_road = false;
+
+ // First, clean the pathfinder with our new begin and endpoints
+ clean_AyStar_AiPathFinder(p->ainew.pathfinder, &p->ainew.path_info);
+
+ p->ainew.temp = 0;
+ }
+
+ // Start the pathfinder
+ r = p->ainew.pathfinder->main(p->ainew.pathfinder);
+ // If it return: no match, stop it...
+ if (r == AYSTAR_NO_PATH) {
+ DEBUG(ai,1)("[AiNew] PathFinder found no route!");
+ // Start all over again...
+ p->ainew.state = AI_STATE_NOTHING;
+ return;
+ }
+ if (r == AYSTAR_FOUND_END_NODE) {
+ // We found the end-point
+ p->ainew.temp = -1;
+ p->ainew.state = AI_STATE_FIND_DEPOT;
+ return;
+ }
+ // In any other case, we are still busy finding the route...
+}
+
+
+// This function tries to locate a good place for a depot!
+static void AiNew_State_FindDepot(Player *p)
+{
+ // 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!
+ // To make the depot stand in the middle of the route, we start from the center..
+ // But first we walk through the route see if we can find a depot that is ours
+ // this keeps things nice ;)
+ int g, i, j, r;
+ TileIndex tile;
+ assert(p->ainew.state == AI_STATE_FIND_DEPOT);
+
+ p->ainew.depot_tile = 0;
+
+ for (i=2;i<p->ainew.path_info.route_length-2;i++) {
+ tile = p->ainew.path_info.route[i];
+ for (j = 0; j < 4; j++) {
+ if (IsTileType(tile + TileOffsByDir(j), MP_STREET)) {
+ // Its a street, test if it is a depot
+ if (_m[tile + TileOffsByDir(j)].m5 & 0x20) {
+ // We found a depot, is it ours? (TELL ME!!!)
+ if (IsTileOwner(tile + TileOffsByDir(j), _current_player)) {
+ // Now, is it pointing to the right direction.........
+ if ((_m[tile + TileOffsByDir(j)].m5 & 3) == (j ^ 2)) {
+ // Yeah!!!
+ p->ainew.depot_tile = tile + TileOffsByDir(j);
+ p->ainew.depot_direction = j ^ 2; // Reverse direction
+ p->ainew.state = AI_STATE_VERIFY_ROUTE;
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // This routine let depot finding start in the middle, and work his way to the stations
+ // It makes depot placing nicer :)
+ i = p->ainew.path_info.route_length / 2;
+ g = 1;
+ while (i > 1 && i < p->ainew.path_info.route_length - 2) {
+ i += g;
+ g *= -1;
+ (g < 0?g--:g++);
+
+ if (p->ainew.path_info.route_extra[i] != 0 || p->ainew.path_info.route_extra[i+1] != 0) {
+ // Bridge or tunnel.. we can't place a depot there
+ continue;
+ }
+
+ tile = p->ainew.path_info.route[i];
+
+ for (j = 0; j < 4; j++) {
+ // 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 (tile + TileOffsByDir(j) == p->ainew.path_info.route[i-1] ||
+ tile + TileOffsByDir(j) == p->ainew.path_info.route[i+1])
+ continue;
+ // Not around a bridge?
+ if (p->ainew.path_info.route_extra[i] != 0) continue;
+ if (IsTileType(tile, MP_TUNNELBRIDGE)) continue;
+ // Is the terrain clear?
+ if (IsTileType(tile + TileOffsByDir(j), MP_CLEAR) ||
+ IsTileType(tile + TileOffsByDir(j), MP_TREES)) {
+ TileInfo ti;
+ FindLandscapeHeightByTile(&ti, tile);
+ // If the current tile is on a slope (tileh != 0) then we do not allow this
+ if (ti.tileh != 0) continue;
+ // Check if everything went okay..
+ r = AiNew_Build_Depot(p, tile + TileOffsByDir(j), j ^ 2, 0);
+ if (r == CMD_ERROR) continue;
+ // Found a spot!
+ p->ainew.new_cost += r;
+ p->ainew.depot_tile = tile + TileOffsByDir(j);
+ p->ainew.depot_direction = j ^ 2; // Reverse direction
+ p->ainew.state = AI_STATE_VERIFY_ROUTE;
+ return;
+ }
+ }
+ }
+
+ // Failed to find a depot?
+ p->ainew.state = AI_STATE_NOTHING;
+}
+
+
+// This function calculates how many vehicles there are needed on this
+// traject.
+// 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)
+{
+ if (p->ainew.tbt == AI_BUS) {
+ // For bus-routes we look at the time before we are back in the station
+ int i, length, tiles_a_day;
+ int amount;
+ i = AiNew_PickVehicle(p);
+ if (i == -1) return 0;
+ // Passenger run.. how long is the route?
+ length = p->ainew.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;
+ // We want a vehicle in a station once a month at least, so, calculate it!
+ // (the * 2 is because we have 2 stations ;))
+ amount = length * 2 * 2 / tiles_a_day / 30;
+ if (amount == 0) amount = 1;
+ return amount;
+ } else if (p->ainew.tbt == AI_TRUCK) {
+ // For truck-routes we look at the cargo
+ int i, length, amount, tiles_a_day;
+ int max_cargo;
+ i = AiNew_PickVehicle(p);
+ if (i == -1) return 0;
+ // Passenger run.. how long is the route?
+ length = p->ainew.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 (p->ainew.from_deliver)
+ max_cargo = GetIndustry(p->ainew.from_ic)->total_production[0];
+ else
+ max_cargo = GetIndustry(p->ainew.to_ic)->total_production[0];
+
+ // This is because moving 60% is more than we can dream of!
+ max_cargo *= 0.6;
+ // We want all the cargo to be gone in a month.. so, we know the cargo it delivers
+ // we know what the vehicle takes with him, and we know the time it takes him
+ // to get back here.. now let's do some math!
+ amount = 2 * length * max_cargo / tiles_a_day / 30 / RoadVehInfo(i)->capacity;
+ amount += 1;
+ return amount;
+ } else {
+ // Currently not supported
+ return 0;
+ }
+}
+
+
+// This function checks:
+// - 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)
+{
+ int res, i;
+ assert(p->ainew.state == AI_STATE_VERIFY_ROUTE);
+
+ // Let's calculate the cost of the path..
+ // new_cost already contains the cost of the stations
+ p->ainew.path_info.position = -1;
+
+ do {
+ p->ainew.path_info.position++;
+ p->ainew.new_cost += AiNew_Build_RoutePart(p, &p->ainew.path_info, DC_QUERY_COST);
+ } while (p->ainew.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);
+ // If res == 0, no vehicle was found, or an other problem did occour
+ if (res == 0) {
+ p->ainew.state = AI_STATE_NOTHING;
+ return;
+ }
+ p->ainew.amount_veh = res;
+ p->ainew.cur_veh = 0;
+
+ // Check how much it it going to cost us..
+ for (i=0;i<res;i++) {
+ p->ainew.new_cost += AiNew_Build_Vehicle(p, 0, DC_QUERY_COST);
+ }
+
+ // Now we know how much the route is going to cost us
+ // Check if we have enough money for it!
+ if (p->ainew.new_cost > p->player_money - AI_MINIMUM_MONEY) {
+ // Too bad..
+ DEBUG(ai,1)("[AiNew] Can't pay for this route (%d)", p->ainew.new_cost);
+ p->ainew.state = AI_STATE_NOTHING;
+ return;
+ }
+
+ // Now we can build the route, check the direction of the stations!
+ if (p->ainew.from_direction == AI_PATHFINDER_NO_DIRECTION) {
+ p->ainew.from_direction = AiNew_GetDirection(p->ainew.path_info.route[p->ainew.path_info.route_length-1], p->ainew.path_info.route[p->ainew.path_info.route_length-2]);
+ }
+ if (p->ainew.to_direction == AI_PATHFINDER_NO_DIRECTION) {
+ p->ainew.to_direction = AiNew_GetDirection(p->ainew.path_info.route[0], p->ainew.path_info.route[1]);
+ }
+ if (p->ainew.from_tile == AI_STATION_RANGE)
+ p->ainew.from_tile = p->ainew.path_info.route[p->ainew.path_info.route_length-1];
+ if (p->ainew.to_tile == AI_STATION_RANGE)
+ p->ainew.to_tile = p->ainew.path_info.route[0];
+
+ p->ainew.state = AI_STATE_BUILD_STATION;
+ p->ainew.temp = 0;
+
+ DEBUG(ai,1)("[AiNew] The route is set and buildable.. going to build it!");
+}
+
+
+// Build the stations
+static void AiNew_State_BuildStation(Player *p)
+{
+ int res = 0;
+ assert(p->ainew.state == AI_STATE_BUILD_STATION);
+ if (p->ainew.temp == 0) {
+ if (!IsTileType(p->ainew.from_tile, MP_STATION))
+ res = AiNew_Build_Station(p, p->ainew.tbt, p->ainew.from_tile, 0, 0, p->ainew.from_direction, DC_EXEC);
+ } else {
+ if (!IsTileType(p->ainew.to_tile, MP_STATION))
+ res = AiNew_Build_Station(p, p->ainew.tbt, p->ainew.to_tile, 0, 0, p->ainew.to_direction, DC_EXEC);
+ p->ainew.state = AI_STATE_BUILD_PATH;
+ }
+ if (res == CMD_ERROR) {
+ DEBUG(ai,0)("[AiNew - BuildStation] Strange but true... station can not be build!");
+ p->ainew.state = AI_STATE_NOTHING;
+ // If the first station _was_ build, destroy it
+ if (p->ainew.temp != 0)
+ DoCommandByTile(p->ainew.from_tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
+ return;
+ }
+ p->ainew.temp++;
+}
+
+
+// Build the path
+static void AiNew_State_BuildPath(Player *p)
+{
+ assert(p->ainew.state == AI_STATE_BUILD_PATH);
+ // p->ainew.temp is set to -1 when this function is called for the first time
+ if (p->ainew.temp == -1) {
+ DEBUG(ai,1)("[AiNew] Starting to build the path..");
+ // Init the counter
+ p->ainew.counter = (4 - _opt.diff.competitor_speed) * AI_BUILDPATH_PAUSE + 1;
+ // Set the position to the startingplace (-1 because in a minute we do ++)
+ p->ainew.path_info.position = -1;
+ // And don't do this again
+ p->ainew.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 (--p->ainew.counter != 0) return;
+ p->ainew.counter = (4 - _opt.diff.competitor_speed) * AI_BUILDPATH_PAUSE + 1;
+
+ // Increase the building position
+ p->ainew.path_info.position++;
+ // Build route
+ AiNew_Build_RoutePart(p, &p->ainew.path_info, DC_EXEC);
+ if (p->ainew.path_info.position == -2) {
+ // This means we are done building!
+
+ if (p->ainew.tbt == AI_TRUCK && !_patches.roadveh_queue) {
+ static const byte _roadbits_by_dir[4] = {2,1,8,4};
+ // 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
+ int dir1, dir2, dir3;
+ TileIndex tile;
+ int i, ret;
+ for (i=0;i<2;i++) {
+ if (i == 0) {
+ tile = p->ainew.from_tile + TileOffsByDir(p->ainew.from_direction);
+ dir1 = p->ainew.from_direction - 1;
+ if (dir1 < 0) dir1 = 3;
+ dir2 = p->ainew.from_direction + 1;
+ if (dir2 > 3) dir2 = 0;
+ dir3 = p->ainew.from_direction;
+ } else {
+ tile = p->ainew.to_tile + TileOffsByDir(p->ainew.to_direction);
+ dir1 = p->ainew.to_direction - 1;
+ if (dir1 < 0) dir1 = 3;
+ dir2 = p->ainew.to_direction + 1;
+ if (dir2 > 3) dir2 = 0;
+ dir3 = p->ainew.to_direction;
+ }
+
+ ret = DoCommandByTile(tile, _roadbits_by_dir[dir1], 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ if (!CmdFailed(ret)) {
+ dir1 = TileOffsByDir(dir1);
+ if (IsTileType(tile + dir1, MP_CLEAR) || IsTileType(tile + dir1, MP_TREES)) {
+ ret = DoCommandByTile(tile+dir1, AiNew_GetRoadDirection(tile, tile+dir1, tile+dir1+dir1), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ if (!CmdFailed(ret)) {
+ if (IsTileType(tile + dir1 + dir1, MP_CLEAR) || IsTileType(tile + dir1 + dir1, MP_TREES))
+ DoCommandByTile(tile+dir1+dir1, AiNew_GetRoadDirection(tile+dir1, tile+dir1+dir1, tile+dir1+dir1+dir1), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ }
+ }
+ }
+
+ ret = DoCommandByTile(tile, _roadbits_by_dir[dir2], 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ if (!CmdFailed(ret)) {
+ dir2 = TileOffsByDir(dir2);
+ if (IsTileType(tile + dir2, MP_CLEAR) || IsTileType(tile + dir2, MP_TREES)) {
+ ret = DoCommandByTile(tile+dir2, AiNew_GetRoadDirection(tile, tile+dir2, tile+dir2+dir2), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ if (!CmdFailed(ret)) {
+ if (IsTileType(tile + dir2 + dir2, MP_CLEAR) || IsTileType(tile + dir2 + dir2, MP_TREES))
+ DoCommandByTile(tile+dir2+dir2, AiNew_GetRoadDirection(tile+dir2, tile+dir2+dir2, tile+dir2+dir2+dir2), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ }
+ }
+ }
+
+ ret = DoCommandByTile(tile, _roadbits_by_dir[dir3^2], 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ if (!CmdFailed(ret)) {
+ dir3 = TileOffsByDir(dir3);
+ if (IsTileType(tile + dir3, MP_CLEAR) || IsTileType(tile + dir3, MP_TREES)) {
+ ret = DoCommandByTile(tile+dir3, AiNew_GetRoadDirection(tile, tile+dir3, tile+dir3+dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ if (!CmdFailed(ret)) {
+ if (IsTileType(tile + dir3 + dir3, MP_CLEAR) || IsTileType(tile + dir3 + dir3, MP_TREES))
+ DoCommandByTile(tile+dir3+dir3, AiNew_GetRoadDirection(tile+dir3, tile+dir3+dir3, tile+dir3+dir3+dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+ }
+ }
+ }
+ }
+ }
+
+
+ DEBUG(ai,1)("[AiNew] Done building the path (cost: %d)", p->ainew.new_cost);
+ p->ainew.state = AI_STATE_BUILD_DEPOT;
+ }
+}
+
+
+// Builds the depot
+static void AiNew_State_BuildDepot(Player *p)
+{
+ int res = 0;
+ assert(p->ainew.state == AI_STATE_BUILD_DEPOT);
+
+ if (IsTileType(p->ainew.depot_tile, MP_STREET) && _m[p->ainew.depot_tile].m5 & 0x20) {
+ if (IsTileOwner(p->ainew.depot_tile, _current_player)) {
+ // The depot is already builded!
+ p->ainew.state = AI_STATE_BUILD_VEHICLE;
+ return;
+ } else {
+ // There is a depot, but not of our team! :(
+ p->ainew.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 (!EnsureNoVehicle(p->ainew.depot_tile + TileOffsByDir(p->ainew.depot_direction)))
+ return;
+
+ res = AiNew_Build_Depot(p, p->ainew.depot_tile, p->ainew.depot_direction, DC_EXEC);
+ if (res == CMD_ERROR) {
+ DEBUG(ai,0)("[AiNew - BuildDepot] Strange but true... depot can not be build!");
+ p->ainew.state = AI_STATE_NOTHING;
+ return;
+ }
+
+ p->ainew.state = AI_STATE_BUILD_VEHICLE;
+ p->ainew.idle = 1;
+ p->ainew.veh_main_id = (VehicleID)-1;
+}
+
+
+// Build vehicles
+static void AiNew_State_BuildVehicle(Player *p)
+{
+ int res;
+ assert(p->ainew.state == AI_STATE_BUILD_VEHICLE);
+
+ // Check if we need to build a vehicle
+ if (p->ainew.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.. :)
+ p->ainew.state = AI_STATE_ACTION_DONE;
+ return;
+ }
+ if (--p->ainew.idle != 0) return;
+ // It is realistic that the AI can only build 1 vehicle a day..
+ // This makes sure of that!
+ p->ainew.idle = AI_BUILD_VEHICLE_TIME_BETWEEN;
+
+ // Build the vehicle
+ res = AiNew_Build_Vehicle(p, p->ainew.depot_tile, DC_EXEC);
+ if (res == CMD_ERROR) {
+ // This happens when the AI can't build any more vehicles!
+ p->ainew.state = AI_STATE_NOTHING;
+ return;
+ }
+ // Increase the current counter
+ p->ainew.cur_veh++;
+ // Decrease the total counter
+ p->ainew.amount_veh--;
+ // Get the new ID
+ if (p->ainew.tbt == AI_TRAIN) {
+ } else {
+ p->ainew.veh_id = _new_roadveh_id;
+ }
+ // Go give some orders!
+ p->ainew.state = AI_STATE_GIVE_ORDERS;
+}
+
+
+// Put the stations in the order list
+static void AiNew_State_GiveOrders(Player *p)
+{
+ int idx;
+ Order order;
+
+ assert(p->ainew.state == AI_STATE_GIVE_ORDERS);
+
+ if (p->ainew.veh_main_id != (VehicleID)-1) {
+ DoCommandByTile(0, p->ainew.veh_id + (p->ainew.veh_main_id << 16), 0, DC_EXEC, CMD_CLONE_ORDER);
+
+ // Skip the first order if it is a second vehicle
+ // This to make vehicles go different ways..
+ if (p->ainew.veh_id & 1)
+ DoCommandByTile(0, p->ainew.veh_id, 0, DC_EXEC, CMD_SKIP_ORDER);
+ p->ainew.state = AI_STATE_START_VEHICLE;
+ return;
+ } else {
+ p->ainew.veh_main_id = p->ainew.veh_id;
+ }
+
+ // When more than 1 vehicle, we send them to different directions
+ idx = 0;
+ order.type = OT_GOTO_STATION;
+ order.flags = 0;
+ order.station = _m[p->ainew.from_tile].m2;
+ if (p->ainew.tbt == AI_TRUCK && p->ainew.from_deliver)
+ order.flags |= OF_FULL_LOAD;
+ DoCommandByTile(0, p->ainew.veh_id + (idx << 16), PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
+
+ idx = 1;
+ order.type = OT_GOTO_STATION;
+ order.flags = 0;
+ order.station = _m[p->ainew.to_tile].m2;
+ if (p->ainew.tbt == AI_TRUCK && p->ainew.to_deliver)
+ order.flags |= OF_FULL_LOAD;
+ DoCommandByTile(0, p->ainew.veh_id + (idx << 16), PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
+
+ // Very handy for AI, goto depot.. but yeah, it needs to be activated ;)
+ if (_patches.gotodepot) {
+ idx = 2;
+ order.type = OT_GOTO_DEPOT;
+ order.flags = OF_UNLOAD;
+ order.station = GetDepotByTile(p->ainew.depot_tile)->index;
+ DoCommandByTile(0, p->ainew.veh_id + (idx << 16), PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
+ }
+
+ // Start the engines!
+ p->ainew.state = AI_STATE_START_VEHICLE;
+}
+
+
+// Start the vehicle
+static void AiNew_State_StartVehicle(Player *p)
+{
+ assert(p->ainew.state == AI_STATE_START_VEHICLE);
+
+ // 3, 2, 1... go! (give START_STOP command ;))
+ DoCommandByTile(0, p->ainew.veh_id, 0, DC_EXEC, CMD_START_STOP_ROADVEH);
+ // Try to build an other vehicle (that function will stop building when needed)
+ p->ainew.state = AI_STATE_BUILD_VEHICLE;
+}
+
+
+// Repays money
+static void AiNew_State_RepayMoney(Player *p)
+{
+ int i;
+ for (i=0;i<AI_LOAN_REPAY;i++)
+ DoCommandByTile(0, 0, 0, DC_EXEC, CMD_DECREASE_LOAN);
+ p->ainew.state = AI_STATE_ACTION_DONE;
+}
+
+
+static void AiNew_CheckVehicle(Player *p, Vehicle *v)
+{
+ // When a vehicle is under the 6 months, we don't check for anything
+ if (v->age < 180) return;
+
+ // When a vehicle is older then 1 year, it should make money...
+ if (v->age > 360) {
+ // If both years together are not more than AI_MINIMUM_ROUTE_PROFIT,
+ // it is not worth the line I guess...
+ if (v->profit_last_year + v->profit_this_year < AI_MINIMUM_ROUTE_PROFIT ||
+ (v->reliability * 100 >> 16) < 40) {
+ // There is a possibility that the route is fucked up...
+ if (v->cargo_days > AI_VEHICLE_LOST_DAYS) {
+ // The vehicle is lost.. check the route, or else, get the vehicle
+ // back to a depot
+ // TODO: make this piece of code
+ }
+
+
+ // We are already sending him back
+ if (AiNew_GetSpecialVehicleFlag(p, v) & AI_VEHICLEFLAG_SELL) {
+ if (v->type == VEH_Road && IsTileDepotType(v->tile, TRANSPORT_ROAD) &&
+ (v->vehstatus&VS_STOPPED)) {
+ // We are at the depot, sell the vehicle
+ DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH);
+ }
+ return;
+ }
+
+ if (!AiNew_SetSpecialVehicleFlag(p, v, AI_VEHICLEFLAG_SELL)) return;
+ {
+ int ret = 0;
+ if (v->type == VEH_Road)
+ ret = DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SEND_ROADVEH_TO_DEPOT);
+ // This means we can not find a depot :s
+ // if (CmdFailed(ret))
+ }
+ }
+ }
+}
+
+
+// Checks all vehicles if they are still valid and make money and stuff
+static void AiNew_State_CheckAllVehicles(Player *p)
+{
+ Vehicle *v;
+
+ FOR_ALL_VEHICLES(v) {
+ if (v->type == 0) continue;
+ if (v->owner != p->index) continue;
+ // Currently, we only know how to handle road-vehicles
+ if (v->type != VEH_Road) continue;
+
+ AiNew_CheckVehicle(p, v);
+ }
+
+ p->ainew.state = AI_STATE_ACTION_DONE;
+}
+
+
+// Using the technique simular to the original AI
+// Keeps things logical
+// It really should be in the same order as the AI_STATE's are!
+static AiNew_StateFunction* const _ainew_state[] = {
+ NULL,
+ AiNew_State_FirstTime,
+ AiNew_State_Nothing,
+ AiNew_State_WakeUp,
+ AiNew_State_LocateRoute,
+ AiNew_State_FindStation,
+ AiNew_State_FindPath,
+ AiNew_State_FindDepot,
+ AiNew_State_VerifyRoute,
+ AiNew_State_BuildStation,
+ AiNew_State_BuildPath,
+ AiNew_State_BuildDepot,
+ AiNew_State_BuildVehicle,
+ AiNew_State_GiveOrders,
+ AiNew_State_StartVehicle,
+ AiNew_State_RepayMoney,
+ AiNew_State_CheckAllVehicles,
+ AiNew_State_ActionDone,
+ NULL,
+};
+
+static void AiNew_OnTick(Player *p)
+{
+ if (_ainew_state[p->ainew.state] != NULL)
+ _ainew_state[p->ainew.state](p);
+}
+
+
+void AiNewDoGameLoop(Player *p)
+{
+ // If it is a human player, it is not an AI, so bubye!
+ if (IS_HUMAN_PLAYER(_current_player)) return;
+
+ if (p->ainew.state == AI_STATE_STARTUP) {
+ // The AI just got alive!
+ p->ainew.state = AI_STATE_FIRST_TIME;
+ p->ainew.tick = 0;
+
+ // Only startup the AI
+ return;
+ }
+
+ // We keep a ticker. We use it for competitor_speed
+ p->ainew.tick++;
+
+ // See what the speed is
+ switch (_opt.diff.competitor_speed) {
+ case 0: // Very slow
+ if (!(p->ainew.tick&8)) return;
+ break;
+
+ case 1: // Slow
+ if (!(p->ainew.tick&4)) return;
+ break;
+
+ case 2:
+ if (!(p->ainew.tick&2)) return;
+ break;
+
+ case 3:
+ if (!(p->ainew.tick&1)) return;
+ break;
+
+ case 4: // Very fast
+ default: // Cool, a new speed setting.. ;) VERY fast ;)
+ break;
+ }
+
+ // If we come here, we can do a tick.. do so!
+ AiNew_OnTick(p);
+}
diff --git a/ai/trolly/trolly.h b/ai/trolly/trolly.h
new file mode 100644
index 000000000..901448dde
--- /dev/null
+++ b/ai/trolly/trolly.h
@@ -0,0 +1,261 @@
+/* $Id: ai_new.h 2892 2005-08-26 20:56:48Z tron $ */
+
+#ifndef AI_TROLLY_H
+#define AI_TROLLY_H
+
+#include "../../aystar.h"
+#include "../../player.h"
+
+/*
+ * These defines can be altered to change the behavoir of the AI
+ *
+ * WARNING:
+ * This can also alter the AI in a negative way. I will never claim these settings
+ * are perfect, but don't change them if you don't know what the effect is.
+ */
+
+// How many times it the H multiplied. The higher, the more it will go straight to the
+// end point. The lower, how more it will find the route with the lowest cost.
+// also: the lower, the longer it takes before route is calculated..
+#define AI_PATHFINDER_H_MULTIPLER 100
+
+// How many loops may AyStar do before it stops
+// 0 = infinite
+#define AI_PATHFINDER_LOOPS_PER_TICK 5
+
+// How long may the AI search for one route?
+// 0 = infinite
+// This number is the number of tiles tested.
+// It takes (AI_PATHFINDER_MAX_SEARCH_NODES / AI_PATHFINDER_LOOPS_PER_TICK) ticks
+// to get here.. with 5000 / 10 = 500. 500 / 74 (one day) = 8 days till it aborts
+// (that is: if the AI is on VERY FAST! :p
+#define AI_PATHFINDER_MAX_SEARCH_NODES 5000
+
+// If you enable this, the AI is not allowed to make 90degree turns
+#define AI_PATHFINDER_NO_90DEGREES_TURN
+
+// Below are defines for the g-calculation
+
+// Standard penalty given to a tile
+#define AI_PATHFINDER_PENALTY 150
+// The penalty given to a tile that is going up
+#define AI_PATHFINDER_TILE_GOES_UP_PENALTY 450
+// The penalty given to a tile which would have to use fundation
+#define AI_PATHFINDER_FOUNDATION_PENALTY 100
+// Changing direction is a penalty, to prevent curved ways (with that: slow ways)
+#define AI_PATHFINDER_DIRECTION_CHANGE_PENALTY 200
+// Same penalty, only for when road already exists
+#define AI_PATHFINDER_DIRECTION_CHANGE_ON_EXISTING_ROAD_PENALTY 50
+// A diagonal track cost the same as a straigh, but a diagonal is faster... so give
+// a bonus for using diagonal track
+#ifdef AI_PATHFINDER_NO_90DEGREES_TURN
+#define AI_PATHFINDER_DIAGONAL_BONUS 95
+#else
+#define AI_PATHFINDER_DIAGONAL_BONUS 75
+#endif
+// If a roadblock already exists, it gets a bonus
+#define AI_PATHFINDER_ROAD_ALREADY_EXISTS_BONUS 140
+// To prevent 3 direction changes in 3 tiles, this penalty is given in such situation
+#define AI_PATHFINDER_CURVE_PENALTY 200
+
+// Penalty a bridge gets per length
+#define AI_PATHFINDER_BRIDGE_PENALTY 180
+// The penalty for a bridge going up
+#define AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY 1000
+
+// Tunnels are expensive...
+// Because of that, every tile the cost is increased with 1/8th of his value
+// This is also true if you are building a tunnel yourself
+#define AI_PATHFINDER_TUNNEL_PENALTY 350
+
+/*
+ * Ai_New defines
+ */
+
+// How long may we search cities and industry for a new route?
+#define AI_LOCATE_ROUTE_MAX_COUNTER 200
+
+// How many days must there be between building the first station and the second station
+// within one city. This number is in days and should be more than 4 months.
+#define AI_CHECKCITY_DATE_BETWEEN 180
+
+// How many cargo is needed for one station in a city?
+#define AI_CHECKCITY_CARGO_PER_STATION 60
+// How much cargo must there not be used in a city before we can build a new station?
+#define AI_CHECKCITY_NEEDED_CARGO 50
+// When there is already a station which takes the same good and the rating of that
+// city is higher then this numer, we are not going to attempt to build anything
+// there
+#define AI_CHECKCITY_CARGO_RATING 50
+// But, there is a chance of 1 out of this number, that we do ;)
+#define AI_CHECKCITY_CARGO_RATING_CHANCE 5
+// If a city is too small to contain a station, there is a small chance
+// that we still do so.. just to make the city bigger!
+#define AI_CHECKCITY_CITY_CHANCE 5
+
+// This number indicates for every unit of cargo, how many tiles two stations maybe be away
+// from eachother. In other words: if we have 120 units of cargo in one station, and 120 units
+// of the cargo in the other station, both stations can be 96 units away from eachother, if the
+// next number is 0.4.
+#define AI_LOCATEROUTE_BUS_CARGO_DISTANCE 0.4
+#define AI_LOCATEROUTE_TRUCK_CARGO_DISTANCE 0.7
+// In whole tiles, the minimum distance for a truck route
+#define AI_LOCATEROUTE_TRUCK_MIN_DISTANCE 30
+
+// The amount of tiles in a square from -X to +X that is scanned for a station spot
+// (so if this number is 10, 20x20 = 400 tiles are scanned for _the_ perfect spot
+// Safe values are between 15 and 5
+#define AI_FINDSTATION_TILE_RANGE 10
+
+// Building on normal speed goes very fast. Idle this amount of ticks between every
+// building part. It is calculated like this: (4 - competitor_speed) * num + 1
+// where competitor_speed is between 0 (very slow) to 4 (very fast)
+#define AI_BUILDPATH_PAUSE 10
+
+// 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
+#define AI_MINIMUM_MONEY 15000
+
+// If the most cheap route is build, how much is it going to cost..
+// This is to prevent the AI from trying to build a route which can not be paid for
+#define AI_MINIMUM_BUS_ROUTE_MONEY 25000
+#define AI_MINIMUM_TRUCK_ROUTE_MONEY 35000
+
+// The minimum amount of money before we are going to repay any money
+#define AI_MINIMUM_LOAN_REPAY_MONEY 40000
+// How many repays do we do if we have enough money to do so?
+// Every repay is 10000
+#define AI_LOAN_REPAY 2
+// How much income must we have before paying back a loan? Month-based (and looked at the last month)
+#define AI_MINIMUM_INCOME_FOR_LOAN 7000
+
+// If there is <num> time as much cargo in the station then the vehicle can handle
+// reuse the station instead of building a new one!
+#define AI_STATION_REUSE_MULTIPLER 2
+
+// No more than this amount of vehicles per station..
+#define AI_CHECK_MAX_VEHICLE_PER_STATION 10
+
+// How many thick between building 2 vehicles
+#define AI_BUILD_VEHICLE_TIME_BETWEEN DAY_TICKS
+
+// 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
+#define AI_DAYS_BETWEEN_VEHICLE_CHECKS 30
+
+// How money profit does a vehicle needs to make to stay in order
+// This is the profit of this year + profit of last year
+// But also for vehicles that are just one year old. In other words:
+// Vehicles of 2 years do easier meet this setting then vehicles
+// of one year. This is a very good thing. New vehicles are filtered,
+// while old vehicles stay longer, because we do get less in return.
+#define AI_MINIMUM_ROUTE_PROFIT 1000
+
+// A vehicle is considered lost when he his cargo is more than 180 days old
+#define AI_VEHICLE_LOST_DAYS 180
+
+// How many times may the AI try to find a route before it gives up
+#define AI_MAX_TRIES_FOR_SAME_ROUTE 8
+
+/*
+ * End of defines
+ */
+
+// This stops 90degrees curves
+static const byte _illegal_curves[6] = {
+ 255, 255, // Horz and vert, don't have the effect
+ 5, // upleft and upright are not valid
+ 4, // downright and downleft are not valid
+ 2, // downleft and upleft are not valid
+ 3, // upright and downright are not valid
+};
+
+enum {
+ AI_STATE_STARTUP = 0,
+ AI_STATE_FIRST_TIME,
+ AI_STATE_NOTHING,
+ AI_STATE_WAKE_UP,
+ AI_STATE_LOCATE_ROUTE,
+ AI_STATE_FIND_STATION,
+ AI_STATE_FIND_PATH,
+ AI_STATE_FIND_DEPOT,
+ AI_STATE_VERIFY_ROUTE,
+ AI_STATE_BUILD_STATION,
+ AI_STATE_BUILD_PATH,
+ AI_STATE_BUILD_DEPOT,
+ AI_STATE_BUILD_VEHICLE,
+ AI_STATE_GIVE_ORDERS,
+ AI_STATE_START_VEHICLE,
+ AI_STATE_REPAY_MONEY,
+ AI_STATE_CHECK_ALL_VEHICLES,
+ AI_STATE_ACTION_DONE,
+ AI_STATE_STOP, // Temporary function to stop the AI
+};
+
+// Used for tbt (train/bus/truck)
+enum {
+ AI_TRAIN = 0,
+ AI_BUS,
+ AI_TRUCK,
+};
+
+enum {
+ AI_ACTION_NONE = 0,
+ AI_ACTION_BUS_ROUTE,
+ AI_ACTION_TRUCK_ROUTE,
+ AI_ACTION_REPAY_LOAN,
+ AI_ACTION_CHECK_ALL_VEHICLES,
+};
+
+// Used for from_type/to_type
+enum {
+ AI_NO_TYPE = 0,
+ AI_CITY,
+ AI_INDUSTRY,
+};
+
+// Flags for in the vehicle
+enum {
+ AI_VEHICLEFLAG_SELL = 1,
+ // Remember, flags must be in power of 2
+};
+
+#define AI_NO_CARGO 0xFF // Means that there is no cargo defined yet (used for industry)
+#define AI_NEED_CARGO 0xFE // Used when the AI needs to find out a cargo for the route
+#define AI_STATION_RANGE TileXY(MapMaxX(), MapMaxY())
+
+#define AI_PATHFINDER_NO_DIRECTION (byte)-1
+
+// Flags used in user_data
+#define AI_PATHFINDER_FLAG_BRIDGE 1
+#define AI_PATHFINDER_FLAG_TUNNEL 2
+
+typedef void AiNew_StateFunction(Player *p);
+
+// ai_new.c
+void AiNewDoGameLoop(Player *p);
+
+// ai_pathfinder.c
+AyStar *new_AyStar_AiPathFinder(int max_tiles_around, Ai_PathFinderInfo *PathFinderInfo);
+void clean_AyStar_AiPathFinder(AyStar *aystar, Ai_PathFinderInfo *PathFinderInfo);
+
+// ai_shared.c
+int AiNew_GetRailDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c);
+int AiNew_GetRoadDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c);
+int AiNew_GetDirection(TileIndex tile_a, TileIndex tile_b);
+bool AiNew_SetSpecialVehicleFlag(Player *p, Vehicle *v, uint flag);
+uint AiNew_GetSpecialVehicleFlag(Player *p, Vehicle *v);
+
+// ai_build.c
+bool AiNew_Build_CompanyHQ(Player *p, TileIndex tile);
+int AiNew_Build_Station(Player *p, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag);
+int AiNew_Build_Bridge(Player *p, TileIndex tile_a, TileIndex tile_b, byte flag);
+int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte flag);
+int AiNew_PickVehicle(Player *p);
+int AiNew_Build_Vehicle(Player *p, TileIndex tile, byte flag);
+int AiNew_Build_Depot(Player *p, TileIndex tile, byte direction, byte flag);
+
+#endif /* AI_TROLLY_H */