(svn r5210) Many small changes which piled up: const, unsigned, variable scope, CSE for readability, DeMorgan, if cascades -> switch, whitespace, parentheses, bracing, misc.

This commit is contained in:
tron 2006-06-10 08:37:41 +00:00
parent 15c945c926
commit 0a72639c2d
44 changed files with 438 additions and 448 deletions

30
ai/ai.c
View File

@ -97,7 +97,7 @@ int32 AI_DoCommandCc(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint pr
/* First, do a test-run to see if we can do this */ /* First, do a test-run to see if we can do this */
res = DoCommand(tile, p1, p2, flags & ~DC_EXEC, procc); res = DoCommand(tile, p1, p2, flags & ~DC_EXEC, procc);
/* The command failed, or you didn't want to execute, or you are quering, return */ /* The command failed, or you didn't want to execute, or you are quering, return */
if ((CmdFailed(res)) || !(flags & DC_EXEC) || (flags & DC_QUERY_COST)) { if (CmdFailed(res) || !(flags & DC_EXEC) || (flags & DC_QUERY_COST)) {
return res; return res;
} }
@ -105,25 +105,28 @@ int32 AI_DoCommandCc(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint pr
_cmd_text = tmp_cmdtext; _cmd_text = tmp_cmdtext;
/* If we did a DC_EXEC, and the command did not return an error, execute it /* If we did a DC_EXEC, and the command did not return an error, execute it
over the network */ * over the network */
if (flags & DC_AUTO) procc |= CMD_AUTO; if (flags & DC_AUTO) procc |= CMD_AUTO;
if (flags & DC_NO_WATER) procc |= CMD_NO_WATER; if (flags & DC_NO_WATER) procc |= CMD_NO_WATER;
/* NetworkSend_Command needs _local_player to be set correctly, so /* NetworkSend_Command needs _local_player to be set correctly, so
adjust it, and put it back right after the function */ * adjust it, and put it back right after the function */
old_lp = _local_player; old_lp = _local_player;
_local_player = _current_player; _local_player = _current_player;
#ifdef ENABLE_NETWORK #ifdef ENABLE_NETWORK
/* Send the command */ /* Send the command */
if (_networking) if (_networking) {
/* Network is easy, send it to his handler */ /* Network is easy, send it to his handler */
NetworkSend_Command(tile, p1, p2, procc, callback); NetworkSend_Command(tile, p1, p2, procc, callback);
else } else {
#else
{
#endif #endif
/* If we execute BuildCommands directly in SP, we have a big problem with events /* If we execute BuildCommands directly in SP, we have a big problem with events
* so we need to delay is for 1 tick */ * so we need to delay is for 1 tick */
AI_PutCommandInQueue(_current_player, tile, p1, p2, procc, callback); AI_PutCommandInQueue(_current_player, tile, p1, p2, procc, callback);
}
/* Set _local_player back */ /* Set _local_player back */
_local_player = old_lp; _local_player = old_lp;
@ -173,16 +176,14 @@ void AI_RunGameLoop(void)
* them.. this avoids that, while loading a network game in singleplayer, does make * them.. this avoids that, while loading a network game in singleplayer, does make
* the AIs to continue ;)) * the AIs to continue ;))
*/ */
if (_networking && !_network_server && !_ai.network_client) if (_networking && !_network_server && !_ai.network_client) return;
return;
/* New tick */ /* New tick */
_ai.tick++; _ai.tick++;
/* Make sure the AI follows the difficulty rule.. */ /* Make sure the AI follows the difficulty rule.. */
assert(_opt.diff.competitor_speed <= 4); assert(_opt.diff.competitor_speed <= 4);
if ((_ai.tick & ((1 << (4 - _opt.diff.competitor_speed)) - 1)) != 0) if ((_ai.tick & ((1 << (4 - _opt.diff.competitor_speed)) - 1)) != 0) return;
return;
/* Check for AI-client (so joining a network with an AI) */ /* Check for AI-client (so joining a network with an AI) */
if (_ai.network_client && _ai_player[_ai.network_playas].active) { if (_ai.network_client && _ai_player[_ai.network_playas].active) {
@ -191,7 +192,7 @@ void AI_RunGameLoop(void)
AI_RunTick(_ai.network_playas); AI_RunTick(_ai.network_playas);
} else if (!_networking || _network_server) { } else if (!_networking || _network_server) {
/* Check if we want to run AIs (server or SP only) */ /* Check if we want to run AIs (server or SP only) */
Player *p; const Player* p;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (p->is_active && p->is_ai) { if (p->is_active && p->is_ai) {
@ -224,8 +225,9 @@ void AI_StartNewAI(PlayerID player)
*/ */
void AI_PlayerDied(PlayerID player) void AI_PlayerDied(PlayerID player)
{ {
if (_ai.network_client && _ai.network_playas == player) if (_ai.network_client && _ai.network_playas == player) {
_ai.network_playas = OWNER_SPECTATOR; _ai.network_playas = OWNER_SPECTATOR;
}
/* Called if this AI died */ /* Called if this AI died */
_ai_player[player].active = false; _ai_player[player].active = false;
@ -254,7 +256,7 @@ void AI_Initialize(void)
*/ */
void AI_Uninitialize(void) void AI_Uninitialize(void)
{ {
Player* p; const Player* p;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (p->is_active && p->is_ai) AI_PlayerDied(p->index); if (p->is_active && p->is_ai) AI_PlayerDied(p->index);

View File

@ -348,11 +348,11 @@ static void AiHandleReplaceRoadVeh(Player *p)
tile = v->tile; tile = v->tile;
if (!CmdFailed(DoCommand(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH)) && if (!CmdFailed(DoCommand(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH)) &&
!CmdFailed(DoCommand(tile, veh, 0, DC_EXEC, CMD_BUILD_ROAD_VEH)) ) { !CmdFailed(DoCommand(tile, veh, 0, DC_EXEC, CMD_BUILD_ROAD_VEH))) {
VehicleID veh = _new_vehicle_id; VehicleID veh = _new_vehicle_id;
AiRestoreVehicleOrders(GetVehicle(veh), orderbak); AiRestoreVehicleOrders(GetVehicle(veh), orderbak);
DoCommand(0, veh, 0, DC_EXEC, CMD_START_STOP_ROADVEH); DoCommand(0, veh, 0, DC_EXEC, CMD_START_STOP_ROADVEH);
DoCommand(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_SERVICE_INT); DoCommand(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_SERVICE_INT);
} }
} }
@ -1608,8 +1608,7 @@ clear_town_stuff:;
} }
} else if (p->mode == 3) { } else if (p->mode == 3) {
//Clear stuff and then build single rail. //Clear stuff and then build single rail.
if (GetTileSlope(c, NULL) != SLOPE_FLAT) if (GetTileSlope(c, NULL) != SLOPE_FLAT) return CMD_ERROR;
return CMD_ERROR;
ret = DoCommand(c, 0, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_LANDSCAPE_CLEAR); ret = DoCommand(c, 0, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return CMD_ERROR; if (CmdFailed(ret)) return CMD_ERROR;
total_cost += ret + _price.build_rail; total_cost += ret + _price.build_rail;
@ -1927,7 +1926,6 @@ static bool AiCheckRailPathBetter(AiRailFinder *arf, const byte *p)
static inline void AiCheckBuildRailBridgeHere(AiRailFinder *arf, TileIndex tile, const byte *p) static inline void AiCheckBuildRailBridgeHere(AiRailFinder *arf, TileIndex tile, const byte *p)
{ {
TileIndex tile_new;
Slope tileh; Slope tileh;
uint z; uint z;
bool flag; bool flag;
@ -1936,7 +1934,8 @@ static inline void AiCheckBuildRailBridgeHere(AiRailFinder *arf, TileIndex tile,
tileh = GetTileSlope(tile, &z); tileh = GetTileSlope(tile, &z);
if (tileh == _dir_table_1[dir2] || (tileh == SLOPE_FLAT && z != 0)) { if (tileh == _dir_table_1[dir2] || (tileh == SLOPE_FLAT && z != 0)) {
tile_new = tile; TileIndex tile_new = tile;
// Allow bridges directly over bottom tiles // Allow bridges directly over bottom tiles
flag = z == 0; flag = z == 0;
for (;;) { for (;;) {
@ -1977,9 +1976,7 @@ static inline void AiCheckBuildRailTunnelHere(AiRailFinder *arf, TileIndex tile,
if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) { if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) {
AiBuildRailRecursive(arf, _build_tunnel_endtile, p[0]&3); AiBuildRailRecursive(arf, _build_tunnel_endtile, p[0]&3);
if (arf->depth == 1) { if (arf->depth == 1) AiCheckRailPathBetter(arf, p);
AiCheckRailPathBetter(arf, p);
}
} }
} }
} }
@ -2009,6 +2006,7 @@ static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir)
// Depth too deep? // Depth too deep?
if (arf->depth >= 4) { if (arf->depth >= 4) {
uint dist = DistanceMaxPlusManhattan(tile, arf->final_tile); uint dist = DistanceMaxPlusManhattan(tile, arf->final_tile);
if (dist < arf->cur_best_dist) { if (dist < arf->cur_best_dist) {
// Store the tile that is closest to the final position. // Store the tile that is closest to the final position.
arf->cur_best_depth = arf->depth; arf->cur_best_depth = arf->depth;
@ -2037,9 +2035,7 @@ static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir)
} }
// At the bottom depth? // At the bottom depth?
if (arf->depth == 1) { if (arf->depth == 1) AiCheckRailPathBetter(arf, p);
AiCheckRailPathBetter(arf, p);
}
p += 2; p += 2;
} while (!(p[0]&0x80)); } while (!(p[0]&0x80));
@ -2093,8 +2089,9 @@ static void AiBuildRailConstruct(Player *p)
// Didn't find anything to build? // Didn't find anything to build?
if (arf.best_ptr == NULL) { if (arf.best_ptr == NULL) {
// Terraform some // Terraform some
for (i=0; i!=5; i++) for (i = 0; i != 5; i++) {
AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0); AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);
}
if (++p->ai.state_counter == 21) { if (++p->ai.state_counter == 21) {
p->ai.state_counter = 40; p->ai.state_counter = 40;
@ -2112,16 +2109,16 @@ static void AiBuildRailConstruct(Player *p)
int i; int i;
int32 bridge_len = GetBridgeLength(arf.bridge_end_tile, p->ai.cur_tile_a); int32 bridge_len = GetBridgeLength(arf.bridge_end_tile, p->ai.cur_tile_a);
/* Figure out what (rail)bridge type to build /* Figure out which (rail)bridge type to build
start with best bridge, then go down to worse and worse bridges * start with best bridge, then go down to worse and worse bridges
unnecessary to check for worse bridge (i=0), since AI will always build that. * unnecessary to check for worst bridge (i=0), since AI will always build
AI is so fucked up that fixing this small thing will probably not solve a thing * that. AI is so fucked up that fixing this small thing will probably not
*/ * solve a thing
*/
for (i = MAX_BRIDGES - 1; i != 0; i--) { for (i = MAX_BRIDGES - 1; i != 0; i--) {
if (CheckBridge_Stuff(i, bridge_len)) { if (CheckBridge_Stuff(i, bridge_len)) {
int32 cost = DoCommand(arf.bridge_end_tile, p->ai.cur_tile_a, i | (p->ai.railtype_to_use << 8), DC_AUTO, CMD_BUILD_BRIDGE); int32 cost = DoCommand(arf.bridge_end_tile, p->ai.cur_tile_a, i | (p->ai.railtype_to_use << 8), DC_AUTO, CMD_BUILD_BRIDGE);
if (!CmdFailed(cost) && cost < (p->player_money >> 5)) if (!CmdFailed(cost) && cost < (p->player_money >> 5)) break;
break;
} }
} }
@ -2130,7 +2127,7 @@ static void AiBuildRailConstruct(Player *p)
p->ai.cur_tile_a = arf.bridge_end_tile; p->ai.cur_tile_a = arf.bridge_end_tile;
p->ai.state_counter = 0; p->ai.state_counter = 0;
} else if (arf.best_ptr[0]&0x40) { } else if (arf.best_ptr[0] & 0x40) {
// tunnel // tunnel
DoCommand(p->ai.cur_tile_a, p->ai.railtype_to_use, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL); DoCommand(p->ai.cur_tile_a, p->ai.railtype_to_use, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
p->ai.cur_tile_a = _build_tunnel_endtile; p->ai.cur_tile_a = _build_tunnel_endtile;
@ -2348,9 +2345,7 @@ static EngineID AiFindBestWagon(CargoID cargo, RailType railtype)
continue; continue;
} }
if (rvi->cargo_type != cargo) { if (rvi->cargo_type != cargo) continue;
continue;
}
/* max_speed of 0 indicates no speed limit */ /* max_speed of 0 indicates no speed limit */
speed = rvi->max_speed == 0 ? 0xFFFF : rvi->max_speed; speed = rvi->max_speed == 0 ? 0xFFFF : rvi->max_speed;
@ -2374,7 +2369,7 @@ static void AiStateBuildRailVeh(Player *p)
CargoID cargo; CargoID cargo;
int32 cost; int32 cost;
Vehicle *v; Vehicle *v;
uint loco_id; VehicleID loco_id;
ptr = _default_rail_track_data[p->ai.src.cur_building_rule]->data; ptr = _default_rail_track_data[p->ai.src.cur_building_rule]->data;
while (ptr->mode != 0) ptr++; while (ptr->mode != 0) ptr++;
@ -2395,14 +2390,12 @@ static void AiStateBuildRailVeh(Player *p)
p->ai.wagon_list[i + 1] = INVALID_VEHICLE; p->ai.wagon_list[i + 1] = INVALID_VEHICLE;
return; return;
} }
if (cargo == CT_MAIL) if (cargo == CT_MAIL) cargo = CT_PASSENGERS;
cargo = CT_PASSENGERS; if (++i == p->ai.num_wagons * 2 - 1) break;
if (++i == p->ai.num_wagons * 2 - 1)
break;
} }
// Which locomotive to build? // Which locomotive to build?
veh = AiChooseTrainToBuild(p->ai.railtype_to_use, p->player_money, (cargo!=CT_PASSENGERS)?1:0, tile); veh = AiChooseTrainToBuild(p->ai.railtype_to_use, p->player_money, cargo != CT_PASSENGERS ? 1 : 0, tile);
if (veh == INVALID_ENGINE) { if (veh == INVALID_ENGINE) {
handle_nocash: handle_nocash:
// after a while, if AI still doesn't have cash, get out of this block by selling the wagons. // after a while, if AI still doesn't have cash, get out of this block by selling the wagons.
@ -2435,7 +2428,7 @@ handle_nocash:
} }
for (i = 0; p->ai.order_list_blocks[i] != 0xFF; i++) { for (i = 0; p->ai.order_list_blocks[i] != 0xFF; i++) {
AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i]; const AiBuildRec* aib = &p->ai.src + p->ai.order_list_blocks[i];
bool is_pass = ( bool is_pass = (
p->ai.cargo_type == CT_PASSENGERS || p->ai.cargo_type == CT_PASSENGERS ||
p->ai.cargo_type == CT_MAIL || p->ai.cargo_type == CT_MAIL ||
@ -2615,11 +2608,8 @@ clear_town_stuff:;
// Make sure the blocks are not too close to each other // Make sure the blocks are not too close to each other
static bool AiCheckBlockDistances(Player *p, TileIndex tile) static bool AiCheckBlockDistances(Player *p, TileIndex tile)
{ {
AiBuildRec *aib; const AiBuildRec* aib = &p->ai.src;
int num; uint num = p->ai.num_build_rec;
num = p->ai.num_build_rec;
aib = &p->ai.src;
do { do {
if (aib->cur_building_rule != 255) { if (aib->cur_building_rule != 255) {
@ -2835,7 +2825,6 @@ static bool AiBuildRoadHelper(TileIndex tile, int flags, int type)
static inline void AiCheckBuildRoadBridgeHere(AiRoadFinder *arf, TileIndex tile, const byte *p) static inline void AiCheckBuildRoadBridgeHere(AiRoadFinder *arf, TileIndex tile, const byte *p)
{ {
TileIndex tile_new;
Slope tileh; Slope tileh;
uint z; uint z;
bool flag; bool flag;
@ -2844,7 +2833,8 @@ static inline void AiCheckBuildRoadBridgeHere(AiRoadFinder *arf, TileIndex tile,
tileh = GetTileSlope(tile, &z); tileh = GetTileSlope(tile, &z);
if (tileh == _dir_table_1[dir2] || (tileh == SLOPE_FLAT && z != 0)) { if (tileh == _dir_table_1[dir2] || (tileh == SLOPE_FLAT && z != 0)) {
tile_new = tile; TileIndex tile_new = tile;
// Allow bridges directly over bottom tiles // Allow bridges directly over bottom tiles
flag = z == 0; flag = z == 0;
for (;;) { for (;;) {
@ -2885,9 +2875,7 @@ static inline void AiCheckBuildRoadTunnelHere(AiRoadFinder *arf, TileIndex tile,
if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) { if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) {
AiBuildRoadRecursive(arf, _build_tunnel_endtile, p[0]&3); AiBuildRoadRecursive(arf, _build_tunnel_endtile, p[0]&3);
if (arf->depth == 1) { if (arf->depth == 1) AiCheckRoadPathBetter(arf, p);
AiCheckRoadPathBetter(arf, p);
}
} }
} }
} }
@ -3032,7 +3020,6 @@ do_some_terraform:
p->ai.cur_tile_a = _build_tunnel_endtile; p->ai.cur_tile_a = _build_tunnel_endtile;
p->ai.state_counter = 0; p->ai.state_counter = 0;
} else { } else {
// road // road
if (!AiBuildRoadHelper(tile, DC_EXEC | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, arf.best_ptr[0])) if (!AiBuildRoadHelper(tile, DC_EXEC | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, arf.best_ptr[0]))
goto do_some_terraform; goto do_some_terraform;
@ -3062,8 +3049,9 @@ static void AiBuildRoad(Player *p)
uint i; uint i;
// Terraform some and then try building again. // Terraform some and then try building again.
for (i = 0; i != 4; i++) for (i = 0; i != 4; i++) {
AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0); AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);
}
if (++p->ai.state_counter == 4) { if (++p->ai.state_counter == 4) {
p->ai.state_counter = 0; p->ai.state_counter = 0;
@ -3156,7 +3144,7 @@ static void AiStateBuildRoadVehicles(Player *p)
{ {
const AiDefaultBlockData *ptr; const AiDefaultBlockData *ptr;
TileIndex tile; TileIndex tile;
uint loco_id; VehicleID loco_id;
EngineID veh; EngineID veh;
uint i; uint i;
@ -3227,7 +3215,7 @@ static void AiStateDeleteRoadBlocks(Player *p)
static void AiStateAirportStuff(Player *p) static void AiStateAirportStuff(Player *p)
{ {
Station *st; const Station* st;
byte acc_planes; byte acc_planes;
int i; int i;
AiBuildRec *aib; AiBuildRec *aib;
@ -3449,10 +3437,10 @@ static void AiStateBuildAircraftVehicles(Player *p)
TileIndex tile; TileIndex tile;
EngineID veh; EngineID veh;
int i; int i;
uint loco_id; VehicleID loco_id;
ptr = _airport_default_block_data[p->ai.src.cur_building_rule]; ptr = _airport_default_block_data[p->ai.src.cur_building_rule];
for (;ptr->mode!=0;ptr++) {} for (; ptr->mode != 0; ptr++) {}
tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs)); tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));
@ -3465,7 +3453,7 @@ static void AiStateBuildAircraftVehicles(Player *p)
if (CmdFailed(DoCommand(tile, veh, 0, DC_EXEC, CMD_BUILD_AIRCRAFT))) return; if (CmdFailed(DoCommand(tile, veh, 0, DC_EXEC, CMD_BUILD_AIRCRAFT))) return;
loco_id = _new_vehicle_id; loco_id = _new_vehicle_id;
for (i=0; p->ai.order_list_blocks[i] != 0xFF; i++) { for (i = 0; p->ai.order_list_blocks[i] != 0xFF; i++) {
AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i]; AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i];
bool is_pass = (p->ai.cargo_type == CT_PASSENGERS || p->ai.cargo_type == CT_MAIL); bool is_pass = (p->ai.cargo_type == CT_PASSENGERS || p->ai.cargo_type == CT_MAIL);
Order order; Order order;
@ -3664,27 +3652,20 @@ pos_3:
if (GetRoadTileType(tile) == ROAD_TILE_DEPOT) { if (GetRoadTileType(tile) == ROAD_TILE_DEPOT) {
DiagDirection dir; DiagDirection dir;
TileIndex t;
// Check if there are any stations around. // Check if there are any stations around.
if (IsTileType(tile + TileDiffXY(-1, 0), MP_STATION) && t = tile + TileDiffXY(-1, 0);
IsTileOwner(tile + TileDiffXY(-1, 0), _current_player)) { if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
return;
}
if (IsTileType(tile + TileDiffXY(1, 0), MP_STATION) && t = tile + TileDiffXY(1, 0);
IsTileOwner(tile + TileDiffXY(1, 0), _current_player)) { if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
return;
}
if (IsTileType(tile + TileDiffXY(0, -1), MP_STATION) && t = tile + TileDiffXY(0, -1);
IsTileOwner(tile + TileDiffXY(0, -1), _current_player)) { if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
return;
}
if (IsTileType(tile + TileDiffXY(0, 1), MP_STATION) && t = tile + TileDiffXY(0, 1);
IsTileOwner(tile + TileDiffXY(0, 1), _current_player)) { if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
return;
}
dir = GetRoadDepotDirection(tile); dir = GetRoadDepotDirection(tile);
@ -3881,8 +3862,7 @@ void AiDoGameLoop(Player *p)
// or in % // or in %
_ai_service_interval = _patches.servint_ispercent?80:180; _ai_service_interval = _patches.servint_ispercent?80:180;
if (IS_HUMAN_PLAYER(_current_player)) if (IS_HUMAN_PLAYER(_current_player)) return;
return;
AiAdjustLoan(p); AiAdjustLoan(p);
AiBuildCompanyHQ(p); AiBuildCompanyHQ(p);

View File

@ -68,14 +68,15 @@ int AiNew_Build_Bridge(Player *p, TileIndex tile_a, TileIndex tile_b, byte flag)
if (type2 != 0) break; if (type2 != 0) break;
} }
} }
// There is only one bridge that can be build.. // There is only one bridge that can be built
if (type2 == 0 && type != 0) type2 = type; if (type2 == 0 && type != 0) type2 = type;
// Now, simply, build the bridge! // Now, simply, build the bridge!
if (p->ainew.tbt == AI_TRAIN) if (p->ainew.tbt == AI_TRAIN) {
return AI_DoCommand(tile_a, tile_b, (0<<8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE); return AI_DoCommand(tile_a, tile_b, (0x00 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
} else {
return AI_DoCommand(tile_a, tile_b, (0x80 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE); return AI_DoCommand(tile_a, tile_b, (0x80 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
}
} }
@ -102,7 +103,10 @@ int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte fla
// the first pieces and the last piece // the first pieces and the last piece
if (part < 1) part = 1; if (part < 1) part = 1;
// When we are done, stop it // When we are done, stop it
if (part >= PathFinderInfo->route_length - 1) { PathFinderInfo->position = -2; return 0; } if (part >= PathFinderInfo->route_length - 1) {
PathFinderInfo->position = -2;
return 0;
}
if (PathFinderInfo->rail_or_road) { if (PathFinderInfo->rail_or_road) {
@ -112,7 +116,7 @@ int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte fla
PathFinderInfo->position++; PathFinderInfo->position++;
// TODO: problems! // TODO: problems!
if (CmdFailed(cost)) { if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be build!"); DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be built!");
return 0; return 0;
} }
return cost; return cost;
@ -123,7 +127,7 @@ int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte fla
PathFinderInfo->position++; PathFinderInfo->position++;
// TODO: problems! // TODO: problems!
if (CmdFailed(cost)) { if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be build!"); DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be built!");
return 0; return 0;
} }
return cost; return cost;
@ -131,7 +135,7 @@ int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte fla
// Build normal rail // Build normal rail
// Keep it doing till we go an other way // Keep it doing till we go an other way
if (route_extra[part-1] == 0 && route_extra[part] == 0) { if (route_extra[part - 1] == 0 && route_extra[part] == 0) {
while (route_extra[part] == 0) { while (route_extra[part] == 0) {
// Get the current direction // Get the current direction
dir = AiNew_GetRailDirection(route[part-1], route[part], route[part+1]); dir = AiNew_GetRailDirection(route[part-1], route[part], route[part+1]);

View File

@ -57,7 +57,8 @@ static bool IsRoad(TileIndex tile)
// Check if the current tile is in our end-area // Check if the current tile is in our end-area
static int32 AyStar_AiPathFinder_EndNodeCheck(AyStar *aystar, OpenListNode *current) static int32 AyStar_AiPathFinder_EndNodeCheck(AyStar *aystar, OpenListNode *current)
{ {
Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target; const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target;
// It is not allowed to have a station on the end of a bridge or tunnel ;) // 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 (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 (TILES_BETWEEN(current->path.node.tile, PathFinderInfo->end_tile_tl, PathFinderInfo->end_tile_br))
@ -155,9 +156,11 @@ void clean_AyStar_AiPathFinder(AyStar *aystar, Ai_PathFinderInfo *PathFinderInfo
// Now we add all the starting tiles // Now we add all the starting tiles
for (x = TileX(PathFinderInfo->start_tile_tl); x <= TileX(PathFinderInfo->start_tile_br); x++) { 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++) { for (y = TileY(PathFinderInfo->start_tile_tl); y <= TileY(PathFinderInfo->start_tile_br); y++) {
if (!(IsTileType(TileXY(x, y), MP_CLEAR) || IsTileType(TileXY(x, y), MP_TREES))) continue; TileIndex tile = TileXY(x, y);
if (!TestCanBuildStationHere(TileXY(x, y), TEST_STATION_NO_DIR)) continue;
start_node.node.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); aystar->addstart(aystar, &start_node.node, 0);
} }
} }
@ -167,8 +170,9 @@ void clean_AyStar_AiPathFinder(AyStar *aystar, Ai_PathFinderInfo *PathFinderInfo
// The h-value, simple calculation // The h-value, simple calculation
static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent) static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
{ {
Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target; const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target;
int r, r2; int r, r2;
if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION) { 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 // The station is pointing to a direction, add a tile towards that direction, so the H-value is more accurate
r = DistanceManhattan(current->tile, PathFinderInfo->end_tile_tl + TileOffsByDir(PathFinderInfo->end_direction)); r = DistanceManhattan(current->tile, PathFinderInfo->end_tile_tl + TileOffsByDir(PathFinderInfo->end_direction));
@ -447,13 +451,15 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current,
// Check if we are going up or down, first for the starting point // Check if we are going up or down, first for the starting point
// In user_data[0] is at the 8th bit the direction // In user_data[0] is at the 8th bit the direction
if (!HASBIT(BRIDGE_NO_FOUNDATION, parent_tileh)) { if (!HASBIT(BRIDGE_NO_FOUNDATION, parent_tileh)) {
if (GetBridgeFoundation(parent_tileh, (current->user_data[0] >> 8) & 1) < 15) if (GetBridgeFoundation(parent_tileh, (current->user_data[0] >> 8) & 1) < 15) {
res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY; res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
}
} }
// Second for the end point // Second for the end point
if (!HASBIT(BRIDGE_NO_FOUNDATION, tileh)) { if (!HASBIT(BRIDGE_NO_FOUNDATION, tileh)) {
if (GetBridgeFoundation(tileh, (current->user_data[0] >> 8) & 1) < 15) if (GetBridgeFoundation(tileh, (current->user_data[0] >> 8) & 1) < 15) {
res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY; res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
}
} }
if (parent_tileh == SLOPE_FLAT) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY; if (parent_tileh == SLOPE_FLAT) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
if (tileh == SLOPE_FLAT) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY; if (tileh == SLOPE_FLAT) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
@ -466,10 +472,11 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current,
if (parent->path.parent != NULL && if (parent->path.parent != NULL &&
AiNew_GetDirection(current->tile, parent->path.node.tile) != AiNew_GetDirection(parent->path.node.tile, parent->path.parent->node.tile)) { 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 // 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)) if (IsRoad(parent->path.node.tile)) {
res += AI_PATHFINDER_DIRECTION_CHANGE_ON_EXISTING_ROAD_PENALTY; res += AI_PATHFINDER_DIRECTION_CHANGE_ON_EXISTING_ROAD_PENALTY;
else } else {
res += AI_PATHFINDER_DIRECTION_CHANGE_PENALTY; res += AI_PATHFINDER_DIRECTION_CHANGE_PENALTY;
}
} }
} else { } else {
// For rail we have 1 exeption: diagonal rail.. // For rail we have 1 exeption: diagonal rail..

View File

@ -128,16 +128,19 @@ static void AiNew_State_WakeUp(Player *p)
} else if (c < 100 && !_patches.ai_disable_veh_roadveh) { } else if (c < 100 && !_patches.ai_disable_veh_roadveh) {
// Do we have any spots for road-vehicles left open? // Do we have any spots for road-vehicles left open?
if (GetFreeUnitNumber(VEH_Road) <= _patches.max_roadveh) { if (GetFreeUnitNumber(VEH_Road) <= _patches.max_roadveh) {
if (c < 85) if (c < 85) {
p->ainew.action = AI_ACTION_TRUCK_ROUTE; p->ainew.action = AI_ACTION_TRUCK_ROUTE;
else } else {
p->ainew.action = AI_ACTION_BUS_ROUTE; p->ainew.action = AI_ACTION_BUS_ROUTE;
}
} }
}/* else if (c < 200 && !_patches.ai_disable_veh_train) { #if 0
} else if (c < 200 && !_patches.ai_disable_veh_train) {
if (GetFreeUnitNumber(VEH_Train) <= _patches.max_trains) { if (GetFreeUnitNumber(VEH_Train) <= _patches.max_trains) {
p->ainew.action = AI_ACTION_TRAIN_ROUTE; p->ainew.action = AI_ACTION_TRAIN_ROUTE;
} }
}*/ #endif
}
p->ainew.counter = 0; p->ainew.counter = 0;
} }
@ -208,8 +211,8 @@ static void AiNew_State_ActionDone(Player *p)
static bool AiNew_Check_City_or_Industry(Player *p, int ic, byte type) static bool AiNew_Check_City_or_Industry(Player *p, int ic, byte type)
{ {
if (type == AI_CITY) { if (type == AI_CITY) {
Town *t = GetTown(ic); const Town* t = GetTown(ic);
Station *st; const Station* st;
uint count = 0; uint count = 0;
int j = 0; int j = 0;
@ -270,8 +273,8 @@ static bool AiNew_Check_City_or_Industry(Player *p, int ic, byte type)
return true; return true;
} }
if (type == AI_INDUSTRY) { if (type == AI_INDUSTRY) {
Industry *i = GetIndustry(ic); const Industry* i = GetIndustry(ic);
Station *st; const Station* st;
int count = 0; int count = 0;
int j = 0; int j = 0;
@ -379,10 +382,11 @@ static void AiNew_State_LocateRoute(Player *p)
if (p->ainew.from_ic == -1) { if (p->ainew.from_ic == -1) {
if (p->ainew.temp == -1) { if (p->ainew.temp == -1) {
// First, we pick a random spot to search from // First, we pick a random spot to search from
if (p->ainew.from_type == AI_CITY) if (p->ainew.from_type == AI_CITY) {
p->ainew.temp = AI_RandomRange(_total_towns); p->ainew.temp = AI_RandomRange(_total_towns);
else } else {
p->ainew.temp = AI_RandomRange(_total_industries); p->ainew.temp = AI_RandomRange(_total_industries);
}
} }
if (!AiNew_Check_City_or_Industry(p, p->ainew.temp, p->ainew.from_type)) { if (!AiNew_Check_City_or_Industry(p, p->ainew.temp, p->ainew.from_type)) {
@ -414,10 +418,11 @@ static void AiNew_State_LocateRoute(Player *p)
// Find a to-city // Find a to-city
if (p->ainew.temp == -1) { if (p->ainew.temp == -1) {
// First, we pick a random spot to search to // First, we pick a random spot to search to
if (p->ainew.to_type == AI_CITY) if (p->ainew.to_type == AI_CITY) {
p->ainew.temp = AI_RandomRange(_total_towns); p->ainew.temp = AI_RandomRange(_total_towns);
else } else {
p->ainew.temp = AI_RandomRange(_total_industries); p->ainew.temp = AI_RandomRange(_total_industries);
}
} }
// The same city is not allowed // The same city is not allowed
@ -425,9 +430,10 @@ static void AiNew_State_LocateRoute(Player *p)
if (p->ainew.temp != p->ainew.from_ic && AiNew_Check_City_or_Industry(p, p->ainew.temp, p->ainew.to_type)) { if (p->ainew.temp != p->ainew.from_ic && AiNew_Check_City_or_Industry(p, p->ainew.temp, p->ainew.to_type)) {
// Maybe it is valid.. // Maybe it is valid..
// We need to know if they are not to far apart from eachother.. /* 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 * We do that by checking how much cargo we have to move and how long the
// is. * route is.
*/
if (p->ainew.from_type == AI_CITY && p->ainew.tbt == AI_BUS) { if (p->ainew.from_type == AI_CITY && p->ainew.tbt == AI_BUS) {
const Town* town_from = GetTown(p->ainew.from_ic); const Town* town_from = GetTown(p->ainew.from_ic);
@ -470,7 +476,7 @@ static void AiNew_State_LocateRoute(Player *p)
for (i = 0; i < lengthof(ind_temp->accepts_cargo); i++) { for (i = 0; i < lengthof(ind_temp->accepts_cargo); i++) {
if (ind_temp->accepts_cargo[i] == CT_INVALID) break; if (ind_temp->accepts_cargo[i] == CT_INVALID) break;
if (ind_from->produced_cargo[0] == ind_temp->accepts_cargo[i]) { if (ind_from->produced_cargo[0] == ind_temp->accepts_cargo[i]) {
// Found a compatbiel industry // Found a compatible industry
max_cargo = ind_from->total_production[0] - ind_from->total_transported[0]; max_cargo = ind_from->total_production[0] - ind_from->total_transported[0];
found = true; found = true;
p->ainew.from_deliver = true; p->ainew.from_deliver = true;
@ -672,7 +678,7 @@ static void AiNew_State_FindStation(Player *p)
} }
} }
// If i is still zero, we did not found anything :( // If i is still zero, we did not find anything
if (i == 0) { if (i == 0) {
p->ainew.state = AI_STATE_NOTHING; p->ainew.state = AI_STATE_NOTHING;
return; return;
@ -682,7 +688,7 @@ static void AiNew_State_FindStation(Player *p)
best = 0; best = 0;
new_tile = 0; new_tile = 0;
for (x=0;x<i;x++) { for (x = 0; x < i; x++) {
if (found_best[x] > best || if (found_best[x] > best ||
(found_best[x] == best && DistanceManhattan(tile, new_tile) > DistanceManhattan(tile, found_spot[x]))) { (found_best[x] == best && DistanceManhattan(tile, new_tile) > DistanceManhattan(tile, found_spot[x]))) {
new_tile = found_spot[x]; new_tile = found_spot[x];
@ -753,10 +759,7 @@ static void AiNew_State_FindPath(Player *p)
p->ainew.path_info.end_direction = p->ainew.to_direction; p->ainew.path_info.end_direction = p->ainew.to_direction;
} }
if (p->ainew.tbt == AI_TRAIN) p->ainew.path_info.rail_or_road = (p->ainew.tbt == AI_TRAIN);
p->ainew.path_info.rail_or_road = true;
else
p->ainew.path_info.rail_or_road = false;
// First, clean the pathfinder with our new begin and endpoints // First, clean the pathfinder with our new begin and endpoints
clean_AyStar_AiPathFinder(p->ainew.pathfinder, &p->ainew.path_info); clean_AyStar_AiPathFinder(p->ainew.pathfinder, &p->ainew.path_info);
@ -766,20 +769,21 @@ static void AiNew_State_FindPath(Player *p)
// Start the pathfinder // Start the pathfinder
r = p->ainew.pathfinder->main(p->ainew.pathfinder); r = p->ainew.pathfinder->main(p->ainew.pathfinder);
// If it return: no match, stop it... switch (r) {
if (r == AYSTAR_NO_PATH) { case AYSTAR_NO_PATH:
DEBUG(ai,1)("[AiNew] PathFinder found no route!"); DEBUG(ai,1)("[AiNew] PathFinder found no route!");
// Start all over again... // Start all over again
p->ainew.state = AI_STATE_NOTHING; p->ainew.state = AI_STATE_NOTHING;
return; break;
case AYSTAR_FOUND_END_NODE: // We found the end-point
p->ainew.temp = -1;
p->ainew.state = AI_STATE_FIND_DEPOT;
break;
// In any other case, we are still busy finding the route
default: break;
} }
if (r == AYSTAR_FOUND_END_NODE) {
// We found the end-point
p->ainew.temp = -1;
p->ainew.state = AI_STATE_FIND_DEPOT;
return;
}
// In any other case, we are still busy finding the route...
} }
@ -900,10 +904,11 @@ static int AiNew_HowManyVehicles(Player *p)
length = p->ainew.path_info.route_length; length = p->ainew.path_info.route_length;
// Calculating tiles a day a vehicle moves is not easy.. this is how it must be done! // 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; tiles_a_day = RoadVehInfo(i)->max_speed * DAY_TICKS / 256 / 16;
if (p->ainew.from_deliver) if (p->ainew.from_deliver) {
max_cargo = GetIndustry(p->ainew.from_ic)->total_production[0]; max_cargo = GetIndustry(p->ainew.from_ic)->total_production[0];
else } else {
max_cargo = GetIndustry(p->ainew.to_ic)->total_production[0]; max_cargo = GetIndustry(p->ainew.to_ic)->total_production[0];
}
// This is because moving 60% is more than we can dream of! // This is because moving 60% is more than we can dream of!
max_cargo *= 0.6; max_cargo *= 0.6;
@ -1109,7 +1114,7 @@ static void AiNew_State_BuildDepot(Player *p)
if (IsTileType(p->ainew.depot_tile, MP_STREET) && GetRoadTileType(p->ainew.depot_tile) == ROAD_TILE_DEPOT) { if (IsTileType(p->ainew.depot_tile, MP_STREET) && GetRoadTileType(p->ainew.depot_tile) == ROAD_TILE_DEPOT) {
if (IsTileOwner(p->ainew.depot_tile, _current_player)) { if (IsTileOwner(p->ainew.depot_tile, _current_player)) {
// The depot is already builded! // The depot is already built
p->ainew.state = AI_STATE_BUILD_VEHICLE; p->ainew.state = AI_STATE_BUILD_VEHICLE;
return; return;
} else { } else {

View File

@ -25,24 +25,24 @@ int _aystar_stats_closed_size;
// This looks in the Hash if a node exists in ClosedList // This looks in the Hash if a node exists in ClosedList
// If so, it returns the PathNode, else NULL // If so, it returns the PathNode, else NULL
static PathNode *AyStarMain_ClosedList_IsInList(AyStar *aystar, AyStarNode *node) static PathNode* AyStarMain_ClosedList_IsInList(AyStar* aystar, const AyStarNode* node)
{ {
return (PathNode*)Hash_Get(&aystar->ClosedListHash, node->tile, node->direction); return (PathNode*)Hash_Get(&aystar->ClosedListHash, node->tile, node->direction);
} }
// This adds a node to the ClosedList // This adds a node to the ClosedList
// It makes a copy of the data // It makes a copy of the data
static void AyStarMain_ClosedList_Add(AyStar *aystar, PathNode *node) static void AyStarMain_ClosedList_Add(AyStar* aystar, const PathNode* node)
{ {
// Add a node to the ClosedList // Add a node to the ClosedList
PathNode *new_node = malloc(sizeof(PathNode)); PathNode* new_node = malloc(sizeof(*new_node));
*new_node = *node; *new_node = *node;
Hash_Set(&aystar->ClosedListHash, node->node.tile, node->node.direction, new_node); Hash_Set(&aystar->ClosedListHash, node->node.tile, node->node.direction, new_node);
} }
// Checks if a node is in the OpenList // Checks if a node is in the OpenList
// If so, it returns the OpenListNode, else NULL // If so, it returns the OpenListNode, else NULL
static OpenListNode *AyStarMain_OpenList_IsInList(AyStar *aystar, AyStarNode *node) static OpenListNode* AyStarMain_OpenList_IsInList(AyStar* aystar, const AyStarNode* node)
{ {
return (OpenListNode*)Hash_Get(&aystar->OpenListHash, node->tile, node->direction); return (OpenListNode*)Hash_Get(&aystar->OpenListHash, node->tile, node->direction);
} }
@ -54,18 +54,19 @@ static OpenListNode *AyStarMain_OpenList_Pop(AyStar *aystar)
{ {
// Return the item the Queue returns.. the best next OpenList item. // Return the item the Queue returns.. the best next OpenList item.
OpenListNode* res = (OpenListNode*)aystar->OpenListQueue.pop(&aystar->OpenListQueue); OpenListNode* res = (OpenListNode*)aystar->OpenListQueue.pop(&aystar->OpenListQueue);
if (res != NULL) if (res != NULL) {
Hash_Delete(&aystar->OpenListHash, res->path.node.tile, res->path.node.direction); Hash_Delete(&aystar->OpenListHash, res->path.node.tile, res->path.node.direction);
}
return res; return res;
} }
// Adds a node to the OpenList // Adds a node to the OpenList
// It makes a copy of node, and puts the pointer of parent in the struct // It makes a copy of node, and puts the pointer of parent in the struct
static void AyStarMain_OpenList_Add(AyStar *aystar, PathNode *parent, AyStarNode *node, int f, int g) static void AyStarMain_OpenList_Add(AyStar* aystar, PathNode* parent, const AyStarNode* node, int f, int g)
{ {
// Add a new Node to the OpenList // Add a new Node to the OpenList
OpenListNode* new_node = malloc(sizeof(OpenListNode)); OpenListNode* new_node = malloc(sizeof(*new_node));
new_node->g = g; new_node->g = g;
new_node->path.parent = parent; new_node->path.parent = parent;
new_node->path.node = *node; new_node->path.node = *node;
@ -80,7 +81,8 @@ static void AyStarMain_OpenList_Add(AyStar *aystar, PathNode *parent, AyStarNode
* return values: * return values:
* AYSTAR_DONE : indicates we are done * AYSTAR_DONE : indicates we are done
*/ */
int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *parent) { int AyStarMain_CheckTile(AyStar* aystar, AyStarNode* current, OpenListNode* parent)
{
int new_f, new_g, new_h; int new_f, new_g, new_h;
PathNode *closedlist_parent; PathNode *closedlist_parent;
OpenListNode *check; OpenListNode *check;
@ -111,7 +113,8 @@ int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *pare
closedlist_parent = AyStarMain_ClosedList_IsInList(aystar, &parent->path.node); closedlist_parent = AyStarMain_ClosedList_IsInList(aystar, &parent->path.node);
// Check if this item is already in the OpenList // Check if this item is already in the OpenList
if ((check = AyStarMain_OpenList_IsInList(aystar, current)) != NULL) { check = AyStarMain_OpenList_IsInList(aystar, current);
if (check != NULL) {
uint i; uint i;
// Yes, check if this g value is lower.. // Yes, check if this g value is lower..
if (new_g > check->g) return AYSTAR_DONE; if (new_g > check->g) return AYSTAR_DONE;
@ -120,8 +123,9 @@ int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *pare
check->g = new_g; check->g = new_g;
check->path.parent = closedlist_parent; check->path.parent = closedlist_parent;
/* Copy user data, will probably have changed */ /* Copy user data, will probably have changed */
for (i=0;i<lengthof(current->user_data);i++) for (i = 0; i < lengthof(current->user_data); i++) {
check->path.node.user_data[i] = current->user_data[i]; check->path.node.user_data[i] = current->user_data[i];
}
// Readd him in the OpenListQueue // Readd him in the OpenListQueue
aystar->OpenListQueue.push(&aystar->OpenListQueue, check, new_f); aystar->OpenListQueue.push(&aystar->OpenListQueue, check, new_f);
} else { } else {
@ -143,15 +147,14 @@ int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *pare
* AYSTAR_FOUND_END_NODE : indicates we found the end. Path_found now is true, and in path is the path found. * AYSTAR_FOUND_END_NODE : indicates we found the end. Path_found now is true, and in path is the path found.
* AYSTAR_STILL_BUSY : indicates we have done this tile, did not found the path yet, and have items left to try. * AYSTAR_STILL_BUSY : indicates we have done this tile, did not found the path yet, and have items left to try.
*/ */
int AyStarMain_Loop(AyStar *aystar) { int AyStarMain_Loop(AyStar* aystar)
{
int i, r; int i, r;
// Get the best node from OpenList // Get the best node from OpenList
OpenListNode *current = AyStarMain_OpenList_Pop(aystar); OpenListNode *current = AyStarMain_OpenList_Pop(aystar);
// If empty, drop an error // If empty, drop an error
if (current == NULL) { if (current == NULL) return AYSTAR_EMPTY_OPENLIST;
return AYSTAR_EMPTY_OPENLIST;
}
// Check for end node and if found, return that code // Check for end node and if found, return that code
if (aystar->EndNodeCheck(aystar, current) == AYSTAR_FOUND_END_NODE) { if (aystar->EndNodeCheck(aystar, current) == AYSTAR_FOUND_END_NODE) {
@ -168,7 +171,7 @@ int AyStarMain_Loop(AyStar *aystar) {
aystar->GetNeighbours(aystar, current); aystar->GetNeighbours(aystar, current);
// Go through all neighbours // Go through all neighbours
for (i=0;i<aystar->num_neighbours;i++) { for (i = 0; i < aystar->num_neighbours; i++) {
// Check and add them to the OpenList if needed // Check and add them to the OpenList if needed
r = aystar->checktile(aystar, &aystar->neighbours[i], current); r = aystar->checktile(aystar, &aystar->neighbours[i], current);
} }
@ -188,7 +191,8 @@ int AyStarMain_Loop(AyStar *aystar) {
/* /*
* This function frees the memory it allocated * This function frees the memory it allocated
*/ */
void AyStarMain_Free(AyStar *aystar) { void AyStarMain_Free(AyStar* aystar)
{
aystar->OpenListQueue.free(&aystar->OpenListQueue, false); aystar->OpenListQueue.free(&aystar->OpenListQueue, false);
/* 2nd argument above is false, below is true, to free the values only /* 2nd argument above is false, below is true, to free the values only
* once */ * once */
@ -203,7 +207,8 @@ void AyStarMain_Free(AyStar *aystar) {
* This function make the memory go back to zero * This function make the memory go back to zero
* This function should be called when you are using the same instance again. * This function should be called when you are using the same instance again.
*/ */
void AyStarMain_Clear(AyStar *aystar) { void AyStarMain_Clear(AyStar* aystar)
{
// Clean the Queue, but not the elements within. That will be done by // Clean the Queue, but not the elements within. That will be done by
// the hash. // the hash.
aystar->OpenListQueue.clear(&aystar->OpenListQueue, false); aystar->OpenListQueue.clear(&aystar->OpenListQueue, false);
@ -232,12 +237,12 @@ int AyStarMain_Main(AyStar *aystar) {
// Quit if result is no AYSTAR_STILL_BUSY or is more than loops_per_tick // Quit if result is no AYSTAR_STILL_BUSY or is more than loops_per_tick
while ((r = aystar->loop(aystar)) == AYSTAR_STILL_BUSY && (aystar->loops_per_tick == 0 || ++i < aystar->loops_per_tick)) { } while ((r = aystar->loop(aystar)) == AYSTAR_STILL_BUSY && (aystar->loops_per_tick == 0 || ++i < aystar->loops_per_tick)) { }
#ifdef AYSTAR_DEBUG #ifdef AYSTAR_DEBUG
if (r == AYSTAR_FOUND_END_NODE) switch (r) {
printf("[AyStar] Found path!\n"); case AYSTAR_FOUND_END_NODE: printf("[AyStar] Found path!\n"); break;
else if (r == AYSTAR_EMPTY_OPENLIST) case AYSTAR_EMPTY_OPENLIST: printf("[AyStar] OpenList run dry, no path found\n"); break;
printf("[AyStar] OpenList run dry, no path found\n"); case AYSTAR_LIMIT_REACHED: printf("[AyStar] Exceeded search_nodes, no path found\n"); break;
else if (r == AYSTAR_LIMIT_REACHED) default: break;
printf("[AyStar] Exceeded search_nodes, no path found\n"); }
#endif #endif
if (r != AYSTAR_STILL_BUSY) { if (r != AYSTAR_STILL_BUSY) {
/* We're done, clean up */ /* We're done, clean up */
@ -246,13 +251,12 @@ int AyStarMain_Main(AyStar *aystar) {
aystar->clear(aystar); aystar->clear(aystar);
} }
// Check result-value switch (r) {
if (r == AYSTAR_FOUND_END_NODE) return AYSTAR_FOUND_END_NODE; case AYSTAR_FOUND_END_NODE: return AYSTAR_FOUND_END_NODE;
// Check if we have some left in the OpenList case AYSTAR_EMPTY_OPENLIST:
if (r == AYSTAR_EMPTY_OPENLIST || r == AYSTAR_LIMIT_REACHED) return AYSTAR_NO_PATH; case AYSTAR_LIMIT_REACHED: return AYSTAR_NO_PATH;
default: return AYSTAR_STILL_BUSY;
// Return we are still busy }
return AYSTAR_STILL_BUSY;
} }
/* /*
@ -262,7 +266,8 @@ int AyStarMain_Main(AyStar *aystar) {
* clear() automatically when the algorithm finishes * clear() automatically when the algorithm finishes
* g is the cost for starting with this node. * g is the cost for starting with this node.
*/ */
void AyStarMain_AddStartNode(AyStar *aystar, AyStarNode *start_node, uint g) { void AyStarMain_AddStartNode(AyStar* aystar, AyStarNode* start_node, uint g)
{
#ifdef AYSTAR_DEBUG #ifdef AYSTAR_DEBUG
printf("[AyStar] Starting A* Algorithm from node (%d, %d, %d)\n", printf("[AyStar] Starting A* Algorithm from node (%d, %d, %d)\n",
TileX(start_node->tile), TileY(start_node->tile), start_node->direction); TileX(start_node->tile), TileY(start_node->tile), start_node->direction);
@ -270,7 +275,8 @@ void AyStarMain_AddStartNode(AyStar *aystar, AyStarNode *start_node, uint g) {
AyStarMain_OpenList_Add(aystar, NULL, start_node, 0, g); AyStarMain_OpenList_Add(aystar, NULL, start_node, 0, g);
} }
void init_AyStar(AyStar* aystar, Hash_HashProc hash, uint num_buckets) { void init_AyStar(AyStar* aystar, Hash_HashProc hash, uint num_buckets)
{
// Allocated the Hash for the OpenList and ClosedList // Allocated the Hash for the OpenList and ClosedList
init_Hash(&aystar->OpenListHash, hash, num_buckets); init_Hash(&aystar->OpenListHash, hash, num_buckets);
init_Hash(&aystar->ClosedListHash, hash, num_buckets); init_Hash(&aystar->ClosedListHash, hash, num_buckets);

View File

@ -142,8 +142,7 @@ static bool TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height
for (;;) { for (;;) {
if (count == 0) { if (count == 0) {
if (ts->modheight_count >= 576) if (ts->modheight_count >= 576) return false;
return false;
ts->modheight_count++; ts->modheight_count++;
break; break;
} }
@ -190,6 +189,7 @@ static bool TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height
int32 CmdTerraformLand(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) int32 CmdTerraformLand(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
{ {
TerraformerState ts; TerraformerState ts;
TileIndex t;
int direction; int direction;
TerraformerHeightMod modheight_data[576]; TerraformerHeightMod modheight_data[576];
@ -210,27 +210,31 @@ int32 CmdTerraformLand(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
if (tile + TileDiffXY(1, 1) >= MapSize()) return CMD_ERROR; if (tile + TileDiffXY(1, 1) >= MapSize()) return CMD_ERROR;
if (p1 & 1) { if (p1 & 1) {
if (!TerraformTileHeight(&ts, tile + TileDiffXY(1, 0), t = tile + TileDiffXY(1, 0);
TileHeight(tile + TileDiffXY(1, 0)) + direction)) if (!TerraformTileHeight(&ts, t, TileHeight(t) + direction)) {
return CMD_ERROR; return CMD_ERROR;
}
} }
if (p1 & 2) { if (p1 & 2) {
if (!TerraformTileHeight(&ts, tile + TileDiffXY(1, 1), t = tile + TileDiffXY(1, 1);
TileHeight(tile + TileDiffXY(1, 1)) + direction)) if (!TerraformTileHeight(&ts, t, TileHeight(t) + direction)) {
return CMD_ERROR; return CMD_ERROR;
}
} }
if (p1 & 4) { if (p1 & 4) {
if (!TerraformTileHeight(&ts, tile + TileDiffXY(0, 1), t = tile + TileDiffXY(0, 1);
TileHeight(tile + TileDiffXY(0, 1)) + direction)) if (!TerraformTileHeight(&ts, t, TileHeight(t) + direction)) {
return CMD_ERROR; return CMD_ERROR;
}
} }
if (p1 & 8) { if (p1 & 8) {
if (!TerraformTileHeight(&ts, tile + TileDiffXY(0, 0), t = tile + TileDiffXY(0, 0);
TileHeight(tile + TileDiffXY(0, 0)) + direction)) if (!TerraformTileHeight(&ts, t, TileHeight(t) + direction)) {
return CMD_ERROR; return CMD_ERROR;
}
} }
{ /* Check if tunnel or track would take damage */ { /* Check if tunnel or track would take damage */
@ -430,8 +434,7 @@ int32 CmdSellLandArea(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
if (!EnsureNoVehicle(tile)) return CMD_ERROR; if (!EnsureNoVehicle(tile)) return CMD_ERROR;
if (flags & DC_EXEC) if (flags & DC_EXEC) DoClearSquare(tile);
DoClearSquare(tile);
return - _price.purchase_land * 2; return - _price.purchase_land * 2;
} }

View File

@ -314,7 +314,10 @@ bool IsValidCommand(uint cmd)
_command_proc_table[cmd].proc != NULL; _command_proc_table[cmd].proc != NULL;
} }
byte GetCommandFlags(uint cmd) {return _command_proc_table[cmd & 0xFF].flags;} byte GetCommandFlags(uint cmd)
{
return _command_proc_table[cmd & 0xFF].flags;
}
static int _docommand_recursive; static int _docommand_recursive;
@ -344,9 +347,11 @@ int32 DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc)
goto error; goto error;
} }
if (_docommand_recursive == 1) { if (_docommand_recursive == 1 &&
if (!(flags&DC_QUERY_COST) && res != 0 && !CheckPlayerHasMoney(res)) !(flags & DC_QUERY_COST) &&
goto error; res != 0 &&
!CheckPlayerHasMoney(res)) {
goto error;
} }
if (!(flags & DC_EXEC)) { if (!(flags & DC_EXEC)) {
@ -496,12 +501,14 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
#endif /* ENABLE_NETWORK */ #endif /* ENABLE_NETWORK */
// update last build coordinate of player. // update last build coordinate of player.
if ( tile != 0 && _current_player < MAX_PLAYERS) GetPlayer(_current_player)->last_build_coordinate = tile; if (tile != 0 && _current_player < MAX_PLAYERS) {
GetPlayer(_current_player)->last_build_coordinate = tile;
}
/* Actually try and execute the command. If no cost-type is given /* Actually try and execute the command. If no cost-type is given
* use the construction one */ * use the construction one */
_yearly_expenses_type = EXPENSES_CONSTRUCTION; _yearly_expenses_type = EXPENSES_CONSTRUCTION;
res2 = proc(tile, flags|DC_EXEC, p1, p2); res2 = proc(tile, flags | DC_EXEC, p1, p2);
// If notest is on, it means the result of the test can be different than // If notest is on, it means the result of the test can be different than
// the real command.. so ignore the test // the real command.. so ignore the test
@ -517,8 +524,7 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
SubtractMoneyFromPlayer(res2); SubtractMoneyFromPlayer(res2);
if (IsLocalPlayer() && _game_mode != GM_EDITOR) { if (IsLocalPlayer() && _game_mode != GM_EDITOR) {
if (res2 != 0) if (res2 != 0) ShowCostOrIncomeAnimation(x, y, GetSlopeZ(x, y), res2);
ShowCostOrIncomeAnimation(x, y, GetSlopeZ(x, y), res2);
if (_additional_cash_required) { if (_additional_cash_required) {
SetDParam(0, _additional_cash_required); SetDParam(0, _additional_cash_required);
ShowErrorMessage(STR_0003_NOT_ENOUGH_CASH_REQUIRES, error_part1, x,y); ShowErrorMessage(STR_0003_NOT_ENOUGH_CASH_REQUIRES, error_part1, x,y);

View File

@ -72,8 +72,7 @@ static inline bool IsValidDepot(const Depot* depot)
*/ */
static inline bool IsTileDepotType(TileIndex tile, TransportType type) static inline bool IsTileDepotType(TileIndex tile, TransportType type)
{ {
switch (type) switch (type) {
{
case TRANSPORT_RAIL: case TRANSPORT_RAIL:
return IsTileType(tile, MP_RAILWAY) && (_m[tile].m5 & 0xFC) == 0xC0; return IsTileType(tile, MP_RAILWAY) && (_m[tile].m5 & 0xFC) == 0xC0;

View File

@ -194,8 +194,9 @@ static void DrawCatenaryRailway(const TileInfo *ti)
/* Next to us, we have a bridge head, don't worry about that one, if it shows away from us */ /* Next to us, we have a bridge head, don't worry about that one, if it shows away from us */
if (TrackSourceTile[i][k] == TS_NEIGHBOUR && if (TrackSourceTile[i][k] == TS_NEIGHBOUR &&
IsBridgeTile(neighbour) && IsBridgeRamp(neighbour) && IsBridgeTile(neighbour) && IsBridgeRamp(neighbour) &&
GetBridgeRampDirection(neighbour) == ReverseDiagDir(i) GetBridgeRampDirection(neighbour) == ReverseDiagDir(i)) {
) continue; continue;
}
/* We check whether the track in question (k) is present in the tile /* We check whether the track in question (k) is present in the tile
(TrackSourceTile) */ (TrackSourceTile) */

View File

@ -205,7 +205,7 @@ bool CheckIfAuthorityAllows(TileIndex tile);
Town *ClosestTownFromTile(TileIndex tile, uint threshold); Town *ClosestTownFromTile(TileIndex tile, uint threshold);
void ChangeTownRating(Town *t, int add, int max); void ChangeTownRating(Town *t, int add, int max);
int GetTownRadiusGroup(const Town *t, TileIndex tile); uint GetTownRadiusGroup(const Town* t, TileIndex tile);
void ShowNetworkChatQueryWindow(byte desttype, byte dest); void ShowNetworkChatQueryWindow(byte desttype, byte dest);
void ShowNetworkGiveMoneyWindow(byte player); void ShowNetworkGiveMoneyWindow(byte player);
void ShowNetworkNeedGamePassword(void); void ShowNetworkNeedGamePassword(void);

View File

@ -395,7 +395,7 @@ void InitializeLandscape(void)
void ConvertGroundTilesIntoWaterTiles(void) void ConvertGroundTilesIntoWaterTiles(void)
{ {
TileIndex tile = 0; TileIndex tile;
for (tile = 0; tile < MapSize(); ++tile) { for (tile = 0; tile < MapSize(); ++tile) {
if (IsTileType(tile, MP_CLEAR) && GetTileMaxZ(tile) == 0) { if (IsTileType(tile, MP_CLEAR) && GetTileMaxZ(tile) == 0) {

10
map.h
View File

@ -67,11 +67,11 @@ static inline TileIndex TileVirtXY(uint x, uint y)
return (y >> 4 << MapLogX()) + (x >> 4); return (y >> 4 << MapLogX()) + (x >> 4);
} }
typedef enum { typedef enum Owner {
OWNER_TOWN = 0xf, // a town owns the tile OWNER_TOWN = 0x0F, // a town owns the tile
OWNER_NONE = 0x10, // nobody owns the tile OWNER_NONE = 0x10, // nobody owns the tile
OWNER_WATER = 0x11, // "water" owns the tile OWNER_WATER = 0x11, // "water" owns the tile
OWNER_SPECTATOR = 0xff, // spectator in MP or in scenario editor OWNER_SPECTATOR = 0xFF, // spectator in MP or in scenario editor
} Owner; } Owner;
enum { enum {

View File

@ -159,20 +159,20 @@ static void Place_LandInfo(TileIndex tile)
GetAcceptedCargo(tile, lid.ac); GetAcceptedCargo(tile, lid.ac);
GetTileDesc(tile, &lid.td); GetTileDesc(tile, &lid.td);
#if defined(_DEBUG) #if defined(_DEBUG)
# define LANDINFOD_LEVEL 0 # define LANDINFOD_LEVEL 0
#else #else
# define LANDINFOD_LEVEL 1 # define LANDINFOD_LEVEL 1
#endif #endif
DEBUG(misc, LANDINFOD_LEVEL) ("TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile)); DEBUG(misc, LANDINFOD_LEVEL) ("TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
DEBUG(misc, LANDINFOD_LEVEL) ("type_height = %#x", _m[tile].type_height); DEBUG(misc, LANDINFOD_LEVEL) ("type_height = %#x", _m[tile].type_height);
DEBUG(misc, LANDINFOD_LEVEL) ("m1 = %#x", _m[tile].m1); DEBUG(misc, LANDINFOD_LEVEL) ("m1 = %#x", _m[tile].m1);
DEBUG(misc, LANDINFOD_LEVEL) ("m2 = %#x", _m[tile].m2); DEBUG(misc, LANDINFOD_LEVEL) ("m2 = %#x", _m[tile].m2);
DEBUG(misc, LANDINFOD_LEVEL) ("m3 = %#x", _m[tile].m3); DEBUG(misc, LANDINFOD_LEVEL) ("m3 = %#x", _m[tile].m3);
DEBUG(misc, LANDINFOD_LEVEL) ("m4 = %#x", _m[tile].m4); DEBUG(misc, LANDINFOD_LEVEL) ("m4 = %#x", _m[tile].m4);
DEBUG(misc, LANDINFOD_LEVEL) ("m5 = %#x", _m[tile].m5); DEBUG(misc, LANDINFOD_LEVEL) ("m5 = %#x", _m[tile].m5);
DEBUG(misc, LANDINFOD_LEVEL) ("extra = %#x", _m[tile].extra); DEBUG(misc, LANDINFOD_LEVEL) ("extra = %#x", _m[tile].extra);
#undef LANDINFOD_LEVEL #undef LANDINFOD_LEVEL
} }
void PlaceLandBlockInfo(void) void PlaceLandBlockInfo(void)
@ -730,7 +730,8 @@ void CheckRedrawStationCoverage(const Window* w)
void UnclickSomeWindowButtons(Window *w, uint32 mask) void UnclickSomeWindowButtons(Window *w, uint32 mask)
{ {
uint32 x = w->click_state & mask; uint32 x = w->click_state & mask;
int i = 0; uint i = 0;
w->click_state ^= x; w->click_state ^= x;
do { do {
if (x & 1) InvalidateWidget(w, i); if (x & 1) InvalidateWidget(w, i);
@ -1251,8 +1252,8 @@ static void SaveLoadDlgWndProc(Window *w, WindowEvent *e)
} }
case WE_PAINT: { case WE_PAINT: {
int y,pos; int pos;
const FiosItem *item; int y;
SetVScrollCount(w, _fios_num); SetVScrollCount(w, _fios_num);
DrawWindowWidgets(w); DrawWindowWidgets(w);
@ -1271,11 +1272,10 @@ static void SaveLoadDlgWndProc(Window *w, WindowEvent *e)
); );
y = w->widget[7].top + 1; y = w->widget[7].top + 1;
pos = w->vscroll.pos; for (pos = w->vscroll.pos; pos < _fios_num; pos++) {
while (pos < _fios_num) { const FiosItem* item = _fios_list + pos;
item = _fios_list + pos;
DoDrawStringTruncated(item->title, 4, y, _fios_colors[item->type], w->width - 18); DoDrawStringTruncated(item->title, 4, y, _fios_colors[item->type], w->width - 18);
pos++;
y += 10; y += 10;
if (y >= w->vscroll.cap * 10 + w->widget[7].top + 1) break; if (y >= w->vscroll.cap * 10 + w->widget[7].top + 1) break;
} }
@ -1285,6 +1285,7 @@ static void SaveLoadDlgWndProc(Window *w, WindowEvent *e)
} }
break; break;
} }
case WE_CLICK: case WE_CLICK:
switch (e->click.widget) { switch (e->click.widget) {
case 2: /* Sort save names by name */ case 2: /* Sort save names by name */

View File

@ -66,14 +66,12 @@ enum {
static bool PathToFSSpec(const char *path, FSSpec *spec) static bool PathToFSSpec(const char *path, FSSpec *spec)
{ {
FSRef ref; FSRef ref;
assert(spec); assert(spec != NULL);
assert(path); assert(path != NULL);
if (noErr != FSPathMakeRef((UInt8*) path, &ref, NULL)) return
return false; FSPathMakeRef((UInt8*)path, &ref, NULL) == noErr &&
FSGetCatalogInfo(&ref, kFSCatInfoNone, NULL, NULL, spec, NULL) == noErr;
return (noErr ==
FSGetCatalogInfo(&ref, kFSCatInfoNone, NULL, NULL, spec, NULL));
} }
@ -91,7 +89,7 @@ static void SetMIDITypeIfNeeded(const FSSpec *spec)
if (noErr != FSpGetFInfo(spec, &info)) return; if (noErr != FSpGetFInfo(spec, &info)) return;
/* Set file type to 'Midi' if the file is _not_ an alias. */ /* Set file type to 'Midi' if the file is _not_ an alias. */
if ((info.fdType != midiType) && !(info.fdFlags & kIsAlias)) { if (info.fdType != midiType && !(info.fdFlags & kIsAlias)) {
info.fdType = midiType; info.fdType = midiType;
FSpSetFInfo(spec, &info); FSpSetFInfo(spec, &info);
DEBUG(driver, 3) ("qtmidi: changed filetype to 'Midi'"); DEBUG(driver, 3) ("qtmidi: changed filetype to 'Midi'");
@ -115,8 +113,8 @@ static bool LoadMovieForMIDIFile(const char *path, Movie *moov)
short refnum = 0; short refnum = 0;
short resid = 0; short resid = 0;
assert(path); assert(path != NULL);
assert(moov); assert(moov != NULL);
DEBUG(driver, 2) ("qtmidi: begin loading '%s'...", path); DEBUG(driver, 2) ("qtmidi: begin loading '%s'...", path);
@ -126,23 +124,20 @@ static bool LoadMovieForMIDIFile(const char *path, Movie *moov)
* a MIDI file and setting the OSType of the file to the 'Midi' value. * a MIDI file and setting the OSType of the file to the 'Midi' value.
* Perhahaps ugly, but it seems that it does the Right Thing(tm). * Perhahaps ugly, but it seems that it does the Right Thing(tm).
*/ */
if ((fd = open(path, O_RDONLY, 0)) == -1) fd = open(path, O_RDONLY, 0);
return false; if (fd == -1) return false;
ret = read(fd, magic, 4); ret = read(fd, magic, 4);
close(fd); close(fd);
if (ret < 4) return false; if (ret < 4) return false;
DEBUG(driver, 3) ("qtmidi: header is '%c%c%c%c'", DEBUG(driver, 3) ("qtmidi: header is '%.4s'", magic);
magic[0], magic[1], magic[2], magic[3]);
if (magic[0] != 'M' || magic[1] != 'T' || magic[2] != 'h' || magic[3] != 'd') if (magic[0] != 'M' || magic[1] != 'T' || magic[2] != 'h' || magic[3] != 'd')
return false; return false;
if (!PathToFSSpec(path, &fsspec)) if (!PathToFSSpec(path, &fsspec)) return false;
return false;
SetMIDITypeIfNeeded(&fsspec); SetMIDITypeIfNeeded(&fsspec);
if (noErr != OpenMovieFile(&fsspec, &refnum, fsRdPerm)) if (OpenMovieFile(&fsspec, &refnum, fsRdPerm) != noErr) return false;
return false;
DEBUG(driver, 1) ("qtmidi: '%s' successfully opened", path); DEBUG(driver, 1) ("qtmidi: '%s' successfully opened", path);
if (noErr != NewMovieFromFile(moov, refnum, &resid, NULL, if (noErr != NewMovieFromFile(moov, refnum, &resid, NULL,
@ -182,13 +177,13 @@ static void InitQuickTimeIfNeeded(void)
(noErr == Gestalt(gestaltQuickTime, &dummy)) && (noErr == Gestalt(gestaltQuickTime, &dummy)) &&
(noErr == EnterMovies()); (noErr == EnterMovies());
DEBUG(driver, 1) ("qtmidi: Quicktime was %s initialized", DEBUG(driver, 1) ("qtmidi: Quicktime was %s initialized",
_quicktime_started ? "successfully" : "NOT"); _quicktime_started ? "successfully" : "NOT"
);
} }
/** Possible states of the QuickTime music driver. */ /** Possible states of the QuickTime music driver. */
enum enum {
{
QT_STATE_IDLE, /**< No file loaded. */ QT_STATE_IDLE, /**< No file loaded. */
QT_STATE_PLAY, /**< File loaded, playing. */ QT_STATE_PLAY, /**< File loaded, playing. */
QT_STATE_STOP, /**< File loaded, stopped. */ QT_STATE_STOP, /**< File loaded, stopped. */
@ -247,7 +242,7 @@ static bool SongIsPlaying(void)
_quicktime_state = QT_STATE_STOP; _quicktime_state = QT_STATE_STOP;
} }
return (_quicktime_state == QT_STATE_PLAY); return _quicktime_state == QT_STATE_PLAY;
} }

View File

@ -1242,11 +1242,9 @@ void NetworkUDPGameLoop(void)
if (_udp_master_socket != INVALID_SOCKET) { if (_udp_master_socket != INVALID_SOCKET) {
NetworkUDPReceive(_udp_master_socket); NetworkUDPReceive(_udp_master_socket);
} }
} } else if (_udp_client_socket != INVALID_SOCKET) {
else if (_udp_client_socket != INVALID_SOCKET) {
NetworkUDPReceive(_udp_client_socket); NetworkUDPReceive(_udp_client_socket);
if (_network_udp_broadcast > 0) if (_network_udp_broadcast > 0) _network_udp_broadcast--;
_network_udp_broadcast--;
} }
} }

View File

@ -221,11 +221,9 @@ static void NewsWindowProc(Window *w, WindowEvent *e)
// (to deal with overflows) // (to deal with overflows)
static byte increaseIndex(byte i) static byte increaseIndex(byte i)
{ {
if (i == INVALID_NEWS) if (i == INVALID_NEWS) return 0;
return 0;
i++; i++;
if (i >= MAX_NEWS) if (i >= MAX_NEWS) i = i % MAX_NEWS;
i = i % MAX_NEWS;
return i; return i;
} }
@ -234,8 +232,7 @@ void AddNewsItem(StringID string, uint32 flags, uint data_a, uint data_b)
NewsItem *ni; NewsItem *ni;
Window *w; Window *w;
if (_game_mode == GM_MENU) if (_game_mode == GM_MENU) return;
return;
// check the rare case that the oldest (to be overwritten) news item is open // check the rare case that the oldest (to be overwritten) news item is open
if (_total_news==MAX_NEWS && (_oldest_news == _current_news || _oldest_news == _forced_news)) if (_total_news==MAX_NEWS && (_oldest_news == _current_news || _oldest_news == _forced_news))

26
npf.c
View File

@ -277,8 +277,7 @@ static int32 NPFRoadPathCost(AyStar* as, AyStarNode* current, OpenListNode* pare
case MP_STREET: case MP_STREET:
cost = NPF_TILE_LENGTH; cost = NPF_TILE_LENGTH;
/* Increase the cost for level crossings */ /* Increase the cost for level crossings */
if (IsLevelCrossing(tile)) if (IsLevelCrossing(tile)) cost += _patches.npf_crossing_penalty;
cost += _patches.npf_crossing_penalty;
break; break;
default: default:
@ -407,15 +406,10 @@ static int32 NPFRailPathCost(AyStar* as, AyStarNode* current, OpenListNode* pare
/* Will find any depot */ /* Will find any depot */
static int32 NPFFindDepot(AyStar* as, OpenListNode *current) static int32 NPFFindDepot(AyStar* as, OpenListNode *current)
{ {
TileIndex tile = current->path.node.tile;
/* It's not worth caching the result with NPF_FLAG_IS_TARGET here as below, /* It's not worth caching the result with NPF_FLAG_IS_TARGET here as below,
* since checking the cache not that much faster than the actual check */ * since checking the cache not that much faster than the actual check */
if (IsTileDepotType(tile, as->user_data[NPF_TYPE])) { return IsTileDepotType(current->path.node.tile, as->user_data[NPF_TYPE]) ?
return AYSTAR_FOUND_END_NODE; AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
} else {
return AYSTAR_DONE;
}
} }
/* Will find a station identified using the NPFFindStationOrTileData */ /* Will find a station identified using the NPFFindStationOrTileData */
@ -682,14 +676,12 @@ static NPFFoundTargetData NPFRouteInternal(AyStarNode* start1, AyStarNode* start
_npf_aystar.EndNodeCheck = target_proc; _npf_aystar.EndNodeCheck = target_proc;
_npf_aystar.FoundEndNode = NPFSaveTargetData; _npf_aystar.FoundEndNode = NPFSaveTargetData;
_npf_aystar.GetNeighbours = NPFFollowTrack; _npf_aystar.GetNeighbours = NPFFollowTrack;
if (type == TRANSPORT_RAIL) switch (type) {
_npf_aystar.CalculateG = NPFRailPathCost; default: NOT_REACHED();
else if (type == TRANSPORT_ROAD) case TRANSPORT_RAIL: _npf_aystar.CalculateG = NPFRailPathCost; break;
_npf_aystar.CalculateG = NPFRoadPathCost; case TRANSPORT_ROAD: _npf_aystar.CalculateG = NPFRoadPathCost; break;
else if (type == TRANSPORT_WATER) case TRANSPORT_WATER: _npf_aystar.CalculateG = NPFWaterPathCost; break;
_npf_aystar.CalculateG = NPFWaterPathCost; }
else
assert(0);
/* Initialize Start Node(s) */ /* Initialize Start Node(s) */
start1->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR; start1->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;

View File

@ -188,12 +188,11 @@ static inline uint32 ReadUint32(LoadgameState *ls)
static bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks) static bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks)
{ {
const OldChunks *chunk = chunks; const OldChunks *chunk = chunks;
byte *ptr;
byte *base_ptr = base; byte *base_ptr = base;
uint i;
while (chunk->type != OC_END) { while (chunk->type != OC_END) {
ptr = chunk->ptr; byte* ptr = chunk->ptr;
uint i;
for (i = 0; i < chunk->amount; i++) { for (i = 0; i < chunk->amount; i++) {
if (ls->failed) return false; if (ls->failed) return false;

View File

@ -1013,14 +1013,18 @@ static void ConvertTownOwner(void)
TileIndex tile; TileIndex tile;
for (tile = 0; tile != MapSize(); tile++) { for (tile = 0; tile != MapSize(); tile++) {
if (IsTileType(tile, MP_STREET)) { switch (GetTileType(tile)) {
if (IsLevelCrossing(tile) && GetCrossingRoadOwner(tile) & 0x80) { case MP_STREET:
SetCrossingRoadOwner(tile, OWNER_TOWN); if (IsLevelCrossing(tile) && GetCrossingRoadOwner(tile) & 0x80) {
} SetCrossingRoadOwner(tile, OWNER_TOWN);
}
/* FALLTHROUGH */
if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN); case MP_TUNNELBRIDGE:
} else if (IsTileType(tile, MP_TUNNELBRIDGE)) { if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN); break;
default: break;
} }
} }
} }

View File

@ -189,7 +189,7 @@ int32 CmdInsertOrder(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
st = GetStation(new_order.station); st = GetStation(new_order.station);
if (!IsValidStation(st) || if (!IsValidStation(st) ||
(st->airport_type != AT_OILRIG && !(IsBuoy(st)) && !CheckOwnership(st->owner))) { (st->airport_type != AT_OILRIG && !IsBuoy(st) && !CheckOwnership(st->owner))) {
return CMD_ERROR; return CMD_ERROR;
} }

View File

@ -468,9 +468,7 @@ static void OrdersWndProc(Window *w, WindowEvent *e)
if (e->keypress.keycode == _order_keycodes[i]) { if (e->keypress.keycode == _order_keycodes[i]) {
e->keypress.cont = false; e->keypress.cont = false;
//see if the button is disabled //see if the button is disabled
if (!(HASBIT(w->disabled_state, (i + 4)))) { if (!HASBIT(w->disabled_state, i + 4)) _order_button_proc[i](w, v);
_order_button_proc[i](w, v);
}
break; break;
} }
} }

View File

@ -180,7 +180,7 @@ static void TPFMode2(TrackPathFinder* tpf, TileIndex tile, DiagDirection directi
} }
continue_here:; continue_here:;
tpf->the_dir = HASBIT(_otherdir_mask[direction],i) ? (i+8) : i; tpf->the_dir = i + (HASBIT(_otherdir_mask[direction], i) ? 8 : 0);
if (!tpf->enum_proc(tile, tpf->userdata, tpf->the_dir, tpf->rd.cur_length, NULL)) { if (!tpf->enum_proc(tile, tpf->userdata, tpf->the_dir, tpf->rd.cur_length, NULL)) {
TPFMode2(tpf, tile, _tpf_new_direction[tpf->the_dir]); TPFMode2(tpf, tile, _tpf_new_direction[tpf->the_dir]);
@ -754,8 +754,7 @@ start_at:
// Check that the tile contains exactly one track // Check that the tile contains exactly one track
if (bits == 0 || KILL_FIRST_BIT(bits) != 0) break; if (bits == 0 || KILL_FIRST_BIT(bits) != 0) break;
/* Check the rail type only if the train is *NOT* on top of /* Check the rail type only if the train is *NOT* on top of a bridge. */
* a bridge. */
if (!(IsBridgeTile(tile) && IsBridgeMiddle(tile) && GetBridgeAxis(tile) == DiagDirToAxis(direction))) { if (!(IsBridgeTile(tile) && IsBridgeMiddle(tile) && GetBridgeAxis(tile) == DiagDirToAxis(direction))) {
if (IsTileType(tile, MP_STREET) ? !HASBIT(tpf->railtypes, GetRailTypeCrossing(tile)) : !HASBIT(tpf->railtypes, GetRailType(tile))) { if (IsTileType(tile, MP_STREET) ? !HASBIT(tpf->railtypes, GetRailTypeCrossing(tile)) : !HASBIT(tpf->railtypes, GetRailType(tile))) {
bits = 0; bits = 0;

View File

@ -37,7 +37,6 @@ typedef struct RememberData {
} RememberData; } RememberData;
struct TrackPathFinder { struct TrackPathFinder {
int num_links_left; int num_links_left;
TrackPathFinderLink *new_link; TrackPathFinderLink *new_link;

View File

@ -271,7 +271,7 @@ static void SelectPlayerColorWndProc(Window *w, WindowEvent *e)
for (i = 0; i != 16; i++) { for (i = 0; i != 16; i++) {
if (!(used_colors & 1) && --pos < 0 && pos >= -8) { if (!(used_colors & 1) && --pos < 0 && pos >= -8) {
DrawString(x + 30, y, STR_00D1_DARK_BLUE + i, 2); DrawString(x + 30, y, STR_00D1_DARK_BLUE + i, 2);
DrawSprite(((GENERAL_SPRITE_COLOR(i) | PALETTE_MODIFIER_COLOR) | SPR_VEH_BUS_SIDE_VIEW), x + 14, y + 4); DrawSprite(GENERAL_SPRITE_COLOR(i) | PALETTE_MODIFIER_COLOR | SPR_VEH_BUS_SIDE_VIEW, x + 14, y + 4);
y += 14; y += 14;
} }
used_colors >>= 1; used_colors >>= 1;

View File

@ -266,7 +266,7 @@ void GetNameOfOwner(PlayerID owner, TileIndex tile)
if (owner >= 8) if (owner >= 8)
SetDParam(0, STR_0150_SOMEONE); SetDParam(0, STR_0150_SOMEONE);
else { else {
Player *p = GetPlayer(owner); const Player* p = GetPlayer(owner);
SetDParam(0, p->name_1); SetDParam(0, p->name_1);
SetDParam(1, p->name_2); SetDParam(1, p->name_2);
} }
@ -479,8 +479,7 @@ Player *DoStartupNewPlayer(bool is_ai)
Player *p; Player *p;
p = AllocatePlayer(); p = AllocatePlayer();
if (p == NULL) if (p == NULL) return NULL;
return NULL;
// Make a color // Make a color
p->player_color = GeneratePlayerColor(); p->player_color = GeneratePlayerColor();
@ -531,15 +530,19 @@ static void MaybeStartNewPlayer(void)
// count number of competitors // count number of competitors
n = 0; n = 0;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (p->is_active && p->is_ai) if (p->is_active && p->is_ai) n++;
n++;
} }
// when there's a lot of computers in game, the probability that a new one starts is lower // when there's a lot of computers in game, the probability that a new one starts is lower
if (n < (uint)_opt.diff.max_no_competitors) if (n < (uint)_opt.diff.max_no_competitors &&
if (n < (_network_server ? InteractiveRandomRange(_opt.diff.max_no_competitors + 2) : RandomRange(_opt.diff.max_no_competitors + 2)) ) n < (_network_server ?
/* Send a command to all clients to start up a new AI. Works fine for Multiplayer and Singleplayer */ InteractiveRandomRange(_opt.diff.max_no_competitors + 2) :
DoCommandP(0, 1, 0, NULL, CMD_PLAYER_CTRL); RandomRange(_opt.diff.max_no_competitors + 2)
)) {
/* Send a command to all clients to start up a new AI.
* Works fine for Multiplayer and Singleplayer */
DoCommandP(0, 1, 0, NULL, CMD_PLAYER_CTRL);
}
// The next AI starts like the difficulty setting said, with +2 month max // The next AI starts like the difficulty setting said, with +2 month max
_next_competitor_start = _opt.diff.competitor_start_time * 90 * DAY_TICKS + 1; _next_competitor_start = _opt.diff.competitor_start_time * 90 * DAY_TICKS + 1;
@ -548,10 +551,10 @@ static void MaybeStartNewPlayer(void)
void InitializePlayers(void) void InitializePlayers(void)
{ {
int i; uint i;
memset(_players, 0, sizeof(_players)); memset(_players, 0, sizeof(_players));
for (i = 0; i != MAX_PLAYERS; i++) for (i = 0; i != MAX_PLAYERS; i++) _players[i].index = i;
_players[i].index=i;
_cur_player_tick_index = 0; _cur_player_tick_index = 0;
} }
@ -559,8 +562,7 @@ void OnTick_Players(void)
{ {
Player *p; Player *p;
if (_game_mode == GM_EDITOR) if (_game_mode == GM_EDITOR) return;
return;
p = GetPlayer(_cur_player_tick_index); p = GetPlayer(_cur_player_tick_index);
_cur_player_tick_index = (_cur_player_tick_index + 1) % MAX_PLAYERS; _cur_player_tick_index = (_cur_player_tick_index + 1) % MAX_PLAYERS;
@ -816,15 +818,20 @@ int32 CmdPlayerCtrl(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
p = DoStartupNewPlayer(false); p = DoStartupNewPlayer(false);
#ifdef ENABLE_NETWORK #ifdef ENABLE_NETWORK
if (_networking && !_network_server && _local_player == OWNER_SPECTATOR) if (_networking && !_network_server && _local_player == OWNER_SPECTATOR) {
/* In case we are a client joining a server... */ /* In case we are a client joining a server... */
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0); DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
}
#endif /* ENABLE_NETWORK */ #endif /* ENABLE_NETWORK */
if (p != NULL) { if (p != NULL) {
if (_local_player == OWNER_SPECTATOR && (!_ai.network_client || _ai.network_playas == OWNER_SPECTATOR)) { if (_local_player == OWNER_SPECTATOR &&
(!_ai.network_client || _ai.network_playas == OWNER_SPECTATOR)) {
/* Check if we do not want to be a spectator in network */ /* Check if we do not want to be a spectator in network */
if (!_networking || (_network_server && !_network_dedicated) || _network_playas != OWNER_SPECTATOR || _ai.network_client) { if (!_networking ||
(_network_server && !_network_dedicated) ||
_network_playas != OWNER_SPECTATOR ||
_ai.network_client) {
if (_ai.network_client) { if (_ai.network_client) {
/* As ai-network-client, we have our own rulez (disable GUI and stuff) */ /* As ai-network-client, we have our own rulez (disable GUI and stuff) */
_ai.network_playas = p->index; _ai.network_playas = p->index;
@ -982,8 +989,7 @@ int8 SaveHighScoreValue(const Player *p)
uint16 score = p->old_economy[0].performance_history; uint16 score = p->old_economy[0].performance_history;
/* Exclude cheaters from the honour of being in the highscore table */ /* Exclude cheaters from the honour of being in the highscore table */
if (CheatHasBeenUsed()) if (CheatHasBeenUsed()) return -1;
return -1;
for (i = 0; i < lengthof(_highscore_table[0]); i++) { for (i = 0; i < lengthof(_highscore_table[0]); i++) {
/* You are in the TOP5. Move all values one down and save us there */ /* You are in the TOP5. Move all values one down and save us there */
@ -1247,8 +1253,9 @@ static void SaveLoad_PLYR(Player* p)
// Write AI? // Write AI?
if (!IS_HUMAN_PLAYER(p->index)) { if (!IS_HUMAN_PLAYER(p->index)) {
SlObject(&p->ai, _player_ai_desc); SlObject(&p->ai, _player_ai_desc);
for (i = 0; i != p->ai.num_build_rec; i++) for (i = 0; i != p->ai.num_build_rec; i++) {
SlObject(&p->ai.src + i, _player_ai_build_rec_desc); SlObject(&p->ai.src + i, _player_ai_build_rec_desc);
}
} }
// Write economy // Write economy

View File

@ -725,7 +725,7 @@ static int32 CmdSignalTrackHelper(TileIndex tile, uint32 flags, uint32 p1, uint3
int mode = p2 & 0x1; int mode = p2 & 0x1;
Track track = GB(p2, 4, 3); Track track = GB(p2, 4, 3);
Trackdir trackdir = TrackToTrackdir(track); Trackdir trackdir = TrackToTrackdir(track);
byte semaphores = (HASBIT(p2, 3)) ? 8 : 0; byte semaphores = (HASBIT(p2, 3) ? 8 : 0);
byte signal_density = (p2 >> 24); byte signal_density = (p2 >> 24);
if (p1 >= MapSize()) return CMD_ERROR; if (p1 >= MapSize()) return CMD_ERROR;

View File

@ -741,20 +741,19 @@ static void DrawRoadBits(TileInfo* ti, RoadBits road)
static void DrawTile_Road(TileInfo *ti) static void DrawTile_Road(TileInfo *ti)
{ {
PalSpriteID image;
switch (GetRoadTileType(ti->tile)) { switch (GetRoadTileType(ti->tile)) {
case ROAD_TILE_NORMAL: case ROAD_TILE_NORMAL:
DrawRoadBits(ti, GetRoadBits(ti->tile)); DrawRoadBits(ti, GetRoadBits(ti->tile));
break; break;
case ROAD_TILE_CROSSING: { case ROAD_TILE_CROSSING: {
PalSpriteID image;
if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh); if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
image = GetRailTypeInfo(GetRailTypeCrossing(ti->tile))->base_sprites.crossing; image = GetRailTypeInfo(GetRailTypeCrossing(ti->tile))->base_sprites.crossing;
if (GetCrossingRoadAxis(ti->tile) == AXIS_X) image++; if (GetCrossingRoadAxis(ti->tile) == AXIS_X) image++;
if (IsCrossingBarred(ti->tile)) image += 2; if (IsCrossingBarred(ti->tile)) image += 2;
if (IsOnSnow(ti->tile)) { if (IsOnSnow(ti->tile)) {
@ -802,12 +801,8 @@ static void DrawTile_Road(TileInfo *ti)
void DrawRoadDepotSprite(int x, int y, int image) void DrawRoadDepotSprite(int x, int y, int image)
{ {
uint32 ormod; const DrawRoadSeqStruct* dtss = _road_display_datas[image];
const DrawRoadSeqStruct *dtss; uint32 ormod = PLAYER_SPRITE_COLOR(_local_player);
ormod = PLAYER_SPRITE_COLOR(_local_player);
dtss = _road_display_datas[image];
x += 33; x += 33;
y += 17; y += 17;
@ -1064,7 +1059,7 @@ static void ChangeTileOwner_Road(TileIndex tile, PlayerID old_player, PlayerID n
if (new_player != OWNER_SPECTATOR) { if (new_player != OWNER_SPECTATOR) {
SetTileOwner(tile, new_player); SetTileOwner(tile, new_player);
} else { } else {
switch (GetRoadTileType(tile)) { switch (GetRoadTileType(tile)) {
case ROAD_TILE_NORMAL: case ROAD_TILE_NORMAL:
SetTileOwner(tile, OWNER_NONE); SetTileOwner(tile, OWNER_NONE);

View File

@ -271,7 +271,7 @@ static void BuildRoadToolbWndProc(Window* w, WindowEvent* e)
TileIndex tile = e->place.tile; TileIndex tile = e->place.tile;
DoCommand(tile, 0x200, 0, DC_AUTO, CMD_BUILD_TUNNEL); DoCommand(tile, 0x200, 0, DC_AUTO, CMD_BUILD_TUNNEL);
VpSetPresizeRange(tile, _build_tunnel_endtile==0?tile:_build_tunnel_endtile); VpSetPresizeRange(tile, _build_tunnel_endtile == 0 ? tile : _build_tunnel_endtile);
break; break;
} }

View File

@ -18,7 +18,7 @@ typedef enum RoadTileType {
static inline RoadTileType GetRoadTileType(TileIndex t) static inline RoadTileType GetRoadTileType(TileIndex t)
{ {
assert(IsTileType(t, MP_STREET)); assert(IsTileType(t, MP_STREET));
return (RoadTileType)(GB(_m[t].m5, 4, 4)); return (RoadTileType)GB(_m[t].m5, 4, 4);
} }
static inline bool IsLevelCrossing(TileIndex t) static inline bool IsLevelCrossing(TileIndex t)
@ -34,7 +34,7 @@ static inline bool IsLevelCrossingTile(TileIndex t)
static inline RoadBits GetRoadBits(TileIndex t) static inline RoadBits GetRoadBits(TileIndex t)
{ {
assert(GetRoadTileType(t) == ROAD_TILE_NORMAL); assert(GetRoadTileType(t) == ROAD_TILE_NORMAL);
return (RoadBits)(GB(_m[t].m5, 0, 4)); return (RoadBits)GB(_m[t].m5, 0, 4);
} }
static inline void SetRoadBits(TileIndex t, RoadBits r) static inline void SetRoadBits(TileIndex t, RoadBits r)

View File

@ -415,10 +415,9 @@ static void RoadVehViewWndProc(Window *w, WindowEvent *e)
case WE_MOUSELOOP: case WE_MOUSELOOP:
{ {
Vehicle *v; const Vehicle* v = GetVehicle(w->window_number);
uint32 h; uint32 h = IsRoadVehInDepotStopped(v) ? 1 << 7 | 1 << 8 : 1 << 11 | 1 << 12;
v = GetVehicle(w->window_number);
h = IsRoadVehInDepotStopped(v) ? (1 << 7) | (1 << 8) : (1 << 11) | (1 << 12);
if (h != w->hidden_state) { if (h != w->hidden_state) {
w->hidden_state = h; w->hidden_state = h;
SetWindowDirty(w); SetWindowDirty(w);
@ -1007,10 +1006,11 @@ static void PlayerRoadVehWndProc(Window *w, WindowEvent *e)
DrawVehicleProfitButton(v, x, y + 13); DrawVehicleProfitButton(v, x, y + 13);
SetDParam(0, v->unitnumber); SetDParam(0, v->unitnumber);
if (IsRoadVehInDepot(v)) if (IsRoadVehInDepot(v)) {
str = STR_021F; str = STR_021F;
else } else {
str = v->age > v->max_age - 366 ? STR_00E3 : STR_00E2; str = v->age > v->max_age - 366 ? STR_00E3 : STR_00E2;
}
DrawString(x, y + 2, str, 0); DrawString(x, y + 2, str, 0);
SetDParam(0, v->profit_this_year); SetDParam(0, v->profit_this_year);

View File

@ -712,9 +712,11 @@ static void ini_load_settings(IniFile *ini, const SettingDesc *sd, const char *g
* @param sd read-only SettingDesc structure which contains the unmodified, * @param sd read-only SettingDesc structure which contains the unmodified,
* loaded values of the configuration file and various information about it * loaded values of the configuration file and various information about it
* @param grpname holds the name of the group (eg. [network]) where these will be saved * @param grpname holds the name of the group (eg. [network]) where these will be saved
* The function works as follows: for each item in the SettingDesc structure we have * The function works as follows: for each item in the SettingDesc structure we
* a look if the value has changed since we started the game (the original values * have a look if the value has changed since we started the game (the original
* are reloaded when saving). If settings indeed have changed, we get these and save them.*/ * values are reloaded when saving). If settings indeed have changed, we get
* these and save them.
*/
static void ini_save_settings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object) static void ini_save_settings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
{ {
IniGroup *group_def = NULL, *group; IniGroup *group_def = NULL, *group;
@ -894,28 +896,28 @@ static void ini_save_setting_list(IniFile *ini, const char *grpname, char **list
* We have two types of list: * We have two types of list:
* 1. SDTG_something * 1. SDTG_something
* 2. SDT_something * 2. SDT_something
* The 'G' stands for global, so this is the one you will use for a SettingDescGlobVarList * The 'G' stands for global, so this is the one you will use for a
* section meaning global variables. The other uses a Base/Offset and runtime variable * SettingDescGlobVarList section meaning global variables. The other uses a
* selection mechanism, known from the saveload convention (it also has global so it * Base/Offset and runtime variable selection mechanism, known from the saveload * convention (it also has global so it should not be hard).
* should not be hard). * Of each type there are again two versions, the normal one and one prefixed
* Of each type there are again two versions, the normal one and one prefixed with 'COND'. * with 'COND'.
* COND means that the setting is only valid in certain savegame versions (since patches * COND means that the setting is only valid in certain savegame versions
* are saved to the savegame, this bookkeeping is necessary. * (since patches are saved to the savegame, this bookkeeping is necessary.
* Now there are a lot of types. Easy ones are: * Now there are a lot of types. Easy ones are:
* - VAR: any number type, 'type' field specifies what number. eg int8 or uint32 * - VAR: any number type, 'type' field specifies what number. eg int8 or uint32
* - BOOL: a boolean number type * - BOOL: a boolean number type
* - STR: a string or character. 'type' field specifies what string. Normal, string, or quoted * - STR: a string or character. 'type' field specifies what string. Normal, string, or quoted
* A bit more difficult to use are MMANY (meaning ManyOfMany) and OMANY (OneOfMany) * A bit more difficult to use are MMANY (meaning ManyOfMany) and OMANY (OneOfMany)
* These are actually normal numbers, only bitmasked. In MMANY several bits can be * These are actually normal numbers, only bitmasked. In MMANY several bits can
* set, in the other only one. * be set, in the other only one.
* The most complex type is INTLIST. This is basically an array of numbers. If * The most complex type is INTLIST. This is basically an array of numbers. If
* the intlist is only valid in certain savegame versions because for example * the intlist is only valid in certain savegame versions because for example
* it has grown in size its length cannot be automatically be calculated so * it has grown in size its length cannot be automatically be calculated so
* use SDT(G)_CONDLISTO() meaning Old. * use SDT(G)_CONDLISTO() meaning Old.
* If nothing fits you, you can use the GENERAL macros, but it exposes the internal * If nothing fits you, you can use the GENERAL macros, but it exposes the
* structure somewhat so it needs a little looking. There are _NULL() macros as * internal structure somewhat so it needs a little looking. There are _NULL()
* well, these fill up space so you can add more patches there (in place) and you * macros as well, these fill up space so you can add more patches there (in
* DON'T have to increase the savegame version. */ * place) and you DON'T have to increase the savegame version. */
#define NSD_GENERAL(name, def, cmd, guiflags, min, max, many, str, proc)\ #define NSD_GENERAL(name, def, cmd, guiflags, min, max, many, str, proc)\
{name, (const void*)(def), cmd, guiflags, min, max, many, str, proc} {name, (const void*)(def), cmd, guiflags, min, max, many, str, proc}
@ -1218,11 +1220,11 @@ static const SettingDesc _gameopt_settings[] = {
* These include for example the GUI settings and will not be saved with the * These include for example the GUI settings and will not be saved with the
* savegame. * savegame.
* It is also a bit tricky since you would think that service_interval * It is also a bit tricky since you would think that service_interval
* for example doesn't need to be synched. Every client assigns the service_interval * for example doesn't need to be synched. Every client assigns the
* value to the v->service_interval, meaning that every client assigns his value. If * service_interval value to the v->service_interval, meaning that every client
* the setting was player-based, that would mean that vehicles could decide on * assigns his value. If the setting was player-based, that would mean that
* different moments that they are heading back to a service depot, causing desyncs * vehicles could decide on different moments that they are heading back to a
* on a massive scale. */ * service depot, causing desyncs on a massive scale. */
const SettingDesc _patch_settings[] = { const SettingDesc _patch_settings[] = {
/***************************************************************************/ /***************************************************************************/
/* User-interface section of the GUI-configure patches window */ /* User-interface section of the GUI-configure patches window */
@ -1336,20 +1338,20 @@ const SettingDesc _patch_settings[] = {
SDT_VAR(Patches, npf_max_search_nodes,SLE_UINT, 0, 0,10000,500,100000, STR_NULL, NULL), SDT_VAR(Patches, npf_max_search_nodes,SLE_UINT, 0, 0,10000,500,100000, STR_NULL, NULL),
/* When a red signal is encountered, a small detour can be made around /* When a red signal is encountered, a small detour can be made around
* it. This specifically occurs when a track is doubled, in which case * it. This specifically occurs when a track is doubled, in which case
* the detour is typically 2 tiles. It is also often used at station * the detour is typically 2 tiles. It is also often used at station
* entrances, when there is a choice of multiple platforms. If we take * entrances, when there is a choice of multiple platforms. If we take
* a typical 4 platform station, the detour is 4 tiles. To properly * a typical 4 platform station, the detour is 4 tiles. To properly
* support larger stations we increase this value. * support larger stations we increase this value.
* We want to prevent that trains that want to leave at one side of a * We want to prevent that trains that want to leave at one side of a
* station, leave through the other side, turn around, enter the * station, leave through the other side, turn around, enter the
* station on another platform and exit the station on the right side * station on another platform and exit the station on the right side
* again, just because the sign at the right side was red. If we take * again, just because the sign at the right side was red. If we take
* a typical 5 length station, this detour is 10 or 11 tiles (not * a typical 5 length station, this detour is 10 or 11 tiles (not
* sure), so we set the default penalty at 10 (the station tile * sure), so we set the default penalty at 10 (the station tile
* penalty will further prevent this. * penalty will further prevent this.
* We give presignal exits (and combo's) a different (larger) penalty, because we really * We give presignal exits (and combo's) a different (larger) penalty, because
* don't want trains waiting in front of a presignal exit. */ * we really don't want trains waiting in front of a presignal exit. */
SDT_VAR(Patches, npf_rail_firstred_penalty, SLE_UINT, 0, 0, (10 * NPF_TILE_LENGTH), 0, 100000, STR_NULL, NULL), SDT_VAR(Patches, npf_rail_firstred_penalty, SLE_UINT, 0, 0, (10 * NPF_TILE_LENGTH), 0, 100000, STR_NULL, NULL),
SDT_VAR(Patches, npf_rail_firstred_exit_penalty,SLE_UINT, 0, 0, (100 * NPF_TILE_LENGTH),0, 100000, STR_NULL, NULL), SDT_VAR(Patches, npf_rail_firstred_exit_penalty,SLE_UINT, 0, 0, (100 * NPF_TILE_LENGTH),0, 100000, STR_NULL, NULL),
/* This penalty is for when the last signal before the target is red. /* This penalty is for when the last signal before the target is red.

View File

@ -564,10 +564,9 @@ static void ShipViewWndProc(Window *w, WindowEvent *e) {
case WE_MOUSELOOP: case WE_MOUSELOOP:
{ {
Vehicle *v; const Vehicle* v = GetVehicle(w->window_number);
uint32 h; uint32 h = IsShipInDepot(v) ? 1 << 7 : 1 << 11;
v = GetVehicle(w->window_number);
h = IsShipInDepot(v) ? 1 << 7 : 1 << 11;
if (h != w->hidden_state) { if (h != w->hidden_state) {
w->hidden_state = h; w->hidden_state = h;
SetWindowDirty(w); SetWindowDirty(w);
@ -1012,10 +1011,11 @@ static void PlayerShipsWndProc(Window *w, WindowEvent *e)
DrawVehicleProfitButton(v, x, y + 13); DrawVehicleProfitButton(v, x, y + 13);
SetDParam(0, v->unitnumber); SetDParam(0, v->unitnumber);
if (IsShipInDepot(v)) if (IsShipInDepot(v)) {
str = STR_021F; str = STR_021F;
else } else {
str = v->age > v->max_age - 366 ? STR_00E3 : STR_00E2; str = v->age > v->max_age - 366 ? STR_00E3 : STR_00E2;
}
DrawString(x, y + 2, str, 0); DrawString(x, y + 2, str, 0);
SetDParam(0, v->profit_this_year); SetDParam(0, v->profit_this_year);

View File

@ -938,22 +938,20 @@ static void ExtraViewPortWndProc(Window *w, WindowEvent *e)
case WE_CREATE: /* Disable zoom in button */ case WE_CREATE: /* Disable zoom in button */
w->disabled_state = (1 << 5); w->disabled_state = (1 << 5);
break; break;
case WE_PAINT: case WE_PAINT:
// set the number in the title bar // set the number in the title bar
SetDParam(0, (w->window_number+1)); SetDParam(0, w->window_number + 1);
DrawWindowWidgets(w); DrawWindowWidgets(w);
DrawWindowViewport(w); DrawWindowViewport(w);
break; break;
case WE_CLICK: { case WE_CLICK:
switch (e->click.widget) { switch (e->click.widget) {
case 5: /* zoom in */ case 5: DoZoomInOutWindow(ZOOM_IN, w); break;
DoZoomInOutWindow(ZOOM_IN, w); case 6: DoZoomInOutWindow(ZOOM_OUT, w); break;
break;
case 6: /* zoom out */
DoZoomInOutWindow(ZOOM_OUT, w);
break;
case 7: { /* location button (move main view to same spot as this view) 'Paste Location' */ case 7: { /* location button (move main view to same spot as this view) 'Paste Location' */
Window *w2 = FindWindowById(WC_MAIN_WINDOW, 0); Window *w2 = FindWindowById(WC_MAIN_WINDOW, 0);
int x = WP(w, vp_d).scrollpos_x; // Where is the main looking at int x = WP(w, vp_d).scrollpos_x; // Where is the main looking at
@ -963,6 +961,7 @@ static void ExtraViewPortWndProc(Window *w, WindowEvent *e)
WP(w2, vp_d).scrollpos_x = x - (w2->viewport->virtual_width - w->viewport->virtual_width) / 2; WP(w2, vp_d).scrollpos_x = x - (w2->viewport->virtual_width - w->viewport->virtual_width) / 2;
WP(w2, vp_d).scrollpos_y = y - (w2->viewport->virtual_height - w->viewport->virtual_height) / 2; WP(w2, vp_d).scrollpos_y = y - (w2->viewport->virtual_height - w->viewport->virtual_height) / 2;
} break; } break;
case 8: { /* inverse location button (move this view to same spot as main view) 'Copy Location' */ case 8: { /* inverse location button (move this view to same spot as main view) 'Copy Location' */
const Window* w2 = FindWindowById(WC_MAIN_WINDOW, 0); const Window* w2 = FindWindowById(WC_MAIN_WINDOW, 0);
int x = WP(w2, const vp_d).scrollpos_x; int x = WP(w2, const vp_d).scrollpos_x;
@ -972,12 +971,11 @@ static void ExtraViewPortWndProc(Window *w, WindowEvent *e)
WP(w, vp_d).scrollpos_y = y + (w2->viewport->virtual_height - w->viewport->virtual_height) / 2; WP(w, vp_d).scrollpos_y = y + (w2->viewport->virtual_height - w->viewport->virtual_height) / 2;
} break; } break;
} }
} break; break;
case WE_RESIZE: case WE_RESIZE:
w->viewport->width += e->sizing.diff.x; w->viewport->width += e->sizing.diff.x;
w->viewport->height += e->sizing.diff.y; w->viewport->height += e->sizing.diff.y;
w->viewport->virtual_width += e->sizing.diff.x; w->viewport->virtual_width += e->sizing.diff.x;
w->viewport->virtual_height += e->sizing.diff.y; w->viewport->virtual_height += e->sizing.diff.y;
break; break;

View File

@ -1914,7 +1914,7 @@ int32 CmdBuildDock(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
cost = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR); cost = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(cost)) return CMD_ERROR; if (CmdFailed(cost)) return CMD_ERROR;
tile_cur = tile_cur + TileOffsByDir(direction); tile_cur += TileOffsByDir(direction);
if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) { if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
return_cmd_error(STR_304B_SITE_UNSUITABLE); return_cmd_error(STR_304B_SITE_UNSUITABLE);
} }

View File

@ -69,11 +69,9 @@
// Stuff for GCC // Stuff for GCC
#if defined(__GNUC__) #if defined(__GNUC__)
# define NORETURN __attribute((noreturn)) # define NORETURN __attribute__ ((noreturn))
# define FORCEINLINE inline # define FORCEINLINE inline
# define CDECL # define CDECL
//#include <alloca.h>
//#include <malloc.h>
# define __int64 long long # define __int64 long long
# define NOT_REACHED() assert(0) # define NOT_REACHED() assert(0)
# define GCC_PACK __attribute__((packed)) # define GCC_PACK __attribute__((packed))

View File

@ -1063,17 +1063,20 @@ bool GenerateTowns(void)
uint n = ScaleByMapSize(_num_initial_towns[_opt.diff.number_towns] + (Random() & 7)); uint n = ScaleByMapSize(_num_initial_towns[_opt.diff.number_towns] + (Random() & 7));
do { do {
if (CreateRandomTown(20, 0) != NULL) //try 20 times to create a random-sized town for the first loop. // try 20 times to create a random-sized town for the first loop.
num++; if (CreateRandomTown(20, 0) != NULL) num++;
} while (--n); } while (--n);
// give it a last try, but now more aggressive // give it a last try, but now more aggressive
if (num == 0 && CreateRandomTown(10000, 0) == NULL) { if (num == 0 && CreateRandomTown(10000, 0) == NULL) {
Town *t; const Town* t;
FOR_ALL_TOWNS(t) { if (IsValidTown(t)) {num = 1; break;}}
FOR_ALL_TOWNS(t) if (IsValidTown(t)) return true;
//XXX can we handle that more gracefully? //XXX can we handle that more gracefully?
if (num == 0 && _game_mode != GM_EDITOR) error("Could not generate any town"); if (num == 0 && _game_mode != GM_EDITOR) {
error("Could not generate any town");
}
return false; return false;
} }
@ -1102,19 +1105,18 @@ static bool CheckBuildHouseMode(TileIndex tile, Slope tileh, int mode)
return !CmdFailed(DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR)); return !CmdFailed(DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR));
} }
int GetTownRadiusGroup(const Town *t, TileIndex tile)
{
uint dist;
int i,smallest;
dist = DistanceSquare(tile, t->xy); uint GetTownRadiusGroup(const Town* t, TileIndex tile)
if (t->fund_buildings_months && dist <= 25) {
return 4; uint dist = DistanceSquare(tile, t->xy);
uint smallest;
uint i;
if (t->fund_buildings_months && dist <= 25) return 4;
smallest = 0; smallest = 0;
for (i = 0; i != lengthof(t->radius); i++) { for (i = 0; i != lengthof(t->radius); i++) {
if (dist < t->radius[i]) if (dist < t->radius[i]) smallest = i;
smallest = i;
} }
return smallest; return smallest;
@ -1160,8 +1162,7 @@ static void DoBuildTownHouse(Town *t, TileIndex tile)
uint rad = GetTownRadiusGroup(t, tile); uint rad = GetTownRadiusGroup(t, tile);
int land = _opt.landscape; int land = _opt.landscape;
if (land == LT_HILLY && z >= _opt.snow_line) if (land == LT_HILLY && z >= _opt.snow_line) land = -1;
land = -1;
bitmask = (1 << rad) + (1 << (land + 12)); bitmask = (1 << rad) + (1 << (land + 12));
} }
@ -1259,8 +1260,6 @@ static void DoBuildTownHouse(Town *t, TileIndex tile)
size_flags = GB(_housetype_extra_flags[house], 2, 3); size_flags = GB(_housetype_extra_flags[house], 2, 3);
MakeTownHouse(tile, t->index, construction_counter, construction_stage, size_flags, house); MakeTownHouse(tile, t->index, construction_counter, construction_stage, size_flags, house);
} }
// ENDING
} }
static bool BuildTownHouse(Town *t, TileIndex tile) static bool BuildTownHouse(Town *t, TileIndex tile)
@ -1710,11 +1709,10 @@ static void UpdateTownAmounts(Town *t)
static void UpdateTownUnwanted(Town *t) static void UpdateTownUnwanted(Town *t)
{ {
Player *p; const Player* p;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (t->unwanted[p->index] > 0) if (t->unwanted[p->index] > 0) t->unwanted[p->index]--;
t->unwanted[p->index]--;
} }
} }
@ -1722,15 +1720,12 @@ bool CheckIfAuthorityAllows(TileIndex tile)
{ {
Town *t; Town *t;
if (_current_player >= MAX_PLAYERS) if (_current_player >= MAX_PLAYERS) return true;
return true;
t = ClosestTownFromTile(tile, _patches.dist_local_authority); t = ClosestTownFromTile(tile, _patches.dist_local_authority);
if (t == NULL) if (t == NULL) return true;
return true;
if (t->ratings[_current_player] > -200) if (t->ratings[_current_player] > -200) return true;
return true;
_error_message = STR_2009_LOCAL_AUTHORITY_REFUSES; _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
SetDParam(0, t->index); SetDParam(0, t->index);
@ -1837,12 +1832,10 @@ void TownsMonthlyLoop(void)
Town *t; Town *t;
FOR_ALL_TOWNS(t) if (t->xy != 0) { FOR_ALL_TOWNS(t) if (t->xy != 0) {
if (t->road_build_months != 0) if (t->road_build_months != 0) t->road_build_months--;
t->road_build_months--;
if (t->exclusive_counter != 0) if (t->exclusive_counter != 0)
if (--t->exclusive_counter == 0) if (--t->exclusive_counter == 0) t->exclusivity = (byte)-1;
t->exclusivity = (byte)-1;
UpdateTownGrowRate(t); UpdateTownGrowRate(t);
UpdateTownAmounts(t); UpdateTownAmounts(t);

View File

@ -340,7 +340,7 @@ static void ShowBuildTrainWindow(TileIndex tile)
w->widget[2].unkA = (w->vscroll.cap << 8) + 1; w->widget[2].unkA = (w->vscroll.cap << 8) + 1;
w->resize.step_height = 14; w->resize.step_height = 14;
w->resize.height = w->height - 14 * 4; /* Minimum of 4 vehicles in the display */ w->resize.height = w->height - 14 * 4; // Minimum of 4 vehicles in the display
if (tile != 0) { if (tile != 0) {
w->caption_color = GetTileOwner(tile); w->caption_color = GetTileOwner(tile);
@ -1049,10 +1049,9 @@ static void TrainViewWndProc(Window *w, WindowEvent *e)
break; break;
case WE_MOUSELOOP: { case WE_MOUSELOOP: {
Vehicle *v; const Vehicle* v = GetVehicle(w->window_number);
uint32 h; uint32 h;
v = GetVehicle(w->window_number);
assert(v->type == VEH_Train); assert(v->type == VEH_Train);
h = CheckTrainStoppedInDepot(v) >= 0 ? (1 << 9)| (1 << 7) : (1 << 12) | (1 << 13); h = CheckTrainStoppedInDepot(v) >= 0 ? (1 << 9)| (1 << 7) : (1 << 12) | (1 << 13);
if (h != w->hidden_state) { if (h != w->hidden_state) {

View File

@ -238,13 +238,15 @@ int32 CmdBuildBridge(TileIndex end_tile, uint32 flags, uint32 p1, uint32 p2)
} }
/* set and test bridge length, availability */ /* set and test bridge length, availability */
bridge_len = (sx + sy - x - y) - 1; bridge_len = sx + sy - x - y - 1;
if (!CheckBridge_Stuff(bridge_type, bridge_len)) return_cmd_error(STR_5015_CAN_T_BUILD_BRIDGE_HERE); if (!CheckBridge_Stuff(bridge_type, bridge_len)) return_cmd_error(STR_5015_CAN_T_BUILD_BRIDGE_HERE);
/* retrieve landscape height and ensure it's on land */ /* retrieve landscape height and ensure it's on land */
tile_start = TileXY(x, y); tile_start = TileXY(x, y);
tile_end = TileXY(sx, sy); tile_end = TileXY(sx, sy);
if (IsClearWaterTile(tile_start) || IsClearWaterTile(tile_end)) return_cmd_error(STR_02A0_ENDS_OF_BRIDGE_MUST_BOTH); if (IsClearWaterTile(tile_start) || IsClearWaterTile(tile_end)) {
return_cmd_error(STR_02A0_ENDS_OF_BRIDGE_MUST_BOTH);
}
tileh_start = GetTileSlope(tile_start, &z_start); tileh_start = GetTileSlope(tile_start, &z_start);
tileh_end = GetTileSlope(tile_end, &z_end); tileh_end = GetTileSlope(tile_end, &z_end);
@ -325,7 +327,7 @@ int32 CmdBuildBridge(TileIndex end_tile, uint32 flags, uint32 p1, uint32 p2)
switch (GetTileType(tile)) { switch (GetTileType(tile)) {
case MP_WATER: case MP_WATER:
if (!EnsureNoVehicle(tile)) return_cmd_error(STR_980E_SHIP_IN_THE_WAY); if (!EnsureNoVehicle(tile)) return_cmd_error(STR_980E_SHIP_IN_THE_WAY);
if (!(IsWater(tile) || IsCoast(tile))) goto not_valid_below; if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
transport_under = TRANSPORT_WATER; transport_under = TRANSPORT_WATER;
owner_under = GetTileOwner(tile); owner_under = GetTileOwner(tile);
break; break;
@ -508,7 +510,6 @@ int32 CmdBuildTunnel(TileIndex start_tile, uint32 flags, uint32 p1, uint32 p2)
MakeRoadTunnel(start_tile, _current_player, direction); MakeRoadTunnel(start_tile, _current_player, direction);
MakeRoadTunnel(end_tile, _current_player, ReverseDiagDir(direction)); MakeRoadTunnel(end_tile, _current_player, ReverseDiagDir(direction));
} }
} }
return cost; return cost;
@ -660,10 +661,11 @@ static int32 DoClearBridge(TileIndex tile, uint32 flags)
direction = GetBridgeRampDirection(tile); direction = GetBridgeRampDirection(tile);
delta = TileOffsByDir(direction); delta = TileOffsByDir(direction);
/* Make sure there's no vehicle on the bridge /* Make sure there's no vehicle on the bridge
Omit tile and endtile, since these are already checked, thus solving the problem * Omit tile and endtile, since these are already checked, thus solving the
of bridges over water, or higher bridges, where z is not increased, eg level bridge * problem of bridges over water, or higher bridges, where z is not increased,
*/ * eg level bridge
*/
/* Bridges on slopes might have their Z-value offset..correct this */ /* Bridges on slopes might have their Z-value offset..correct this */
v = FindVehicleBetween( v = FindVehicleBetween(
tile + delta, tile + delta,
@ -737,10 +739,10 @@ static int32 ClearTile_TunnelBridge(TileIndex tile, byte flags)
int32 DoConvertTunnelBridgeRail(TileIndex tile, RailType totype, bool exec) int32 DoConvertTunnelBridgeRail(TileIndex tile, RailType totype, bool exec)
{ {
TileIndex endtile; TileIndex endtile;
uint length;
Vehicle *v;
if (IsTunnel(tile) && GetTunnelTransportType(tile) == TRANSPORT_RAIL) { if (IsTunnel(tile) && GetTunnelTransportType(tile) == TRANSPORT_RAIL) {
uint length;
if (!CheckTileOwnership(tile)) return CMD_ERROR; if (!CheckTileOwnership(tile)) return CMD_ERROR;
if (GetRailType(tile) == totype) return CMD_ERROR; if (GetRailType(tile) == totype) return CMD_ERROR;
@ -783,11 +785,10 @@ int32 DoConvertTunnelBridgeRail(TileIndex tile, RailType totype, bool exec)
} }
return _price.build_rail >> 1; return _price.build_rail >> 1;
} else if (IsBridge(tile) && IsBridgeRamp(tile) && GetBridgeTransportType(tile) == TRANSPORT_RAIL) { } else if (IsBridge(tile) && IsBridgeRamp(tile) && GetBridgeTransportType(tile) == TRANSPORT_RAIL) {
uint z = TilePixelHeight(tile) + TILE_HEIGHT;
const Vehicle* v;
TileIndexDiff delta; TileIndexDiff delta;
int32 cost; int32 cost;
uint z = TilePixelHeight(tile);
z += TILE_HEIGHT;
if (!CheckTileOwnership(tile)) return CMD_ERROR; if (!CheckTileOwnership(tile)) return CMD_ERROR;
@ -828,8 +829,9 @@ int32 DoConvertTunnelBridgeRail(TileIndex tile, RailType totype, bool exec)
} }
return cost; return cost;
} else } else {
return CMD_ERROR; return CMD_ERROR;
}
} }
@ -876,7 +878,7 @@ static void DrawBridgePillars(PalSpriteID image, const TileInfo *ti, int x, int
for (; z >= front_height || z >= back_height; z -= TILE_HEIGHT) { for (; z >= front_height || z >= back_height; z -= TILE_HEIGHT) {
if (z >= front_height) { // front facing pillar if (z >= front_height) { // front facing pillar
AddSortableSpriteToDraw(image, x,y, p[4], p[5], 0x28, z); AddSortableSpriteToDraw(image, x, y, p[4], p[5], 0x28, z);
} }
if (drawfarpillar && z >= back_height && z < i - TILE_HEIGHT) { // back facing pillar if (drawfarpillar && z >= back_height && z < i - TILE_HEIGHT) { // back facing pillar

View File

@ -664,8 +664,6 @@ static bool QZ_PollEvent(void)
} }
static void QZ_GameLoop(void) static void QZ_GameLoop(void)
{ {
uint32 next_tick = GetTick() + 30; uint32 next_tick = GetTick() + 30;

View File

@ -649,13 +649,15 @@ static const uint16 default_resolutions[][2] = {
static void FindResolutions(void) static void FindResolutions(void)
{ {
int i = 0, n = 0; uint n = 0;
uint i;
DEVMODE dm; DEVMODE dm;
while (EnumDisplaySettings(NULL, i++, &dm) != 0) { for (i = 0; EnumDisplaySettings(NULL, i, &dm) != 0; i++) {
if (dm.dmBitsPerPel == 8 && IS_INT_INSIDE(dm.dmPelsWidth, 640, MAX_SCREEN_WIDTH + 1) && if (dm.dmBitsPerPel == 8 && IS_INT_INSIDE(dm.dmPelsWidth, 640, MAX_SCREEN_WIDTH + 1) &&
IS_INT_INSIDE(dm.dmPelsHeight, 480, MAX_SCREEN_HEIGHT + 1)){ IS_INT_INSIDE(dm.dmPelsHeight, 480, MAX_SCREEN_HEIGHT + 1)) {
int j; uint j;
for (j = 0; j < n; j++) { for (j = 0; j < n; j++) {
if (_resolutions[j][0] == dm.dmPelsWidth && _resolutions[j][1] == dm.dmPelsHeight) break; if (_resolutions[j][0] == dm.dmPelsWidth && _resolutions[j][1] == dm.dmPelsHeight) break;
} }

View File

@ -546,6 +546,7 @@ void *AddStringToDraw(int x, int y, StringID string, uint32 params_1, uint32 par
return ss; return ss;
} }
static void DrawSelectionSprite(uint32 image, const TileInfo *ti) static void DrawSelectionSprite(uint32 image, const TileInfo *ti)
{ {
if (_added_tile_sprite && !(_thd.drawstyle & HT_LINE)) { // draw on real ground if (_added_tile_sprite && !(_thd.drawstyle & HT_LINE)) { // draw on real ground

View File

@ -217,8 +217,9 @@ int32 CmdBuildTrainWaypoint(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
MakeRailWaypoint(tile, GetTileOwner(tile), axis, GetRailType(tile), wp->index); MakeRailWaypoint(tile, GetTileOwner(tile), axis, GetRailType(tile), wp->index);
MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile);
if (GB(p1, 0, 8) < GetNumCustomStations(STAT_CLASS_WAYP)) if (GB(p1, 0, 8) < GetNumCustomStations(STAT_CLASS_WAYP)) {
statspec = GetCustomStationSpec(STAT_CLASS_WAYP, GB(p1, 0, 8)); statspec = GetCustomStationSpec(STAT_CLASS_WAYP, GB(p1, 0, 8));
}
if (statspec != NULL) { if (statspec != NULL) {
SetCustomWaypointSprite(tile); SetCustomWaypointSprite(tile);
@ -237,8 +238,7 @@ int32 CmdBuildTrainWaypoint(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
wp->xy = tile; wp->xy = tile;
wp->build_date = _date; wp->build_date = _date;
if (wp->town_index == 0) if (wp->town_index == 0) MakeDefaultWaypointName(wp);
MakeDefaultWaypointName(wp);
UpdateWaypointSign(wp); UpdateWaypointSign(wp);
RedrawWaypointSign(wp); RedrawWaypointSign(wp);

View File

@ -1456,9 +1456,9 @@ void InputLoop(void)
_current_player = _local_player; _current_player = _local_player;
// Handle pressed keys // Handle pressed keys
if (_pressed_key) { if (_pressed_key != 0) {
uint32 key = _pressed_key; _pressed_key = 0; HandleKeypress(_pressed_key);
HandleKeypress(key); _pressed_key = 0;
} }
// Mouse event? // Mouse event?