From a3dd7506d377b1434f913bd65c019eed52b64b6e Mon Sep 17 00:00:00 2001 From: truebrain Date: Mon, 12 Jan 2009 17:11:45 +0000 Subject: (svn r15027) -Merge: tomatos and bananas left to be, here is NoAI for all to see. NoAI is an API (a framework) to build your own AIs in. See: http://wiki.openttd.org/wiki/index.php/AI:Main_Page With many thanks to: - glx and Rubidium for their syncing, feedback and hard work - Yexo for his feedback, patches, and AIs which tested the system very deep - Morloth for his feedback and patches - TJIP for hosting a challenge which kept NoAI on track - All AI authors for testing our AI API, and all other people who helped in one way or another -Remove: all old AIs and their cheats/hacks --- src/ai/trolly/build.cpp | 328 ---------- src/ai/trolly/pathfinder.cpp | 482 --------------- src/ai/trolly/shared.cpp | 121 ---- src/ai/trolly/trolly.cpp | 1348 ------------------------------------------ src/ai/trolly/trolly.h | 344 ----------- 5 files changed, 2623 deletions(-) delete mode 100644 src/ai/trolly/build.cpp delete mode 100644 src/ai/trolly/pathfinder.cpp delete mode 100644 src/ai/trolly/shared.cpp delete mode 100644 src/ai/trolly/trolly.cpp delete mode 100644 src/ai/trolly/trolly.h (limited to 'src/ai/trolly') diff --git a/src/ai/trolly/build.cpp b/src/ai/trolly/build.cpp deleted file mode 100644 index 0723386f7..000000000 --- a/src/ai/trolly/build.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/* $Id$ */ - -/** @file build.cpp Building support for the trolly AI. */ - -#include "../../stdafx.h" -#include "../../openttd.h" -#include "../../debug.h" -#include "../../road_map.h" -#include "../../command_func.h" -#include "trolly.h" -#include "../../engine_func.h" -#include "../../engine_base.h" -#include "../../variables.h" -#include "../../bridge.h" -#include "../../vehicle_func.h" -#include "../../vehicle_base.h" -#include "../../company_base.h" -#include "../../company_func.h" -#include "../ai.h" -#include "../../tunnelbridge.h" - - -// Build HQ -// Params: -// tile : tile where HQ is going to be build -bool AiNew_Build_CompanyHQ(Company *c, TileIndex tile) -{ - if (CmdFailed(AI_DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ))) - return false; - AI_DoCommand(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) -CommandCost AiNew_Build_Station(Company *c, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag) -{ - if (type == AI_TRAIN) - return AI_DoCommand(tile, (direction << 4) + (numtracks << 8) + (length << 16), INVALID_STATION << 16, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_RAILROAD_STATION); - - if (type == AI_BUS) - return AI_DoCommand(tile, direction, ROADTYPES_ROAD << 2 | ROADSTOP_BUS | INVALID_STATION << 16, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_STOP); - - return AI_DoCommand(tile, direction, ROADTYPES_ROAD << 2 | ROADSTOP_TRUCK | INVALID_STATION << 16, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_STOP); -} - - -// Builds a brdige. The second best out of the ones available for this company -// Params: -// tile_a : starting point -// tile_b : end point -// flag : flag passed to DoCommand -CommandCost AiNew_Build_Bridge(Company *c, 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 = GetTunnelBridgeLength(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 built - if (type2 == 0 && type != 0) type2 = type; - - // Now, simply, build the bridge! - if (_companies_ainew[c->index].tbt == AI_TRAIN) { - return AI_DoCommand(tile_a, tile_b, type2 | RAILTYPE_RAIL << 8 | TRANSPORT_RAIL << 15, flag | DC_AUTO, CMD_BUILD_BRIDGE); - } else { - return AI_DoCommand(tile_a, tile_b, type2 | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, flag | DC_AUTO, CMD_BUILD_BRIDGE); - } -} - - -// 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) -CommandCost AiNew_Build_RoutePart(Company *c, 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; - CommandCost cost; - CommandCost 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 CommandCost(); - } - - - if (PathFinderInfo->rail_or_road) { - // Tunnel code - if ((AI_PATHFINDER_FLAG_TUNNEL & route_extra[part]) != 0) { - cost.AddCost(AI_DoCommand(route[part], 0, 0, flag, CMD_BUILD_TUNNEL)); - PathFinderInfo->position++; - // TODO: problems! - if (CmdFailed(cost)) { - DEBUG(ai, 0, "[BuildPath] tunnel could not be built (0x%X)", route[part]); - return CommandCost(); - } - return cost; - } - // Bridge code - if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) { - cost.AddCost(AiNew_Build_Bridge(c, route[part], route[part - 1], flag)); - PathFinderInfo->position++; - // TODO: problems! - if (CmdFailed(cost)) { - DEBUG(ai, 0, "[BuildPath] bridge could not be built (0x%X, 0x%X)", route[part], route[part - 1]); - return CommandCost(); - } - 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 = AI_DoCommand(route[part], 0, dir, flag, CMD_BUILD_SINGLE_RAIL); - if (CmdFailed(res)) { - // Problem.. let's just abort it all! - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return CommandCost(); - } - cost.AddCost(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.AddCost(AI_DoCommand(route[part], 0x200 | ROADTYPES_ROAD, 0, flag, CMD_BUILD_TUNNEL)); - PathFinderInfo->position++; - // TODO: problems! - if (CmdFailed(cost)) { - DEBUG(ai, 0, "[BuildPath] tunnel could not be built (0x%X)", route[part]); - return CommandCost(); - } - return cost; - } - // Bridge code - if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) { - cost.AddCost(AiNew_Build_Bridge(c, route[part], route[part + 1], flag)); - PathFinderInfo->position++; - // TODO: problems! - if (CmdFailed(cost)) { - DEBUG(ai, 0, "[BuildPath] bridge could not be built (0x%X, 0x%X)", route[part], route[part + 1]); - return CommandCost(); - } - return cost; - } - - // Build normal road - // Keep it doing till we go an other way - // EnsureNoVehicleOnGround 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 || EnsureNoVehicleOnGround(route[part]))) { - while (route_extra[part] == 0 && (flag != DC_EXEC || EnsureNoVehicleOnGround(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 = AI_DoCommand(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_ROAD) && !EnsureNoVehicleOnGround(route[part])) { - // Problem.. let's just abort it all! - DEBUG(ai, 0, "[BuidPath] route building failed at tile 0x%X, aborting", route[part]); - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return CommandCost(); - } - - if (CmdSucceeded(res)) cost.AddCost(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 (!EnsureNoVehicleOnGround(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 INVALID_ENGINE if not suitable engine is found -EngineID AiNew_PickVehicle(Company *c) -{ - if (_companies_ainew[c->index].tbt == AI_TRAIN) { - // Not supported yet - return INVALID_ENGINE; - } else { - EngineID best_veh_index = INVALID_ENGINE; - int32 best_veh_rating = 0; - const Engine *e; - - /* Loop through all road vehicles */ - FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) { - EngineID i = e->index; - const RoadVehicleInfo *rvi = &e->u.road; - - /* Skip vehicles which can't take our cargo type */ - if (rvi->cargo_type != _companies_ainew[c->index].cargo && !CanRefitTo(i, _companies_ainew[c->index].cargo)) continue; - - /* Skip trams */ - if (HasBit(EngInfo(i)->misc_flags, EF_ROAD_TRAM)) continue; - - // Is it availiable? - // Also, check if the reliability of the vehicle is above the AI_VEHICLE_MIN_RELIABILTY - if (!HasBit(e->company_avail, _current_company) || e->reliability * 100 < AI_VEHICLE_MIN_RELIABILTY << 16) continue; - - /* Rate and compare the engine by speed & capacity */ - int rating = rvi->max_speed * rvi->capacity; - if (rating <= best_veh_rating) continue; - - // Can we build it? - CommandCost ret = AI_DoCommand(0, i, 0, DC_QUERY_COST, CMD_BUILD_ROAD_VEH); - if (CmdFailed(ret)) continue; - - best_veh_rating = rating; - best_veh_index = i; - } - - return best_veh_index; - } -} - - -void CcAI(bool success, TileIndex tile, uint32 p1, uint32 p2) -{ - Company *c = GetCompany(_current_company); - - if (success) { - _companies_ainew[c->index].state = AI_STATE_GIVE_ORDERS; - _companies_ainew[c->index].veh_id = _new_vehicle_id; - - if (GetVehicle(_companies_ainew[c->index].veh_id)->cargo_type != _companies_ainew[c->index].cargo) { - /* Cargo type doesn't match, so refit it */ - if (CmdFailed(DoCommand(tile, _companies_ainew[c->index].veh_id, _companies_ainew[c->index].cargo, DC_EXEC, CMD_REFIT_ROAD_VEH))) { - /* Refit failed, so sell the vehicle */ - DoCommand(tile, _companies_ainew[c->index].veh_id, 0, DC_EXEC, CMD_SELL_ROAD_VEH); - _companies_ainew[c->index].state = AI_STATE_NOTHING; - } - } - } else { - /* XXX this should be handled more gracefully */ - _companies_ainew[c->index].state = AI_STATE_NOTHING; - } -} - - -// Builds the best vehicle possible -CommandCost AiNew_Build_Vehicle(Company *c, TileIndex tile, byte flag) -{ - EngineID i = AiNew_PickVehicle(c); - - if (i == INVALID_ENGINE) return CMD_ERROR; - if (_companies_ainew[c->index].tbt == AI_TRAIN) return CMD_ERROR; - - if (flag & DC_EXEC) { - return AI_DoCommandCc(tile, i, 0, flag, CMD_BUILD_ROAD_VEH, CcAI); - } else { - return AI_DoCommand(tile, i, 0, flag, CMD_BUILD_ROAD_VEH); - } -} - -CommandCost AiNew_Build_Depot(Company *c, TileIndex tile, DiagDirection direction, byte flag) -{ - CommandCost ret, ret2; - if (_companies_ainew[c->index].tbt == AI_TRAIN) { - return AI_DoCommand(tile, 0, direction, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_TRAIN_DEPOT); - } else { - ret = AI_DoCommand(tile, direction, 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_DEPOT); - if (CmdFailed(ret2)) return ret; - // Try to build the road from the depot - ret2 = AI_DoCommand(tile + TileOffsByDiagDir(direction), DiagDirToRoadBits(ReverseDiagDir(direction)), 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD); - // If it fails, ignore it.. - if (CmdFailed(ret2)) return ret; - ret.AddCost(ret2); - return ret; - } -} diff --git a/src/ai/trolly/pathfinder.cpp b/src/ai/trolly/pathfinder.cpp deleted file mode 100644 index 0e08ddf77..000000000 --- a/src/ai/trolly/pathfinder.cpp +++ /dev/null @@ -1,482 +0,0 @@ -/* $Id$ */ - -/** @file pathfinder.cpp Pathfinder support for the trolly AI. */ - -#include "../../stdafx.h" -#include "../../openttd.h" -#include "../../bridge_map.h" -#include "../../debug.h" -#include "../../command_func.h" -#include "trolly.h" -#include "../../tunnel_map.h" -#include "../../bridge.h" -#include "../../tunnelbridge_map.h" -#include "../ai.h" -#include "../../variables.h" -#include "../../company_base.h" -#include "../../company_func.h" -#include "../../tunnelbridge.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) -{ - Company *c = GetCompany(_current_company); - - if (dir == TEST_STATION_NO_DIR) { - CommandCost ret; - // TODO: currently we only allow spots that can be access from al 4 directions... - // should be fixed!!! - for (dir = 0; dir < 4; dir++) { - ret = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, tile, 1, 1, dir, DC_QUERY_COST); - if (CmdSucceeded(ret)) return true; - } - return false; - } - - // return true if command succeeded, so the inverse of CmdFailed() - return CmdSucceeded(AiNew_Build_Station(c, _companies_ainew[c->index].tbt, tile, 1, 1, dir, DC_QUERY_COST)); -} - - -static bool IsRoad(TileIndex tile) -{ - return - // MP_ROAD, but not a road depot? - (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile)) || - (IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD); -} - - -// 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) -{ - const 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); - delete 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 = new 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->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 = INVALID_TRACKDIR; - 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 = INVALID_TRACKDIR; - 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++) { - TileIndex tile = TileXY(x, y); - - if (!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) continue; - if (!TestCanBuildStationHere(tile, TEST_STATION_NO_DIR)) continue; - start_node.node.tile = tile; - aystar->addstart(aystar, &start_node.node, 0); - } - } -} - - -// The h-value, simple calculation -static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent) -{ - const 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 + TileOffsByDiagDir(PathFinderInfo->end_direction)); - r2 = DistanceManhattan(current->tile, PathFinderInfo->end_tile_br + TileOffsByDiagDir(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 = ¤t->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, "No more space in pathfinder 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, "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) -{ - CommandCost 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 (DiagDirection i = DIAGDIR_BEGIN; i < DIAGDIR_END; i++) { - TileIndex ctile = current->path.node.tile; // Current tile - TileIndex atile = ctile + TileOffsByDiagDir(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)) { - if (GetTunnelBridgeDirection(atile) != i) 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 ((uint)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 = AI_DoCommand(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 ((GetAnyRoadBits(ctile, ROADTYPE_ROAD) & dir) != dir) { - // We do miss some pieces :( - dir &= ~GetAnyRoadBits(ctile, ROADTYPE_ROAD); - } else { - dir = 0; - } - } - } - // Only destruct things if it is MP_CLEAR of MP_TREES - if (dir != 0) { - ret = AI_DoCommand(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 = INVALID_TRACKDIR; - } - } - - // Next step, check for bridges and tunnels - if (current->path.parent != NULL && current->path.node.user_data[0] == 0) { - // First we get the dir from this tile and his parent - DiagDirection 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; - Slope tileh = GetTileSlope(tile, NULL); - - // Bridges can only be build on land that is not flat - // And if there is a road or rail blocking - if (tileh != SLOPE_FLAT || - (PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDiagDir(dir), MP_ROAD)) || - (!PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDiagDir(dir), MP_RAILWAY))) { - for (;;) { - new_tile += TileOffsByDiagDir(dir); - - // Precheck, is the length allowed? - if (!CheckBridge_Stuff(0, GetTunnelBridgeLength(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 = AI_DoCommand(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 = INVALID_TRACKDIR; - // 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 built on slopes corresponding to the direction - // For now, we check both sides for this tile.. terraforming gives fuzzy result - if (tileh == InclinedSlope(dir)) { - // Now simply check if a tunnel can be build - ret = AI_DoCommand(tile, (PathFinderInfo->rail_or_road ? 0 : 0x200), 0, DC_AUTO, CMD_BUILD_TUNNEL); - tileh = GetTileSlope(_build_tunnel_endtile, NULL); - if (CmdSucceeded(ret) && IsInclinedSlope(tileh)) { - 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 = INVALID_TRACKDIR; - } - } - } -} - - -extern Foundation GetRailFoundation(Slope tileh, TrackBits bits); // XXX function declaration in .c -extern Foundation GetRoadFoundation(Slope tileh, RoadBits bits); // XXX function declaration in .c - -// 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 res = 0; - Slope tileh = GetTileSlope(current->tile, NULL); - Slope parent_tileh = GetTileSlope(parent->path.node.tile, NULL); - - // 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_tileh != SLOPE_FLAT && 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) { - Foundation f = GetRailFoundation(parent_tileh, (TrackBits)(1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile))); - if (IsInclinedFoundation(f) || (!IsFoundation(f) && IsInclinedSlope(parent_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)) { - Foundation f = GetRoadFoundation(parent_tileh, (RoadBits)AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile)); - if (IsInclinedFoundation(f) || (!IsFoundation(f) && IsInclinedSlope(parent_tileh))) { - 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) { - int r; - // Tunnels are very expensive when build on long routes.. - // Ironicly, we are using BridgeCode here ;) - r = AI_PATHFINDER_TUNNEL_PENALTY * GetTunnelBridgeLength(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 * GetTunnelBridgeLength(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 (!HasBridgeFlatRamp(parent_tileh, (Axis)((current->user_data[0] >> 8) & 1))) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY; - // Second for the end point - if (!HasBridgeFlatRamp(tileh, (Axis)((current->user_data[0] >> 8) & 1))) 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; - } - } - } - } - } - - return (res < 0) ? 0 : res; -} diff --git a/src/ai/trolly/shared.cpp b/src/ai/trolly/shared.cpp deleted file mode 100644 index 1183f0371..000000000 --- a/src/ai/trolly/shared.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* $Id$ */ - -/** @file shared.cpp Shared functions for the trolly AI. */ - -#include "../../stdafx.h" -#include "../../openttd.h" -#include "../../debug.h" -#include "../../map_func.h" -#include "../../vehicle_base.h" -#include "../../company_base.h" -#include "trolly.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 - - uint x1 = TileX(tile_a); - uint x2 = TileX(tile_b); - uint x3 = TileX(tile_c); - - uint y1 = TileY(tile_a); - uint y2 = TileY(tile_b); - uint y3 = TileY(tile_c); - - if (y1 == y2 && y2 == y3) return 0; - if (x1 == x2 && x2 == x3) return 1; - if (y2 > y1) return x2 > x3 ? 2 : 4; - if (x2 > x1) return y2 > y3 ? 2 : 5; - if (y1 > y2) return x2 > x3 ? 5 : 3; - if (x1 > x2) return y2 > y3 ? 4 : 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 -DiagDirection AiNew_GetDirection(TileIndex tile_a, TileIndex tile_b) -{ - if (TileY(tile_a) < TileY(tile_b)) return DIAGDIR_SE; - if (TileY(tile_a) > TileY(tile_b)) return DIAGDIR_NW; - if (TileX(tile_a) < TileX(tile_b)) return DIAGDIR_SW; - return DIAGDIR_NE; -} - - -// This functions looks up if this vehicle is special for this AI -// and returns his flag -uint AiNew_GetSpecialVehicleFlag(Company *c, Vehicle *v) -{ - uint i; - - for (i = 0; i < AI_MAX_SPECIAL_VEHICLES; i++) { - if (_companies_ainew[c->index].special_vehicles[i].veh_id == v->index) { - return _companies_ainew[c->index].special_vehicles[i].flag; - } - } - - // Not found :( - return 0; -} - - -bool AiNew_SetSpecialVehicleFlag(Company *c, Vehicle *v, uint flag) -{ - int new_id = -1; - uint i; - - for (i = 0; i < AI_MAX_SPECIAL_VEHICLES; i++) { - if (_companies_ainew[c->index].special_vehicles[i].veh_id == v->index) { - _companies_ainew[c->index].special_vehicles[i].flag |= flag; - return true; - } - if (new_id == -1 && - _companies_ainew[c->index].special_vehicles[i].veh_id == 0 && - _companies_ainew[c->index].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; - } - _companies_ainew[c->index].special_vehicles[new_id].veh_id = v->index; - _companies_ainew[c->index].special_vehicles[new_id].flag = flag; - return true; -} diff --git a/src/ai/trolly/trolly.cpp b/src/ai/trolly/trolly.cpp deleted file mode 100644 index 6b874ec0d..000000000 --- a/src/ai/trolly/trolly.cpp +++ /dev/null @@ -1,1348 +0,0 @@ -/* $Id$ */ - -/** - * @file trolly.cpp Implementation of the trolly AI. - * - * 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 its - * 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. - * - * 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 "../../road_map.h" -#include "../../station_map.h" -#include "../../command_func.h" -#include "trolly.h" -#include "../../depot_base.h" -#include "../../town.h" -#include "../../industry.h" -#include "../../station_base.h" -#include "../../engine_func.h" -#include "../../engine_base.h" -#include "../../gui.h" -#include "../../vehicle_base.h" -#include "../../vehicle_func.h" -#include "../../date_func.h" -#include "../ai.h" -#include "../../company_base.h" -#include "../../company_func.h" - -#include "table/strings.h" - -CompanyAiNew _companies_ainew[MAX_COMPANIES]; - -// This function is called after StartUp. It is the init of an AI -static void AiNew_State_FirstTime(Company *c) -{ - // This assert is used to protect those function from misuse - // You have quickly a small mistake in the state-array - // With that, everything would go wrong. Finding that, is almost impossible - // With this assert, that problem can never happen. - assert(_companies_ainew[c->index].state == AI_STATE_FIRST_TIME); - // We first have to init some things - - if (_current_company == 1) ShowErrorMessage(INVALID_STRING_ID, TEMP_AI_IN_PROGRESS, 0, 0); - - // The PathFinder (AyStar) - // TODO: Maybe when an AI goes bankrupt, this is de-init - // or when coming from a savegame.. should be checked out! - _companies_ainew[c->index].path_info.start_tile_tl = 0; - _companies_ainew[c->index].path_info.start_tile_br = 0; - _companies_ainew[c->index].path_info.end_tile_tl = 0; - _companies_ainew[c->index].path_info.end_tile_br = 0; - _companies_ainew[c->index].pathfinder = new_AyStar_AiPathFinder(12, &_companies_ainew[c->index].path_info); - - _companies_ainew[c->index].idle = 0; - _companies_ainew[c->index].last_vehiclecheck_date = _date; - - // We ALWAYS start with a bus route.. just some basic money ;) - _companies_ainew[c->index].action = AI_ACTION_BUS_ROUTE; - - // Let's popup the news, and after that, start building.. - _companies_ainew[c->index].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(Company *c) -{ - assert(_companies_ainew[c->index].state == AI_STATE_NOTHING); - // If we are done idling, start over again - if (_companies_ainew[c->index].idle == 0) _companies_ainew[c->index].idle = AI_RandomRange(DAY_TICKS * 2) + DAY_TICKS; - if (--_companies_ainew[c->index].idle == 0) { - // We are done idling.. what you say? Let's do something! - // I mean.. the next tick ;) - _companies_ainew[c->index].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(Company *c) -{ - assert(_companies_ainew[c->index].state == AI_STATE_WAKE_UP); - // First, check if we have a HQ - if (c->location_of_HQ == INVALID_TILE) { - // 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(c, AI_Random() % MapSize()); - // Enough for now, but we want to come back here the next time - // so we do not change any status - return; - } - - Money money = c->money - AI_MINIMUM_MONEY; - - // Let's pick an action! - if (_companies_ainew[c->index].action == AI_ACTION_NONE) { - int r = AI_Random() & 0xFF; - if (c->current_loan > 0 && - c->old_economy[1].income > AI_MINIMUM_INCOME_FOR_LOAN && - r < 10) { - _companies_ainew[c->index].action = AI_ACTION_REPAY_LOAN; - } else if (_companies_ainew[c->index].last_vehiclecheck_date + AI_DAYS_BETWEEN_VEHICLE_CHECKS < _date) { - // Check all vehicles once in a while - _companies_ainew[c->index].action = AI_ACTION_CHECK_ALL_VEHICLES; - _companies_ainew[c->index].last_vehiclecheck_date = _date; - } else if (r < 100 && !_settings_game.ai.ai_disable_veh_roadveh) { - // Do we have any spots for road-vehicles left open? - if (GetFreeUnitNumber(VEH_ROAD) <= _settings_game.vehicle.max_roadveh) { - if (r < 85) { - _companies_ainew[c->index].action = AI_ACTION_TRUCK_ROUTE; - } else { - _companies_ainew[c->index].action = AI_ACTION_BUS_ROUTE; - } - } -#if 0 - } else if (r < 200 && !_settings_game.ai.ai_disable_veh_train) { - if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) { - _companies_ainew[c->index].action = AI_ACTION_TRAIN_ROUTE; - } -#endif - } - - _companies_ainew[c->index].counter = 0; - } - - if (_companies_ainew[c->index].counter++ > AI_MAX_TRIES_FOR_SAME_ROUTE) { - _companies_ainew[c->index].action = AI_ACTION_NONE; - return; - } - - if (_settings_game.ai.ai_disable_veh_roadveh && ( - _companies_ainew[c->index].action == AI_ACTION_BUS_ROUTE || - _companies_ainew[c->index].action == AI_ACTION_TRUCK_ROUTE - )) { - _companies_ainew[c->index].action = AI_ACTION_NONE; - return; - } - - if (_companies_ainew[c->index].action == AI_ACTION_REPAY_LOAN && - money > AI_MINIMUM_LOAN_REPAY_MONEY) { - // We start repaying some money.. - _companies_ainew[c->index].state = AI_STATE_REPAY_MONEY; - return; - } - - if (_companies_ainew[c->index].action == AI_ACTION_CHECK_ALL_VEHICLES) { - _companies_ainew[c->index].state = AI_STATE_CHECK_ALL_VEHICLES; - return; - } - - // It is useless to start finding a route if we don't have enough money - // to build the route anyway.. - if (_companies_ainew[c->index].action == AI_ACTION_BUS_ROUTE && - money > AI_MINIMUM_BUS_ROUTE_MONEY) { - if (GetFreeUnitNumber(VEH_ROAD) > _settings_game.vehicle.max_roadveh) { - _companies_ainew[c->index].action = AI_ACTION_NONE; - return; - } - _companies_ainew[c->index].cargo = AI_NEED_CARGO; - _companies_ainew[c->index].state = AI_STATE_LOCATE_ROUTE; - _companies_ainew[c->index].tbt = AI_BUS; // Bus-route - return; - } - if (_companies_ainew[c->index].action == AI_ACTION_TRUCK_ROUTE && - money > AI_MINIMUM_TRUCK_ROUTE_MONEY) { - if (GetFreeUnitNumber(VEH_ROAD) > _settings_game.vehicle.max_roadveh) { - _companies_ainew[c->index].action = AI_ACTION_NONE; - return; - } - _companies_ainew[c->index].cargo = AI_NEED_CARGO; - _companies_ainew[c->index].last_id = 0; - _companies_ainew[c->index].state = AI_STATE_LOCATE_ROUTE; - _companies_ainew[c->index].tbt = AI_TRUCK; - return; - } - - _companies_ainew[c->index].state = AI_STATE_NOTHING; -} - - -static void AiNew_State_ActionDone(Company *c) -{ - _companies_ainew[c->index].action = AI_ACTION_NONE; - _companies_ainew[c->index].state = AI_STATE_NOTHING; -} - - -// Check if a city or industry is good enough to start a route there -static bool AiNew_Check_City_or_Industry(Company *c, int ic, byte type) -{ - if (type == AI_CITY) { - const Town *t = GetTown(ic); - const 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_company] < 0 && AI_CHANCE16(1, 4)) return false; - - if (t->max_pass - t->act_pass < AI_CHECKCITY_NEEDED_CARGO && !AI_CHANCE16(1, AI_CHECKCITY_CITY_CHANCE)) return false; - - // 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) { - // Do we own it? - if (st->owner == _current_company) { - // Are we talking busses? - if (_companies_ainew[c->index].tbt == AI_BUS && (FACIL_BUS_STOP & st->facilities) != FACIL_BUS_STOP) continue; - // Is it the same city as we are in now? - if (st->town != t) continue; - // When was this station build? - 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 && AI_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) { - const Industry *i = GetIndustry(ic); - const Station *st; - int count = 0; - int j = 0; - - if (i->town != NULL && i->town->ratings[_current_company] < 0 && AI_CHANCE16(1, 4)) return false; - - // No limits on delevering stations! - // Or for industry that does not give anything yet - if (i->produced_cargo[0] == CT_INVALID || i->last_month_production[0] == 0) return true; - - if (i->last_month_production[0] - i->last_month_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) { - // Do we own it? - if (st->owner == _current_company) { - // Are we talking trucks? - if (_companies_ainew[c->index].tbt == AI_TRUCK && (FACIL_TRUCK_STOP & st->facilities) != FACIL_TRUCK_STOP) continue; - // Is it the same city as we are in now? - if (st->town != i->town) continue; - // When was this station build? - 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] == CT_INVALID) 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 && AI_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->last_month_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(Company *c) -{ - assert(_companies_ainew[c->index].state == AI_STATE_LOCATE_ROUTE); - // For now, we only support PASSENGERS, CITY and BUSSES - - // We don't have a route yet - if (_companies_ainew[c->index].cargo == AI_NEED_CARGO) { - _companies_ainew[c->index].new_cost = 0; // No cost yet - _companies_ainew[c->index].temp = -1; - // Reset the counter - _companies_ainew[c->index].counter = 0; - - _companies_ainew[c->index].from_ic = -1; - _companies_ainew[c->index].to_ic = -1; - if (_companies_ainew[c->index].tbt == AI_BUS) { - // For now we only have a passenger route - _companies_ainew[c->index].cargo = CT_PASSENGERS; - - // Find a route to cities - _companies_ainew[c->index].from_type = AI_CITY; - _companies_ainew[c->index].to_type = AI_CITY; - } else if (_companies_ainew[c->index].tbt == AI_TRUCK) { - _companies_ainew[c->index].cargo = AI_NO_CARGO; - - _companies_ainew[c->index].from_type = AI_INDUSTRY; - _companies_ainew[c->index].to_type = AI_INDUSTRY; - } - - // Now we are doing initing, we wait one tick - return; - } - - // Increase the counter and abort if it is taking too long! - _companies_ainew[c->index].counter++; - if (_companies_ainew[c->index].counter > AI_LOCATE_ROUTE_MAX_COUNTER) { - // Switch back to doing nothing! - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return; - } - - // We are going to locate a city from where we are going to connect - if (_companies_ainew[c->index].from_ic == -1) { - if (_companies_ainew[c->index].temp == -1) { - // First, we pick a random spot to search from - if (_companies_ainew[c->index].from_type == AI_CITY) { - _companies_ainew[c->index].temp = AI_RandomRange(GetMaxTownIndex() + 1); - } else { - _companies_ainew[c->index].temp = AI_RandomRange(GetMaxIndustryIndex() + 1); - } - } - - if (!AiNew_Check_City_or_Industry(c, _companies_ainew[c->index].temp, _companies_ainew[c->index].from_type)) { - // It was not a valid city - // increase the temp with one, and return. We will come back later here - // to try again - _companies_ainew[c->index].temp++; - if (_companies_ainew[c->index].from_type == AI_CITY) { - if (_companies_ainew[c->index].temp > GetMaxTownIndex()) _companies_ainew[c->index].temp = 0; - } else { - if (_companies_ainew[c->index].temp > GetMaxIndustryIndex()) _companies_ainew[c->index].temp = 0; - } - - // Don't do an attempt if we are trying the same id as the last time... - if (_companies_ainew[c->index].last_id == _companies_ainew[c->index].temp) return; - _companies_ainew[c->index].last_id = _companies_ainew[c->index].temp; - - return; - } - - // We found a good city/industry, save the data of it - _companies_ainew[c->index].from_ic = _companies_ainew[c->index].temp; - - // Start the next tick with finding a to-city - _companies_ainew[c->index].temp = -1; - return; - } - - // Find a to-city - if (_companies_ainew[c->index].temp == -1) { - // First, we pick a random spot to search to - if (_companies_ainew[c->index].to_type == AI_CITY) { - _companies_ainew[c->index].temp = AI_RandomRange(GetMaxTownIndex() + 1); - } else { - _companies_ainew[c->index].temp = AI_RandomRange(GetMaxIndustryIndex() + 1); - } - } - - // The same city is not allowed - // Also check if the city is valid - if (_companies_ainew[c->index].temp != _companies_ainew[c->index].from_ic && AiNew_Check_City_or_Industry(c, _companies_ainew[c->index].temp, _companies_ainew[c->index].to_type)) { - // Maybe it is valid.. - - /* We need to know if they are not to far apart from eachother.. - * We do that by checking how much cargo we have to move and how long the - * route is. - */ - - if (_companies_ainew[c->index].from_type == AI_CITY && _companies_ainew[c->index].tbt == AI_BUS) { - const Town *town_from = GetTown(_companies_ainew[c->index].from_ic); - const Town *town_temp = GetTown(_companies_ainew[c->index].temp); - uint distance = DistanceManhattan(town_from->xy, town_temp->xy); - int max_cargo; - - max_cargo = town_from->max_pass + town_temp->max_pass; - max_cargo -= town_from->act_pass + town_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 (distance <= max_cargo * AI_LOCATEROUTE_BUS_CARGO_DISTANCE) { - // We found a good city/industry, save the data of it - _companies_ainew[c->index].to_ic = _companies_ainew[c->index].temp; - _companies_ainew[c->index].state = AI_STATE_FIND_STATION; - - DEBUG(ai, 1, "[LocateRoute] found bus-route of %d tiles long (from %d to %d)", - distance, - _companies_ainew[c->index].from_ic, - _companies_ainew[c->index].temp - ); - - _companies_ainew[c->index].from_tile = 0; - _companies_ainew[c->index].to_tile = 0; - - return; - } - } else if (_companies_ainew[c->index].tbt == AI_TRUCK) { - const Industry *ind_from = GetIndustry(_companies_ainew[c->index].from_ic); - const Industry *ind_temp = GetIndustry(_companies_ainew[c->index].temp); - bool found = false; - int max_cargo = 0; - uint i; - - // TODO: in max_cargo, also check other cargo (beside [0]) - // First we check if the from_ic produces cargo that this ic accepts - if (ind_from->produced_cargo[0] != CT_INVALID && ind_from->last_month_production[0] != 0) { - for (i = 0; i < lengthof(ind_temp->accepts_cargo); i++) { - if (ind_temp->accepts_cargo[i] == CT_INVALID) break; - if (ind_from->produced_cargo[0] == ind_temp->accepts_cargo[i]) { - // Found a compatible industry - max_cargo = ind_from->last_month_production[0] - ind_from->last_month_transported[0]; - found = true; - _companies_ainew[c->index].from_deliver = true; - _companies_ainew[c->index].to_deliver = false; - break; - } - } - } - if (!found && ind_temp->produced_cargo[0] != CT_INVALID && ind_temp->last_month_production[0] != 0) { - // If not check if the current ic produces cargo that the from_ic accepts - for (i = 0; i < lengthof(ind_from->accepts_cargo); i++) { - if (ind_from->accepts_cargo[i] == CT_INVALID) break; - if (ind_from->produced_cargo[0] == ind_from->accepts_cargo[i]) { - // Found a compatbiel industry - found = true; - max_cargo = ind_temp->last_month_production[0] - ind_temp->last_month_transported[0]; - _companies_ainew[c->index].from_deliver = false; - _companies_ainew[c->index].to_deliver = true; - break; - } - } - } - if (found) { - // Yeah, they are compatible!!! - // Check the length against the amount of goods - uint distance = DistanceManhattan(ind_from->xy, ind_temp->xy); - - if (distance > AI_LOCATEROUTE_TRUCK_MIN_DISTANCE && - distance <= max_cargo * AI_LOCATEROUTE_TRUCK_CARGO_DISTANCE) { - _companies_ainew[c->index].to_ic = _companies_ainew[c->index].temp; - if (_companies_ainew[c->index].from_deliver) { - _companies_ainew[c->index].cargo = ind_from->produced_cargo[0]; - } else { - _companies_ainew[c->index].cargo = ind_temp->produced_cargo[0]; - } - _companies_ainew[c->index].state = AI_STATE_FIND_STATION; - - DEBUG(ai, 1, "[LocateRoute] found truck-route of %d tiles long (from %d to %d)", - distance, - _companies_ainew[c->index].from_ic, - _companies_ainew[c->index].temp - ); - - _companies_ainew[c->index].from_tile = 0; - _companies_ainew[c->index].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 - _companies_ainew[c->index].temp++; - if (_companies_ainew[c->index].to_type == AI_CITY) { - if (_companies_ainew[c->index].temp > GetMaxTownIndex()) _companies_ainew[c->index].temp = 0; - } else { - if (_companies_ainew[c->index].temp > GetMaxIndustryIndex()) _companies_ainew[c->index].temp = 0; - } - - // Don't do an attempt if we are trying the same id as the last time... - if (_companies_ainew[c->index].last_id == _companies_ainew[c->index].temp) return; - _companies_ainew[c->index].last_id = _companies_ainew[c->index].temp; -} - - -// Check if there are not more than a certain amount of vehicles pointed to a certain -// station. This to prevent 10 busses going to one station, which gives... problems ;) -static bool AiNew_CheckVehicleStation(Company *c, Station *st) -{ - int count = 0; - Vehicle *v; - - // Also check if we don't have already a lot of busses to this city... - FOR_ALL_VEHICLES(v) { - if (v->owner == _current_company) { - const Order *order; - - FOR_VEHICLE_ORDERS(v, order) { - if (order->IsType(OT_GOTO_STATION) && GetStation(order->GetDestination()) == 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(Company *c) -{ - TileIndex tile; - Station *st; - int count = 0; - EngineID i; - TileIndex new_tile = 0; - DiagDirection direction = DIAGDIR_NE; - Town *town = NULL; - assert(_companies_ainew[c->index].state == AI_STATE_FIND_STATION); - - if (_companies_ainew[c->index].from_tile == 0) { - // First we scan for a station in the from-city - if (_companies_ainew[c->index].from_type == AI_CITY) { - town = GetTown(_companies_ainew[c->index].from_ic); - tile = town->xy; - } else { - tile = GetIndustry(_companies_ainew[c->index].from_ic)->xy; - } - } else if (_companies_ainew[c->index].to_tile == 0) { - // Second we scan for a station in the to-city - if (_companies_ainew[c->index].to_type == AI_CITY) { - town = GetTown(_companies_ainew[c->index].to_ic); - tile = town->xy; - } else { - tile = GetIndustry(_companies_ainew[c->index].to_ic)->xy; - } - } else { - // Unsupported request - // Go to FIND_PATH - _companies_ainew[c->index].temp = -1; - _companies_ainew[c->index].state = AI_STATE_FIND_PATH; - return; - } - - // First, we are going to look at the stations that already exist inside the city - // If there is enough cargo left in the station, we take that station - // If that is not possible, and there are more than 2 stations in the city, abort - i = AiNew_PickVehicle(c); - // Euhmz, this should not happen _EVER_ - // Quit finding a route... - if (i == INVALID_ENGINE) { - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return; - } - - FOR_ALL_STATIONS(st) { - if (st->owner == _current_company) { - if (_companies_ainew[c->index].tbt == AI_BUS && (FACIL_BUS_STOP & st->facilities) == FACIL_BUS_STOP) { - if (st->town == town) { - // Check how much cargo there is left in the station - if ((int)st->goods[_companies_ainew[c->index].cargo].cargo.Count() > RoadVehInfo(i)->capacity * AI_STATION_REUSE_MULTIPLER) { - if (AiNew_CheckVehicleStation(c, st)) { - // We did found a station that was good enough! - new_tile = st->xy; - direction = GetRoadStopDir(st->xy); - 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) { - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return; - } - - if (new_tile == 0 && _companies_ainew[c->index].tbt == AI_BUS) { - uint x, y, i = 0; - CommandCost 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 passengers 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[_companies_ainew[c->index].cargo] >> 3 == 0) continue; - // See if we can build the station - r = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, new_tile, 0, 0, 0, DC_QUERY_COST); - if (CmdFailed(r)) continue; - // We can build it, so add it to found_spot - found_spot[i] = new_tile; - found_best[i++] = accepts[_companies_ainew[c->index].cargo]; - } - } - } - - // If i is still zero, we did not find anything - if (i == 0) { - _companies_ainew[c->index].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(c, _companies_ainew[c->index].tbt, new_tile, 0, 0, 0, DC_QUERY_COST); - _companies_ainew[c->index].new_cost += r.GetCost(); - - direction = (DiagDirection)AI_PATHFINDER_NO_DIRECTION; - } else if (new_tile == 0 && _companies_ainew[c->index].tbt == AI_TRUCK) { - // Truck station locater works differently.. a station can be on any place - // as long as it is in range. So we give back code AI_STATION_RANGE - // so the pathfinder routine can work it out! - new_tile = AI_STATION_RANGE; - direction = (DiagDirection)AI_PATHFINDER_NO_DIRECTION; - } - - if (_companies_ainew[c->index].from_tile == 0) { - _companies_ainew[c->index].from_tile = new_tile; - _companies_ainew[c->index].from_direction = direction; - // Now we found thisone, go in for to_tile - return; - } else if (_companies_ainew[c->index].to_tile == 0) { - _companies_ainew[c->index].to_tile = new_tile; - _companies_ainew[c->index].to_direction = direction; - // K, done placing stations! - _companies_ainew[c->index].temp = -1; - _companies_ainew[c->index].state = AI_STATE_FIND_PATH; - return; - } -} - - -// We try to find a path between 2 points -static void AiNew_State_FindPath(Company *c) -{ - int r; - assert(_companies_ainew[c->index].state == AI_STATE_FIND_PATH); - - // First time, init some data - if (_companies_ainew[c->index].temp == -1) { - // Init path_info - if (_companies_ainew[c->index].from_tile == AI_STATION_RANGE) { - const Industry *i = GetIndustry(_companies_ainew[c->index].from_ic); - - // For truck routes we take a range around the industry - _companies_ainew[c->index].path_info.start_tile_tl = i->xy - TileDiffXY(1, 1); - _companies_ainew[c->index].path_info.start_tile_br = i->xy + TileDiffXY(i->width + 1, i->height + 1); - _companies_ainew[c->index].path_info.start_direction = _companies_ainew[c->index].from_direction; - } else { - _companies_ainew[c->index].path_info.start_tile_tl = _companies_ainew[c->index].from_tile; - _companies_ainew[c->index].path_info.start_tile_br = _companies_ainew[c->index].from_tile; - _companies_ainew[c->index].path_info.start_direction = _companies_ainew[c->index].from_direction; - } - - if (_companies_ainew[c->index].to_tile == AI_STATION_RANGE) { - const Industry *i = GetIndustry(_companies_ainew[c->index].to_ic); - - _companies_ainew[c->index].path_info.end_tile_tl = i->xy - TileDiffXY(1, 1); - _companies_ainew[c->index].path_info.end_tile_br = i->xy + TileDiffXY(i->width + 1, i->height + 1); - _companies_ainew[c->index].path_info.end_direction = _companies_ainew[c->index].to_direction; - } else { - _companies_ainew[c->index].path_info.end_tile_tl = _companies_ainew[c->index].to_tile; - _companies_ainew[c->index].path_info.end_tile_br = _companies_ainew[c->index].to_tile; - _companies_ainew[c->index].path_info.end_direction = _companies_ainew[c->index].to_direction; - } - - _companies_ainew[c->index].path_info.rail_or_road = (_companies_ainew[c->index].tbt == AI_TRAIN); - - // First, clean the pathfinder with our new begin and endpoints - clean_AyStar_AiPathFinder(_companies_ainew[c->index].pathfinder, &_companies_ainew[c->index].path_info); - - _companies_ainew[c->index].temp = 0; - } - - // Start the pathfinder - r = _companies_ainew[c->index].pathfinder->main(_companies_ainew[c->index].pathfinder); - switch (r) { - case AYSTAR_NO_PATH: - DEBUG(ai, 1, "No route found by pathfinder"); - // Start all over again - _companies_ainew[c->index].state = AI_STATE_NOTHING; - break; - - case AYSTAR_FOUND_END_NODE: // We found the end-point - _companies_ainew[c->index].temp = -1; - _companies_ainew[c->index].state = AI_STATE_FIND_DEPOT; - break; - - // In any other case, we are still busy finding the route - default: break; - } -} - - -// This function tries to locate a good place for a depot! -static void AiNew_State_FindDepot(Company *c) -{ - // To place the depot, we walk through the route, and if we find a lovely spot (MP_CLEAR, MP_TREES), we place it there.. - // Simple, easy, works! - // 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; - CommandCost r; - DiagDirection j; - TileIndex tile; - assert(_companies_ainew[c->index].state == AI_STATE_FIND_DEPOT); - - _companies_ainew[c->index].depot_tile = 0; - - for (i = 2; i < _companies_ainew[c->index].path_info.route_length - 2; i++) { - tile = _companies_ainew[c->index].path_info.route[i]; - for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) { - TileIndex t = tile + TileOffsByDiagDir(j); - - if (IsRoadDepotTile(t) && - IsTileOwner(t, _current_company) && - GetRoadDepotDirection(t) == ReverseDiagDir(j)) { - _companies_ainew[c->index].depot_tile = t; - _companies_ainew[c->index].depot_direction = ReverseDiagDir(j); - _companies_ainew[c->index].state = AI_STATE_VERIFY_ROUTE; - return; - } - } - } - - // This routine let depot finding start in the middle, and work his way to the stations - // It makes depot placing nicer :) - i = _companies_ainew[c->index].path_info.route_length / 2; - g = 1; - while (i > 1 && i < _companies_ainew[c->index].path_info.route_length - 2) { - i += g; - g *= -1; - (g < 0 ? g-- : g++); - - if (_companies_ainew[c->index].path_info.route_extra[i] != 0 || _companies_ainew[c->index].path_info.route_extra[i + 1] != 0) { - // Bridge or tunnel.. we can't place a depot there - continue; - } - - tile = _companies_ainew[c->index].path_info.route[i]; - - for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) { - TileIndex t = tile + TileOffsByDiagDir(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 (t == _companies_ainew[c->index].path_info.route[i - 1] || - t == _companies_ainew[c->index].path_info.route[i + 1]) { - continue; - } - // Not around a bridge? - if (_companies_ainew[c->index].path_info.route_extra[i] != 0) continue; - if (IsTileType(tile, MP_TUNNELBRIDGE)) continue; - // Is the terrain clear? - if (IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)) { - // If the current tile is on a slope then we do not allow this - if (GetTileSlope(tile, NULL) != SLOPE_FLAT) continue; - // Check if everything went okay.. - r = AiNew_Build_Depot(c, t, ReverseDiagDir(j), 0); - if (CmdFailed(r)) continue; - // Found a spot! - _companies_ainew[c->index].new_cost += r.GetCost(); - _companies_ainew[c->index].depot_tile = t; - _companies_ainew[c->index].depot_direction = ReverseDiagDir(j); // Reverse direction - _companies_ainew[c->index].state = AI_STATE_VERIFY_ROUTE; - return; - } - } - } - - // Failed to find a depot? - _companies_ainew[c->index].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(Company *c) -{ - if (_companies_ainew[c->index].tbt == AI_BUS) { - // For bus-routes we look at the time before we are back in the station - EngineID i; - int length, tiles_a_day; - int amount; - i = AiNew_PickVehicle(c); - if (i == INVALID_ENGINE) return 0; - // Passenger run.. how long is the route? - length = _companies_ainew[c->index].path_info.route_length; - // Calculating tiles a day a vehicle moves is not easy.. this is how it must be done! - tiles_a_day = RoadVehInfo(i)->max_speed * DAY_TICKS / 256 / 16; - if (tiles_a_day == 0) tiles_a_day = 1; - // 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 (_companies_ainew[c->index].tbt == AI_TRUCK) { - // For truck-routes we look at the cargo - EngineID i; - int length, amount, tiles_a_day; - int max_cargo; - i = AiNew_PickVehicle(c); - if (i == INVALID_ENGINE) return 0; - // Passenger run.. how long is the route? - length = _companies_ainew[c->index].path_info.route_length; - // Calculating tiles a day a vehicle moves is not easy.. this is how it must be done! - tiles_a_day = RoadVehInfo(i)->max_speed * DAY_TICKS / 256 / 16; - if (tiles_a_day == 0) tiles_a_day = 1; - if (_companies_ainew[c->index].from_deliver) { - max_cargo = GetIndustry(_companies_ainew[c->index].from_ic)->last_month_production[0]; - } else { - max_cargo = GetIndustry(_companies_ainew[c->index].to_ic)->last_month_production[0]; - } - - // This is because moving 60% is more than we can dream of! - max_cargo *= 6; - max_cargo /= 10; - // 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(Company *c) -{ - int res, i; - assert(_companies_ainew[c->index].state == AI_STATE_VERIFY_ROUTE); - - // Let's calculate the cost of the path.. - // new_cost already contains the cost of the stations - _companies_ainew[c->index].path_info.position = -1; - - do { - _companies_ainew[c->index].path_info.position++; - _companies_ainew[c->index].new_cost += AiNew_Build_RoutePart(c, &_companies_ainew[c->index].path_info, DC_QUERY_COST).GetCost(); - } while (_companies_ainew[c->index].path_info.position != -2); - - // Now we know the price of build station + path. Now check how many vehicles - // we need and what the price for that will be - res = AiNew_HowManyVehicles(c); - // If res == 0, no vehicle was found, or an other problem did occour - if (res == 0) { - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return; - } - _companies_ainew[c->index].amount_veh = res; - _companies_ainew[c->index].cur_veh = 0; - - // Check how much it it going to cost us.. - for (i = 0; i < res; i++) { - _companies_ainew[c->index].new_cost += AiNew_Build_Vehicle(c, 0, DC_QUERY_COST).GetCost(); - } - - // Now we know how much the route is going to cost us - // Check if we have enough money for it! - if (_companies_ainew[c->index].new_cost > c->money - AI_MINIMUM_MONEY) { - // Too bad.. - DEBUG(ai, 1, "Insufficient funds to build route (%" OTTD_PRINTF64 "d)", (int64)_companies_ainew[c->index].new_cost); - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return; - } - - // Now we can build the route, check the direction of the stations! - if (_companies_ainew[c->index].from_direction == AI_PATHFINDER_NO_DIRECTION) { - _companies_ainew[c->index].from_direction = AiNew_GetDirection(_companies_ainew[c->index].path_info.route[_companies_ainew[c->index].path_info.route_length - 1], _companies_ainew[c->index].path_info.route[_companies_ainew[c->index].path_info.route_length - 2]); - } - if (_companies_ainew[c->index].to_direction == AI_PATHFINDER_NO_DIRECTION) { - _companies_ainew[c->index].to_direction = AiNew_GetDirection(_companies_ainew[c->index].path_info.route[0], _companies_ainew[c->index].path_info.route[1]); - } - if (_companies_ainew[c->index].from_tile == AI_STATION_RANGE) - _companies_ainew[c->index].from_tile = _companies_ainew[c->index].path_info.route[_companies_ainew[c->index].path_info.route_length - 1]; - if (_companies_ainew[c->index].to_tile == AI_STATION_RANGE) - _companies_ainew[c->index].to_tile = _companies_ainew[c->index].path_info.route[0]; - - _companies_ainew[c->index].state = AI_STATE_BUILD_STATION; - _companies_ainew[c->index].temp = 0; - - DEBUG(ai, 1, "The route is set and buildable, building 0x%X to 0x%X...", _companies_ainew[c->index].from_tile, _companies_ainew[c->index].to_tile); -} - - -// Build the stations -static void AiNew_State_BuildStation(Company *c) -{ - CommandCost res; - assert(_companies_ainew[c->index].state == AI_STATE_BUILD_STATION); - if (_companies_ainew[c->index].temp == 0) { - if (!IsTileType(_companies_ainew[c->index].from_tile, MP_STATION)) - res = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, _companies_ainew[c->index].from_tile, 0, 0, _companies_ainew[c->index].from_direction, DC_EXEC); - } else { - if (!IsTileType(_companies_ainew[c->index].to_tile, MP_STATION)) - res = AiNew_Build_Station(c, _companies_ainew[c->index].tbt, _companies_ainew[c->index].to_tile, 0, 0, _companies_ainew[c->index].to_direction, DC_EXEC); - _companies_ainew[c->index].state = AI_STATE_BUILD_PATH; - } - if (CmdFailed(res)) { - DEBUG(ai, 0, "[BuildStation] station could not be built (0x%X)", _companies_ainew[c->index].to_tile); - _companies_ainew[c->index].state = AI_STATE_NOTHING; - // If the first station _was_ build, destroy it - if (_companies_ainew[c->index].temp != 0) - AI_DoCommand(_companies_ainew[c->index].from_tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR); - return; - } - _companies_ainew[c->index].temp++; -} - - -// Build the path -static void AiNew_State_BuildPath(Company *c) -{ - assert(_companies_ainew[c->index].state == AI_STATE_BUILD_PATH); - // _companies_ainew[c->index].temp is set to -1 when this function is called for the first time - if (_companies_ainew[c->index].temp == -1) { - DEBUG(ai, 1, "Starting to build new path"); - // Init the counter - _companies_ainew[c->index].counter = (4 - _settings_game.difficulty.competitor_speed) * AI_BUILDPATH_PAUSE + 1; - // Set the position to the startingplace (-1 because in a minute we do ++) - _companies_ainew[c->index].path_info.position = -1; - // And don't do this again - _companies_ainew[c->index].temp = 0; - } - // Building goes very fast on normal rate, so we are going to slow it down.. - // By let the counter count from AI_BUILDPATH_PAUSE to 0, we have a nice way :) - if (--_companies_ainew[c->index].counter != 0) return; - _companies_ainew[c->index].counter = (4 - _settings_game.difficulty.competitor_speed) * AI_BUILDPATH_PAUSE + 1; - - // Increase the building position - _companies_ainew[c->index].path_info.position++; - // Build route - AiNew_Build_RoutePart(c, &_companies_ainew[c->index].path_info, DC_EXEC); - if (_companies_ainew[c->index].path_info.position == -2) { - // This means we are done building! - - if (_companies_ainew[c->index].tbt == AI_TRUCK && !_settings_game.pf.roadveh_queue) { - // If they not queue, they have to go up and down to try again at a station... - // We don't want that, so try building some road left or right of the station - DiagDirection dir1, dir2, dir3; - TileIndex tile; - CommandCost ret; - for (int i = 0; i < 2; i++) { - if (i == 0) { - tile = _companies_ainew[c->index].from_tile + TileOffsByDiagDir(_companies_ainew[c->index].from_direction); - dir1 = ChangeDiagDir(_companies_ainew[c->index].from_direction, DIAGDIRDIFF_90LEFT); - dir2 = ChangeDiagDir(_companies_ainew[c->index].from_direction, DIAGDIRDIFF_90RIGHT); - dir3 = _companies_ainew[c->index].from_direction; - } else { - tile = _companies_ainew[c->index].to_tile + TileOffsByDiagDir(_companies_ainew[c->index].to_direction); - dir1 = ChangeDiagDir(_companies_ainew[c->index].to_direction, DIAGDIRDIFF_90LEFT); - dir2 = ChangeDiagDir(_companies_ainew[c->index].to_direction, DIAGDIRDIFF_90RIGHT); - dir3 = _companies_ainew[c->index].to_direction; - } - - ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir1)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - if (CmdSucceeded(ret)) { - TileIndexDiff offset = TileOffsByDiagDir(dir1); - if (IsTileType(tile + offset, MP_CLEAR) || IsTileType(tile + offset, MP_TREES)) { - ret = AI_DoCommand(tile + offset, AiNew_GetRoadDirection(tile, tile + offset, tile + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - if (CmdSucceeded(ret)) { - if (IsTileType(tile + offset + offset, MP_CLEAR) || IsTileType(tile + offset + offset, MP_TREES)) - AI_DoCommand(tile + offset + offset, AiNew_GetRoadDirection(tile + offset, tile + offset + offset, tile + offset + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - } - } - } - - ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir2)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - if (CmdSucceeded(ret)) { - TileIndexDiff offset = TileOffsByDiagDir(dir2); - if (IsTileType(tile + offset, MP_CLEAR) || IsTileType(tile + offset, MP_TREES)) { - ret = AI_DoCommand(tile + offset, AiNew_GetRoadDirection(tile, tile + offset, tile + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - if (CmdSucceeded(ret)) { - if (IsTileType(tile + offset + offset, MP_CLEAR) || IsTileType(tile + offset + offset, MP_TREES)) - AI_DoCommand(tile + offset + offset, AiNew_GetRoadDirection(tile + offset, tile + offset + offset, tile + offset + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - } - } - } - - ret = AI_DoCommand(tile, DiagDirToRoadBits(dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - if (CmdSucceeded(ret)) { - TileIndexDiff offset = TileOffsByDiagDir(dir3); - if (IsTileType(tile + offset, MP_CLEAR) || IsTileType(tile + offset, MP_TREES)) { - ret = AI_DoCommand(tile + offset, AiNew_GetRoadDirection(tile, tile + offset, tile + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - if (CmdSucceeded(ret)) { - if (IsTileType(tile + offset + offset, MP_CLEAR) || IsTileType(tile + offset + offset, MP_TREES)) - AI_DoCommand(tile + offset + offset, AiNew_GetRoadDirection(tile + offset, tile + offset + offset, tile + offset + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); - } - } - } - } - } - - DEBUG(ai, 1, "Finished building path, cost: %" OTTD_PRINTF64 "d", (int64)_companies_ainew[c->index].new_cost); - _companies_ainew[c->index].state = AI_STATE_BUILD_DEPOT; - } -} - - -// Builds the depot -static void AiNew_State_BuildDepot(Company *c) -{ - CommandCost res; - assert(_companies_ainew[c->index].state == AI_STATE_BUILD_DEPOT); - - if (IsRoadDepotTile(_companies_ainew[c->index].depot_tile)) { - if (IsTileOwner(_companies_ainew[c->index].depot_tile, _current_company)) { - // The depot is already built - _companies_ainew[c->index].state = AI_STATE_BUILD_VEHICLE; - return; - } else { - // There is a depot, but not of our team! :( - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return; - } - } - - // There is a bus on the tile we want to build road on... idle till he is gone! (BAD PERSON! :p) - if (!EnsureNoVehicleOnGround(_companies_ainew[c->index].depot_tile + TileOffsByDiagDir(_companies_ainew[c->index].depot_direction))) - return; - - res = AiNew_Build_Depot(c, _companies_ainew[c->index].depot_tile, _companies_ainew[c->index].depot_direction, DC_EXEC); - if (CmdFailed(res)) { - DEBUG(ai, 0, "[BuildDepot] depot could not be built (0x%X)", _companies_ainew[c->index].depot_tile); - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return; - } - - _companies_ainew[c->index].state = AI_STATE_BUILD_VEHICLE; - _companies_ainew[c->index].idle = 10; - _companies_ainew[c->index].veh_main_id = INVALID_VEHICLE; -} - - -// Build vehicles -static void AiNew_State_BuildVehicle(Company *c) -{ - CommandCost res; - assert(_companies_ainew[c->index].state == AI_STATE_BUILD_VEHICLE); - - // Check if we need to build a vehicle - if (_companies_ainew[c->index].amount_veh == 0) { - // Nope, we are done! - // This means: we are all done! The route is open.. go back to NOTHING - // He will idle some time and it will all start over again.. :) - _companies_ainew[c->index].state = AI_STATE_ACTION_DONE; - return; - } - if (--_companies_ainew[c->index].idle != 0) return; - // It is realistic that the AI can only build 1 vehicle a day.. - // This makes sure of that! - _companies_ainew[c->index].idle = AI_BUILD_VEHICLE_TIME_BETWEEN; - - // Build the vehicle - res = AiNew_Build_Vehicle(c, _companies_ainew[c->index].depot_tile, DC_EXEC); - if (CmdFailed(res)) { - // This happens when the AI can't build any more vehicles! - _companies_ainew[c->index].state = AI_STATE_NOTHING; - return; - } - // Increase the current counter - _companies_ainew[c->index].cur_veh++; - // Decrease the total counter - _companies_ainew[c->index].amount_veh--; - // Go give some orders! - _companies_ainew[c->index].state = AI_STATE_WAIT_FOR_BUILD; -} - - -// Put the stations in the order list -static void AiNew_State_GiveOrders(Company *c) -{ - int idx; - Order order; - - assert(_companies_ainew[c->index].state == AI_STATE_GIVE_ORDERS); - - if (_companies_ainew[c->index].veh_main_id != INVALID_VEHICLE) { - AI_DoCommand(0, _companies_ainew[c->index].veh_id + (_companies_ainew[c->index].veh_main_id << 16), CO_SHARE, DC_EXEC, CMD_CLONE_ORDER); - - _companies_ainew[c->index].state = AI_STATE_START_VEHICLE; - return; - } else { - _companies_ainew[c->index].veh_main_id = _companies_ainew[c->index].veh_id; - } - - // Very handy for AI, goto depot.. but yeah, it needs to be activated ;) - if (_settings_game.order.gotodepot) { - idx = 0; - order.MakeGoToDepot(GetDepotByTile(_companies_ainew[c->index].depot_tile)->index, ODTFB_PART_OF_ORDERS); - AI_DoCommand(0, _companies_ainew[c->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER); - } - - idx = 0; - order.MakeGoToStation(GetStationIndex(_companies_ainew[c->index].to_tile)); - if (_companies_ainew[c->index].tbt == AI_TRUCK && _companies_ainew[c->index].to_deliver) order.SetLoadType(OLFB_FULL_LOAD); - AI_DoCommand(0, _companies_ainew[c->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER); - - idx = 0; - order.MakeGoToStation(GetStationIndex(_companies_ainew[c->index].from_tile)); - if (_companies_ainew[c->index].tbt == AI_TRUCK && _companies_ainew[c->index].from_deliver) order.SetLoadType(OLFB_FULL_LOAD); - AI_DoCommand(0, _companies_ainew[c->index].veh_id + (idx << 16), order.Pack(), DC_EXEC, CMD_INSERT_ORDER); - - // Start the engines! - _companies_ainew[c->index].state = AI_STATE_START_VEHICLE; -} - - -// Start the vehicle -static void AiNew_State_StartVehicle(Company *c) -{ - assert(_companies_ainew[c->index].state == AI_STATE_START_VEHICLE); - - // Skip the first order if it is a second vehicle - // This to make vehicles go different ways.. - if (_companies_ainew[c->index].cur_veh & 1) - AI_DoCommand(0, _companies_ainew[c->index].veh_id, 1, DC_EXEC, CMD_SKIP_TO_ORDER); - - // 3, 2, 1... go! (give START_STOP command ;)) - AI_DoCommand(0, _companies_ainew[c->index].veh_id, 0, DC_EXEC, CMD_START_STOP_VEHICLE); - // Try to build an other vehicle (that function will stop building when needed) - _companies_ainew[c->index].idle = 10; - _companies_ainew[c->index].state = AI_STATE_BUILD_VEHICLE; -} - - -// Repays money -static void AiNew_State_RepayMoney(Company *c) -{ - uint i; - - for (i = 0; i < AI_LOAN_REPAY; i++) { - AI_DoCommand(0, 0, 0, DC_EXEC, CMD_DECREASE_LOAN); - } - _companies_ainew[c->index].state = AI_STATE_ACTION_DONE; -} - - -static void AiNew_CheckVehicle(Company *c, Vehicle *v) -{ - // When a vehicle is under the 6 months, we don't check for anything - if (v->age < 180) return; - - // When a vehicle is older than 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 < (Money)256 * AI_MINIMUM_ROUTE_PROFIT || - (v->reliability * 100 >> 16) < 40) { - // There is a possibility that the route is fucked up... - if (v->cargo.DaysInTransit() > 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(c, v) & AI_VEHICLEFLAG_SELL) { - if (v->type == VEH_ROAD && IsRoadDepotTile(v->tile) && - (v->vehstatus & VS_STOPPED)) { - // We are at the depot, sell the vehicle - AI_DoCommand(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH); - } - return; - } - - if (!AiNew_SetSpecialVehicleFlag(c, v, AI_VEHICLEFLAG_SELL)) return; - { - CommandCost ret; - if (v->type == VEH_ROAD) - ret = AI_DoCommand(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(Company *c) -{ - Vehicle *v; - - FOR_ALL_VEHICLES(v) { - if (v->owner != c->index) continue; - // Currently, we only know how to handle road-vehicles - if (v->type != VEH_ROAD) continue; - - AiNew_CheckVehicle(c, v); - } - - _companies_ainew[c->index].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, - NULL, - AiNew_State_GiveOrders, - AiNew_State_StartVehicle, - AiNew_State_RepayMoney, - AiNew_State_CheckAllVehicles, - AiNew_State_ActionDone, - NULL, -}; - -static void AiNew_OnTick(Company *c) -{ - if (_ainew_state[_companies_ainew[c->index].state] != NULL) - _ainew_state[_companies_ainew[c->index].state](c); -} - - -void AiNewDoGameLoop(Company *c) -{ - if (_companies_ainew[c->index].state == AI_STATE_STARTUP) { - // The AI just got alive! - _companies_ainew[c->index].state = AI_STATE_FIRST_TIME; - _companies_ainew[c->index].tick = 0; - - // Only startup the AI - return; - } - - // We keep a ticker. We use it for competitor_speed - _companies_ainew[c->index].tick++; - - // If we come here, we can do a tick.. do so! - AiNew_OnTick(c); -} diff --git a/src/ai/trolly/trolly.h b/src/ai/trolly/trolly.h deleted file mode 100644 index 60180694c..000000000 --- a/src/ai/trolly/trolly.h +++ /dev/null @@ -1,344 +0,0 @@ -/* $Id$ */ - -/** @file trolly.h Functions/defines related to the trolly AI. */ - -#ifndef AI_TROLLY_H -#define AI_TROLLY_H - -#include "../../aystar.h" -#include "../../company_type.h" -#include "../../vehicle_type.h" -#include "../../date_type.h" -#include "../../engine_type.h" -#include "../../direction_type.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 than 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 company 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 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 company -#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 than 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_WAIT_FOR_BUILD, - 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(Company *c); - -// ai_new.c -void AiNewDoGameLoop(Company *c); - -struct Ai_PathFinderInfo { - TileIndex start_tile_tl; ///< tl = top-left - TileIndex start_tile_br; ///< br = bottom-right - TileIndex end_tile_tl; ///< tl = top-left - TileIndex end_tile_br; ///< br = bottom-right - DiagDirection start_direction; ///< 0 to 3 or AI_PATHFINDER_NO_DIRECTION - DiagDirection end_direction; ///< 0 to 3 or AI_PATHFINDER_NO_DIRECTION - - TileIndex route[500]; - byte route_extra[500]; ///< Some extra information about the route like bridge/tunnel - int route_length; - int position; ///< Current position in the build-path, needed to build the path - - bool rail_or_road; ///< true = rail, false = road -}; - -// 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); -DiagDirection AiNew_GetDirection(TileIndex tile_a, TileIndex tile_b); -bool AiNew_SetSpecialVehicleFlag(Company *c, Vehicle *v, uint flag); -uint AiNew_GetSpecialVehicleFlag(Company *c, Vehicle *v); - -// ai_build.c -bool AiNew_Build_CompanyHQ(Company *c, TileIndex tile); -CommandCost AiNew_Build_Station(Company *c, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag); -CommandCost AiNew_Build_Bridge(Company *c, TileIndex tile_a, TileIndex tile_b, byte flag); -CommandCost AiNew_Build_RoutePart(Company *c, Ai_PathFinderInfo *PathFinderInfo, byte flag); -EngineID AiNew_PickVehicle(Company *c); -CommandCost AiNew_Build_Vehicle(Company *c, TileIndex tile, byte flag); -CommandCost AiNew_Build_Depot(Company *c, TileIndex tile, DiagDirection direction, byte flag); - -/* The amount of memory reserved for the AI-special-vehicles */ -#define AI_MAX_SPECIAL_VEHICLES 100 - -struct Ai_SpecialVehicle { - VehicleID veh_id; - uint32 flag; -}; - -struct CompanyAiNew { - uint8 state; - uint tick; - uint idle; - - int temp; ///< A value used in more than one function, but it just temporary - ///< The use is pretty simple: with this we can 'think' about stuff - ///< in more than one tick, and more than one AI. A static will not - ///< do, because they are not saved. This way, the AI is almost human ;) - int counter; ///< For the same reason as temp, we have counter. It can count how - ///< long we are trying something, and just abort if it takes too long - - /* Pathfinder stuff */ - Ai_PathFinderInfo path_info; - AyStar *pathfinder; - - /* Route stuff */ - - CargoID cargo; - byte tbt; ///< train/bus/truck 0/1/2 AI_TRAIN/AI_BUS/AI_TRUCK - Money new_cost; - - byte action; - - int last_id; ///< here is stored the last id of the searched city/industry - Date last_vehiclecheck_date; // Used in CheckVehicle - Ai_SpecialVehicle special_vehicles[AI_MAX_SPECIAL_VEHICLES]; ///< Some vehicles have some special flags - - TileIndex from_tile; - TileIndex to_tile; - - DiagDirectionByte from_direction; - DiagDirectionByte to_direction; - - bool from_deliver; ///< True if this is the station that GIVES cargo - bool to_deliver; - - TileIndex depot_tile; - DiagDirectionByte depot_direction; - - byte amount_veh; ///< How many vehicles we are going to build in this route - byte cur_veh; ///< How many vehicles did we bought? - VehicleID veh_id; ///< Used when bought a vehicle - VehicleID veh_main_id; ///< The ID of the first vehicle, for shared copy - - int from_ic; ///< ic = industry/city. This is the ID of them - byte from_type; ///< AI_NO_TYPE/AI_CITY/AI_INDUSTRY - int to_ic; - byte to_type; -}; -extern CompanyAiNew _companies_ainew[MAX_COMPANIES]; - -#endif /* AI_TROLLY_H */ -- cgit v1.2.3-54-g00ecf