diff options
author | rubidium <rubidium@openttd.org> | 2007-01-10 18:56:51 +0000 |
---|---|---|
committer | rubidium <rubidium@openttd.org> | 2007-01-10 18:56:51 +0000 |
commit | a7d0cdf95fd8847ab76b35446e1c9b77f8ef1cb7 (patch) | |
tree | 1a1c59c13ddb1d152052f3a3a0bcffe4fb531173 /src | |
parent | ce75f6549dd379b506c9f1e9383bd881aa7cf5c7 (diff) | |
download | openttd-a7d0cdf95fd8847ab76b35446e1c9b77f8ef1cb7.tar.xz |
(svn r8038) -Merge: the cpp branch. Effort of KUDr, Celestar, glx, Smoovius, stillunknown and pv2b.
Diffstat (limited to 'src')
182 files changed, 2323 insertions, 1718 deletions
diff --git a/src/ai/ai.cpp b/src/ai/ai.cpp index 58b97ad39..5b2e5a8fc 100644 --- a/src/ai/ai.cpp +++ b/src/ai/ai.cpp @@ -5,6 +5,7 @@ #include "../variables.h" #include "../command.h" #include "../network/network.h" +#include "../helpers.hpp" #include "ai.h" #include "default/default.h" @@ -50,11 +51,11 @@ static void AI_PutCommandInQueue(PlayerID player, TileIndex tile, uint32 p1, uin if (_ai_player[player].queue_tail == NULL) { /* There is no item in the queue yet, create the queue */ - _ai_player[player].queue = malloc(sizeof(AICommand)); + MallocT(&_ai_player[player].queue, 1); _ai_player[player].queue_tail = _ai_player[player].queue; } else { /* Add an item at the end */ - _ai_player[player].queue_tail->next = malloc(sizeof(AICommand)); + MallocT(&_ai_player[player].queue_tail->next, 1); _ai_player[player].queue_tail = _ai_player[player].queue_tail->next; } diff --git a/src/ai/default/default.cpp b/src/ai/default/default.cpp index 143e724b9..5a328e9d0 100644 --- a/src/ai/default/default.cpp +++ b/src/ai/default/default.cpp @@ -26,6 +26,7 @@ #include "../../variables.h" #include "../../bridge.h" #include "../../date.h" +#include "../../helpers.hpp" #include "default.h" // remove some day perhaps? @@ -63,10 +64,10 @@ enum { #include "../../table/ai_rail.h" -static byte GetRailTrackStatus(TileIndex tile) +static TrackBits GetRailTrackStatus(TileIndex tile) { uint32 r = GetTileTrackStatus(tile, TRANSPORT_RAIL); - return (byte) (r | r >> 8); + return (TrackBits)(byte) (r | r >> 8); } @@ -644,8 +645,8 @@ static bool AiCheckIfRouteIsGood(Player *p, FoundRoute *fr, byte bitmask) } if (fr->cargo == CT_PASSENGERS || fr->cargo == CT_MAIL) { - const Town* from = fr->from; - const Town* to = fr->to; + const Town* from = (const Town*)fr->from; + const Town* to = (const Town*)fr->to; if (from->pct_pass_transported > 0x99 || to->pct_pass_transported > 0x99) { @@ -783,7 +784,7 @@ static void AiWantLongIndustryRoute(Player *p) p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -851,7 +852,7 @@ static void AiWantMediumIndustryRoute(Player *p) p->ai.order_list_blocks[1] = 1; p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -919,7 +920,7 @@ static void AiWantShortIndustryRoute(Player *p) p->ai.order_list_blocks[1] = 1; p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -1020,7 +1021,7 @@ static void AiWantMailRoute(Player *p) p->ai.order_list_blocks[1] = 1; p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -1089,7 +1090,7 @@ static void AiWantPassengerRoute(Player *p) p->ai.order_list_blocks[1] = 1; p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -1164,7 +1165,7 @@ static void AiWantLongRoadIndustryRoute(Player *p) p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -1220,7 +1221,7 @@ static void AiWantMediumRoadIndustryRoute(Player *p) p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -1278,7 +1279,7 @@ static void AiWantLongRoadPassengerRoute(Player *p) p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -1334,7 +1335,7 @@ static void AiWantPassengerRouteInsideTown(Player *p) p->ai.order_list_blocks[2] = 255; p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS; - p->ai.state_mode = -1; + p->ai.state_mode = UCHAR_MAX; p->ai.state_counter = 0; p->ai.timeout_counter = 0; } @@ -1852,7 +1853,7 @@ static bool AiDoFollowTrack(const Player* p) arpfd.tile2 = p->ai.cur_tile_a; arpfd.flag = false; arpfd.count = 0; - FollowTrack(p->ai.cur_tile_a + TileOffsByDiagDir(p->ai.cur_dir_a), 0x2000 | TRANSPORT_RAIL, p->ai.cur_dir_a^2, + FollowTrack(p->ai.cur_tile_a + TileOffsByDiagDir(p->ai.cur_dir_a), 0x2000 | TRANSPORT_RAIL, (DiagDirection)(p->ai.cur_dir_a^2), (TPFEnumProc*)AiEnumFollowTrack, NULL, &arpfd); return arpfd.count > 8; } @@ -1941,7 +1942,7 @@ static bool AiCheckRailPathBetter(AiRailFinder *arf, const byte *p) } } arf->recursive_mode = 0; - arf->cur_best_dist = (uint)-1; + arf->cur_best_dist = UINT_MAX; arf->cur_best_depth = 0xff; return better; @@ -2185,7 +2186,7 @@ static bool AiRemoveTileAndGoForward(Player *p) } else { // Check if the bridge points in the right direction. // This is not really needed the first place AiRemoveTileAndGoForward is called. - if (DiagDirToAxis(GetBridgeRampDirection(tile)) != (p->ai.cur_dir_a & 1U)) return false; + if (DiagDirToAxis(GetBridgeRampDirection(tile)) != (p->ai.cur_dir_a & 1)) return false; tile = GetOtherBridgeEnd(tile); @@ -2820,7 +2821,7 @@ static bool AiCheckRoadFinished(Player *p) are.best_dist = (uint)-1; for_each_bit(i, bits) { - FollowTrack(tile, 0x3000 | TRANSPORT_ROAD, _dir_by_track[i], (TPFEnumProc*)AiEnumFollowRoad, NULL, &are); + FollowTrack(tile, 0x3000 | TRANSPORT_ROAD, (DiagDirection)_dir_by_track[i], (TPFEnumProc*)AiEnumFollowRoad, NULL, &are); } if (DistanceManhattan(tile, are.dest) <= are.best_dist) return false; @@ -3583,7 +3584,7 @@ static void AiStateRemoveStation(Player *p) p->ai.state = AIS_1; // Get a list of all stations that are in use by a vehicle - in_use = malloc(GetMaxStationIndex() + 1); + MallocT(&in_use, GetMaxStationIndex() + 1); memset(in_use, 0, GetMaxStationIndex() + 1); FOR_ALL_ORDERS(ord) { if (ord->type == OT_GOTO_STATION) in_use[ord->dest] = 1; @@ -3705,7 +3706,7 @@ pos_3: return; } - rails = 0; + rails = TRACK_BIT_NONE; switch (GetBridgeRampDirection(tile)) { default: @@ -3798,7 +3799,6 @@ static void AiHandleTakeover(Player *p) uint asked = p->bankrupt_asked; Player *pp, *best_pl = NULL; int32 best_val = -1; - uint old_p; // Ask the guy with the highest performance hist. FOR_ALL_PLAYERS(pp) { @@ -3830,7 +3830,7 @@ static void AiHandleTakeover(Player *p) // Too little money for computer to buy it? if (best_pl->player_money >> 1 >= p->bankrupt_value) { // Computer wants to buy it. - old_p = _current_player; + PlayerID old_p = _current_player; _current_player = p->index; DoCommand(0, old_p, 0, DC_EXEC, CMD_BUY_COMPANY); _current_player = old_p; diff --git a/src/ai/trolly/pathfinder.cpp b/src/ai/trolly/pathfinder.cpp index 6ffdf1fec..5ba50ca7f 100644 --- a/src/ai/trolly/pathfinder.cpp +++ b/src/ai/trolly/pathfinder.cpp @@ -57,7 +57,7 @@ static bool IsRoad(TileIndex tile) // Check if the current tile is in our end-area static int32 AyStar_AiPathFinder_EndNodeCheck(AyStar *aystar, OpenListNode *current) { - const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target; + const Ai_PathFinderInfo* PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target; // It is not allowed to have a station on the end of a bridge or tunnel ;) if (current->path.node.user_data[0] != 0) return AYSTAR_DONE; @@ -82,7 +82,7 @@ static uint AiPathFinder_Hash(uint key1, uint key2) static void AyStar_AiPathFinder_Free(AyStar *aystar) { AyStarMain_Free(aystar); - free(aystar); + delete aystar; } @@ -99,7 +99,7 @@ AyStar *new_AyStar_AiPathFinder(int max_tiles_around, Ai_PathFinderInfo *PathFin uint x; uint y; // Create AyStar - AyStar *result = malloc(sizeof(AyStar)); + AyStar *result = new AyStar(); init_AyStar(result, AiPathFinder_Hash, 1 << 10); // Set the function pointers result->CalculateG = AyStar_AiPathFinder_CalculateG; @@ -170,7 +170,7 @@ void clean_AyStar_AiPathFinder(AyStar *aystar, Ai_PathFinderInfo *PathFinderInfo // The h-value, simple calculation static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent) { - const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target; + const Ai_PathFinderInfo* PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target; int r, r2; if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION) { @@ -214,7 +214,6 @@ static void AyStar_AiPathFinder_FoundEndNode(AyStar *aystar, OpenListNode *curre // What tiles are around us. static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *current) { - uint i; int ret; int dir; @@ -223,7 +222,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr aystar->num_neighbours = 0; // Go through all surrounding tiles and check if they are within the limits - for (i = 0; i < 4; i++) { + for (DiagDirection i = DIAGDIR_BEGIN; i < DIAGDIR_END; i++) { TileIndex ctile = current->path.node.tile; // Current tile TileIndex atile = ctile + TileOffsByDiagDir(i); // Adjacent tile @@ -238,7 +237,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr if (IsTunnel(atile)) { if (GetTunnelDirection(atile) != i) continue; } else { - if ((_m[atile].m5 & 1U) != DiagDirToAxis(i)) continue; + if ((_m[atile].m5 & 1) != DiagDirToAxis(i)) continue; } } } @@ -246,7 +245,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr if (!PathFinderInfo->rail_or_road && IsRoad(ctile)) { if (IsTileType(ctile, MP_TUNNELBRIDGE)) { // An existing bridge/tunnel... let's test the direction ;) - if ((_m[ctile].m5 & 1U) != (i & 1)) continue; + if ((_m[ctile].m5 & 1) != (i & 1)) continue; } } @@ -254,7 +253,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr (AI_PATHFINDER_FLAG_TUNNEL & current->path.node.user_data[0]) != 0) { // We are a bridge/tunnel, how cool!! // This means we can only point forward.. get the direction from the user_data - if (i != (current->path.node.user_data[0] >> 8)) continue; + if ((uint)i != (current->path.node.user_data[0] >> 8)) continue; } dir = 0; @@ -371,7 +370,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr extern uint GetRailFoundation(Slope tileh, TrackBits bits); // XXX function declaration in .c -extern uint GetRoadFoundation(Slope tileh, uint bits); // XXX function declaration in .c +extern uint GetRoadFoundation(Slope tileh, RoadBits bits); // XXX function declaration in .c extern uint GetBridgeFoundation(Slope tileh, Axis); // XXX function declaration in .c enum { BRIDGE_NO_FOUNDATION = 1 << 0 | 1 << 3 | 1 << 6 | 1 << 9 | 1 << 12, @@ -417,7 +416,7 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current, // Skip if the tile was from a bridge or tunnel if (parent->path.node.user_data[0] == 0 && current->user_data[0] == 0) { if (PathFinderInfo->rail_or_road) { - r = GetRailFoundation(parent_tileh, 1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile)); + r = GetRailFoundation(parent_tileh, (TrackBits)(1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile))); // Maybe is BRIDGE_NO_FOUNDATION a bit strange here, but it contains just the right information.. if (r >= 15 || (r == 0 && HASBIT(BRIDGE_NO_FOUNDATION, tileh))) { res += AI_PATHFINDER_TILE_GOES_UP_PENALTY; @@ -426,7 +425,7 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current, } } else { if (!IsRoad(parent->path.node.tile) || !IsTileType(parent->path.node.tile, MP_TUNNELBRIDGE)) { - r = GetRoadFoundation(parent_tileh, AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile)); + r = GetRoadFoundation(parent_tileh, (RoadBits)AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile)); if (r >= 15 || r == 0) { res += AI_PATHFINDER_TILE_GOES_UP_PENALTY; } else { @@ -452,13 +451,13 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current, // Check if we are going up or down, first for the starting point // In user_data[0] is at the 8th bit the direction if (!HASBIT(BRIDGE_NO_FOUNDATION, parent_tileh)) { - if (GetBridgeFoundation(parent_tileh, (current->user_data[0] >> 8) & 1) < 15) { + if (GetBridgeFoundation(parent_tileh, (Axis)((current->user_data[0] >> 8) & 1)) < 15) { res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY; } } // Second for the end point if (!HASBIT(BRIDGE_NO_FOUNDATION, tileh)) { - if (GetBridgeFoundation(tileh, (current->user_data[0] >> 8) & 1) < 15) { + if (GetBridgeFoundation(tileh, (Axis)((current->user_data[0] >> 8) & 1)) < 15) { res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY; } } diff --git a/src/ai/trolly/trolly.cpp b/src/ai/trolly/trolly.cpp index 35115a880..855f74c8f 100644 --- a/src/ai/trolly/trolly.cpp +++ b/src/ai/trolly/trolly.cpp @@ -794,7 +794,7 @@ static void AiNew_State_FindDepot(Player *p) for (i=2;i<p->ainew.path_info.route_length-2;i++) { tile = p->ainew.path_info.route[i]; - for (j = 0; j < 4; j++) { + for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) { TileIndex t = tile + TileOffsByDiagDir(j); if (IsTileType(t, MP_STREET) && @@ -825,7 +825,7 @@ static void AiNew_State_FindDepot(Player *p) tile = p->ainew.path_info.route[i]; - for (j = 0; j < 4; j++) { + for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) { TileIndex t = tile + TileOffsByDiagDir(j); // It may not be placed on the road/rail itself @@ -901,7 +901,8 @@ static int AiNew_HowManyVehicles(Player *p) } // This is because moving 60% is more than we can dream of! - max_cargo *= 0.6; + max_cargo *= 6; + max_cargo /= 10; // We want all the cargo to be gone in a month.. so, we know the cargo it delivers // we know what the vehicle takes with him, and we know the time it takes him // to get back here.. now let's do some math! @@ -1051,7 +1052,7 @@ static void AiNew_State_BuildPath(Player *p) dir3 = p->ainew.to_direction; } - ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir1)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); + ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir((DiagDirection)dir1)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); if (!CmdFailed(ret)) { dir1 = TileOffsByDiagDir(dir1); if (IsTileType(tile + dir1, MP_CLEAR) || IsTileType(tile + dir1, MP_TREES)) { @@ -1063,7 +1064,7 @@ static void AiNew_State_BuildPath(Player *p) } } - ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir2)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); + ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir((DiagDirection)dir2)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); if (!CmdFailed(ret)) { dir2 = TileOffsByDiagDir(dir2); if (IsTileType(tile + dir2, MP_CLEAR) || IsTileType(tile + dir2, MP_TREES)) { @@ -1075,7 +1076,7 @@ static void AiNew_State_BuildPath(Player *p) } } - ret = AI_DoCommand(tile, DiagDirToRoadBits(dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); + ret = AI_DoCommand(tile, DiagDirToRoadBits((DiagDirection)dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD); if (!CmdFailed(ret)) { dir3 = TileOffsByDiagDir(dir3); if (IsTileType(tile + dir3, MP_CLEAR) || IsTileType(tile + dir3, MP_TREES)) { diff --git a/src/aircraft_cmd.cpp b/src/aircraft_cmd.cpp index bbc3aa4db..16c4edfab 100644 --- a/src/aircraft_cmd.cpp +++ b/src/aircraft_cmd.cpp @@ -246,7 +246,7 @@ int32 CmdBuildAircraft(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) v->unitnumber = unit_num; v->type = u->type = VEH_Aircraft; - v->direction = 3; + v->direction = DIR_SE; v->owner = u->owner = _current_player; @@ -382,7 +382,7 @@ int32 CmdBuildAircraft(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) u->next = w; w->type = VEH_Aircraft; - w->direction = 0; + w->direction = DIR_N; w->owner = _current_player; w->x_pos = v->x_pos; w->y_pos = v->y_pos; @@ -907,7 +907,8 @@ static bool AircraftController(Vehicle *v) Station *st; const AirportMovingData *amd; Vehicle *u; - byte z,newdir,maxz,curz; + byte z, maxz, curz; + Direction newdir; GetNewVehiclePosResult gp; uint dist; int x,y; @@ -1419,7 +1420,7 @@ static void AircraftLeaveHangar(Vehicle *v) v->cur_speed = 0; v->subspeed = 0; v->progress = 0; - v->direction = 3; + v->direction = DIR_SE; v->vehstatus &= ~VS_HIDDEN; { Vehicle *u = v->next; diff --git a/src/airport.cpp b/src/airport.cpp index 2135bd11b..60df231bb 100644 --- a/src/airport.cpp +++ b/src/airport.cpp @@ -9,6 +9,7 @@ #include "variables.h" #include "airport_movement.h" #include "date.h" +#include "helpers.hpp" /* Uncomment this to print out a full report of the airport-structure * You should either use @@ -30,7 +31,7 @@ static AirportFTAClass *HeliStation; static void AirportFTAClass_Constructor(AirportFTAClass *apc, const byte *terminals, const byte *helipads, - const byte entry_point, const byte acc_planes, + const byte entry_point, const AcceptPlanes acc_planes, const AirportFTAbuildup *apFA, const TileIndexDiffC *depots, const byte nof_depots, uint size_x, uint size_y @@ -49,7 +50,7 @@ static void AirportPrintOut(const AirportFTAClass *apc, bool full_report); void InitializeAirports(void) { // country airport - CountryAirport = malloc(sizeof(AirportFTAClass)); + MallocT(&CountryAirport, 1); AirportFTAClass_Constructor( CountryAirport, @@ -64,7 +65,7 @@ void InitializeAirports(void) ); // city airport - CityAirport = malloc(sizeof(AirportFTAClass)); + MallocT(&CityAirport, 1); AirportFTAClass_Constructor( CityAirport, @@ -79,7 +80,7 @@ void InitializeAirports(void) ); // metropolitan airport - MetropolitanAirport = malloc(sizeof(AirportFTAClass)); + MallocT(&MetropolitanAirport, 1); AirportFTAClass_Constructor( MetropolitanAirport, @@ -94,7 +95,7 @@ void InitializeAirports(void) ); // international airport - InternationalAirport = (AirportFTAClass *)malloc(sizeof(AirportFTAClass)); + MallocT(&InternationalAirport, 1); AirportFTAClass_Constructor( InternationalAirport, @@ -109,7 +110,7 @@ void InitializeAirports(void) ); // intercontintental airport - IntercontinentalAirport = (AirportFTAClass *)malloc(sizeof(AirportFTAClass)); + MallocT(&IntercontinentalAirport, 1); AirportFTAClass_Constructor( IntercontinentalAirport, @@ -124,7 +125,7 @@ void InitializeAirports(void) ); // heliport, oilrig - Heliport = (AirportFTAClass *)malloc(sizeof(AirportFTAClass)); + MallocT(&Heliport, 1); AirportFTAClass_Constructor( Heliport, @@ -141,7 +142,7 @@ void InitializeAirports(void) Oilrig = Heliport; // exactly the same structure for heliport/oilrig, so share state machine // commuter airport - CommuterAirport = malloc(sizeof(AirportFTAClass)); + MallocT(&CommuterAirport, 1); AirportFTAClass_Constructor( CommuterAirport, @@ -156,7 +157,7 @@ void InitializeAirports(void) ); // helidepot airport - HeliDepot = malloc(sizeof(AirportFTAClass)); + MallocT(&HeliDepot, 1); AirportFTAClass_Constructor( HeliDepot, @@ -171,7 +172,7 @@ void InitializeAirports(void) ); // helistation airport - HeliStation = malloc(sizeof(AirportFTAClass)); + MallocT(&HeliStation, 1); AirportFTAClass_Constructor( HeliStation, @@ -202,7 +203,7 @@ void UnInitializeAirports(void) static void AirportFTAClass_Constructor(AirportFTAClass *apc, const byte *terminals, const byte *helipads, - const byte entry_point, const byte acc_planes, + const byte entry_point, const AcceptPlanes acc_planes, const AirportFTAbuildup *apFA, const TileIndexDiffC *depots, const byte nof_depots, uint size_x, uint size_y @@ -323,7 +324,8 @@ static byte AirportGetTerminalCount(const byte *terminals, byte *groups) static void AirportBuildAutomata(AirportFTAClass *apc, const AirportFTAbuildup *apFA) { AirportFTA *current; - AirportFTA *FAutomata = malloc(sizeof(AirportFTA) * apc->nofelements); + AirportFTA *FAutomata; + MallocT(&FAutomata, apc->nofelements); uint16 internalcounter = 0; uint16 i; @@ -337,7 +339,8 @@ static void AirportBuildAutomata(AirportFTAClass *apc, const AirportFTAbuildup * // outgoing nodes from the same position, create linked list while (current->position == apFA[internalcounter + 1].position) { - AirportFTA *newNode = malloc(sizeof(AirportFTA)); + AirportFTA *newNode; + MallocT(&newNode, 1); newNode->position = apFA[internalcounter + 1].position; newNode->heading = apFA[internalcounter + 1].heading; diff --git a/src/airport.h b/src/airport.h index 2dcbd1660..207de84fa 100644 --- a/src/airport.h +++ b/src/airport.h @@ -3,6 +3,8 @@ #ifndef AIRPORT_H #define AIRPORT_H +#include "direction.h" + enum {MAX_TERMINALS = 10}; enum {MAX_HELIPADS = 4}; enum {MAX_ELEMENTS = 255}; @@ -23,12 +25,18 @@ enum { }; // do not change unless you change v->subtype too. This aligns perfectly with its current setting -enum { +enum AcceptPlanes { + ACC_BEGIN = 0, AIRCRAFT_ONLY = 0, ALL = 1, HELICOPTERS_ONLY = 2, + ACC_END }; +/** Define basic enum properties */ +template <> struct EnumPropsT<AcceptPlanes> : MakeEnumPropsT<AcceptPlanes, byte, ACC_BEGIN, ACC_END, ACC_END> {}; +typedef TinyEnumT<AcceptPlanes> AcceptPlanesByte; + enum { AMED_NOSPDCLAMP = 1 << 0, AMED_TAKEOFF = 1 << 1, @@ -122,7 +130,7 @@ enum { typedef struct AirportMovingData { int x,y; byte flag; - byte direction; + DirectionByte direction; } AirportMovingData; // Finite sTate mAchine --> FTA @@ -131,7 +139,7 @@ typedef struct AirportFTAClass { const byte *terminals; const byte *helipads; byte entry_point; // when an airplane arrives at this airport, enter it at position entry_point - byte acc_planes; // accept airplanes or helicopters or both + AcceptPlanesByte acc_planes; // accept airplanes or helicopters or both const TileIndexDiffC *airport_depots; // gives the position of the depots on the airports byte nof_depots; // number of depots this airport has struct AirportFTA *layout; // state machine for airport diff --git a/src/airport_gui.cpp b/src/airport_gui.cpp index c049d50d5..adfd6849c 100644 --- a/src/airport_gui.cpp +++ b/src/airport_gui.cpp @@ -216,7 +216,7 @@ static void BuildAirportPickerWndProc(Window *w, WindowEvent *e) SetWindowDirty(w); break; case 16: case 17: - _station_show_coverage = e->we.click.widget - 16; + _station_show_coverage = (e->we.click.widget != 16); SetWindowWidgetLoweredState(w, 16, !_station_show_coverage); SetWindowWidgetLoweredState(w, 17, _station_show_coverage); SndPlayFx(SND_15_BEEP); diff --git a/src/airport_movement.h b/src/airport_movement.h index 1ca00ed75..ac0937cc1 100644 --- a/src/airport_movement.h +++ b/src/airport_movement.h @@ -17,354 +17,354 @@ typedef struct AirportFTAbuildup { /////*********Movement Positions on Airports********************/////// // Country Airfield (small) 4x3 static const AirportMovingData _airport_moving_data_country[22] = { - { 53, 3, AMED_EXACTPOS, 3 }, // 00 In Hangar - { 53, 27, 0, 0 }, // 01 Taxi to right outside depot - { 32, 23, AMED_EXACTPOS, 7 }, // 02 Terminal 1 - { 10, 23, AMED_EXACTPOS, 7 }, // 03 Terminal 2 - { 43, 37, 0, 0 }, // 04 Going towards terminal 2 - { 24, 37, 0, 0 }, // 05 Going towards terminal 2 - { 53, 37, 0, 0 }, // 06 Going for takeoff - { 61, 40, AMED_EXACTPOS, 1 }, // 07 Taxi to start of runway (takeoff) - { 3, 40, AMED_NOSPDCLAMP, 0 }, // 08 Accelerate to end of runway - { -79, 40, AMED_NOSPDCLAMP | AMED_TAKEOFF, 0 }, // 09 Take off - { 177, 40, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 10 Fly to landing position in air - { 56, 40, AMED_NOSPDCLAMP | AMED_LAND, 0 }, // 11 Going down for land - { 3, 40, AMED_NOSPDCLAMP | AMED_BRAKE, 0 }, // 12 Just landed, brake until end of runway - { 7, 40, 0, 0 }, // 13 Just landed, turn around and taxi 1 square - { 53, 40, 0, 0 }, // 14 Taxi from runway to crossing - { -31, 193, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 15 Fly around waiting for a landing spot (north-east) - { 1, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 16 Fly around waiting for a landing spot (north-west) - { 257, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 17 Fly around waiting for a landing spot (south-west) - { 273, 49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 18 Fly around waiting for a landing spot (south) - { 44, 37, AMED_HELI_RAISE, 0 }, // 19 Helicopter takeoff - { 44, 40, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 20 In position above landing spot helicopter - { 44, 40, AMED_HELI_LOWER, 0 }, // 21 Helicopter landing + { 53, 3, AMED_EXACTPOS, {DIR_SE} }, // 00 In Hangar + { 53, 27, 0, {DIR_N} }, // 01 Taxi to right outside depot + { 32, 23, AMED_EXACTPOS, {DIR_NW} }, // 02 Terminal 1 + { 10, 23, AMED_EXACTPOS, {DIR_NW} }, // 03 Terminal 2 + { 43, 37, 0, {DIR_N} }, // 04 Going towards terminal 2 + { 24, 37, 0, {DIR_N} }, // 05 Going towards terminal 2 + { 53, 37, 0, {DIR_N} }, // 06 Going for takeoff + { 61, 40, AMED_EXACTPOS, {DIR_NE} }, // 07 Taxi to start of runway (takeoff) + { 3, 40, AMED_NOSPDCLAMP, {DIR_N} }, // 08 Accelerate to end of runway + { -79, 40, AMED_NOSPDCLAMP | AMED_TAKEOFF, {DIR_N} }, // 09 Take off + { 177, 40, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 10 Fly to landing position in air + { 56, 40, AMED_NOSPDCLAMP | AMED_LAND, {DIR_N} }, // 11 Going down for land + { 3, 40, AMED_NOSPDCLAMP | AMED_BRAKE, {DIR_N} }, // 12 Just landed, brake until end of runway + { 7, 40, 0, {DIR_N} }, // 13 Just landed, turn around and taxi 1 square + { 53, 40, 0, {DIR_N} }, // 14 Taxi from runway to crossing + { -31, 193, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 15 Fly around waiting for a landing spot (north-east) + { 1, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 16 Fly around waiting for a landing spot (north-west) + { 257, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 17 Fly around waiting for a landing spot (south-west) + { 273, 49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 18 Fly around waiting for a landing spot (south) + { 44, 37, AMED_HELI_RAISE, {DIR_N} }, // 19 Helicopter takeoff + { 44, 40, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 20 In position above landing spot helicopter + { 44, 40, AMED_HELI_LOWER, {DIR_N} }, // 21 Helicopter landing }; // Commuter Airfield (small) 5x4 static const AirportMovingData _airport_moving_data_commuter[37] = { - { 69, 3, AMED_EXACTPOS, 3 }, // 00 In Hangar - { 72, 22, 0, 0 }, // 01 Taxi to right outside depot - { 8, 22, AMED_EXACTPOS, 5 }, // 01 Taxi to right outside depot - { 24, 36, AMED_EXACTPOS, 3 }, // 03 Terminal 1 - { 40, 36, AMED_EXACTPOS, 3 }, // 04 Terminal 2 - { 56, 36, AMED_EXACTPOS, 3 }, // 05 Terminal 3 - { 40, 8, AMED_EXACTPOS, 1 }, // 06 Helipad 1 - { 56, 8, AMED_EXACTPOS, 1 }, // 07 Helipad 2 - { 24, 22, 0, 5 }, // 08 Taxiing - { 40, 22, 0, 5 }, // 09 Taxiing - { 56, 22, 0, 5 }, // 10 Taxiing - { 72, 40, 0, 3 }, // 11 Airport OUTWAY - { 72, 54, AMED_EXACTPOS, 1 }, // 12 Accelerate to end of runway - { 7, 54, AMED_NOSPDCLAMP, 0 }, // 13 Release control of runway, for smoother movement - { 5, 54, AMED_NOSPDCLAMP, 0 }, // 14 End of runway - { -79, 54, AMED_NOSPDCLAMP | AMED_TAKEOFF, 0 }, // 15 Take off - { 145, 54, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 16 Fly to landing position in air - { 73, 54, AMED_NOSPDCLAMP | AMED_LAND, 0 }, // 17 Going down for land - { 3, 54, AMED_NOSPDCLAMP | AMED_BRAKE, 0 }, // 18 Just landed, brake until end of runway - { 12, 54, 0, 7 }, // 19 Just landed, turn around and taxi - { 8, 32, 0, 7 }, // 20 Taxi from runway to crossing - { -31, 149, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 21 Fly around waiting for a landing spot (north-east) - { 1, 6, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 22 Fly around waiting for a landing spot (north-west) - { 193, 6, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 23 Fly around waiting for a landing spot (south-west) - { 225, 81, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 24 Fly around waiting for a landing spot (south) + { 69, 3, AMED_EXACTPOS, {DIR_SE} }, // 00 In Hangar + { 72, 22, 0, {DIR_N} }, // 01 Taxi to right outside depot + { 8, 22, AMED_EXACTPOS, {DIR_SW} }, // 01 Taxi to right outside depot + { 24, 36, AMED_EXACTPOS, {DIR_SE} }, // 03 Terminal 1 + { 40, 36, AMED_EXACTPOS, {DIR_SE} }, // 04 Terminal 2 + { 56, 36, AMED_EXACTPOS, {DIR_SE} }, // 05 Terminal 3 + { 40, 8, AMED_EXACTPOS, {DIR_NE} }, // 06 Helipad 1 + { 56, 8, AMED_EXACTPOS, {DIR_NE} }, // 07 Helipad 2 + { 24, 22, 0, {DIR_SW} }, // 08 Taxiing + { 40, 22, 0, {DIR_SW} }, // 09 Taxiing + { 56, 22, 0, {DIR_SW} }, // 10 Taxiing + { 72, 40, 0, {DIR_SE} }, // 11 Airport OUTWAY + { 72, 54, AMED_EXACTPOS, {DIR_NE} }, // 12 Accelerate to end of runway + { 7, 54, AMED_NOSPDCLAMP, {DIR_N} }, // 13 Release control of runway, for smoother movement + { 5, 54, AMED_NOSPDCLAMP, {DIR_N} }, // 14 End of runway + { -79, 54, AMED_NOSPDCLAMP | AMED_TAKEOFF, {DIR_N} }, // 15 Take off + { 145, 54, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 16 Fly to landing position in air + { 73, 54, AMED_NOSPDCLAMP | AMED_LAND, {DIR_N} }, // 17 Going down for land + { 3, 54, AMED_NOSPDCLAMP | AMED_BRAKE, {DIR_N} }, // 18 Just landed, brake until end of runway + { 12, 54, 0, {DIR_NW} }, // 19 Just landed, turn around and taxi + { 8, 32, 0, {DIR_NW} }, // 20 Taxi from runway to crossing + { -31, 149, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 21 Fly around waiting for a landing spot (north-east) + { 1, 6, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 22 Fly around waiting for a landing spot (north-west) + { 193, 6, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 23 Fly around waiting for a landing spot (south-west) + { 225, 81, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 24 Fly around waiting for a landing spot (south) // Helicopter - { 80, 0, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 25 Bufferspace before helipad - { 80, 0, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 26 Bufferspace before helipad - { 32, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 27 Get in position for Helipad1 - { 48, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 28 Get in position for Helipad2 - { 32, 8, AMED_HELI_LOWER, 0 }, // 29 Land at Helipad1 - { 48, 8, AMED_HELI_LOWER, 0 }, // 30 Land at Helipad2 - { 32, 8, AMED_HELI_RAISE, 0 }, // 31 Takeoff Helipad1 - { 48, 8, AMED_HELI_RAISE, 0 }, // 32 Takeoff Helipad2 - { 64, 22, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 33 Go to position for Hangarentrance in air - { 64, 22, AMED_HELI_LOWER, 0 }, // 34 Land in front of hangar - { 40, 8, AMED_EXACTPOS, 0 }, // pre-helitakeoff helipad 1 - { 56, 8, AMED_EXACTPOS, 0 }, // pre-helitakeoff helipad 2 + { 80, 0, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 25 Bufferspace before helipad + { 80, 0, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 26 Bufferspace before helipad + { 32, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 27 Get in position for Helipad1 + { 48, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 28 Get in position for Helipad2 + { 32, 8, AMED_HELI_LOWER, {DIR_N} }, // 29 Land at Helipad1 + { 48, 8, AMED_HELI_LOWER, {DIR_N} }, // 30 Land at Helipad2 + { 32, 8, AMED_HELI_RAISE, {DIR_N} }, // 31 Takeoff Helipad1 + { 48, 8, AMED_HELI_RAISE, {DIR_N} }, // 32 Takeoff Helipad2 + { 64, 22, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 33 Go to position for Hangarentrance in air + { 64, 22, AMED_HELI_LOWER, {DIR_N} }, // 34 Land in front of hangar + { 40, 8, AMED_EXACTPOS, {DIR_N} }, // pre-helitakeoff helipad 1 + { 56, 8, AMED_EXACTPOS, {DIR_N} }, // pre-helitakeoff helipad 2 }; // City Airport (large) 6x6 static const AirportMovingData _airport_moving_data_town[25] = { - { 85, 3, AMED_EXACTPOS, 3 }, // 00 In Hangar - { 85, 27, 0, 0 }, // 01 Taxi to right outside depot - { 26, 41, AMED_EXACTPOS, 5 }, // 02 Terminal 1 - { 56, 20, AMED_EXACTPOS, 3 }, // 03 Terminal 2 - { 38, 8, AMED_EXACTPOS, 5 }, // 04 Terminal 3 - { 65, 6, 0, 0 }, // 05 Taxi to right in infront of terminal 2/3 - { 80, 27, 0, 0 }, // 06 Taxiway terminals 2-3 - { 44, 63, 0, 0 }, // 07 Taxi to Airport center - { 58, 71, 0, 0 }, // 08 Towards takeoff - { 72, 85, 0, 0 }, // 09 Taxi to runway (takeoff) - { 89, 85, AMED_EXACTPOS, 1 }, // 10 Taxi to start of runway (takeoff) - { 3, 85, AMED_NOSPDCLAMP, 0 }, // 11 Accelerate to end of runway - { -79, 85, AMED_NOSPDCLAMP | AMED_TAKEOFF, 0 }, // 12 Take off - { 177, 85, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 13 Fly to landing position in air - { 89, 85, AMED_NOSPDCLAMP | AMED_LAND, 0 }, // 14 Going down for land - { 3, 85, AMED_NOSPDCLAMP | AMED_BRAKE, 0 }, // 15 Just landed, brake until end of runway - { 20, 87, 0, 0 }, // 16 Just landed, turn around and taxi 1 square - { 36, 71, 0, 0 }, // 17 Taxi from runway to crossing - { -31, 193, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 18 Fly around waiting for a landing spot (north-east) - { 1, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 19 Fly around waiting for a landing spot (north-west) - { 257, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 20 Fly around waiting for a landing spot (south-west) - { 273, 49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 21 Fly around waiting for a landing spot (south) - { 44, 63, AMED_HELI_RAISE, 0 }, // 22 Helicopter takeoff - { 28, 74, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 23 In position above landing spot helicopter - { 28, 74, AMED_HELI_LOWER, 0 }, // 24 Helicopter landing + { 85, 3, AMED_EXACTPOS, {DIR_SE} }, // 00 In Hangar + { 85, 27, 0, {DIR_N} }, // 01 Taxi to right outside depot + { 26, 41, AMED_EXACTPOS, {DIR_SW} }, // 02 Terminal 1 + { 56, 20, AMED_EXACTPOS, {DIR_SE} }, // 03 Terminal 2 + { 38, 8, AMED_EXACTPOS, {DIR_SW} }, // 04 Terminal 3 + { 65, 6, 0, {DIR_N} }, // 05 Taxi to right in infront of terminal 2/3 + { 80, 27, 0, {DIR_N} }, // 06 Taxiway terminals 2-3 + { 44, 63, 0, {DIR_N} }, // 07 Taxi to Airport center + { 58, 71, 0, {DIR_N} }, // 08 Towards takeoff + { 72, 85, 0, {DIR_N} }, // 09 Taxi to runway (takeoff) + { 89, 85, AMED_EXACTPOS, {DIR_NE} }, // 10 Taxi to start of runway (takeoff) + { 3, 85, AMED_NOSPDCLAMP, {DIR_N} }, // 11 Accelerate to end of runway + { -79, 85, AMED_NOSPDCLAMP | AMED_TAKEOFF, {DIR_N} }, // 12 Take off + { 177, 85, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 13 Fly to landing position in air + { 89, 85, AMED_NOSPDCLAMP | AMED_LAND, {DIR_N} }, // 14 Going down for land + { 3, 85, AMED_NOSPDCLAMP | AMED_BRAKE, {DIR_N} }, // 15 Just landed, brake until end of runway + { 20, 87, 0, {DIR_N} }, // 16 Just landed, turn around and taxi 1 square + { 36, 71, 0, {DIR_N} }, // 17 Taxi from runway to crossing + { -31, 193, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 18 Fly around waiting for a landing spot (north-east) + { 1, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 19 Fly around waiting for a landing spot (north-west) + { 257, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 20 Fly around waiting for a landing spot (south-west) + { 273, 49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 21 Fly around waiting for a landing spot (south) + { 44, 63, AMED_HELI_RAISE, {DIR_N} }, // 22 Helicopter takeoff + { 28, 74, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 23 In position above landing spot helicopter + { 28, 74, AMED_HELI_LOWER, {DIR_N} }, // 24 Helicopter landing }; // Metropolitan Airport (metropolitan) - 2 runways static const AirportMovingData _airport_moving_data_metropolitan[27] = { - { 85, 3, AMED_EXACTPOS, 3 }, // 00 In Hangar - { 85, 27, 0, 0 }, // 01 Taxi to right outside depot - { 26, 41, AMED_EXACTPOS, 5 }, // 02 Terminal 1 - { 56, 20, AMED_EXACTPOS, 3 }, // 03 Terminal 2 - { 38, 8, AMED_EXACTPOS, 5 }, // 04 Terminal 3 - { 65, 6, 0, 0 }, // 05 Taxi to right in infront of terminal 2/3 - { 70, 33, 0, 0 }, // 06 Taxiway terminals 2-3 - { 44, 58, 0, 0 }, // 07 Taxi to Airport center - { 72, 58, 0, 0 }, // 08 Towards takeoff - { 72, 69, 0, 0 }, // 09 Taxi to runway (takeoff) - { 89, 69, AMED_EXACTPOS, 1 }, // 10 Taxi to start of runway (takeoff) - { 3, 69, AMED_NOSPDCLAMP, 0 }, // 11 Accelerate to end of runway - { -79, 69, AMED_NOSPDCLAMP | AMED_TAKEOFF, 0 }, // 12 Take off - { 177, 85, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 13 Fly to landing position in air - { 89, 85, AMED_NOSPDCLAMP | AMED_LAND, 0 }, // 14 Going down for land - { 3, 85, AMED_NOSPDCLAMP | AMED_BRAKE, 0 }, // 15 Just landed, brake until end of runway - { 21, 85, 0, 0 }, // 16 Just landed, turn around and taxi 1 square - { 21, 69, 0, 0 }, // 17 On Runway-out taxiing to In-Way - { 21, 54, AMED_EXACTPOS, 5 }, // 18 Taxi from runway to crossing - { -31, 193, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 19 Fly around waiting for a landing spot (north-east) - { 1, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 20 Fly around waiting for a landing spot (north-west) - { 257, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 21 Fly around waiting for a landing spot (south-west) - { 273, 49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 22 Fly around waiting for a landing spot (south) - { 44, 58, 0, 0 }, // 23 Helicopter takeoff spot on ground (to clear airport sooner) - { 44, 63, AMED_HELI_RAISE, 0 }, // 24 Helicopter takeoff - { 15, 54, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 25 Get in position above landing spot helicopter - { 15, 54, AMED_HELI_LOWER, 0 }, // 26 Helicopter landing + { 85, 3, AMED_EXACTPOS, {DIR_SE} }, // 00 In Hangar + { 85, 27, 0, {DIR_N} }, // 01 Taxi to right outside depot + { 26, 41, AMED_EXACTPOS, {DIR_SW} }, // 02 Terminal 1 + { 56, 20, AMED_EXACTPOS, {DIR_SE} }, // 03 Terminal 2 + { 38, 8, AMED_EXACTPOS, {DIR_SW} }, // 04 Terminal 3 + { 65, 6, 0, {DIR_N} }, // 05 Taxi to right in infront of terminal 2/3 + { 70, 33, 0, {DIR_N} }, // 06 Taxiway terminals 2-3 + { 44, 58, 0, {DIR_N} }, // 07 Taxi to Airport center + { 72, 58, 0, {DIR_N} }, // 08 Towards takeoff + { 72, 69, 0, {DIR_N} }, // 09 Taxi to runway (takeoff) + { 89, 69, AMED_EXACTPOS, {DIR_NE} }, // 10 Taxi to start of runway (takeoff) + { 3, 69, AMED_NOSPDCLAMP, {DIR_N} }, // 11 Accelerate to end of runway + { -79, 69, AMED_NOSPDCLAMP | AMED_TAKEOFF, {DIR_N} }, // 12 Take off + { 177, 85, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 13 Fly to landing position in air + { 89, 85, AMED_NOSPDCLAMP | AMED_LAND, {DIR_N} }, // 14 Going down for land + { 3, 85, AMED_NOSPDCLAMP | AMED_BRAKE, {DIR_N} }, // 15 Just landed, brake until end of runway + { 21, 85, 0, {DIR_N} }, // 16 Just landed, turn around and taxi 1 square + { 21, 69, 0, {DIR_N} }, // 17 On Runway-out taxiing to In-Way + { 21, 54, AMED_EXACTPOS, {DIR_SW} }, // 18 Taxi from runway to crossing + { -31, 193, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 19 Fly around waiting for a landing spot (north-east) + { 1, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 20 Fly around waiting for a landing spot (north-west) + { 257, 1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 21 Fly around waiting for a landing spot (south-west) + { 273, 49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 22 Fly around waiting for a landing spot (south) + { 44, 58, 0, {DIR_N} }, // 23 Helicopter takeoff spot on ground (to clear airport sooner) + { 44, 63, AMED_HELI_RAISE, {DIR_N} }, // 24 Helicopter takeoff + { 15, 54, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 25 Get in position above landing spot helicopter + { 15, 54, AMED_HELI_LOWER, {DIR_N} }, // 26 Helicopter landing }; // International Airport (international) - 2 runways, 6 terminals, dedicated helipod static const AirportMovingData _airport_moving_data_international[51] = { - { 7, 55, AMED_EXACTPOS, 3 }, // 00 In Hangar 1 - { 100, 21, AMED_EXACTPOS, 3 }, // 01 In Hangar 2 - { 7, 70, 0, 0 }, // 02 Taxi to right outside depot - { 100, 36, 0, 0 }, // 03 Taxi to right outside depot - { 38, 70, AMED_EXACTPOS, 5 }, // 04 Terminal 1 - { 38, 54, AMED_EXACTPOS, 5 }, // 05 Terminal 2 - { 38, 38, AMED_EXACTPOS, 5 }, // 06 Terminal 3 - { 70, 70, AMED_EXACTPOS, 1 }, // 07 Terminal 4 - { 70, 54, AMED_EXACTPOS, 1 }, // 08 Terminal 5 - { 70, 38, AMED_EXACTPOS, 1 }, // 09 Terminal 6 - { 104, 71, AMED_EXACTPOS, 1 }, // 10 Helipad 1 - { 104, 55, AMED_EXACTPOS, 1 }, // 11 Helipad 2 - { 22, 87, 0, 0 }, // 12 Towards Terminals 4/5/6, Helipad 1/2 - { 60, 87, 0, 0 }, // 13 Towards Terminals 4/5/6, Helipad 1/2 - { 66, 87, 0, 0 }, // 14 Towards Terminals 4/5/6, Helipad 1/2 - { 86, 87, AMED_EXACTPOS, 7 }, // 15 Towards Terminals 4/5/6, Helipad 1/2 - { 86, 70, 0, 0 }, // 16 In Front of Terminal 4 / Helipad 1 - { 86, 54, 0, 0 }, // 17 In Front of Terminal 5 / Helipad 2 - { 86, 38, 0, 0 }, // 18 In Front of Terminal 6 - { 86, 22, 0, 0 }, // 19 Towards Terminals Takeoff (Taxiway) - { 66, 22, 0, 0 }, // 20 Towards Terminals Takeoff (Taxiway) - { 60, 22, 0, 0 }, // 21 Towards Terminals Takeoff (Taxiway) - { 38, 22, 0, 0 }, // 22 Towards Terminals Takeoff (Taxiway) - { 22, 70, 0, 0 }, // 23 In Front of Terminal 1 - { 22, 58, 0, 0 }, // 24 In Front of Terminal 2 - { 22, 38, 0, 0 }, // 25 In Front of Terminal 3 - { 22, 22, AMED_EXACTPOS, 7 }, // 26 Going for Takeoff - { 22, 6, 0, 0 }, // 27 On Runway-out, prepare for takeoff - { 3, 6, AMED_EXACTPOS, 5 }, // 28 Accelerate to end of runway - { 60, 6, AMED_NOSPDCLAMP, 0 }, // 29 Release control of runway, for smoother movement - { 105, 6, AMED_NOSPDCLAMP, 0 }, // 30 End of runway - { 190, 6, AMED_NOSPDCLAMP | AMED_TAKEOFF, 0 }, // 31 Take off - { 193, 104, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 32 Fly to landing position in air - { 105, 104, AMED_NOSPDCLAMP | AMED_LAND, 0 }, // 33 Going down for land - { 3, 104, AMED_NOSPDCLAMP | AMED_BRAKE, 0 }, // 34 Just landed, brake until end of runway - { 12, 104, 0, 0 }, // 35 Just landed, turn around and taxi 1 square - { 7, 84, 0, 0 }, // 36 Taxi from runway to crossing - { -31, 209, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 37 Fly around waiting for a landing spot (north-east) - { 1, 6, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 38 Fly around waiting for a landing spot (north-west) - { 273, 6, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 39 Fly around waiting for a landing spot (south-west) - { 305, 81, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 40 Fly around waiting for a landing spot (south) + { 7, 55, AMED_EXACTPOS, {DIR_SE} }, // 00 In Hangar 1 + { 100, 21, AMED_EXACTPOS, {DIR_SE} }, // 01 In Hangar 2 + { 7, 70, 0, {DIR_N} }, // 02 Taxi to right outside depot + { 100, 36, 0, {DIR_N} }, // 03 Taxi to right outside depot + { 38, 70, AMED_EXACTPOS, {DIR_SW} }, // 04 Terminal 1 + { 38, 54, AMED_EXACTPOS, {DIR_SW} }, // 05 Terminal 2 + { 38, 38, AMED_EXACTPOS, {DIR_SW} }, // 06 Terminal 3 + { 70, 70, AMED_EXACTPOS, {DIR_NE} }, // 07 Terminal 4 + { 70, 54, AMED_EXACTPOS, {DIR_NE} }, // 08 Terminal 5 + { 70, 38, AMED_EXACTPOS, {DIR_NE} }, // 09 Terminal 6 + { 104, 71, AMED_EXACTPOS, {DIR_NE} }, // 10 Helipad 1 + { 104, 55, AMED_EXACTPOS, {DIR_NE} }, // 11 Helipad 2 + { 22, 87, 0, {DIR_N} }, // 12 Towards Terminals 4/5/6, Helipad 1/2 + { 60, 87, 0, {DIR_N} }, // 13 Towards Terminals 4/5/6, Helipad 1/2 + { 66, 87, 0, {DIR_N} }, // 14 Towards Terminals 4/5/6, Helipad 1/2 + { 86, 87, AMED_EXACTPOS, {DIR_NW} }, // 15 Towards Terminals 4/5/6, Helipad 1/2 + { 86, 70, 0, {DIR_N} }, // 16 In Front of Terminal 4 / Helipad 1 + { 86, 54, 0, {DIR_N} }, // 17 In Front of Terminal 5 / Helipad 2 + { 86, 38, 0, {DIR_N} }, // 18 In Front of Terminal 6 + { 86, 22, 0, {DIR_N} }, // 19 Towards Terminals Takeoff (Taxiway) + { 66, 22, 0, {DIR_N} }, // 20 Towards Terminals Takeoff (Taxiway) + { 60, 22, 0, {DIR_N} }, // 21 Towards Terminals Takeoff (Taxiway) + { 38, 22, 0, {DIR_N} }, // 22 Towards Terminals Takeoff (Taxiway) + { 22, 70, 0, {DIR_N} }, // 23 In Front of Terminal 1 + { 22, 58, 0, {DIR_N} }, // 24 In Front of Terminal 2 + { 22, 38, 0, {DIR_N} }, // 25 In Front of Terminal 3 + { 22, 22, AMED_EXACTPOS, {DIR_NW} }, // 26 Going for Takeoff + { 22, 6, 0, {DIR_N} }, // 27 On Runway-out, prepare for takeoff + { 3, 6, AMED_EXACTPOS, {DIR_SW} }, // 28 Accelerate to end of runway + { 60, 6, AMED_NOSPDCLAMP, {DIR_N} }, // 29 Release control of runway, for smoother movement + { 105, 6, AMED_NOSPDCLAMP, {DIR_N} }, // 30 End of runway + { 190, 6, AMED_NOSPDCLAMP | AMED_TAKEOFF, {DIR_N} }, // 31 Take off + { 193, 104, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 32 Fly to landing position in air + { 105, 104, AMED_NOSPDCLAMP | AMED_LAND, {DIR_N} }, // 33 Going down for land + { 3, 104, AMED_NOSPDCLAMP | AMED_BRAKE, {DIR_N} }, // 34 Just landed, brake until end of runway + { 12, 104, 0, {DIR_N} }, // 35 Just landed, turn around and taxi 1 square + { 7, 84, 0, {DIR_N} }, // 36 Taxi from runway to crossing + { -31, 209, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 37 Fly around waiting for a landing spot (north-east) + { 1, 6, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 38 Fly around waiting for a landing spot (north-west) + { 273, 6, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 39 Fly around waiting for a landing spot (south-west) + { 305, 81, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 40 Fly around waiting for a landing spot (south) // Helicopter - { 128, 80, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 41 Bufferspace before helipad - { 128, 80, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 42 Bufferspace before helipad - { 96, 71, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 43 Get in position for Helipad1 - { 96, 55, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 44 Get in position for Helipad2 - { 96, 71, AMED_HELI_LOWER, 0 }, // 45 Land at Helipad1 - { 96, 55, AMED_HELI_LOWER, 0 }, // 46 Land at Helipad2 - { 104, 71, AMED_HELI_RAISE, 0 }, // 47 Takeoff Helipad1 - { 104, 55, AMED_HELI_RAISE, 0 }, // 48 Takeoff Helipad2 - { 104, 32, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 49 Go to position for Hangarentrance in air - { 104, 32, AMED_HELI_LOWER, 0} // 50 Land in HANGAR2_AREA to go to hangar + { 128, 80, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 41 Bufferspace before helipad + { 128, 80, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 42 Bufferspace before helipad + { 96, 71, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 43 Get in position for Helipad1 + { 96, 55, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 44 Get in position for Helipad2 + { 96, 71, AMED_HELI_LOWER, {DIR_N} }, // 45 Land at Helipad1 + { 96, 55, AMED_HELI_LOWER, {DIR_N} }, // 46 Land at Helipad2 + { 104, 71, AMED_HELI_RAISE, {DIR_N} }, // 47 Takeoff Helipad1 + { 104, 55, AMED_HELI_RAISE, {DIR_N} }, // 48 Takeoff Helipad2 + { 104, 32, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 49 Go to position for Hangarentrance in air + { 104, 32, AMED_HELI_LOWER, {DIR_N} }, // 50 Land in HANGAR2_AREA to go to hangar }; // Intercontinental Airport - 4 runways, 8 terminals, 2 dedicated helipads static const AirportMovingData _airport_moving_data_intercontinental[77] = { - { 7, 87, AMED_EXACTPOS, 3 }, // 00 In Hangar 1 - { 135, 72, AMED_EXACTPOS, 3 }, // 01 In Hangar 2 - { 7, 104, 0, 0 }, // 02 Taxi to right outside depot 1 - { 135, 88, 0, 0 }, // 03 Taxi to right outside depot 2 - { 56, 120, AMED_EXACTPOS, 6 }, // 04 Terminal 1 - { 56, 104, AMED_EXACTPOS, 5 }, // 05 Terminal 2 - { 56, 88, AMED_EXACTPOS, 5 }, // 06 Terminal 3 - { 56, 72, AMED_EXACTPOS, 5 }, // 07 Terminal 4 - { 88, 120, AMED_EXACTPOS, 0 }, // 08 Terminal 5 - { 88, 104, AMED_EXACTPOS, 1 }, // 09 Terminal 6 - { 88, 88, AMED_EXACTPOS, 1 }, // 10 Terminal 7 - { 88, 72, AMED_EXACTPOS, 1 }, // 11 Terminal 8 - { 88, 56, AMED_EXACTPOS, 3 }, // 12 Helipad 1 - { 72, 56, AMED_EXACTPOS, 1 }, // 13 Helipad 2 - { 40, 136, 0, 0 }, // 14 Term group 2 enter 1 a - { 56, 136, 0, 0 }, // 15 Term group 2 enter 1 b - { 88, 136, 0, 0 }, // 16 Term group 2 enter 2 a - { 104, 136, 0, 0 }, // 17 Term group 2 enter 2 b - { 104, 120, 0, 0 }, // 18 Term group 2 - opp term 5 - { 104, 104, 0, 0 }, // 19 Term group 2 - opp term 6 & exit2 - { 104, 88, 0, 0 }, // 20 Term group 2 - opp term 7 & hangar area 2 - { 104, 72, 0, 0 }, // 21 Term group 2 - opp term 8 - { 104, 56, 0, 0 }, // 22 Taxi Term group 2 exit a - { 104, 40, 0, 0 }, // 23 Taxi Term group 2 exit b - { 56, 40, 0, 0 }, // 24 Term group 2 exit 2a - { 40, 40, 0, 0 }, // 25 Term group 2 exit 2b - { 40, 120, 0, 0 }, // 26 Term group 1 - opp term 1 - { 40, 104, 0, 0 }, // 27 Term group 1 - opp term 2 & hangar area 1 - { 40, 88, 0, 0 }, // 28 Term group 1 - opp term 3 - { 40, 72, 0, 0 }, // 29 Term group 1 - opp term 4 - { 18, 72, 0, 7 }, // 30 Outway 1 - { 8, 40, 0, 7 }, // 31 Airport OUTWAY - { 8, 24, AMED_EXACTPOS, 5 }, // 32 Accelerate to end of runway - { 119, 24, AMED_NOSPDCLAMP, 0 }, // 33 Release control of runway, for smoother movement - { 117, 24, AMED_NOSPDCLAMP, 0 }, // 34 End of runway - { 197, 24, AMED_NOSPDCLAMP | AMED_TAKEOFF, 0 }, // 35 Take off - { 254, 84, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 36 Flying to landing position in air - { 117, 168, AMED_NOSPDCLAMP | AMED_LAND, 0 }, // 37 Going down for land - { 3, 168, AMED_NOSPDCLAMP | AMED_BRAKE, 0 }, // 38 Just landed, brake until end of runway - { 8, 168, 0, 0 }, // 39 Just landed, turn around and taxi - { 8, 144, 0, 7 }, // 40 Taxi from runway - { 8, 128, 0, 7 }, // 41 Taxi from runway - { 8, 120, AMED_EXACTPOS, 5 }, // 42 Airport entrance - { 56, 344, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 43 Fly around waiting for a landing spot (north-east) - { -200, 88, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 44 Fly around waiting for a landing spot (north-west) - { 56, -168, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 45 Fly around waiting for a landing spot (south-west) - { 312, 88, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 46 Fly around waiting for a landing spot (south) + { 7, 87, AMED_EXACTPOS, {DIR_SE} }, // 00 In Hangar 1 + { 135, 72, AMED_EXACTPOS, {DIR_SE} }, // 01 In Hangar 2 + { 7, 104, 0, {DIR_N} }, // 02 Taxi to right outside depot 1 + { 135, 88, 0, {DIR_N} }, // 03 Taxi to right outside depot 2 + { 56, 120, AMED_EXACTPOS, {DIR_W} }, // 04 Terminal 1 + { 56, 104, AMED_EXACTPOS, {DIR_SW} }, // 05 Terminal 2 + { 56, 88, AMED_EXACTPOS, {DIR_SW} }, // 06 Terminal 3 + { 56, 72, AMED_EXACTPOS, {DIR_SW} }, // 07 Terminal 4 + { 88, 120, AMED_EXACTPOS, {DIR_N} }, // 08 Terminal 5 + { 88, 104, AMED_EXACTPOS, {DIR_NE} }, // 09 Terminal 6 + { 88, 88, AMED_EXACTPOS, {DIR_NE} }, // 10 Terminal 7 + { 88, 72, AMED_EXACTPOS, {DIR_NE} }, // 11 Terminal 8 + { 88, 56, AMED_EXACTPOS, {DIR_SE} }, // 12 Helipad 1 + { 72, 56, AMED_EXACTPOS, {DIR_NE} }, // 13 Helipad 2 + { 40, 136, 0, {DIR_N} }, // 14 Term group 2 enter 1 a + { 56, 136, 0, {DIR_N} }, // 15 Term group 2 enter 1 b + { 88, 136, 0, {DIR_N} }, // 16 Term group 2 enter 2 a + { 104, 136, 0, {DIR_N} }, // 17 Term group 2 enter 2 b + { 104, 120, 0, {DIR_N} }, // 18 Term group 2 - opp term 5 + { 104, 104, 0, {DIR_N} }, // 19 Term group 2 - opp term 6 & exit2 + { 104, 88, 0, {DIR_N} }, // 20 Term group 2 - opp term 7 & hangar area 2 + { 104, 72, 0, {DIR_N} }, // 21 Term group 2 - opp term 8 + { 104, 56, 0, {DIR_N} }, // 22 Taxi Term group 2 exit a + { 104, 40, 0, {DIR_N} }, // 23 Taxi Term group 2 exit b + { 56, 40, 0, {DIR_N} }, // 24 Term group 2 exit 2a + { 40, 40, 0, {DIR_N} }, // 25 Term group 2 exit 2b + { 40, 120, 0, {DIR_N} }, // 26 Term group 1 - opp term 1 + { 40, 104, 0, {DIR_N} }, // 27 Term group 1 - opp term 2 & hangar area 1 + { 40, 88, 0, {DIR_N} }, // 28 Term group 1 - opp term 3 + { 40, 72, 0, {DIR_N} }, // 29 Term group 1 - opp term 4 + { 18, 72, 0, {DIR_NW} }, // 30 Outway 1 + { 8, 40, 0, {DIR_NW} }, // 31 Airport OUTWAY + { 8, 24, AMED_EXACTPOS, {DIR_SW} }, // 32 Accelerate to end of runway + { 119, 24, AMED_NOSPDCLAMP, {DIR_N} }, // 33 Release control of runway, for smoother movement + { 117, 24, AMED_NOSPDCLAMP, {DIR_N} }, // 34 End of runway + { 197, 24, AMED_NOSPDCLAMP | AMED_TAKEOFF, {DIR_N} }, // 35 Take off + { 254, 84, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 36 Flying to landing position in air + { 117, 168, AMED_NOSPDCLAMP | AMED_LAND, {DIR_N} }, // 37 Going down for land + { 3, 168, AMED_NOSPDCLAMP | AMED_BRAKE, {DIR_N} }, // 38 Just landed, brake until end of runway + { 8, 168, 0, {DIR_N} }, // 39 Just landed, turn around and taxi + { 8, 144, 0, {DIR_NW} }, // 40 Taxi from runway + { 8, 128, 0, {DIR_NW} }, // 41 Taxi from runway + { 8, 120, AMED_EXACTPOS, {DIR_SW} }, // 42 Airport entrance + { 56, 344, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 43 Fly around waiting for a landing spot (north-east) + { -200, 88, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 44 Fly around waiting for a landing spot (north-west) + { 56, -168, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 45 Fly around waiting for a landing spot (south-west) + { 312, 88, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 46 Fly around waiting for a landing spot (south) // Helicopter - { 96, 40, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 47 Bufferspace before helipad - { 96, 40, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 48 Bufferspace before helipad - { 82, 54, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 49 Get in position for Helipad1 - { 64, 56, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 50 Get in position for Helipad2 - { 81, 55, AMED_HELI_LOWER, 0 }, // 51 Land at Helipad1 - { 64, 56, AMED_HELI_LOWER, 0 }, // 52 Land at Helipad2 - { 80, 56, AMED_HELI_RAISE, 0 }, // 53 Takeoff Helipad1 - { 64, 56, AMED_HELI_RAISE, 0 }, // 54 Takeoff Helipad2 - { 136, 96, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 55 Go to position for Hangarentrance in air - { 136, 96, AMED_HELI_LOWER, 0 }, // 56 Land in front of hangar2 - { 126, 104, 0, 3 }, // 57 Outway 2 - { 136, 136, 0, 1 }, // 58 Airport OUTWAY 2 - { 136, 152, AMED_EXACTPOS, 5 }, // 59 Accelerate to end of runway2 - { 16, 152, AMED_NOSPDCLAMP, 0 }, // 60 Release control of runway2, for smoother movement - { 20, 152, AMED_NOSPDCLAMP, 0 }, // 61 End of runway2 - { -56, 152, AMED_NOSPDCLAMP | AMED_TAKEOFF, 0 }, // 62 Take off2 - { 24, 8, AMED_NOSPDCLAMP | AMED_LAND, 0 }, // 63 Going down for land2 - { 136, 8, AMED_NOSPDCLAMP | AMED_BRAKE, 0 }, // 64 Just landed, brake until end of runway2in - { 136, 8, 0, 0 }, // 65 Just landed, turn around and taxi - { 136, 24, 0, 3 }, // 66 Taxi from runway 2in - { 136, 40, 0, 3 }, // 67 Taxi from runway 2in - { 136, 56, AMED_EXACTPOS, 1 }, // 68 Airport entrance2 - { -56, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 69 Fly to landing position in air2 - { 88, 40, 0, 0 }, // 70 Taxi Term group 2 exit - opp heli1 - { 72, 40, 0, 0 }, // 71 Taxi Term group 2 exit - opp heli2 - { 88, 57, AMED_EXACTPOS, 3 }, // 72 pre-helitakeoff helipad 1 - { 71, 56, AMED_EXACTPOS, 1 }, // 73 pre-helitakeoff helipad 2 - { 8, 120, AMED_HELI_RAISE, 0 }, // 74 Helitakeoff outside depot 1 - { 136, 104, AMED_HELI_RAISE, 0 }, // 75 Helitakeoff outside depot 2 - { 197, 168, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0} // 76 Fly to landing position in air1 + { 96, 40, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 47 Bufferspace before helipad + { 96, 40, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 48 Bufferspace before helipad + { 82, 54, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 49 Get in position for Helipad1 + { 64, 56, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 50 Get in position for Helipad2 + { 81, 55, AMED_HELI_LOWER, {DIR_N} }, // 51 Land at Helipad1 + { 64, 56, AMED_HELI_LOWER, {DIR_N} }, // 52 Land at Helipad2 + { 80, 56, AMED_HELI_RAISE, {DIR_N} }, // 53 Takeoff Helipad1 + { 64, 56, AMED_HELI_RAISE, {DIR_N} }, // 54 Takeoff Helipad2 + { 136, 96, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 55 Go to position for Hangarentrance in air + { 136, 96, AMED_HELI_LOWER, {DIR_N} }, // 56 Land in front of hangar2 + { 126, 104, 0, {DIR_SE} }, // 57 Outway 2 + { 136, 136, 0, {DIR_NE} }, // 58 Airport OUTWAY 2 + { 136, 152, AMED_EXACTPOS, {DIR_SW} }, // 59 Accelerate to end of runway2 + { 16, 152, AMED_NOSPDCLAMP, {DIR_N} }, // 60 Release control of runway2, for smoother movement + { 20, 152, AMED_NOSPDCLAMP, {DIR_N} }, // 61 End of runway2 + { -56, 152, AMED_NOSPDCLAMP | AMED_TAKEOFF, {DIR_N} }, // 62 Take off2 + { 24, 8, AMED_NOSPDCLAMP | AMED_LAND, {DIR_N} }, // 63 Going down for land2 + { 136, 8, AMED_NOSPDCLAMP | AMED_BRAKE, {DIR_N} }, // 64 Just landed, brake until end of runway2in + { 136, 8, 0, {DIR_N} }, // 65 Just landed, turn around and taxi + { 136, 24, 0, {DIR_SE} }, // 66 Taxi from runway 2in + { 136, 40, 0, {DIR_SE} }, // 67 Taxi from runway 2in + { 136, 56, AMED_EXACTPOS, {DIR_NE} }, // 68 Airport entrance2 + { -56, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 69 Fly to landing position in air2 + { 88, 40, 0, {DIR_N} }, // 70 Taxi Term group 2 exit - opp heli1 + { 72, 40, 0, {DIR_N} }, // 71 Taxi Term group 2 exit - opp heli2 + { 88, 57, AMED_EXACTPOS, {DIR_SE} }, // 72 pre-helitakeoff helipad 1 + { 71, 56, AMED_EXACTPOS, {DIR_NE} }, // 73 pre-helitakeoff helipad 2 + { 8, 120, AMED_HELI_RAISE, {DIR_N} }, // 74 Helitakeoff outside depot 1 + { 136, 104, AMED_HELI_RAISE, {DIR_N} }, // 75 Helitakeoff outside depot 2 + { 197, 168, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 76 Fly to landing position in air1 }; // Heliport (heliport) static const AirportMovingData _airport_moving_data_heliport[9] = { - { 5, 9, AMED_EXACTPOS, 1 }, // 0 - At heliport terminal - { 2, 9, AMED_HELI_RAISE, 0 }, // 1 - Take off (play sound) - { -3, 9, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 2 - In position above landing spot helicopter - { -3, 9, AMED_HELI_LOWER, 0 }, // 3 - Land - { 2, 9, 0, 0 }, // 4 - Goto terminal on ground - { -31, 59, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 5 - Circle #1 (north-east) - { -31, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 6 - Circle #2 (north-west) - { 49, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 7 - Circle #3 (south-west) - { 70, 9, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 8 - Circle #4 (south) + { 5, 9, AMED_EXACTPOS, {DIR_NE} }, // 0 - At heliport terminal + { 2, 9, AMED_HELI_RAISE, {DIR_N} }, // 1 - Take off (play sound) + { -3, 9, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 2 - In position above landing spot helicopter + { -3, 9, AMED_HELI_LOWER, {DIR_N} }, // 3 - Land + { 2, 9, 0, {DIR_N} }, // 4 - Goto terminal on ground + { -31, 59, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 5 - Circle #1 (north-east) + { -31, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 6 - Circle #2 (north-west) + { 49, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 7 - Circle #3 (south-west) + { 70, 9, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 8 - Circle #4 (south) }; // HeliDepot 2x2 (heliport) static const AirportMovingData _airport_moving_data_helidepot[18] = { - { 24, 4, AMED_EXACTPOS, 1 }, // 0 - At depot - { 24, 28, 0, 0 }, // 1 Taxi to right outside depot - { 5, 38, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 2 Flying - { -15, -15, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 3 - Circle #1 (north-east) - { -15, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 4 - Circle #2 (north-west) - { 49, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 5 - Circle #3 (south-west) - { 49, -15, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 6 - Circle #4 (south-east) - { 8, 32, AMED_NOSPDCLAMP | AMED_SLOWTURN, 7 }, // 7 - PreHelipad - { 8, 32, AMED_NOSPDCLAMP | AMED_SLOWTURN, 7 }, // 8 - Helipad - { 8, 16, AMED_NOSPDCLAMP | AMED_SLOWTURN, 7 }, // 9 - Land - { 8, 16, AMED_HELI_LOWER, 7 }, // 10 - Land - { 8, 24, AMED_HELI_RAISE, 0 }, // 11 - Take off (play sound) - { 32, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 7 }, // 12 Air to above hangar area - { 32, 24, AMED_HELI_LOWER, 7 }, // 13 Taxi to right outside depot - { 8, 24, AMED_EXACTPOS, 7 }, // 14 - on helipad1 - { 24, 28, AMED_HELI_RAISE, 0 }, // 15 Takeoff right outside depot - { 8, 24, AMED_HELI_RAISE, 5 }, // 16 - Take off (play sound) - { 8, 24, AMED_SLOWTURN | AMED_EXACTPOS, 2 }, // 17 - turn on helipad1 for takeoff + { 24, 4, AMED_EXACTPOS, {DIR_NE} }, // 0 - At depot + { 24, 28, 0, {DIR_N} }, // 1 Taxi to right outside depot + { 5, 38, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 2 Flying + { -15, -15, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 3 - Circle #1 (north-east) + { -15, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 4 - Circle #2 (north-west) + { 49, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 5 - Circle #3 (south-west) + { 49, -15, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 6 - Circle #4 (south-east) + { 8, 32, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NW} }, // 7 - PreHelipad + { 8, 32, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NW} }, // 8 - Helipad + { 8, 16, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NW} }, // 9 - Land + { 8, 16, AMED_HELI_LOWER, {DIR_NW} }, // 10 - Land + { 8, 24, AMED_HELI_RAISE, {DIR_N} }, // 11 - Take off (play sound) + { 32, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NW} }, // 12 Air to above hangar area + { 32, 24, AMED_HELI_LOWER, {DIR_NW} }, // 13 Taxi to right outside depot + { 8, 24, AMED_EXACTPOS, {DIR_NW} }, // 14 - on helipad1 + { 24, 28, AMED_HELI_RAISE, {DIR_N} }, // 15 Takeoff right outside depot + { 8, 24, AMED_HELI_RAISE, {DIR_SW} }, // 16 - Take off (play sound) + { 8, 24, AMED_SLOWTURN | AMED_EXACTPOS, {DIR_E} }, // 17 - turn on helipad1 for takeoff }; // HeliDepot 2x2 (heliport) static const AirportMovingData _airport_moving_data_helistation[33] = { - { 8, 3, AMED_EXACTPOS, 3 }, // 00 In Hangar2 - { 8, 22, 0, 0 }, // 01 outside hangar 2 - { 116, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 02 Fly to landing position in air - { 14, 22, AMED_HELI_RAISE, 0 }, // 03 Helitakeoff outside hangar1(play sound) - { 24, 22, 0, 0 }, // 04 taxiing - { 40, 22, 0, 0 }, // 05 taxiing - { 40, 8, AMED_EXACTPOS, 1 }, // 06 Helipad 1 - { 56, 8, AMED_EXACTPOS, 1 }, // 07 Helipad 2 - { 56, 24, AMED_EXACTPOS, 1 }, // 08 Helipad 3 - { 40, 8, AMED_EXACTPOS, 0 }, // 09 pre-helitakeoff helipad 1 - { 56, 8, AMED_EXACTPOS, 0 }, // 10 pre-helitakeoff helipad 2 - { 56, 24, AMED_EXACTPOS, 0 }, // 11 pre-helitakeoff helipad 3 - { 32, 8, AMED_HELI_RAISE, 0 }, // 12 Takeoff Helipad1 - { 48, 8, AMED_HELI_RAISE, 0 }, // 13 Takeoff Helipad2 - { 48, 24, AMED_HELI_RAISE, 0 }, // 14 Takeoff Helipad3 - { 84, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 15 Bufferspace before helipad - { 68, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 16 Bufferspace before helipad - { 32, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 17 Get in position for Helipad1 - { 48, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 18 Get in position for Helipad2 - { 48, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 1 }, // 19 Get in position for Helipad3 - { 40, 8, AMED_HELI_LOWER, 0 }, // 20 Land at Helipad1 - { 48, 8, AMED_HELI_LOWER, 0 }, // 21 Land at Helipad2 - { 48, 24, AMED_HELI_LOWER, 0 }, // 22 Land at Helipad3 - { 0, 22, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 23 Go to position for Hangarentrance in air - { 0, 22, AMED_HELI_LOWER, 0 }, // 24 Land in front of hangar - { 148, -8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 25 Fly around waiting for a landing spot (south-east) - { 148, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 26 Fly around waiting for a landing spot (south-west) - { 132, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 27 Fly around waiting for a landing spot (south-west) - { 100, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 28 Fly around waiting for a landing spot (north-east) - { 84, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 29 Fly around waiting for a landing spot (south-east) - { 84, -8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 30 Fly around waiting for a landing spot (south-west) - { 100, -24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 31 Fly around waiting for a landing spot (north-west) - { 132, -24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 32 Fly around waiting for a landing spot (north-east) + { 8, 3, AMED_EXACTPOS, {DIR_SE} }, // 00 In Hangar2 + { 8, 22, 0, {DIR_N} }, // 01 outside hangar 2 + { 116, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 02 Fly to landing position in air + { 14, 22, AMED_HELI_RAISE, {DIR_N} }, // 03 Helitakeoff outside hangar1(play sound) + { 24, 22, 0, {DIR_N} }, // 04 taxiing + { 40, 22, 0, {DIR_N} }, // 05 taxiing + { 40, 8, AMED_EXACTPOS, {DIR_NE} }, // 06 Helipad 1 + { 56, 8, AMED_EXACTPOS, {DIR_NE} }, // 07 Helipad 2 + { 56, 24, AMED_EXACTPOS, {DIR_NE} }, // 08 Helipad 3 + { 40, 8, AMED_EXACTPOS, {DIR_N} }, // 09 pre-helitakeoff helipad 1 + { 56, 8, AMED_EXACTPOS, {DIR_N} }, // 10 pre-helitakeoff helipad 2 + { 56, 24, AMED_EXACTPOS, {DIR_N} }, // 11 pre-helitakeoff helipad 3 + { 32, 8, AMED_HELI_RAISE, {DIR_N} }, // 12 Takeoff Helipad1 + { 48, 8, AMED_HELI_RAISE, {DIR_N} }, // 13 Takeoff Helipad2 + { 48, 24, AMED_HELI_RAISE, {DIR_N} }, // 14 Takeoff Helipad3 + { 84, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 15 Bufferspace before helipad + { 68, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 16 Bufferspace before helipad + { 32, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 17 Get in position for Helipad1 + { 48, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 18 Get in position for Helipad2 + { 48, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NE} }, // 19 Get in position for Helipad3 + { 40, 8, AMED_HELI_LOWER, {DIR_N} }, // 20 Land at Helipad1 + { 48, 8, AMED_HELI_LOWER, {DIR_N} }, // 21 Land at Helipad2 + { 48, 24, AMED_HELI_LOWER, {DIR_N} }, // 22 Land at Helipad3 + { 0, 22, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 23 Go to position for Hangarentrance in air + { 0, 22, AMED_HELI_LOWER, {DIR_N} }, // 24 Land in front of hangar + { 148, -8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 25 Fly around waiting for a landing spot (south-east) + { 148, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 26 Fly around waiting for a landing spot (south-west) + { 132, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 27 Fly around waiting for a landing spot (south-west) + { 100, 24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 28 Fly around waiting for a landing spot (north-east) + { 84, 8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 29 Fly around waiting for a landing spot (south-east) + { 84, -8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 30 Fly around waiting for a landing spot (south-west) + { 100, -24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 31 Fly around waiting for a landing spot (north-west) + { 132, -24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 32 Fly around waiting for a landing spot (north-east) }; // Oilrig static const AirportMovingData _airport_moving_data_oilrig[9] = { - { 31, 9, AMED_EXACTPOS, 1 }, // 0 - At oilrig terminal - { 28, 9, AMED_HELI_RAISE, 0 }, // 1 - Take off (play sound) - { 23, 9, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 2 - In position above landing spot helicopter - { 23, 9, AMED_HELI_LOWER, 0 }, // 3 - Land - { 28, 9, 0, 0 }, // 4 - Goto terminal on ground - { -31, 69, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 5 - circle #1 (north-east) - { -31, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 6 - circle #2 (north-west) - { 69, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 7 - circle #3 (south-west) - { 70, 9, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 8 - circle #4 (south) + { 31, 9, AMED_EXACTPOS, {DIR_NE} }, // 0 - At oilrig terminal + { 28, 9, AMED_HELI_RAISE, {DIR_N} }, // 1 - Take off (play sound) + { 23, 9, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 2 - In position above landing spot helicopter + { 23, 9, AMED_HELI_LOWER, {DIR_N} }, // 3 - Land + { 28, 9, 0, {DIR_N} }, // 4 - Goto terminal on ground + { -31, 69, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 5 - circle #1 (north-east) + { -31, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 6 - circle #2 (north-west) + { 69, -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 7 - circle #3 (south-west) + { 70, 9, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 8 - circle #4 (south) }; /////////////////////////////////////////////////////////////////////// diff --git a/src/aystar.cpp b/src/aystar.cpp index 0000d584c..36260d4f3 100644 --- a/src/aystar.cpp +++ b/src/aystar.cpp @@ -19,6 +19,7 @@ #include "stdafx.h" #include "openttd.h" #include "aystar.h" +#include "helpers.hpp" int _aystar_stats_open_size; int _aystar_stats_closed_size; @@ -35,7 +36,8 @@ static PathNode* AyStarMain_ClosedList_IsInList(AyStar *aystar, const AyStarNode static void AyStarMain_ClosedList_Add(AyStar *aystar, const PathNode *node) { // Add a node to the ClosedList - PathNode *new_node = malloc(sizeof(*new_node)); + PathNode *new_node; + MallocT(&new_node, 1); *new_node = *node; Hash_Set(&aystar->ClosedListHash, node->node.tile, node->node.direction, new_node); } @@ -66,7 +68,8 @@ static OpenListNode *AyStarMain_OpenList_Pop(AyStar *aystar) static void AyStarMain_OpenList_Add(AyStar *aystar, PathNode *parent, const AyStarNode *node, int f, int g) { // Add a new Node to the OpenList - OpenListNode *new_node = malloc(sizeof(*new_node)); + OpenListNode *new_node; + MallocT(&new_node, 1); new_node->g = g; new_node->path.parent = parent; new_node->path.node = *node; diff --git a/src/aystar.h b/src/aystar.h index 4920a37d4..f00da20b1 100644 --- a/src/aystar.h +++ b/src/aystar.h @@ -30,7 +30,7 @@ enum{ typedef struct AyStarNode AyStarNode; struct AyStarNode { TileIndex tile; - uint direction; + int direction; uint user_data[2]; }; diff --git a/src/bmp.cpp b/src/bmp.cpp index c2bd91270..e9a882021 100644 --- a/src/bmp.cpp +++ b/src/bmp.cpp @@ -5,6 +5,7 @@ #include "gfx.h" #include "bmp.h" #include "macros.h" +#include "helpers.hpp" void BmpInitializeBuffer(BmpBuffer *buffer, FILE *file) { buffer->pos = -1; @@ -328,7 +329,7 @@ bool BmpReadHeader(BmpBuffer *buffer, BmpInfo *info, BmpData *data) } if (info->palette_size == 0) info->palette_size = 1 << info->bpp; - data->palette = calloc(info->palette_size, sizeof(*(data->palette))); + CallocT(&data->palette, info->palette_size); if (data->palette == NULL) return false; for (i = 0; i < info->palette_size; i++) { @@ -350,7 +351,7 @@ bool BmpReadBitmap(BmpBuffer *buffer, BmpInfo *info, BmpData *data) { assert(info != NULL && data != NULL); - data->bitmap = calloc(info->width * info->height, ((info->bpp == 24) ? 3 : 1) * sizeof(byte)); + data->bitmap = (byte*)calloc(info->width * info->height, ((info->bpp == 24) ? 3 : 1) * sizeof(byte)); if (data->bitmap == NULL) return false; /* Load image */ diff --git a/src/bridge_map.cpp b/src/bridge_map.cpp index 8e2405ea3..416e603c5 100644 --- a/src/bridge_map.cpp +++ b/src/bridge_map.cpp @@ -40,7 +40,7 @@ TileIndex GetOtherBridgeEnd(TileIndex tile) uint GetBridgeHeight(TileIndex t) { uint h; - uint tileh = GetTileSlope(t, &h); + Slope tileh = GetTileSlope(t, &h); uint f = GetBridgeFoundation(tileh, DiagDirToAxis(GetBridgeRampDirection(t))); // one height level extra if the ramp is on a flat foundation diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp index b293b516c..6c0632564 100644 --- a/src/build_vehicle_gui.cpp +++ b/src/build_vehicle_gui.cpp @@ -302,6 +302,8 @@ static void GenerateBuildAircraftList(Window *w) break; case ALL: break; + default: + NOT_REACHED(); } EngList_Add(&bv->eng_list, eid); @@ -479,7 +481,7 @@ void ShowBuildVehicleWindow(TileIndex tile, byte type) switch (type) { case VEH_Aircraft: { - byte acc_planes = (tile == 0) ? ALL : GetAirport(GetStationByTile(tile)->airport_type)->acc_planes; + AcceptPlanes acc_planes = (tile == 0) ? ALL : GetAirport(GetStationByTile(tile)->airport_type)->acc_planes; bv->filter.acc_planes = acc_planes; break; } diff --git a/src/clear_cmd.cpp b/src/clear_cmd.cpp index 4d1a78ba9..08f5873b5 100644 --- a/src/clear_cmd.cpp +++ b/src/clear_cmd.cpp @@ -548,7 +548,7 @@ static void DrawTile_Clear(TileInfo *ti) static uint GetSlopeZ_Clear(TileIndex tile, uint x, uint y) { uint z; - uint tileh = GetTileSlope(tile, &z); + Slope tileh = GetTileSlope(tile, &z); return z + GetPartialZ(x & 0xF, y & 0xF, tileh); } @@ -786,7 +786,7 @@ void InitializeClearLand(void) _opt.snow_line = _patches.snow_line_height * TILE_HEIGHT; } -const TileTypeProcs _tile_type_clear_procs = { +extern const TileTypeProcs _tile_type_clear_procs = { DrawTile_Clear, /* draw_tile_proc */ GetSlopeZ_Clear, /* get_slope_z_proc */ ClearTile_Clear, /* clear_tile_proc */ diff --git a/src/clear_map.h b/src/clear_map.h index 85c52a1a7..dd7a15061 100644 --- a/src/clear_map.h +++ b/src/clear_map.h @@ -23,7 +23,7 @@ typedef enum ClearGround { static inline ClearGround GetClearGround(TileIndex t) { assert(IsTileType(t, MP_CLEAR)); - return GB(_m[t].m5, 2, 3); + return (ClearGround)GB(_m[t].m5, 2, 3); } static inline bool IsClearGround(TileIndex t, ClearGround ct) diff --git a/src/command.cpp b/src/command.cpp index ad93fc643..942da930a 100644 --- a/src/command.cpp +++ b/src/command.cpp @@ -504,7 +504,7 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback, */ if (_networking && !(cmd & CMD_NETWORK_COMMAND)) { PlayerID pbck = _local_player; - if (_network_dedicated || (_network_server && pbck == PLAYER_SPECTATOR)) _local_player = 0; + if (_network_dedicated || (_network_server && pbck == PLAYER_SPECTATOR)) _local_player = PLAYER_FIRST; NetworkSend_Command(tile, p1, p2, cmd, callback); if (_network_dedicated || (_network_server && pbck == PLAYER_SPECTATOR)) _local_player = pbck; _docommand_recursive = 0; diff --git a/src/console.cpp b/src/console.cpp index 07d218130..cf192fb33 100644 --- a/src/console.cpp +++ b/src/console.cpp @@ -13,6 +13,7 @@ #include <stdarg.h> #include <string.h> #include "console.h" +#include "helpers.hpp" #include "network/network.h" #include "network/network_data.h" #include "network/network_server.h" @@ -223,7 +224,7 @@ void IConsoleInit(void) memset(_iconsole_history, 0, sizeof(_iconsole_history)); memset(_iconsole_buffer, 0, sizeof(_iconsole_buffer)); memset(_iconsole_cbuffer, 0, sizeof(_iconsole_cbuffer)); - _iconsole_cmdline.buf = calloc(ICON_CMDLN_SIZE, sizeof(*_iconsole_cmdline.buf)); // create buffer and zero it + CallocT(&_iconsole_cmdline.buf, ICON_CMDLN_SIZE); // create buffer and zero it _iconsole_cmdline.maxlength = ICON_CMDLN_SIZE; IConsolePrintF(13, "OpenTTD Game Console Revision 7 - %s", _openttd_revision); @@ -612,7 +613,8 @@ void IConsoleVarHookAdd(const char *name, IConsoleHookTypes type, IConsoleHook * void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc) { char *new_cmd = strdup(name); - IConsoleCmd *item_new = malloc(sizeof(IConsoleCmd)); + IConsoleCmd *item_new; + MallocT(&item_new, 1); item_new->next = NULL; item_new->proc = proc; @@ -649,7 +651,8 @@ void IConsoleAliasRegister(const char *name, const char *cmd) { char *new_alias = strdup(name); char *cmd_aliased = strdup(cmd); - IConsoleAlias *item_new = malloc(sizeof(IConsoleAlias)); + IConsoleAlias *item_new; + MallocT(&item_new, 1); item_new->next = NULL; item_new->cmdline = cmd_aliased; @@ -784,7 +787,8 @@ void IConsoleVarStringRegister(const char *name, void *addr, uint32 size, const void IConsoleVarRegister(const char *name, void *addr, IConsoleVarTypes type, const char *help) { char *new_cmd = strdup(name); - IConsoleVar *item_new = malloc(sizeof(IConsoleVar)); + IConsoleVar *item_new; + MallocT(&item_new, 1); item_new->help = (help != NULL) ? strdup(help) : NULL; @@ -861,7 +865,7 @@ static void IConsoleVarSetStringvalue(const IConsoleVar *var, const char *value) if (var->type != ICONSOLE_VAR_STRING || var->addr == NULL) return; IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_PRE_ACTION); - ttd_strlcpy(var->addr, value, var->size); + ttd_strlcpy((char*)var->addr, value, var->size); IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_POST_ACTION); IConsoleVarPrintSetValue(var); // print out the new value, giving feedback return; diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index 46846af7d..8f495e32b 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -562,7 +562,7 @@ DEF_CONSOLE_CMD(ConStatus) const NetworkClientInfo *ci = DEREF_CLIENT_INFO(cs); const char* status; - status = (cs->status < lengthof(stat_str) ? stat_str[cs->status] : "unknown"); + status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown"); IConsolePrintF(8, "Client #%1d name: '%s' status: '%s' frame-lag: %3d company: %1d IP: %s unique-id: '%s'", cs->index, ci->client_name, status, lag, ci->client_playas + (IsValidPlayer(ci->client_playas) ? 1 : 0), @@ -684,7 +684,7 @@ DEF_CONSOLE_CMD(ConResetCompany) if (argc != 2) return false; - index = atoi(argv[1]) - 1; + index = (PlayerID)(atoi(argv[1]) - 1); /* Check valid range */ if (!IsValidPlayer(index)) { @@ -770,7 +770,7 @@ DEF_CONSOLE_CMD(ConNetworkConnect) IConsolePrintF(_icolour_def, "Connecting to %s...", ip); if (player != NULL) { - _network_playas = atoi(player); + _network_playas = (PlayerID)atoi(player); IConsolePrintF(_icolour_def, " player-no: %d", _network_playas); /* From a user pov 0 is a new player, internally it's different and all diff --git a/src/debug.h b/src/debug.h index c99795ddd..ff0761a8d 100644 --- a/src/debug.h +++ b/src/debug.h @@ -3,6 +3,10 @@ #ifndef DEBUG_H #define DEBUG_H +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + /* Debugging messages policy: * These should be the severities used for direct DEBUG() calls * maximum debugging level should be 10 if really deep, deep @@ -105,4 +109,8 @@ const char *GetDebugString(void); }\ } +#ifdef __cplusplus +} +#endif //__cplusplus + #endif /* DEBUG_H */ diff --git a/src/depot.cpp b/src/depot.cpp index 49fdfa21c..889d2a35c 100644 --- a/src/depot.cpp +++ b/src/depot.cpp @@ -122,6 +122,6 @@ static void Load_DEPT(void) } } -const ChunkHandler _depot_chunk_handlers[] = { +extern const ChunkHandler _depot_chunk_handlers[] = { { 'DEPT', Save_DEPT, Load_DEPT, CH_ARRAY | CH_LAST}, }; diff --git a/src/direction.h b/src/direction.h index 477c34046..576d8e1bb 100644 --- a/src/direction.h +++ b/src/direction.h @@ -3,8 +3,11 @@ #ifndef DIRECTION_H #define DIRECTION_H +#include "helpers.hpp" + /* Direction as commonly used in v->direction, 8 way. */ typedef enum Direction { + DIR_BEGIN = 0, DIR_N = 0, DIR_NE = 1, /* Northeast, upper right on your monitor */ DIR_E = 2, @@ -17,6 +20,10 @@ typedef enum Direction { INVALID_DIR = 0xFF, } Direction; +/** Define basic enum properties */ +template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, byte, DIR_BEGIN, DIR_END, INVALID_DIR> {}; +typedef TinyEnumT<Direction> DirectionByte; + static inline Direction ReverseDir(Direction d) { return (Direction)(4 ^ d); @@ -51,6 +58,7 @@ static inline Direction ChangeDir(Direction d, DirDiff delta) /* Direction commonly used as the direction of entering and leaving tiles, 4-way */ typedef enum DiagDirection { + DIAGDIR_BEGIN = 0, DIAGDIR_NE = 0, /* Northeast, upper right on your monitor */ DIAGDIR_SE = 1, DIAGDIR_SW = 2, @@ -59,6 +67,12 @@ typedef enum DiagDirection { INVALID_DIAGDIR = 0xFF, } DiagDirection; +DECLARE_POSTFIX_INCREMENT(DiagDirection); + +/** Define basic enum properties */ +template <> struct EnumPropsT<DiagDirection> : MakeEnumPropsT<DiagDirection, byte, DIAGDIR_BEGIN, DIAGDIR_END, INVALID_DIAGDIR> {}; +typedef TinyEnumT<DiagDirection> DiagDirectionByte; + static inline DiagDirection ReverseDiagDir(DiagDirection d) { return (DiagDirection)(2 ^ d); diff --git a/src/disaster_cmd.cpp b/src/disaster_cmd.cpp index 2d4579b52..f018149f2 100644 --- a/src/disaster_cmd.cpp +++ b/src/disaster_cmd.cpp @@ -276,7 +276,7 @@ static void DisasterTick_UFO(Vehicle *v) // fly around randomly int x = TileX(v->dest_tile) * TILE_SIZE; int y = TileY(v->dest_tile) * TILE_SIZE; - if (abs(x - v->x_pos) + abs(y - v->y_pos) >= TILE_SIZE) { + if (delta(x, v->x_pos) + delta(y, v->y_pos) >= TILE_SIZE) { v->direction = GetDirectionTowards(v, x, y); GetNewVehiclePos(v, &gp); SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos); @@ -305,7 +305,7 @@ static void DisasterTick_UFO(Vehicle *v) return; } - dist = abs(v->x_pos - u->x_pos) + abs(v->y_pos - u->y_pos); + dist = delta(v->x_pos, u->x_pos) + delta(v->y_pos, u->y_pos); if (dist < TILE_SIZE && !(u->vehstatus&VS_HIDDEN) && u->breakdown_ctr==0) { u->breakdown_ctr = 3; @@ -526,7 +526,7 @@ static void DisasterTick_4(Vehicle *v) if (v->current_order.dest == 1) { int x = TileX(v->dest_tile) * TILE_SIZE + TILE_SIZE / 2; int y = TileY(v->dest_tile) * TILE_SIZE + TILE_SIZE / 2; - if (abs(v->x_pos - x) + abs(v->y_pos - y) >= 8) { + if (delta(v->x_pos, x) + delta(v->y_pos, y) >= 8) { v->direction = GetDirectionTowards(v, x, y); GetNewVehiclePos(v, &gp); @@ -544,7 +544,7 @@ static void DisasterTick_4(Vehicle *v) FOR_ALL_VEHICLES(u) { if (u->type == VEH_Train || u->type == VEH_Road) { - if (abs(u->x_pos - v->x_pos) + abs(u->y_pos - v->y_pos) <= 12 * TILE_SIZE) { + if (delta(u->x_pos, v->x_pos) + delta(u->y_pos, v->y_pos) <= 12 * TILE_SIZE) { u->breakdown_ctr = 5; u->breakdown_delay = 0xF0; } @@ -578,7 +578,7 @@ static void DisasterTick_4(Vehicle *v) int x = TileX(v->dest_tile) * TILE_SIZE; int y = TileY(v->dest_tile) * TILE_SIZE; - if (abs(x - v->x_pos) + abs(y - v->y_pos) >= TILE_SIZE) { + if (delta(x, v->x_pos) + delta(y, v->y_pos) >= TILE_SIZE) { v->direction = GetDirectionTowards(v, x, y); GetNewVehiclePos(v, &gp); SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos); @@ -626,7 +626,7 @@ static void DisasterTick_4b(Vehicle *v) if (v->current_order.dest == 0) { u = GetVehicle(v->u.disaster.unk2); - if (abs(v->x_pos - u->x_pos) > TILE_SIZE) + if (delta(v->x_pos, u->x_pos) > TILE_SIZE) return; v->current_order.dest = 1; diff --git a/src/dock_gui.cpp b/src/dock_gui.cpp index 8e550e9ec..89137396d 100644 --- a/src/dock_gui.cpp +++ b/src/dock_gui.cpp @@ -254,7 +254,7 @@ static void BuildDockStationWndProc(Window *w, WindowEvent *e) case 3: case 4: RaiseWindowWidget(w, _station_show_coverage + 3); - _station_show_coverage = e->we.click.widget - 3; + _station_show_coverage = (e->we.click.widget != 3); LowerWindowWidget(w, _station_show_coverage + 3); SndPlayFx(SND_15_BEEP); SetWindowDirty(w); @@ -328,7 +328,7 @@ static void BuildDocksDepotWndProc(Window *w, WindowEvent *e) case 3: case 4: RaiseWindowWidget(w, _ship_depot_direction + 3); - _ship_depot_direction = e->we.click.widget - 3; + _ship_depot_direction = (e->we.click.widget == 3 ? AXIS_X : AXIS_Y); LowerWindowWidget(w, _ship_depot_direction + 3); SndPlayFx(SND_15_BEEP); UpdateDocksDirection(); diff --git a/src/dummy_land.cpp b/src/dummy_land.cpp index 10952fc00..aa9a72d99 100644 --- a/src/dummy_land.cpp +++ b/src/dummy_land.cpp @@ -66,7 +66,7 @@ static uint32 GetTileTrackStatus_Dummy(TileIndex tile, TransportType mode) return 0; } -const TileTypeProcs _tile_type_dummy_procs = { +extern const TileTypeProcs _tile_type_dummy_procs = { DrawTile_Dummy, /* draw_tile_proc */ GetSlopeZ_Dummy, /* get_slope_z_proc */ ClearTile_Dummy, /* clear_tile_proc */ diff --git a/src/economy.cpp b/src/economy.cpp index a325a863c..402fc9cec 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -47,7 +47,7 @@ const ScoreInfo _score_info[] = { { SCORE_TOTAL, 0, 0 } }; -int _score_part[MAX_PLAYERS][NUM_SCORE]; +int _score_part[MAX_PLAYERS][SCORE_END]; int64 CalculateCompanyValue(const Player* p) { @@ -209,11 +209,10 @@ int UpdateCompanyRatingAndValue(Player *p, bool update) // Now we calculate the score for each item.. { - int i; int total_score = 0; int s; score = 0; - for (i = 0; i < NUM_SCORE; i++) { + for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) { // Skip the total if (i == SCORE_TOTAL) continue; // Check the score @@ -467,7 +466,7 @@ void DrawNewsBankrupcy(Window *w) DrawNewsBorder(w); - p = GetPlayer(GB(WP(w,news_d).ni->string_id, 0, 4)); + p = GetPlayer((PlayerID)GB(WP(w,news_d).ni->string_id, 0, 4)); DrawPlayerFace(p->face, p->player_color, 2, 23); GfxFillRect(3, 23, 3+91, 23+118, 0x323 | USE_COLORTABLE); @@ -536,7 +535,7 @@ void DrawNewsBankrupcy(Window *w) StringID GetNewsStringBankrupcy(const NewsItem *ni) { - const Player *p = GetPlayer(GB(ni->string_id, 0, 4)); + const Player *p = GetPlayer((PlayerID)GB(ni->string_id, 0, 4)); switch (ni->string_id & 0xF0) { case NB_BTROUBLE: @@ -1562,7 +1561,7 @@ void PlayersMonthlyLoop(void) static void DoAcquireCompany(Player *p) { Player *owner; - int i,pi; + int i; int64 value; SetDParam(0, p->name_1); @@ -1571,7 +1570,7 @@ static void DoAcquireCompany(Player *p) AddNewsItem( (StringID)(_current_player | NB_BMERGER), NEWS_FLAGS(NM_CALLBACK, 0, NT_COMPANY_INFO, DNC_BANKRUPCY),0,0); // original code does this a little bit differently - pi = p->index; + PlayerID pi = p->index; ChangeOwnershipOfPlayerItems(pi, _current_player); if (p->bankrupt_value == 0) { @@ -1595,7 +1594,7 @@ static void DoAcquireCompany(Player *p) RebuildVehicleLists(); //Updates the open windows to add the newly acquired vehicles to the lists } -extern int GetAmountOwnedBy(Player *p, byte owner); +extern int GetAmountOwnedBy(const Player *p, PlayerID owner); /** Acquire shares in an opposing company. * @param tile unused @@ -1611,7 +1610,7 @@ int32 CmdBuyShareInCompany(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (!IsValidPlayer((PlayerID)p1) || !_patches.allow_shares) return CMD_ERROR; SET_EXPENSES_TYPE(EXPENSES_OTHER); - p = GetPlayer(p1); + p = GetPlayer((PlayerID)p1); /* Protect new companies from hostile takeovers */ if (_cur_year - p->inaugurated_year < 6) return_cmd_error(STR_7080_PROTECTED); @@ -1624,7 +1623,7 @@ int32 CmdBuyShareInCompany(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) cost = CalculateCompanyValue(p) >> 2; if (flags & DC_EXEC) { - PlayerID* b = p->share_owners; + PlayerByte* b = p->share_owners; int i; while (*b != PLAYER_SPECTATOR) b++; /* share owners is guaranteed to contain at least one PLAYER_SPECTATOR */ @@ -1656,7 +1655,7 @@ int32 CmdSellShareInCompany(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (!IsValidPlayer((PlayerID)p1) || !_patches.allow_shares) return CMD_ERROR; SET_EXPENSES_TYPE(EXPENSES_OTHER); - p = GetPlayer(p1); + p = GetPlayer((PlayerID)p1); /* Those lines are here for network-protection (clients can be slow) */ if (GetAmountOwnedBy(p, _current_player) == 0) return 0; @@ -1666,7 +1665,7 @@ int32 CmdSellShareInCompany(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) cost = -(cost - (cost >> 7)); if (flags & DC_EXEC) { - PlayerID* b = p->share_owners; + PlayerByte* b = p->share_owners; while (*b != _current_player) b++; /* share owners is guaranteed to contain player */ *b = PLAYER_SPECTATOR; InvalidateWindow(WC_COMPANY, p1); @@ -1690,7 +1689,7 @@ int32 CmdBuyCompany(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (!IsValidPlayer((PlayerID)p1) || _networking) return CMD_ERROR; SET_EXPENSES_TYPE(EXPENSES_OTHER); - p = GetPlayer(p1); + p = GetPlayer((PlayerID)p1); if (!p->is_ai) return CMD_ERROR; @@ -1730,7 +1729,7 @@ static void SaveLoad_ECMY(void) SlObject(&_economy, _economy_desc); } -const ChunkHandler _economy_chunk_handlers[] = { +extern const ChunkHandler _economy_chunk_handlers[] = { { 'PRIC', SaveLoad_PRIC, SaveLoad_PRIC, CH_RIFF | CH_AUTO_LENGTH}, { 'CAPR', SaveLoad_CAPR, SaveLoad_CAPR, CH_RIFF | CH_AUTO_LENGTH}, { 'SUBS', Save_SUBS, Load_SUBS, CH_ARRAY}, diff --git a/src/economy.h b/src/economy.h index 823e167c8..7737eefd9 100644 --- a/src/economy.h +++ b/src/economy.h @@ -29,7 +29,8 @@ typedef struct Subsidy { } Subsidy; -enum { +enum ScoreID { + SCORE_BEGIN = 0, SCORE_VEHICLES = 0, SCORE_STATIONS = 1, SCORE_MIN_PROFIT = 2, @@ -40,13 +41,14 @@ enum { SCORE_MONEY = 7, SCORE_LOAN = 8, SCORE_TOTAL = 9, // This must always be the last entry - - NUM_SCORE = 10, // How many scores are there.. + SCORE_END = 10, // How many scores are there.. SCORE_MAX = 1000 // The max score that can be in the performance history // the scores together of score_info is allowed to be more! }; +DECLARE_POSTFIX_INCREMENT(ScoreID); + typedef struct ScoreInfo { byte id; // Unique ID of the score int needed; // How much you need to get the perfect score @@ -54,7 +56,7 @@ typedef struct ScoreInfo { } ScoreInfo; extern const ScoreInfo _score_info[]; -extern int _score_part[MAX_PLAYERS][NUM_SCORE]; +extern int _score_part[MAX_PLAYERS][SCORE_END]; int UpdateCompanyRatingAndValue(Player *p, bool update); diff --git a/src/elrail.cpp b/src/elrail.cpp index da043b582..97d4b1550 100644 --- a/src/elrail.cpp +++ b/src/elrail.cpp @@ -67,7 +67,7 @@ static inline TLG GetTLG(TileIndex t) { - return (HASBIT(TileX(t), 0) << 1) + HASBIT(TileY(t), 0); + return (TLG)((HASBIT(TileX(t), 0) << 1) + HASBIT(TileY(t), 0)); } /** Finds which Rail Bits are present on a given tile. For bridge tiles, @@ -77,24 +77,24 @@ static TrackBits GetRailTrackBitsUniversal(TileIndex t, byte *override) { switch (GetTileType(t)) { case MP_RAILWAY: - if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0; + if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE; switch (GetRailTileType(t)) { case RAIL_TILE_NORMAL: case RAIL_TILE_SIGNALS: return GetTrackBits(t); case RAIL_TILE_DEPOT_WAYPOINT: if (GetRailTileSubtype(t) == RAIL_SUBTYPE_WAYPOINT) return GetRailWaypointBits(t); default: - return 0; + return TRACK_BIT_NONE; } break; case MP_TUNNELBRIDGE: if (IsTunnel(t)) { - if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0; + if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE; if (override != NULL) *override = 1 << GetTunnelDirection(t); return AxisToTrackBits(DiagDirToAxis(GetTunnelDirection(t))); } else { - if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0; + if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE; if (override != NULL && DistanceMax(t, GetOtherBridgeEnd(t)) > 1) { *override = 1 << GetBridgeRampDirection(t); } @@ -102,18 +102,18 @@ static TrackBits GetRailTrackBitsUniversal(TileIndex t, byte *override) } case MP_STREET: - if (GetRoadTileType(t) != ROAD_TILE_CROSSING) return 0; - if (GetRailTypeCrossing(t) != RAILTYPE_ELECTRIC) return 0; + if (GetRoadTileType(t) != ROAD_TILE_CROSSING) return TRACK_BIT_NONE; + if (GetRailTypeCrossing(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE; return GetCrossingRailBits(t); case MP_STATION: - if (!IsRailwayStation(t)) return 0; - if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0; - if (!IsStationTileElectrifiable(t)) return 0; + if (!IsRailwayStation(t)) return TRACK_BIT_NONE; + if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE; + if (!IsStationTileElectrifiable(t)) return TRACK_BIT_NONE; return TrackToTrackBits(GetRailStationTrack(t)); default: - return 0; + return TRACK_BIT_NONE; } } @@ -171,7 +171,7 @@ static void DrawCatenaryRailway(const TileInfo *ti) * which have no middle tiles */ trackconfig[TS_HOME] = GetRailTrackBitsUniversal(ti->tile, &OverridePCP); /* If a track bit is present that is not in the main direction, the track is level */ - isflat[TS_HOME] = trackconfig[TS_HOME] & (TRACK_BIT_HORZ | TRACK_BIT_VERT); + isflat[TS_HOME] = ((trackconfig[TS_HOME] & (TRACK_BIT_HORZ | TRACK_BIT_VERT)) != 0); AdjustTileh(ti->tile, &tileh[TS_HOME]); @@ -184,8 +184,8 @@ static void DrawCatenaryRailway(const TileInfo *ti) * existing foundataions, so we do have to do that manually later on.*/ tileh[TS_NEIGHBOUR] = GetTileSlope(neighbour, NULL); trackconfig[TS_NEIGHBOUR] = GetRailTrackBitsUniversal(neighbour, NULL); - if (IsTunnelTile(neighbour) && i != GetTunnelDirection(neighbour)) trackconfig[TS_NEIGHBOUR] = 0; - isflat[TS_NEIGHBOUR] = trackconfig[TS_NEIGHBOUR] & (TRACK_BIT_HORZ | TRACK_BIT_VERT); + if (IsTunnelTile(neighbour) && i != GetTunnelDirection(neighbour)) trackconfig[TS_NEIGHBOUR] = TRACK_BIT_NONE; + isflat[TS_NEIGHBOUR] = ((trackconfig[TS_NEIGHBOUR] & (TRACK_BIT_HORZ | TRACK_BIT_VERT)) != 0); PPPpreferred[i] = 0xFF; /* We start with preferring everything (end-of-line in any direction) */ PPPallowed[i] = AllowedPPPonPCP[i]; @@ -289,7 +289,7 @@ static void DrawCatenaryRailway(const TileInfo *ti) } /* Drawing of pylons is finished, now draw the wires */ - for (t = 0; t < TRACK_END; t++) { + for (t = TRACK_BEGIN; t < TRACK_END; t++) { if (HASBIT(trackconfig[TS_HOME], t)) { byte PCPconfig = HASBIT(PCPstatus, PCPpositions[t][0]) + @@ -321,7 +321,7 @@ static void DrawCatenaryOnBridge(const TileInfo *ti) Axis axis = GetBridgeAxis(ti->tile); TLG tlg = GetTLG(ti->tile); - CatenarySprite offset = axis == AXIS_X ? 0 : WIRE_Y_FLAT_BOTH - WIRE_X_FLAT_BOTH; + CatenarySprite offset = (CatenarySprite)(axis == AXIS_X ? 0 : WIRE_Y_FLAT_BOTH - WIRE_X_FLAT_BOTH); if ((length % 2) && num == length) { /* Draw the "short" wire on the southern end of the bridge diff --git a/src/endian_check.cpp b/src/endian_check.cpp index a302ea40b..97773496f 100644 --- a/src/endian_check.cpp +++ b/src/endian_check.cpp @@ -1,6 +1,7 @@ /* $Id$ */ #include <stdio.h> +#include <string.h> // This pretty simple file checks if the system is LITTLE_ENDIAN or BIG_ENDIAN // it does that by putting a 1 and a 0 in an array, and read it out as one diff --git a/src/engine.cpp b/src/engine.cpp index 0a4b21c3d..8c3779dc5 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -129,7 +129,7 @@ void StartupEngines(void) uint32 r; e->age = 0; - e->railtype = ei->railtype; + e->railtype = (RailType)ei->railtype; e->flags = 0; e->player_avail = 0; @@ -189,7 +189,7 @@ static void AcceptEnginePreview(Engine *e, PlayerID player) SETBIT(e->player_avail, player); SETBIT(p->avail_railtypes, e->railtype); - e->preview_player = 0xFF; + e->preview_player = INVALID_PLAYER; if (player == _local_player) { InvalidateWindowClassesData(WC_BUILD_VEHICLE); InvalidateWindowClasses(WC_REPLACE_VEHICLE); @@ -217,7 +217,7 @@ static PlayerID GetBestPlayer(PlayerID pp) if (best_player == PLAYER_SPECTATOR) return PLAYER_SPECTATOR; SETBIT(mask, best_player); - } while (--pp != 0); + } while (pp--, pp != 0); return best_player; } @@ -242,7 +242,7 @@ void EnginesDailyLoop(void) PlayerID best_player = GetBestPlayer(e->preview_player); if (best_player == PLAYER_SPECTATOR) { - e->preview_player = 0xFF; + e->preview_player = INVALID_PLAYER; continue; } @@ -364,7 +364,7 @@ void EnginesMonthlyLoop(void) // Do not introduce new rail wagons if (!IsWagon(e - _engines)) - e->preview_player = 1; // Give to the player with the highest rating. + e->preview_player = (PlayerID)1; // Give to the player with the highest rating. } } } @@ -636,7 +636,7 @@ static void LoadSave_ENGS(void) SlArray(_engine_name_strings, lengthof(_engine_name_strings), SLE_STRINGID); } -const ChunkHandler _engine_chunk_handlers[] = { +extern const ChunkHandler _engine_chunk_handlers[] = { { 'ENGN', Save_ENGN, Load_ENGN, CH_ARRAY }, { 'ENGS', LoadSave_ENGS, LoadSave_ENGS, CH_RIFF }, { 'ERNW', Save_ERNW, Load_ERNW, CH_ARRAY | CH_LAST}, diff --git a/src/engine.h b/src/engine.h index 2fa6b9eb0..c2dca0b9b 100644 --- a/src/engine.h +++ b/src/engine.h @@ -6,6 +6,8 @@ /** @file engine.h */ #include "oldpool.h" +#include "rail.h" +#include "sound.h" typedef struct RailVehicleInfo { byte image_index; @@ -38,8 +40,8 @@ typedef struct ShipVehicleInfo { CargoID cargo_type; uint16 capacity; byte running_cost; - byte sfx; - byte refittable; + SoundFxByte sfx; + bool refittable; } ShipVehicleInfo; // Aircraft subtypes @@ -53,7 +55,7 @@ typedef struct AircraftVehicleInfo { byte base_cost; byte running_cost; byte subtype; - byte sfx; + SoundFxByte sfx; byte acceleration; byte max_speed; byte mail_capacity; @@ -64,7 +66,7 @@ typedef struct RoadVehicleInfo { byte image_index; byte base_cost; byte running_cost; - byte sfx; + SoundFxByte sfx; byte max_speed; byte capacity; CargoID cargo_type; @@ -96,9 +98,9 @@ typedef struct Engine { uint16 duration_phase_1, duration_phase_2, duration_phase_3; byte lifelength; byte flags; - byte preview_player; + PlayerByte preview_player; byte preview_wait; - byte railtype; + RailTypeByte railtype; byte player_avail; byte type; // type, ie VEH_Road, VEH_Train, etc. Same as in vehicle.h } Engine; @@ -122,9 +124,8 @@ enum { NUM_VEHICLE_TYPES = 6 }; -enum { - INVALID_ENGINE = 0xFFFF, -}; +static const EngineID INVALID_ENGINE = 0xFFFF; + void AddTypeToEngines(void); void StartupEngines(void); diff --git a/src/engine_gui.cpp b/src/engine_gui.cpp index 31f175cf1..91db313f6 100644 --- a/src/engine_gui.cpp +++ b/src/engine_gui.cpp @@ -24,6 +24,7 @@ static StringID GetEngineCategoryName(EngineID engine) case RAILTYPE_ELECTRIC: return STR_8102_RAILROAD_LOCOMOTIVE; case RAILTYPE_MONO: return STR_8106_MONORAIL_LOCOMOTIVE; case RAILTYPE_MAGLEV: return STR_8107_MAGLEV_LOCOMOTIVE; + default: NOT_REACHED(); } } diff --git a/src/fios.cpp b/src/fios.cpp index 950e26a23..87e7ea93d 100644 --- a/src/fios.cpp +++ b/src/fios.cpp @@ -11,6 +11,7 @@ #include "variables.h" #include "functions.h" #include "heightmap.h" +#include "helpers.hpp" #include "table/strings.h" #include "fios.h" #include <sys/types.h> @@ -47,7 +48,7 @@ FiosItem *FiosAlloc(void) { if (_fios_count == _fios_alloc) { _fios_alloc += 256; - _fios_items = realloc(_fios_items, _fios_alloc * sizeof(FiosItem)); + ReallocT(&_fios_items, _fios_alloc); } return &_fios_items[_fios_count++]; } @@ -323,7 +324,7 @@ FiosItem *FiosGetSavegameList(int mode) static char *_fios_save_path = NULL; if (_fios_save_path == NULL) { - _fios_save_path = malloc(MAX_PATH); + MallocT(&_fios_save_path, MAX_PATH); ttd_strlcpy(_fios_save_path, _paths.save_dir, MAX_PATH); } @@ -371,7 +372,7 @@ FiosItem *FiosGetScenarioList(int mode) static char *_fios_scn_path = NULL; if (_fios_scn_path == NULL) { - _fios_scn_path = malloc(MAX_PATH); + MallocT(&_fios_scn_path, MAX_PATH); ttd_strlcpy(_fios_scn_path, _paths.scenario_dir, MAX_PATH); } @@ -402,7 +403,7 @@ FiosItem *FiosGetHeightmapList(int mode) static char *_fios_hmap_path = NULL; if (_fios_hmap_path == NULL) { - _fios_hmap_path = malloc(MAX_PATH); + MallocT(&_fios_hmap_path, MAX_PATH); strcpy(_fios_hmap_path, _paths.heightmap_dir); } diff --git a/src/fontcache.cpp b/src/fontcache.cpp index d555eea94..e60fe8bc7 100644 --- a/src/fontcache.cpp +++ b/src/fontcache.cpp @@ -11,6 +11,7 @@ #include "gfx.h" #include "string.h" #include "fontcache.h" +#include "helpers.hpp" #ifdef WITH_FREETYPE @@ -77,7 +78,7 @@ static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) * normal char to match the data returned by RegEnumValue, * otherwise just use parameter */ #if defined(UNICODE) - font_namep = malloc(MAX_PATH * sizeof(TCHAR)); + MallocT(&font_namep, MAX_PATH); MB_TO_WIDE_BUFFER(font_name, font_namep, MAX_PATH * sizeof(TCHAR)); #else font_namep = (char*)font_name; // only cast because in unicode pointer is not const @@ -345,12 +346,12 @@ static void SetGlyphPtr(FontSize size, WChar key, const GlyphEntry *glyph) { if (_glyph_ptr[size] == NULL) { DEBUG(freetype, 3, "Allocating root glyph cache for size %u", size); - _glyph_ptr[size] = calloc(256, sizeof(**_glyph_ptr)); + CallocT(&_glyph_ptr[size], 256); } if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) { DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), size); - _glyph_ptr[size][GB(key, 8, 8)] = calloc(256, sizeof(***_glyph_ptr)); + CallocT(&_glyph_ptr[size][GB(key, 8, 8)], 256); } DEBUG(freetype, 4, "Set glyph for unicode character 0x%04X, size %u", key, size); @@ -395,7 +396,7 @@ const Sprite *GetGlyph(FontSize size, WChar key) height = max(1, slot->bitmap.rows + (size == FS_NORMAL)); /* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */ - sprite = calloc(width * height + 8, 1); + sprite = (Sprite*)calloc(width * height + 8, 1); sprite->info = 1; sprite->width = width; sprite->height = height; @@ -483,8 +484,8 @@ SpriteID GetUnicodeGlyph(FontSize size, uint32 key) void SetUnicodeGlyph(FontSize size, uint32 key, SpriteID sprite) { - if (_unicode_glyph_map[size] == NULL) _unicode_glyph_map[size] = calloc(256, sizeof(*_unicode_glyph_map[size])); - if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) _unicode_glyph_map[size][GB(key, 8, 8)] = calloc(256, sizeof(**_unicode_glyph_map[size])); + if (_unicode_glyph_map[size] == NULL) CallocT(&_unicode_glyph_map[size], 256); + if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) CallocT(&_unicode_glyph_map[size][GB(key, 8, 8)], 256); _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)] = sprite; } diff --git a/src/functions.h b/src/functions.h index 12490b10d..bba59f5ea 100644 --- a/src/functions.h +++ b/src/functions.h @@ -10,7 +10,7 @@ uint GetPartialZ(int x, int y, Slope corners); uint GetSlopeZ(int x, int y); uint32 GetTileTrackStatus(TileIndex tile, TransportType mode); void GetAcceptedCargo(TileIndex tile, AcceptedCargo ac); -void ChangeTileOwner(TileIndex tile, byte old_player, byte new_player); +void ChangeTileOwner(TileIndex tile, PlayerID old_player, PlayerID new_player); void AnimateTile(TileIndex tile); void ClickTile(TileIndex tile); void GetTileDesc(TileIndex tile, TileDesc *td); @@ -217,5 +217,4 @@ void HandleExitGameRequest(void); void DeterminePaths(void); -void CSleep(int milliseconds); #endif /* FUNCTIONS_H */ diff --git a/src/genworld.cpp b/src/genworld.cpp index ba9fe126f..eef47eaed 100644 --- a/src/genworld.cpp +++ b/src/genworld.cpp @@ -182,7 +182,7 @@ void WaitTillGeneratedWorld(void) { if (_gw.thread == NULL) return; _gw.quit_thread = true; - OTTDJoinThread(_gw.thread); + OTTDJoinThread((OTTDThread*)_gw.thread); _gw.thread = NULL; _gw.threaded = false; } diff --git a/src/genworld.h b/src/genworld.h index 0cf67cbe6..10fb569a1 100644 --- a/src/genworld.h +++ b/src/genworld.h @@ -34,7 +34,7 @@ typedef struct gw_info { bool quit_thread; //! Do we want to quit the active thread bool threaded; //! Whether we run _GenerateWorld threaded int mode; //! What mode are we making a world in - byte lp; //! The local_player before generating + PlayerID lp; //! The local_player before generating uint size_x; //! X-size of the map uint size_y; //! Y-size of the map gw_done_proc *proc; //! Proc that is called when done (can be NULL) @@ -84,8 +84,8 @@ bool IsGeneratingWorldAborted(void); void HandleGeneratingWorldAbortion(void); /* genworld_gui.c */ -void SetGeneratingWorldProgress(gwp_class class, uint total); -void IncreaseGeneratingWorldProgress(gwp_class class); +void SetGeneratingWorldProgress(gwp_class cls, uint total); +void IncreaseGeneratingWorldProgress(gwp_class cls); void PrepareGenerateWorldProgress(void); void ShowGenerateWorldProgress(void); void StartNewGameWithoutGUI(uint seed); diff --git a/src/genworld_gui.cpp b/src/genworld_gui.cpp index 83d0f4cf1..65cbbd6da 100644 --- a/src/genworld_gui.cpp +++ b/src/genworld_gui.cpp @@ -196,7 +196,7 @@ void GenerateLandscapeWndProc(Window *w, WindowEvent *e) static querystr_d _genseed_query; static char _genseed_buffer[LEN_RND_SEED]; - uint mode = w->window_number; + glwp_modes mode = (glwp_modes)w->window_number; uint y; switch (e->event) { @@ -714,7 +714,7 @@ static const Widget _show_terrain_progress_widgets[] = { typedef struct tp_info { uint percent; - StringID class; + StringID cls; uint current; uint total; int timer; @@ -753,12 +753,12 @@ static void ShowTerrainProgressProc(Window* w, WindowEvent* e) /* Draw the % complete with a bar and a text */ DrawFrameRect(19, 20, (w->width - 18), 37, 14, FR_BORDERONLY); - DrawFrameRect(20, 21, (int)((w->width - 40) * _tp.percent / 100) + 20, 36, 10, 0); + DrawFrameRect(20, 21, (int)((w->width - 40) * _tp.percent / 100) + 20, 36, 10, FR_NONE); SetDParam(0, _tp.percent); DrawStringCentered(90, 25, STR_PROGRESS, 0); /* Tell which class we are generating */ - DrawStringCentered(90, 46, _tp.class, 0); + DrawStringCentered(90, 46, _tp.cls, 0); /* And say where we are in that class */ SetDParam(0, _tp.current); @@ -783,7 +783,7 @@ static const WindowDesc _show_terrain_progress_desc = { */ void PrepareGenerateWorldProgress(void) { - _tp.class = STR_WORLD_GENERATION; + _tp.cls = STR_WORLD_GENERATION; _tp.current = 0; _tp.total = 0; _tp.percent = 0; @@ -798,7 +798,7 @@ void ShowGenerateWorldProgress(void) AllocateWindowDescFront(&_show_terrain_progress_desc, 0); } -static void _SetGeneratingWorldProgress(gwp_class class, uint progress, uint total) +static void _SetGeneratingWorldProgress(gwp_class cls, uint progress, uint total) { static const int percent_table[GWP_CLASS_COUNT + 1] = {0, 5, 15, 20, 40, 60, 65, 80, 85, 99, 100 }; static const StringID class_table[GWP_CLASS_COUNT] = { @@ -814,7 +814,7 @@ static void _SetGeneratingWorldProgress(gwp_class class, uint progress, uint tot STR_PREPARING_GAME }; - assert(class < GWP_CLASS_COUNT); + assert(cls < GWP_CLASS_COUNT); /* Do not run this function if we aren't in a thread */ if (!IsGenerateWorldThreaded() && !_network_dedicated) return; @@ -822,13 +822,13 @@ static void _SetGeneratingWorldProgress(gwp_class class, uint progress, uint tot if (IsGeneratingWorldAborted()) HandleGeneratingWorldAbortion(); if (total == 0) { - assert(_tp.class == class_table[class]); + assert(_tp.cls == class_table[cls]); _tp.current += progress; } else { - _tp.class = class_table[class]; + _tp.cls = class_table[cls]; _tp.current = progress; _tp.total = total; - _tp.percent = percent_table[class]; + _tp.percent = percent_table[cls]; } /* Don't update the screen too often. So update it once in every 200ms. @@ -837,7 +837,7 @@ static void _SetGeneratingWorldProgress(gwp_class class, uint progress, uint tot if (!_network_dedicated && _tp.timer != 0 && _timer_counter - _tp.timer < (200 * 8 / 30)) return; /* Percentage is about the number of completed tasks, so 'current - 1' */ - _tp.percent = percent_table[class] + (percent_table[class + 1] - percent_table[class]) * (_tp.current == 0 ? 0 : _tp.current - 1) / _tp.total; + _tp.percent = percent_table[cls] + (percent_table[cls + 1] - percent_table[cls]) * (_tp.current == 0 ? 0 : _tp.current - 1) / _tp.total; _tp.timer = _timer_counter; if (_network_dedicated) { @@ -877,11 +877,11 @@ static void _SetGeneratingWorldProgress(gwp_class class, uint progress, uint tot * Warning: this function isn't clever. Don't go from class 4 to 3. Go upwards, always. * Also, progress works if total is zero, total works if progress is zero. */ -void SetGeneratingWorldProgress(gwp_class class, uint total) +void SetGeneratingWorldProgress(gwp_class cls, uint total) { if (total == 0) return; - _SetGeneratingWorldProgress(class, 0, total); + _SetGeneratingWorldProgress(cls, 0, total); } /** @@ -891,8 +891,8 @@ void SetGeneratingWorldProgress(gwp_class class, uint total) * Warning: this function isn't clever. Don't go from class 4 to 3. Go upwards, always. * Also, progress works if total is zero, total works if progress is zero. */ -void IncreaseGeneratingWorldProgress(gwp_class class) +void IncreaseGeneratingWorldProgress(gwp_class cls) { /* In fact the param 'class' isn't needed.. but for some security reasons, we want it around */ - _SetGeneratingWorldProgress(class, 1, 0); + _SetGeneratingWorldProgress(cls, 1, 0); } diff --git a/src/gfx.cpp b/src/gfx.cpp index a78e20040..de90ca461 100644 --- a/src/gfx.cpp +++ b/src/gfx.cpp @@ -473,7 +473,7 @@ void DrawStringMultiCenter(int x, int y, StringID str, int maxw) tmp = FormatStringLinebreaks(buffer, maxw); num = GB(tmp, 0, 16); - mt = GetCharacterHeight(GB(tmp, 16, 16)); + mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16)); y -= (mt >> 1) * num; @@ -517,7 +517,7 @@ uint DrawStringMultiLine(int x, int y, StringID str, int maxw) tmp = FormatStringLinebreaks(buffer, maxw); num = GB(tmp, 0, 16); - mt = GetCharacterHeight(GB(tmp, 16, 16)); + mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16)); total_height = (num + 1) * mt; src = buffer; @@ -3,31 +3,7 @@ #ifndef GFX_H #define GFX_H -typedef byte Pixel; - -struct DrawPixelInfo { - Pixel *dst_ptr; - int left, top, width, height; - int pitch; - uint16 zoom; -}; - - -typedef struct CursorVars { - Point pos, size, offs, delta; ///< position, size, offset from top-left, and movement - Point draw_pos, draw_size; ///< position and size bounding-box for drawing - CursorID sprite; ///< current image of cursor - - int wheel; ///< mouse wheel movement - const CursorID *animate_list, *animate_cur; ///< in case of animated cursor, list of frames - uint animate_timeout; ///< current frame in list of animated cursor - - bool visible; ///< cursor is visible - bool dirty; ///< the rect occupied by the mouse is dirty (redraw) - bool fix_at; ///< mouse is moving, but cursor is not (used for scrolling) - bool in_window; ///< mouse inside this window, determines drawing logic -} CursorVars; - +#include "helpers.hpp" typedef enum FontSizes { FS_NORMAL, @@ -36,6 +12,7 @@ typedef enum FontSizes { FS_END, } FontSize; +DECLARE_POSTFIX_INCREMENT(FontSize); void RedrawScreenRect(int left, int top, int right, int bottom); void GfxScroll(int left, int top, int width, int height, int xo, int yo); @@ -83,7 +60,7 @@ bool FillDrawPixelInfo(DrawPixelInfo* n, int left, int top, int width, int heigh /* window.c */ void DrawOverlappedWindowForAll(int left, int top, int right, int bottom); -void SetMouseCursor(uint cursor); +void SetMouseCursor(CursorID cursor); void SetAnimatedMouseCursor(const CursorID *table); void CursorTick(void); void DrawMouseCursor(void); @@ -91,7 +68,7 @@ void ScreenSizeChanged(void); void UndrawMouseCursor(void); bool ChangeResInGame(int w, int h); void SortResolutions(int count); -void ToggleFullScreen(bool fs); +extern "C" void ToggleFullScreen(bool fs); /* gfx.c */ #define ASCII_LETTERSTART 32 @@ -109,9 +86,7 @@ static inline byte GetCharacterHeight(FontSize size) } } -VARDEF DrawPixelInfo _screen; VARDEF DrawPixelInfo *_cur_dpi; -VARDEF CursorVars _cursor; enum { COLOUR_DARK_BLUE, @@ -138,20 +113,8 @@ enum { */ VARDEF byte _colour_gradient[16][8]; -VARDEF int _pal_first_dirty; -VARDEF int _pal_last_dirty; - VARDEF bool _use_dos_palette; -typedef struct Colour { - byte r; - byte g; - byte b; -} Colour; - -extern Colour _cur_palette[256]; - - typedef enum StringColorFlags { IS_PALETTE_COLOR = 0x100, // color value is already a real palette color index, not an index of a StringColor } StringColorFlags; diff --git a/src/gfxinit.cpp b/src/gfxinit.cpp index 4b55ec904..6de300100 100644 --- a/src/gfxinit.cpp +++ b/src/gfxinit.cpp @@ -17,13 +17,13 @@ #include <string.h> typedef struct MD5File { - const char * const filename; // filename - const md5_byte_t hash[16]; // md5 sum of the file + const char * filename; // filename + md5_byte_t hash[16]; // md5 sum of the file } MD5File; typedef struct FileList { - const MD5File basic[4]; // grf files that always have to be loaded - const MD5File landscape[3]; // landscape specific grf files + MD5File basic[4]; // grf files that always have to be loaded + MD5File landscape[3]; // landscape specific grf files } FileList; enum { diff --git a/src/graph_gui.cpp b/src/graph_gui.cpp index c6a9b845b..96d0f9f7a 100644 --- a/src/graph_gui.cpp +++ b/src/graph_gui.cpp @@ -15,6 +15,7 @@ #include "debug.h" #include "variables.h" #include "date.h" +#include "helpers.hpp" const byte _cargo_colours[NUM_CARGO] = {152, 32, 15, 174, 208, 194, 191, 84, 184, 10, 202, 48}; @@ -65,7 +66,7 @@ static void DrawGraph(const GraphDrawer *gw) /* the colors and cost array of GraphDrawer must accomodate * both values for cargo and players. So if any are higher, quit */ - assert(GRAPH_NUM >= NUM_CARGO && GRAPH_NUM >= MAX_PLAYERS); + assert(GRAPH_NUM >= (int)NUM_CARGO && GRAPH_NUM >= (int)MAX_PLAYERS); color = _colour_gradient[gw->bg_line_color][4]; @@ -118,7 +119,7 @@ static void DrawGraph(const GraphDrawer *gw) col_ptr = row_ptr; do { if (*col_ptr != INVALID_VALUE) { - mx = max64(mx, myabs64(*col_ptr)); + mx = max64(mx, *col_ptr); } } while (col_ptr++, --num_x); } @@ -906,11 +907,10 @@ void ShowCompanyLeagueTable(void) static void PerformanceRatingDetailWndProc(Window *w, WindowEvent *e) { - static PlayerID _performance_rating_detail_player = 0; + static PlayerID _performance_rating_detail_player = PLAYER_FIRST; switch (e->event) { case WE_PAINT: { - int i; byte x; uint16 y = 14; int total_score = 0; @@ -920,7 +920,7 @@ static void PerformanceRatingDetailWndProc(Window *w, WindowEvent *e) DrawWindowWidgets(w); // Paint the player icons - for (i = 0; i < MAX_PLAYERS; i++) { + for (PlayerID i = PLAYER_FIRST; i < MAX_PLAYERS; i++) { if (!GetPlayer(i)->is_active) { // Check if we have the player as an active player if (!IsWindowWidgetDisabled(w, i + 13)) { @@ -930,7 +930,7 @@ static void PerformanceRatingDetailWndProc(Window *w, WindowEvent *e) if (IsWindowWidgetLowered(w, i + 13)) { RaiseWindowWidget(w, i + 13); LowerWindowWidget(w, 13); - _performance_rating_detail_player = 0; + _performance_rating_detail_player = PLAYER_FIRST; } // We need a repaint SetWindowDirty(w); @@ -955,7 +955,7 @@ static void PerformanceRatingDetailWndProc(Window *w, WindowEvent *e) color_notdone = _colour_gradient[COLOUR_RED][4]; // Draw all the score parts - for (i = 0; i < NUM_SCORE; i++) { + for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) { int val = _score_part[_performance_rating_detail_player][i]; int needed = _score_info[i].needed; int score = _score_info[i].score; @@ -1030,7 +1030,7 @@ static void PerformanceRatingDetailWndProc(Window *w, WindowEvent *e) // Is it no on disable? if (!IsWindowWidgetDisabled(w, e->we.click.widget)) { RaiseWindowWidget(w, _performance_rating_detail_player + 13); - _performance_rating_detail_player = e->we.click.widget - 13; + _performance_rating_detail_player = (PlayerID)(e->we.click.widget - 13); LowerWindowWidget(w, _performance_rating_detail_player + 13); SetWindowDirty(w); } @@ -1038,11 +1038,11 @@ static void PerformanceRatingDetailWndProc(Window *w, WindowEvent *e) break; case WE_CREATE: { - int i; + PlayerID i; Player *p2; /* Disable the players who are not active */ - for (i = 0; i < MAX_PLAYERS; i++) { + for (i = PLAYER_FIRST; i < MAX_PLAYERS; i++) { SetWindowWidgetDisabledState(w, i + 13, !GetPlayer(i)->is_active); } /* Update all player stats with the current data @@ -1054,7 +1054,7 @@ static void PerformanceRatingDetailWndProc(Window *w, WindowEvent *e) w->custom[0] = DAY_TICKS; w->custom[1] = 5; - _performance_rating_detail_player = 0; + _performance_rating_detail_player = PLAYER_FIRST; LowerWindowWidget(w, _performance_rating_detail_player + 13); SetWindowDirty(w); @@ -1151,7 +1151,7 @@ static void GlobalSortSignList(void) uint n = 0; /* Create array for sorting */ - _sign_sort = realloc((void *)_sign_sort, (GetMaxSignIndex() + 1)* sizeof(_sign_sort[0])); + ReallocT(&_sign_sort, GetMaxSignIndex() + 1); if (_sign_sort == NULL) error("Could not allocate memory for the sign-sorting-list"); FOR_ALL_SIGNS(si) _sign_sort[n++] = si; @@ -132,7 +132,7 @@ void ShowMusicWindow(void); /* main_gui.c */ void HandleOnEditText(const char *str); -VARDEF byte _station_show_coverage; +VARDEF bool _station_show_coverage; VARDEF PlaceProc *_place_proc; /* vehicle_gui.c */ @@ -3,6 +3,85 @@ #ifndef HAL_H #define HAL_H +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + +enum WindowKeyCodes { + WKC_SHIFT = 0x8000, + WKC_CTRL = 0x4000, + WKC_ALT = 0x2000, + WKC_META = 0x1000, + + // Special ones + WKC_NONE = 0, + WKC_ESC = 1, + WKC_BACKSPACE = 2, + WKC_INSERT = 3, + WKC_DELETE = 4, + + WKC_PAGEUP = 5, + WKC_PAGEDOWN = 6, + WKC_END = 7, + WKC_HOME = 8, + + // Arrow keys + WKC_LEFT = 9, + WKC_UP = 10, + WKC_RIGHT = 11, + WKC_DOWN = 12, + + // Return & tab + WKC_RETURN = 13, + WKC_TAB = 14, + + // Numerical keyboard + WKC_NUM_0 = 16, + WKC_NUM_1 = 17, + WKC_NUM_2 = 18, + WKC_NUM_3 = 19, + WKC_NUM_4 = 20, + WKC_NUM_5 = 21, + WKC_NUM_6 = 22, + WKC_NUM_7 = 23, + WKC_NUM_8 = 24, + WKC_NUM_9 = 25, + WKC_NUM_DIV = 26, + WKC_NUM_MUL = 27, + WKC_NUM_MINUS = 28, + WKC_NUM_PLUS = 29, + WKC_NUM_ENTER = 30, + WKC_NUM_DECIMAL = 31, + + // Space + WKC_SPACE = 32, + + // Function keys + WKC_F1 = 33, + WKC_F2 = 34, + WKC_F3 = 35, + WKC_F4 = 36, + WKC_F5 = 37, + WKC_F6 = 38, + WKC_F7 = 39, + WKC_F8 = 40, + WKC_F9 = 41, + WKC_F10 = 42, + WKC_F11 = 43, + WKC_F12 = 44, + + // backquote is the key left of "1" + // we only store this key here, no matter what character is really mapped to it + // on a particular keyboard. (US keyboard: ` and ~ ; German keyboard: ^ and °) + WKC_BACKQUOTE = 45, + WKC_PAUSE = 46, + + // 0-9 are mapped to 48-57 + // A-Z are mapped to 65-90 + // a-z are mapped to 97-122 +}; + + typedef struct { const char *(*start)(const char * const *parm); void (*stop)(void); @@ -32,9 +111,9 @@ typedef struct { void (*set_volume)(byte vol); } HalMusicDriver; -VARDEF HalMusicDriver *_music_driver; -VARDEF HalSoundDriver *_sound_driver; -VARDEF HalVideoDriver *_video_driver; +extern HalMusicDriver *_music_driver; +extern HalSoundDriver *_sound_driver; +extern HalVideoDriver *_video_driver; enum DriverType { VIDEO_DRIVER = 0, @@ -42,8 +121,99 @@ enum DriverType { MUSIC_DRIVER = 2, }; +enum GameModes { + GM_MENU, + GM_NORMAL, + GM_EDITOR +}; + void GameLoop(void); void CreateConsole(void); +typedef int32 CursorID; +typedef byte Pixel; + +typedef struct Point { + int x,y; +} Point; + +typedef struct Rect { + int left,top,right,bottom; +} Rect; + + +typedef struct CursorVars { + Point pos, size, offs, delta; ///< position, size, offset from top-left, and movement + Point draw_pos, draw_size; ///< position and size bounding-box for drawing + CursorID sprite; ///< current image of cursor + + int wheel; ///< mouse wheel movement + const CursorID *animate_list, *animate_cur; ///< in case of animated cursor, list of frames + uint animate_timeout; ///< current frame in list of animated cursor + + bool visible; ///< cursor is visible + bool dirty; ///< the rect occupied by the mouse is dirty (redraw) + bool fix_at; ///< mouse is moving, but cursor is not (used for scrolling) + bool in_window; ///< mouse inside this window, determines drawing logic +} CursorVars; + +typedef struct DrawPixelInfo { + Pixel *dst_ptr; + int left, top, width, height; + int pitch; + uint16 zoom; +} DrawPixelInfo; + + +extern byte _dirkeys; // 1 = left, 2 = up, 4 = right, 8 = down +extern bool _fullscreen; +extern CursorVars _cursor; +extern bool _ctrl_pressed; // Is Ctrl pressed? +extern bool _shift_pressed; // Is Shift pressed? +extern byte _fast_forward; + +extern bool _left_button_down; +extern bool _left_button_clicked; +extern bool _right_button_down; +extern bool _right_button_clicked; + +extern DrawPixelInfo _screen; +extern bool _exit_game; +extern bool _networking; ///< are we in networking mode? +extern byte _game_mode; +extern byte _pause; + + +void HandleKeypress(uint32 key); +void HandleMouseEvents(void); +void CSleep(int milliseconds); +void UpdateWindows(void); + +uint32 InteractiveRandom(void); /* Used for random sequences that are not the same on the other end of the multiplayer link */ +uint InteractiveRandomRange(uint max); +void DrawTextMessage(void); +void DrawMouseCursor(void); +void ScreenSizeChanged(void); +void HandleExitGameRequest(void); +void GameSizeChanged(void); +void UndrawMouseCursor(void); + +extern int _pal_first_dirty; +extern int _pal_last_dirty; +extern int _num_resolutions; +extern uint16 _resolutions[32][2]; +extern uint16 _cur_resolution[2]; + +typedef struct Colour { + byte r; + byte g; + byte b; +} Colour; +extern Colour _cur_palette[256]; + +#ifdef __cplusplus +} // extern "C" +#endif //__cplusplus + #endif /* HAL_H */ diff --git a/src/heightmap.cpp b/src/heightmap.cpp index aeaa5c38e..57f4c30b1 100644 --- a/src/heightmap.cpp +++ b/src/heightmap.cpp @@ -13,6 +13,7 @@ #include "gui.h" #include "saveload.h" #include "bmp.h" +#include "helpers.hpp" /** * Convert RGB colors to Grayscale using 29.9% Red, 58.7% Green, 11.4% Blue @@ -135,7 +136,7 @@ static bool ReadHeightmapPNG(char *filename, uint *x, uint *y, byte **map) } if (map != NULL) { - *map = malloc(info_ptr->width * info_ptr->height * sizeof(byte)); + MallocT(/* NO & */map, info_ptr->width * info_ptr->height); if (*map == NULL) { ShowErrorMessage(STR_PNGMAP_ERR_MISC, STR_PNGMAP_ERROR, 0, 0); @@ -248,7 +249,7 @@ static bool ReadHeightmapBMP(char *filename, uint *x, uint *y, byte **map) return false; } - *map = malloc(info.width * info.height * sizeof(byte)); + MallocT(map, info.width * info.height); if (*map == NULL) { ShowErrorMessage(STR_PNGMAP_ERR_MISC, STR_BMPMAP_ERROR, 0, 0); fclose(f); diff --git a/src/helpers.cpp b/src/helpers.cpp index b78df5de8..d40078683 100644 --- a/src/helpers.cpp +++ b/src/helpers.cpp @@ -1,10 +1,8 @@ /* $Id$ */ #include "stdafx.h" -EXTERN_C_BEGIN #include "openttd.h" #include "engine.h" -EXTERN_C_END #include <new> #include "yapf/blob.hpp" diff --git a/src/helpers.hpp b/src/helpers.hpp new file mode 100644 index 000000000..b13fc25d4 --- /dev/null +++ b/src/helpers.hpp @@ -0,0 +1,178 @@ +/* $Id$ */ + +#ifndef HELPERS_HPP +#define HELPERS_HPP + +/** @file helpers.hpp */ +#include "macros.h" + +#ifdef __cplusplus + +/** When allocating using malloc/calloc in C++ it is usually needed to cast the return value +* from void* to the proper pointer type. Another alternative would be MallocT<> as follows */ +template <typename T> FORCEINLINE bool MallocT(T** t_ptr, size_t num_elements) +{ + *t_ptr = (T*)malloc(num_elements * sizeof(T)); + return (*t_ptr != NULL); +} +/** When allocating using malloc/calloc in C++ it is usually needed to cast the return value +* from void* to the proper pointer type. Another alternative would be MallocT<> as follows */ +template <typename T> FORCEINLINE bool CallocT(T** t_ptr, size_t num_elements) +{ + *t_ptr = (T*)calloc(num_elements, sizeof(T)); + return (*t_ptr != NULL); +} +/** When allocating using malloc/calloc in C++ it is usually needed to cast the return value +* from void* to the proper pointer type. Another alternative would be MallocT<> as follows */ +template <typename T> FORCEINLINE bool ReallocT(T** t_ptr, size_t num_elements) +{ + *t_ptr = (T*)realloc(*t_ptr, num_elements * sizeof(T)); + return (*t_ptr != NULL); +} + +/** type safe swap operation */ +template <typename T> void SwapT(T *a, T *b); + +template <typename T> FORCEINLINE void SwapT(T *a, T *b) +{ + T t = *a; + *a = *b; + *b = t; +} + + +/** returns the absolute value of (scalar) variable. @note assumes variable to be signed */ +template <typename T> static inline T myabs(T a) { return a < (T)0 ? -a : a; } +/** returns the (absolute) difference between two (scalar) variables */ +template <typename T> static inline T delta(T a, T b) { return a < b ? b - a : a - b; } + +/** Some enums need to have allowed incrementing (i.e. StationClassID) */ +#define DECLARE_POSTFIX_INCREMENT(type) \ + FORCEINLINE type operator ++(type& e, int) \ + { \ + type e_org = e; \ + e = (type)((int)e + 1); \ + return e_org; \ + } \ + FORCEINLINE type operator --(type& e, int) \ + { \ + type e_org = e; \ + e = (type)((int)e - 1); \ + return e_org; \ + } + + + +/** Operators to allow to work with enum as with type safe bit set in C++ */ +# define DECLARE_ENUM_AS_BIT_SET(mask_t) \ + FORCEINLINE mask_t operator | (mask_t m1, mask_t m2) {return (mask_t)((int)m1 | m2);} \ + FORCEINLINE mask_t operator & (mask_t m1, mask_t m2) {return (mask_t)((int)m1 & m2);} \ + FORCEINLINE mask_t operator ^ (mask_t m1, mask_t m2) {return (mask_t)((int)m1 ^ m2);} \ + FORCEINLINE mask_t& operator |= (mask_t& m1, mask_t m2) {m1 = m1 | m2; return m1;} \ + FORCEINLINE mask_t& operator &= (mask_t& m1, mask_t m2) {m1 = m1 & m2; return m1;} \ + FORCEINLINE mask_t& operator ^= (mask_t& m1, mask_t m2) {m1 = m1 ^ m2; return m1;} \ + FORCEINLINE mask_t operator ~(mask_t m) {return (mask_t)(~(int)m);} + +/** probably redundant enum combining operators (as we have conversion functions) + * but the old code is full of such arithmetics */ +# define DECLARE_ENUM_AS_BIT_INDEX(idx_t, mask_t) \ + FORCEINLINE mask_t operator << (int m, idx_t i) {return (mask_t)(m << (int)i);} \ + FORCEINLINE mask_t operator << (mask_t m, int i) {return (mask_t)(((int)m) << i);} \ + FORCEINLINE mask_t operator >> (mask_t m, int i) {return (mask_t)(((int)m) >> i);} + + +/** Informative template class exposing basic enumeration properties used by several + * other templates below. Here we have only forward declaration. For each enum type + * we will create specialization derived from MakeEnumPropsT<>. */ +template <typename Tenum_t> struct EnumPropsT; + +/** Helper template class that makes basic properties of given enumeration type visible + * from outsize. It is used as base class of several EnumPropsT specializations each + * dedicated to one of commonly used enumeration types. */ +template <typename Tenum_t, typename Tstorage_t, Tenum_t Tbegin, Tenum_t Tend, Tenum_t Tinvalid> +struct MakeEnumPropsT { + typedef Tenum_t type; ///< enum type (i.e. Trackdir) + typedef Tstorage_t storage; ///< storage type (i.e. byte) + static const Tenum_t begin = Tbegin; ///< lowest valid value (i.e. TRACKDIR_BEGIN) + static const Tenum_t end = Tend; ///< one after the last valid value (i.e. TRACKDIR_END) + static const Tenum_t invalid = Tinvalid; ///< what value is used as invalid value (i.e. INVALID_TRACKDIR) +}; + + + +/** In some cases we use byte or uint16 to store values that are defined as enum. It is + * necessary in order to control the sizeof() such values. Some compilers make enum + * the same size as int (4 or 8 bytes instead of 1 or 2). As a consequence the strict + * compiler type-checking causes errors like: + * 'HasPowerOnRail' : cannot convert parameter 1 from 'byte' to 'RailType' when + * u->u.rail.railtype is passed as argument or type RailType. In such cases it is better + * to teach the compiler that u->u.rail.railtype is to be treated as RailType. */ +template <typename Tenum_t> struct TinyEnumT; + +/** The general declaration of TinyEnumT<> (above) */ +template <typename Tenum_t> struct TinyEnumT +{ + typedef Tenum_t enum_type; ///< expose our enumeration type (i.e. Trackdir) to outside + typedef EnumPropsT<Tenum_t> Props; ///< make easier access to our enumeration propeties + typedef typename Props::storage storage_type; ///< small storage type + static const enum_type begin = Props::begin; ///< enum beginning (i.e. TRACKDIR_BEGIN) + static const enum_type end = Props::end; ///< enum end (i.e. TRACKDIR_END) + static const enum_type invalid = Props::invalid;///< invalid value (i.e. INVALID_TRACKDIR) + + storage_type m_val; ///< here we hold the actual value in small (i.e. byte) form + + /** Cast operator - invoked then the value is assigned to the Tenum_t type */ + FORCEINLINE operator enum_type () const + { + return (enum_type)m_val; + } + + /** Assignment operator (from Tenum_t type) */ + FORCEINLINE TinyEnumT& operator = (enum_type e) + { + m_val = (storage_type)e; return *this; + } + + /** postfix ++ operator on tiny type */ + FORCEINLINE TinyEnumT& operator ++ (int) + { + if (++m_val >= end) m_val -= (storage_type)(end - begin); + return *this; + } +}; + +template <typename Tenum_t> FORCEINLINE void SwapT(TinyEnumT<Tenum_t> *a, TinyEnumT<Tenum_t> *b) +{ + SwapT(&a->m_val, &b->m_val); +} + +template <typename T> FORCEINLINE T ClrBitT(T t, int bit_index) +{ + int val = t; + CLRBIT(val, bit_index); + return (T)val; +} + +template <typename T> FORCEINLINE T SetBitT(T t, int bit_index) +{ + int val = t; + SETBIT(val, bit_index); + return (T)val; +} + +template <typename T> FORCEINLINE T ToggleBitT(T t, int bit_index) +{ + int val = t; + TOGGLEBIT(val, bit_index); + return (T)val; +} + +#else // __cplusplus + +#define DECLARE_POSTFIX_INCREMENT(E) +#define DECLARE_ENUM_AS_BIT_SET(E) +#define DECLARE_ENUM_AS_BIT_INDEX(E1,E2) + +#endif // __cplusplus + +#endif /* HELPERS_HPP */ diff --git a/src/industry.h b/src/industry.h index f8cf63c82..a7b532381 100644 --- a/src/industry.h +++ b/src/industry.h @@ -36,7 +36,7 @@ struct Industry { uint16 counter; byte type; - byte owner; + OwnerByte owner; byte random_color; Year last_prod_year; byte was_cargo_delivered; diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp index 38e2c516b..5b37939c0 100644 --- a/src/industry_cmd.cpp +++ b/src/industry_cmd.cpp @@ -765,14 +765,14 @@ static void SetupFarmFieldFence(TileIndex tile, int size, byte type, Axis direct tile = TILE_MASK(tile); if (IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) { - byte or = type; + byte or_ = type; - if (or == 1 && CHANCE16(1, 7)) or = 2; + if (or_ == 1 && CHANCE16(1, 7)) or_ = 2; if (direction == AXIS_X) { - SetFenceSE(tile, or); + SetFenceSE(tile, or_); } else { - SetFenceSW(tile, or); + SetFenceSW(tile, or_); } } @@ -942,7 +942,7 @@ static void ProduceIndustryGoods(Industry *i) if ((i->counter & 0x3F) == 0) { if (CHANCE16R(1,14,r) && (num=_industry_sounds[i->type][0]) != 0) { SndPlayTileFx( - _industry_sounds[i->type][1] + (((r >> 16) * num) >> 16), + (SoundFx)(_industry_sounds[i->type][1] + (((r >> 16) * num) >> 16)), i->xy); } } @@ -1225,7 +1225,7 @@ static bool CheckCanTerraformSurroundingTiles(TileIndex tile, uint height, int i return false; /* Don't allow too big of a change if this is the sub-tile check */ - if (internal != 0 && myabs(curh - height) > 1) return false; + if (internal != 0 && delta(curh, height) > 1) return false; /* Different height, so the surrounding tiles of this tile * has to be correct too (in level, or almost in level) @@ -1353,7 +1353,7 @@ static Industry *AllocateIndustry(void) return AddBlockToPool(&_Industry_pool) ? AllocateIndustry() : NULL; } -static void DoCreateNewIndustry(Industry *i, TileIndex tile, int type, const IndustryTileTable *it, const Town *t, byte owner) +static void DoCreateNewIndustry(Industry *i, TileIndex tile, int type, const IndustryTileTable *it, const Town *t, Owner owner) { const IndustrySpec *indspec = GetIndustrySpec(type); uint32 r; @@ -1595,25 +1595,25 @@ static void ExtChangeIndustryProduction(Industry *i) default: /* INDUSTRY_PRODUCTION */ for (j = 0; j < 2 && i->produced_cargo[j] != CT_INVALID; j++){ uint32 r = Random(); - int old, new, percent; + int old_prod, new_prod, percent; int mag; - new = old = i->production_rate[j]; + new_prod = old_prod = i->production_rate[j]; if (CHANCE16I(20, 1024, r)) - new -= ((RandomRange(50) + 10) * old) >> 8; + new_prod -= ((RandomRange(50) + 10) * old_prod) >> 8; if (CHANCE16I(20 + (i->pct_transported[j] * 20 >> 8), 1024, r >> 16)) - new += ((RandomRange(50) + 10) * old) >> 8; + new_prod += ((RandomRange(50) + 10) * old_prod) >> 8; - new = clamp(new, 0, 255); - if (new == old) { + new_prod = clamp(new_prod, 0, 255); + if (new_prod == old_prod) { closeit = false; continue; } - percent = new * 100 / old - 100; - i->production_rate[j] = new; + percent = new_prod * 100 / old_prod - 100; + i->production_rate[j] = new_prod; - if (new >= indspec->production_rate[j] / 4) + if (new_prod >= indspec->production_rate[j] / 4) closeit = false; mag = abs(percent); @@ -1827,7 +1827,7 @@ void InitializeIndustries(void) _industry_sound_tile = 0; } -const TileTypeProcs _tile_type_industry_procs = { +extern const TileTypeProcs _tile_type_industry_procs = { DrawTile_Industry, /* draw_tile_proc */ GetSlopeZ_Industry, /* get_slope_z_proc */ ClearTile_Industry, /* clear_tile_proc */ @@ -1905,6 +1905,6 @@ static void Load_INDY(void) } } -const ChunkHandler _industry_chunk_handlers[] = { +extern const ChunkHandler _industry_chunk_handlers[] = { { 'INDY', Save_INDY, Load_INDY, CH_ARRAY | CH_LAST}, }; diff --git a/src/industry_gui.cpp b/src/industry_gui.cpp index 3e481ef88..7247036a4 100644 --- a/src/industry_gui.cpp +++ b/src/industry_gui.cpp @@ -16,6 +16,7 @@ #include "industry.h" #include "town.h" #include "variables.h" +#include "helpers.hpp" const byte _build_industry_types[4][12] = { { 1, 2, 4, 6, 8, 0, 3, 5, 9, 11, 18 }, @@ -559,7 +560,7 @@ static void MakeSortedIndustryList(void) if (GetNumIndustries() == 0) return; /* Create array for sorting */ - _industry_sort = realloc((void *)_industry_sort, (GetMaxIndustryIndex() + 1) * sizeof(_industry_sort[0])); + ReallocT(&_industry_sort, GetMaxIndustryIndex() + 1); if (_industry_sort == NULL) error("Could not allocate memory for the industry-sorting-list"); FOR_ALL_INDUSTRIES(i) _industry_sort[n++] = i; diff --git a/src/landscape.cpp b/src/landscape.cpp index 2d8b7205b..2f05fc2ba 100644 --- a/src/landscape.cpp +++ b/src/landscape.cpp @@ -55,7 +55,7 @@ const byte _tileh_to_sprite[32] = { 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 17, 0, 15, 18, 0, }; -const byte _inclined_tileh[] = { +const Slope _inclined_tileh[] = { SLOPE_SW, SLOPE_NW, SLOPE_SW, SLOPE_SE, SLOPE_NE, SLOPE_SE, SLOPE_NE, SLOPE_NW, SLOPE_E, SLOPE_N, SLOPE_W, SLOPE_S, SLOPE_NWS, SLOPE_WSE, SLOPE_SEN, SLOPE_ENW @@ -276,7 +276,7 @@ uint32 GetTileTrackStatus(TileIndex tile, TransportType mode) return _tile_type_procs[GetTileType(tile)]->get_tile_track_status_proc(tile, mode); } -void ChangeTileOwner(TileIndex tile, byte old_player, byte new_player) +void ChangeTileOwner(TileIndex tile, PlayerID old_player, PlayerID new_player) { _tile_type_procs[GetTileType(tile)]->change_tile_owner_proc(tile, old_player, new_player); } @@ -468,13 +468,13 @@ static void GenerateTerrain(int type, int flag) uint y; uint w; uint h; - const Sprite* template; + const Sprite* templ; const byte *p; Tile* tile; byte direction; r = Random(); - template = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + 4845); + templ = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + 4845); x = r & MapMaxX(); y = (r >> MapLogX()) & MapMaxY(); @@ -484,13 +484,13 @@ static void GenerateTerrain(int type, int flag) direction = GB(r, 22, 2); if (direction & 1) { - w = template->height; - h = template->width; + w = templ->height; + h = templ->width; } else { - w = template->width; - h = template->height; + w = templ->width; + h = templ->height; } - p = template->data; + p = templ->data; if (flag & 4) { uint xw = x * MapSizeY(); diff --git a/src/livery.h b/src/livery.h index 2655dcd48..76b5c7e28 100644 --- a/src/livery.h +++ b/src/livery.h @@ -3,10 +3,12 @@ #ifndef LIVERY_H #define LIVERY_H +#include "helpers.hpp" /* List of different livery schemes. */ typedef enum LiverySchemes { - LS_DEFAULT, + LS_BEGIN = 0, + LS_DEFAULT = 0, /* Rail vehicles */ LS_STEAM, @@ -37,6 +39,7 @@ typedef enum LiverySchemes { LS_END } LiveryScheme; +DECLARE_POSTFIX_INCREMENT(LiveryScheme); /* List of different livery classes, used only by the livery GUI. */ typedef enum LiveryClasses { diff --git a/src/macros.h b/src/macros.h index 8e310c07e..644f178af 100644 --- a/src/macros.h +++ b/src/macros.h @@ -20,9 +20,10 @@ #undef max #endif -static inline int min(int a, int b) { if (a <= b) return a; return b; } static inline int max(int a, int b) { if (a >= b) return a; return b; } -static inline int64 max64(int64 a, int64 b) { if (a >= b) return a; return b; } +static inline double dmax(double a, double b) { if (a >= b) return a; return b; } +static inline uint64 max64(uint64 a, uint64 b) { if (a >= b) return a; return b; } +static inline int min(int a, int b) { if (a <= b) return a; return b; } static inline uint minu(uint a, uint b) { if (a <= b) return a; return b; } static inline uint maxu(uint a, uint b) { if (a >= b) return a; return b; } @@ -136,15 +137,11 @@ static inline int KillFirstBit2x64(int value) #define abs myabs - static inline int intxchg_(int *a, int b) { int t = *a; *a = b; return t; } #define intswap(a,b) ((b) = intxchg_(&(a), (b))) static inline int uintxchg_(uint *a, uint b) { uint t = *a; *a = b; return t; } #define uintswap(a,b) ((b) = uintxchg_(&(a), (b))) -static inline int myabs(int a) { if (a<0) a = -a; return a; } -static inline int64 myabs64(int64 a) { if (a<0) a = -a; return a; } - static inline void swap_byte(byte *a, byte *b) { byte t = *a; *a = *b; *b = t; } static inline void swap_uint16(uint16 *a, uint16 *b) { uint16 t = *a; *a = *b; *b = t; } static inline void swap_int16(int16 *a, int16 *b) { int16 t = *a; *a = *b; *b = t; } diff --git a/src/main_gui.cpp b/src/main_gui.cpp index e2b816e75..556a8feb4 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -215,12 +215,12 @@ static void MenuClickSubsidies(int index) static void MenuClickStations(int index) { - ShowPlayerStations(index); + ShowPlayerStations((PlayerID)index); } static void MenuClickFinances(int index) { - ShowPlayerFinances(index); + ShowPlayerFinances((PlayerID)index); } static void MenuClickCompany(int index) @@ -229,7 +229,7 @@ static void MenuClickCompany(int index) ShowClientList(); } else { if (_networking) index--; - ShowPlayerCompany(index); + ShowPlayerCompany((PlayerID)index); } } @@ -263,27 +263,27 @@ static void MenuClickIndustry(int index) static void MenuClickShowTrains(int index) { - ShowVehicleListWindow(index, INVALID_STATION, VEH_Train); + ShowVehicleListWindow((PlayerID)index, INVALID_STATION, VEH_Train); } static void MenuClickShowRoad(int index) { - ShowVehicleListWindow(index, INVALID_STATION, VEH_Road); + ShowVehicleListWindow((PlayerID)index, INVALID_STATION, VEH_Road); } static void MenuClickShowShips(int index) { - ShowVehicleListWindow(index, INVALID_STATION, VEH_Ship); + ShowVehicleListWindow((PlayerID)index, INVALID_STATION, VEH_Ship); } static void MenuClickShowAir(int index) { - ShowVehicleListWindow(index, INVALID_STATION, VEH_Aircraft); + ShowVehicleListWindow((PlayerID)index, INVALID_STATION, VEH_Aircraft); } static void MenuClickBuildRail(int index) { - _last_built_railtype = index; + _last_built_railtype = (RailType)index; ShowBuildRailToolbar(_last_built_railtype, -1); } @@ -1564,7 +1564,7 @@ static bool AnyTownExists(void) return false; } -extern Industry *CreateNewIndustry(TileIndex tile, int type); +extern Industry *CreateNewIndustry(TileIndex tile, IndustryType type); /** * Search callback function for TryBuildIndustry @@ -2283,7 +2283,7 @@ static void MainWindowWndProc(Window *w, WindowEvent *e) case '1' | WKC_ALT: /* Gimme money */ /* Server can not cheat in advertise mode either! */ if (!_networking || !_network_server || !_network_advertise) - DoCommandP(0, -10000000, 0, NULL, CMD_MONEY_CHEAT); + DoCommandP(0, 10000000, 0, NULL, CMD_MONEY_CHEAT); break; case '2' | WKC_ALT: /* Update the coordinates of all station signs */ @@ -2430,7 +2430,7 @@ void GameSizeChanged(void) void InitializeMainGui(void) { /* Clean old GUI values */ - _last_built_railtype = 0; + _last_built_railtype = RAILTYPE_RAIL; } diff --git a/src/map.cpp b/src/map.cpp index df16343c7..05a51d8e8 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -7,10 +7,11 @@ #include "macros.h" #include "map.h" #include "direction.h" +#include "helpers.hpp" #if defined(_MSC_VER) && _MSC_VER >= 1400 /* VStudio 2005 is stupid! */ /* Why the hell is that not in all MSVC headers?? */ -_CRTIMP void __cdecl _assert(void *, void *, unsigned); +extern "C" _CRTIMP void __cdecl _assert(void *, void *, unsigned); #endif uint _map_log_x; @@ -41,7 +42,7 @@ void AllocateMap(uint size_x, uint size_y) _map_tile_mask = _map_size - 1; free(_m); - _m = calloc(_map_size, sizeof(*_m)); + CallocT(&_m, _map_size); // XXX TODO handle memory shortage more gracefully if (_m == NULL) error("Failed to allocate memory for the map"); @@ -121,14 +122,14 @@ uint TileAddWrap(TileIndex tile, int addx, int addy) return INVALID_TILE; } -const TileIndexDiffC _tileoffs_by_diagdir[] = { +extern const TileIndexDiffC _tileoffs_by_diagdir[] = { {-1, 0}, // DIAGDIR_NE { 0, 1}, // DIAGDIR_SE { 1, 0}, // DIAGDIR_SW { 0, -1} // DIAGDIR_NW }; -const TileIndexDiffC _tileoffs_by_dir[] = { +extern const TileIndexDiffC _tileoffs_by_dir[] = { {-1, -1}, // DIR_N {-1, 0}, // DIR_NE {-1, 1}, // DIR_E @@ -141,8 +142,8 @@ const TileIndexDiffC _tileoffs_by_dir[] = { uint DistanceManhattan(TileIndex t0, TileIndex t1) { - const uint dx = abs(TileX(t0) - TileX(t1)); - const uint dy = abs(TileY(t0) - TileY(t1)); + const uint dx = delta(TileX(t0), TileX(t1)); + const uint dy = delta(TileY(t0), TileY(t1)); return dx + dy; } @@ -157,16 +158,16 @@ uint DistanceSquare(TileIndex t0, TileIndex t1) uint DistanceMax(TileIndex t0, TileIndex t1) { - const uint dx = abs(TileX(t0) - TileX(t1)); - const uint dy = abs(TileY(t0) - TileY(t1)); + const uint dx = delta(TileX(t0), TileX(t1)); + const uint dy = delta(TileY(t0), TileY(t1)); return dx > dy ? dx : dy; } uint DistanceMaxPlusManhattan(TileIndex t0, TileIndex t1) { - const uint dx = abs(TileX(t0) - TileX(t1)); - const uint dy = abs(TileY(t0) - TileY(t1)); + const uint dx = delta(TileX(t0), TileX(t1)); + const uint dy = delta(TileY(t0), TileY(t1)); return dx > dy ? 2 * dx + dy : 2 * dy + dx; } @@ -67,13 +67,6 @@ static inline TileIndex TileVirtXY(uint x, uint y) return (y >> 4 << MapLogX()) + (x >> 4); } -typedef byte Owner; -enum Owners { - OWNER_TOWN = 0x0F, // a town owns the tile - OWNER_NONE = 0x10, // nobody owns the tile - OWNER_WATER = 0x11, // "water" owns the tile - OWNER_END = 0x12, -}; enum { INVALID_TILE = (TileIndex)-1 diff --git a/src/misc.cpp b/src/misc.cpp index fd3a74b79..d753445e9 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -611,13 +611,13 @@ static void Load_CHTS(void) uint i; for (i = 0; i < count; i++) { - cht[i].been_used = SlReadByte(); - cht[i].value = SlReadByte(); + cht[i].been_used = (SlReadByte() != 0); + cht[i].value = (SlReadByte() != 0); } } -const ChunkHandler _misc_chunk_handlers[] = { +extern const ChunkHandler _misc_chunk_handlers[] = { { 'MAPS', Save_MAPS, Load_MAPS, CH_RIFF }, { 'MAPT', Save_MAPT, Load_MAPT, CH_RIFF }, { 'MAPO', Save_MAP1, Load_MAP1, CH_RIFF }, diff --git a/src/misc_cmd.cpp b/src/misc_cmd.cpp index 94b675531..9eb9e6647 100644 --- a/src/misc_cmd.cpp +++ b/src/misc_cmd.cpp @@ -40,7 +40,7 @@ int32 CmdSetPlayerColor(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) { Player *p, *pp; byte colour; - LiveryScheme scheme = GB(p1, 0, 8); + LiveryScheme scheme = (LiveryScheme)GB(p1, 0, 8); byte state = GB(p1, 8, 2); if (p2 >= 16) return CMD_ERROR; // max 16 colours @@ -271,7 +271,7 @@ int32 CmdMoneyCheat(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (_networking) return CMD_ERROR; #endif SET_EXPENSES_TYPE(EXPENSES_OTHER); - return (int32)p1; + return -(int32)p1; } /** Transfer funds (money) from one player to another. @@ -296,7 +296,7 @@ int32 CmdGiveMoney(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (flags & DC_EXEC) { /* Add money to player */ PlayerID old_cp = _current_player; - _current_player = p2; + _current_player = (PlayerID)p2; SubtractMoneyFromPlayer(-amount); _current_player = old_cp; } diff --git a/src/misc_gui.cpp b/src/misc_gui.cpp index c80126f7a..0da96faf7 100644 --- a/src/misc_gui.cpp +++ b/src/misc_gui.cpp @@ -95,7 +95,7 @@ static void Place_LandInfo(TileIndex tile) w = AllocateWindowDesc(&_land_info_desc); WP(w, void_d).data = &_landinfo_data; - p = GetPlayer(IsValidPlayer(_local_player) ? _local_player : 0); + p = GetPlayer(IsValidPlayer(_local_player) ? _local_player : PLAYER_FIRST); t = ClosestTownFromTile(tile, _patches.dist_local_authority); old_money = p->money64; @@ -166,7 +166,7 @@ static void Place_LandInfo(TileIndex tile) if (td.build_date != 0) { SetDParam(0, td.build_date); - GetString(_landinfo_data[6], STR_BUILD_DATE, lastof(_landinfo_data[6])); + GetString(_landinfo_data[6], STR_BUILD_DATE, lastof(_landinfo_data[6])); } else { _landinfo_data[6][0] = '\0'; } @@ -505,7 +505,7 @@ static void ErrmsgWndProc(Window *w, WindowEvent *e) _errmsg_message_1, 238); } else { - const Player *p = GetPlayer(GetDParamX(_errmsg_decode_params,2)); + const Player *p = GetPlayer((PlayerID)GetDParamX(_errmsg_decode_params,2)); DrawPlayerFace(p->face, p->player_color, 2, 16); DrawStringMultiCenter( @@ -1383,7 +1383,7 @@ static void GenerateFileName(void) { /* Check if we are not a specatator who wants to generate a name.. Let's use the name of player #0 for now. */ - const Player *p = GetPlayer(IsValidPlayer(_local_player) ? _local_player : 0); + const Player *p = GetPlayer(IsValidPlayer(_local_player) ? _local_player : PLAYER_FIRST); SetDParam(0, p->name_1); SetDParam(1, p->name_2); @@ -1691,7 +1691,7 @@ void SetFiosType(const byte fiostype) static int32 ClickMoneyCheat(int32 p1, int32 p2) { - DoCommandP(0, -10000000, 0, NULL, CMD_MONEY_CHEAT); + DoCommandP(0, 10000000, 0, NULL, CMD_MONEY_CHEAT); return true; } @@ -1739,9 +1739,17 @@ static int32 ClickChangeDateCheat(int32 p1, int32 p2) typedef int32 CheckButtonClick(int32, int32); -enum ce_flags {CE_CLICK = 1 << 0}; +enum ce_flags_long +{ + CE_NONE = 0, + CE_CLICK = 1 << 0, + CE_END = 1 << 1, +}; + +/** Define basic enum properties */ +template <> struct EnumPropsT<ce_flags_long> : MakeEnumPropsT<ce_flags_long, byte, CE_NONE, CE_END, CE_END> {}; +typedef TinyEnumT<ce_flags_long> ce_flags; -typedef byte ce_flags; typedef struct CheatEntry { VarType type; // type of selector @@ -1754,15 +1762,15 @@ typedef struct CheatEntry { } CheatEntry; static const CheatEntry _cheats_ui[] = { - {SLE_BOOL,CE_CLICK, STR_CHEAT_MONEY, &_cheats.money.value, &_cheats.money.been_used, &ClickMoneyCheat, 0, 0}, - {SLE_UINT8, 0, STR_CHEAT_CHANGE_PLAYER, &_local_player, &_cheats.switch_player.been_used, &ClickChangePlayerCheat, 0, 11}, - {SLE_BOOL, 0, STR_CHEAT_EXTRA_DYNAMITE, &_cheats.magic_bulldozer.value, &_cheats.magic_bulldozer.been_used, NULL, 0, 0}, - {SLE_BOOL, 0, STR_CHEAT_CROSSINGTUNNELS,&_cheats.crossing_tunnels.value,&_cheats.crossing_tunnels.been_used,NULL, 0, 0}, - {SLE_BOOL, 0, STR_CHEAT_BUILD_IN_PAUSE, &_cheats.build_in_pause.value, &_cheats.build_in_pause.been_used, NULL, 0, 0}, - {SLE_BOOL, 0, STR_CHEAT_NO_JETCRASH, &_cheats.no_jetcrash.value, &_cheats.no_jetcrash.been_used, NULL, 0, 0}, - {SLE_BOOL, 0, STR_CHEAT_SETUP_PROD, &_cheats.setup_prod.value, &_cheats.setup_prod.been_used, NULL, 0, 0}, - {SLE_UINT8, 0, STR_CHEAT_SWITCH_CLIMATE, &_opt.landscape, &_cheats.switch_climate.been_used, &ClickChangeClimateCheat,-1, 4}, - {SLE_INT32, 0, STR_CHEAT_CHANGE_DATE, &_cur_year, &_cheats.change_date.been_used, &ClickChangeDateCheat, -1, 1}, + {SLE_BOOL, {CE_CLICK}, STR_CHEAT_MONEY, &_cheats.money.value, &_cheats.money.been_used, &ClickMoneyCheat, 0, 0}, + {SLE_UINT8, {CE_NONE}, STR_CHEAT_CHANGE_PLAYER, &_local_player, &_cheats.switch_player.been_used, &ClickChangePlayerCheat, 0, 11}, + {SLE_BOOL, {CE_NONE}, STR_CHEAT_EXTRA_DYNAMITE, &_cheats.magic_bulldozer.value, &_cheats.magic_bulldozer.been_used, NULL, 0, 0}, + {SLE_BOOL, {CE_NONE}, STR_CHEAT_CROSSINGTUNNELS,&_cheats.crossing_tunnels.value,&_cheats.crossing_tunnels.been_used,NULL, 0, 0}, + {SLE_BOOL, {CE_NONE}, STR_CHEAT_BUILD_IN_PAUSE, &_cheats.build_in_pause.value, &_cheats.build_in_pause.been_used, NULL, 0, 0}, + {SLE_BOOL, {CE_NONE}, STR_CHEAT_NO_JETCRASH, &_cheats.no_jetcrash.value, &_cheats.no_jetcrash.been_used, NULL, 0, 0}, + {SLE_BOOL, {CE_NONE}, STR_CHEAT_SETUP_PROD, &_cheats.setup_prod.value, &_cheats.setup_prod.been_used, NULL, 0, 0}, + {SLE_UINT8, {CE_NONE}, STR_CHEAT_SWITCH_CLIMATE, &_opt.landscape, &_cheats.switch_climate.been_used, &ClickChangeClimateCheat,-1, 4}, + {SLE_INT32, {CE_NONE}, STR_CHEAT_CHANGE_DATE, &_cur_year, &_cheats.change_date.been_used, &ClickChangeDateCheat, -1, 1}, }; @@ -1801,14 +1809,14 @@ static void CheatsWndProc(Window *w, WindowEvent *e) bool on = (*(bool*)ce->variable); if (ce->flags & CE_CLICK) { - DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, 0, (clk - (i * 2) == 1) ? FR_LOWERED : 0); + DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, 0, (clk - (i * 2) == 1) ? FR_LOWERED : FR_NONE); if (i == 0) { // XXX - hack/hack for first element which is increase money. Told ya it's a mess SetDParam64(0, 10000000); } else { SetDParam(0, false); } } else { - DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, on ? 6 : 4, on ? FR_LOWERED : 0); + DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, on ? 6 : 4, on ? FR_LOWERED : FR_NONE); SetDParam(0, on ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF); } } break; diff --git a/src/mixer.cpp b/src/mixer.cpp index 5b97afbf9..5037f771b 100644 --- a/src/mixer.cpp +++ b/src/mixer.cpp @@ -85,7 +85,7 @@ void MxMixSamples(void *buffer, uint samples) // Mix each channel for (mc = _channels; mc != endof(_channels); mc++) { if (mc->active) { - mix_int8_to_int16(mc, buffer, samples); + mix_int8_to_int16(mc, (int16*)buffer, samples); if (mc->samples_left == 0) MxCloseChannel(mc); } } diff --git a/src/music/dmusic.cpp b/src/music/dmusic.cpp index e20842d2e..1c5b1d200 100644 --- a/src/music/dmusic.cpp +++ b/src/music/dmusic.cpp @@ -4,12 +4,10 @@ #ifdef WIN32_ENABLE_DIRECTMUSIC_SUPPORT -extern "C" { - #include "../openttd.h" - #include "../debug.h" - #include "../win32.h" - #include "dmusic.h" -} +#include "../openttd.h" +#include "../debug.h" +#include "../win32.h" +#include "dmusic.h" #include <windows.h> #include <dmksctrl.h> diff --git a/src/music_gui.cpp b/src/music_gui.cpp index 37cd3fa79..620346e7e 100644 --- a/src/music_gui.cpp +++ b/src/music_gui.cpp @@ -396,11 +396,11 @@ static void MusicWindowWndProc(Window *w, WindowEvent *e) DrawFrameRect(214, 23, 280, 26, 14, FR_LOWERED); DrawFrameRect( - 108 + msf.music_vol / 2, 22, 111 + msf.music_vol / 2, 28, 14, 0 + 108 + msf.music_vol / 2, 22, 111 + msf.music_vol / 2, 28, 14, FR_NONE ); DrawFrameRect( - 214 + msf.effect_vol / 2, 22, 217 + msf.effect_vol / 2, 28, 14, 0 + 214 + msf.effect_vol / 2, 22, 217 + msf.effect_vol / 2, 28, 14, FR_NONE ); } break; diff --git a/src/network/core/packet.cpp b/src/network/core/packet.cpp index d75d78c7e..38d00d8c0 100644 --- a/src/network/core/packet.cpp +++ b/src/network/core/packet.cpp @@ -5,6 +5,8 @@ #include "../../stdafx.h" #include "../../macros.h" #include "../../string.h" +#include "../../helpers.hpp" +#include "../network_data.h" #include "packet.h" @@ -24,7 +26,8 @@ extern void NORETURN CDECL error(const char *str, ...); */ Packet *NetworkSend_Init(const PacketType type) { - Packet *packet = malloc(sizeof(Packet)); + Packet *packet; + MallocT(&packet, 1); /* An error is inplace here, because it simply means we ran out of memory. */ if (packet == NULL) error("Failed to allocate Packet"); @@ -109,7 +112,7 @@ void NetworkSend_string(Packet *packet, const char* data) */ -extern uint CloseConnection(NetworkClientState *cs); +extern NetworkRecvStatus CloseConnection(NetworkClientState *cs); /** Is it safe to read from the packet, i.e. didn't we run over the buffer ? */ static inline bool CanReadFromPacket(NetworkClientState *cs, const Packet *packet, const uint bytes_to_read) diff --git a/src/network/core/tcp.cpp b/src/network/core/tcp.cpp index 9261ea049..ce00335fe 100644 --- a/src/network/core/tcp.cpp +++ b/src/network/core/tcp.cpp @@ -12,6 +12,7 @@ #include "../network_data.h" #include "packet.h" #include "tcp.h" +#include "../../helpers.hpp" /** * @file tcp.c Basic functions to receive and send TCP packets. @@ -99,7 +100,7 @@ bool NetworkSend_Packets(NetworkClientState *cs) p = cs->packet_queue; while (p != NULL) { - res = send(cs->socket, p->buffer + p->pos, p->size - p->pos, 0); + res = send(cs->socket, (const char*)p->buffer + p->pos, p->size - p->pos, 0); if (res == -1) { int err = GET_LAST_ERROR(); if (err != EWOULDBLOCK) { @@ -148,7 +149,7 @@ Packet *NetworkRecv_Packet(NetworkClientState *cs, NetworkRecvStatus *status) if (cs->socket == INVALID_SOCKET) return NULL; if (cs->packet_recv == NULL) { - cs->packet_recv = malloc(sizeof(Packet)); + MallocT(&cs->packet_recv, 1); if (cs->packet_recv == NULL) error("Failed to allocate packet"); /* Set pos to zero! */ cs->packet_recv->pos = 0; @@ -161,7 +162,7 @@ Packet *NetworkRecv_Packet(NetworkClientState *cs, NetworkRecvStatus *status) if (p->pos < sizeof(PacketSize)) { while (p->pos < sizeof(PacketSize)) { /* Read the size of the packet */ - res = recv(cs->socket, p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0); + res = recv(cs->socket, (char*)p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0); if (res == -1) { int err = GET_LAST_ERROR(); if (err != EWOULDBLOCK) { @@ -191,7 +192,7 @@ Packet *NetworkRecv_Packet(NetworkClientState *cs, NetworkRecvStatus *status) /* Read rest of packet */ while (p->pos < p->size) { - res = recv(cs->socket, p->buffer + p->pos, p->size - p->pos, 0); + res = recv(cs->socket, (char*)p->buffer + p->pos, p->size - p->pos, 0); if (res == -1) { int err = GET_LAST_ERROR(); if (err != EWOULDBLOCK) { diff --git a/src/network/core/udp.cpp b/src/network/core/udp.cpp index 6699b4b87..91d751fd5 100644 --- a/src/network/core/udp.cpp +++ b/src/network/core/udp.cpp @@ -5,6 +5,7 @@ #include "../../stdafx.h" #include "../../debug.h" #include "../../macros.h" +#include "../../helpers.hpp" #include "packet.h" #include "udp.h" @@ -92,7 +93,7 @@ void NetworkSendUDP_Packet(const SOCKET udp, Packet *p, const struct sockaddr_in NetworkSend_FillPacketSize(p); /* Send the buffer */ - res = sendto(udp, p->buffer, p->size, 0, (struct sockaddr *)recv, sizeof(*recv)); + res = sendto(udp, (const char*)p->buffer, p->size, 0, (struct sockaddr *)recv, sizeof(*recv)); /* Check for any errors, but ignore it otherwise */ if (res == -1) DEBUG(net, 1, "[udp] sendto failed with: %i", GET_LAST_ERROR()); @@ -114,7 +115,7 @@ void NetworkUDPReceive(const SOCKET udp) client_len = sizeof(client_addr); /* Try to receive anything */ - nbytes = recvfrom(udp, p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len); + nbytes = recvfrom(udp, (char*)p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len); /* We got some bytes for the base header of the packet. */ if (nbytes > 2) { @@ -256,7 +257,7 @@ void NetworkRecv_NetworkGameInfo(NetworkClientState *cs, Packet *p, NetworkGameI uint num_grfs = NetworkRecv_uint8(cs, p); for (i = 0; i < num_grfs; i++) { - c = calloc(1, sizeof(*c)); + CallocT(&c, 1); NetworkRecv_GRFIdentifier(cs, p, c); HandleIncomingNetworkGameInfoGRFConfig(c); @@ -290,7 +291,7 @@ void NetworkRecv_NetworkGameInfo(NetworkClientState *cs, Packet *p, NetworkGameI info->map_width = NetworkRecv_uint16(cs, p); info->map_height = NetworkRecv_uint16(cs, p); info->map_set = NetworkRecv_uint8 (cs, p); - info->dedicated = NetworkRecv_uint8 (cs, p); + info->dedicated = (NetworkRecv_uint8 (cs, p) != 0); } } diff --git a/src/network/network.cpp b/src/network/network.cpp index ac8dd82b7..443ee3066 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -7,9 +7,9 @@ extern const char _openttd_revision[]; #elif defined(WITH_REV_HACK) #define WITH_REV - const char _openttd_revision[] = WITH_REV_HACK; + extern const char _openttd_revision[] = WITH_REV_HACK; #else - const char _openttd_revision[] = NOREV_STRING; + extern const char _openttd_revision[] = NOREV_STRING; #endif @@ -38,6 +38,19 @@ #include <stdarg.h> /* va_list */ #include "../md5.h" +// global variables (declared in network_data.h) +CommandPacket *_local_command_queue; + +SOCKET _udp_client_socket; // udp client socket +SOCKET _udp_server_socket; // udp server socket +SOCKET _udp_master_socket; // udp master socket + +// Here we keep track of the clients +// (and the client uses [0] for his own communication) +NetworkClientState _clients[MAX_CLIENTS]; + + + // The listen socket for the server static SOCKET _listensocket; @@ -277,7 +290,7 @@ char* GetNetworkErrorMsg(char* buf, NetworkErrorCode err, const char* last) STR_NETWORK_ERR_CLIENT_SERVER_FULL }; - if (err >= lengthof(network_error_strings)) err = 0; + if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL; return GetString(buf, network_error_strings[err], last); } @@ -729,7 +742,7 @@ static void NetworkAcceptClients(void) p->buffer[0] = p->size & 0xFF; p->buffer[1] = p->size >> 8; - send(s, p->buffer, p->size, 0); + send(s, (const char*)p->buffer, p->size, 0); closesocket(s); free(p); @@ -750,7 +763,7 @@ static void NetworkAcceptClients(void) p->buffer[0] = p->size & 0xFF; p->buffer[1] = p->size >> 8; - send(s, p->buffer, p->size, 0); + send(s, (const char*)p->buffer, p->size, 0); closesocket(s); free(p); @@ -1032,7 +1045,7 @@ bool NetworkServerStart(void) _network_own_client_index = NETWORK_SERVER_INDEX; /* Non-dedicated server will always be player #1 */ - if (!_network_dedicated) _network_playas = 0; + if (!_network_dedicated) _network_playas = PLAYER_FIRST; _network_clients_connected = 0; diff --git a/src/network/network.h b/src/network/network.h index 0bd65c0b6..cc60ac96e 100644 --- a/src/network/network.h +++ b/src/network/network.h @@ -59,7 +59,7 @@ typedef struct NetworkClientInfo { uint16 client_index; // Index of the client (same as ClientState->index) char client_name[NETWORK_CLIENT_NAME_LENGTH]; // Name of the client byte client_lang; // The language of the client - byte client_playas; // As which player is this client playing (PlayerID) + PlayerID client_playas; // As which player is this client playing (PlayerID) uint32 client_ip; // IP-address of the client (so he can be banned) Date join_date; // Gamedate the player has joined char unique_id[NETWORK_NAME_LENGTH]; // Every play sends an unique id so we can indentify him @@ -188,7 +188,6 @@ bool NetworkClientConnectGame(const char *host, uint16 port); void NetworkReboot(void); void NetworkDisconnect(void); -VARDEF bool _networking; ///< are we in networking mode? VARDEF bool _network_server; ///< network-server is active VARDEF bool _network_available; ///< is network mode available? diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index 6e27eec56..338d076e6 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -20,7 +20,7 @@ #include "../console.h" #include "../variables.h" #include "../ai/ai.h" - +#include "../helpers.hpp" // This file handles all the client-commands @@ -286,14 +286,14 @@ DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMPANY_INFO) if (!MY_CLIENT->has_quit && company_info_version == NETWORK_COMPANY_INFO_VERSION) { byte total; - byte current; + PlayerID current; total = NetworkRecv_uint8(MY_CLIENT, p); // There is no data at all.. if (total == 0) return NETWORK_RECV_STATUS_CLOSE_QUERY; - current = NetworkRecv_uint8(MY_CLIENT, p); + current = (Owner)NetworkRecv_uint8(MY_CLIENT, p); if (!IsValidPlayer(current)) return NETWORK_RECV_STATUS_CLOSE_QUERY; NetworkRecv_string(MY_CLIENT, p, _network_player_info[current].company_name, sizeof(_network_player_info[current].company_name)); @@ -325,7 +325,7 @@ DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CLIENT_INFO) { NetworkClientInfo *ci; uint16 index = NetworkRecv_uint16(MY_CLIENT, p); - PlayerID playas = NetworkRecv_uint8(MY_CLIENT, p); + PlayerID playas = (Owner)NetworkRecv_uint8(MY_CLIENT, p); char name[NETWORK_NAME_LENGTH]; char unique_id[NETWORK_NAME_LENGTH]; @@ -375,7 +375,7 @@ DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CLIENT_INFO) DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR) { - NetworkErrorCode error = NetworkRecv_uint8(MY_CLIENT, p); + NetworkErrorCode error = (NetworkErrorCode)NetworkRecv_uint8(MY_CLIENT, p); switch (error) { /* We made an error in the protocol, and our connection is closed.... */ @@ -410,7 +410,7 @@ DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR) DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_NEED_PASSWORD) { - NetworkPasswordType type = NetworkRecv_uint8(MY_CLIENT, p); + NetworkPasswordType type = (NetworkPasswordType)NetworkRecv_uint8(MY_CLIENT, p); switch (type) { case NETWORK_GAME_PASSWORD: @@ -570,8 +570,9 @@ DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_SYNC) DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMMAND) { - CommandPacket *cp = malloc(sizeof(CommandPacket)); - cp->player = NetworkRecv_uint8(MY_CLIENT, p); + CommandPacket *cp; + MallocT(&cp, 1); + cp->player = (PlayerID)NetworkRecv_uint8(MY_CLIENT, p); cp->cmd = NetworkRecv_uint32(MY_CLIENT, p); cp->p1 = NetworkRecv_uint32(MY_CLIENT, p); cp->p2 = NetworkRecv_uint32(MY_CLIENT, p); @@ -601,9 +602,9 @@ DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CHAT) char name[NETWORK_NAME_LENGTH], msg[MAX_TEXT_MSG_LEN]; const NetworkClientInfo *ci = NULL, *ci_to; - NetworkAction action = NetworkRecv_uint8(MY_CLIENT, p); + NetworkAction action = (NetworkAction)NetworkRecv_uint8(MY_CLIENT, p); uint16 index = NetworkRecv_uint16(MY_CLIENT, p); - bool self_send = NetworkRecv_uint8(MY_CLIENT, p); + bool self_send = (NetworkRecv_uint8(MY_CLIENT, p) != 0); NetworkRecv_string(MY_CLIENT, p, msg, MAX_TEXT_MSG_LEN); ci_to = NetworkFindClientInfoFromIndex(index); @@ -623,7 +624,7 @@ DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CHAT) if (!IsValidPlayer(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY; /* fallthrough */ case NETWORK_ACTION_CHAT_COMPANY: { - StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : STR_NETWORK_SPECTATORS; + StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : (uint16)STR_NETWORK_SPECTATORS; GetString(name, str, lastof(name)); ci = NetworkFindClientInfoFromIndex(_network_own_client_index); @@ -649,7 +650,7 @@ DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR_QUIT) NetworkClientInfo *ci; index = NetworkRecv_uint16(MY_CLIENT, p); - GetNetworkErrorMsg(str, NetworkRecv_uint8(MY_CLIENT, p), lastof(str)); + GetNetworkErrorMsg(str, (NetworkErrorCode)NetworkRecv_uint8(MY_CLIENT, p), lastof(str)); ci = NetworkFindClientInfoFromIndex(index); if (ci != NULL) { diff --git a/src/network/network_data.cpp b/src/network/network_data.cpp index 9e5e6424d..89011f18d 100644 --- a/src/network/network_data.cpp +++ b/src/network/network_data.cpp @@ -9,11 +9,13 @@ #include "network_client.h" #include "../command.h" #include "../callback_table.h" +#include "../helpers.hpp" // Add a command to the local command queue void NetworkAddCommandQueue(NetworkClientState *cs, CommandPacket *cp) { - CommandPacket* new_cp = malloc(sizeof(*new_cp)); + CommandPacket* new_cp; + MallocT(&new_cp, 1); *new_cp = *cp; @@ -29,7 +31,8 @@ void NetworkAddCommandQueue(NetworkClientState *cs, CommandPacket *cp) // Prepare a DoCommand to be send over the network void NetworkSend_Command(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback) { - CommandPacket *c = malloc(sizeof(CommandPacket)); + CommandPacket *c; + MallocT(&c, 1); byte temp_callback; c->player = _local_player; diff --git a/src/network/network_data.h b/src/network/network_data.h index 3e42e00cf..2e44b8fcd 100644 --- a/src/network/network_data.h +++ b/src/network/network_data.h @@ -20,7 +20,7 @@ typedef struct CommandPacket { struct CommandPacket *next; - PlayerID player; /// player that is executing the command + PlayerByte player; /// player that is executing the command uint32 cmd; /// command being executed uint32 p1; /// parameter p1 uint32 p2; /// parameter p2 @@ -120,15 +120,17 @@ typedef enum { DESTTYPE_CLIENT, ///< Send message/notice to only a certain player (Private) } DestType; -CommandPacket *_local_command_queue; +// following externs are instantiated at network.cpp +extern CommandPacket *_local_command_queue; -SOCKET _udp_client_socket; // udp client socket -SOCKET _udp_server_socket; // udp server socket -SOCKET _udp_master_socket; // udp master socket +extern SOCKET _udp_client_socket; // udp client socket +extern SOCKET _udp_server_socket; // udp server socket +extern SOCKET _udp_master_socket; // udp master socket // Here we keep track of the clients // (and the client uses [0] for his own communication) -NetworkClientState _clients[MAX_CLIENTS]; +extern NetworkClientState _clients[MAX_CLIENTS]; + #define DEREF_CLIENT(i) (&_clients[i]) // This returns the NetworkClientInfo from a NetworkClientState #define DEREF_CLIENT_INFO(cs) (&_network_client_info[cs - _clients]) diff --git a/src/network/network_gamelist.cpp b/src/network/network_gamelist.cpp index a830073ad..b1b3993bb 100644 --- a/src/network/network_gamelist.cpp +++ b/src/network/network_gamelist.cpp @@ -6,6 +6,7 @@ #include "../debug.h" #include "network_data.h" #include "../newgrf_config.h" +#include "../helpers.hpp" // This file handles the GameList // Also, it handles the request to a server for data about the server @@ -25,7 +26,7 @@ NetworkGameList *NetworkGameListAddItem(uint32 ip, uint16 port) prev_item = item; } - item = malloc(sizeof(*item)); + MallocT(&item, 1); memset(item, 0, sizeof(*item)); item->next = NULL; item->ip = ip; diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index dd865118e..7a6fc221b 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -27,6 +27,7 @@ #include "../string.h" #include "../town.h" #include "../newgrf.h" +#include "../helpers.hpp" #define BGC 5 #define BTC 15 @@ -166,7 +167,7 @@ static void BuildNetworkGameList(network_ql_d *nqld) /* Create temporary array of games to use for listing */ free(nqld->sort_list); - nqld->sort_list = malloc(n * sizeof(nqld->sort_list[0])); + MallocT(&nqld->sort_list, n); if (nqld->sort_list == NULL) error("Could not allocate memory for the network-game-sorting-list"); nqld->l.list_length = n; @@ -221,7 +222,7 @@ static void NetworkGameWindowWndProc(Window *w, WindowEvent *e) nd->server = NULL; WP(w, network_ql_d).sort_list = NULL; - ld->flags = VL_REBUILD | (_ng_sorting.order << (VL_DESC - 1)); + ld->flags = VL_REBUILD | (_ng_sorting.order ? VL_DESC : VL_NONE); ld->sort_type = _ng_sorting.criteria; break; @@ -787,19 +788,19 @@ static void ShowNetworkStartServerWindow(void) InitializeTextBuffer(&WP(w, network_ql_d).q.text, _edit_str_buf, lengthof(_edit_str_buf), 160); } -static byte NetworkLobbyFindCompanyIndex(byte pos) +static PlayerID NetworkLobbyFindCompanyIndex(byte pos) { - byte i; + PlayerID i; /* Scroll through all _network_player_info and get the 'pos' item that is not empty */ - for (i = 0; i < MAX_PLAYERS; i++) { + for (i = PLAYER_FIRST; i < MAX_PLAYERS; i++) { if (_network_player_info[i].company_name[0] != '\0') { if (pos-- == 0) return i; } } - return 0; + return PLAYER_FIRST; } /* uses network_d WP macro */ @@ -809,7 +810,7 @@ static void NetworkLobbyWindowWndProc(Window *w, WindowEvent *e) switch (e->event) { case WE_CREATE: - nd->company = (byte)-1; + nd->company = INVALID_PLAYER; break; case WE_PAINT: { @@ -919,7 +920,7 @@ static void NetworkLobbyWindowWndProc(Window *w, WindowEvent *e) if (id_v >= w->vscroll.cap) return; id_v += w->vscroll.pos; - nd->company = (id_v >= nd->server->info.companies_on) ? (byte)-1 : NetworkLobbyFindCompanyIndex(id_v); + nd->company = (id_v >= nd->server->info.companies_on) ? INVALID_PLAYER : NetworkLobbyFindCompanyIndex(id_v); SetWindowDirty(w); } break; case 7: /* Join company */ @@ -1411,7 +1412,7 @@ static void NetworkJoinStatusWindowWndProc(Window *w, WindowEvent *e) } /* Draw nice progress bar :) */ - DrawFrameRect(20, 18, (int)((w->width - 20) * progress / 100), 28, 10, 0); + DrawFrameRect(20, 18, (int)((w->width - 20) * progress / 100), 28, 10, FR_NONE); } break; case WE_CLICK: @@ -1465,9 +1466,9 @@ static void SendChat(const char *buf, DestType type, byte dest) { if (buf[0] == '\0') return; if (!_network_server) { - SEND_COMMAND(PACKET_CLIENT_CHAT)(NETWORK_ACTION_CHAT + type, type, dest, buf); + SEND_COMMAND(PACKET_CLIENT_CHAT)((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf); } else { - NetworkServer_HandleChat(NETWORK_ACTION_CHAT + type, type, dest, buf, NETWORK_SERVER_INDEX); + NetworkServer_HandleChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, NETWORK_SERVER_INDEX); } } @@ -1635,7 +1636,7 @@ static void ChatWindowWndProc(Window *w, WindowEvent *e) case WE_CLICK: switch (e->we.click.widget) { case 3: { /* Send */ - DestType type = GB(WP(w, querystr_d).caption, 0, 8); + DestType type = (DestType)GB(WP(w, querystr_d).caption, 0, 8); byte dest = GB(WP(w, querystr_d).caption, 8, 8); SendChat(WP(w, querystr_d).text.buf, type, dest); } /* FALLTHROUGH */ @@ -1654,7 +1655,7 @@ static void ChatWindowWndProc(Window *w, WindowEvent *e) _chat_tab_completion_active = false; switch (HandleEditBoxKey(w, &WP(w, querystr_d), 2, e)) { case 1: { /* Return */ - DestType type = GB(WP(w, querystr_d).caption, 0, 8); + DestType type = (DestType)GB(WP(w, querystr_d).caption, 0, 8); byte dest = GB(WP(w, querystr_d).caption, 8, 8); SendChat(WP(w, querystr_d).text.buf, type, dest); } /* FALLTHROUGH */ diff --git a/src/network/network_gui.h b/src/network/network_gui.h index aa4313eba..650cf2554 100644 --- a/src/network/network_gui.h +++ b/src/network/network_gui.h @@ -8,7 +8,7 @@ #include "network_data.h" void ShowNetworkNeedPassword(NetworkPasswordType npt); -void ShowNetworkGiveMoneyWindow(byte player); // PlayerID +void ShowNetworkGiveMoneyWindow(PlayerID player); // PlayerID void ShowNetworkChatQueryWindow(DestType type, byte dest); void ShowJoinStatusWindow(void); void ShowNetworkGameWindow(void); diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index 5a7109105..c7bc2069d 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -22,6 +22,7 @@ #include "../station.h" #include "../variables.h" #include "../genworld.h" +#include "../helpers.hpp" // This file handles all the server-commands @@ -571,7 +572,7 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_JOIN) char name[NETWORK_CLIENT_NAME_LENGTH]; char unique_id[NETWORK_NAME_LENGTH]; NetworkClientInfo *ci; - byte playas; + PlayerID playas; NetworkLanguage client_lang; char client_revision[NETWORK_REVISION_LENGTH]; @@ -588,8 +589,8 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_JOIN) #endif NetworkRecv_string(cs, p, name, sizeof(name)); - playas = NetworkRecv_uint8(cs, p); - client_lang = NetworkRecv_uint8(cs, p); + playas = (Owner)NetworkRecv_uint8(cs, p); + client_lang = (NetworkLanguage)NetworkRecv_uint8(cs, p); NetworkRecv_string(cs, p, unique_id, sizeof(unique_id)); if (cs->has_quit) return; @@ -654,7 +655,7 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_PASSWORD) char password[NETWORK_PASSWORD_LENGTH]; const NetworkClientInfo *ci; - type = NetworkRecv_uint8(cs, p); + type = (NetworkPasswordType)NetworkRecv_uint8(cs, p); NetworkRecv_string(cs, p, password, sizeof(password)); if (cs->status == STATUS_INACTIVE && type == NETWORK_GAME_PASSWORD) { @@ -792,7 +793,8 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND) const NetworkClientInfo *ci; byte callback; - CommandPacket *cp = malloc(sizeof(CommandPacket)); + CommandPacket *cp; + MallocT(&cp, 1); // The client was never joined.. so this is impossible, right? // Ignore the packet, give the client a warning, and close his connection @@ -801,7 +803,7 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND) return; } - cp->player = NetworkRecv_uint8(cs, p); + cp->player = (Owner)NetworkRecv_uint8(cs, p); cp->cmd = NetworkRecv_uint32(cs, p); cp->p1 = NetworkRecv_uint32(cs, p); cp->p2 = NetworkRecv_uint32(cs, p); @@ -851,7 +853,7 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND) /* XXX - Execute the command as a valid player. Normally this would be done by a * spectator, but that is not allowed any commands. So do an impersonation. The drawback * of this is that the first company's last_built_tile is also updated... */ - cp->player = 0; + cp->player = OWNER_BEGIN; cp->p2 = cs - _clients; // XXX - UGLY! p2 is mis-used to get the client-id in CmdPlayerCtrl } @@ -890,7 +892,7 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ERROR) NetworkClientState *new_cs; char str[100]; char client_name[NETWORK_CLIENT_NAME_LENGTH]; - NetworkErrorCode errorno = NetworkRecv_uint8(cs, p); + NetworkErrorCode errorno = (NetworkErrorCode)NetworkRecv_uint8(cs, p); // The client was never joined.. thank the client for the packet, but ignore it if (cs->status < STATUS_DONE_MAP || cs->has_quit) { @@ -1044,7 +1046,7 @@ void NetworkServer_HandleChat(NetworkAction action, DestType desttype, int dest, if (ci != NULL && show_local) { if (from_index == NETWORK_SERVER_INDEX) { char name[NETWORK_NAME_LENGTH]; - StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : STR_NETWORK_SPECTATORS; + StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : (uint16)STR_NETWORK_SPECTATORS; GetString(name, str, lastof(name)); NetworkTextMessage(action, GetDrawStringPlayerColor(ci_own->client_playas), true, name, "%s", msg); } else { @@ -1073,8 +1075,8 @@ void NetworkServer_HandleChat(NetworkAction action, DestType desttype, int dest, DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_CHAT) { - NetworkAction action = NetworkRecv_uint8(cs, p); - DestType desttype = NetworkRecv_uint8(cs, p); + NetworkAction action = (NetworkAction)NetworkRecv_uint8(cs, p); + DestType desttype = (DestType)NetworkRecv_uint8(cs, p); int dest = NetworkRecv_uint8(cs, p); char msg[MAX_TEXT_MSG_LEN]; diff --git a/src/network/network_udp.cpp b/src/network/network_udp.cpp index 5caec3b42..b6bc2a9ce 100644 --- a/src/network/network_udp.cpp +++ b/src/network/network_udp.cpp @@ -335,7 +335,7 @@ DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS) * the current list and do not send the other data. * The name could be an empty string, if so take the filename. */ packet_len += sizeof(c.grfid) + sizeof(c.md5sum) + - min(strlen((f->name != NULL && strlen(f->name) > 0) ? f->name : f->filename) + 1, NETWORK_GRF_NAME_LENGTH); + min(strlen((f->name != NULL && strlen(f->name) > 0) ? f->name : f->filename) + 1, (size_t)NETWORK_GRF_NAME_LENGTH); if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply break; } diff --git a/src/newgrf.cpp b/src/newgrf.cpp index 5278ee6b4..48097fd82 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -30,6 +30,7 @@ #include "newgrf_config.h" #include "newgrf_sound.h" #include "newgrf_spritegroup.h" +#include "helpers.hpp" /* TTDPatch extended GRF format codec * (c) Petr Baudis 2004 (GPL'd) @@ -542,7 +543,7 @@ static bool RoadVehicleChangeInfo(uint engine, int numinfo, int prop, byte **buf break; case 0x12: /* SFX */ - FOR_EACH_OBJECT rvi[i].sfx = grf_load_byte(&buf); + FOR_EACH_OBJECT rvi[i].sfx = (SoundFx)grf_load_byte(&buf); break; case 0x13: /* Power in 10hp */ @@ -627,7 +628,7 @@ static bool ShipVehicleChangeInfo(uint engine, int numinfo, int prop, byte **buf break; case 0x09: /* Refittable */ - FOR_EACH_OBJECT svi[i].refittable = grf_load_byte(&buf); + FOR_EACH_OBJECT svi[i].refittable = (grf_load_byte(&buf) != 0); break; case 0x0A: /* Cost factor */ @@ -666,7 +667,7 @@ static bool ShipVehicleChangeInfo(uint engine, int numinfo, int prop, byte **buf break; case 0x10: /* SFX */ - FOR_EACH_OBJECT svi[i].sfx = grf_load_byte(&buf); + FOR_EACH_OBJECT svi[i].sfx = (SoundFx)grf_load_byte(&buf); break; case 0x11: /* Cargos available for refitting */ @@ -779,7 +780,7 @@ static bool AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, byte * break; case 0x12: /* SFX */ - FOR_EACH_OBJECT avi[i].sfx = grf_load_byte(&buf); + FOR_EACH_OBJECT avi[i].sfx = (SoundFx)grf_load_byte(&buf); break; case 0x13: /* Cargos available for refitting */ @@ -841,7 +842,7 @@ static bool StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int } /* Allocate station specs if necessary */ - if (_cur_grffile->stations == NULL) _cur_grffile->stations = calloc(MAX_STATIONS, sizeof(*_cur_grffile->stations)); + if (_cur_grffile->stations == NULL) CallocT(&_cur_grffile->stations, MAX_STATIONS); statspec = &_cur_grffile->stations[stid]; @@ -861,7 +862,7 @@ static bool StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int uint32 classid; /* Property 0x08 is special; it is where the station is allocated */ - if (statspec[i] == NULL) statspec[i] = calloc(1, sizeof(*statspec[i])); + if (statspec[i] == NULL) CallocT(&statspec[i], 1); /* Swap classid because we read it in BE meaning WAYP or DFLT */ classid = grf_load_dword(&buf); @@ -875,7 +876,7 @@ static bool StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int uint t; statspec->tiles = grf_load_extended(&buf); - statspec->renderdata = calloc(statspec->tiles, sizeof(*statspec->renderdata)); + CallocT(&statspec->renderdata, statspec->tiles); statspec->copied_renderdata = false; for (t = 0; t < statspec->tiles; t++) { @@ -890,7 +891,7 @@ static bool StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int DrawTileSeqStruct *dtss; // no relative bounding box support - dts->seq = realloc((void*)dts->seq, ++seq_count * sizeof(DrawTileSeqStruct)); + ReallocT((DrawTileSeqStruct**)&dts->seq, ++seq_count); dtss = (DrawTileSeqStruct*) &dts->seq[seq_count - 1]; dtss->delta_x = grf_load_byte(&buf); @@ -956,10 +957,10 @@ static bool StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int //debug("l %d > %d ?", length, stat->lengths); if (length > statspec->lengths) { - statspec->platforms = realloc(statspec->platforms, length); + ReallocT(&statspec->platforms, length); memset(statspec->platforms + statspec->lengths, 0, length - statspec->lengths); - statspec->layouts = realloc(statspec->layouts, length * sizeof(*statspec->layouts)); + ReallocT(&statspec->layouts, length); memset(statspec->layouts + statspec->lengths, 0, (length - statspec->lengths) * sizeof(*statspec->layouts)); @@ -969,8 +970,7 @@ static bool StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int //debug("p %d > %d ?", number, stat->platforms[l]); if (number > statspec->platforms[l]) { - statspec->layouts[l] = realloc(statspec->layouts[l], - number * sizeof(**statspec->layouts)); + ReallocT(&statspec->layouts[l], number); // We expect NULL being 0 here, but C99 guarantees that. memset(statspec->layouts[l] + statspec->platforms[l], 0, (number - statspec->platforms[l]) * sizeof(**statspec->layouts)); @@ -979,7 +979,7 @@ static bool StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int } p = 0; - layout = malloc(length * number); + MallocT(&layout, length * number); for (l = 0; l < length; l++) { for (p = 0; p < number; p++) { layout[l * number + p] = grf_load_byte(&buf); @@ -1075,7 +1075,7 @@ static bool BridgeChangeInfo(uint brid, int numinfo, int prop, byte **bufp, int if (bridge->sprite_table == NULL) { /* Allocate memory for sprite table pointers and zero out */ - bridge->sprite_table = calloc(7, sizeof(*bridge->sprite_table)); + CallocT(bridge->sprite_table, 7); } for (; numtables-- != 0; tableid++) { @@ -1088,7 +1088,7 @@ static bool BridgeChangeInfo(uint brid, int numinfo, int prop, byte **bufp, int } if (bridge->sprite_table[tableid] == NULL) { - bridge->sprite_table[tableid] = malloc(32 * sizeof(**bridge->sprite_table)); + MallocT(&bridge->sprite_table[tableid], 32); } for (sprite = 0; sprite < 32; sprite++) @@ -1595,7 +1595,7 @@ static void NewSpriteGroup(byte *buf, int len) if (setid >= _cur_grffile->spritegroups_count) { // Allocate memory for new sprite group references. - _cur_grffile->spritegroups = realloc(_cur_grffile->spritegroups, (setid + 1) * sizeof(*_cur_grffile->spritegroups)); + ReallocT(&_cur_grffile->spritegroups, setid + 1); // Initialise new space to NULL for (; _cur_grffile->spritegroups_count < (setid + 1); _cur_grffile->spritegroups_count++) _cur_grffile->spritegroups[_cur_grffile->spritegroups_count] = NULL; @@ -1640,18 +1640,18 @@ static void NewSpriteGroup(byte *buf, int len) } group->g.determ.num_adjusts++; - group->g.determ.adjusts = realloc(group->g.determ.adjusts, group->g.determ.num_adjusts * sizeof(*group->g.determ.adjusts)); + ReallocT(&group->g.determ.adjusts, group->g.determ.num_adjusts); adjust = &group->g.determ.adjusts[group->g.determ.num_adjusts - 1]; /* The first var adjust doesn't have an operation specified, so we set it to add. */ - adjust->operation = group->g.determ.num_adjusts == 1 ? DSGA_OP_ADD : grf_load_byte(&buf); + adjust->operation = group->g.determ.num_adjusts == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)grf_load_byte(&buf); adjust->variable = grf_load_byte(&buf); adjust->parameter = IS_BYTE_INSIDE(adjust->variable, 0x60, 0x80) ? grf_load_byte(&buf) : 0; varadjust = grf_load_byte(&buf); adjust->shift_num = GB(varadjust, 0, 5); - adjust->type = GB(varadjust, 6, 2); + adjust->type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2); adjust->and_mask = grf_load_var(varsize, &buf); if (adjust->type != DSGA_TYPE_NONE) { @@ -1666,7 +1666,7 @@ static void NewSpriteGroup(byte *buf, int len) } while (HASBIT(varadjust, 5)); group->g.determ.num_ranges = grf_load_byte(&buf); - group->g.determ.ranges = calloc(group->g.determ.num_ranges, sizeof(*group->g.determ.ranges)); + CallocT(&group->g.determ.ranges, group->g.determ.num_ranges); check_length(bufend - buf, 2 + (2 + 2 * varsize) * group->g.determ.num_ranges, "NewSpriteGroup (Deterministic)"); @@ -1698,7 +1698,7 @@ static void NewSpriteGroup(byte *buf, int len) group->g.random.cmp_mode = HASBIT(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY; group->g.random.lowest_randbit = grf_load_byte(&buf); group->g.random.num_groups = grf_load_byte(&buf); - group->g.random.groups = calloc(group->g.random.num_groups, sizeof(*group->g.random.groups)); + CallocT(&group->g.random.groups, group->g.random.num_groups); check_length(bufend - buf, 2 * group->g.random.num_groups, "NewSpriteGroup (Randomized) (2)"); @@ -1738,8 +1738,8 @@ static void NewSpriteGroup(byte *buf, int len) group->g.real.num_loaded = num_loaded; group->g.real.num_loading = num_loading; - if (num_loaded > 0) group->g.real.loaded = calloc(num_loaded, sizeof(*group->g.real.loaded)); - if (num_loading > 0) group->g.real.loading = calloc(num_loading, sizeof(*group->g.real.loading)); + if (num_loaded > 0) CallocT(&group->g.real.loaded, num_loaded); + if (num_loading > 0) CallocT(&group->g.real.loading, num_loading); grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u views, %u loaded, %u loading", setid, sprites, num_loaded, num_loading); @@ -1884,7 +1884,7 @@ static void FeatureMapSpriteGroup(byte *buf, int len) } if (!wagover && last_engines_count != idcount) { - last_engines = realloc(last_engines, idcount); + ReallocT(&last_engines, idcount); last_engines_count = idcount; } @@ -2235,7 +2235,7 @@ static uint32 GetParamVal(byte param, uint32 *cond_val) return _game_mode; case 0x9A: /* Always -1 */ - return -1; + return UINT_MAX; case 0x9D: /* TTD Platform, 00=TTDPatch, 01=OpenTTD */ return 1; @@ -2249,7 +2249,7 @@ static uint32 GetParamVal(byte param, uint32 *cond_val) /* In-game variable. */ grfmsg(1, "Unsupported in-game variable 0x%02X", param); - return -1; + return UINT_MAX; } } @@ -2274,7 +2274,7 @@ static void CfgApply(byte *buf, int len) /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */ if (type == 0xFF) { - _preload_sprite = malloc(num); + MallocT(&_preload_sprite, num); FioReadBlock(_preload_sprite, num); } @@ -2788,7 +2788,7 @@ static void ParamSet(byte *buf, int len) } grfmsg(1, "GRM: Unable to allocate %d vehicles", count); - src1 = -1; + src1 = UINT_MAX; } break; } @@ -3026,7 +3026,7 @@ static void DefineGotoLabel(byte *buf, int len) check_length(len, 1, "DefineGotoLabel"); buf++; len--; - label = malloc(sizeof(*label)); + MallocT(&label, 1); label->label = grf_load_byte(&buf); label->nfo_line = _nfo_line; label->pos = FioGetPos(); @@ -3198,7 +3198,7 @@ static void LoadFontGlyph(byte *buf, int len) check_length(len, 1 + num_def * 4, "LoadFontGlyph"); for (i = 0; i < num_def; i++) { - FontSize size = grf_load_byte(&buf); + FontSize size = (FontSize)grf_load_byte(&buf); uint8 num_char = grf_load_byte(&buf); uint16 base_char = grf_load_word(&buf); uint c; @@ -3489,7 +3489,7 @@ static void InitNewGRFFile(const GRFConfig *config, int sprite_offset) return; } - newfile = calloc(1, sizeof(*newfile)); + CallocT(&newfile, 1); if (newfile == NULL) error ("Out of memory"); @@ -3617,7 +3617,7 @@ static void DecodeSpecialSprite(uint num, GrfLoadingStage stage) if (_preload_sprite == NULL) { /* No preloaded sprite to work with; allocate and read the * pseudo sprite content. */ - buf = malloc(num); + MallocT(&buf, num); if (buf == NULL) error("DecodeSpecialSprite: Could not allocate memory"); FioReadBlock(buf, num); } else { @@ -3770,3 +3770,4 @@ void LoadNewGRF(uint load_index, uint file_index) } + diff --git a/src/newgrf.h b/src/newgrf.h index 1d8c5a365..697ef9fc0 100644 --- a/src/newgrf.h +++ b/src/newgrf.h @@ -5,6 +5,7 @@ #include "station.h" #include "newgrf_config.h" +#include "helpers.hpp" typedef enum GrfLoadingStage { GLS_FILESCAN, @@ -15,6 +16,9 @@ typedef enum GrfLoadingStage { GLS_END, } GrfLoadingStage; +DECLARE_POSTFIX_INCREMENT(GrfLoadingStage); + + typedef struct GRFLabel { byte label; uint32 nfo_line; diff --git a/src/newgrf_config.cpp b/src/newgrf_config.cpp index 977cb139e..c624328dd 100644 --- a/src/newgrf_config.cpp +++ b/src/newgrf_config.cpp @@ -12,6 +12,7 @@ #include "network/network_data.h" #include "newgrf.h" #include "newgrf_config.h" +#include "helpers.hpp" #include "fileio.h" #include "fios.h" @@ -123,7 +124,7 @@ GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src) /* Clear destination as it will be overwritten */ ClearGRFConfigList(dst); for (; src != NULL; src = src->next) { - c = calloc(1, sizeof(*c)); + CallocT(&c, 1); *c = *src; if (src->filename != NULL) c->filename = strdup(src->filename); if (src->name != NULL) c->name = strdup(src->name); @@ -269,7 +270,7 @@ static uint ScanPath(const char *path) if (ext == NULL) continue; if (strcasecmp(ext, ".grf") != 0) continue; - c = calloc(1, sizeof(*c)); + CallocT(&c, 1); c->filename = strdup(file); if (FillGRFDetails(c, false)) { @@ -374,7 +375,7 @@ char *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create) if (!create) return NULL; - grf = calloc(1, sizeof(*grf)); + CallocT(&grf, 1); grf->grfid = grfid; grf->next = unknown_grfs; ttd_strlcpy(grf->name, UNKNOWN_GRF_NAME_PLACEHOLDER, sizeof(grf->name)); @@ -445,7 +446,8 @@ static void Load_NGRF(void) GRFConfig **last = &first; while (SlIterateArray() != -1) { - GRFConfig *c = calloc(1, sizeof(*c)); + GRFConfig *c; + CallocT(&c, 1); SlObject(c, _grfconfig_desc); /* Append our configuration to the list */ @@ -461,7 +463,7 @@ static void Load_NGRF(void) AppendStaticGRFConfigs(&_grfconfig); } -const ChunkHandler _newgrf_chunk_handlers[] = { +extern const ChunkHandler _newgrf_chunk_handlers[] = { { 'NGRF', Save_NGRF, Load_NGRF, CH_ARRAY | CH_LAST } }; diff --git a/src/newgrf_engine.cpp b/src/newgrf_engine.cpp index 0662f3fc8..5b0fa5179 100644 --- a/src/newgrf_engine.cpp +++ b/src/newgrf_engine.cpp @@ -17,6 +17,7 @@ #include "newgrf_spritegroup.h" #include "newgrf_cargo.h" #include "date.h" +#include "helpers.hpp" @@ -82,8 +83,7 @@ void SetWagonOverrideSprites(EngineID engine, CargoID cargo, const SpriteGroup * wos = &_engine_wagon_overrides[engine]; wos->overrides_count++; - wos->overrides = realloc(wos->overrides, - wos->overrides_count * sizeof(*wos->overrides)); + ReallocT(&wos->overrides, wos->overrides_count); wo = &wos->overrides[wos->overrides_count - 1]; /* FIXME: If we are replacing an override, release original SpriteGroup @@ -92,7 +92,7 @@ void SetWagonOverrideSprites(EngineID engine, CargoID cargo, const SpriteGroup * wo->group = group; wo->cargo = cargo; wo->trains = trains; - wo->train_id = malloc(trains); + MallocT(&wo->train_id, trains); memcpy(wo->train_id, train_id, trains); } @@ -563,7 +563,7 @@ static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, by } *available = false; - return -1; + return UINT_MAX; } /* Calculated vehicle parameters */ @@ -628,7 +628,7 @@ static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, by return v->owner; case 0x44: /* Aircraft information */ - if (v->type != VEH_Aircraft) return -1; + if (v->type != VEH_Aircraft) return UINT_MAX; { const Vehicle *w = v->next; @@ -806,7 +806,7 @@ static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, by DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, v->type); *available = false; - return -1; + return UINT_MAX; } diff --git a/src/newgrf_gui.cpp b/src/newgrf_gui.cpp index 4ae734207..7eb63d722 100644 --- a/src/newgrf_gui.cpp +++ b/src/newgrf_gui.cpp @@ -11,6 +11,7 @@ #include "table/sprites.h" #include "newgrf.h" #include "newgrf_config.h" +#include "helpers.hpp" /** Parse an integerlist string and set each found value @@ -164,7 +165,7 @@ static void NewGRFAddDlgWndProc(Window *w, WindowEvent *e) } /* Copy GRF details from scanned list */ - c = calloc(1, sizeof(*c)); + CallocT(&c, 1); *c = *src; c->filename = strdup(src->filename); if (src->name != NULL) c->name = strdup(src->name); diff --git a/src/newgrf_sound.cpp b/src/newgrf_sound.cpp index e96934104..16990faf5 100644 --- a/src/newgrf_sound.cpp +++ b/src/newgrf_sound.cpp @@ -63,6 +63,6 @@ bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event) if (callback == CALLBACK_FAILED) return false; if (callback >= GetNumOriginalSounds()) callback += file->sound_offset - GetNumOriginalSounds(); - if (callback < GetNumSounds()) SndPlayVehicleFx(callback, v); + if (callback < GetNumSounds()) SndPlayVehicleFx((SoundFx)callback, v); return true; } diff --git a/src/newgrf_spritegroup.cpp b/src/newgrf_spritegroup.cpp index f97da9c90..096ed21c5 100644 --- a/src/newgrf_spritegroup.cpp +++ b/src/newgrf_spritegroup.cpp @@ -81,7 +81,7 @@ static inline uint32 GetVariable(const ResolverObject *object, byte variable, by case 0x10: return object->callback_param1; case 0x11: return 0; case 0x18: return object->callback_param2; - case 0x1A: return -1; + case 0x1A: return (uint32)-1; case 0x1B: return GB(_display_opt, 0, 6); case 0x1C: return object->last_value; case 0x20: return _opt.landscape == LT_HILLY ? _opt.snow_line : 0xFF; diff --git a/src/newgrf_station.cpp b/src/newgrf_station.cpp index f36769a41..0ef1ec84e 100644 --- a/src/newgrf_station.cpp +++ b/src/newgrf_station.cpp @@ -17,6 +17,7 @@ #include "newgrf_station.h" #include "newgrf_spritegroup.h" #include "date.h" +#include "helpers.hpp" static StationClass station_classes[STAT_CLASS_MAX]; @@ -31,8 +32,7 @@ enum { */ void ResetStationClasses(void) { - StationClassID i; - for (i = 0; i < STAT_CLASS_MAX; i++) { + for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) { station_classes[i].id = 0; station_classes[i].name = STR_EMPTY; station_classes[i].stations = 0; @@ -45,13 +45,13 @@ void ResetStationClasses(void) station_classes[0].id = 'DFLT'; station_classes[0].name = STR_STAT_CLASS_DFLT; station_classes[0].stations = 1; - station_classes[0].spec = malloc(sizeof(*station_classes[0].spec)); + MallocT(&station_classes[0].spec, 1); station_classes[0].spec[0] = NULL; station_classes[1].id = 'WAYP'; station_classes[1].name = STR_STAT_CLASS_WAYP; station_classes[1].stations = 1; - station_classes[1].spec = malloc(sizeof(*station_classes[1].spec)); + MallocT(&station_classes[1].spec, 1); station_classes[1].spec[0] = NULL; } @@ -60,17 +60,15 @@ void ResetStationClasses(void) * @param classid A 32 bit value identifying the class. * @return Index into station_classes of allocated class. */ -StationClassID AllocateStationClass(uint32 class) +StationClassID AllocateStationClass(uint32 cls) { - StationClassID i; - - for (i = 0; i < STAT_CLASS_MAX; i++) { - if (station_classes[i].id == class) { + for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) { + if (station_classes[i].id == cls) { // ClassID is already allocated, so reuse it. return i; } else if (station_classes[i].id == 0) { // This class is empty, so allocate it to the ClassID. - station_classes[i].id = class; + station_classes[i].id = cls; return i; } } @@ -150,7 +148,7 @@ void SetCustomStationSpec(StationSpec *statspec) station_class = &station_classes[statspec->sclass]; i = station_class->stations++; - station_class->spec = realloc(station_class->spec, station_class->stations * sizeof(*station_class->spec)); + ReallocT(&station_class->spec, station_class->stations); station_class->spec[i] = statspec; statspec->allocated = true; @@ -176,10 +174,9 @@ const StationSpec *GetCustomStationSpec(StationClassID sclass, uint station) const StationSpec *GetCustomStationSpecByGrf(uint32 grfid, byte localidx) { - StationClassID i; uint j; - for (i = STAT_CLASS_DFLT; i < STAT_CLASS_MAX; i++) { + for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) { for (j = 0; j < station_classes[i].stations; j++) { const StationSpec *statspec = station_classes[i].spec[j]; if (statspec == NULL) continue; @@ -364,7 +361,7 @@ static uint32 StationGetVariable(const ResolverObject *object, byte variable, by } *available = false; - return -1; + return UINT_MAX; } switch (variable) { @@ -430,7 +427,7 @@ static uint32 StationGetVariable(const ResolverObject *object, byte variable, by DEBUG(grf, 1, "Unhandled station property 0x%X", variable); *available = false; - return -1; + return UINT_MAX; } @@ -610,7 +607,7 @@ int AllocateSpecToStation(const StationSpec *statspec, Station *st, bool exec) if (exec) { if (i >= st->num_specs) { st->num_specs = i + 1; - st->speclist = realloc(st->speclist, st->num_specs * sizeof(*st->speclist)); + ReallocT(&st->speclist, st->num_specs); if (st->num_specs == 2) { /* Initial allocation */ @@ -656,7 +653,7 @@ void DeallocateSpecFromStation(Station* st, byte specindex) for (; st->speclist[st->num_specs - 1].grfid == 0 && st->num_specs > 1; st->num_specs--); if (st->num_specs > 1) { - st->speclist = realloc(st->speclist, st->num_specs * sizeof(*st->speclist)); + ReallocT(&st->speclist, st->num_specs); } else { free(st->speclist); st->num_specs = 0; @@ -696,7 +693,7 @@ bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID if (statspec->renderdata == NULL) { sprites = GetStationTileLayout(tile + axis); } else { - sprites = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : axis]; + sprites = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : (uint)axis]; } image = sprites->ground_sprite; diff --git a/src/newgrf_station.h b/src/newgrf_station.h index a133fb3d7..f504bdd2b 100644 --- a/src/newgrf_station.h +++ b/src/newgrf_station.h @@ -7,13 +7,22 @@ #include "engine.h" #include "newgrf_cargo.h" +#include "helpers.hpp" typedef enum { - STAT_CLASS_DFLT, ///< Default station class. - STAT_CLASS_WAYP, ///< Waypoint class. - STAT_CLASS_MAX = 32, ///< Maximum number of classes. + STAT_CLASS_BEGIN = 0, ///< the lowest valid value + STAT_CLASS_DFLT = 0, ///< Default station class. + STAT_CLASS_WAYP, ///< Waypoint class. + STAT_CLASS_MAX = 32, ///< Maximum number of classes. } StationClassID; +/** Define basic enum properties */ +template <> struct EnumPropsT<StationClassID> : MakeEnumPropsT<StationClassID, byte, STAT_CLASS_BEGIN, STAT_CLASS_MAX, STAT_CLASS_MAX> {}; +typedef TinyEnumT<StationClassID> StationClassIDByte; + +/** Allow incrementing of StationClassID variables */ +DECLARE_POSTFIX_INCREMENT(StationClassID); + /* Station layout for given dimensions - it is a two-dimensional array * where index is computed as (x * platforms) + platform. */ typedef byte *StationLayout; diff --git a/src/newgrf_text.cpp b/src/newgrf_text.cpp index e859f6e6c..af1dc688a 100644 --- a/src/newgrf_text.cpp +++ b/src/newgrf_text.cpp @@ -20,6 +20,7 @@ #include "newgrf.h" #include "newgrf_text.h" #include "table/control_codes.h" +#include "helpers.hpp" #define GRFTAB 28 #define TABSIZE 11 @@ -157,7 +158,8 @@ static byte _currentLangID = GRFLX_ENGLISH; //by default, english is used. char *TranslateTTDPatchCodes(const char *str) { - char *tmp = malloc(strlen(str) * 10 + 1); /* Allocate space to allow for expansion */ + char *tmp; + MallocT(&tmp, strlen(str) * 10 + 1); /* Allocate space to allow for expansion */ char *d = tmp; bool unicode = false; WChar c; @@ -253,7 +255,8 @@ char *TranslateTTDPatchCodes(const char *str) } *d = '\0'; - return realloc(tmp, strlen(tmp) + 1); + ReallocT(&tmp, strlen(tmp) + 1); + return tmp; } @@ -295,7 +298,7 @@ StringID AddGRFString(uint32 grfid, uint16 stringid, byte langid_to_add, bool ne translatedtext = TranslateTTDPatchCodes(text_to_add); - newtext = malloc(sizeof(*newtext) + strlen(translatedtext) + 1); + newtext = (GRFText*)malloc(sizeof(*newtext) + strlen(translatedtext) + 1); newtext->next = NULL; newtext->langid = langid_to_add; strcpy(newtext->text, translatedtext); diff --git a/src/news_gui.cpp b/src/news_gui.cpp index 677a87765..df3936af1 100644 --- a/src/news_gui.cpp +++ b/src/news_gui.cpp @@ -74,6 +74,7 @@ static DrawNewsCallbackProc * const _draw_news_callback[] = { DrawNewsBankrupcy, /* DNC_BANKRUPCY */ }; +extern GetNewsStringCallbackProc * const _get_news_string_callback[]; GetNewsStringCallbackProc * const _get_news_string_callback[] = { GetNewsStringNewTrainAvail, /* DNC_TRAINAVAIL */ GetNewsStringNewRoadVehAvail, /* DNC_ROADAVAIL */ @@ -218,7 +219,7 @@ static void NewsWindowProc(Window *w, WindowEvent *e) if (w->viewport != NULL) w->viewport->top += y - w->top; - diff = abs(w->top - y); + diff = delta(w->top, y); w->top = y; SetDirtyBlocks(w->left, w->top - diff, w->left + w->width, w->top + w->height); @@ -367,14 +368,14 @@ static WindowDesc _news_type0_desc = { static const SoundFx _news_sounds[] = { SND_1D_APPLAUSE, SND_1D_APPLAUSE, - 0, - 0, - 0, - 0, + SND_BEGIN, + SND_BEGIN, + SND_BEGIN, + SND_BEGIN, SND_1E_OOOOH, - 0, - 0, - 0 + SND_BEGIN, + SND_BEGIN, + SND_BEGIN }; /** Get the value of an item of the news-display settings. This is @@ -752,7 +753,7 @@ static void MessageOptionsWndProc(Window *w, WindowEvent *e) for (i = 0, y = 26; i != 10; i++, y += 12, click_state >>= 1, val >>= 2) { bool clicked = !!(click_state & 1); - DrawFrameRect(13, y, 89, 11 + y, 3, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(13, y, 89, 11 + y, 3, (clicked) ? FR_LOWERED : FR_NONE); DrawStringCentered(((13 + 89 + 1) >> 1) + clicked, ((y + 11 + y + 1) >> 1) - 5 + clicked, message_opt[val & 0x3], 0x10); DrawString(103, y + 1, i + STR_0206_ARRIVAL_OF_FIRST_VEHICLE, 0); } diff --git a/src/npf.cpp b/src/npf.cpp index 97b9bf367..4e2cba0a4 100644 --- a/src/npf.cpp +++ b/src/npf.cpp @@ -37,8 +37,8 @@ static const uint _trackdir_length[TRACKDIR_END] = { */ static uint NPFDistanceTrack(TileIndex t0, TileIndex t1) { - const uint dx = abs(TileX(t0) - TileX(t1)); - const uint dy = abs(TileY(t0) - TileY(t1)); + const uint dx = delta(TileX(t0), TileX(t1)); + const uint dy = delta(TileY(t0), TileY(t1)); const uint straightTracks = 2 * min(dx, dy); /* The number of straight (not full length) tracks */ /* OPTIMISATION: @@ -74,7 +74,7 @@ static uint NPFHash(uint key1, uint key2) uint part1 = TileX(key1) & NPF_HASH_HALFMASK; uint part2 = TileY(key1) & NPF_HASH_HALFMASK; - assert(IsValidTrackdir(key2)); + assert(IsValidTrackdir((Trackdir)key2)); assert(IsValidTile(key1)); return ((part1 << NPF_HASH_HALFBITS | part2) + (NPF_HASH_SIZE * key2 / TRACKDIR_END)) % NPF_HASH_SIZE; } @@ -137,7 +137,7 @@ static int32 NPFCalcStationOrTileHeuristic(AyStar* as, AyStarNode* current, Open if (dist < ftd->best_bird_dist) { ftd->best_bird_dist = dist; - ftd->best_trackdir = current->user_data[NPF_TRACKDIR_CHOICE]; + ftd->best_trackdir = (Trackdir)current->user_data[NPF_TRACKDIR_CHOICE]; } return dist; } @@ -188,7 +188,7 @@ static inline uint NPFBridgeCost(AyStarNode *current) static uint NPFSlopeCost(AyStarNode* current) { - TileIndex next = current->tile + TileOffsByDiagDir(TrackdirToExitdir(current->direction)); + TileIndex next = current->tile + TileOffsByDiagDir(TrackdirToExitdir((Trackdir)current->direction)); int x,y; int8 z1,z2; @@ -290,7 +290,7 @@ static int32 NPFRoadPathCost(AyStar* as, AyStarNode* current, OpenListNode* pare /* Check for turns. Road vehicles only really drive diagonal, turns are * represented by non-diagonal tracks */ - if (!IsDiagonalTrackdir(current->direction)) + if (!IsDiagonalTrackdir((Trackdir)current->direction)) cost += _patches.npf_road_curve_penalty; NPFMarkTile(tile); @@ -403,7 +403,7 @@ static int32 NPFFindDepot(AyStar* as, OpenListNode *current) { /* 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 */ - return IsTileDepotType(current->path.node.tile, as->user_data[NPF_TYPE]) ? + return IsTileDepotType(current->path.node.tile, (TransportType)as->user_data[NPF_TYPE]) ? AYSTAR_FOUND_END_NODE : AYSTAR_DONE; } @@ -511,8 +511,9 @@ static void NPFFollowTrack(AyStar* aystar, OpenListNode* current) DiagDirection src_exitdir = TrackdirToExitdir(src_trackdir); TileIndex dst_tile = INVALID_TILE; int i; - TrackdirBits trackdirbits, ts; - TransportType type = aystar->user_data[NPF_TYPE]; + uint32 ts; + TrackdirBits trackdirbits; + TransportType type = (TransportType)aystar->user_data[NPF_TYPE]; bool override_dst_check = false; /* Initialize to 0, so we can jump out (return) somewhere an have no neighbours */ aystar->num_neighbours = 0; @@ -587,13 +588,13 @@ static void NPFFollowTrack(AyStar* aystar, OpenListNode* current) /* check correct rail type (mono, maglev, etc) */ if (type == TRANSPORT_RAIL) { - RailType dst_type = GetTileRailType(dst_tile, src_trackdir); + RailType dst_type = GetTileRailType(dst_tile, TrackdirToTrack(src_trackdir)); if (!HASBIT(aystar->user_data[NPF_RAILTYPES], dst_type)) return; } /* Check the owner of the tile */ - if (!VehicleMayEnterTile(aystar->user_data[NPF_OWNER], dst_tile, TrackdirToExitdir(src_trackdir))) { + if (!VehicleMayEnterTile((Owner)aystar->user_data[NPF_OWNER], dst_tile, TrackdirToExitdir(src_trackdir))) { return; } @@ -614,7 +615,7 @@ static void NPFFollowTrack(AyStar* aystar, OpenListNode* current) } else { ts = GetTileTrackStatus(dst_tile, type); } - trackdirbits = ts & TRACKDIR_BIT_MASK; /* Filter out signal status and the unused bits */ + trackdirbits = (TrackdirBits)(ts & TRACKDIR_BIT_MASK); /* Filter out signal status and the unused bits */ DEBUG(npf, 4, "Next node: (%d, %d) [%d], possible trackdirs: 0x%X", TileX(dst_tile), TileY(dst_tile), dst_tile, trackdirbits); /* Select only trackdirs we can reach from our current trackdir */ @@ -627,9 +628,7 @@ static void NPFFollowTrack(AyStar* aystar, OpenListNode* current) i = 0; /* Enumerate possible track */ while (trackdirbits != 0) { - Trackdir dst_trackdir; - dst_trackdir = FindFirstBit2x64(trackdirbits); - trackdirbits = KillFirstBit2x64(trackdirbits); + Trackdir dst_trackdir = RemoveFirstTrackdir(trackdirbits); DEBUG(npf, 5, "Expanded into trackdir: %d, remaining trackdirs: 0x%X", dst_trackdir, trackdirbits); /* Check for oneway signal against us */ @@ -739,7 +738,7 @@ NPFFoundTargetData NPFRouteToStationOrTileTwoWay(TileIndex tile1, Trackdir track NPFFoundTargetData NPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, NPFFindStationOrTileData* target, TransportType type, Owner owner, RailTypeMask railtypes) { - return NPFRouteToStationOrTileTwoWay(tile, trackdir, INVALID_TILE, 0, target, type, owner, railtypes); + return NPFRouteToStationOrTileTwoWay(tile, trackdir, INVALID_TILE, INVALID_TRACKDIR, target, type, owner, railtypes); } NPFFoundTargetData NPFRouteToDepotBreadthFirstTwoWay(TileIndex tile1, Trackdir trackdir1, TileIndex tile2, Trackdir trackdir2, TransportType type, Owner owner, RailTypeMask railtypes, uint reverse_penalty) @@ -763,7 +762,7 @@ NPFFoundTargetData NPFRouteToDepotBreadthFirstTwoWay(TileIndex tile1, Trackdir t NPFFoundTargetData NPFRouteToDepotBreadthFirst(TileIndex tile, Trackdir trackdir, TransportType type, Owner owner, RailTypeMask railtypes) { - return NPFRouteToDepotBreadthFirstTwoWay(tile, trackdir, INVALID_TILE, 0, type, owner, railtypes, 0); + return NPFRouteToDepotBreadthFirstTwoWay(tile, trackdir, INVALID_TILE, INVALID_TRACKDIR, type, owner, railtypes, 0); } NPFFoundTargetData NPFRouteToDepotTrialError(TileIndex tile, Trackdir trackdir, TransportType type, Owner owner, RailTypeMask railtypes) @@ -827,7 +826,7 @@ NPFFoundTargetData NPFRouteToDepotTrialError(TileIndex tile, Trackdir trackdir, best_result.best_bird_dist = (uint)-1; /* Just iterate the depots in order of increasing distance */ - while ((current = depots.pop(&depots))) { + while ((current = (Depot*)depots.pop(&depots))) { /* Check to see if we already have a path shorter than this * depot's manhattan distance. HACK: We call DistanceManhattan * again, we should probably modify the queue to give us that diff --git a/src/oldloader.cpp b/src/oldloader.cpp index f6a56fdd6..98a1e9223 100644 --- a/src/oldloader.cpp +++ b/src/oldloader.cpp @@ -80,6 +80,8 @@ typedef enum OldChunkTypes { OC_END = 0 ///< End of the whole chunk, all 32bits set to zero } OldChunkType; +DECLARE_ENUM_AS_BIT_SET(OldChunkType); + typedef bool OldChunkProc(LoadgameState *ls, int num); typedef struct OldChunks { @@ -97,9 +99,9 @@ assert_compile(sizeof(TileIndex) == 4); static uint32 _bump_assert_value; static bool _read_ttdpatch_flags; -static OldChunkType GetOldChunkType(OldChunkType type) {return GB(type, 0, 8);} -static OldChunkType GetOldChunkVarType(OldChunkType type) {return GB(type, 8, 8) << 8;} -static OldChunkType GetOldChunkFileType(OldChunkType type) {return GB(type, 16, 8) << 16;} +static OldChunkType GetOldChunkType(OldChunkType type) {return (OldChunkType)GB(type, 0, 8);} +static OldChunkType GetOldChunkVarType(OldChunkType type) {return (OldChunkType)(GB(type, 8, 8) << 8);} +static OldChunkType GetOldChunkFileType(OldChunkType type) {return (OldChunkType)(GB(type, 16, 8) << 16);} static inline byte CalcOldVarLen(OldChunkType type) { @@ -189,10 +191,10 @@ static inline uint32 ReadUint32(LoadgameState *ls) static bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks) { const OldChunks *chunk = chunks; - byte *base_ptr = base; + byte *base_ptr = (byte*)base; while (chunk->type != OC_END) { - byte* ptr = chunk->ptr; + byte* ptr = (byte*)chunk->ptr; uint i; for (i = 0; i < chunk->amount; i++) { @@ -959,9 +961,9 @@ static const OldChunks player_chunk[] = { static bool LoadOldPlayer(LoadgameState *ls, int num) { - Player *p = GetPlayer(num); + Player *p = GetPlayer((PlayerID)num); - _current_player_id = num; + _current_player_id = (PlayerID)num; if (!LoadChunk(ls, p, player_chunk)) return false; @@ -996,7 +998,7 @@ static bool LoadOldPlayer(LoadgameState *ls, int num) * really figured out as of now, p->ai.cur_veh; needed for 'sell vehicle' * is NULL and the function will crash. To fix this, just change the state * to some harmless state, like 'loop vehicle'; 1 */ - if (!IsHumanPlayer(num) && p->ai.state == 20) p->ai.state = 1; + if (!IsHumanPlayer((PlayerID)num) && p->ai.state == 20) p->ai.state = 1; if (p->is_ai && (!_networking || _network_server) && _ai.enabled) AI_StartNewAI(p->index); diff --git a/src/oldpool.cpp b/src/oldpool.cpp index 2b2d188e8..d19aa684e 100644 --- a/src/oldpool.cpp +++ b/src/oldpool.cpp @@ -5,6 +5,7 @@ #include "debug.h" #include "functions.h" #include "oldpool.h" +#include "helpers.hpp" /** * Clean a pool in a safe way (does free all blocks) @@ -49,11 +50,11 @@ bool AddBlockToPool(OldMemoryPool *pool) DEBUG(misc, 4, "[Pool] (%s) increasing size of pool to %d items (%d bytes)", pool->name, pool->total_items, pool->total_items * pool->item_size); /* Increase the poolsize */ - pool->blocks = realloc(pool->blocks, sizeof(pool->blocks[0]) * (pool->current_blocks + 1)); + ReallocT(&pool->blocks, pool->current_blocks + 1); if (pool->blocks == NULL) error("Pool: (%s) could not allocate memory for blocks", pool->name); /* Allocate memory to the new block item */ - pool->blocks[pool->current_blocks] = malloc(pool->item_size * (1 << pool->block_size_bits)); + MallocT(&pool->blocks[pool->current_blocks], pool->item_size * (1 << pool->block_size_bits)); if (pool->blocks[pool->current_blocks] == NULL) error("Pool: (%s) could not allocate memory for blocks", pool->name); diff --git a/src/oldpool.h b/src/oldpool.h index ba22e4ef4..b6f5385da 100644 --- a/src/oldpool.h +++ b/src/oldpool.h @@ -16,11 +16,11 @@ typedef void OldMemoryPoolCleanBlock(uint start_item, uint end_item); * please try to avoid manual calls! */ struct OldMemoryPool { - const char* const name; ///< Name of the pool (just for debugging) + const char* name; ///< Name of the pool (just for debugging) - const uint max_blocks; ///< The max amount of blocks this pool can have - const uint block_size_bits; ///< The size of each block in bits - const uint item_size; ///< How many bytes one block is + uint max_blocks; ///< The max amount of blocks this pool can have + uint block_size_bits; ///< The size of each block in bits + uint item_size; ///< How many bytes one block is /// Pointer to a function that is called after a new block is added OldMemoryPoolNewBlock *new_block_proc; diff --git a/src/openttd.cpp b/src/openttd.cpp index a7604801a..c1a66a555 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -1,6 +1,7 @@ /* $Id$ */ #include "stdafx.h" +#define VARDEF #include "string.h" #include "table/strings.h" #include "debug.h" @@ -10,8 +11,8 @@ #include "map.h" #include "tile.h" #include "void_map.h" +#include "helpers.hpp" -#define VARDEF #include "openttd.h" #include "bridge_map.h" #include "functions.h" @@ -73,7 +74,7 @@ void InitializeStations(void); void DeleteAllPlayerStations(void); extern void SetDifficultyLevel(int mode, GameOptions *gm_opt); -extern void DoStartupNewPlayer(bool is_ai); +extern Player* DoStartupNewPlayer(bool is_ai); extern void ShowOSErrorBox(const char *buf); /* TODO: usrerror() for errors which are not of an internal nature but @@ -119,7 +120,7 @@ void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize) fseek(in, 0, SEEK_END); len = ftell(in); fseek(in, 0, SEEK_SET); - if (len > maxsize || (mem = malloc(len + 1)) == NULL) { + if (len > maxsize || !MallocT(&mem, len + 1)) { fclose(in); return NULL; } @@ -135,9 +136,9 @@ void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize) return mem; } +extern const char _openttd_revision[]; static void showhelp(void) { - extern const char _openttd_revision[]; char buf[4096], *p; p = buf; @@ -175,25 +176,26 @@ static void showhelp(void) } -typedef struct { +struct MyGetOptData { char *opt; int numleft; char **argv; const char *options; - char *cont; -} MyGetOptData; + const char *cont; -static void MyGetOptInit(MyGetOptData *md, int argc, char **argv, const char *options) -{ - md->cont = NULL; - md->numleft = argc; - md->argv = argv; - md->options = options; -} + MyGetOptData(int argc, char **argv, const char *options) + { + opt = NULL; + numleft = argc; + this->argv = argv; + this->options = options; + cont = NULL; + } +}; static int MyGetOpt(MyGetOptData *md) { - char *s,*r,*t; + const char *s,*r,*t; s = md->cont; if (s != NULL) @@ -226,7 +228,7 @@ md_continue_here:; md->argv++; } } - md->opt = t; + md->opt = (char*)t; md->cont = NULL; return *s; } @@ -244,7 +246,7 @@ md_continue_here:; static void ParseResolution(int res[2], const char *s) { - char *t = strchr(s, 'x'); + const char *t = strchr(s, 'x'); if (t == NULL) { ShowInfoF("Invalid resolution '%s'", s); return; @@ -308,7 +310,7 @@ static void LoadIntroGame(void) } _pause = 0; - SetLocalPlayer(0); + SetLocalPlayer(PLAYER_FIRST); /* Make sure you can't scroll in the menu */ _scrolling_viewport = 0; _cursor.fix_at = false; @@ -324,7 +326,6 @@ extern void DedicatedFork(void); int ttd_main(int argc, char *argv[]) { - MyGetOptData mgo; int i; const char *optformat; char musicdriver[16], sounddriver[16], videodriver[16]; @@ -356,7 +357,8 @@ int ttd_main(int argc, char *argv[]) #endif ; - MyGetOptInit(&mgo, argc-1, argv+1, optformat); + MyGetOptData mgo(argc-1, argv+1, optformat); + while ((i = MyGetOpt(&mgo)) != -1) { switch (i) { case 'm': ttd_strlcpy(musicdriver, mgo.opt, sizeof(musicdriver)); break; @@ -512,7 +514,7 @@ int ttd_main(int argc, char *argv[]) ParseConnectionString(&player, &port, network_conn); if (player != NULL) { - _network_playas = atoi(player); + _network_playas = (PlayerID)atoi(player); if (_network_playas != PLAYER_SPECTATOR) { _network_playas--; @@ -628,7 +630,7 @@ static void MakeNewGameDone(void) /* Create a single player */ DoStartupNewPlayer(false); - SetLocalPlayer(0); + SetLocalPlayer(PLAYER_FIRST); _current_player = _local_player; DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_SET_AUTOREPLACE); @@ -708,7 +710,7 @@ static void StartScenario(void) StartupEngines(); StartupDisasters(); - SetLocalPlayer(0); + SetLocalPlayer(PLAYER_FIRST); _current_player = _local_player; DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_SET_AUTOREPLACE); @@ -799,7 +801,7 @@ void SwitchMode(int new_mode) } else { /* Update the local player for a loaded game. It is either always * player #1 (eg 0) or in the case of a dedicated server a spectator */ - SetLocalPlayer(_network_dedicated ? PLAYER_SPECTATOR : 0); + SetLocalPlayer(_network_dedicated ? PLAYER_SPECTATOR : PLAYER_FIRST); DoCommandP(0, 0, 0, NULL, CMD_PAUSE); // decrease pause counter (was increased from opening load dialog) #ifdef ENABLE_NETWORK if (_network_server) { @@ -1096,7 +1098,7 @@ static void UpdateExclusiveRights(void) Town *t; FOR_ALL_TOWNS(t) { - t->exclusivity = (byte)-1; + t->exclusivity = INVALID_PLAYER; } /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete) @@ -1312,8 +1314,8 @@ bool AfterLoadGame(void) * becomes player 0, unless we are in the scenario editor where all the * players are 'invalid'. */ - if (!_network_dedicated && IsValidPlayer(0)) { - p = GetPlayer(0); + if (!_network_dedicated && IsValidPlayer(PLAYER_FIRST)) { + p = GetPlayer(PLAYER_FIRST); p->engine_renew = _patches.autorenew; p->engine_renew_months = _patches.autorenew_months; p->engine_renew_money = _patches.autorenew_money; @@ -1387,7 +1389,7 @@ bool AfterLoadGame(void) continue; } if (v->type == VEH_Train) { - v->u.rail.track = 0x40; + v->u.rail.track = TRACK_BIT_WORMHOLE; } else { v->u.road.state = 0xFF; } @@ -1567,10 +1569,9 @@ bool AfterLoadGame(void) { /* Set up the engine count for all players */ Player *players[MAX_PLAYERS]; - int i; const Vehicle *v; - for (i = 0; i < MAX_PLAYERS; i++) players[i] = GetPlayer(i); + for (PlayerID i = PLAYER_FIRST; i < MAX_PLAYERS; i++) players[i] = GetPlayer(i); FOR_ALL_VEHICLES(v) { if (!IsEngineCountable(v)) continue; @@ -1702,3 +1703,25 @@ void ReloadNewGRFData(void) /* redraw the whole screen */ MarkWholeScreenDirty(); } + +HalMusicDriver *_music_driver; +HalSoundDriver *_sound_driver; +HalVideoDriver *_video_driver; + +byte _dirkeys; // 1 = left, 2 = up, 4 = right, 8 = down +bool _fullscreen; +CursorVars _cursor; +bool _ctrl_pressed; // Is Ctrl pressed? +bool _shift_pressed; // Is Shift pressed? +byte _fast_forward; +bool _left_button_down; +bool _left_button_clicked; +bool _right_button_down; +bool _right_button_clicked; +DrawPixelInfo _screen; +bool _exit_game; +bool _networking; ///< are we in networking mode? +byte _game_mode; +byte _pause; +int _pal_first_dirty; +int _pal_last_dirty; diff --git a/src/openttd.h b/src/openttd.h index 912ae4d8d..e87ad09a5 100644 --- a/src/openttd.h +++ b/src/openttd.h @@ -8,9 +8,8 @@ #define VARDEF extern #endif -typedef struct Rect { - int left,top,right,bottom; -} Rect; +#include "hal.h" +#include "helpers.hpp" typedef struct Oblong { int x, y; @@ -22,10 +21,6 @@ typedef struct BoundingRect { int height; } BoundingRect; -typedef struct Point { - int x,y; -} Point; - typedef struct Pair { int a; int b; @@ -45,13 +40,11 @@ typedef struct Town Town; typedef struct NewsItem NewsItem; typedef struct Industry Industry; typedef struct DrawPixelInfo DrawPixelInfo; -typedef byte PlayerID; typedef byte VehicleOrderID; ///< The index of an order within its current vehicle (not pool related) typedef byte CargoID; typedef byte LandscapeID; typedef uint32 SpriteID; ///< The number of a sprite, without mapping bits and colortables typedef uint32 PalSpriteID; ///< The number of a sprite plus all the mapping bits and colortables -typedef uint32 CursorID; typedef uint16 EngineID; typedef uint16 UnitID; typedef uint16 StringID; @@ -77,7 +70,7 @@ assert_compile(sizeof(DestinationID) == sizeof(DepotID)); assert_compile(sizeof(DestinationID) == sizeof(WaypointID)); assert_compile(sizeof(DestinationID) == sizeof(StationID)); -typedef uint32 WindowNumber; +typedef int32 WindowNumber; typedef byte WindowClass; enum { @@ -89,12 +82,6 @@ typedef int32 Year; typedef int32 Date; -enum GameModes { - GM_MENU, - GM_NORMAL, - GM_EDITOR -}; - enum SwitchModes { SM_NONE = 0, SM_NEWGAME = 1, @@ -124,6 +111,32 @@ enum InitializeGameModes { IG_DATE_RESET = 1, /* Reset the date when initializing a game */ }; +enum Owner { + PLAYER_INACTIVE_CLIENT = 253, + PLAYER_NEW_COMPANY = 254, + PLAYER_SPECTATOR = 255, + OWNER_BEGIN = 0x00, + PLAYER_FIRST = 0x00, + MAX_PLAYERS = 8, + OWNER_TOWN = 0x0F, // a town owns the tile + OWNER_NONE = 0x10, // nobody owns the tile + OWNER_WATER = 0x11, // "water" owns the tile + OWNER_END = 0x12, + INVALID_OWNER = 0xFF, + INVALID_PLAYER = 0xFF, + /* Player identifiers All players below MAX_PLAYERS are playable + * players, above, they are special, computer controlled players */ +}; + +typedef Owner PlayerID; + +DECLARE_POSTFIX_INCREMENT(Owner); + +/** Define basic enum properties */ +template <> struct EnumPropsT<Owner> : MakeEnumPropsT<Owner, byte, OWNER_BEGIN, OWNER_END, INVALID_OWNER> {}; +typedef TinyEnumT<Owner> OwnerByte; +typedef OwnerByte PlayerByte; + typedef enum TransportTypes { /* These constants are for now linked to the representation of bridges @@ -132,6 +145,7 @@ typedef enum TransportTypes { * accessing tunnels and bridges. For now, you should just not change * the values for road and rail. */ + TRANSPORT_BEGIN = 0, TRANSPORT_RAIL = 0, TRANSPORT_ROAD = 1, TRANSPORT_WATER, // = 2 @@ -139,6 +153,11 @@ typedef enum TransportTypes { INVALID_TRANSPORT = 0xff, } TransportType; +/** Define basic enum properties */ +template <> struct EnumPropsT<TransportType> : MakeEnumPropsT<TransportType, byte, TRANSPORT_BEGIN, TRANSPORT_END, INVALID_TRANSPORT> {}; +typedef TinyEnumT<TransportType> TransportTypeByte; + + typedef struct TileInfo { uint x; uint y; diff --git a/src/order.h b/src/order.h index 7031f2455..ddc97481d 100644 --- a/src/order.h +++ b/src/order.h @@ -10,11 +10,13 @@ enum { INVALID_VEH_ORDER_ID = 0xFF, - INVALID_ORDER = 0xFFFF, }; +static const OrderID INVALID_ORDER = 0xFFFF; + /* Order types */ -enum OrderTypes { +enum OrderType { + OT_BEGIN = 0, OT_NOTHING = 0, OT_GOTO_STATION = 1, OT_GOTO_DEPOT = 2, @@ -22,9 +24,14 @@ enum OrderTypes { OT_LEAVESTATION = 4, OT_DUMMY = 5, OT_GOTO_WAYPOINT = 6, + OT_END }; + /* It needs to be 8bits, because we save and load it as such */ -typedef uint8 OrderType; +/** Define basic enum properties */ +template <> struct EnumPropsT<OrderType> : MakeEnumPropsT<OrderType, byte, OT_BEGIN, OT_END, OT_END> {}; +typedef TinyEnumT<OrderType> OrderTypeByte; + /* Order flags -- please use OFB instead OF and use HASBIT/SETBIT/CLEARBIT */ @@ -82,7 +89,7 @@ enum { * - REF_SHEDULE (all REFs are currently limited to 16 bits!!) */ typedef struct Order { - OrderType type; + OrderTypeByte type; uint8 flags; DestinationID dest; ///< The destionation of the order. diff --git a/src/order_cmd.cpp b/src/order_cmd.cpp index b510e84ea..7b89e7b54 100644 --- a/src/order_cmd.cpp +++ b/src/order_cmd.cpp @@ -38,7 +38,7 @@ DEFINE_OLD_POOL(Order, Order, OrderPoolNewBlock, NULL) Order UnpackOldOrder(uint16 packed) { Order order; - order.type = GB(packed, 0, 4); + order.type = (OrderType)GB(packed, 0, 4); order.flags = GB(packed, 4, 4); order.dest = GB(packed, 8, 8); order.next = NULL; @@ -65,7 +65,7 @@ Order UnpackOldOrder(uint16 packed) static Order UnpackVersion4Order(uint16 packed) { Order order; - order.type = GB(packed, 0, 4); + order.type = (OrderType)GB(packed, 0, 4); order.flags = GB(packed, 4, 4); order.dest = GB(packed, 8, 8); order.next = NULL; @@ -359,12 +359,12 @@ int32 CmdInsertOrder(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (flags & DC_EXEC) { Vehicle *u; - Order *new = AllocateOrder(); - AssignOrder(new, new_order); + Order *new_o = AllocateOrder(); + AssignOrder(new_o, new_order); /* Create new order and link in list */ if (v->orders == NULL) { - v->orders = new; + v->orders = new_o; } else { /* Try to get the previous item (we are inserting above the selected) */ @@ -375,17 +375,17 @@ int32 CmdInsertOrder(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) But because the orders can be shared, we copy the info over the v->orders, so we don't have to change the pointers of all vehicles */ - SwapOrders(v->orders, new); + SwapOrders(v->orders, new_o); /* Now update the next pointers */ - v->orders->next = new; + v->orders->next = new_o; } else if (order == NULL) { /* 'sel' is a non-existing order, add him to the end */ order = GetLastVehicleOrder(v); - order->next = new; + order->next = new_o; } else { /* Put the new order in between */ - new->next = order->next; - order->next = new; + new_o->next = order->next; + order->next = new_o; } } @@ -616,7 +616,7 @@ int32 CmdModifyOrder(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) * whether we are not going to a depot as there are three * cases where the full load flag can be active and only * one case where the flag is used for depot orders. In the - * other cases for the OrderType the flags are not used, + * other cases for the OrderTypeByte the flags are not used, * so do not care and those orders should not be active * when this function is called. */ @@ -1273,6 +1273,6 @@ static void Load_ORDR(void) } } -const ChunkHandler _order_chunk_handlers[] = { +extern const ChunkHandler _order_chunk_handlers[] = { { 'ORDR', Save_ORDR, Load_ORDR, CH_ARRAY | CH_LAST}, }; diff --git a/src/os/macosx/macos.h b/src/os/macosx/macos.h index b8a6cd511..ba33ce602 100644 --- a/src/os/macosx/macos.h +++ b/src/os/macosx/macos.h @@ -11,9 +11,15 @@ * the function then adds text that tells the user to update and then report the bug if it's present in the newest version * It also quits in a nice way since we call it when we know something happened that will crash OpenTTD (like a needed pointer turns out to be NULL or similar) */ -void ShowMacDialog ( const char *title, const char *message, const char *buttonLabel ); -void ShowMacAssertDialog ( const char *function, const char *file, const int line, const char *expression ); -void ShowMacErrorDialog(const char *error); +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + void ShowMacDialog ( const char *title, const char *message, const char *buttonLabel ); + void ShowMacAssertDialog ( const char *function, const char *file, const int line, const char *expression ); + void ShowMacErrorDialog(const char *error); +#ifdef __cplusplus +} +#endif //__cplusplus // Since MacOS X users will never see an assert unless they started the game from a terminal // we're using a custom assert(e) macro. diff --git a/src/os/macosx/macos.m b/src/os/macosx/macos.m index 59801fce0..33f296325 100644 --- a/src/os/macosx/macos.m +++ b/src/os/macosx/macos.m @@ -8,11 +8,7 @@ #include <mach/machine.h> #include <stdio.h> #include "../../stdafx.h" -#include "../../openttd.h" -#include "../../newgrf.h" -#include "../../gfx.h" #include "../../macros.h" -#include "../../string.h" #ifndef CPU_SUBTYPE_POWERPC_970 #define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100) @@ -26,6 +22,8 @@ * To insure that the crosscompiler still works, let him try any changes before they are committed */ +void ToggleFullScreen(bool fs); + static char *GetOSString(void) { static char buffer[175]; @@ -74,7 +72,7 @@ static char *GetOSString(void) } // make a list of used newgrf files - if (_first_grffile != NULL) { +/* if (_first_grffile != NULL) { char* n = newgrf; const GRFFile* file; @@ -82,9 +80,9 @@ static char *GetOSString(void) n = strecpy(n, " ", lastof(newgrf)); n = strecpy(n, file->filename, lastof(newgrf)); } - } else { + } else {*/ sprintf(newgrf, "none"); - } +// } snprintf( buffer, lengthof(buffer), diff --git a/src/os/macosx/splash.h b/src/os/macosx/splash.h index 39880562d..1bc4fa53c 100644 --- a/src/os/macosx/splash.h +++ b/src/os/macosx/splash.h @@ -5,6 +5,14 @@ #define SPLASH_IMAGE_FILE "splash.png" -void DisplaySplashImage(void); +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + + void DisplaySplashImage(void); + +#ifdef __cplusplus +} +#endif //__cplusplus #endif diff --git a/src/pathfind.cpp b/src/pathfind.cpp index 81ccc699c..6fc452647 100644 --- a/src/pathfind.cpp +++ b/src/pathfind.cpp @@ -114,16 +114,16 @@ static const byte _bits_mask[4] = { 0x2A, }; -static const byte _tpf_new_direction[14] = { - 0, 1, 0, 1, 2, 1, - 0, 0, - 2, 3, 3, 2, 3, 0, +static const DiagDirection _tpf_new_direction[14] = { + DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, + INVALID_DIAGDIR, INVALID_DIAGDIR, + DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, }; -static const byte _tpf_prev_direction[14] = { - 0, 1, 1, 0, 1, 2, - 0, 0, - 2, 3, 2, 3, 0, 3, +static const DiagDirection _tpf_prev_direction[14] = { + DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, + INVALID_DIAGDIR, INVALID_DIAGDIR, + DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, DIAGDIR_NW, }; @@ -182,7 +182,7 @@ static void TPFMode2(TrackPathFinder* tpf, TileIndex tile, DiagDirection directi } continue_here:; - tpf->the_dir = i + (HASBIT(_otherdir_mask[direction], i) ? 8 : 0); + tpf->the_dir = (Trackdir)(i + (HASBIT(_otherdir_mask[direction], i) ? 8 : 0)); if (!tpf->enum_proc(tile, tpf->userdata, tpf->the_dir, tpf->rd.cur_length, NULL)) { TPFMode2(tpf, tile, _tpf_new_direction[tpf->the_dir]); @@ -333,7 +333,7 @@ static void TPFMode1(TrackPathFinder* tpf, TileIndex tile, DiagDirection directi i = FIND_FIRST_BIT(bits); bits = KILL_FIRST_BIT(bits); - tpf->the_dir = (_otherdir_mask[direction] & (byte)(1 << i)) ? (i+8) : i; + tpf->the_dir = (Trackdir)((_otherdir_mask[direction] & (byte)(1 << i)) ? (i+8) : i); rd = tpf->rd; if (TPFSetTileBit(tpf, tile, tpf->the_dir) && @@ -375,7 +375,7 @@ static void TPFMode1(TrackPathFinder* tpf, TileIndex tile, DiagDirection directi i = FIND_FIRST_BIT(bits); bits = KILL_FIRST_BIT(bits); - tpf->the_dir = (_otherdir_mask[direction] & (byte)(1 << i)) ? (i+8) : i; + tpf->the_dir = (Trackdir)((_otherdir_mask[direction] & (byte)(1 << i)) ? (i+8) : i); rd = tpf->rd; if (TPFSetTileBit(tpf, tile, tpf->the_dir) && !tpf->enum_proc(tile, tpf->userdata, tpf->the_dir, tpf->rd.cur_length, &tpf->rd.pft_var6) ) { @@ -407,11 +407,11 @@ void FollowTrack(TileIndex tile, uint16 flags, DiagDirection direction, TPFEnumP tpf.hasbit_13 = HASBIT(flags, 13); /* 0x2000 */ - tpf.tracktype = (byte)flags; + tpf.tracktype = (TransportType)(flags & 0xFF); if (HASBIT(flags, 11)) { tpf.rd.pft_var6 = 0xFF; - tpf.enum_proc(tile, data, 0, 0, 0); + tpf.enum_proc(tile, data, INVALID_TRACKDIR, 0, 0); TPFMode2(&tpf, tile, direction); } else { /* clear the hash_heads */ @@ -427,19 +427,19 @@ typedef struct { TileIndex tile; uint16 cur_length; // This is the current length to this tile. uint16 priority; // This is the current length + estimated length to the goal. - byte track; + TrackdirByte track; byte depth; byte state; byte first_track; } StackedItem; -static const byte _new_track[6][4] = { -{0, 0xff, 8, 0xff,}, -{0xff, 1, 0xff, 9,}, -{0xff, 2, 10, 0xff,}, -{3, 0xff, 0xff, 11,}, -{12, 4, 0xff, 0xff,}, -{0xff, 0xff, 5, 13,}, +static const Trackdir _new_trackdir[6][4] = { +{TRACKDIR_X_NE, INVALID_TRACKDIR, TRACKDIR_X_SW, INVALID_TRACKDIR,}, +{INVALID_TRACKDIR, TRACKDIR_Y_SE, INVALID_TRACKDIR, TRACKDIR_Y_NW,}, +{INVALID_TRACKDIR, TRACKDIR_UPPER_E, TRACKDIR_UPPER_W, INVALID_TRACKDIR,}, +{TRACKDIR_LOWER_E, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_LOWER_W,}, +{TRACKDIR_LEFT_N, TRACKDIR_LEFT_S, INVALID_TRACKDIR, INVALID_TRACKDIR,}, +{INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_RIGHT_S, TRACKDIR_RIGHT_N,}, }; typedef struct HashLink { @@ -539,7 +539,7 @@ static bool NtpVisit(NewTrackPathFinder* tpf, TileIndex tile, DiagDirection dir, } if (head != 0xffff) { - if (tile == tpf->hash_tile[hash] && (head & 0x3) == dir) { + if (tile == tpf->hash_tile[hash] && (head & 0x3) == (uint)dir) { // longer length if (length >= (head >> 2)) return false; @@ -574,7 +574,7 @@ static bool NtpVisit(NewTrackPathFinder* tpf, TileIndex tile, DiagDirection dir, uint offs = tpf->hash_tile[hash]; do { link = NTP_GET_LINK_PTR(tpf, offs); - if (tile == link->tile && (link->typelength & 0x3U) == dir) { + if (tile == link->tile && (link->typelength & 0x3U) == (uint)dir) { if (length >= (uint)(link->typelength >> 2)) return false; link->typelength = dir | (length << 2); return true; @@ -657,8 +657,8 @@ static const uint16 _is_upwards_slope[15] = { static uint DistanceMoo(TileIndex t0, TileIndex t1) { - const uint dx = abs(TileX(t0) - TileX(t1)); - const uint dy = abs(TileY(t0) - TileY(t1)); + const uint dx = delta(TileX(t0), TileX(t1)); + const uint dy = delta(TileY(t0), TileY(t1)); const uint straightTracks = 2 * min(dx, dy); /* The number of straight (not full length) tracks */ /* OPTIMISATION: @@ -685,7 +685,7 @@ static const byte _length_of_track[16] = { static void NTPEnum(NewTrackPathFinder* tpf, TileIndex tile, DiagDirection direction) { TrackBits bits, allbits; - uint track; + Trackdir track; TileIndex tile_org; StackedItem si; int estimation; @@ -737,7 +737,7 @@ start_at: continue; } if (!HASBIT(tpf->railtypes, GetRailType(tile))) { - bits = 0; + bits = TRACK_BIT_NONE; break; } flotr = FindLengthOfTunnel(tile, direction); @@ -771,7 +771,7 @@ start_at: // too long search length? bail out. if (si.cur_length >= tpf->maxlength) { DEBUG(ntp, 1, "Cur_length too big"); - bits = 0; + bits = TRACK_BIT_NONE; break; } @@ -780,14 +780,14 @@ start_at: if (!IsTileType(tile, MP_RAILWAY) || !IsPlainRailTile(tile)) { // We found a tile which is not a normal railway tile. // Determine which tracks that exist on this tile. - bits = GetTileTrackStatus(tile, TRANSPORT_RAIL) & _tpfmode1_and[direction]; - bits = (bits | (bits >> 8)) & 0x3F; + uint32 ts = GetTileTrackStatus(tile, TRANSPORT_RAIL) & _tpfmode1_and[direction]; + bits = TrackdirBitsToTrackBits((TrackdirBits)(ts & TRACKDIR_BIT_MASK)); // Check that the tile contains exactly one track if (bits == 0 || KILL_FIRST_BIT(bits) != 0) break; if (!HASBIT(tpf->railtypes, IsTileType(tile, MP_STREET) ? GetRailTypeCrossing(tile) : GetRailType(tile))) { - bits = 0; + bits = TRACK_BIT_NONE; break; } @@ -797,7 +797,7 @@ start_at: // bits - bitmask of which track that exist on the tile (exactly one bit is set) // direction - which direction are we moving in? /////////////////// - si.track = _new_track[FIND_FIRST_BIT(bits)][direction]; + si.track = _new_trackdir[FIND_FIRST_BIT(bits)][direction]; si.cur_length += _length_of_track[si.track]; goto callback_and_continue; } @@ -810,18 +810,18 @@ start_at: /* The tile has no reachable tracks => End of rail segment * or Intersection => End of rail segment. We check this agains all the * bits, not just reachable ones, to prevent infinite loops. */ - if (bits == 0 || TracksOverlap(allbits)) break; + if (bits == TRACK_BIT_NONE || TracksOverlap(allbits)) break; if (!HASBIT(tpf->railtypes, GetRailType(tile))) { - bits = 0; + bits = TRACK_BIT_NONE; break; } /* If we reach here, the tile has exactly one track, and this track is reachable => Rail segment continues */ - track = _new_track[FIND_FIRST_BIT(bits)][direction]; - assert(track != 0xff); + track = _new_trackdir[FIND_FIRST_BIT(bits)][direction]; + assert(track != INVALID_TRACKDIR); si.cur_length += _length_of_track[track]; @@ -837,7 +837,7 @@ start_at: if (!HasSignalOnTrackdir(tile, track)) { // if one way signal not pointing towards us, stop going in this direction => End of rail segment. if (HasSignalOnTrackdir(tile, ReverseTrackdir(track))) { - bits = 0; + bits = TRACK_BIT_NONE; break; } } else if (GetSignalStateByTrackdir(tile, track) == SIGNAL_STATE_GREEN) { @@ -850,7 +850,7 @@ start_at: // stop going in this direction => End of rail segment. // this is to prevent us from going into a full platform. if (!(si.state&1)) { - bits = 0; + bits = TRACK_BIT_NONE; break; } } @@ -874,14 +874,14 @@ start_at: // safety check if we're running around chasing our tail... (infinite loop) if (tile == tile_org) { - bits = 0; + bits = TRACK_BIT_NONE; break; } } // There are no tracks to choose between. // Stop searching in this direction - if (bits == 0) + if (bits == TRACK_BIT_NONE) continue; //////////////// @@ -909,8 +909,9 @@ start_at: if (si.depth == 0) continue; /* We overflowed our depth. No more searching in this direction. */ si.tile = tile; - do { - si.track = _new_track[FIND_FIRST_BIT(bits)][direction]; + while (bits != TRACK_BIT_NONE) { + Track track = RemoveFirstTrack(bits); + si.track = _new_trackdir[track][direction]; assert(si.track != 0xFF); si.priority = si.cur_length + estimation; @@ -922,7 +923,7 @@ start_at: tpf->stack[tpf->nstack] = si; HeapifyUp(tpf); - } while ((bits = KILL_FIRST_BIT(bits)) != 0); + }; // If this is the first intersection, we need to fill the first_track member. // so the code outside knows which path is better. @@ -931,11 +932,11 @@ start_at: assert(tpf->nstack == 1 || tpf->nstack == 2 || tpf->nstack == 3); if (tpf->nstack != 1) { uint32 r = Random(); - if (r&1) swap_byte(&tpf->stack[0].track, &tpf->stack[1].track); + if (r&1) SwapT(&tpf->stack[0].track, &tpf->stack[1].track); if (tpf->nstack != 2) { - byte t = tpf->stack[2].track; - if (r&2) swap_byte(&tpf->stack[0].track, &t); - if (r&4) swap_byte(&tpf->stack[1].track, &t); + TrackdirByte t = tpf->stack[2].track; + if (r&2) SwapT(&tpf->stack[0].track, &t); + if (r&4) SwapT(&tpf->stack[1].track, &t); tpf->stack[2].first_track = tpf->stack[2].track = t; } tpf->stack[0].first_track = tpf->stack[0].track; diff --git a/src/pathfind.h b/src/pathfind.h index 432d7ea88..6c0dccad1 100644 --- a/src/pathfind.h +++ b/src/pathfind.h @@ -4,6 +4,7 @@ #define PATHFIND_H #include "direction.h" +#include "openttd.h" enum { STR_FACTOR = 2, @@ -14,7 +15,7 @@ enum { //supported on all archs) typedef struct TrackPathFinder TrackPathFinder; -typedef bool TPFEnumProc(TileIndex tile, void *data, int track, uint length, byte *state); +typedef bool TPFEnumProc(TileIndex tile, void *data, Trackdir trackdir, uint length, byte *state); typedef void TPFAfterProc(TrackPathFinder *tpf); typedef bool NTPEnumProc(TileIndex tile, void *data, int track, uint length); @@ -51,9 +52,9 @@ struct TrackPathFinder { RememberData rd; - int the_dir; + TrackdirByte the_dir; - byte tracktype; + TransportTypeByte tracktype; byte var2; bool disable_tile_hash; bool hasbit_13; diff --git a/src/player.h b/src/player.h index df959c6e0..e3329c0d1 100644 --- a/src/player.h +++ b/src/player.h @@ -38,7 +38,7 @@ typedef struct PlayerAI { byte state_mode; byte banned_tile_count; - byte railtype_to_use; + RailTypeByte railtype_to_use; CargoID cargo_type; byte num_wagons; @@ -132,7 +132,7 @@ typedef struct PlayerAiNew { bool to_deliver; TileIndex depot_tile; - byte depot_direction; + DiagDirectionByte depot_direction; byte amount_veh; // How many vehicles we are going to build in this route byte cur_veh; // How many vehicles did we bought? @@ -166,14 +166,14 @@ typedef struct Player { byte player_money_fraction; byte avail_railtypes; byte block_preview; - PlayerID index; + PlayerByte index; uint16 cargo_types; /* which cargo types were transported the last year */ TileIndex location_of_house; TileIndex last_build_coordinate; - PlayerID share_owners[4]; + PlayerByte share_owners[4]; Year inaugurated_year; byte num_valid_stat_ent; @@ -212,15 +212,6 @@ void SetLocalPlayer(PlayerID new_player); VARDEF PlayerID _local_player; VARDEF PlayerID _current_player; -/* Player identifiers All players below MAX_PLAYERS are playable - * players, above, they are special, computer controlled players */ -enum Players { - PLAYER_INACTIVE_CLIENT = 253, - PLAYER_NEW_COMPANY = 254, ///< Command 'player' in Multiplayer to create a new company - PLAYER_SPECTATOR = 255, ///< Spectator in Multiplayer or the player in the scenario editor - MAX_PLAYERS = 8, -}; - VARDEF Player _players[MAX_PLAYERS]; // NOSAVE: can be determined from player structs VARDEF byte _player_colors[MAX_PLAYERS]; @@ -239,7 +230,7 @@ static inline byte ActivePlayerCount(void) static inline Player* GetPlayer(PlayerID i) { - assert(i < lengthof(_players)); + assert(i < (PlayerID)lengthof(_players)); return &_players[i]; } diff --git a/src/player_gui.cpp b/src/player_gui.cpp index c4612f5dc..1a2563d3b 100644 --- a/src/player_gui.cpp +++ b/src/player_gui.cpp @@ -148,7 +148,7 @@ static void PlayerFinancesWndProc(Window *w, WindowEvent *e) { switch (e->event) { case WE_PAINT: { - PlayerID player = w->window_number; + PlayerID player = (PlayerID)w->window_number; const Player *p = GetPlayer(player); if (player == _local_player) { @@ -170,7 +170,7 @@ static void PlayerFinancesWndProc(Window *w, WindowEvent *e) case 2: {/* toggle size */ byte mode = (byte)WP(w,def_d).data_1; bool stickied = !!(w->flags4 & WF_STICKY); - PlayerID player = w->window_number; + PlayerID player = (PlayerID)w->window_number; DeleteWindow(w); DoShowPlayerFinances(player, !HASBIT(mode, 0), stickied); } break; @@ -305,11 +305,11 @@ static void ShowColourDropDownMenu(Window *w, uint32 widget) } /* Get the first selected livery to use as the default dropdown item */ - for (scheme = 0; scheme < LS_END; scheme++) { + for (scheme = LS_BEGIN; scheme < LS_END; scheme++) { if (HASBIT(WP(w, livery_d).sel, scheme)) break; } if (scheme == LS_END) scheme = LS_DEFAULT; - livery = &GetPlayer(w->window_number)->livery[scheme]; + livery = &GetPlayer((PlayerID)w->window_number)->livery[scheme]; ShowDropDownMenu(w, _colour_dropdown, widget == 10 ? livery->colour1 : livery->colour2, widget, used_colours, 0); } @@ -326,7 +326,7 @@ static void SelectPlayerLiveryWndProc(Window *w, WindowEvent *e) break; case WE_PAINT: { - const Player *p = GetPlayer(w->window_number); + const Player *p = GetPlayer((PlayerID)w->window_number); LiveryScheme scheme = LS_DEFAULT; int y = 51; @@ -337,7 +337,7 @@ static void SelectPlayerLiveryWndProc(Window *w, WindowEvent *e) SetWindowWidgetDisabledState(w, 12, (WP(w, livery_d).sel == 0)); if (!(WP(w, livery_d).sel == 0)) { - for (scheme = 0; scheme < LS_END; scheme++) { + for (scheme = LS_BEGIN; scheme < LS_END; scheme++) { if (HASBIT(WP(w, livery_d).sel, scheme)) break; } if (scheme == LS_END) scheme = LS_DEFAULT; @@ -383,7 +383,7 @@ static void SelectPlayerLiveryWndProc(Window *w, WindowEvent *e) LiveryScheme scheme; RaiseWindowWidget(w, WP(w, livery_d).livery_class + 2); - WP(w, livery_d).livery_class = e->we.click.widget - 2; + WP(w, livery_d).livery_class = (LiveryClass)(e->we.click.widget - 2); WP(w, livery_d).sel = 0; LowerWindowWidget(w, WP(w, livery_d).livery_class + 2); @@ -413,9 +413,9 @@ static void SelectPlayerLiveryWndProc(Window *w, WindowEvent *e) case 13: { LiveryScheme scheme; - LiveryScheme j = (e->we.click.pt.y - 48) / 14; + LiveryScheme j = (LiveryScheme)((e->we.click.pt.y - 48) / 14); - for (scheme = 0; scheme <= j; scheme++) { + for (scheme = LS_BEGIN; scheme <= j; scheme++) { if (livery_class[scheme] != WP(w, livery_d).livery_class) j++; if (scheme >= LS_END) return; } @@ -423,7 +423,7 @@ static void SelectPlayerLiveryWndProc(Window *w, WindowEvent *e) /* If clicking on the left edge, toggle using the livery */ if (e->we.click.pt.x < 10) { - DoCommandP(0, j | (2 << 8), !GetPlayer(w->window_number)->livery[j].in_use, NULL, CMD_SET_PLAYER_COLOR); + DoCommandP(0, j | (2 << 8), !GetPlayer((PlayerID)w->window_number)->livery[j].in_use, NULL, CMD_SET_PLAYER_COLOR); } if (_ctrl_pressed) { @@ -511,7 +511,7 @@ static void SelectPlayerFaceWndProc(Window *w, WindowEvent *e) Player *p; LowerWindowWidget(w, WP(w, facesel_d).gender + 5); DrawWindowWidgets(w); - p = GetPlayer(w->window_number); + p = GetPlayer((PlayerID)w->window_number); DrawPlayerFace(WP(w,facesel_d).face, p->player_color, 2, 16); } break; @@ -675,7 +675,7 @@ static void PlayerCompanyWndProc(Window *w, WindowEvent *e) { switch (e->event) { case WE_PAINT: { - const Player *p = GetPlayer(w->window_number); + const Player *p = GetPlayer((PlayerID)w->window_number); bool local = w->window_number == _local_player; SetWindowWidgetHiddenState(w, PCW_WIDGET_NEW_FACE, !local); @@ -711,14 +711,14 @@ static void PlayerCompanyWndProc(Window *w, WindowEvent *e) SetDParam(0, p->name_1); SetDParam(1, p->name_2); - SetDParam(2, GetPlayerNameString((byte)w->window_number, 3)); + SetDParam(2, GetPlayerNameString((PlayerID)w->window_number, 3)); DrawWindowWidgets(w); SetDParam(0, p->inaugurated_year); DrawString(110, 25, STR_7038_INAUGURATED, 0); - DrawPlayerVehiclesAmount(w->window_number); + DrawPlayerVehiclesAmount((PlayerID)w->window_number); DrawString(110,48, STR_7006_COLOR_SCHEME, 0); // Draw company-colour bus @@ -744,7 +744,7 @@ static void PlayerCompanyWndProc(Window *w, WindowEvent *e) Window *wf = AllocateWindowDescFront(&_select_player_face_desc, w->window_number); if (wf != NULL) { wf->caption_color = w->window_number; - WP(wf,facesel_d).face = GetPlayer(wf->window_number)->face; + WP(wf,facesel_d).face = GetPlayer((PlayerID)wf->window_number)->face; WP(wf,facesel_d).gender = 0; } break; @@ -762,7 +762,7 @@ static void PlayerCompanyWndProc(Window *w, WindowEvent *e) } case PCW_WIDGET_PRESIDENT_NAME: { - const Player *p = GetPlayer(w->window_number); + const Player *p = GetPlayer((PlayerID)w->window_number); WP(w, def_d).byte_1 = 0; SetDParam(0, p->president_name_2); ShowQueryString(p->president_name_1, STR_700B_PRESIDENT_S_NAME, 31, 94, w, CS_ALPHANUMERAL); @@ -770,7 +770,7 @@ static void PlayerCompanyWndProc(Window *w, WindowEvent *e) } case PCW_WIDGET_COMPANY_NAME: { - Player *p = GetPlayer(w->window_number); + Player *p = GetPlayer((PlayerID)w->window_number); WP(w,def_d).byte_1 = 1; SetDParam(0, p->name_2); ShowQueryString(p->name_1, STR_700A_COMPANY_NAME, 31, 150, w, CS_ALPHANUMERAL); @@ -778,7 +778,7 @@ static void PlayerCompanyWndProc(Window *w, WindowEvent *e) } case PCW_WIDGET_BUILD_VIEW_HQ: { - TileIndex tile = GetPlayer(w->window_number)->location_of_house; + TileIndex tile = GetPlayer((PlayerID)w->window_number)->location_of_house; if (tile == 0) { if ((byte)w->window_number != _local_player) return; @@ -890,7 +890,7 @@ static void BuyCompanyWndProc(Window *w, WindowEvent *e) { switch (e->event) { case WE_PAINT: { - Player *p = GetPlayer(w->window_number); + Player *p = GetPlayer((PlayerID)w->window_number); SetDParam(0, p->name_1); SetDParam(1, p->name_2); DrawWindowWidgets(w); diff --git a/src/players.cpp b/src/players.cpp index 4c2d1ed37..6d295d87d 100644 --- a/src/players.cpp +++ b/src/players.cpp @@ -483,7 +483,7 @@ static Player *AllocatePlayer(void) // Find a free slot FOR_ALL_PLAYERS(p) { if (!p->is_active) { - int i = p->index; + PlayerID i = p->index; memset(p, 0, sizeof(Player)); p->index = i; return p; @@ -494,9 +494,7 @@ static Player *AllocatePlayer(void) void ResetPlayerLivery(Player *p) { - LiveryScheme scheme; - - for (scheme = 0; scheme < LS_END; scheme++) { + for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) { p->livery[scheme].in_use = false; p->livery[scheme].colour1 = p->player_color; p->livery[scheme].colour2 = p->player_color; @@ -583,10 +581,8 @@ static void MaybeStartNewPlayer(void) void InitializePlayers(void) { - uint i; - memset(_players, 0, sizeof(_players)); - for (i = 0; i != MAX_PLAYERS; i++) _players[i].index = i; + for (PlayerID i = PLAYER_FIRST; i != MAX_PLAYERS; i++) _players[i].index = i; _cur_player_tick_index = 0; } @@ -596,7 +592,7 @@ void OnTick_Players(void) if (_game_mode == GM_EDITOR) return; - p = GetPlayer(_cur_player_tick_index); + p = GetPlayer((PlayerID)_cur_player_tick_index); _cur_player_tick_index = (_cur_player_tick_index + 1) % MAX_PLAYERS; if (p->name_1 != 0) GenerateCompanyName(p); @@ -614,7 +610,7 @@ StringID GetPlayerNameString(PlayerID player, uint index) return STR_EMPTY; } -extern void ShowPlayerFinances(int player); +extern void ShowPlayerFinances(PlayerID player); void PlayersYearlyLoop(void) { @@ -928,11 +924,11 @@ int32 CmdPlayerCtrl(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) case 2: { /* Delete a player */ Player *p; - if (!IsValidPlayer(p2)) return CMD_ERROR; + if (!IsValidPlayer((PlayerID)p2)) return CMD_ERROR; if (!(flags & DC_EXEC)) return 0; - p = GetPlayer(p2); + p = GetPlayer((PlayerID)p2); /* Only allow removal of HUMAN companies */ if (IsHumanPlayer(p->index)) { @@ -953,8 +949,8 @@ int32 CmdPlayerCtrl(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) } break; case 3: { /* Merge a company (#1) into another company (#2), elimination company #1 */ - PlayerID pid_old = GB(p2, 0, 16); - PlayerID pid_new = GB(p2, 16, 16); + PlayerID pid_old = (PlayerID)GB(p2, 0, 16); + PlayerID pid_new = (PlayerID)GB(p2, 16, 16); if (!IsValidPlayer(pid_old) || !IsValidPlayer(pid_new)) return CMD_ERROR; @@ -1323,7 +1319,7 @@ static void Load_PLYR(void) { int index; while ((index = SlIterateArray()) != -1) { - Player *p = GetPlayer(index); + Player *p = GetPlayer((PlayerID)index); SaveLoad_PLYR(p); _player_colors[index] = p->player_color; UpdatePlayerMoney32(p); @@ -1334,6 +1330,6 @@ static void Load_PLYR(void) } } -const ChunkHandler _player_chunk_handlers[] = { +extern const ChunkHandler _player_chunk_handlers[] = { { 'PLYR', Save_PLYR, Load_PLYR, CH_ARRAY | CH_LAST}, }; diff --git a/src/queue.cpp b/src/queue.cpp index 9986442bf..44ace52e5 100644 --- a/src/queue.cpp +++ b/src/queue.cpp @@ -3,6 +3,7 @@ #include "stdafx.h" #include "openttd.h" #include "queue.h" +#include "helpers.hpp" static void Stack_Clear(Queue* q, bool free_values) { @@ -48,14 +49,15 @@ static Queue* init_stack(Queue* q, uint max_size) q->free = Stack_Free; q->data.stack.max_size = max_size; q->data.stack.size = 0; - q->data.stack.elements = malloc(max_size * sizeof(*q->data.stack.elements)); + MallocT(&q->data.stack.elements, max_size); q->freeq = false; return q; } Queue* new_Stack(uint max_size) { - Queue* q = malloc(sizeof(*q)); + Queue* q; + MallocT(&q, 1); init_stack(q, max_size); q->freeq = true; @@ -125,14 +127,15 @@ static Queue* init_fifo(Queue* q, uint max_size) q->data.fifo.max_size = max_size; q->data.fifo.head = 0; q->data.fifo.tail = 0; - q->data.fifo.elements = malloc(max_size * sizeof(*q->data.fifo.elements)); + MallocT(&q->data.fifo.elements, max_size); q->freeq = false; return q; } Queue* new_Fifo(uint max_size) { - Queue* q = malloc(sizeof(*q)); + Queue* q; + MallocT(&q, 1); init_fifo(q, max_size); q->freeq = true; @@ -166,7 +169,8 @@ static void InsSort_Free(Queue* q, bool free_values) static bool InsSort_Push(Queue* q, void* item, int priority) { - InsSortNode* newnode = malloc(sizeof(*newnode)); + InsSortNode* newnode; + MallocT(&newnode, 1); if (newnode == NULL) return false; newnode->item = item; @@ -220,7 +224,8 @@ void init_InsSort(Queue* q) Queue* new_InsSort(void) { - Queue* q = malloc(sizeof(*q)); + Queue* q; + MallocT(&q, 1); init_InsSort(q); q->freeq = true; @@ -299,7 +304,7 @@ static bool BinaryHeap_Push(Queue* q, void* item, int priority) if (q->data.binaryheap.elements[q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS] == NULL) { /* The currently allocated blocks are full, allocate a new one */ assert((q->data.binaryheap.size & BINARY_HEAP_BLOCKSIZE_MASK) == 0); - q->data.binaryheap.elements[q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS] = malloc(BINARY_HEAP_BLOCKSIZE * sizeof(*q->data.binaryheap.elements[0])); + MallocT(&q->data.binaryheap.elements[q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS], BINARY_HEAP_BLOCKSIZE); q->data.binaryheap.blocks++; #ifdef QUEUE_DEBUG printf("[BinaryHeap] Increasing size of elements to %d nodes\n", q->data.binaryheap.blocks * BINARY_HEAP_BLOCKSIZE); @@ -427,8 +432,8 @@ void init_BinaryHeap(Queue* q, uint max_size) q->data.binaryheap.size = 0; // We malloc memory in block of BINARY_HEAP_BLOCKSIZE // It autosizes when it runs out of memory - q->data.binaryheap.elements = calloc((max_size - 1) / BINARY_HEAP_BLOCKSIZE + 1, sizeof(*q->data.binaryheap.elements)); - q->data.binaryheap.elements[0] = malloc(BINARY_HEAP_BLOCKSIZE * sizeof(*q->data.binaryheap.elements[0])); + CallocT(&q->data.binaryheap.elements, (max_size - 1) / BINARY_HEAP_BLOCKSIZE + 1); + MallocT(&q->data.binaryheap.elements[0], BINARY_HEAP_BLOCKSIZE); q->data.binaryheap.blocks = 1; q->freeq = false; #ifdef QUEUE_DEBUG @@ -438,7 +443,8 @@ void init_BinaryHeap(Queue* q, uint max_size) Queue* new_BinaryHeap(uint max_size) { - Queue* q = malloc(sizeof(*q)); + Queue* q; + MallocT(&q, 1); init_BinaryHeap(q, max_size); q->freeq = true; @@ -464,7 +470,7 @@ void init_Hash(Hash* h, Hash_HashProc* hash, uint num_buckets) h->hash = hash; h->size = 0; h->num_buckets = num_buckets; - h->buckets = malloc(num_buckets * (sizeof(*h->buckets) + sizeof(*h->buckets_in_use))); + h->buckets = (HashNode*)malloc(num_buckets * (sizeof(*h->buckets) + sizeof(*h->buckets_in_use))); #ifdef HASH_DEBUG debug("Buckets = %p", h->buckets); #endif @@ -475,7 +481,8 @@ void init_Hash(Hash* h, Hash_HashProc* hash, uint num_buckets) Hash* new_Hash(Hash_HashProc* hash, int num_buckets) { - Hash* h = malloc(sizeof(*h)); + Hash* h; + MallocT(&h, 1); init_Hash(h, hash, num_buckets); h->freeh = true; @@ -709,7 +716,7 @@ void* Hash_Set(Hash* h, uint key1, uint key2, void* value) node = h->buckets + hash; } else { /* Add it after prev */ - node = malloc(sizeof(*node)); + MallocT(&node, 1); prev->next = node; } node->next = NULL; diff --git a/src/rail.cpp b/src/rail.cpp index c4b20de27..2255b428b 100644 --- a/src/rail.cpp +++ b/src/rail.cpp @@ -10,41 +10,41 @@ /* XXX: Below 3 tables store duplicate data. Maybe remove some? */ /* Maps a trackdir to the bit that stores its status in the map arrays, in the * direction along with the trackdir */ -const byte _signal_along_trackdir[] = { +extern const byte _signal_along_trackdir[] = { 0x80, 0x80, 0x80, 0x20, 0x40, 0x10, 0, 0, 0x40, 0x40, 0x40, 0x10, 0x80, 0x20 }; /* Maps a trackdir to the bit that stores its status in the map arrays, in the * direction against the trackdir */ -const byte _signal_against_trackdir[] = { +extern const byte _signal_against_trackdir[] = { 0x40, 0x40, 0x40, 0x10, 0x80, 0x20, 0, 0, 0x80, 0x80, 0x80, 0x20, 0x40, 0x10 }; /* Maps a Track to the bits that store the status of the two signals that can * be present on the given track */ -const byte _signal_on_track[] = { +extern const byte _signal_on_track[] = { 0xC0, 0xC0, 0xC0, 0x30, 0xC0, 0x30 }; /* Maps a diagonal direction to the all trackdirs that are connected to any * track entering in this direction (including those making 90 degree turns) */ -const TrackdirBits _exitdir_reaches_trackdirs[] = { +extern const TrackdirBits _exitdir_reaches_trackdirs[] = { TRACKDIR_BIT_X_NE | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_LEFT_N, /* DIAGDIR_NE */ TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_UPPER_E, /* DIAGDIR_SE */ TRACKDIR_BIT_X_SW | TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_RIGHT_S, /* DIAGDIR_SW */ TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_W /* DIAGDIR_NW */ }; -const Trackdir _next_trackdir[] = { +extern const Trackdir _next_trackdir[] = { TRACKDIR_X_NE, TRACKDIR_Y_SE, TRACKDIR_LOWER_E, TRACKDIR_UPPER_E, TRACKDIR_RIGHT_S, TRACKDIR_LEFT_S, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_LOWER_W, TRACKDIR_UPPER_W, TRACKDIR_RIGHT_N, TRACKDIR_LEFT_N }; /* Maps a trackdir to all trackdirs that make 90 deg turns with it. */ -const TrackdirBits _track_crosses_trackdirs[] = { +extern const TrackdirBits _track_crosses_trackdirs[] = { TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_Y_NW, /* TRACK_X */ TRACKDIR_BIT_X_NE | TRACKDIR_BIT_X_SW, /* TRACK_Y */ TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_LEFT_S, /* TRACK_UPPER */ @@ -54,7 +54,7 @@ const TrackdirBits _track_crosses_trackdirs[] = { }; /* Maps a track to all tracks that make 90 deg turns with it. */ -const TrackBits _track_crosses_tracks[] = { +extern const TrackBits _track_crosses_tracks[] = { TRACK_BIT_Y, /* TRACK_X */ TRACK_BIT_X, /* TRACK_Y */ TRACK_BIT_VERT, /* TRACK_UPPER */ @@ -65,12 +65,12 @@ const TrackBits _track_crosses_tracks[] = { /* Maps a trackdir to the (4-way) direction the tile is exited when following * that trackdir */ -const DiagDirection _trackdir_to_exitdir[] = { +extern const DiagDirection _trackdir_to_exitdir[] = { DIAGDIR_NE,DIAGDIR_SE,DIAGDIR_NE,DIAGDIR_SE,DIAGDIR_SW,DIAGDIR_SE, DIAGDIR_NE,DIAGDIR_NE, DIAGDIR_SW,DIAGDIR_NW,DIAGDIR_NW,DIAGDIR_SW,DIAGDIR_NW,DIAGDIR_NE, }; -const Trackdir _track_exitdir_to_trackdir[][DIAGDIR_END] = { +extern const Trackdir _track_exitdir_to_trackdir[][DIAGDIR_END] = { {TRACKDIR_X_NE, INVALID_TRACKDIR, TRACKDIR_X_SW, INVALID_TRACKDIR}, {INVALID_TRACKDIR, TRACKDIR_Y_SE, INVALID_TRACKDIR, TRACKDIR_Y_NW}, {TRACKDIR_UPPER_E, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_UPPER_W}, @@ -79,7 +79,7 @@ const Trackdir _track_exitdir_to_trackdir[][DIAGDIR_END] = { {TRACKDIR_RIGHT_N, TRACKDIR_RIGHT_S, INVALID_TRACKDIR, INVALID_TRACKDIR} }; -const Trackdir _track_enterdir_to_trackdir[][DIAGDIR_END] = { // TODO: replace magic with enums +extern const Trackdir _track_enterdir_to_trackdir[][DIAGDIR_END] = { // TODO: replace magic with enums {TRACKDIR_X_NE, INVALID_TRACKDIR, TRACKDIR_X_SW, INVALID_TRACKDIR}, {INVALID_TRACKDIR, TRACKDIR_Y_SE, INVALID_TRACKDIR, TRACKDIR_Y_NW}, {INVALID_TRACKDIR, TRACKDIR_UPPER_E, TRACKDIR_UPPER_W, INVALID_TRACKDIR}, @@ -88,7 +88,7 @@ const Trackdir _track_enterdir_to_trackdir[][DIAGDIR_END] = { // TODO: replace m {INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_RIGHT_S, TRACKDIR_RIGHT_N} }; -const Trackdir _track_direction_to_trackdir[][DIR_END] = { +extern const Trackdir _track_direction_to_trackdir[][DIR_END] = { {INVALID_TRACKDIR, TRACKDIR_X_NE, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_X_SW, INVALID_TRACKDIR, INVALID_TRACKDIR}, {INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_Y_SE, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_Y_NW}, {INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_UPPER_E, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_UPPER_W, INVALID_TRACKDIR}, @@ -97,12 +97,12 @@ const Trackdir _track_direction_to_trackdir[][DIR_END] = { {TRACKDIR_RIGHT_N, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_RIGHT_S, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR} }; -const Trackdir _dir_to_diag_trackdir[] = { +extern const Trackdir _dir_to_diag_trackdir[] = { TRACKDIR_X_NE, TRACKDIR_Y_SE, TRACKDIR_X_SW, TRACKDIR_Y_NW, }; -RailType GetTileRailType(TileIndex tile, Trackdir trackdir) +RailType GetTileRailType(TileIndex tile, Track track) { switch (GetTileType(tile)) { case MP_RAILWAY: diff --git a/src/rail.h b/src/rail.h index 37270a1bf..aaadc9060 100644 --- a/src/rail.h +++ b/src/rail.h @@ -9,6 +9,7 @@ #include "tile.h" typedef enum RailTypes { + RAILTYPE_BEGIN = 0, RAILTYPE_RAIL = 0, RAILTYPE_ELECTRIC = 1, RAILTYPE_MONO = 2, @@ -19,10 +20,17 @@ typedef enum RailTypes { typedef byte RailTypeMask; +/** Allow incrementing of Track variables */ +DECLARE_POSTFIX_INCREMENT(RailType); +/** Define basic enum properties */ +template <> struct EnumPropsT<RailType> : MakeEnumPropsT<RailType, byte, RAILTYPE_BEGIN, RAILTYPE_END, INVALID_RAILTYPE> {}; +typedef TinyEnumT<RailType> RailTypeByte; + /** These are used to specify a single track. * Can be translated to a trackbit with TrackToTrackbit */ typedef enum Track { + TRACK_BEGIN = 0, TRACK_X = 0, TRACK_Y = 1, TRACK_UPPER = 2, @@ -33,6 +41,12 @@ typedef enum Track { INVALID_TRACK = 0xFF } Track; +/** Allow incrementing of Track variables */ +DECLARE_POSTFIX_INCREMENT(Track); +/** Define basic enum properties */ +template <> struct EnumPropsT<Track> : MakeEnumPropsT<Track, byte, TRACK_BEGIN, TRACK_END, INVALID_TRACK> {}; +typedef TinyEnumT<Track> TrackByte; + /** Convert an Axis to the corresponding Track * AXIS_X -> TRACK_X @@ -62,9 +76,18 @@ typedef enum TrackBits { TRACK_BIT_3WAY_SW = TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_LEFT, TRACK_BIT_3WAY_NW = TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_LEFT, TRACK_BIT_ALL = TRACK_BIT_CROSS | TRACK_BIT_HORZ | TRACK_BIT_VERT, - TRACK_BIT_MASK = 0x3FU + TRACK_BIT_MASK = 0x3FU, + TRACK_BIT_WORMHOLE = 0x40U, + TRACK_BIT_SPECIAL = 0x80U, + INVALID_TRACK_BIT = 0xFF } TrackBits; +/** Define basic enum properties */ +template <> struct EnumPropsT<TrackBits> : MakeEnumPropsT<TrackBits, byte, TRACK_BIT_NONE, TRACK_BIT_ALL, INVALID_TRACK_BIT> {}; +typedef TinyEnumT<TrackBits> TrackBitsByte; + +DECLARE_ENUM_AS_BIT_SET(TrackBits); +DECLARE_ENUM_AS_BIT_INDEX(Track, TrackBits); /** * Maps a Track to the corresponding TrackBits value @@ -84,6 +107,7 @@ static inline TrackBits AxisToTrackBits(Axis a) /** These are a combination of tracks and directions. Values are 0-5 in one * direction (corresponding to the Track enum) and 8-13 in the other direction. */ typedef enum Trackdirs { + TRACKDIR_BEGIN = 0, TRACKDIR_X_NE = 0, TRACKDIR_Y_SE = 1, TRACKDIR_UPPER_E = 2, @@ -102,6 +126,10 @@ typedef enum Trackdirs { INVALID_TRACKDIR = 0xFF, } Trackdir; +/** Define basic enum properties */ +template <> struct EnumPropsT<Trackdir> : MakeEnumPropsT<Trackdir, byte, TRACKDIR_BEGIN, TRACKDIR_END, INVALID_TRACKDIR> {}; +typedef TinyEnumT<Trackdir> TrackdirByte; + /** These are a combination of tracks and directions. Values are 0-5 in one * direction (corresponding to the Track enum) and 8-13 in the other direction. */ typedef enum TrackdirBits { @@ -123,6 +151,12 @@ typedef enum TrackdirBits { INVALID_TRACKDIR_BIT = 0xFFFF, } TrackdirBits; +/** Define basic enum properties */ +template <> struct EnumPropsT<TrackdirBits> : MakeEnumPropsT<TrackdirBits, uint16, TRACKDIR_BIT_NONE, TRACKDIR_BIT_MASK, INVALID_TRACKDIR_BIT> {}; +typedef TinyEnumT<TrackdirBits> TrackdirBitsShort; +DECLARE_ENUM_AS_BIT_SET(TrackdirBits); +DECLARE_ENUM_AS_BIT_INDEX(Trackdir, TrackdirBits); + /** This struct contains all the info that is needed to draw and construct tracks. */ typedef struct RailtypeInfo { @@ -214,6 +248,58 @@ enum { static inline TrackdirBits TrackdirToTrackdirBits(Trackdir trackdir) { return (TrackdirBits)(1 << trackdir); } /** +* Removes first Track from TrackBits and returns it +*/ +static inline Track RemoveFirstTrack(TrackBits &tracks) +{ + if (tracks != TRACK_BIT_NONE && tracks != INVALID_TRACK_BIT) { + Track first = (Track)FIND_FIRST_BIT(tracks); + tracks = ClrBitT(tracks, first); + return first; + } + return INVALID_TRACK; +} + +/** +* Removes first Trackdir from TrackdirBits and returns it +*/ +static inline Trackdir RemoveFirstTrackdir(TrackdirBits &trackdirs) +{ + if (trackdirs != TRACKDIR_BIT_NONE && trackdirs != INVALID_TRACKDIR_BIT) { + Trackdir first = (Trackdir)FindFirstBit2x64(trackdirs); + trackdirs = ClrBitT(trackdirs, first); + return first; + } + return INVALID_TRACKDIR; +} + +/** +* Returns first Track from TrackBits or INVALID_TRACK +*/ +static inline Track FindFirstTrack(TrackBits tracks) +{ + return (tracks != TRACK_BIT_NONE && tracks != INVALID_TRACK_BIT) ? (Track)FIND_FIRST_BIT(tracks) : INVALID_TRACK; +} + +/** +* Converts TrackBits to Track. TrackBits must contain just one Track or INVALID_TRACK_BIT! +*/ +static inline Track TrackBitsToTrack(TrackBits tracks) +{ + assert (tracks == INVALID_TRACK_BIT || (tracks != TRACK_BIT_NONE && KILL_FIRST_BIT(tracks) == 0)); + return tracks != INVALID_TRACK_BIT ? (Track)FIND_FIRST_BIT(tracks) : INVALID_TRACK; +} + +/** +* Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR +*/ +static inline Trackdir FindFirstTrackdir(TrackdirBits trackdirs) +{ + assert((trackdirs & ~TRACKDIR_BIT_MASK) == TRACKDIR_BIT_NONE); + return (trackdirs != TRACKDIR_BIT_NONE) ? (Trackdir)FindFirstBit2x64(trackdirs) : INVALID_TRACKDIR; +} + +/** * These functions check the validity of Tracks and Trackdirs. assert against * them when convenient. */ @@ -263,7 +349,9 @@ static inline byte SignalOnTrack(Track track) { /** * Maps a trackdir to the reverse trackdir. */ -static inline Trackdir ReverseTrackdir(Trackdir trackdir) { +static inline Trackdir ReverseTrackdir(Trackdir trackdir) +{ + assert(trackdir != INVALID_TRACKDIR); return (Trackdir)(trackdir ^ 8); } diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp index a793bb8a5..c7a912e8a 100644 --- a/src/rail_cmd.cpp +++ b/src/rail_cmd.cpp @@ -114,13 +114,13 @@ static const TrackBits _valid_tileh_slopes[][15] = { TRACK_BIT_X, TRACK_BIT_LEFT, - 0, + TRACK_BIT_NONE, TRACK_BIT_Y, TRACK_BIT_LOWER, TRACK_BIT_LOWER, TRACK_BIT_Y, - 0, + TRACK_BIT_NONE, TRACK_BIT_LEFT, TRACK_BIT_X, @@ -130,7 +130,7 @@ static const TrackBits _valid_tileh_slopes[][15] = { // allowed rail for an evenly raised platform { - 0, + TRACK_BIT_NONE, TRACK_BIT_LEFT, TRACK_BIT_LOWER, TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT, @@ -237,7 +237,7 @@ int32 CmdBuildSingleRail(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) int32 cost = 0; int32 ret; - if (!ValParamRailtype(p1) || !ValParamTrackOrientation(p2)) return CMD_ERROR; + if (!ValParamRailtype(p1) || !ValParamTrackOrientation((Track)p2)) return CMD_ERROR; railtype = (RailType)p1; track = (Track)p2; @@ -304,7 +304,7 @@ int32 CmdBuildSingleRail(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) /* FALLTHROUGH */ default: - ret = CheckRailSlope(tileh, trackbit, 0, tile); + ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile); if (CmdFailed(ret)) return ret; cost += ret; @@ -337,7 +337,7 @@ int32 CmdRemoveSingleRail(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) int32 cost = _price.remove_rail; bool crossing = false; - if (!ValParamTrackOrientation(p2)) return CMD_ERROR; + if (!ValParamTrackOrientation((Track)p2)) return CMD_ERROR; trackbit = TrackToTrackBits(track); SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION); @@ -427,7 +427,7 @@ static int32 ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end int ey = TileY(end); int dx, dy, trdx, trdy; - if (!ValParamTrackOrientation(*trackdir)) return CMD_ERROR; + if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR; // calculate delta x,y from start to end tile dx = ex - x; @@ -450,7 +450,7 @@ static int32 ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end (trdy >= 0 && dy < 0) ) { if (!HASBIT(*trackdir, 3)) { // first direction is invalid, try the other - SETBIT(*trackdir, 3); // reverse the direction + *trackdir = SetBitT(*trackdir, 3); // reverse the direction trdx = -trdx; trdy = -trdy; } else { // other direction is invalid too, invalid drag @@ -513,7 +513,7 @@ static int32 CmdRailTrackHelper(TileIndex tile, uint32 flags, uint32 p1, uint32 tile += ToTileIndexDiff(_trackdelta[trackdir]); // toggle railbit for the non-diagonal tracks - if (!IsDiagonalTrackdir(trackdir)) trackdir ^= 1; + if (!IsDiagonalTrackdir(trackdir)) trackdir = ToggleBitT(trackdir, 0); } return (total_cost == 0) ? CMD_ERROR : total_cost; @@ -586,14 +586,15 @@ int32 CmdBuildTrainDepot(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (d == NULL) return CMD_ERROR; if (flags & DC_EXEC) { - MakeRailDepot(tile, _current_player, p2, p1); + DiagDirection dir = (DiagDirection)p2; + MakeRailDepot(tile, _current_player, dir, (RailType)p1); MarkTileDirtyByTile(tile); d->xy = tile; d->town_index = ClosestTownFromTile(tile, (uint)-1)->index; - UpdateSignalsOnSegment(tile, p2); - YapfNotifyTrackLayoutChange(tile, TrackdirToTrack(DiagdirToDiagTrackdir(p2))); + UpdateSignalsOnSegment(tile, dir); + YapfNotifyTrackLayoutChange(tile, TrackdirToTrack(DiagdirToDiagTrackdir(dir))); } return cost + _price.build_train_depot; @@ -676,7 +677,7 @@ int32 CmdBuildSingleSignal(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) // cycle between normal -> pre -> exit -> combo -> ... SignalType type = GetSignalType(tile); - SetSignalType(tile, type == SIGTYPE_COMBO ? SIGTYPE_NORMAL : type + 1); + SetSignalType(tile, type == SIGTYPE_COMBO ? SIGTYPE_NORMAL : (SignalType)(type + 1)); } else { CycleSignalSide(tile, track); } @@ -714,7 +715,7 @@ static int32 CmdSignalTrackHelper(TileIndex tile, uint32 flags, uint32 p1, uint3 TileIndex end_tile; int mode = p2 & 0x1; - Track track = GB(p2, 4, 3); + Track track = (Track)GB(p2, 4, 3); Trackdir trackdir = TrackToTrackdir(track); byte semaphores = (HASBIT(p2, 3) ? 8 : 0); byte signal_density = (p2 >> 24); @@ -773,7 +774,7 @@ static int32 CmdSignalTrackHelper(TileIndex tile, uint32 flags, uint32 p1, uint3 signal_ctr++; // toggle railbit for the non-diagonal tracks (|, -- tracks) - if (!IsDiagonalTrackdir(trackdir)) trackdir ^= 1; + if (!IsDiagonalTrackdir(trackdir)) trackdir = ToggleBitT(trackdir, 0); } return error ? CMD_ERROR : total_cost; @@ -853,13 +854,14 @@ static int32 DoConvertRail(TileIndex tile, RailType totype, bool exec) // change type. if (exec) { - TrackBits tracks; SetRailType(tile, totype); MarkTileDirtyByTile(tile); // notify YAPF about the track layout change - for (tracks = GetTrackBits(tile); tracks != TRACK_BIT_NONE; tracks = KILL_FIRST_BIT(tracks)) - YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(tracks)); + TrackBits tracks = GetTrackBits(tile); + while (tracks != TRACK_BIT_NONE) { + YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(tracks)); + } if (IsTileDepotType(tile, TRANSPORT_RAIL)) { Vehicle *v; @@ -926,7 +928,7 @@ int32 CmdConvertRail(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) default: continue; } - ret = proc(tile, p2, false); + ret = proc(tile, (RailType)p2, false); if (CmdFailed(ret)) continue; cost += ret; @@ -936,7 +938,7 @@ int32 CmdConvertRail(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) _additional_cash_required = ret; return cost - ret; } - proc(tile, p2, true); + proc(tile, (RailType)p2, true); } } } @@ -985,10 +987,9 @@ static int32 ClearTile_Track(TileIndex tile, byte flags) case RAIL_TILE_SIGNALS: case RAIL_TILE_NORMAL: { TrackBits tracks = GetTrackBits(tile); - uint i; - - for_each_bit (i, tracks) { - ret = DoCommand(tile, 0, i, flags, CMD_REMOVE_SINGLE_RAIL); + while (tracks != TRACK_BIT_NONE) { + Track track = RemoveFirstTrack(tracks); + ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL); if (CmdFailed(ret)) return CMD_ERROR; cost += ret; } @@ -1011,7 +1012,7 @@ static int32 ClearTile_Track(TileIndex tile, byte flags) static void DrawSingleSignal(TileIndex tile, byte condition, uint image, uint pos) { - bool side = _opt.road_side & _patches.signal_side; + bool side = (_opt.road_side != 0) && _patches.signal_side; static const Point SignalPositions[2][12] = { { /* Signals on the left side */ /* LEFT LEFT RIGHT RIGHT UPPER UPPER */ @@ -1403,28 +1404,28 @@ typedef struct SetSignalsData { int presignal_exits_free; // these are used to keep track of the signals that change. - byte bit[NUM_SSD_ENTRY]; + TrackdirByte bit[NUM_SSD_ENTRY]; TileIndex tile[NUM_SSD_ENTRY]; // these are used to keep track of the stack that modifies presignals recursively TileIndex next_tile[NUM_SSD_STACK]; - byte next_dir[NUM_SSD_STACK]; + DiagDirectionByte next_dir[NUM_SSD_STACK]; } SetSignalsData; -static bool SetSignalsEnumProc(TileIndex tile, void* data, int track, uint length, byte* state) +static bool SetSignalsEnumProc(TileIndex tile, void* data, Trackdir trackdir, uint length, byte* state) { - SetSignalsData* ssd = data; + SetSignalsData* ssd = (SetSignalsData*)data; if (!IsTileType(tile, MP_RAILWAY)) return false; // the tile has signals? - if (HasSignalOnTrack(tile, TrackdirToTrack(track))) { - if (HasSignalOnTrackdir(tile, ReverseTrackdir(track))) { + if (HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) { + if (HasSignalOnTrackdir(tile, ReverseTrackdir(trackdir))) { // yes, add the signal to the list of signals if (ssd->cur != NUM_SSD_ENTRY) { ssd->tile[ssd->cur] = tile; // remember the tile index - ssd->bit[ssd->cur] = track; // and the controlling bit number + ssd->bit[ssd->cur] = trackdir; // and the controlling bit number ssd->cur++; } @@ -1432,10 +1433,10 @@ static bool SetSignalsEnumProc(TileIndex tile, void* data, int track, uint lengt ssd->has_presignal |= IsPresignalEntry(tile); } - if (HasSignalOnTrackdir(tile, track) && IsPresignalExit(tile)) { + if (HasSignalOnTrackdir(tile, trackdir) && IsPresignalExit(tile)) { // this is an exit signal that points out from the segment ssd->presignal_exits++; - if (GetSignalStateByTrackdir(tile, track) != SIGNAL_STATE_RED) + if (GetSignalStateByTrackdir(tile, trackdir) != SIGNAL_STATE_RED) ssd->presignal_exits_free++; } @@ -1455,7 +1456,7 @@ typedef struct SignalVehicleCheckStruct { static void *SignalVehicleCheckProc(Vehicle *v, void *data) { - const SignalVehicleCheckStruct* dest = data; + const SignalVehicleCheckStruct* dest = (SignalVehicleCheckStruct*)data; if (v->type != VEH_Train) return NULL; @@ -1514,7 +1515,7 @@ static bool SignalVehicleCheck(TileIndex tile, uint track) static void SetSignalsAfterProc(TrackPathFinder *tpf) { - SetSignalsData *ssd = tpf->userdata; + SetSignalsData *ssd = (SetSignalsData*)tpf->userdata; const TrackPathFinderLink* link; uint offs; uint i; @@ -1550,9 +1551,9 @@ static void SetSignalsAfterProc(TrackPathFinder *tpf) } } -static const byte _dir_from_track[14] = { - 0,1,0,1,2,1, 0,0, - 2,3,3,2,3,0, +static const DiagDirection _dir_from_track[14] = { + DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_NE, + DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, }; @@ -1909,7 +1910,7 @@ static void ChangeTileOwner_Track(TileIndex tile, PlayerID old_player, PlayerID static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 }; static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 }; -static const byte _deltacoord_leaveoffset[8] = { +static const signed char _deltacoord_leaveoffset[8] = { -1, 0, 1, 0, /* x */ 0, 1, 0, -1 /* y */ }; @@ -1945,7 +1946,7 @@ static uint32 VehicleEnter_Track(Vehicle *v, TileIndex tile, int x, int y) } else if (_fractcoords_enter[dir] == fract_coord) { if (DiagDirToDir(ReverseDiagDir(dir)) == v->direction) { /* enter the depot */ - v->u.rail.track = 0x80, + v->u.rail.track = TRACK_BIT_SPECIAL, v->vehstatus |= VS_HIDDEN; /* hide it */ v->direction = ReverseDir(v->direction); if (v->next == NULL) VehicleEnterDepot(v); @@ -1959,7 +1960,7 @@ static uint32 VehicleEnter_Track(Vehicle *v, TileIndex tile, int x, int y) /* leave the depot? */ if ((v = v->next) != NULL) { v->vehstatus &= ~VS_HIDDEN; - v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? 1 : 2); + v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y); } } } @@ -1968,7 +1969,7 @@ static uint32 VehicleEnter_Track(Vehicle *v, TileIndex tile, int x, int y) } -const TileTypeProcs _tile_type_rail_procs = { +extern const TileTypeProcs _tile_type_rail_procs = { DrawTile_Track, /* draw_tile_proc */ GetSlopeZ_Track, /* get_slope_z_proc */ ClearTile_Track, /* clear_tile_proc */ diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp index 4b651db5e..a84b4f212 100644 --- a/src/rail_gui.cpp +++ b/src/rail_gui.cpp @@ -37,7 +37,7 @@ static struct { bool dragdrop; bool newstations; - byte station_class; + StationClassIDByte station_class; byte station_type; byte station_count; } _railstation; @@ -107,7 +107,7 @@ static const uint16 _place_depot_extra[12] = { void CcRailDepot(bool success, TileIndex tile, uint32 p1, uint32 p2) { if (success) { - DiagDirection dir = p2; + DiagDirection dir = (DiagDirection)p2; SndPlayTileFx(SND_20_SPLAT_2, tile); ResetObjectToPlace(); @@ -834,7 +834,7 @@ static void StationBuildWndProc(Window *w, WindowEvent *e) case 20: case 21: - _station_show_coverage = e->we.click.widget - 20; + _station_show_coverage = (e->we.click.widget != 20); SetWindowWidgetLoweredState(w, 20, !_station_show_coverage); SetWindowWidgetLoweredState(w, 21, _station_show_coverage); SndPlayFx(SND_15_BEEP); @@ -873,7 +873,7 @@ static void StationBuildWndProc(Window *w, WindowEvent *e) case WE_DROPDOWN_SELECT: if (_railstation.station_class != e->we.dropdown.index) { - _railstation.station_class = e->we.dropdown.index; + _railstation.station_class = (StationClassID)e->we.dropdown.index; _railstation.station_type = 0; _railstation.station_count = GetNumCustomStations(_railstation.station_class); @@ -1023,7 +1023,7 @@ static void BuildTrainDepotWndProc(Window *w, WindowEvent *e) case 5: case 6: RaiseWindowWidget(w, _build_depot_direction + 3); - _build_depot_direction = e->we.click.widget - 3; + _build_depot_direction = (DiagDirection)(e->we.click.widget - 3); LowerWindowWidget(w, _build_depot_direction + 3); SndPlayFx(SND_15_BEEP); SetWindowDirty(w); diff --git a/src/rail_map.h b/src/rail_map.h index 902d4e6a4..60c7f3f6f 100644 --- a/src/rail_map.h +++ b/src/rail_map.h @@ -266,7 +266,7 @@ static inline SignalState GetSignalStateByTrackdir(TileIndex tile, Trackdir trac * The given trackdir is used when there are (could be) multiple rail types on * one tile. */ -RailType GetTileRailType(TileIndex tile, Trackdir trackdir); +RailType GetTileRailType(TileIndex tile, Track track); typedef enum RailGroundType { diff --git a/src/road.h b/src/road.h index 3418ef8cd..ef70733ec 100644 --- a/src/road.h +++ b/src/road.h @@ -3,7 +3,10 @@ #ifndef ROAD_H #define ROAD_H +#include "helpers.hpp" + typedef enum RoadBits { + ROAD_NONE = 0U, ROAD_NW = 1U, ROAD_SW = 2U, ROAD_SE = 4U, @@ -13,6 +16,8 @@ typedef enum RoadBits { ROAD_ALL = ROAD_X | ROAD_Y } RoadBits; +DECLARE_ENUM_AS_BIT_SET(RoadBits); + static inline RoadBits ComplementRoadBits(RoadBits r) { return (RoadBits)(ROAD_ALL ^ r); diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp index 9f3bc3f6a..dc4304d03 100644 --- a/src/road_cmd.cpp +++ b/src/road_cmd.cpp @@ -56,7 +56,7 @@ static bool CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, bool* edge_roa if (_cheats.magic_bulldozer.value) return true; // Get a bitmask of which neighbouring roads has a tile - n = 0; + n = ROAD_NONE; present = GetAnyRoadBits(tile); if (present & ROAD_NE && GetAnyRoadBits(TILE_ADDXY(tile,-1, 0)) & ROAD_SW) n |= ROAD_NE; if (present & ROAD_SE && GetAnyRoadBits(TILE_ADDXY(tile, 0, 1)) & ROAD_NW) n |= ROAD_SE; @@ -103,7 +103,7 @@ int32 CmdRemoveRoad(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) /* Road pieces are max 4 bitset values (NE, NW, SE, SW) */ if (p1 >> 4) return CMD_ERROR; - pieces = p1; + pieces = (RoadBits)p1; if (!IsTileType(tile, MP_STREET)) return CMD_ERROR; @@ -132,8 +132,8 @@ int32 CmdRemoveRoad(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (GetTileSlope(tile, NULL) != SLOPE_FLAT && (present == ROAD_Y || present == ROAD_X)) { - c |= (c & 0xC) >> 2; - c |= (c & 0x3) << 2; + c |= (RoadBits)((c & 0xC) >> 2); + c |= (RoadBits)((c & 0x3) << 2); } // limit the bits to delete to the existing bits. @@ -164,7 +164,7 @@ int32 CmdRemoveRoad(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) MakeRailNormal(tile, GetTileOwner(tile), GetCrossingRailBits(tile), GetRailTypeCrossing(tile)); MarkTileDirtyByTile(tile); - YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(GetTrackBits(tile))); + YapfNotifyTrackLayoutChange(tile, FindFirstTrack(GetTrackBits(tile))); } return _price.remove_road * 2; } @@ -179,15 +179,15 @@ int32 CmdRemoveRoad(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) static const RoadBits _valid_tileh_slopes_road[][15] = { // set of normal ones { - ROAD_ALL, 0, 0, - ROAD_X, 0, 0, // 3, 4, 5 - ROAD_Y, 0, 0, - ROAD_Y, 0, 0, // 9, 10, 11 - ROAD_X, 0, 0 + ROAD_ALL, ROAD_NONE, ROAD_NONE, + ROAD_X, ROAD_NONE, ROAD_NONE, // 3, 4, 5 + ROAD_Y, ROAD_NONE, ROAD_NONE, + ROAD_Y, ROAD_NONE, ROAD_NONE, // 9, 10, 11 + ROAD_X, ROAD_NONE, ROAD_NONE }, // allowed road for an evenly raised platform { - 0, + ROAD_NONE, ROAD_SW | ROAD_NW, ROAD_SW | ROAD_SE, ROAD_Y | ROAD_SW, @@ -216,8 +216,8 @@ static uint32 CheckRoadSlope(Slope tileh, RoadBits* pieces, RoadBits existing) if (IsSteepSlope(tileh)) { if (existing == 0) { // force full pieces. - *pieces |= (*pieces & 0xC) >> 2; - *pieces |= (*pieces & 0x3) << 2; + *pieces |= (RoadBits)((*pieces & 0xC) >> 2); + *pieces |= (RoadBits)((*pieces & 0x3) << 2); if (*pieces == ROAD_X || *pieces == ROAD_Y) return _price.terraform; } return CMD_ERROR; @@ -239,8 +239,8 @@ static uint32 CheckRoadSlope(Slope tileh, RoadBits* pieces, RoadBits existing) // partly leveled up tile, only if there's no road on that tile if (existing == 0 && (tileh == SLOPE_W || tileh == SLOPE_S || tileh == SLOPE_E || tileh == SLOPE_N)) { // force full pieces. - *pieces |= (*pieces & 0xC) >> 2; - *pieces |= (*pieces & 0x3) << 2; + *pieces |= (RoadBits)((*pieces & 0xC) >> 2); + *pieces |= (RoadBits)((*pieces & 0x3) << 2); if (*pieces == ROAD_X || *pieces == ROAD_Y) return _price.terraform; } return CMD_ERROR; @@ -255,7 +255,7 @@ int32 CmdBuildRoad(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) { int32 cost = 0; int32 ret; - RoadBits existing = 0; + RoadBits existing = ROAD_NONE; RoadBits pieces; Slope tileh; @@ -264,7 +264,7 @@ int32 CmdBuildRoad(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero * if a non-player is building the road */ if ((p1 >> 4) || (IsValidPlayer(_current_player) && p2 != 0) || !IsValidTownID(p2)) return CMD_ERROR; - pieces = p1; + pieces = (RoadBits)p1; tileh = GetTileSlope(tile, NULL); @@ -325,7 +325,7 @@ int32 CmdBuildRoad(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (!EnsureNoVehicle(tile)) return CMD_ERROR; if (flags & DC_EXEC) { - YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(GetTrackBits(tile))); + YapfNotifyTrackLayoutChange(tile, FindFirstTrack(GetTrackBits(tile))); MakeRoadCrossing(tile, _current_player, GetTileOwner(tile), roaddir, GetRailType(tile), p2); MarkTileDirtyByTile(tile); } @@ -382,7 +382,7 @@ int32 DoConvertStreetRail(TileIndex tile, RailType totype, bool exec) if (exec) { SetRailTypeCrossing(tile, totype); MarkTileDirtyByTile(tile); - YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(GetCrossingRailBits(tile))); + YapfNotifyTrackLayoutChange(tile, FindFirstTrack(GetCrossingRailBits(tile))); } return _price.build_rail >> 1; @@ -540,7 +540,7 @@ int32 CmdBuildRoadDepot(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) dep->xy = tile; dep->town_index = ClosestTownFromTile(tile, (uint)-1)->index; - MakeRoadDepot(tile, _current_player, p1); + MakeRoadDepot(tile, _current_player, (DiagDirection)p1); MarkTileDirtyByTile(tile); } return cost + _price.build_road_depot; @@ -1048,7 +1048,7 @@ static void ChangeTileOwner_Road(TileIndex tile, PlayerID old_player, PlayerID n } -const TileTypeProcs _tile_type_road_procs = { +extern const TileTypeProcs _tile_type_road_procs = { DrawTile_Road, /* draw_tile_proc */ GetSlopeZ_Road, /* get_slope_z_proc */ ClearTile_Road, /* clear_tile_proc */ diff --git a/src/road_gui.cpp b/src/road_gui.cpp index 8507de65f..36b6d516f 100644 --- a/src/road_gui.cpp +++ b/src/road_gui.cpp @@ -28,8 +28,8 @@ static bool _remove_button_clicked; static byte _place_road_flag; -static byte _road_depot_orientation; -static byte _road_station_picker_orientation; +static DiagDirection _road_depot_orientation; +static DiagDirection _road_station_picker_orientation; void CcPlaySound1D(bool success, TileIndex tile, uint32 p1, uint32 p2) { @@ -83,7 +83,7 @@ void CcRoadDepot(bool success, TileIndex tile, uint32 p1, uint32 p2) if (success) { SndPlayTileFx(SND_1F_SPLAT, tile); ResetObjectToPlace(); - BuildRoadOutsideStation(tile, p1); + BuildRoadOutsideStation(tile, (DiagDirection)p1); } } @@ -388,7 +388,7 @@ static void BuildRoadDepotWndProc(Window *w, WindowEvent *e) switch (e->we.click.widget) { case 3: case 4: case 5: case 6: RaiseWindowWidget(w, _road_depot_orientation + 3); - _road_depot_orientation = e->we.click.widget - 3; + _road_depot_orientation = (DiagDirection)(e->we.click.widget - 3); LowerWindowWidget(w, _road_depot_orientation + 3); SndPlayFx(SND_15_BEEP); SetWindowDirty(w); @@ -454,10 +454,10 @@ static void RoadStationPickerWndProc(Window *w, WindowEvent *e) image = (w->window_class == WC_BUS_STATION) ? 0x47 : 0x43; - StationPickerDrawSprite(103, 35, 0, image); - StationPickerDrawSprite(103, 85, 0, image+1); - StationPickerDrawSprite(35, 85, 0, image+2); - StationPickerDrawSprite(35, 35, 0, image+3); + StationPickerDrawSprite(103, 35, RAILTYPE_BEGIN, image); + StationPickerDrawSprite(103, 85, RAILTYPE_BEGIN, image+1); + StationPickerDrawSprite(35, 85, RAILTYPE_BEGIN, image+2); + StationPickerDrawSprite(35, 35, RAILTYPE_BEGIN, image+3); DrawStationCoverageAreaText(2, 146, ((w->window_class == WC_BUS_STATION) ? (1<<CT_PASSENGERS) : ~(1<<CT_PASSENGERS)), @@ -469,14 +469,14 @@ static void RoadStationPickerWndProc(Window *w, WindowEvent *e) switch (e->we.click.widget) { case 3: case 4: case 5: case 6: RaiseWindowWidget(w, _road_station_picker_orientation + 3); - _road_station_picker_orientation = e->we.click.widget - 3; + _road_station_picker_orientation = (DiagDirection)(e->we.click.widget - 3); LowerWindowWidget(w, _road_station_picker_orientation + 3); SndPlayFx(SND_15_BEEP); SetWindowDirty(w); break; case 7: case 8: RaiseWindowWidget(w, _station_show_coverage + 7); - _station_show_coverage = e->we.click.widget - 7; + _station_show_coverage = (e->we.click.widget != 7); LowerWindowWidget(w, _station_show_coverage + 7); SndPlayFx(SND_15_BEEP); SetWindowDirty(w); @@ -555,6 +555,6 @@ static void ShowTruckStationPicker(void) void InitializeRoadGui(void) { - _road_depot_orientation = 3; - _road_station_picker_orientation = 3; + _road_depot_orientation = DIAGDIR_NW; + _road_station_picker_orientation = DIAGDIR_NW; } diff --git a/src/road_map.cpp b/src/road_map.cpp index cccd2e76a..ccbf7b614 100644 --- a/src/road_map.cpp +++ b/src/road_map.cpp @@ -23,19 +23,19 @@ RoadBits GetAnyRoadBits(TileIndex tile) } case MP_STATION: - if (!IsRoadStopTile(tile)) return 0; + if (!IsRoadStopTile(tile)) return ROAD_NONE; return DiagDirToRoadBits(GetRoadStopDir(tile)); case MP_TUNNELBRIDGE: if (IsTunnel(tile)) { - if (GetTunnelTransportType(tile) != TRANSPORT_ROAD) return 0; + if (GetTunnelTransportType(tile) != TRANSPORT_ROAD) return ROAD_NONE; return DiagDirToRoadBits(ReverseDiagDir(GetTunnelDirection(tile))); } else { - if (GetBridgeTransportType(tile) != TRANSPORT_ROAD) return 0; + if (GetBridgeTransportType(tile) != TRANSPORT_ROAD) return ROAD_NONE; return DiagDirToRoadBits(ReverseDiagDir(GetBridgeRampDirection(tile))); } - default: return 0; + default: return ROAD_NONE; } } @@ -46,9 +46,9 @@ TrackBits GetAnyRoadTrackBits(TileIndex tile) // Don't allow local authorities to build roads through road depots or road stops. if ((IsTileType(tile, MP_STREET) && IsTileDepotType(tile, TRANSPORT_ROAD)) || IsTileType(tile, MP_STATION)) { - return 0; + return TRACK_BIT_NONE; } r = GetTileTrackStatus(tile, TRANSPORT_ROAD); - return (byte)(r | (r >> 8)); + return (TrackBits)(byte)(r | (r >> 8)); } diff --git a/src/roadveh_cmd.cpp b/src/roadveh_cmd.cpp index 48f6ad180..11873d97b 100644 --- a/src/roadveh_cmd.cpp +++ b/src/roadveh_cmd.cpp @@ -1,7 +1,6 @@ /* $Id$ */ #include "stdafx.h" -#include <limits.h> #include "openttd.h" #include "debug.h" #include "functions.h" @@ -144,7 +143,7 @@ int32 CmdBuildRoadVeh(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) const RoadVehicleInfo *rvi = RoadVehInfo(p1); v->unitnumber = unit_num; - v->direction = 0; + v->direction = INVALID_DIR; v->owner = _current_player; v->tile = tile; @@ -296,19 +295,19 @@ int32 CmdSellRoadVeh(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) typedef struct RoadFindDepotData { uint best_length; TileIndex tile; - byte owner; + OwnerByte owner; } RoadFindDepotData; static const DiagDirection _road_pf_directions[] = { - DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, 255, 255, - DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, 255, 255 + DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, INVALID_DIAGDIR, INVALID_DIAGDIR, + DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, INVALID_DIAGDIR, INVALID_DIAGDIR }; -static bool EnumRoadSignalFindDepot(TileIndex tile, void* data, int track, uint length, byte* state) +static bool EnumRoadSignalFindDepot(TileIndex tile, void* data, Trackdir trackdir, uint length, byte* state) { - RoadFindDepotData* rfdd = data; + RoadFindDepotData* rfdd = (RoadFindDepotData*)data; - tile += TileOffsByDiagDir(_road_pf_directions[track]); + tile += TileOffsByDiagDir(_road_pf_directions[trackdir]); if (IsTileType(tile, MP_STREET) && GetRoadTileType(tile) == ROAD_TILE_DEPOT && @@ -341,13 +340,12 @@ static const Depot* FindClosestRoadDepot(const Vehicle* v) /* We do not search in two directions here, why should we? We can't reverse right now can we? */ } else { RoadFindDepotData rfdd; - DiagDirection i; rfdd.owner = v->owner; rfdd.best_length = (uint)-1; /* search in all directions */ - for (i = 0; i != 4; i++) { + for (DiagDirection i = DIAGDIR_BEGIN; i != DIAGDIR_END; i++) { FollowTrack(tile, 0x2000 | TRANSPORT_ROAD, i, EnumRoadSignalFindDepot, NULL, &rfdd); } @@ -564,7 +562,7 @@ static void RoadVehIsCrashed(Vehicle *v) static void* EnumCheckRoadVehCrashTrain(Vehicle* v, void* data) { - const Vehicle* u = data; + const Vehicle* u = (Vehicle*)data; return v->type == VEH_Train && @@ -789,7 +787,7 @@ static void* EnumCheckRoadVehClose(Vehicle *v, void* data) static const int8 dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 }; static const int8 dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 }; - const RoadVehFindData* rvf = data; + const RoadVehFindData* rvf = (RoadVehFindData*)data; short x_diff = v->x_pos - rvf->x; short y_diff = v->y_pos - rvf->y; @@ -818,7 +816,7 @@ static Vehicle* RoadVehFindCloseTo(Vehicle* v, int x, int y, Direction dir) rvf.y = y; rvf.dir = dir; rvf.veh = v; - u = VehicleFromPos(TileVirtXY(x, y), &rvf, EnumCheckRoadVehClose); + u = (Vehicle*)VehicleFromPos(TileVirtXY(x, y), &rvf, EnumCheckRoadVehClose); // This code protects a roadvehicle from being blocked for ever // If more than 1480 / 74 days a road vehicle is blocked, it will @@ -900,8 +898,8 @@ static bool RoadVehAccelerate(Vehicle *v) static Direction RoadVehGetNewDirection(const Vehicle* v, int x, int y) { static const Direction _roadveh_new_dir[] = { - DIR_N , DIR_NW, DIR_W , 0, - DIR_NE, DIR_N , DIR_SW, 0, + DIR_N , DIR_NW, DIR_W , INVALID_DIR, + DIR_NE, DIR_N , DIR_SW, INVALID_DIR, DIR_E , DIR_SE, DIR_S }; @@ -914,13 +912,13 @@ static Direction RoadVehGetNewDirection(const Vehicle* v, int x, int y) static Direction RoadVehGetSlidingDirection(const Vehicle* v, int x, int y) { - Direction new = RoadVehGetNewDirection(v, x, y); - Direction old = v->direction; + Direction new_dir = RoadVehGetNewDirection(v, x, y); + Direction old_dir = v->direction; DirDiff delta; - if (new == old) return old; - delta = (DirDifference(new, old) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT); - return ChangeDir(old, delta); + if (new_dir == old_dir) return old_dir; + delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT); + return ChangeDir(old_dir, delta); } typedef struct OvertakeData { @@ -932,7 +930,7 @@ typedef struct OvertakeData { static void* EnumFindVehToOvertake(Vehicle* v, void* data) { - const OvertakeData* od = data; + const OvertakeData* od = (OvertakeData*)data; return v->tile == od->tile && v->type == VEH_Road && v != od->u && v != od->v ? @@ -1025,9 +1023,9 @@ typedef struct { uint mindist; } FindRoadToChooseData; -static bool EnumRoadTrackFindDist(TileIndex tile, void* data, int track, uint length, byte* state) +static bool EnumRoadTrackFindDist(TileIndex tile, void* data, Trackdir trackdir, uint length, byte* state) { - FindRoadToChooseData* frd = data; + FindRoadToChooseData* frd = (FindRoadToChooseData*)data; uint dist = DistanceManhattan(tile, frd->dest); if (dist <= frd->mindist) { @@ -1133,7 +1131,7 @@ static int RoadFindPathToDest(Vehicle* v, TileIndex tile, DiagDirection enterdir } else if (_patches.new_pathfinding_all) { NPFFindStationOrTileData fstd; NPFFoundTargetData ftd; - byte trackdir; + Trackdir trackdir; NPFFillWithOrderData(&fstd, v); trackdir = DiagdirToDiagTrackdir(enterdir); @@ -1215,7 +1213,7 @@ static uint RoadFindPathToStop(const Vehicle *v, TileIndex tile) } else { // use NPF NPFFindStationOrTileData fstd; - byte trackdir = GetVehicleTrackdir(v); + Trackdir trackdir = GetVehicleTrackdir(v); assert(trackdir != 0xFF); fstd.dest_coords = tile; @@ -1363,7 +1361,7 @@ static void RoadVehController(Vehicle *v) // switch to another tile if (rd.x & 0x80) { TileIndex tile = v->tile + TileOffsByDiagDir(rd.x & 3); - int dir = RoadFindPathToDest(v, tile, rd.x & 3); + int dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3)); uint32 r; Direction newdir; const RoadDriveEntry *rdp; @@ -1428,7 +1426,7 @@ again: } if (rd.x & 0x40) { - int dir = RoadFindPathToDest(v, v->tile, rd.x & 3); + int dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3)); uint32 r; int tmp; Direction newdir; diff --git a/src/saveload.cpp b/src/saveload.cpp index 75396aeee..6189d540e 100644 --- a/src/saveload.cpp +++ b/src/saveload.cpp @@ -30,7 +30,7 @@ #include "variables.h" #include <setjmp.h> -const uint16 SAVEGAME_VERSION = 43; +extern const uint16 SAVEGAME_VERSION = 43; uint16 _sl_version; /// the major savegame version identifier byte _sl_minor_version; /// the minor savegame version, DO NOT USE! @@ -511,7 +511,7 @@ static inline size_t SlCalcStringLen(const void *ptr, size_t length, VarType con case SLE_VAR_STR: case SLE_VAR_STRQ: str = *(const char**)ptr; - len = -1; + len = SIZE_MAX; break; case SLE_VAR_STRB: case SLE_VAR_STRBQ: @@ -538,12 +538,12 @@ static void SlString(void *ptr, size_t length, VarType conv) default: NOT_REACHED(); case SLE_VAR_STRB: case SLE_VAR_STRBQ: - len = SlCalcNetStringLen(ptr, length); + len = SlCalcNetStringLen((char*)ptr, length); break; case SLE_VAR_STR: case SLE_VAR_STRQ: ptr = *(char**)ptr; - len = SlCalcNetStringLen(ptr, -1); + len = SlCalcNetStringLen((char*)ptr, SIZE_MAX); break; } @@ -568,7 +568,7 @@ static void SlString(void *ptr, size_t length, VarType conv) case SLE_VAR_STR: case SLE_VAR_STRQ: /* Malloc'd string, free previous incarnation, and allocate */ free(*(char**)ptr); - *(char**)ptr = malloc(len + 1); // terminating '\0' + *(char**)ptr = (char*)malloc(len + 1); // terminating '\0' ptr = *(char**)ptr; SlCopyBytes(ptr, len); break; @@ -714,9 +714,9 @@ bool SlObjectMember(void *ptr, const SaveLoad *sld) case SL_REF: /* Reference variable, translate */ /// @todo XXX - another artificial limitof 65K elements of pointers? if (_sl.save) { // XXX - read/write pointer as uint16? What is with higher indeces? - SlWriteUint16(ReferenceToInt(*(void**)ptr, conv)); + SlWriteUint16(ReferenceToInt(*(void**)ptr, (SLRefType)conv)); } else { - *(void**)ptr = IntToReference(SlReadUint16(), conv); + *(void**)ptr = IntToReference(SlReadUint16(), (SLRefType)conv); } break; case SL_ARR: SlArray(ptr, sld->length, conv); break; @@ -1397,7 +1397,7 @@ static inline SaveOrLoadResult AbortSaveLoad(void) * saving takes Aaaaages */ void SaveFileStart(void) { - _ts.ff_state = _fast_forward; + _ts.ff_state = (_fast_forward != 0); _fast_forward = false; if (_cursor.sprite == SPR_CURSOR_MOUSE) SetMouseCursor(SPR_CURSOR_ZZZ); @@ -1525,7 +1525,7 @@ SaveOrLoadResult SaveOrLoad(const char *filename, int mode) _sl.bufe = _sl.bufp = NULL; _sl.offs_base = 0; - _sl.save = mode; + _sl.save = (mode != 0); _sl.includes = _desc_includes; _sl.chs = _chunk_handlers; diff --git a/src/saveload.h b/src/saveload.h index 5d490b35a..7f7a190c6 100644 --- a/src/saveload.h +++ b/src/saveload.h @@ -3,6 +3,12 @@ #ifndef SAVELOAD_H #define SAVELOAD_H +#ifdef SIZE_MAX +#undef SIZE_MAX +#endif + +#define SIZE_MAX ((size_t)-1) + typedef enum SaveOrLoadResult { SL_OK = 0, // completed successfully SL_ERROR = 1, // error that was caught before internal structures were modified diff --git a/src/screenshot.cpp b/src/screenshot.cpp index 5a73fa52a..f66745540 100644 --- a/src/screenshot.cpp +++ b/src/screenshot.cpp @@ -13,6 +13,7 @@ #include "screenshot.h" #include "variables.h" #include "date.h" +#include "helpers.hpp" char _screenshot_format_name[8]; uint _num_screenshot_formats; @@ -118,7 +119,7 @@ static bool MakeBmpImage(const char *name, ScreenshotCallback *callb, void *user maxlines = clamp(65536 / padw, 16, 128); // now generate the bitmap bits - buff = malloc(padw * maxlines); // by default generate 128 lines at a time. + MallocT(&buff, padw * maxlines); // by default generate 128 lines at a time. if (buff == NULL) { fclose(f); return false; @@ -225,7 +226,7 @@ static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *user maxlines = clamp(65536 / w, 16, 128); // now generate the bitmap bits - buff = malloc(w * maxlines); // by default generate 128 lines at a time. + MallocT(&buff, w * maxlines); // by default generate 128 lines at a time. if (buff == NULL) { png_destroy_write_struct(&png_ptr, &info_ptr); fclose(f); @@ -322,7 +323,7 @@ static bool MakePCXImage(const char *name, ScreenshotCallback *callb, void *user maxlines = clamp(65536 / w, 16, 128); // now generate the bitmap bits - buff = malloc(w * maxlines); // by default generate 128 lines at a time. + MallocT(&buff, w * maxlines); // by default generate 128 lines at a time. if (buff == NULL) { fclose(f); return false; diff --git a/src/settings.cpp b/src/settings.cpp index 2f509768f..447f87d13 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -40,6 +40,7 @@ #include "genworld.h" #include "date.h" #include "rail.h" +#include "helpers.hpp" #ifdef WITH_FREETYPE #include "gfx.h" #include "fontcache.h" @@ -74,7 +75,7 @@ static SettingsMemoryPool *pool_new(uint minsize) SettingsMemoryPool *p; if (minsize < 4096 - 12) minsize = 4096 - 12; - p = malloc(sizeof(SettingsMemoryPool) - 1 + minsize); + p = (SettingsMemoryPool*)malloc(sizeof(SettingsMemoryPool) - 1 + minsize); p->pos = 0; p->size = minsize; p->next = NULL; @@ -111,7 +112,7 @@ static void *pool_alloc(SettingsMemoryPool **pool, uint size) static void *pool_strdup(SettingsMemoryPool **pool, const char *mem, uint size) { - byte *p = pool_alloc(pool, size + 1); + byte *p = (byte*)pool_alloc(pool, size + 1); p[size] = 0; memcpy(p, mem, size); return p; @@ -168,9 +169,9 @@ static IniFile *ini_alloc(void) // allocate an ini group object static IniGroup *ini_group_alloc(IniFile *ini, const char *grpt, int len) { - IniGroup *grp = pool_alloc(&ini->pool, sizeof(IniGroup)); + IniGroup *grp = (IniGroup*)pool_alloc(&ini->pool, sizeof(IniGroup)); grp->ini = ini; - grp->name = pool_strdup(&ini->pool, grpt, len); + grp->name = (char*)pool_strdup(&ini->pool, grpt, len); if (!strcmp(grp->name, "newgrf") || !strcmp(grp->name, "servers") || !strcmp(grp->name, "bans")) { grp->type = IGT_LIST; } else { @@ -187,8 +188,8 @@ static IniGroup *ini_group_alloc(IniFile *ini, const char *grpt, int len) static IniItem *ini_item_alloc(IniGroup *group, const char *name, int len) { - IniItem *item = pool_alloc(&group->ini->pool, sizeof(IniItem)); - item->name = pool_strdup(&group->ini->pool, name, len); + IniItem *item = (IniItem*)pool_alloc(&group->ini->pool, sizeof(IniItem)); + item->name = (char*)pool_strdup(&group->ini->pool, name, len); item->next = NULL; item->comment = NULL; item->value = NULL; @@ -235,7 +236,7 @@ static IniFile *ini_load(const char *filename) if (ns > a) { a = max(a, 128); do a*=2; while (a < ns); - comment = realloc(comment, comment_alloc = a); + ReallocT(&comment, comment_alloc = a); } pos = comment_size; comment_size += (e - s + 1); @@ -254,7 +255,7 @@ static IniFile *ini_load(const char *filename) s++; // skip [ group = ini_group_alloc(ini, s, e - s); if (comment_size) { - group->comment = pool_strdup(&ini->pool, comment, comment_size); + group->comment = (char*)pool_strdup(&ini->pool, comment, comment_size); comment_size = 0; } } else if (group) { @@ -264,7 +265,7 @@ static IniFile *ini_load(const char *filename) // it's an item in an existing group item = ini_item_alloc(group, s, t-s); if (comment_size) { - item->comment = pool_strdup(&ini->pool, comment, comment_size); + item->comment = (char*)pool_strdup(&ini->pool, comment, comment_size); comment_size = 0; } @@ -279,7 +280,7 @@ static IniFile *ini_load(const char *filename) if (e > t && e[-1] == '\"') e--; *e = '\0'; - item->value = pool_strdup(&ini->pool, t, e - t); + item->value = (char*)pool_strdup(&ini->pool, t, e - t); } else { // it's an orphan item ShowInfoF("ini: '%s' outside of group", buffer); @@ -287,7 +288,7 @@ static IniFile *ini_load(const char *filename) } if (comment_size > 0) { - ini->comment = pool_strdup(&ini->pool, comment, comment_size); + ini->comment = (char*)pool_strdup(&ini->pool, comment, comment_size); comment_size = 0; } @@ -311,7 +312,7 @@ static IniGroup *ini_getgroup(IniFile *ini, const char *name, int len) // otherwise make a new one group = ini_group_alloc(ini, name, len); - group->comment = pool_strdup(&ini->pool, "\n", 1); + group->comment = (char*)pool_strdup(&ini->pool, "\n", 1); return group; } @@ -603,6 +604,7 @@ static const void *string_to_val(const SettingDescBase *desc, const char *str) case SDT_STRING: case SDT_INTLIST: return str; + default: break; } return NULL; @@ -704,7 +706,7 @@ static void ini_load_settings(IniFile *ini, const SettingDesc *sd, const char *g switch (GetVarMemType(sld->conv)) { case SLE_VAR_STRB: case SLE_VAR_STRBQ: - if (p != NULL) ttd_strlcpy((char*)ptr, p, sld->length); + if (p != NULL) ttd_strlcpy((char*)ptr, (const char*)p, sld->length); break; case SLE_VAR_STR: case SLE_VAR_STRQ: @@ -719,7 +721,7 @@ static void ini_load_settings(IniFile *ini, const SettingDesc *sd, const char *g break; case SDT_INTLIST: { - if (!load_intlist(p, ptr, sld->length, GetVarMemType(sld->conv))) + if (!load_intlist((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) ShowInfoF("ini: error in array '%s'", sdb->name); break; } @@ -782,7 +784,7 @@ static void ini_save_settings(IniFile *ini, const SettingDesc *sd, const char *g case SDT_MANYOFMANY: switch (GetVarMemType(sld->conv)) { case SLE_VAR_BL: - if (*(bool*)ptr == (bool)(unsigned long)p) continue; + if (*(bool*)ptr == (p != NULL)) continue; break; case SLE_VAR_I8: case SLE_VAR_U8: @@ -838,7 +840,7 @@ static void ini_save_settings(IniFile *ini, const SettingDesc *sd, const char *g } /* The value is different, that means we have to write it to the ini */ - item->value = pool_strdup(&ini->pool, buf, strlen(buf)); + item->value = (char*)pool_strdup(&ini->pool, buf, strlen(buf)); } } @@ -945,12 +947,12 @@ static void ini_save_setting_list(IniFile *ini, const char *grpname, char **list * place) and you DON'T have to increase the savegame version. */ #define NSD_GENERAL(name, def, cmd, guiflags, min, max, interval, many, str, proc)\ - {name, (const void*)(def), cmd, guiflags, min, max, interval, many, str, proc} + {name, (const void*)(def), {cmd}, {guiflags}, min, max, interval, many, str, proc} /* Macros for various objects to go in the configuration file. * This section is for global variables */ #define SDTG_GENERAL(name, sdt_cmd, sle_cmd, type, flags, guiflags, var, length, def, min, max, interval, full, str, proc, from, to)\ -{NSD_GENERAL(name, def, sdt_cmd, guiflags, min, max, interval, full, str, proc), SLEG_GENERAL(sle_cmd, var, type | flags, length, from, to)} + {NSD_GENERAL(name, def, sdt_cmd, guiflags, min, max, interval, full, str, proc), SLEG_GENERAL(sle_cmd, var, type | flags, length, from, to)} #define SDTG_CONDVAR(name, type, flags, guiflags, var, def, min, max, interval, str, proc, from, to)\ SDTG_GENERAL(name, SDT_NUMX, SL_VAR, type, flags, guiflags, var, 0, def, min, max, interval, NULL, str, proc, from, to) @@ -983,9 +985,9 @@ static void ini_save_setting_list(IniFile *ini, const char *grpname, char **list SDTG_CONDMMANY(name, type, flags, guiflags, var, def, full, str, proc, 0, SL_MAX_VERSION) #define SDTG_CONDNULL(length, from, to)\ - {{"", NULL, 0, 0, 0, 0, 0, NULL, STR_NULL, NULL}, SLEG_CONDNULL(length, from, to)} + {{"", NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL}, SLEG_CONDNULL(length, from, to)} -#define SDTG_END() {{NULL, NULL, 0, 0, 0, 0, 0, NULL, STR_NULL, NULL}, SLEG_END()} +#define SDTG_END() {{NULL, NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL}, SLEG_END()} /* Macros for various objects to go in the configuration file. * This section is for structures where their various members are saved */ @@ -1032,9 +1034,9 @@ static void ini_save_setting_list(IniFile *ini, const char *grpname, char **list SDT_CONDMMANY(base, var, type, 0, SL_MAX_VERSION, flags, guiflags, def, full, str, proc) #define SDT_CONDNULL(length, from, to)\ - {{"", NULL, 0, 0, 0, 0, 0, NULL, STR_NULL, NULL}, SLE_CONDNULL(length, from, to)} + {{"", NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL}, SLE_CONDNULL(length, from, to)} -#define SDT_END() {{NULL, NULL, 0, 0, 0, 0, 0, NULL, STR_NULL, NULL}, SLE_END()} +#define SDT_END() {{NULL, NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL}, SLE_END()} /* Shortcuts for macros below. Logically if we don't save the value * we also don't sync it in a network game */ @@ -1507,7 +1509,8 @@ static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_stati if (group == NULL) return NULL; for (item = group->item; item != NULL; item = item->next) { - GRFConfig *c = calloc(1, sizeof(*c)); + GRFConfig *c; + CallocT(&c, 1); c->filename = strdup(item->name); /* Parse parameters */ @@ -1566,7 +1569,7 @@ static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *li GRFBuildParamList(params, c, lastof(params)); *item = ini_item_alloc(group, c->filename, strlen(c->filename)); - (*item)->value = pool_strdup(&ini->pool, params, strlen(params)); + (*item)->value = (char*)pool_strdup(&ini->pool, params, strlen(params)); item = &(*item)->next; } } @@ -1843,7 +1846,7 @@ void UpdatePatches(void) _patches = _patches_newgame; /* backwards compatibility */ } -const ChunkHandler _setting_chunk_handlers[] = { +extern const ChunkHandler _setting_chunk_handlers[] = { { 'OPTS', Save_OPTS, Load_OPTS, CH_RIFF}, { 'PATS', Save_PATS, Load_PATS, CH_RIFF | CH_LAST}, }; diff --git a/src/settings.h b/src/settings.h index 0ab3ecef3..79e0e3b62 100644 --- a/src/settings.h +++ b/src/settings.h @@ -9,31 +9,42 @@ * with the SLE_ (SLE_VAR/SLE_FILE) enums in saveload.h * @see VarTypes * @see SettingDescBase */ -enum SettingDescType { +enum SettingDescTypeLong { /* 4 bytes allocated a maximum of 16 types for GenericType */ + SDT_BEGIN = 0, SDT_NUMX = 0, // any number-type SDT_BOOLX = 1, // a boolean number SDT_ONEOFMANY = 2, // bitmasked number where only ONE bit may be set SDT_MANYOFMANY = 3, // bitmasked number where MULTIPLE bits may be set SDT_INTLIST = 4, // list of integers seperated by a comma ',' SDT_STRING = 5, // string with a pre-allocated buffer + SDT_END, /* 10 more possible primitives */ }; -enum SettingGuiFlag { +template <> struct EnumPropsT<SettingDescTypeLong> : MakeEnumPropsT<SettingDescTypeLong, byte, SDT_BEGIN, SDT_END, SDT_END> {}; +typedef TinyEnumT<SettingDescTypeLong> SettingDescType; + + +enum SettingGuiFlagLong { /* 8 bytes allocated for a maximum of 8 flags * Flags directing saving/loading of a variable */ + SGF_NONE = 0, SGF_0ISDISABLED = 1 << 0, ///< a value of zero means the feature is disabled SGF_NOCOMMA = 1 << 1, ///< number without any thousand seperators (no formatting) SGF_MULTISTRING = 1 << 2, ///< the value represents a limited number of string-options (internally integer) SGF_NETWORK_ONLY = 1 << 3, ///< this setting only applies to network games SGF_CURRENCY = 1 << 4, ///< the number represents money, so when reading value multiply by exchange rate + SGF_END = 1 << 5, /* 3 more possible flags */ }; +DECLARE_ENUM_AS_BIT_SET(SettingGuiFlagLong); +template <> struct EnumPropsT<SettingGuiFlagLong> : MakeEnumPropsT<SettingGuiFlagLong, byte, SGF_NONE, SGF_END, SGF_END> {}; +typedef TinyEnumT<SettingGuiFlagLong> SettingGuiFlag; + + typedef int32 OnChange(int32 var); -typedef byte SettingDescType; -typedef byte SettingGuiFlag; typedef struct SettingDescBase { const char *name; ///< name of the setting. Used in configuration file and for console diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index f6806f424..d3d5dcbf6 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -21,6 +21,7 @@ #include "settings.h" #include "vehicle.h" #include "date.h" +#include "helpers.hpp" static uint32 _difficulty_click_a; static uint32 _difficulty_click_b; @@ -409,8 +410,8 @@ static void GameDifficultyWndProc(Window *w, WindowEvent *e) y = GAMEDIFF_WND_TOP_OFFSET; for (i = 0; i != GAME_DIFFICULTY_NUM; i++) { - DrawFrameRect( 5, y, 5 + 8, y + 8, 3, GetBitAndShift(&click_a) ? FR_LOWERED : 0); - DrawFrameRect(15, y, 15 + 8, y + 8, 3, GetBitAndShift(&click_b) ? FR_LOWERED : 0); + DrawFrameRect( 5, y, 5 + 8, y + 8, 3, GetBitAndShift(&click_a) ? FR_LOWERED : FR_NONE); + DrawFrameRect(15, y, 15 + 8, y + 8, 3, GetBitAndShift(&click_b) ? FR_LOWERED : FR_NONE); if (GetBitAndShift(&disabled) || (_networking && !_network_server)) { int color = PALETTE_MODIFIER_GREYOUT | _colour_gradient[COLOUR_YELLOW][2]; GfxFillRect( 6, y + 1, 6 + 8, y + 8, color); @@ -499,7 +500,7 @@ static void GameDifficultyWndProc(Window *w, WindowEvent *e) if (val != ((int*)&_opt_ptr->diff)[btn]) DoCommandP(0, btn, val, NULL, CMD_CHANGE_DIFFICULTY_LEVEL); } - DoCommandP(0, -1, _opt_mod_temp.diff_level, NULL, CMD_CHANGE_DIFFICULTY_LEVEL); + DoCommandP(0, UINT_MAX, _opt_mod_temp.diff_level, NULL, CMD_CHANGE_DIFFICULTY_LEVEL); DeleteWindow(w); // If we are in the editor, we should reload the economy. // This way when you load a game, the max loan and interest rate @@ -693,7 +694,7 @@ static void PatchesSelectionWndProc(Window *w, WindowEvent *e) for (page = &_patches_page[0]; page != endof(_patches_page); page++) { uint i; - page->entries = malloc(page->num * sizeof(*page->entries)); + MallocT(&page->entries, page->num); for (i = 0; i != page->num; i++) { uint index; const SettingDesc *sd = GetPatchFromName(page->names[i], &index); @@ -734,7 +735,7 @@ static void PatchesSelectionWndProc(Window *w, WindowEvent *e) /* Draw checkbox for boolean-value either on/off */ bool on = (*(bool*)var); - DrawFrameRect(x, y, x + 19, y + 8, _bool_ctabs[!!on][!!editable], on ? FR_LOWERED : 0); + DrawFrameRect(x, y, x + 19, y + 8, _bool_ctabs[!!on][!!editable], on ? FR_LOWERED : FR_NONE); SetDParam(0, on ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF); } else { int32 value; @@ -930,8 +931,8 @@ void DrawArrowButtons(int x, int y, int ctab, byte state, bool clickable_left, b { int color = PALETTE_MODIFIER_GREYOUT | _colour_gradient[COLOUR_YELLOW][2]; - DrawFrameRect(x, y + 1, x + 9, y + 9, ctab, (state == 1) ? FR_LOWERED : 0); - DrawFrameRect(x + 10, y + 1, x + 19, y + 9, ctab, (state == 2) ? FR_LOWERED : 0); + DrawFrameRect(x, y + 1, x + 9, y + 9, ctab, (state == 1) ? FR_LOWERED : FR_NONE); + DrawFrameRect(x + 10, y + 1, x + 19, y + 9, ctab, (state == 2) ? FR_LOWERED : FR_NONE); DrawStringCentered(x + 5, y + 1, STR_6819, 0); // [<] DrawStringCentered(x + 15, y + 1, STR_681A, 0); // [>] @@ -961,19 +962,19 @@ static void CustCurrencyWndProc(Window *w, WindowEvent *e) y += 12; // separator - DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 2, 2) ? FR_LOWERED : 0); + DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 2, 2) ? FR_LOWERED : FR_NONE); x = DrawString(35, y + 1, STR_CURRENCY_SEPARATOR, 0); DoDrawString(_str_separator, x + 4, y + 1, 6); y += 12; // prefix - DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 4, 2) ? FR_LOWERED : 0); + DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 4, 2) ? FR_LOWERED : FR_NONE); x = DrawString(35, y + 1, STR_CURRENCY_PREFIX, 0); DoDrawString(_custom_currency.prefix, x + 4, y + 1, 6); y += 12; // suffix - DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 6, 2) ? FR_LOWERED : 0); + DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 6, 2) ? FR_LOWERED : FR_NONE); x = DrawString(35, y + 1, STR_CURRENCY_SUFFIX, 0); DoDrawString(_custom_currency.suffix, x + 4, y + 1, 6); y += 12; diff --git a/src/ship_cmd.cpp b/src/ship_cmd.cpp index f72323915..78138612e 100644 --- a/src/ship_cmd.cpp +++ b/src/ship_cmd.cpp @@ -29,12 +29,18 @@ #include "date.h" static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D}; -static const byte _ship_sometracks[4] = {0x19, 0x16, 0x25, 0x2A}; -static byte GetTileShipTrackStatus(TileIndex tile) +static const TrackBits _ship_sometracks[4] = { + TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_LEFT, // 0x19, // DIAGDIR_NE + TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_LEFT, // 0x16, // DIAGDIR_SE + TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT, // 0x25, // DIAGDIR_SW + TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_RIGHT, // 0x2A, // DIAGDIR_NW +}; + +static TrackBits GetTileShipTrackStatus(TileIndex tile) { uint32 r = GetTileTrackStatus(tile, TRANSPORT_WATER); - return r | r >> 8; + return TrackdirBitsToTrackBits((TrackdirBits)(TRACKDIR_BIT_MASK & (r | r >> 8))); } void DrawShipEngine(int x, int y, EngineID engine, uint32 image_ormod) @@ -77,7 +83,7 @@ static const Depot* FindClosestShipDepot(const Vehicle* v) if (_patches.new_pathfinding_all) { NPFFoundTargetData ftd; - byte trackdir = GetVehicleTrackdir(v); + Trackdir trackdir = GetVehicleTrackdir(v); ftd = NPFRouteToDepotTrialError(v->tile, trackdir, TRANSPORT_WATER, v->owner, INVALID_RAILTYPE); if (ftd.best_bird_dist == 0) { best_depot = GetDepotByTile(ftd.node.tile); /* Found target */ @@ -350,8 +356,8 @@ static void CheckShipLeaveDepot(Vehicle *v) } else { return; } - v->direction = GB(m, 0, 8); - v->u.ship.state = GB(m, 8, 8); + v->direction = (Direction)GB(m, 0, 8); + v->u.ship.state = (TrackBits)GB(m, 8, 8); v->vehstatus &= ~VS_HIDDEN; v->cur_speed = 0; @@ -447,10 +453,10 @@ static const byte _ship_search_directions[6][4] = { static const byte _pick_shiptrack_table[6] = {1, 3, 2, 2, 0, 0}; -static uint FindShipTrack(Vehicle *v, TileIndex tile, int dir, uint bits, TileIndex skiptile, int *track) +static uint FindShipTrack(Vehicle *v, TileIndex tile, DiagDirection dir, TrackBits bits, TileIndex skiptile, Track *track) { PathFindShip pfs; - int i, best_track; + Track i, best_track; uint best_bird_dist = 0; uint best_length = 0; uint r; @@ -459,18 +465,17 @@ static uint FindShipTrack(Vehicle *v, TileIndex tile, int dir, uint bits, TileIn pfs.dest_coords = v->dest_tile; pfs.skiptile = skiptile; - best_track = -1; + best_track = INVALID_TRACK; do { - i = FIND_FIRST_BIT(bits); - bits = KILL_FIRST_BIT(bits); + i = RemoveFirstTrack(bits); pfs.best_bird_dist = (uint)-1; pfs.best_length = (uint)-1; - FollowTrack(tile, 0x3800 | TRANSPORT_WATER, _ship_search_directions[i][dir], (TPFEnumProc*)ShipTrackFollower, NULL, &pfs); + FollowTrack(tile, 0x3800 | TRANSPORT_WATER, (DiagDirection)_ship_search_directions[i][dir], (TPFEnumProc*)ShipTrackFollower, NULL, &pfs); - if (best_track >= 0) { + if (best_track != INVALID_TRACK) { if (pfs.best_bird_dist != 0) { /* neither reached the destination, pick the one with the smallest bird dist */ if (pfs.best_bird_dist > best_bird_dist) goto bad; @@ -512,19 +517,19 @@ static inline NPFFoundTargetData PerfNPFRouteToStationOrTile(TileIndex tile, Tra /* returns the track to choose on the next tile, or -1 when it's better to * reverse. The tile given is the tile we are about to enter, enterdir is the * direction in which we are entering the tile */ -static int ChooseShipTrack(Vehicle *v, TileIndex tile, int enterdir, uint tracks) +static Track ChooseShipTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks) { assert(enterdir>=0 && enterdir<=3); if (_patches.yapf.ship_use_yapf) { Trackdir trackdir = YapfChooseShipTrack(v, tile, enterdir, tracks); - return (trackdir != INVALID_TRACKDIR) ? (int)TrackdirToTrack(trackdir) : -1; + return (trackdir != INVALID_TRACKDIR) ? TrackdirToTrack(trackdir) : INVALID_TRACK; } else if (_patches.new_pathfinding_all) { NPFFindStationOrTileData fstd; NPFFoundTargetData ftd; TileIndex src_tile = TILE_ADD(tile, TileOffsByDiagDir(ReverseDiagDir(enterdir))); - byte trackdir = GetVehicleTrackdir(v); - assert (trackdir != 0xFF); /* Check that we are not in a depot */ + Trackdir trackdir = GetVehicleTrackdir(v); + assert(trackdir != INVALID_TRACKDIR); /* Check that we are not in a depot */ NPFFillWithOrderData(&fstd, v); @@ -535,21 +540,20 @@ static int ChooseShipTrack(Vehicle *v, TileIndex tile, int enterdir, uint tracks the direction we need to take to get there, if ftd.best_bird_dist is not 0, we did not find our target, but ftd.best_trackdir contains the direction leading to the tile closest to our target. */ - return ftd.best_trackdir & 7; /* TODO: Wrapper function? */ + return TrackdirToTrack(ftd.best_trackdir); /* TODO: Wrapper function? */ } else { - return -1; /* Already at target, reverse? */ + return INVALID_TRACK; /* Already at target, reverse? */ } } else { - uint b; uint tot_dist, dist; - int track; + Track track; TileIndex tile2; tile2 = TILE_ADD(tile, -TileOffsByDiagDir(enterdir)); tot_dist = (uint)-1; /* Let's find out how far it would be if we would reverse first */ - b = GetTileShipTrackStatus(tile2) & _ship_sometracks[ReverseDiagDir(enterdir)] & v->u.ship.state; + TrackBits b = GetTileShipTrackStatus(tile2) & _ship_sometracks[ReverseDiagDir(enterdir)] & v->u.ship.state; if (b != 0) { dist = FindShipTrack(v, tile2, ReverseDiagDir(enterdir), b, tile, &track); if (dist != (uint)-1) @@ -559,18 +563,18 @@ static int ChooseShipTrack(Vehicle *v, TileIndex tile, int enterdir, uint tracks dist = FindShipTrack(v, tile, enterdir, tracks, 0, &track); if (dist > tot_dist) /* We could better reverse */ - return -1; + return INVALID_TRACK; return track; } } static const Direction _new_vehicle_direction_table[] = { - DIR_N , DIR_NW, DIR_W , 0, - DIR_NE, DIR_N , DIR_SW, 0, + DIR_N , DIR_NW, DIR_W , INVALID_DIR, + DIR_NE, DIR_N , DIR_SW, INVALID_DIR, DIR_E , DIR_SE, DIR_S }; -static int ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile) +static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile) { uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 + TileX(new_tile) - TileX(old_tile) + 1; @@ -578,17 +582,17 @@ static int ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile) return _new_vehicle_direction_table[offs]; } -static int ShipGetNewDirection(Vehicle *v, int x, int y) +static Direction ShipGetNewDirection(Vehicle *v, int x, int y) { uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1); assert(offs < 11 && offs != 3 && offs != 7); return _new_vehicle_direction_table[offs]; } -static int GetAvailShipTracks(TileIndex tile, int dir) +static TrackBits GetAvailShipTracks(TileIndex tile, int dir) { uint32 r = GetTileTrackStatus(tile, TRANSPORT_WATER); - return (byte) ((r | r >> 8)) & _ship_sometracks[dir]; + return (TrackBits)((r | r >> 8) & _ship_sometracks[dir]); } static const byte _ship_subcoord[4][6][3] = { @@ -632,8 +636,8 @@ static void ShipController(Vehicle *v) uint32 r; const byte *b; Direction dir; - int track; - int tracks; + Track track; + TrackBits tracks; v->tick_counter++; @@ -737,7 +741,7 @@ static void ShipController(Vehicle *v) // Choose a direction, and continue if we find one track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks); - if (track < 0) + if (track == INVALID_TRACK) goto reverse_direction; b = _ship_subcoord[diagdir][track]; @@ -751,10 +755,10 @@ static void ShipController(Vehicle *v) if (!(r&0x4)) { v->tile = gp.new_tile; - v->u.ship.state = 1 << track; + v->u.ship.state = TrackToTrackBits(track); } - v->direction = b[2]; + v->direction = (Direction)b[2]; } /* update image of ship, as well as delta XY */ @@ -872,7 +876,7 @@ int32 CmdBuildShip(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) _new_vehicle_id = v->index; v->string_id = STR_SV_SHIP_NAME; - v->u.ship.state = 0x80; + v->u.ship.state = TRACK_BIT_SPECIAL; v->service_interval = _patches.servint_ships; v->date_of_last_service = _date; diff --git a/src/signs.cpp b/src/signs.cpp index 4b2d48cd1..16df0d1da 100644 --- a/src/signs.cpp +++ b/src/signs.cpp @@ -272,6 +272,6 @@ static void Load_SIGN(void) _sign_sort_dirty = true; } -const ChunkHandler _sign_chunk_handlers[] = { +extern const ChunkHandler _sign_chunk_handlers[] = { { 'SIGN', Save_SIGN, Load_SIGN, CH_ARRAY | CH_LAST}, }; diff --git a/src/signs.h b/src/signs.h index 9c9fd2982..09d72a350 100644 --- a/src/signs.h +++ b/src/signs.h @@ -11,7 +11,7 @@ typedef struct Sign { int32 x; int32 y; byte z; - PlayerID owner; // placed by this player. Anyone can delete them though. OWNER_NONE for gray signs from old games. + PlayerByte owner; // placed by this player. Anyone can delete them though. OWNER_NONE for gray signs from old games. SignID index; } Sign; diff --git a/src/sound.cpp b/src/sound.cpp index 7e78b07dd..c1d9c73f4 100644 --- a/src/sound.cpp +++ b/src/sound.cpp @@ -11,6 +11,7 @@ #include "viewport.h" #include "fileio.h" #include "newgrf_sound.h" +#include "helpers.hpp" static uint _file_count; static FileEntry *_files; @@ -28,7 +29,7 @@ static void OpenBankFile(const char *filename) FioOpenFile(SOUND_SLOT, filename); count = FioReadDword() / 8; - fe = calloc(count, sizeof(*fe)); + CallocT(&fe, count); if (fe == NULL) { _file_count = 0; @@ -109,7 +110,7 @@ static bool SetBankSource(MixerChannel *mc, uint bank) if (fe->file_size == 0) return false; - mem = malloc(fe->file_size); + MallocT(&mem, fe->file_size); if (mem == NULL) return false; FioSeekToFile(fe->file_offset); diff --git a/src/sound.h b/src/sound.h index fd5638558..b815471c4 100644 --- a/src/sound.h +++ b/src/sound.h @@ -3,6 +3,8 @@ #ifndef SOUND_H #define SOUND_H +#include "helpers.hpp" + typedef struct MusicFileSettings { byte playlist; byte music_vol; @@ -30,7 +32,8 @@ bool SoundInitialize(const char *filename); uint GetNumOriginalSounds(void); typedef enum SoundFx { - SND_02_SPLAT, // 0 == 0x00 ! + SND_BEGIN = 0, + SND_02_SPLAT = 0, // 0 == 0x00 ! SND_03_FACTORY_WHISTLE, SND_04_TRAIN, SND_05_TRAIN_THROUGH_TUNNEL, @@ -102,9 +105,14 @@ typedef enum SoundFx { SND_45_PLANE_CRASHING, SND_46_PLANE_ENGINE_SPUTTERING, SND_47_MAGLEV_2, - SND_48_DISTANT_BIRD // 72 == 0x48 + SND_48_DISTANT_BIRD, // 72 == 0x48 + SND_END } SoundFx; +/** Define basic enum properties */ +template <> struct EnumPropsT<SoundFx> : MakeEnumPropsT<SoundFx, byte, SND_BEGIN, SND_END, SND_END> {}; +typedef TinyEnumT<SoundFx> SoundFxByte; + void SndPlayTileFx(SoundFx sound, TileIndex tile); void SndPlayVehicleFx(SoundFx sound, const Vehicle *v); void SndPlayFx(SoundFx sound); diff --git a/src/sound/win32_s.cpp b/src/sound/win32_s.cpp index a39cee985..a1ecab017 100644 --- a/src/sound/win32_s.cpp +++ b/src/sound/win32_s.cpp @@ -5,6 +5,7 @@ #include "../driver.h" #include "../functions.h" #include "../mixer.h" +#include "../helpers.hpp" #include "win32_s.h" #include <windows.h> #include <mmsystem.h> @@ -17,7 +18,7 @@ static void PrepareHeader(WAVEHDR *hdr) { hdr->dwBufferLength = _bufsize * 4; hdr->dwFlags = 0; - hdr->lpData = malloc(_bufsize * 4); + MallocT(&hdr->lpData, _bufsize * 4); if (hdr->lpData == NULL || waveOutPrepareHeader(_waveout, hdr, sizeof(WAVEHDR)) != MMSYSERR_NOERROR) error("waveOutPrepareHeader failed"); diff --git a/src/spritecache.cpp b/src/spritecache.cpp index fd881bb2a..6eaa1d7fd 100644 --- a/src/spritecache.cpp +++ b/src/spritecache.cpp @@ -8,6 +8,7 @@ #include "spritecache.h" #include "table/sprites.h" #include "fileio.h" +#include "helpers.hpp" #define SPRITE_CACHE_SIZE 1024*1024 @@ -37,7 +38,7 @@ static SpriteCache *AllocateSpriteCache(uint index) DEBUG(sprite, 4, "Increasing sprite cache to %d items (%d bytes)", items, items * sizeof(*_spritecache)); - _spritecache = realloc(_spritecache, items * sizeof(*_spritecache)); + ReallocT(&_spritecache, items); if (_spritecache == NULL) { error("Unable to allocate sprite cache of %d items (%d bytes)", items, items * sizeof(*_spritecache)); @@ -132,7 +133,7 @@ static void* ReadSprite(SpriteCache *sc, SpriteID id) num = FioReadWord(); type = FioReadByte(); if (type == 0xFF) { - byte* dest = AllocSprite(num); + byte* dest = (byte*)AllocSprite(num); sc->ptr = dest; FioReadBlock(dest, num); @@ -145,7 +146,7 @@ static void* ReadSprite(SpriteCache *sc, SpriteID id) byte* dest; num = (type & 0x02) ? width * height : num - 8; - sprite = AllocSprite(sizeof(*sprite) + num); + sprite = (Sprite*)AllocSprite(sizeof(*sprite) + num); sc->ptr = sprite; sprite->info = type; sprite->height = (id != 142) ? height : 10; // Compensate for a TTD bug @@ -195,10 +196,10 @@ bool LoadNextSprite(int load_index, byte file_index) } -void DupSprite(SpriteID old, SpriteID new) +void DupSprite(SpriteID old_spr, SpriteID new_spr) { - SpriteCache *scold = GetSpriteCache(old); - SpriteCache *scnew = AllocateSpriteCache(new); + SpriteCache *scold = GetSpriteCache(old_spr); + SpriteCache *scnew = AllocateSpriteCache(new_spr); scnew->file_pos = scold->file_pos; scnew->ptr = NULL; @@ -306,7 +307,7 @@ static void CompactSpriteCache(void) static void DeleteEntryFromSpriteCache(void) { SpriteID i; - uint best = -1; + uint best = UINT_MAX; MemBlock* s; int cur_lru; @@ -403,7 +404,7 @@ const void *GetRawSprite(SpriteID sprite) void GfxInitSpriteMem(void) { // initialize sprite cache heap - if (_spritecache_ptr == NULL) _spritecache_ptr = malloc(SPRITE_CACHE_SIZE); + if (_spritecache_ptr == NULL) _spritecache_ptr = (MemBlock*)malloc(SPRITE_CACHE_SIZE); // A big free block _spritecache_ptr->size = (SPRITE_CACHE_SIZE - sizeof(MemBlock)) | S_FREE_MASK; diff --git a/src/spritecache.h b/src/spritecache.h index 3a5676a63..bddc75f69 100644 --- a/src/spritecache.h +++ b/src/spritecache.h @@ -17,19 +17,19 @@ bool SpriteExists(SpriteID sprite); static inline const Sprite *GetSprite(SpriteID sprite) { - return GetRawSprite(sprite); + return (Sprite*)GetRawSprite(sprite); } static inline const byte *GetNonSprite(SpriteID sprite) { - return GetRawSprite(sprite); + return (byte*)GetRawSprite(sprite); } void GfxInitSpriteMem(void); void IncreaseSpriteLRU(void); bool LoadNextSprite(int load_index, byte file_index); -void DupSprite(SpriteID old, SpriteID new); +void DupSprite(SpriteID old_spr, SpriteID new_spr); void SkipSprites(uint count); #endif /* SPRITECACHE_H */ diff --git a/src/station.h b/src/station.h index aaa168384..4e2bebc9a 100644 --- a/src/station.h +++ b/src/station.h @@ -26,10 +26,11 @@ typedef enum RoadStopType { } RoadStopType; enum { - INVALID_STATION = 0xFFFF, ROAD_STOP_LIMIT = 16, }; +static const StationID INVALID_STATION = 0xFFFF; + typedef struct RoadStop { TileIndex xy; bool used; @@ -64,7 +65,7 @@ struct Station { byte time_since_load; byte time_since_unload; byte delete_ctr; - PlayerID owner; + PlayerByte owner; byte facilities; byte airport_type; diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index 21784c473..adca43cbe 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -33,6 +33,7 @@ #include "newgrf_station.h" #include "yapf/yapf.h" #include "date.h" +#include "helpers.hpp" typedef enum StationRectModes { @@ -982,7 +983,7 @@ int32 CmdBuildRailroadStation(TileIndex tile_org, uint32 flags, uint32 p1, uint3 if (!ValParamRailtype(p2 & 0xF)) return CMD_ERROR; /* unpack parameters */ - axis = p1 & 1; + axis = (Axis)(p1 & 1); numtracks = GB(p1, 8, 8); plat_len = GB(p1, 16, 8); /* w = length, h = num_tracks */ @@ -1052,7 +1053,7 @@ int32 CmdBuildRailroadStation(TileIndex tile_org, uint32 flags, uint32 p1, uint3 if (GB(p2, 8, 8) >= STAT_CLASS_MAX) return CMD_ERROR; /* Check if we can allocate a custom stationspec to this station */ - statspec = GetCustomStationSpec(GB(p2, 8, 8), GB(p2, 16, 8)); + statspec = GetCustomStationSpec((StationClassID)GB(p2, 8, 8), GB(p2, 16, 8)); specindex = AllocateSpecToStation(statspec, st, flags & DC_EXEC); if (specindex == -1) return CMD_ERROR; @@ -1097,7 +1098,7 @@ int32 CmdBuildRailroadStation(TileIndex tile_org, uint32 flags, uint32 p1, uint3 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1)); track = AxisToTrack(axis); - layout_ptr = alloca(numtracks * plat_len); + layout_ptr = (byte*)alloca(numtracks * plat_len); GetStationLayout(layout_ptr, numtracks, plat_len, statspec); numtracks_orig = numtracks; @@ -1107,7 +1108,7 @@ int32 CmdBuildRailroadStation(TileIndex tile_org, uint32 flags, uint32 p1, uint3 int w = plat_len; do { byte layout = *layout_ptr++; - MakeRailStation(tile, st->owner, st->index, axis, layout, GB(p2, 0, 4)); + MakeRailStation(tile, st->owner, st->index, axis, layout, (RailType)GB(p2, 0, 4)); SetCustomStationSpecIndex(tile, specindex); SetStationTileRandomBits(tile, GB(Random(), 0, 4)); @@ -1424,7 +1425,7 @@ int32 CmdBuildRoadStop(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) bool type = !!p2; /* Saveguard the parameters */ - if (!IsValidDiagDirection(p1)) return CMD_ERROR; + if (!IsValidDiagDirection((DiagDirection)p1)) return CMD_ERROR; SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION); @@ -1435,7 +1436,7 @@ int32 CmdBuildRoadStop(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (CmdFailed(ret)) return ret; cost = ret; - st = GetStationAround(tile, 1, 1, -1); + st = GetStationAround(tile, 1, 1, INVALID_STATION); if (st == CHECK_STATIONS_ERR) return CMD_ERROR; /* Find a station close to us */ @@ -1500,7 +1501,7 @@ int32 CmdBuildRoadStop(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) StationRect_BeforeAddTile(st, tile, RECT_MODE_TRY); - MakeRoadStop(tile, st->owner, st->index, type, p1); + MakeRoadStop(tile, st->owner, st->index, type ? RS_TRUCK : RS_BUS, (DiagDirection)p1); UpdateStationVirtCoordDirty(st); UpdateStationAcceptance(st, false); @@ -1696,7 +1697,7 @@ int32 CmdBuildAirport(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) if (CmdFailed(ret)) return ret; cost = ret; - st = GetStationAround(tile, w, h, -1); + st = GetStationAround(tile, w, h, INVALID_STATION); if (st == CHECK_STATIONS_ERR) return CMD_ERROR; /* Find a station close to us */ @@ -1973,7 +1974,7 @@ int32 CmdBuildDock(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) /* middle */ st = GetStationAround( tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]), - _dock_w_chk[direction], _dock_h_chk[direction], -1); + _dock_w_chk[direction], _dock_h_chk[direction], INVALID_STATION); if (st == CHECK_STATIONS_ERR) return CMD_ERROR; /* Find a station close to us */ @@ -2109,7 +2110,7 @@ static void DrawTile_Station(TileInfo *ti) /* Ensure the chosen tile layout is valid for this custom station */ if (statspec->renderdata != NULL) { - t = &statspec->renderdata[tile < statspec->tiles ? tile : GetRailStationAxis(ti->tile)]; + t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)]; } } } @@ -2507,10 +2508,10 @@ static void UpdateStationRating(Station *st) } { - int or = ge->rating; // old rating + int or_ = ge->rating; // old rating // only modify rating in steps of -2, -1, 0, 1 or 2 - ge->rating = rating = or + clamp(clamp(rating, 0, 255) - or, -2, 2); + ge->rating = rating = or_ + clamp(clamp(rating, 0, 255) - or_, -2, 2); // if rating is <= 64 and more than 200 items waiting, remove some random amount of goods from the station if (rating <= 64 && waiting >= 200) { @@ -2932,7 +2933,7 @@ void AfterLoadStations(void) } -const TileTypeProcs _tile_type_station_procs = { +extern const TileTypeProcs _tile_type_station_procs = { DrawTile_Station, /* draw_tile_proc */ GetSlopeZ_Station, /* get_slope_z_proc */ ClearTile_Station, /* clear_tile_proc */ @@ -3064,7 +3065,7 @@ static void SaveLoad_STNS(Station *st) if (st->num_specs != 0) { /* Allocate speclist memory when loading a game */ - if (st->speclist == NULL) st->speclist = calloc(st->num_specs, sizeof(*st->speclist)); + if (st->speclist == NULL) CallocT(&st->speclist, st->num_specs); for (i = 0; i < st->num_specs; i++) SlObject(&st->speclist[i], _station_speclist_desc); } } @@ -3155,7 +3156,7 @@ static void Load_ROADSTOP(void) } } -const ChunkHandler _station_chunk_handlers[] = { +extern const ChunkHandler _station_chunk_handlers[] = { { 'STNS', Save_STNS, Load_STNS, CH_ARRAY }, { 'ROAD', Save_ROADSTOP, Load_ROADSTOP, CH_ARRAY | CH_LAST}, }; diff --git a/src/station_gui.cpp b/src/station_gui.cpp index 55428a793..56b05ee0e 100644 --- a/src/station_gui.cpp +++ b/src/station_gui.cpp @@ -18,6 +18,7 @@ #include "vehicle_gui.h" #include "date.h" #include "vehicle.h" +#include "helpers.hpp" enum StationListWidgets { STATIONLIST_WIDGET_CLOSEBOX = 0, @@ -156,6 +157,8 @@ typedef enum StationListFlags { SL_REBUILD = 0x04, } StationListFlags; +DECLARE_ENUM_AS_BIT_SET(StationListFlags); + typedef struct plstations_d { const Station** sort_list; uint16 list_length; @@ -201,7 +204,7 @@ static void BuildStationsList(plstations_d* sl, PlayerID owner, byte facilities, if (!(sl->flags & SL_REBUILD)) return; /* Create array for sorting */ - station_sort = malloc((GetMaxStationIndex() + 1) * sizeof(station_sort[0])); + MallocT(&station_sort, GetMaxStationIndex() + 1); if (station_sort == NULL) error("Could not allocate memory for the station-sorting-list"); DEBUG(misc, 3, "Building station list for player %d", owner); @@ -228,7 +231,7 @@ static void BuildStationsList(plstations_d* sl, PlayerID owner, byte facilities, } free((void*)sl->sort_list); - sl->sort_list = malloc(n * sizeof(sl->sort_list[0])); + MallocT(&sl->sort_list, n); if (n != 0 && sl->sort_list == NULL) error("Could not allocate memory for the station-sorting-list"); sl->list_length = n; @@ -260,7 +263,7 @@ static void SortStationsList(plstations_d *sl) static void PlayerStationsWndProc(Window *w, WindowEvent *e) { - const PlayerID owner = w->window_number; + const PlayerID owner = (PlayerID)w->window_number; static byte facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK; static uint16 cargo_filter = CARGO_ALL_SELECTED; plstations_d *sl = &WP(w, plstations_d); @@ -432,7 +435,7 @@ static void PlayerStationsWndProc(Window *w, WindowEvent *e) break; } case STATIONLIST_WIDGET_SORTBY: /*flip sorting method asc/desc*/ - TOGGLEBIT(sl->flags, 0); //DESC-flag + sl->flags ^= SL_ORDER; //DESC-flag sl->flags |= SL_RESORT; w->flags4 |= 5 << WF_TIMEOUT_SHL; LowerWindowWidget(w, STATIONLIST_WIDGET_SORTBY); @@ -477,7 +480,7 @@ static void PlayerStationsWndProc(Window *w, WindowEvent *e) if (--sl->resort_timer == 0) { DEBUG(misc, 3, "Periodic rebuild station list player %d", owner); sl->resort_timer = DAY_TICKS * PERIODIC_RESORT_DAYS; - sl->flags |= VL_REBUILD; + sl->flags |= SL_REBUILD; SetWindowDirty(w); } break; diff --git a/src/stdafx.h b/src/stdafx.h index eae4fa512..89d51c477 100644 --- a/src/stdafx.h +++ b/src/stdafx.h @@ -7,6 +7,7 @@ #include <stddef.h> #include <string.h> #include <stdlib.h> +#include <limits.h> // MacOS X will use an NSAlert to display failed assertaions since they're lost unless running from a terminal // strgen always runs from terminal and don't need a window for asserts @@ -103,6 +104,7 @@ # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers # pragma warning(disable: 4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data # pragma warning(disable: 4761) // integral size mismatch in argument : conversion supplied +# pragma warning(disable: 4200) // nonstandard extension used : zero-sized array in struct/union # if _MSC_VER >= 1400 // MSVC 2005 safety checks # pragma warning(disable: 4996) // 'strdup' was declared deprecated @@ -306,7 +308,4 @@ assert_compile(sizeof(uint8) == 1); # define Point OTTD_AMIGA_POINT #endif -#define EXTERN_C_BEGIN extern "C" { -#define EXTERN_C_END } - #endif /* STDAFX_H */ diff --git a/src/strgen/strgen.cpp b/src/strgen/strgen.cpp index 640ac3c63..4268f0bbb 100644 --- a/src/strgen/strgen.cpp +++ b/src/strgen/strgen.cpp @@ -4,6 +4,7 @@ #include "../macros.h" #include "../string.h" #include "../table/control_codes.h" +#include "../helpers.hpp" #include <stdio.h> #include <string.h> #include <stdlib.h> @@ -11,6 +12,8 @@ #if (!defined(WIN32) && !defined(WIN64)) || defined(__CYGWIN__) #include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> #endif #if defined WIN32 || defined __WATCOMC__ @@ -113,7 +116,7 @@ static const char *_cur_ident; typedef struct CmdPair { const CmdStruct *a; - char *v; + const char *v; } CmdPair; typedef struct ParsedCommandStruct { @@ -842,7 +845,7 @@ static void HandleString(char *str, bool master) } // Allocate a new LangString - ent = calloc(1, sizeof(*ent)); + CallocT(&ent, 1); _strings[_next_string_id] = ent; ent->index = _next_string_id++; ent->name = strdup(str); @@ -852,7 +855,8 @@ static void HandleString(char *str, bool master) } if (casep != NULL) { - Case* c = malloc(sizeof(*c)); + Case* c; + MallocT(&c, 1); c->caseidx = ResolveCaseName(casep, strlen(casep)); c->string = strdup(s); @@ -881,7 +885,8 @@ static void HandleString(char *str, bool master) if (!CheckCommandsMatch(s, ent->english, str)) return; if (casep != NULL) { - Case* c = malloc(sizeof(*c)); + Case* c; + MallocT(&c, 1); c->caseidx = ResolveCaseName(casep, strlen(casep)); c->string = strdup(s); @@ -1021,17 +1026,12 @@ static void WriteStringsH(const char *filename) out = fopen("tmp.xxx", "w"); if (out == NULL) fatal("can't open tmp.xxx"); - fprintf(out, "enum {"); + fprintf(out, "enum StringIdEnum {"); lastgrp = 0; for (i = 0; i != lengthof(_strings); i++) { if (_strings[i] != NULL) { - if (lastgrp != (i >> 11)) { - lastgrp = (i >> 11); - fprintf(out, "};\n\nenum {"); - } - fprintf(out, next == i ? "\t%s,\n" : "\n\t%s = 0x%X,\n", _strings[i]->name, i); next = i + 1; } diff --git a/src/string.cpp b/src/string.cpp index dba2c7131..7e4aaf1d2 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -6,6 +6,7 @@ #include "string.h" #include "macros.h" #include "table/control_codes.h" +#include "helpers.hpp" #include <stdarg.h> #include <ctype.h> // required for tolower() @@ -63,7 +64,7 @@ char* CDECL str_fmt(const char* str, ...) va_start(va, str); len = vsnprintf(buf, lengthof(buf), str, va); va_end(va); - p = malloc(len + 1); + MallocT(&p, len + 1); if (p != NULL) memcpy(p, buf, len + 1); return p; } diff --git a/src/strings.cpp b/src/strings.cpp index d94674193..86a6709fc 100644 --- a/src/strings.cpp +++ b/src/strings.cpp @@ -22,6 +22,7 @@ #include "music.h" #include "date.h" #include "industry.h" +#include "helpers.hpp" #ifdef WIN32 /* for opendir/readdir/closedir */ @@ -751,7 +752,7 @@ static char* FormatString(char* buff, const char* str, const int32* argv, uint c // 8bit - cargo type // 16-bit - cargo count CargoID cargo = GetInt32(&argv); - StringID cargo_str = (cargo == CT_INVALID) ? STR_8838_N_A : _cargoc.names_long[cargo]; + StringID cargo_str = (cargo == CT_INVALID) ? (StringID)STR_8838_N_A : _cargoc.names_long[cargo]; buff = GetStringWithArgs(buff, cargo_str, argv++, last); break; } @@ -1139,7 +1140,7 @@ bool ReadLanguagePack(int lang_index) { char *lang = str_fmt("%s%s", _paths.lang_dir, _dynlang.ent[lang_index].file); - lang_pack = ReadFileToMem(lang, &len, 200000); + lang_pack = (LanguagePack*)ReadFileToMem(lang, &len, 200000); free(lang); } if (lang_pack == NULL) return false; @@ -1165,7 +1166,7 @@ bool ReadLanguagePack(int lang_index) } // Allocate offsets - langpack_offs = malloc(tot_count * sizeof(*langpack_offs)); + MallocT(&langpack_offs, tot_count); // Fill offsets s = lang_pack->data; @@ -1229,7 +1230,7 @@ static int GetLanguageList(char **languages, int max) if (dir != NULL) { while ((dirent = readdir(dir)) != NULL) { const char *d_name = FS2OTTD(dirent->d_name); - char *t = strrchr(d_name, '.'); + const char *t = strrchr(d_name, '.'); if (t != NULL && strcmp(t, ".lng") == 0) { languages[num++] = strdup(d_name); diff --git a/src/table/ai_rail.h b/src/table/ai_rail.h index 8e6a49c50..218f33f3d 100644 --- a/src/table/ai_rail.h +++ b/src/table/ai_rail.h @@ -12,24 +12,23 @@ typedef struct { byte p2; byte p3; byte dir; - AiDefaultBlockData data[VARARRAY_SIZE]; + const AiDefaultBlockData *data; } AiDefaultRailBlock; typedef struct { byte dir; - AiDefaultBlockData data[VARARRAY_SIZE]; + const AiDefaultBlockData *data; } AiDefaultRoadBlock; -#define MKHDR(a,b,c,d,e) a,b,c,d,e,{ +#define MKHDR(a,b,c,d,e) a,b,c,d,e, #define MKDEPOT(a, b, c) {0, a, {b, c}} #define MKSTATION(a, b, c) {1, a, {b, c}} #define MKRAIL(a, b, c) {2, a, {b, c}} #define MKCLRRAIL(a, b, c) {3, a, {b, c}} -#define MKEND {4, 0, {0, 0}}} +#define MKEND {4, 0, {0, 0}} -static const AiDefaultRailBlock _raildata_ai_0 = { - MKHDR(1, 2, 1, 0, 1) +static const AiDefaultBlockData _raildata_ai_0_data[] = { MKDEPOT(2, -1, 1), MKSTATION(0x15, 0, -1), MKRAIL(0x26, 0, 1), @@ -37,8 +36,11 @@ static const AiDefaultRailBlock _raildata_ai_0 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_1 = { - MKHDR(1, 2, 1, 0, 3) +static const AiDefaultRailBlock _raildata_ai_0 = { + 1, 2, 1, 0, 1, _raildata_ai_0_data +}; + +static const AiDefaultBlockData _raildata_ai_1_data[] = { MKDEPOT(2, -1, -1), MKRAIL(0x26, 0, -1), MKSTATION(0x15, 0, 0), @@ -46,8 +48,11 @@ static const AiDefaultRailBlock _raildata_ai_1 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_2 = { - MKHDR(1, 2, 1, 0, 0) +static const AiDefaultRailBlock _raildata_ai_1 = { + 1, 2, 1, 0, 3, _raildata_ai_1_data +}; + +static const AiDefaultBlockData _raildata_ai_2_data[] = { MKDEPOT(1, -1, -1), MKRAIL(0x15, -1, 0), MKSTATION(0x14, 0, 0), @@ -55,8 +60,11 @@ static const AiDefaultRailBlock _raildata_ai_2 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_3 = { - MKHDR(1, 2, 1, 0, 2) +static const AiDefaultRailBlock _raildata_ai_2 = { + 1, 2, 1, 0, 0, _raildata_ai_2_data +}; + +static const AiDefaultBlockData _raildata_ai_3_data[] = { MKDEPOT(1, 1, -1), MKRAIL(0x15, 1, 0), MKSTATION(0x14, -1, 0), @@ -64,24 +72,33 @@ static const AiDefaultRailBlock _raildata_ai_3 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_4 = { - MKHDR(1, 2, 2, 0, 255) +static const AiDefaultRailBlock _raildata_ai_3 = { + 1, 2, 1, 0, 2, _raildata_ai_3_data +}; + +static const AiDefaultBlockData _raildata_ai_4_data[] = { MKSTATION(0x15, 0, 0), MKCLRRAIL(3, 0, -1), MKCLRRAIL(1, 0, 2), MKEND }; -static const AiDefaultRailBlock _raildata_ai_5 = { - MKHDR(1, 2, 2, 0, 255) +static const AiDefaultRailBlock _raildata_ai_4 = { + 1, 2, 2, 0, 255, _raildata_ai_4_data +}; + +static const AiDefaultBlockData _raildata_ai_5_data[] = { MKSTATION(0x14, 0, 0), MKCLRRAIL(0, -1, 0), MKCLRRAIL(2, 2, 0), MKEND }; -static const AiDefaultRailBlock _raildata_ai_6 = { - MKHDR(2, 3, 1, 0, 1) +static const AiDefaultRailBlock _raildata_ai_5 = { + 1, 2, 2, 0, 255, _raildata_ai_5_data +}; + +static const AiDefaultBlockData _raildata_ai_6_data[] = { MKSTATION(0x27, 0, -2), MKRAIL(0xC2, 0, 1), MKRAIL(0xC2, 1, 1), @@ -92,8 +109,11 @@ static const AiDefaultRailBlock _raildata_ai_6 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_7 = { - MKHDR(2, 3, 1, 0, 3) +static const AiDefaultRailBlock _raildata_ai_6 = { + 2, 3, 1, 0, 1, _raildata_ai_6_data +}; + +static const AiDefaultBlockData _raildata_ai_7_data[] = { MKDEPOT(1, 0, -3), MKRAIL(0x1A, 0, -2), MKRAIL(0x26, 1, -2), @@ -104,8 +124,11 @@ static const AiDefaultRailBlock _raildata_ai_7 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_8 = { - MKHDR(2, 3, 1, 0, 2) +static const AiDefaultRailBlock _raildata_ai_7 = { + 2, 3, 1, 0, 3, _raildata_ai_7_data +}; + +static const AiDefaultBlockData _raildata_ai_8_data[] = { MKSTATION(0x26, -2, 0), MKRAIL(0xC1, 1, 0), MKRAIL(0xC1, 1, 1), @@ -116,8 +139,11 @@ static const AiDefaultRailBlock _raildata_ai_8 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_9 = { - MKHDR(2, 3, 1, 0, 0) +static const AiDefaultRailBlock _raildata_ai_8 = { + 2, 3, 1, 0, 2, _raildata_ai_8_data +}; + +static const AiDefaultBlockData _raildata_ai_9_data[] = { MKDEPOT(2, -3, -1), MKRAIL(0x29, -2, -1), MKRAIL(0x15, -2, 0), @@ -128,8 +154,11 @@ static const AiDefaultRailBlock _raildata_ai_9 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_10 = { - MKHDR(2, 3, 2, 0, 255) +static const AiDefaultRailBlock _raildata_ai_9 = { + 2, 3, 1, 0, 0, _raildata_ai_9_data +}; + +static const AiDefaultBlockData _raildata_ai_10_data[] = { MKRAIL(0x1A, 0, -3), MKRAIL(0x20, 1, -3), MKRAIL(0xC2, 0, -2), @@ -144,8 +173,11 @@ static const AiDefaultRailBlock _raildata_ai_10 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_11 = { - MKHDR(2, 3, 2, 0, 255) +static const AiDefaultRailBlock _raildata_ai_10 = { + 2, 3, 2, 0, 255, _raildata_ai_10_data +}; + +static const AiDefaultBlockData _raildata_ai_11_data[] = { MKRAIL(0x29, -3, 0), MKRAIL(0x10, -3, 1), MKRAIL(0xC1, -2, 0), @@ -160,8 +192,11 @@ static const AiDefaultRailBlock _raildata_ai_11 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_12 = { - MKHDR(2, 3, 2, 1, 3) +static const AiDefaultRailBlock _raildata_ai_11 = { + 2, 3, 2, 0, 255, _raildata_ai_11_data +}; + +static const AiDefaultBlockData _raildata_ai_12_data[] = { MKRAIL(0x88, -1, -3), MKRAIL(0x6, 0, -3), MKRAIL(0x2, -1, -2), @@ -179,8 +214,11 @@ static const AiDefaultRailBlock _raildata_ai_12 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_13 = { - MKHDR(2, 3, 2, 1, 0) +static const AiDefaultRailBlock _raildata_ai_12 = { + 2, 3, 2, 1, 3, _raildata_ai_12_data +}; + +static const AiDefaultBlockData _raildata_ai_13_data[] = { MKRAIL(0x21, -3, 0), MKRAIL(0x50, -3, 1), MKRAIL(0x81, -2, 0), @@ -198,8 +236,11 @@ static const AiDefaultRailBlock _raildata_ai_13 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_14 = { - MKHDR(2, 3, 2, 1, 1) +static const AiDefaultRailBlock _raildata_ai_13 = { + 2, 3, 2, 1, 0, _raildata_ai_13_data +}; + +static const AiDefaultBlockData _raildata_ai_14_data[] = { MKRAIL(0x88, -1, -3), MKRAIL(0x6, 0, -3), MKRAIL(0x2, -1, -2), @@ -217,8 +258,11 @@ static const AiDefaultRailBlock _raildata_ai_14 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_15 = { - MKHDR(2, 3, 2, 1, 2) +static const AiDefaultRailBlock _raildata_ai_14 = { + 2, 3, 2, 1, 1, _raildata_ai_14_data +}; + +static const AiDefaultBlockData _raildata_ai_15_data[] = { MKRAIL(0x21, -3, 0), MKRAIL(0x50, -3, 1), MKRAIL(0x81, -2, 0), @@ -236,8 +280,11 @@ static const AiDefaultRailBlock _raildata_ai_15 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_16 = { - MKHDR(1, 3, 1, 0, 1) +static const AiDefaultRailBlock _raildata_ai_15 = { + 2, 3, 2, 1, 2, _raildata_ai_15_data +}; + +static const AiDefaultBlockData _raildata_ai_16_data[] = { MKSTATION(0x17, 0, -2), MKRAIL(0x1A, 0, 1), MKCLRRAIL(1, 0, 2), @@ -245,8 +292,11 @@ static const AiDefaultRailBlock _raildata_ai_16 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_17 = { - MKHDR(1, 3, 1, 0, 3) +static const AiDefaultRailBlock _raildata_ai_16 = { + 1, 3, 1, 0, 1, _raildata_ai_16_data +}; + +static const AiDefaultBlockData _raildata_ai_17_data[] = { MKCLRRAIL(3, 0, -2), MKRAIL(0x26, 0, -1), MKDEPOT(2, -1, -1), @@ -254,8 +304,11 @@ static const AiDefaultRailBlock _raildata_ai_17 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_18 = { - MKHDR(1, 3, 1, 0, 0) +static const AiDefaultRailBlock _raildata_ai_17 = { + 1, 3, 1, 0, 3, _raildata_ai_17_data +}; + +static const AiDefaultBlockData _raildata_ai_18_data[] = { MKCLRRAIL(0, -2, 0), MKRAIL(0x29, -1, 0), MKDEPOT(3, -1, 1), @@ -263,8 +316,11 @@ static const AiDefaultRailBlock _raildata_ai_18 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_19 = { - MKHDR(1, 3, 1, 0, 2) +static const AiDefaultRailBlock _raildata_ai_18 = { + 1, 3, 1, 0, 0, _raildata_ai_18_data +}; + +static const AiDefaultBlockData _raildata_ai_19_data[] = { MKSTATION(0x16, -2, 0), MKDEPOT(2, 0, -1), MKRAIL(0x20, 1, -1), @@ -273,8 +329,11 @@ static const AiDefaultRailBlock _raildata_ai_19 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_20 = { - MKHDR(2, 3, 1, 0, 1) +static const AiDefaultRailBlock _raildata_ai_19 = { + 1, 3, 1, 0, 2, _raildata_ai_19_data +}; + +static const AiDefaultBlockData _raildata_ai_20_data[] = { MKSTATION(0x26, -2, 0), MKRAIL(0xC1, 1, 0), MKRAIL(0xC1, 1, 1), @@ -285,8 +344,11 @@ static const AiDefaultRailBlock _raildata_ai_20 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_21 = { - MKHDR(2, 3, 1, 0, 3) +static const AiDefaultRailBlock _raildata_ai_20 = { + 2, 3, 1, 0, 1, _raildata_ai_20_data +}; + +static const AiDefaultBlockData _raildata_ai_21_data[] = { MKDEPOT(2, -3, -1), MKRAIL(0x3F, -2, -1), MKRAIL(0x10, -2, 0), @@ -297,8 +359,11 @@ static const AiDefaultRailBlock _raildata_ai_21 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_22 = { - MKHDR(2, 3, 1, 0, 0) +static const AiDefaultRailBlock _raildata_ai_21 = { + 2, 3, 1, 0, 3, _raildata_ai_21_data +}; + +static const AiDefaultBlockData _raildata_ai_22_data[] = { MKSTATION(0x27, 0, -2), MKRAIL(0xC2, 0, 1), MKRAIL(0xC2, 1, 1), @@ -310,8 +375,11 @@ static const AiDefaultRailBlock _raildata_ai_22 = { MKEND }; -static const AiDefaultRailBlock _raildata_ai_23 = { - MKHDR(2, 3, 1, 0, 2) +static const AiDefaultRailBlock _raildata_ai_22 = { + 2, 3, 1, 0, 0, _raildata_ai_22_data +}; + +static const AiDefaultBlockData _raildata_ai_23_data[] = { MKDEPOT(1, 0, -3), MKRAIL(0x1A, 0, -2), MKRAIL(0x29, 1, -2), @@ -322,7 +390,9 @@ static const AiDefaultRailBlock _raildata_ai_23 = { MKEND }; - +static const AiDefaultRailBlock _raildata_ai_23 = { + 2, 3, 1, 0, 2, _raildata_ai_23_data +}; static const AiDefaultRailBlock * const _default_rail_track_data[] = { &_raildata_ai_0, @@ -356,8 +426,7 @@ static const AiDefaultRailBlock * const _default_rail_track_data[] = { #define MKHDR(a) a,{ -static const AiDefaultRoadBlock _roaddata_ai_0 = { - MKHDR(0) +static const AiDefaultBlockData _roaddata_ai_0_data[] = { MKDEPOT(2, -1,1), MKSTATION(0x2, -1,0), MKRAIL(0xC, 0,0), @@ -369,8 +438,11 @@ static const AiDefaultRoadBlock _roaddata_ai_0 = { MKEND }; -static const AiDefaultRoadBlock _roaddata_ai_1 = { - MKHDR(0) +static const AiDefaultRoadBlock _roaddata_ai_0 = { + 0, _roaddata_ai_0_data +}; + +static const AiDefaultBlockData _roaddata_ai_1_data[] = { MKDEPOT(1, 0,-1), MKSTATION(0x1, 1,-1), MKRAIL(0x3, 0,0), @@ -382,8 +454,11 @@ static const AiDefaultRoadBlock _roaddata_ai_1 = { MKEND }; -static const AiDefaultRoadBlock _roaddata_ai_2 = { - MKHDR(0) +static const AiDefaultRoadBlock _roaddata_ai_1 = { + 0, _roaddata_ai_1_data +}; + +static const AiDefaultBlockData _roaddata_ai_2_data[] = { MKDEPOT(3, 1,1), MKSTATION(0x3, 0,1), MKRAIL(0x6, 0,0), @@ -395,8 +470,11 @@ static const AiDefaultRoadBlock _roaddata_ai_2 = { MKEND }; -static const AiDefaultRoadBlock _roaddata_ai_3 = { - MKHDR(0) +static const AiDefaultRoadBlock _roaddata_ai_2 = { + 0, _roaddata_ai_2_data +}; + +static const AiDefaultBlockData _roaddata_ai_3_data[] = { MKDEPOT(0, 1,0), MKSTATION(0x0, 1,1), MKRAIL(0x6, 0,0), @@ -408,8 +486,11 @@ static const AiDefaultRoadBlock _roaddata_ai_3 = { MKEND }; -static const AiDefaultRoadBlock _roaddata_ai_4 = { - MKHDR(1) +static const AiDefaultRoadBlock _roaddata_ai_3 = { + 0, _roaddata_ai_3_data +}; + +static const AiDefaultBlockData _roaddata_ai_4_data[] = { MKSTATION(0x2, -1,0), MKRAIL(0x8, 0,0), MKCLRRAIL(0, 0,-1), @@ -418,8 +499,11 @@ static const AiDefaultRoadBlock _roaddata_ai_4 = { MKEND }; -static const AiDefaultRoadBlock _roaddata_ai_5 = { - MKHDR(1) +static const AiDefaultRoadBlock _roaddata_ai_4 = { + 1, _roaddata_ai_4_data +}; + +static const AiDefaultBlockData _roaddata_ai_5_data[] = { MKSTATION(0x3, 0,1), MKRAIL(0x4, 0,0), MKCLRRAIL(0, -1,0), @@ -428,8 +512,11 @@ static const AiDefaultRoadBlock _roaddata_ai_5 = { MKEND }; -static const AiDefaultRoadBlock _roaddata_ai_6 = { - MKHDR(1) +static const AiDefaultRoadBlock _roaddata_ai_5 = { + 1, _roaddata_ai_5_data +}; + +static const AiDefaultBlockData _roaddata_ai_6_data[] = { MKSTATION(0x0, 1,1), MKRAIL(0x2, 0,1), MKCLRRAIL(0, 0,0), @@ -438,8 +525,11 @@ static const AiDefaultRoadBlock _roaddata_ai_6 = { MKEND }; -static const AiDefaultRoadBlock _roaddata_ai_7 = { - MKHDR(1) +static const AiDefaultRoadBlock _roaddata_ai_6 = { + 1, _roaddata_ai_6_data +}; + +static const AiDefaultBlockData _roaddata_ai_7_data[] = { MKSTATION(0x1, 1,-1), MKRAIL(0x1, 1,0), MKCLRRAIL(0, 0,0), @@ -448,6 +538,10 @@ static const AiDefaultRoadBlock _roaddata_ai_7 = { MKEND }; +static const AiDefaultRoadBlock _roaddata_ai_7 = { + 1, _roaddata_ai_7_data +}; + static const AiDefaultRoadBlock * const _road_default_block_data[] = { &_roaddata_ai_0, diff --git a/src/table/engines.h b/src/table/engines.h index 08c4cea00..8fd8a7ee6 100644 --- a/src/table/engines.h +++ b/src/table/engines.h @@ -490,7 +490,7 @@ const RailVehicleInfo orig_rail_vehicle_info[NUM_TRAIN_ENGINES] = { * @param g sound effect * @param h refittable */ -#define SVI(a, b, c, d, e, f, g, h) { a, b, c, d, e, f, g, h } +#define SVI(a, b, c, d, e, f, g, h) { a, b, c, d, e, f, {g}, h } const ShipVehicleInfo orig_ship_vehicle_info[NUM_SHIP_ENGINES] = { // image_index cargo_type cargo_amount refittable // | base_cost | | running_cost | @@ -522,7 +522,7 @@ const ShipVehicleInfo orig_ship_vehicle_info[NUM_SHIP_ENGINES] = { * @param h mail_capacity * @param i passenger_capacity */ -#define AVI(a, b, c, d, e, f, g, h, i) { a, b, c, d, e, f, g, h, i } +#define AVI(a, b, c, d, e, f, g, h, i) { a, b, c, d, {e}, f, g, h, i } #define H 0 #define P AIR_CTOL #define J AIR_CTOL | AIR_FAST @@ -589,7 +589,7 @@ const AircraftVehicleInfo orig_aircraft_vehicle_info[NUM_AIRCRAFT_ENGINES] = { * @param f capacity * @param g cargo_type */ -#define RVI(a, b, c, d, e, f, g) { a, b, c, d, e, f, g } +#define RVI(a, b, c, d, e, f, g) { a, b, c, {d}, e, f, g } const RoadVehicleInfo orig_road_vehicle_info[NUM_ROAD_ENGINES] = { // image_index sfx max_speed // | base_cost | | capacity diff --git a/src/table/namegen.h b/src/table/namegen.h index a5d9974d6..d5a4b6107 100644 --- a/src/table/namegen.h +++ b/src/table/namegen.h @@ -1727,6 +1727,9 @@ typedef enum CzechAllow { CZA_LONG = 4, CZA_ALL = ~0 } CzechAllow; + +DECLARE_ENUM_AS_BIT_SET(CzechAllow); + // All these flags must be satisfied (in the stem->others direction): typedef enum CzechChoose { CZC_NONE = 0, // No requirements. @@ -1736,6 +1739,8 @@ typedef enum CzechChoose { CZC_ANY = ~0 } CzechChoose; +DECLARE_ENUM_AS_BIT_SET(CzechChoose); + typedef struct CzechNameSubst { CzechGender gender; CzechAllow allow; diff --git a/src/table/sprites.h b/src/table/sprites.h index 071c5ddfb..4d5b91571 100644 --- a/src/table/sprites.h +++ b/src/table/sprites.h @@ -1336,6 +1336,9 @@ enum Recoloring { }; #define PALETTE_RECOLOR_SPRITE(a) (a << PALETTE_SPRITE_START | PALETTE_MODIFIER_COLOR) + +static const PalSpriteID PALETTE_CRASH = PALETTE_RECOLOR_SPRITE(0x324); + enum PaletteSprites { //note: these numbers are already the modified once the renderer needs. //the actual sprite number is the upper 16 bits of the number @@ -1384,7 +1387,8 @@ enum PaletteSprites { PALETTE_TO_TRANSPARENT = 0x322 << PALETTE_SPRITE_START | PALETTE_MODIFIER_TRANSPARENT, //This sets the sprite to transparent //This is used for changing the tubular bridges to the silicon display, or some grayish color PALETTE_TO_STRUCT_GREY = PALETTE_RECOLOR_SPRITE(0x323), - PALETTE_CRASH = PALETTE_RECOLOR_SPRITE(0x324), //this changes stuff to the "crash color" + + //XXX - const - PALETTE_CRASH = PALETTE_RECOLOR_SPRITE(0x324), //this changes stuff to the "crash color" //XXX another place where structures are colored. //I'm not sure which colors these are PALETTE_59E = PALETTE_RECOLOR_SPRITE(0x59E), diff --git a/src/table/station_land.h b/src/table/station_land.h index 1c5864c2a..443987208 100644 --- a/src/table/station_land.h +++ b/src/table/station_land.h @@ -1,6 +1,6 @@ /* $Id$ */ -#define TILE_SEQ_END() { 0x80, 0, 0, 0, 0, 0, 0 } +#define TILE_SEQ_END() { (byte)0x80, 0, 0, 0, 0, 0, 0 } static const DrawTileSeqStruct _station_display_datas_0[] = { { 0, 0, 0, 16, 5, 2, SPR_RAIL_PLATFORM_X_REAR | PALETTE_MODIFIER_COLOR }, @@ -30,7 +30,7 @@ static const DrawTileSeqStruct _station_display_datas_4[] = { { 0, 0, 0, 16, 5, 7, SPR_RAIL_PLATFORM_PILLARS_X_REAR | PALETTE_MODIFIER_COLOR }, { 0, 11, 0, 16, 5, 2, SPR_RAIL_PLATFORM_X_FRONT | PALETTE_MODIFIER_COLOR }, { 0, 0, 16, 16, 16, 10, SPR_RAIL_ROOF_STRUCTURE_X_TILE_A | PALETTE_MODIFIER_COLOR }, - { 0, 0,0x80, 0, 0, 0, SPR_RAIL_ROOF_GLASS_X_TILE_A | PALETTE_TO_TRANSPARENT }, + { 0, 0,(byte)0x80, 0, 0, 0, SPR_RAIL_ROOF_GLASS_X_TILE_A | PALETTE_TO_TRANSPARENT }, TILE_SEQ_END() }; @@ -38,7 +38,7 @@ static const DrawTileSeqStruct _station_display_datas_5[] = { { 0, 0, 0, 5, 16, 2, SPR_RAIL_PLATFORM_PILLARS_Y_REAR | PALETTE_MODIFIER_COLOR }, { 11, 0, 0, 5, 16, 2, SPR_RAIL_PLATFORM_Y_FRONT | PALETTE_MODIFIER_COLOR }, { 0, 0, 16, 16, 16, 10, SPR_RAIL_ROOF_STRUCTURE_Y_TILE_A | PALETTE_MODIFIER_COLOR }, - { 0, 0,0x80, 0, 0, 0, SPR_RAIL_ROOF_GLASS_Y_TILE_A | PALETTE_TO_TRANSPARENT }, + { 0, 0,(byte)0x80, 0, 0, 0, SPR_RAIL_ROOF_GLASS_Y_TILE_A | PALETTE_TO_TRANSPARENT }, TILE_SEQ_END() }; @@ -46,7 +46,7 @@ static const DrawTileSeqStruct _station_display_datas_6[] = { { 0, 0, 0, 16, 5, 2, SPR_RAIL_PLATFORM_X_REAR | PALETTE_MODIFIER_COLOR }, { 0, 11, 0, 16, 5, 2, SPR_RAIL_PLATFORM_PILLARS_X_FRONT | PALETTE_MODIFIER_COLOR }, { 0, 0, 16, 16, 16, 10, SPR_RAIL_ROOF_STRUCTURE_X_TILE_B | PALETTE_MODIFIER_COLOR }, - { 0, 0,0x80, 0, 0, 0, SPR_RAIL_ROOF_GLASS_X_TILE_B | PALETTE_TO_TRANSPARENT }, + { 0, 0,(byte)0x80, 0, 0, 0, SPR_RAIL_ROOF_GLASS_X_TILE_B | PALETTE_TO_TRANSPARENT }, TILE_SEQ_END() }; @@ -54,7 +54,7 @@ static const DrawTileSeqStruct _station_display_datas_7[] = { { 0, 0, 0, 5, 16, 2, SPR_RAIL_PLATFORM_Y_REAR | PALETTE_MODIFIER_COLOR }, { 11, 0, 0, 5, 16, 2, SPR_RAIL_PLATFORM_PILLARS_Y_FRONT | PALETTE_MODIFIER_COLOR }, { 0, 0, 16, 16, 16, 10, SPR_RAIL_ROOF_STRUCTURE_Y_TILE_B | PALETTE_MODIFIER_COLOR }, - { 0, 0,0x80, 0, 0, 0, SPR_RAIL_ROOF_GLASS_Y_TILE_B | PALETTE_TO_TRANSPARENT }, + { 0, 0,(byte)0x80, 0, 0, 0, SPR_RAIL_ROOF_GLASS_Y_TILE_B | PALETTE_TO_TRANSPARENT }, TILE_SEQ_END() }; diff --git a/src/table/track_land.h b/src/table/track_land.h index 78031e840..06b33205e 100644 --- a/src/table/track_land.h +++ b/src/table/track_land.h @@ -1,7 +1,7 @@ /* $Id$ */ #define TILE_SEQ_LINE(img, dx, dy, sx, sy) { dx, dy, 0, sx, sy, 23, img }, -#define TILE_SEQ_END() { 0x80, 0, 0, 0, 0, 0, 0 } +#define TILE_SEQ_END() { (byte)0x80, 0, 0, 0, 0, 0, 0 } static const DrawTileSeqStruct _depot_gfx_NE[] = { diff --git a/src/table/unmovable_land.h b/src/table/unmovable_land.h index 9b9e7d6cd..4c5908fb6 100644 --- a/src/table/unmovable_land.h +++ b/src/table/unmovable_land.h @@ -10,7 +10,7 @@ typedef struct DrawTileUnmovableStruct { byte unused; } DrawTileUnmovableStruct; -#define TILE_SEQ_END() { 0x80, 0, 0, 0, 0, 0, 0 } +#define TILE_SEQ_END() { (byte)0x80, 0, 0, 0, 0, 0, 0 } static const DrawTileUnmovableStruct _draw_tile_unmovable_data[] = { {0xA29, 7, 7, 2, 2, 70, 0}, diff --git a/src/texteff.cpp b/src/texteff.cpp index c65cb8675..82264098e 100644 --- a/src/texteff.cpp +++ b/src/texteff.cpp @@ -379,6 +379,6 @@ static void SaveLoad_ANIT(void) } -const ChunkHandler _animated_tile_chunk_handlers[] = { +extern const ChunkHandler _animated_tile_chunk_handlers[] = { { 'ANIT', SaveLoad_ANIT, SaveLoad_ANIT, CH_RIFF | CH_LAST}, }; diff --git a/src/tgp.cpp b/src/tgp.cpp index d7f9722f9..897aad3bf 100644 --- a/src/tgp.cpp +++ b/src/tgp.cpp @@ -14,6 +14,7 @@ #include "tgp.h" #include "console.h" #include "genworld.h" +#include "helpers.hpp" /* * OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin @@ -190,9 +191,8 @@ static HeightMap _height_map = {NULL, 0, 0, 0, 0}; #define A2I(i) ((i) >> amplitude_decimal_bits) /** Conversion: amplitude_t to height_t */ -#define A2H(a) ((height_decimal_bits < amplitude_decimal_bits) \ - ? ((a) >> (amplitude_decimal_bits - height_decimal_bits)) \ - : ((a) << (height_decimal_bits - amplitude_decimal_bits))) +#define A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits)) + /** Walk through all items of _height_map.h */ #define FOR_ALL_TILES_IN_HEIGHT(h) for (h = _height_map.h; h < &_height_map.h[_height_map.total_size]; h++) @@ -239,7 +239,7 @@ static inline bool AllocHeightMap(void) /* Allocate memory block for height map row pointers */ _height_map.total_size = (_height_map.size_x + 1) * (_height_map.size_y + 1); _height_map.dim_x = _height_map.size_x + 1; - _height_map.h = calloc(_height_map.total_size, sizeof(*_height_map.h)); + CallocT(&_height_map.h, _height_map.total_size); if (_height_map.h == NULL) return false; /* Iterate through height map initialize values */ @@ -455,7 +455,7 @@ static void HeightMapSineTransform(height_t h_min, height_t h_max) break; } /* Transform it back into h_min..h_max space */ - *h = fheight * (h_max - h_min) + h_min; + *h = (height_t)(fheight * (h_max - h_min) + h_min); if (*h < 0) *h = I2H(0); if (*h >= h_max) *h = h_max - 1; } @@ -472,7 +472,7 @@ static void HeightMapAdjustWaterLevel(amplitude_t water_percent, height_t h_max_ HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg); /* Allocate histogram buffer and clear its cells */ - hist_buf = calloc(h_max - h_min + 1, sizeof(*hist_buf)); + CallocT(&hist_buf, h_max - h_min + 1); /* Fill histogram */ hist = HeightMapMakeHistogram(h_min, h_max, hist_buf); @@ -529,14 +529,14 @@ static void HeightMapCoastLines(void) int smallest_size = min(_patches.map_x, _patches.map_y); const int margin = 4; uint y, x; - uint max_x; - uint max_y; + double max_x; + double max_y; /* Lower to sea level */ for (y = 0; y <= _height_map.size_y; y++) { /* Top right */ max_x = myabs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.9, 53) + 0.25) * 5 + (perlin_coast_noise_2D(y, y, 0.35, 179) + 1) * 12); - max_x = max((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x); + max_x = dmax((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x); if (smallest_size < 8 && max_x > 5) max_x /= 1.5; for (x = 0; x < max_x; x++) { HeightMapXY(x, y) = 0; @@ -544,7 +544,7 @@ static void HeightMapCoastLines(void) /* Bottom left */ max_x = myabs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.85, 101) + 0.3) * 6 + (perlin_coast_noise_2D(y, y, 0.45, 67) + 0.75) * 8); - max_x = max((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x); + max_x = dmax((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x); if (smallest_size < 8 && max_x > 5) max_x /= 1.5; for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) { HeightMapXY(x, y) = 0; @@ -555,7 +555,7 @@ static void HeightMapCoastLines(void) for (x = 0; x <= _height_map.size_x; x++) { /* Top left */ max_y = myabs((perlin_coast_noise_2D(x, _height_map.size_y / 2, 0.9, 167) + 0.4) * 5 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.4, 211) + 0.7) * 9); - max_y = max((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y); + max_y = dmax((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y); if (smallest_size < 8 && max_y > 5) max_y /= 1.5; for (y = 0; y < max_y; y++) { HeightMapXY(x, y) = 0; @@ -564,7 +564,7 @@ static void HeightMapCoastLines(void) /* Bottom right */ max_y = myabs((perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.85, 71) + 0.25) * 6 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.35, 193) + 0.75) * 12); - max_y = max((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y); + max_y = dmax((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y); if (smallest_size < 8 && max_y > 5) max_y /= 1.5; for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) { HeightMapXY(x, y) = 0; diff --git a/src/thread.cpp b/src/thread.cpp index ab2cfd21d..233c4ecb6 100644 --- a/src/thread.cpp +++ b/src/thread.cpp @@ -3,6 +3,7 @@ #include "stdafx.h" #include "thread.h" #include <stdlib.h> +#include "helpers.hpp" #if defined(__AMIGA__) || defined(__MORPHOS__) || defined(NO_THREADS) OTTDThread *OTTDCreateThread(OTTDThreadFunc function, void *arg) { return NULL; } @@ -24,20 +25,21 @@ struct OTTDThread { static void Proxy(void* arg) { - OTTDThread* t = arg; + OTTDThread* t = (OTTDThread*)arg; t->ret = t->func(t->arg); } OTTDThread* OTTDCreateThread(OTTDThreadFunc function, void* arg) { - OTTDThread* t = malloc(sizeof(*t)); + OTTDThread* t; + MallocT(&t, 1); if (t == NULL) return NULL; t->func = function; t->arg = arg; t->thread = _beginthread(Proxy, NULL, 32768, t); - if (t->thread != -1) { + if (t->thread != (TID)-1) { return t; } else { free(t); @@ -72,7 +74,8 @@ struct OTTDThread { OTTDThread* OTTDCreateThread(OTTDThreadFunc function, void* arg) { - OTTDThread* t = malloc(sizeof(*t)); + OTTDThread* t; + MallocT(&t, 1); if (t == NULL) return NULL; @@ -113,14 +116,15 @@ struct OTTDThread { static DWORD WINAPI Proxy(LPVOID arg) { - OTTDThread* t = arg; + OTTDThread* t = (OTTDThread*)arg; t->ret = t->func(t->arg); return 0; } OTTDThread* OTTDCreateThread(OTTDThreadFunc function, void* arg) { - OTTDThread* t = malloc(sizeof(*t)); + OTTDThread* t; + MallocT(&t, 1); DWORD dwThreadId; if (t == NULL) return NULL; diff --git a/src/tile.cpp b/src/tile.cpp index ba6900a36..c9db4516f 100644 --- a/src/tile.cpp +++ b/src/tile.cpp @@ -16,7 +16,7 @@ Slope GetTileSlope(TileIndex tile, uint *h) if (TileX(tile) == MapMaxX() || TileY(tile) == MapMaxY()) { if (h != NULL) *h = 0; - return 0; + return SLOPE_FLAT; } min = a = TileHeight(tile); @@ -35,7 +35,7 @@ Slope GetTileSlope(TileIndex tile, uint *h) if (h != NULL) *h = min * TILE_HEIGHT; - return r; + return (Slope)r; } uint GetTileZ(TileIndex tile) diff --git a/src/tile.h b/src/tile.h index 97123645f..0de85ac5b 100644 --- a/src/tile.h +++ b/src/tile.h @@ -4,6 +4,7 @@ #define TILE_H #include "macros.h" +#include "openttd.h" #include "map.h" #include "slope.h" diff --git a/src/town.h b/src/town.h index d1edca1c8..3cf060f69 100644 --- a/src/town.h +++ b/src/town.h @@ -36,7 +36,7 @@ struct Town { // Player ratings as well as a mask that determines which players have a rating. byte have_ratings; uint8 unwanted[MAX_PLAYERS]; // how many months companies aren't wanted by towns (bribe) - PlayerID exclusivity; // which player has exslusivity + PlayerByte exclusivity; // which player has exslusivity uint8 exclusive_counter; // months till the exclusivity expires int16 ratings[MAX_PLAYERS]; diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index 9c00cf25a..b54c544d5 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -454,7 +454,7 @@ void OnTick_Town(void) static RoadBits GetTownRoadMask(TileIndex tile) { TrackBits b = GetAnyRoadTrackBits(tile); - RoadBits r = 0; + RoadBits r = ROAD_NONE; if (b & TRACK_BIT_X) r |= ROAD_X; if (b & TRACK_BIT_Y) r |= ROAD_Y; @@ -602,13 +602,13 @@ static void GrowTownInTile(TileIndex* tile_ptr, RoadBits mask, int block, Town* // That means that the road is only allowed if there is a house // at any side of the new road. } - rcmd = (1 << a) + (1 << b); + rcmd = (RoadBits)((1 << a) + (1 << b)); } else if (block < 5 && !HASBIT(mask,block^2)) { // Continue building on a partial road. // Always OK. _grow_town_result = 0; - rcmd = 1 << (block ^ 2); + rcmd = (RoadBits)(1 << (block ^ 2)); } else { int i; @@ -649,7 +649,7 @@ static void GrowTownInTile(TileIndex* tile_ptr, RoadBits mask, int block, Town* } _grow_town_result = 0; - rcmd = 1 << i; + rcmd = (RoadBits)(1 << i); } // Return if a water tile @@ -721,7 +721,7 @@ static int GrowTownAtRoad(Town *t, TileIndex tile) // Exclude the source position from the bitmask // and return if no more road blocks available - CLRBIT(mask, (block ^ 2)); + mask = ClrBitT(mask, (block ^ 2)); if (mask == 0) return _grow_town_result; @@ -757,7 +757,7 @@ static RoadBits GenRandomRoadBits(void) uint a = GB(r, 0, 2); uint b = GB(r, 8, 2); if (a == b) b ^= 2; - return (1 << a) + (1 << b); + return (RoadBits)((1 << a) + (1 << b)); } // Grow the town @@ -794,7 +794,7 @@ static bool GrowTown(Town *t) if (GetAnyRoadTrackBits(tile) != 0) { int r = GrowTownAtRoad(t, tile); _current_player = old_player; - return r; + return r != 0; } tile = TILE_ADD(tile, ToTileIndexDiff(*ptr)); } @@ -949,7 +949,7 @@ static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, uint siz t->ratings[i] = 500; t->have_ratings = 0; - t->exclusivity = (byte)-1; + t->exclusivity = INVALID_PLAYER; t->exclusive_counter = 0; t->statues = 0; @@ -1423,7 +1423,7 @@ void ExpandTown(Town *t) _generating_world = false; } -const byte _town_action_costs[8] = { +extern const byte _town_action_costs[8] = { 2, 4, 9, 35, 48, 53, 117, 175 }; @@ -1808,7 +1808,7 @@ void TownsMonthlyLoop(void) if (t->road_build_months != 0) t->road_build_months--; if (t->exclusive_counter != 0) - if (--t->exclusive_counter == 0) t->exclusivity = (byte)-1; + if (--t->exclusive_counter == 0) t->exclusivity = INVALID_PLAYER; UpdateTownGrowRate(t); UpdateTownAmounts(t); @@ -1834,7 +1834,7 @@ void InitializeTowns(void) _town_sort_dirty = true; } -const TileTypeProcs _tile_type_town_procs = { +extern const TileTypeProcs _tile_type_town_procs = { DrawTile_Town, /* draw_tile_proc */ GetSlopeZ_Town, /* get_slope_z_proc */ ClearTile_Town, /* clear_tile_proc */ @@ -1960,6 +1960,6 @@ void AfterLoadTown(void) } -const ChunkHandler _town_chunk_handlers[] = { +extern const ChunkHandler _town_chunk_handlers[] = { { 'CITY', Save_TOWN, Load_TOWN, CH_ARRAY | CH_LAST}, }; diff --git a/src/town_gui.cpp b/src/town_gui.cpp index f580cd324..56084b3b2 100644 --- a/src/town_gui.cpp +++ b/src/town_gui.cpp @@ -16,6 +16,7 @@ #include "player.h" #include "network/network.h" #include "variables.h" +#include "helpers.hpp" static const Widget _town_authority_widgets[] = { { WWT_CLOSEBOX, RESIZE_NONE, 13, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, @@ -409,7 +410,7 @@ static void MakeSortedTownList(void) uint n = 0; /* Create array for sorting */ - _town_sort = realloc((void*)_town_sort, (GetMaxTownIndex() + 1) * sizeof(_town_sort[0])); + ReallocT(&_town_sort, GetMaxTownIndex() + 1); if (_town_sort == NULL) error("Could not allocate memory for the town-sorting-list"); FOR_ALL_TOWNS(t) _town_sort[n++] = t; diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index 074d92ce7..431455ba0 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -171,7 +171,7 @@ void TrainConsistChanged(Vehicle* v) if (u->first == NULL) u->first = v; // update the 'first engine' - u->u.rail.first_engine = (v == u) ? INVALID_ENGINE : first_engine; + u->u.rail.first_engine = (v == u) ? (EngineID)INVALID_ENGINE : first_engine; u->u.rail.railtype = GetEngine(u->engine_type)->railtype; if (IsTrainEngine(u)) first_engine = u->engine_type; @@ -424,6 +424,8 @@ static int GetTrainAcceleration(Vehicle *v, bool mode) case RAILTYPE_MAGLEV: force = power / 25; break; + + default: NOT_REACHED(); } } else { //"kickoff" acceleration @@ -466,7 +468,7 @@ int GetTrainImage(const Vehicle* v, Direction direction) if (HASBIT(v->u.rail.flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction); if (is_custom_sprite(img)) { - base = GetCustomVehicleSprite(v, direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(img)); + base = GetCustomVehicleSprite(v, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(img))); if (base != 0) return base; img = orig_rail_vehicle_info[v->engine_type].image_index; } @@ -501,7 +503,7 @@ void DrawTrainEngine(int x, int y, EngineID engine, uint32 image_ormod) x += 15; image = 0; if (is_custom_sprite(img)) { - image = GetCustomVehicleIcon(engine, 2); + image = GetCustomVehicleIcon(engine, DIR_E); if (image == 0) img = orig_rail_vehicle_info[engine].image_index; } if (image == 0) { @@ -646,7 +648,7 @@ static int32 CmdBuildRailWagon(EngineID engine, TileIndex tile, uint32 flags) v->z_pos = GetSlopeZ(x,y); v->owner = _current_player; v->z_height = 6; - v->u.rail.track = 0x80; + v->u.rail.track = TRACK_BIT_SPECIAL; v->vehstatus = VS_HIDDEN | VS_DEFPAL; v->subtype = 0; @@ -719,7 +721,7 @@ static void AddRearEngineToMultiheadedTrain(Vehicle* v, Vehicle* u, bool buildin u->y_pos = v->y_pos; u->z_pos = v->z_pos; u->z_height = 6; - u->u.rail.track = 0x80; + u->u.rail.track = TRACK_BIT_SPECIAL; u->vehstatus = v->vehstatus & ~VS_STOPPED; u->subtype = 0; SetMultiheaded(u); @@ -807,7 +809,7 @@ int32 CmdBuildRailVehicle(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) v->y_pos = y; v->z_pos = GetSlopeZ(x,y); v->z_height = 6; - v->u.rail.track = 0x80; + v->u.rail.track = TRACK_BIT_SPECIAL; v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL; v->spritenum = rvi->image_index; v->cargo_type = rvi->cargo_type; @@ -903,7 +905,7 @@ int CheckTrainInDepot(const Vehicle *v, bool needs_to_be_stopped) } /* Used to check if the train is inside the depot and verifying that the VS_STOPPED flag is set */ -inline int CheckTrainStoppedInDepot(const Vehicle *v) +int CheckTrainStoppedInDepot(const Vehicle *v) { return CheckTrainInDepot(v, true); } @@ -1593,8 +1595,8 @@ static void ReverseTrainSwapVeh(Vehicle *v, int l, int r) } /* swap variables */ - swap_byte(&a->u.rail.track, &b->u.rail.track); - swap_byte(&a->direction, &b->direction); + SwapT(&a->u.rail.track, &b->u.rail.track); + SwapT(&a->direction, &b->direction); /* toggle direction */ if (!(a->u.rail.track & 0x80)) a->direction = ReverseDir(a->direction); @@ -2110,7 +2112,7 @@ static void HandleLocomotiveSmokeCloud(const Vehicle* v) if (IsTileDepotType(v->tile, TRANSPORT_RAIL) || IsTunnelTile(v->tile)) continue; // No sparks for electric vehicles on nonelectrified tracks - if (!HasPowerOnRail(v->u.rail.railtype, GetTileRailType(v->tile, GetVehicleTrackdir(v)))) continue; + if (!HasPowerOnRail(v->u.rail.railtype, GetTileRailType(v->tile, TrackdirToTrack(GetVehicleTrackdir(v))))) continue; if (effect_type == 0) { // Use default effect type for engine class. @@ -2177,6 +2179,7 @@ static void TrainPlayLeaveStationSound(const Vehicle* v) case RAILTYPE_MONO: SndPlayVehicleFx(SND_47_MAGLEV_2, v); break; case RAILTYPE_MAGLEV: SndPlayVehicleFx(SND_41_MAGLEV, v); break; + default: NOT_REACHED(); } } @@ -2214,8 +2217,8 @@ static bool CheckTrainStayInDepot(Vehicle *v) InvalidateWindowClasses(WC_TRAINS_LIST); TrainPlayLeaveStationSound(v); - v->u.rail.track = 1; - if (v->direction & 2) v->u.rail.track = 2; + v->u.rail.track = TRACK_BIT_X; + if (v->direction & 2) v->u.rail.track = TRACK_BIT_Y; v->vehstatus &= ~VS_HIDDEN; v->cur_speed = 0; @@ -2236,10 +2239,10 @@ typedef struct TrainTrackFollowerData { StationID station_index; // station index we're heading for uint best_bird_dist; uint best_track_dist; - byte best_track; + TrackdirByte best_track; } TrainTrackFollowerData; -static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, int track, uint length) +static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, Trackdir track, uint length) { // heading for nowhere? if (ttfd->dest_coords == 0) return false; @@ -2307,10 +2310,10 @@ static const byte _search_directions[6][4] = { static const byte _pick_track_table[6] = {1, 3, 2, 2, 0, 0}; /* choose a track */ -static byte ChooseTrainTrack(Vehicle* v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirbits) +static Track ChooseTrainTrack(Vehicle* v, TileIndex tile, DiagDirection enterdir, TrackBits tracks) { TrainTrackFollowerData fd; - uint best_track; + Track best_track; // pathfinders are able to tell that route was only 'guessed' bool path_not_found = false; @@ -2318,17 +2321,17 @@ static byte ChooseTrainTrack(Vehicle* v, TileIndex tile, DiagDirection enterdir, TIC() #endif - assert((trackdirbits & ~0x3F) == 0); + assert((tracks & ~0x3F) == 0); /* quick return in case only one possible track is available */ - if (KILL_FIRST_BIT(trackdirbits) == 0) return FIND_FIRST_BIT(trackdirbits); + if (KILL_FIRST_BIT(tracks) == 0) return FindFirstTrack(tracks); if (_patches.yapf.rail_use_yapf) { - Trackdir trackdir = YapfChooseRailTrack(v, tile, enterdir, trackdirbits, &path_not_found); + Trackdir trackdir = YapfChooseRailTrack(v, tile, enterdir, tracks, &path_not_found); if (trackdir != INVALID_TRACKDIR) { best_track = TrackdirToTrack(trackdir); } else { - best_track = FIND_FIRST_BIT(TrackdirBitsToTrackBits(trackdirbits)); + best_track = FindFirstTrack(tracks); } } else if (_patches.new_pathfinding_all) { /* Use a new pathfinding for everything */ void* perf = NpfBeginInterval(); @@ -2349,7 +2352,7 @@ static byte ChooseTrainTrack(Vehicle* v, TileIndex tile, DiagDirection enterdir, /* We are already at our target. Just do something */ //TODO: maybe display error? //TODO: go straight ahead if possible? - best_track = FIND_FIRST_BIT(trackdirbits); + best_track = FindFirstTrack(tracks); } else { /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains the direction we need to take to get there, if ftd.best_bird_dist is not 0, @@ -2371,7 +2374,7 @@ static byte ChooseTrainTrack(Vehicle* v, TileIndex tile, DiagDirection enterdir, /* New train pathfinding */ fd.best_bird_dist = (uint)-1; fd.best_track_dist = (uint)-1; - fd.best_track = 0xFF; + fd.best_track = INVALID_TRACKDIR; NewTrainPathfind(tile - TileOffsByDiagDir(enterdir), v->dest_tile, v->u.rail.compatible_railtypes, enterdir, (NTPEnumProc*)NtpCallbFindStation, &fd); @@ -2381,9 +2384,9 @@ static byte ChooseTrainTrack(Vehicle* v, TileIndex tile, DiagDirection enterdir, if (fd.best_track == 0xff) { // blaha - best_track = FIND_FIRST_BIT(trackdirbits); + best_track = FindFirstTrack(tracks); } else { - best_track = fd.best_track & 7; + best_track = TrackdirToTrack(fd.best_track); } time = NpfEndInterval(perf); @@ -2450,7 +2453,7 @@ static bool CheckReverseTrain(Vehicle *v) } else if (_patches.new_pathfinding_all) { /* Use a new pathfinding for everything */ NPFFindStationOrTileData fstd; NPFFoundTargetData ftd; - byte trackdir, trackdir_rev; + Trackdir trackdir, trackdir_rev; Vehicle* last = GetLastVehicleInChain(v); NPFFillWithOrderData(&fstd, v); @@ -2476,7 +2479,7 @@ static bool CheckReverseTrain(Vehicle *v) fd.best_bird_dist = (uint)-1; fd.best_track_dist = (uint)-1; - NewTrainPathfind(v->tile, v->dest_tile, v->u.rail.compatible_railtypes, reverse ^ i, (NTPEnumProc*)NtpCallbFindStation, &fd); + NewTrainPathfind(v->tile, v->dest_tile, v->u.rail.compatible_railtypes, (DiagDirection)(reverse ^ i), (NTPEnumProc*)NtpCallbFindStation, &fd); if (best_track != -1) { if (best_bird_dist != 0) { @@ -2768,8 +2771,8 @@ static byte AfterSetTrainPos(Vehicle *v, bool new_tile) } static const Direction _new_vehicle_direction_table[11] = { - DIR_N , DIR_NW, DIR_W , 0, - DIR_NE, DIR_N , DIR_SW, 0, + DIR_N , DIR_NW, DIR_W , INVALID_DIR, + DIR_NE, DIR_N , DIR_SW, INVALID_DIR, DIR_E , DIR_SE, DIR_S }; @@ -2885,7 +2888,7 @@ static void AffectSpeedByZChange(Vehicle *v, byte old_z) } static const DiagDirection _otherside_signal_directions[] = { - DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, 0, 0, + DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, INVALID_DIAGDIR, INVALID_DIAGDIR, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE }; @@ -2906,7 +2909,7 @@ typedef struct TrainCollideChecker { static void *FindTrainCollideEnum(Vehicle *v, void *data) { - const TrainCollideChecker* tcc = data; + const TrainCollideChecker* tcc = (TrainCollideChecker*)data; if (v != tcc->v && v != tcc->v_skip && @@ -2968,7 +2971,7 @@ static void CheckTrainCollision(Vehicle *v) tcc.v_skip = v->next; /* find colliding vehicle */ - realcoll = VehicleFromPos(TileVirtXY(v->x_pos, v->y_pos), &tcc, FindTrainCollideEnum); + realcoll = (Vehicle*)VehicleFromPos(TileVirtXY(v->x_pos, v->y_pos), &tcc, FindTrainCollideEnum); if (realcoll == NULL) return; coll = GetFirstVehicleInChain(realcoll); @@ -3005,7 +3008,7 @@ typedef struct VehicleAtSignalData { static void *CheckVehicleAtSignal(Vehicle *v, void *data) { - const VehicleAtSignalData* vasd = data; + const VehicleAtSignalData* vasd = (VehicleAtSignalData*)data; if (v->type == VEH_Train && IsFrontEngine(v) && v->tile == vasd->tile) { DirDiff diff = ChangeDirDiff(DirDifference(v->direction, vasd->direction), DIRDIFF_90RIGHT); @@ -3020,12 +3023,12 @@ static void TrainController(Vehicle *v, bool update_image) Vehicle *prev; GetNewVehiclePosResult gp; uint32 r, tracks,ts; - int i; + Trackdir i; DiagDirection enterdir; Direction dir; Direction newdir; Direction chosen_dir; - byte chosen_track; + TrackBits chosen_track; byte old_z; /* For every vehicle after and including the given vehicle */ @@ -3064,7 +3067,7 @@ static void TrainController(Vehicle *v, bool update_image) } else { /* A new tile is about to be entered. */ - byte bits; + TrackBits bits; /* Determine what direction we're entering the new tile from */ dir = GetNewVehicleDirectionByTile(gp.new_tile, gp.old_tile); enterdir = DirToDiagDir(dir); @@ -3078,14 +3081,14 @@ static void TrainController(Vehicle *v, bool update_image) * Now, the lower byte contains the track status, and the byte at bit 16 contains * the signal status. */ tracks = ts | (ts >> 8); - bits = tracks & 0xFF; + bits = (TrackBits)(tracks & TRACK_BIT_MASK); if ((_patches.new_pathfinding_all || _patches.yapf.rail_use_yapf) && _patches.forbid_90_deg && prev == NULL) { /* We allow wagons to make 90 deg turns, because forbid_90_deg * can be switched on halfway a turn */ - bits &= ~TrackCrossesTracks(FIND_FIRST_BIT(v->u.rail.track)); + bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track)); } - if (bits == 0) { + if (bits == TRACK_BIT_NONE) { //debug("%x == 0", bits); goto invalid_rail; } @@ -3109,7 +3112,7 @@ static void TrainController(Vehicle *v, bool update_image) static byte _matching_tracks[8] = {0x30, 1, 0xC, 2, 0x30, 1, 0xC, 2}; /* The wagon is active, simply follow the prev vehicle. */ - chosen_track = (byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits); + chosen_track = (TrackBits)(byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits); } /* make sure chosen track is a valid track */ @@ -3120,7 +3123,7 @@ static void TrainController(Vehicle *v, bool update_image) const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir]; gp.x = (gp.x & ~0xF) | b[0]; gp.y = (gp.y & ~0xF) | b[1]; - chosen_dir = b[2]; + chosen_dir = (Direction)b[2]; } /* Call the landscape function and tell it that the vehicle entered the tile */ @@ -3140,7 +3143,7 @@ static void TrainController(Vehicle *v, bool update_image) if (!(r&0x4)) { v->tile = gp.new_tile; - if (GetTileRailType(gp.new_tile, chosen_track) != GetTileRailType(gp.old_tile, v->u.rail.track)) { + if (GetTileRailType(gp.new_tile, FindFirstTrack(chosen_track)) != GetTileRailType(gp.old_tile, FindFirstTrack(v->u.rail.track))) { TrainPowerChanged(GetFirstVehicleInChain(v)); } @@ -3201,7 +3204,7 @@ red_light: { /* We're in front of a red signal ?? */ /* find the first set bit in ts. need to do it in 2 steps, since * FIND_FIRST_BIT only handles 6 bits at a time. */ - i = FindFirstBit2x64(ts); + i = FindFirstTrackdir((TrackdirBits)(uint16)ts); if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) { v->cur_speed = 0; @@ -3441,6 +3444,7 @@ static bool TrainCheckIfLineEnds(Vehicle *v) case DIR_SE: x = y; break; case DIR_S : x = x + y - 8; break; case DIR_W : x = ~y + x + 8; break; + default: break; } if (GB(ts, 0, 16) != 0) { diff --git a/src/tree_cmd.cpp b/src/tree_cmd.cpp index 47b9a4a37..eddd9c082 100644 --- a/src/tree_cmd.cpp +++ b/src/tree_cmd.cpp @@ -28,20 +28,20 @@ static TreeType GetRandomTreeType(TileIndex tile, uint seed) { switch (_opt.landscape) { case LT_NORMAL: - return seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE; + return (TreeType)(seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE); case LT_HILLY: - return seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC; + return (TreeType)(seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC); case LT_DESERT: switch (GetTropicZone(tile)) { - case TROPICZONE_INVALID: return seed * TREE_COUNT_SUB_TROPICAL / 256 + TREE_SUB_TROPICAL; - case TROPICZONE_DESERT: return (seed > 12) ? TREE_INVALID : TREE_CACTUS; - default: return seed * TREE_COUNT_RAINFOREST / 256 + TREE_RAINFOREST; + case TROPICZONE_INVALID: return (TreeType)(seed * TREE_COUNT_SUB_TROPICAL / 256 + TREE_SUB_TROPICAL); + case TROPICZONE_DESERT: return (TreeType)((seed > 12) ? TREE_INVALID : TREE_CACTUS); + default: return (TreeType)(seed * TREE_COUNT_RAINFOREST / 256 + TREE_RAINFOREST); } default: - return seed * TREE_COUNT_TOYLAND / 256 + TREE_TOYLAND; + return (TreeType)(seed * TREE_COUNT_TOYLAND / 256 + TREE_TOYLAND); } } @@ -55,10 +55,10 @@ static void PlaceTree(TileIndex tile, uint32 r) // above snowline? if (_opt.landscape == LT_HILLY && GetTileZ(tile) > _opt.snow_line) { SetTreeGroundDensity(tile, TREE_GROUND_SNOW_DESERT, 3); - SetTreeCounter(tile, GB(r, 24, 3)); + SetTreeCounter(tile, (TreeGround)GB(r, 24, 3)); } else { - SetTreeGroundDensity(tile, GB(r, 28, 1), 0); - SetTreeCounter(tile, GB(r, 24, 4)); + SetTreeGroundDensity(tile, (TreeGround)GB(r, 28, 1), 0); + SetTreeCounter(tile, (TreeGround)GB(r, 24, 4)); } } } @@ -116,7 +116,7 @@ void PlaceTreeAtSameHeight(TileIndex tile, uint height) continue; /* Not too much height difference */ - if (myabs(GetTileZ(cur_tile) - height) > 2) continue; + if (delta(GetTileZ(cur_tile), height) > 2) continue; /* Place one tree and quit */ PlaceTree(cur_tile, r); @@ -278,7 +278,7 @@ int32 CmdPlantTree(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM); } - treetype = p1; + treetype = (TreeType)p1; if (treetype == TREE_INVALID) { treetype = GetRandomTreeType(tile, GB(Random(), 24, 8)); if (treetype == TREE_INVALID) treetype = TREE_CACTUS; @@ -408,7 +408,7 @@ static void DrawTile_Trees(TileInfo *ti) static uint GetSlopeZ_Trees(TileIndex tile, uint x, uint y) { uint z; - uint tileh = GetTileSlope(tile, &z); + Slope tileh = GetTileSlope(tile, &z); return z + GetPartialZ(x & 0xF, y & 0xF, tileh); } @@ -654,7 +654,7 @@ void InitializeTrees(void) } -const TileTypeProcs _tile_type_trees_procs = { +extern const TileTypeProcs _tile_type_trees_procs = { DrawTile_Trees, /* draw_tile_proc */ GetSlopeZ_Trees, /* get_slope_z_proc */ ClearTile_Trees, /* clear_tile_proc */ diff --git a/src/tree_map.h b/src/tree_map.h index 326504659..47da5eb25 100644 --- a/src/tree_map.h +++ b/src/tree_map.h @@ -35,14 +35,14 @@ typedef enum TreeGround { static inline TreeType GetTreeType(TileIndex t) { assert(IsTileType(t, MP_TREES)); - return _m[t].m3; + return (TreeType)_m[t].m3; } static inline TreeGround GetTreeGround(TileIndex t) { assert(IsTileType(t, MP_TREES)); - return GB(_m[t].m2, 4, 2); + return (TreeGround)GB(_m[t].m2, 4, 2); } diff --git a/src/tunnelbridge_cmd.cpp b/src/tunnelbridge_cmd.cpp index ea2aaf730..b1cf8a563 100644 --- a/src/tunnelbridge_cmd.cpp +++ b/src/tunnelbridge_cmd.cpp @@ -202,11 +202,11 @@ int32 CmdBuildBridge(TileIndex end_tile, uint32 flags, uint32 p1, uint32 p2) // type of bridge if (HASBIT(p2, 15)) { - railtype = 0; + railtype = RAILTYPE_BEGIN; // ?? transport = TRANSPORT_ROAD; } else { if (!ValParamRailtype(GB(p2, 8, 8))) return CMD_ERROR; - railtype = GB(p2, 8, 8); + railtype = (RailType)GB(p2, 8, 8); transport = TRANSPORT_RAIL; } @@ -469,8 +469,8 @@ int32 CmdBuildTunnel(TileIndex start_tile, uint32 flags, uint32 p1, uint32 p2) if (flags & DC_EXEC) { if (GB(p1, 9, 1) == TRANSPORT_RAIL) { - MakeRailTunnel(start_tile, _current_player, direction, GB(p1, 0, 4)); - MakeRailTunnel(end_tile, _current_player, ReverseDiagDir(direction), GB(p1, 0, 4)); + MakeRailTunnel(start_tile, _current_player, direction, (RailType)GB(p1, 0, 4)); + MakeRailTunnel(end_tile, _current_player, ReverseDiagDir(direction), (RailType)GB(p1, 0, 4)); UpdateSignalsOnSegment(start_tile, direction); YapfNotifyTrackLayoutChange(start_tile, AxisToTrack(DiagDirToAxis(direction))); } else { @@ -1030,7 +1030,7 @@ static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y) } else if (f < 15) { return z + TILE_HEIGHT; } - tileh = _inclined_tileh[f - 15]; + tileh = (Slope)_inclined_tileh[f - 15]; } } } @@ -1050,7 +1050,7 @@ static Slope GetSlopeTileh_TunnelBridge(TileIndex tile, Slope tileh) if (f == 0) return tileh; if (f < 15) return SLOPE_FLAT; - return _inclined_tileh[f - 15]; + return (Slope)_inclined_tileh[f - 15]; } } } @@ -1206,7 +1206,7 @@ static uint32 VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y } if (fc == _tunnel_fractcoord_2[dir]) { v->tile = tile; - v->u.rail.track = 0x40; + v->u.rail.track = TRACK_BIT_WORMHOLE; v->vehstatus |= VS_HIDDEN; return 4; } @@ -1215,7 +1215,7 @@ static uint32 VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y if (dir == ReverseDiagDir(vdir) && fc == _tunnel_fractcoord_3[dir] && z == 0) { /* We're at the tunnel exit ?? */ v->tile = tile; - v->u.rail.track = _exit_tunnel_track[dir]; + v->u.rail.track = (TrackBits)_exit_tunnel_track[dir]; assert(v->u.rail.track); v->vehstatus &= ~VS_HIDDEN; return 4; @@ -1272,7 +1272,7 @@ static uint32 VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y case DIAGDIR_NW: if ((y & 0xF) != 0) return 0; break; } if (v->type == VEH_Train) { - v->u.rail.track = 0x40; + v->u.rail.track = TRACK_BIT_WORMHOLE; CLRBIT(v->u.rail.flags, VRF_GOINGUP); CLRBIT(v->u.rail.flags, VRF_GOINGDOWN); } else { @@ -1283,7 +1283,7 @@ static uint32 VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y v->tile = tile; if (v->type == VEH_Train) { if (v->u.rail.track == 0x40) { - v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? 1 : 2); + v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y); return 4; } } else { @@ -1299,7 +1299,7 @@ static uint32 VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y return 0; } -const TileTypeProcs _tile_type_tunnelbridge_procs = { +extern const TileTypeProcs _tile_type_tunnelbridge_procs = { DrawTile_TunnelBridge, /* draw_tile_proc */ GetSlopeZ_TunnelBridge, /* get_slope_z_proc */ ClearTile_TunnelBridge, /* clear_tile_proc */ diff --git a/src/unix.cpp b/src/unix.cpp index 4af6372b1..ba15b8701 100644 --- a/src/unix.cpp +++ b/src/unix.cpp @@ -127,9 +127,9 @@ void ShowOSErrorBox(const char *buf) } #ifdef WITH_COCOA -void cocoaSetWorkingDirectory(void); -void cocoaSetupAutoreleasePool(void); -void cocoaReleaseAutoreleasePool(void); +extern "C" void cocoaSetWorkingDirectory(void); +extern "C" void cocoaSetupAutoreleasePool(void); +extern "C" void cocoaReleaseAutoreleasePool(void); #endif int CDECL main(int argc, char* argv[]) @@ -169,10 +169,10 @@ void DeterminePaths(void) { char *s; - _paths.game_data_dir = malloc(MAX_PATH); + MallocT(&_paths.game_data_dir, MAX_PATH); ttd_strlcpy(_paths.game_data_dir, GAME_DATA_DIR, MAX_PATH); #if defined SECOND_DATA_DIR - _paths.second_data_dir = malloc(MAX_PATH); + MallocT(&_paths.second_data_dir, MAX_PATH); ttd_strlcpy(_paths.second_data_dir, SECOND_DATA_DIR, MAX_PATH); #endif @@ -190,7 +190,7 @@ void DeterminePaths(void) #else /* not defined(USE_HOMEDIR) */ - _paths.personal_dir = malloc(MAX_PATH); + MallocT(&_paths.personal_dir, MAX_PATH); ttd_strlcpy(_paths.personal_dir, PERSONAL_DIR, MAX_PATH); // check if absolute or relative path @@ -226,7 +226,7 @@ void DeterminePaths(void) #if defined CUSTOM_LANG_DIR // sets the search path for lng files to the custom one - _paths.lang_dir = malloc( MAX_PATH ); + MallocT(&_paths.lang_dir, MAX_PATH ); ttd_strlcpy( _paths.lang_dir, CUSTOM_LANG_DIR, MAX_PATH); #else _paths.lang_dir = str_fmt("%slang/", _paths.game_data_dir); diff --git a/src/unmovable_cmd.cpp b/src/unmovable_cmd.cpp index 5c1666c22..58ff9291f 100644 --- a/src/unmovable_cmd.cpp +++ b/src/unmovable_cmd.cpp @@ -74,7 +74,7 @@ void UpdateCompanyHQ(Player *p, uint score) * @param p1 unused * @param p2 unused */ -extern int32 CheckFlatLandBelow(TileIndex tile, uint w, uint h, uint flags, uint invalid_dirs, int *); +extern int32 CheckFlatLandBelow(TileIndex tile, uint w, uint h, uint flags, uint invalid_dirs, StationID* station); int32 CmdBuildCompanyHQ(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) { Player *p = GetPlayer(_current_player); @@ -183,7 +183,7 @@ static uint GetSlopeZ_Unmovable(TileIndex tile, uint x, uint y) { if (IsOwnedLand(tile)) { uint z; - uint tileh = GetTileSlope(tile, &z); + Slope tileh = GetTileSlope(tile, &z); return z + GetPartialZ(x & 0xF, y & 0xF, tileh); } else { @@ -397,7 +397,7 @@ static void ChangeTileOwner_Unmovable(TileIndex tile, PlayerID old_player, Playe } } -const TileTypeProcs _tile_type_unmovable_procs = { +extern const TileTypeProcs _tile_type_unmovable_procs = { DrawTile_Unmovable, /* draw_tile_proc */ GetSlopeZ_Unmovable, /* get_slope_z_proc */ ClearTile_Unmovable, /* clear_tile_proc */ diff --git a/src/unmovable_map.h b/src/unmovable_map.h index d016a7ac1..2e9ecfb9d 100644 --- a/src/unmovable_map.h +++ b/src/unmovable_map.h @@ -26,7 +26,7 @@ typedef enum UnmovableType { static inline UnmovableType GetUnmovableType(TileIndex t) { assert(IsTileType(t, MP_UNMOVABLE)); - return _m[t].m5; + return (UnmovableType)_m[t].m5; } diff --git a/src/variables.h b/src/variables.h index bbbe0b79b..63e229a09 100644 --- a/src/variables.h +++ b/src/variables.h @@ -276,23 +276,15 @@ VARDEF bool _do_autosave; VARDEF int _autosave_ctr; VARDEF byte _display_opt; -VARDEF byte _pause; VARDEF int _caret_timer; VARDEF uint32 _news_display_opt; VARDEF bool _news_ticker_sound; -VARDEF byte _game_mode; VARDEF StringID _error_message; VARDEF int32 _additional_cash_required; VARDEF uint32 _decode_parameters[20]; -VARDEF bool _ctrl_pressed; // Is Ctrl pressed? -VARDEF bool _shift_pressed; // Is Shift pressed? -VARDEF byte _dirkeys; // 1 = left, 2 = up, 4 = right, 8 = down - -VARDEF bool _fullscreen; -VARDEF bool _fast_forward; VARDEF bool _rightclick_emulate; // IN/OUT parameters to commands @@ -311,7 +303,6 @@ typedef struct { // Used when switching from the intro menu. VARDEF byte _switch_mode; VARDEF StringID _switch_mode_errorstr; -VARDEF bool _exit_game; VARDEF SmallFiosItem _file_to_saveload; @@ -406,7 +397,7 @@ StringID BindCString(const char *str); /* landscape.c */ extern const byte _tileh_to_sprite[32]; -extern const byte _inclined_tileh[16]; +extern const Slope _inclined_tileh[16]; extern const TileTypeProcs * const _tile_type_procs[16]; diff --git a/src/vehicle.cpp b/src/vehicle.cpp index c7b5365e4..8a0b47588 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -35,6 +35,7 @@ #include "date.h" #include "newgrf_engine.h" #include "newgrf_sound.h" +#include "helpers.hpp" #define INVALID_COORD (-0x8000) #define GEN_HASH(x, y) ((GB((y), 6, 6) << 6) + GB((x), 7, 6)) @@ -145,7 +146,7 @@ bool EnsureNoVehicle(TileIndex tile) static void *EnsureNoVehicleProcZ(Vehicle *v, void *data) { - const TileInfo *ti = data; + const TileInfo *ti = (const TileInfo*)data; if (v->tile != ti->tile || v->type == VEH_Disaster) return NULL; if (v->z_pos > ti->z) return NULL; @@ -171,7 +172,7 @@ Vehicle *FindVehicleOnTileZ(TileIndex tile, byte z) ti.tile = tile; ti.z = z; - return VehicleFromPos(tile, &ti, EnsureNoVehicleProcZ); + return (Vehicle*)VehicleFromPos(tile, &ti, EnsureNoVehicleProcZ); } Vehicle *FindVehicleBetween(TileIndex from, TileIndex to, byte z) @@ -643,7 +644,7 @@ void CallVehicleTicks(void) // hotfix for desync problem: // for MP games invalidate the YAPF cache every tick to keep it exactly the same on the server and all clients if (_networking) { - YapfNotifyTrackLayoutChange(0, 0); + YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK); } #endif //ENABLE_NETWORK @@ -1959,7 +1960,7 @@ static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type) if (v->cargo_type == new_cargo_type || CanRefitTo(engine_type, v->cargo_type)) { if (VerifyAutoreplaceRefitForOrders(v, engine_type)) { - return v->cargo_type == new_cargo_type ? CT_NO_REFIT : v->cargo_type; + return v->cargo_type == new_cargo_type ? (CargoID)CT_NO_REFIT : v->cargo_type; } else { return CT_INVALID; } @@ -2258,7 +2259,7 @@ static int32 MaybeReplaceVehicle(Vehicle *v, bool check, bool display_costs) static inline void ExtendVehicleListSize(const Vehicle ***engine_list, uint16 *engine_list_length, uint16 step_size) { *engine_list_length = min(*engine_list_length + step_size, GetMaxVehicleIndex() + 1); - *engine_list = realloc((void*)*engine_list, (*engine_list_length) * sizeof((*engine_list)[0])); + ReallocT((Vehicle ***)/* NO & */engine_list, *engine_list_length); } /** Generates a list of vehicles inside a depot @@ -2435,7 +2436,7 @@ uint GenerateVehicleSortList(const Vehicle ***sort_list, uint16 *length_of_array * We will still make it have room for 50 extra vehicles to prevent having * to move the whole array if just one vehicle is added later */ *length_of_array = n + 50; - *sort_list = realloc((void*)*sort_list, (*length_of_array) * sizeof((*sort_list)[0])); + ReallocT((Vehicle***)/* NO & */sort_list, (*length_of_array) * sizeof((*sort_list)[0])); } return n; @@ -2460,7 +2461,7 @@ int32 SendAllVehiclesToDepot(byte type, uint32 flags, bool service, PlayerID own /* Send all the vehicles to a depot */ for (i = 0; i < n; i++) { const Vehicle *v = sort_list[i]; - int32 ret = DoCommand(v->tile, v->index, service | DEPOT_DONT_CANCEL, flags, CMD_SEND_TO_DEPOT(type)); + int32 ret = DoCommand(v->tile, v->index, (service ? 1 : 0) | DEPOT_DONT_CANCEL, flags, CMD_SEND_TO_DEPOT(type)); /* Return 0 if DC_EXEC is not set this is a valid goto depot command) * In this case we know that at least one vehicle can be sent to a depot @@ -2505,7 +2506,7 @@ void VehicleEnterDepot(Vehicle *v) case VEH_Ship: InvalidateWindowClasses(WC_SHIPS_LIST); - v->u.ship.state = 0x80; + v->u.ship.state = TRACK_BIT_SPECIAL; RecalcShipStuff(v); break; @@ -2709,7 +2710,7 @@ Direction GetDirectionTowards(const Vehicle* v, int x, int y) Trackdir GetVehicleTrackdir(const Vehicle* v) { - if (v->vehstatus & VS_CRASHED) return 0xFF; + if (v->vehstatus & VS_CRASHED) return INVALID_TRACKDIR; switch (v->type) { case VEH_Train: @@ -2719,14 +2720,14 @@ Trackdir GetVehicleTrackdir(const Vehicle* v) if (v->u.rail.track == 0x40) /* train in tunnel, so just use his direction and assume a diagonal track */ return DiagdirToDiagTrackdir(DirToDiagDir(v->direction)); - return TrackDirectionToTrackdir(FIND_FIRST_BIT(v->u.rail.track),v->direction); + return TrackDirectionToTrackdir(FindFirstTrack(v->u.rail.track), v->direction); case VEH_Ship: if (IsShipInDepot(v)) /* We'll assume the ship is facing outwards */ return DiagdirToDiagTrackdir(GetShipDepotDirection(v->tile)); - return TrackDirectionToTrackdir(FIND_FIRST_BIT(v->u.ship.state),v->direction); + return TrackDirectionToTrackdir(FindFirstTrack(v->u.ship.state), v->direction); case VEH_Road: if (IsRoadVehInDepot(v)) /* We'll assume the road vehicle is facing outwards */ @@ -2736,13 +2737,13 @@ Trackdir GetVehicleTrackdir(const Vehicle* v) return DiagdirToDiagTrackdir(GetRoadStopDir(v->tile)); /* Road vehicle in a station */ /* If vehicle's state is a valid track direction (vehicle is not turning around) return it */ - if ((v->u.road.state & 7) < 6) return v->u.road.state; + if ((v->u.road.state & 7) < 6) return (Trackdir)v->u.road.state; /* Vehicle is turning around, get the direction from vehicle's direction */ return DiagdirToDiagTrackdir(DirToDiagDir(v->direction)); /* case VEH_Aircraft: case VEH_Special: case VEH_Disaster: */ - default: return 0xFF; + default: return INVALID_TRACKDIR; } } /* Return value has bit 0x2 set, when the vehicle enters a station. Then, @@ -2780,7 +2781,7 @@ UnitID GetFreeUnitNumber(byte type) if (max > gmax) { gmax = max; free(cache); - cache = malloc((max + 1) * sizeof(*cache)); + MallocT(&cache, max + 1); } // Clear the cache @@ -2908,7 +2909,7 @@ PalSpriteID GetVehiclePalette(const Vehicle *v) } // Save and load of vehicles -const SaveLoad _common_veh_desc[] = { +extern const SaveLoad _common_veh_desc[] = { SLE_VAR(Vehicle, subtype, SLE_UINT8), SLE_REF(Vehicle, next, REF_VEHICLE_OLD), @@ -3174,7 +3175,7 @@ static void Save_VEHS(void) // Write the vehicles FOR_ALL_VEHICLES(v) { SlSetArrayIndex(v->index); - SlObject(v, _veh_descs[v->type - 0x10]); + SlObject(v, (SaveLoad*)_veh_descs[v->type - 0x10]); } } @@ -3191,7 +3192,7 @@ static void Load_VEHS(void) error("Vehicles: failed loading savegame: too many vehicles"); v = GetVehicle(index); - SlObject(v, _veh_descs[SlReadByte()]); + SlObject(v, (SaveLoad*)_veh_descs[SlReadByte()]); /* Old savegames used 'last_station_visited = 0xFF' */ if (CheckSavegameVersion(5) && v->last_station_visited == 0xFF) @@ -3201,7 +3202,7 @@ static void Load_VEHS(void) /* Convert the current_order.type (which is a mix of type and flags, because * in those versions, they both were 4 bits big) to type and flags */ v->current_order.flags = (v->current_order.type & 0xF0) >> 4; - v->current_order.type = v->current_order.type & 0x0F; + v->current_order.type.m_val &= 0x0F; } } @@ -3223,6 +3224,6 @@ static void Load_VEHS(void) } } -const ChunkHandler _veh_chunk_handlers[] = { +extern const ChunkHandler _veh_chunk_handlers[] = { { 'VEHS', Save_VEHS, Load_VEHS, CH_SPARSE_ARRAY | CH_LAST}, }; diff --git a/src/vehicle.h b/src/vehicle.h index 612807f48..6c16c9921 100644 --- a/src/vehicle.h +++ b/src/vehicle.h @@ -76,9 +76,9 @@ typedef struct VehicleRail { // 0xffff == not in train EngineID first_engine; - byte track; + TrackBitsByte track; byte force_proceed; - byte railtype; + RailTypeByte railtype; RailTypeMask compatible_railtypes; byte flags; @@ -138,7 +138,7 @@ typedef struct VehicleDisaster { } VehicleDisaster; typedef struct VehicleShip { - byte state; + TrackBitsByte state; } VehicleShip; @@ -155,7 +155,7 @@ struct Vehicle { StringID string_id; // Displayed string UnitID unitnumber; // unit number, for display purposes only - PlayerID owner; // which player owns the vehicle? + PlayerByte owner; // which player owns the vehicle? TileIndex tile; // Current tile index TileIndex dest_tile; // Heading for this tile @@ -163,7 +163,7 @@ struct Vehicle { int32 x_pos; // coordinates int32 y_pos; byte z_pos; - byte direction; // facing + DirectionByte direction; // facing byte spritenum; // currently displayed sprite index // 0xfd == custom sprite, 0xfe == custom second head sprite @@ -455,9 +455,7 @@ static inline Vehicle *GetFirstVehicleFromSharedList(const Vehicle *v) VARDEF VehicleID _new_vehicle_id; VARDEF uint16 _returned_refit_capacity; -enum { - INVALID_VEHICLE = 0xFFFF, -}; +static const VehicleID INVALID_VEHICLE = 0xFFFF; /** * Get the colour map for an engine. This used for unbuilt engines in the user interface. diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp index 1c3d45b82..55dd412ec 100644 --- a/src/vehicle_gui.cpp +++ b/src/vehicle_gui.cpp @@ -27,6 +27,7 @@ #include "aircraft.h" #include "roadveh.h" #include "depot.h" +#include "helpers.hpp" typedef struct Sorting { Listing aircraft; @@ -153,7 +154,7 @@ static void SortVehicleList(vehiclelist_d *vl) { if (!(vl->l.flags & VL_RESORT)) return; - _internal_sort_order = vl->l.flags & VL_DESC; + _internal_sort_order = (vl->l.flags & VL_DESC) != 0; qsort((void*)vl->sort_list, vl->l.list_length, sizeof(vl->sort_list[0]), _vehicle_sorter[vl->l.sort_type]); @@ -206,8 +207,10 @@ typedef struct RefitList { static RefitList *BuildRefitList(const Vehicle *v) { uint max_lines = 256; - RefitOption *refit = calloc(max_lines, sizeof(*refit)); - RefitList *list = calloc(1, sizeof(*list)); + RefitOption *refit; + CallocT(&refit, max_lines); + RefitList *list; + CallocT(&list, 1); Vehicle *u = (Vehicle*)v; uint num_lines = 0; uint i; @@ -855,12 +858,12 @@ static void SetupScrollStuffForReplaceWindow(Window *w) if (selected_id[0] != INVALID_ENGINE) { const ShipVehicleInfo* svi = ShipVehInfo(selected_id[0]); CargoID cargo = svi->cargo_type; - byte refittable = svi->refittable; + bool refittable = svi->refittable; for (i = SHIP_ENGINES_INDEX; i < SHIP_ENGINES_INDEX + NUM_SHIP_ENGINES; i++) { if (HASBIT(GetEngine(i)->player_avail, _local_player) && ( ShipVehInfo(i)->cargo_type == cargo || - ShipVehInfo(i)->refittable & refittable + ShipVehInfo(i)->refittable && refittable )) { if (sel[1] == count2) selected_id[1] = i; count2++; @@ -1205,7 +1208,7 @@ static void ReplaceVehicleWndProc(Window *w, WindowEvent *e) } case WE_DROPDOWN_SELECT: /* we have selected a dropdown item in the list */ - _railtype_selected_in_replace_gui = e->we.dropdown.index; + _railtype_selected_in_replace_gui = (RailType)e->we.dropdown.index; /* Reset scrollbar positions */ w->vscroll.pos = 0; w->vscroll2.pos = 0; @@ -1437,7 +1440,7 @@ static void CreateVehicleListWindow(Window *w) { vehiclelist_d *vl = &WP(w, vehiclelist_d); uint16 window_type = w->window_number & VLW_MASK; - PlayerID player = GB(w->window_number, 0, 8); + PlayerID player = (PlayerID)GB(w->window_number, 0, 8); vl->vehicle_type = GB(w->window_number, 11, 5); vl->length_of_sort_list = 0; @@ -1550,7 +1553,7 @@ static void CreateVehicleListWindow(Window *w) default: NOT_REACHED(); break; } - vl->l.flags = VL_REBUILD | (vl->_sorting->order << (VL_DESC - 1)); + vl->l.flags = VL_REBUILD | (vl->_sorting->order ? VL_DESC : VL_NONE); vl->l.sort_type = vl->_sorting->criteria; vl->sort_list = NULL; vl->l.resort_timer = DAY_TICKS * PERIODIC_RESORT_DAYS; // Set up resort timer diff --git a/src/video/cocoa_v.h b/src/video/cocoa_v.h index 93d7b2639..c3f533467 100644 --- a/src/video/cocoa_v.h +++ b/src/video/cocoa_v.h @@ -5,6 +5,14 @@ #include "../hal.h" +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + extern const HalVideoDriver _cocoa_video_driver; +#ifdef __cplusplus +} // extern "C" +#endif //__cplusplus + #endif diff --git a/src/video/cocoa_v.m b/src/video/cocoa_v.m index 46518445b..79551c865 100644 --- a/src/video/cocoa_v.m +++ b/src/video/cocoa_v.m @@ -46,18 +46,11 @@ extern void HideMenuBar(void); # endif #endif + #include "../stdafx.h" -#include "../openttd.h" #include "../debug.h" -#include "../functions.h" -#include "../gfx.h" #include "../macros.h" -#include "../sdl.h" -#include "../window.h" -#include "../network/network.h" -#include "../variables.h" #include "../os/macosx/splash.h" - #include "cocoa_v.h" #include "cocoa_keys.h" @@ -65,6 +58,7 @@ extern void HideMenuBar(void); #undef Rect + /* Subclass of NSWindow to fix genie effect and support resize events */ @interface OTTD_QuartzWindow : NSWindow - (void)miniaturize:(id)sender; @@ -162,7 +156,7 @@ static struct CocoaVideoData { NSQuickDrawView *qdview; #define MAX_DIRTY_RECTS 100 - OTTDRect dirty_rects[MAX_DIRTY_RECTS]; + Rect dirty_rects[MAX_DIRTY_RECTS]; int num_dirty_rects; uint16 palette16[256]; diff --git a/src/video/dedicated_v.cpp b/src/video/dedicated_v.cpp index 764df3afd..043414945 100644 --- a/src/video/dedicated_v.cpp +++ b/src/video/dedicated_v.cpp @@ -277,7 +277,7 @@ static void DedicatedVideoMainLoop(void) next_tick = cur_ticks + 30; GameLoop(); - _screen.dst_ptr = _dedicated_video_mem; + _screen.dst_ptr = (Pixel*)_dedicated_video_mem; UpdateWindows(); } CSleep(1); diff --git a/src/video/null_v.cpp b/src/video/null_v.cpp index ecdd3486c..8916dadbc 100644 --- a/src/video/null_v.cpp +++ b/src/video/null_v.cpp @@ -27,7 +27,7 @@ static void NullVideoMainLoop(void) for (i = 0; i < 1000; i++) { GameLoop(); - _screen.dst_ptr = _null_video_mem; + _screen.dst_ptr = (Pixel*)_null_video_mem; UpdateWindows(); } } diff --git a/src/video/sdl_v.cpp b/src/video/sdl_v.cpp index 3e776d29f..1f9910565 100644 --- a/src/video/sdl_v.cpp +++ b/src/video/sdl_v.cpp @@ -469,7 +469,7 @@ static void SdlVideoMainLoop(void) (keys[SDLK_DOWN] ? 8 : 0); GameLoop(); - _screen.dst_ptr = _sdl_screen->pixels; + _screen.dst_ptr = (Pixel*)_sdl_screen->pixels; UpdateWindows(); if (++pal_tick > 4) { CheckPaletteAnim(); @@ -478,7 +478,7 @@ static void SdlVideoMainLoop(void) DrawSurfaceToScreen(); } else { SDL_CALL SDL_Delay(1); - _screen.dst_ptr = _sdl_screen->pixels; + _screen.dst_ptr = (Pixel*)_sdl_screen->pixels; DrawTextMessage(); DrawMouseCursor(); DrawSurfaceToScreen(); diff --git a/src/video/win32_v.cpp b/src/video/win32_v.cpp index eab832ae5..28e5f5e62 100644 --- a/src/video/win32_v.cpp +++ b/src/video/win32_v.cpp @@ -42,7 +42,7 @@ static void MakePalette(void) LOGPALETTE *pal; uint i; - pal = alloca(sizeof(LOGPALETTE) + (256-1) * sizeof(PALETTEENTRY)); + pal = (LOGPALETTE*)alloca(sizeof(LOGPALETTE) + (256-1) * sizeof(PALETTEENTRY)); pal->palVersion = 0x300; pal->palNumEntries = 256; @@ -169,7 +169,7 @@ int RedrawScreenDebug(void) dc = GetDC(_wnd.main_wnd); dc2 = CreateCompatibleDC(dc); - old_bmp = SelectObject(dc2, _wnd.dib_sect); + old_bmp = (HBITMAP)SelectObject(dc2, _wnd.dib_sect); old_palette = SelectPalette(dc, _wnd.gdi_palette, FALSE); BitBlt(dc, 0, 0, _wnd.width, _wnd.height, dc2, 0, 0, SRCCOPY); SelectPalette(dc, old_palette, TRUE); @@ -222,7 +222,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP BeginPaint(hwnd, &ps); dc = ps.hdc; dc2 = CreateCompatibleDC(dc); - old_bmp = SelectObject(dc2, _wnd.dib_sect); + old_bmp = (HBITMAP)SelectObject(dc2, _wnd.dib_sect); old_palette = SelectPalette(dc, _wnd.gdi_palette, FALSE); if (_pal_last_dirty != -1) { @@ -358,7 +358,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP GetKeyboardState(ks); if (ToUnicode(wParam, 0, ks, &w, 1, 0) != 1) { /* On win9x ToUnicode always fails, so fall back to ToAscii */ - if (ToAscii(wParam, 0, ks, &w, 0) != 1) w = 0; // no translation was possible + if (ToAscii(wParam, 0, ks, (LPWORD)&w, 0) != 1) w = 0; // no translation was possible } pressed_key = w | MapWindowsKey(wParam) << 16; @@ -496,7 +496,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP } case WM_ACTIVATEAPP: - _wnd.has_focus = (bool)wParam; + _wnd.has_focus = (wParam != 0); break; } return DefWindowProc(hwnd, msg, wParam, lParam); @@ -622,13 +622,13 @@ static bool AllocateDibSection(int w, int h) _wnd.alloced_bits = NULL; } - bi = alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256); + bi = (BITMAPINFO*)alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256); memset(bi, 0, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256); bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); if (_wnd.double_size) { w = ALIGN(w, 4); - _wnd.alloced_bits = _wnd.buffer_bits = malloc(w * h); + _wnd.alloced_bits = _wnd.buffer_bits = (Pixel*)malloc(w * h); w *= 2; h *= 2; } diff --git a/src/viewport.cpp b/src/viewport.cpp index 7199edbd9..10670c361 100644 --- a/src/viewport.cpp +++ b/src/viewport.cpp @@ -680,9 +680,7 @@ static void DrawTileSelection(const TileInfo *ti) side = 0; } else { TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y); - int diffx = myabs(TileX(start) - TileX(ti->tile)); - int diffy = myabs(TileY(start) - TileY(ti->tile)); - side = myabs(diffx - diffy); + side = delta(delta(TileX(start), TileX(ti->tile)), delta(TileY(start), TileY(ti->tile))); } image = SPR_AUTORAIL_BASE + _AutorailTilehSprite[ti->tileh][_AutorailType[dir][side]]; @@ -838,7 +836,7 @@ static void AddStation(const Station *st, StringID str, uint16 width) { StringSpriteToDraw *sstd; - sstd = AddStringToDraw(st->sign.left + 1, st->sign.top + 1, str, st->index, st->facilities); + sstd = (StringSpriteToDraw*)AddStringToDraw(st->sign.left + 1, st->sign.top + 1, str, st->index, st->facilities); if (sstd != NULL) { sstd->color = (st->owner == OWNER_NONE || st->facilities == 0) ? 0xE : _player_colors[st->owner]; sstd->width = width; @@ -905,7 +903,7 @@ static void AddSign(const Sign *si, StringID str, uint16 width) { StringSpriteToDraw *sstd; - sstd = AddStringToDraw(si->sign.left + 1, si->sign.top + 1, str, si->str, 0); + sstd = (StringSpriteToDraw*)AddStringToDraw(si->sign.left + 1, si->sign.top + 1, str, si->str, 0); if (sstd != NULL) { sstd->color = (si->owner == OWNER_NONE) ? 14 : _player_colors[si->owner]; sstd->width = width; @@ -972,7 +970,7 @@ static void AddWaypoint(const Waypoint *wp, StringID str, uint16 width) { StringSpriteToDraw *sstd; - sstd = AddStringToDraw(wp->sign.left + 1, wp->sign.top + 1, str, wp->index, 0); + sstd = (StringSpriteToDraw*)AddStringToDraw(wp->sign.left + 1, wp->sign.top + 1, str, wp->index, 0); if (sstd != NULL) { sstd->color = (wp->deleted ? 0xE : 11); sstd->width = width; @@ -1175,7 +1173,7 @@ static void ViewportDrawStrings(DrawPixelInfo *dpi, const StringSpriteToDraw *ss if (!(_display_opt & DO_TRANS_SIGNS) || ss->string == STR_2806) DrawFrameRect( x, y, x + w, bottom, ss->color, - (_display_opt & DO_TRANS_BUILDINGS) ? FR_TRANSPARENT : 0 + (_display_opt & DO_TRANS_BUILDINGS) ? FR_TRANSPARENT : FR_NONE ); } @@ -2318,8 +2316,8 @@ calc_heightdiff_single_direction:; int limit = (_thd.sizelimit - 1) * TILE_SIZE; x = sx + clamp(x - sx, -limit, limit); y = sy + clamp(y - sy, -limit, limit); - /* Fallthrough */ - case VPM_X_AND_Y: /* drag an X by Y area */ + } /* Fallthrough */ + case VPM_X_AND_Y: { /* drag an X by Y area */ if (_patches.measure_tooltip) { static const StringID measure_strings_area[] = { STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF @@ -2327,8 +2325,8 @@ calc_heightdiff_single_direction:; TileIndex t0 = TileVirtXY(sx, sy); TileIndex t1 = TileVirtXY(x, y); - uint dx = abs(TileX(t0) - TileX(t1)) + 1; - uint dy = abs(TileY(t0) - TileY(t1)) + 1; + uint dx = delta(TileX(t0), TileX(t1)) + 1; + uint dy = delta(TileY(t0), TileY(t1)) + 1; byte index = 0; uint params[3]; diff --git a/src/viewport.h b/src/viewport.h index b9d1fce7e..13f9538dd 100644 --- a/src/viewport.h +++ b/src/viewport.h @@ -139,7 +139,7 @@ typedef struct TileHighlightData { // common button handler -bool HandlePlacePushButton(Window *w, int widget, uint32 cursor, int mode, PlaceProc *placeproc); +bool HandlePlacePushButton(Window *w, int widget, CursorID cursor, int mode, PlaceProc *placeproc); VARDEF Point _tile_fract_coords; diff --git a/src/water_cmd.cpp b/src/water_cmd.cpp index 10051e877..78787b20b 100644 --- a/src/water_cmd.cpp +++ b/src/water_cmd.cpp @@ -83,8 +83,8 @@ int32 CmdBuildShipDepot(TileIndex tile, uint32 flags, uint32 p1, uint32 p2) depot->xy = tile; depot->town_index = ClosestTownFromTile(tile, (uint)-1)->index; - MakeShipDepot(tile,_current_player, DEPOT_NORTH, p1); - MakeShipDepot(tile2,_current_player, DEPOT_SOUTH, p1); + MakeShipDepot(tile, _current_player, DEPOT_NORTH, (Axis)p1); + MakeShipDepot(tile2, _current_player, DEPOT_SOUTH, (Axis)p1); MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile2); } @@ -471,7 +471,7 @@ void DrawShipDepotSprite(int x, int y, int image) static uint GetSlopeZ_Water(TileIndex tile, uint x, uint y) { uint z; - uint tileh = GetTileSlope(tile, &z); + Slope tileh = GetTileSlope(tile, &z); return z + GetPartialZ(x & 0xF, y & 0xF, tileh); } @@ -672,7 +672,7 @@ static uint32 GetTileTrackStatus_Water(TileIndex tile, TransportType mode) switch (GetWaterTileType(tile)) { case WATER_CLEAR: ts = TRACK_BIT_ALL; break; - case WATER_COAST: ts = coast_tracks[GetTileSlope(tile, NULL) & 0xF]; break; + case WATER_COAST: ts = (TrackBits)coast_tracks[GetTileSlope(tile, NULL) & 0xF]; break; case WATER_LOCK: ts = AxisToTrackBits(DiagDirToAxis(GetLockDirection(tile))); break; case WATER_DEPOT: ts = AxisToTrackBits(GetShipDepotAxis(tile)); break; default: return 0; @@ -714,7 +714,7 @@ static uint32 VehicleEnter_Water(Vehicle *v, TileIndex tile, int x, int y) } -const TileTypeProcs _tile_type_water_procs = { +extern const TileTypeProcs _tile_type_water_procs = { DrawTile_Water, /* draw_tile_proc */ GetSlopeZ_Water, /* get_slope_z_proc */ ClearTile_Water, /* clear_tile_proc */ diff --git a/src/waypoint.cpp b/src/waypoint.cpp index e0bc48936..fe74d7ca7 100644 --- a/src/waypoint.cpp +++ b/src/waypoint.cpp @@ -437,6 +437,6 @@ static void Load_WAYP(void) } } -const ChunkHandler _waypoint_chunk_handlers[] = { +extern const ChunkHandler _waypoint_chunk_handlers[] = { { 'CHKP', Save_WAYP, Load_WAYP, CH_ARRAY | CH_LAST}, }; diff --git a/src/widget.cpp b/src/widget.cpp index 2c77ccd7c..54114ca67 100644 --- a/src/widget.cpp +++ b/src/widget.cpp @@ -206,7 +206,7 @@ void DrawWindowWidgets(const Window *w) case WWT_IMGBTN_2: { int img = wi->data; assert(img != 0); - DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); /* show different image when clicked for WWT_IMGBTN_2 */ if ((wi->type & WWT_MASK) == WWT_IMGBTN_2 && clicked) img++; @@ -216,13 +216,13 @@ void DrawWindowWidgets(const Window *w) case WWT_PANEL: { assert(wi->data == 0); - DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); goto draw_default; } case WWT_TEXTBTN: case WWT_TEXTBTN_2: { - DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); } /* fall through */ @@ -248,7 +248,7 @@ void DrawWindowWidgets(const Window *w) int x, amt1, amt2; int color; - DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); c = GB(wi->data, 0, 8); amt1 = (wi->right - wi->left + 1) / c; @@ -296,11 +296,11 @@ void DrawWindowWidgets(const Window *w) // draw up/down buttons clicked = ((w->flags4 & (WF_SCROLL_UP | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_UP); - DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->color, (clicked) ? FR_LOWERED : FR_NONE); DoDrawString(UPARROW, r.left + 2 + clicked, r.top + clicked, 0x10); clicked = (((w->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_DOWN)); - DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); DoDrawString(DOWNARROW, r.left + 2 + clicked, r.bottom - 9 + clicked, 0x10); c1 = _colour_gradient[wi->color&0xF][3]; @@ -317,7 +317,7 @@ void DrawWindowWidgets(const Window *w) GfxFillRect(r.left+8, r.top+10, r.left+8, r.bottom-10, c2); pt = HandleScrollbarHittest(&w->vscroll, r.top, r.bottom); - DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_MIDDLE ? FR_LOWERED : 0); + DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_MIDDLE ? FR_LOWERED : FR_NONE); break; } case WWT_SCROLL2BAR: { @@ -328,11 +328,11 @@ void DrawWindowWidgets(const Window *w) // draw up/down buttons clicked = ((w->flags4 & (WF_SCROLL_UP | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_UP | WF_SCROLL2)); - DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->color, (clicked) ? FR_LOWERED : FR_NONE); DoDrawString(UPARROW, r.left + 2 + clicked, r.top + clicked, 0x10); clicked = ((w->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_DOWN | WF_SCROLL2)); - DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); DoDrawString(DOWNARROW, r.left + 2 + clicked, r.bottom - 9 + clicked, 0x10); c1 = _colour_gradient[wi->color&0xF][3]; @@ -349,7 +349,7 @@ void DrawWindowWidgets(const Window *w) GfxFillRect(r.left+8, r.top+10, r.left+8, r.bottom-10, c2); pt = HandleScrollbarHittest(&w->vscroll2, r.top, r.bottom); - DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_MIDDLE | WF_SCROLL2) ? FR_LOWERED : 0); + DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_MIDDLE | WF_SCROLL2) ? FR_LOWERED : FR_NONE); break; } @@ -361,11 +361,11 @@ void DrawWindowWidgets(const Window *w) assert(r.bottom - r.top == 11); // XXX - to ensure the same sizes are used everywhere! clicked = ((w->flags4 & (WF_SCROLL_UP | WF_HSCROLL)) == (WF_SCROLL_UP | WF_HSCROLL)); - DrawFrameRect(r.left, r.top, r.left + 9, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.left + 9, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); DrawSprite(SPR_ARROW_LEFT, r.left + 1 + clicked, r.top + 1 + clicked); clicked = ((w->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL)) == (WF_SCROLL_DOWN | WF_HSCROLL)); - DrawFrameRect(r.right-9, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.right-9, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); DrawSprite(SPR_ARROW_RIGHT, r.right - 8 + clicked, r.top + 1 + clicked); c1 = _colour_gradient[wi->color&0xF][3]; @@ -383,7 +383,7 @@ void DrawWindowWidgets(const Window *w) // draw actual scrollbar pt = HandleScrollbarHittest(&w->hscroll, r.left, r.right); - DrawFrameRect(pt.x, r.top, pt.y, r.bottom, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL)) == (WF_SCROLL_MIDDLE | WF_HSCROLL) ? FR_LOWERED : 0); + DrawFrameRect(pt.x, r.top, pt.y, r.bottom, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL)) == (WF_SCROLL_MIDDLE | WF_HSCROLL) ? FR_LOWERED : FR_NONE); break; } @@ -423,7 +423,7 @@ void DrawWindowWidgets(const Window *w) assert(r.right - r.left == 11); // XXX - to ensure the same sizes are used everywhere! clicked = !!(w->flags4 & WF_STICKY); - DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); DrawSprite((clicked) ? SPR_PIN_UP : SPR_PIN_DOWN, r.left + 2 + clicked, r.top + 3 + clicked); break; } @@ -432,7 +432,7 @@ void DrawWindowWidgets(const Window *w) assert(r.right - r.left == 11); // XXX - to ensure the same sizes are used everywhere! clicked = !!(w->flags4 & WF_SIZING); - DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0); + DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE); DrawSprite(SPR_WINDOW_RESIZE, r.left + 3 + clicked, r.top + 3 + clicked); break; } @@ -440,7 +440,7 @@ void DrawWindowWidgets(const Window *w) case WWT_CLOSEBOX: { assert(r.right - r.left == 10); // ensure the same sizes are used everywhere - DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, 0); + DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, FR_NONE); DrawString(r.left + 2, r.top + 2, STR_00C5, 0); break; } diff --git a/src/win32.cpp b/src/win32.cpp index f2fe5b110..423581467 100644 --- a/src/win32.cpp +++ b/src/win32.cpp @@ -1,10 +1,12 @@ /* $Id$ */ #include "stdafx.h" +#include "hal.h" #include "openttd.h" #include "debug.h" #include "functions.h" #include "macros.h" +#include "helpers.hpp" #include "saveload.h" #include "string.h" #include "gfx.h" @@ -447,8 +449,8 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) _ident = GetTickCount(); // something pretty unique - MakeCRCTable(alloca(256 * sizeof(uint32))); - _crash_msg = output = LocalAlloc(LMEM_FIXED, 8192); + MakeCRCTable((uint32*)alloca(256 * sizeof(uint32))); + _crash_msg = output = (char*)LocalAlloc(LMEM_FIXED, 8192); { SYSTEMTIME time; @@ -634,7 +636,7 @@ static inline DIR *dir_calloc(void) DIR *d; if (_global_dir_is_in_use) { - d = calloc(1, sizeof(*d)); + CallocT(&d, 1); } else { _global_dir_is_in_use = true; d = &_global_dir; @@ -911,7 +913,7 @@ void DeterminePaths(void) char *s, *cfg; wchar_t path[MAX_PATH]; - _paths.personal_dir = _paths.game_data_dir = cfg = malloc(MAX_PATH); + _paths.personal_dir = _paths.game_data_dir = cfg = (char*)malloc(MAX_PATH); GetCurrentDirectoryW(MAX_PATH - 1, path); convert_from_fs(path, cfg, MAX_PATH); @@ -962,7 +964,7 @@ bool InsertTextBufferClipboard(Textbuf *tb) OpenClipboard(NULL); cbuf = GetClipboardData(CF_UNICODETEXT); - ptr = GlobalLock(cbuf); + ptr = (const char*)GlobalLock(cbuf); ret = convert_from_fs((wchar_t*)ptr, utf8_buf, lengthof(utf8_buf)); GlobalUnlock(cbuf); CloseClipboard(); @@ -972,7 +974,7 @@ bool InsertTextBufferClipboard(Textbuf *tb) OpenClipboard(NULL); cbuf = GetClipboardData(CF_TEXT); - ptr = GlobalLock(cbuf); + ptr = (const char*)GlobalLock(cbuf); ttd_strlcpy(utf8_buf, ptr, lengthof(utf8_buf)); GlobalUnlock(cbuf); CloseClipboard(); diff --git a/src/window.cpp b/src/window.cpp index 1a12c7c6b..583876ecf 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -14,6 +14,7 @@ #include "variables.h" #include "table/sprites.h" #include "genworld.h" +#include "helpers.hpp" // delta between mouse cursor and upper left corner of dragged window static Point _drag_delta; @@ -312,7 +313,7 @@ Window **FindWindowZPosition(const Window *w) if (*wz == w) return wz; } - DEBUG(misc, 3, "Window (class %d, number %d) is not open, probably removed by recursive calls", + DEBUG(misc, 3, "Window (cls %d, number %d) is not open, probably removed by recursive calls", w->window_class, w->window_number); return NULL; } @@ -543,7 +544,7 @@ void AssignWidgetToWindow(Window *w, const Widget *widget) for (wi = widget; wi->type != WWT_LAST; wi++) index++; - w->widget = realloc(w->widget, sizeof(*w->widget) * index); + ReallocT(&w->widget, index); memcpy(w->widget, widget, sizeof(*w->widget) * index); w->widget_count = index - 1; } else { @@ -1488,7 +1489,7 @@ static void SendWindowMessageW(Window *w, uint msg, uint wparam, uint lparam) * @param wparam Specifies additional message-specific information * @param lparam Specifies additional message-specific information */ -void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, uint msg, uint wparam, uint lparam) +void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, int msg, int wparam, int lparam) { Window *w = FindWindowById(wnd_class, wnd_num); if (w != NULL) SendWindowMessageW(w, msg, wparam, lparam); @@ -1501,7 +1502,7 @@ void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, uint msg, ui * @param wparam Specifies additional message-specific information * @param lparam Specifies additional message-specific information */ -void SendWindowMessageClass(WindowClass wnd_class, uint msg, uint wparam, uint lparam) +void SendWindowMessageClass(WindowClass wnd_class, int msg, int wparam, int lparam) { Window* const *wz; diff --git a/src/window.h b/src/window.h index 2e6fd8b94..8a4eaa93e 100644 --- a/src/window.h +++ b/src/window.h @@ -6,6 +6,8 @@ #include "macros.h" #include "string.h" #include "order.h" +#include "rail.h" +#include "airport.h" typedef struct WindowEvent WindowEvent; @@ -38,7 +40,7 @@ typedef void WindowProc(Window *w, WindowEvent *e); w->resize.width or w->resize.height. That was all.. good luck, and enjoy :) -- TrueLight */ -enum ResizeFlags { +typedef enum ResizeFlags { RESIZE_NONE = 0, RESIZE_LEFT = 1, @@ -77,12 +79,15 @@ typedef struct Widget { } Widget; typedef enum FrameFlags { + FR_NONE = 0x00, FR_TRANSPARENT = 0x01, ///< Makes the background transparent if set FR_BORDERONLY = 0x10, ///< Draw border only, no background FR_LOWERED = 0x20, ///< If set the frame is lowered and the background color brighter (ie. buttons when pressed) FR_DARKENED = 0x40, ///< If set the background is darker, allows for lowered frames with normal background color when used with FR_LOWERED (ie. dropdown boxes) } FrameFlags; +DECLARE_ENUM_AS_BIT_SET(FrameFlags); + void DrawFrameRect(int left, int top, int right, int bottom, int color, FrameFlags flags); enum WindowEventCodes { @@ -165,9 +170,9 @@ struct WindowEvent { } keypress; struct { - uint msg; // message to be sent - uint wparam; // additional message-specific information - uint lparam; // additional message-specific information + int msg; // message to be sent + int wparam; // additional message-specific information + int lparam; // additional message-specific information } message; struct { @@ -180,80 +185,6 @@ struct WindowEvent { } we; }; -enum WindowKeyCodes { - WKC_SHIFT = 0x8000, - WKC_CTRL = 0x4000, - WKC_ALT = 0x2000, - WKC_META = 0x1000, - - // Special ones - WKC_NONE = 0, - WKC_ESC = 1, - WKC_BACKSPACE = 2, - WKC_INSERT = 3, - WKC_DELETE = 4, - - WKC_PAGEUP = 5, - WKC_PAGEDOWN = 6, - WKC_END = 7, - WKC_HOME = 8, - - // Arrow keys - WKC_LEFT = 9, - WKC_UP = 10, - WKC_RIGHT = 11, - WKC_DOWN = 12, - - // Return & tab - WKC_RETURN = 13, - WKC_TAB = 14, - - // Numerical keyboard - WKC_NUM_0 = 16, - WKC_NUM_1 = 17, - WKC_NUM_2 = 18, - WKC_NUM_3 = 19, - WKC_NUM_4 = 20, - WKC_NUM_5 = 21, - WKC_NUM_6 = 22, - WKC_NUM_7 = 23, - WKC_NUM_8 = 24, - WKC_NUM_9 = 25, - WKC_NUM_DIV = 26, - WKC_NUM_MUL = 27, - WKC_NUM_MINUS = 28, - WKC_NUM_PLUS = 29, - WKC_NUM_ENTER = 30, - WKC_NUM_DECIMAL = 31, - - // Space - WKC_SPACE = 32, - - // Function keys - WKC_F1 = 33, - WKC_F2 = 34, - WKC_F3 = 35, - WKC_F4 = 36, - WKC_F5 = 37, - WKC_F6 = 38, - WKC_F7 = 39, - WKC_F8 = 40, - WKC_F9 = 41, - WKC_F10 = 42, - WKC_F11 = 43, - WKC_F12 = 44, - - // backquote is the key left of "1" - // we only store this key here, no matter what character is really mapped to it - // on a particular keyboard. (US keyboard: ` and ~ ; German keyboard: ^ and °) - WKC_BACKQUOTE = 45, - WKC_PAUSE = 46, - - // 0-9 are mapped to 48-57 - // A-Z are mapped to 65-90 - // a-z are mapped to 97-122 -}; - typedef struct WindowDesc { int16 left, top, width, height; WindowClass cls; @@ -389,8 +320,8 @@ assert_compile(WINDOW_CUSTOM_SIZE >= sizeof(tooltips_d)); typedef struct { byte vehicle_type; union { - byte railtype; - byte acc_planes; // AIRCRAFT_ONLY, ALL, HELICOPTERS_ONLY + RailTypeByte railtype; + AcceptPlanesByte acc_planes; // AIRCRAFT_ONLY, ALL, HELICOPTERS_ONLY } filter; byte sel_index; // deprecated value, used for 'unified' ship and road bool descending_sort_order; @@ -494,11 +425,15 @@ typedef struct { assert_compile(WINDOW_CUSTOM_SIZE >= sizeof(scroller_d)); typedef enum SortListFlags { + VL_NONE = 0x00, VL_DESC = 0x01, // sort descending or ascending VL_RESORT = 0x02, // instruct the code to resort the list in the next loop - VL_REBUILD = 0x04 // create sort-listing to use for qsort and friends + VL_REBUILD = 0x04, // create sort-listing to use for qsort and friends + VL_END = 0x08 } SortListFlags; +DECLARE_ENUM_AS_BIT_SET(SortListFlags); + typedef struct Listing { bool order; // Ascending/descending byte criteria; // Sorting criteria @@ -596,8 +531,8 @@ enum WindowFlags { void CallWindowEventNP(Window *w, int event); void CallWindowTickEvent(void); void SetWindowDirty(const Window *w); -void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, uint msg, uint wparam, uint lparam); -void SendWindowMessageClass(WindowClass wnd_class, uint msg, uint wparam, uint lparam); +void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, int msg, int wparam, int lparam); +void SendWindowMessageClass(WindowClass wnd_class, int msg, int wparam, int lparam); Window *FindWindowById(WindowClass cls, WindowNumber number); void DeleteWindow(Window *w); @@ -775,9 +710,6 @@ void UnInitWindowSystem(void); void ResetWindowSystem(void); int GetMenuItemIndex(const Window *w, int x, int y); void InputLoop(void); -void HandleKeypress(uint32 key); -void HandleMouseEvents(void); -void UpdateWindows(void); void InvalidateWidget(const Window *w, byte widget_index); void InvalidateThisWindowData(Window *w); void InvalidateWindowData(WindowClass cls, WindowNumber number); @@ -816,12 +748,6 @@ extern Window **_last_z_window; VARDEF Point _cursorpos_drag_start; -VARDEF bool _left_button_down; -VARDEF bool _left_button_clicked; - -VARDEF bool _right_button_down; -VARDEF bool _right_button_clicked; - VARDEF int _scrollbar_start_pos; VARDEF int _scrollbar_size; VARDEF byte _scroller_click_timeout; diff --git a/src/yapf/follow_track.hpp b/src/yapf/follow_track.hpp index 7864dc5e5..36cc75a4a 100644 --- a/src/yapf/follow_track.hpp +++ b/src/yapf/follow_track.hpp @@ -171,7 +171,7 @@ protected: // rail transport is possible only on compatible rail types if (IsRailTT()) { - RailType rail_type = GetTileRailType(m_new_tile, DiagdirToDiagTrackdir(m_exitdir)); + RailType rail_type = GetTileRailType(m_new_tile, TrackdirToTrack(DiagdirToDiagTrackdir(m_exitdir))); if (((1 << rail_type) & m_veh->u.rail.compatible_railtypes) == 0) { // incompatible rail type return false; diff --git a/src/yapf/track_dir.hpp b/src/yapf/track_dir.hpp index 0239f853e..824075577 100644 --- a/src/yapf/track_dir.hpp +++ b/src/yapf/track_dir.hpp @@ -3,33 +3,9 @@ #ifndef TRACK_DIR_HPP #define TRACK_DIR_HPP -EXTERN_C_BEGIN #include "../tile.h" #include "../openttd.h" #include "../map.h" #include "../rail.h" -EXTERN_C_END - -/** Helpers to allow to work with enum as with type safe bit set in C++ */ -#define DECLARE_ENUM_AS_BIT_MASK(mask_t) \ - FORCEINLINE mask_t operator | (mask_t m1, mask_t m2) {return (mask_t)((int)m1 | m2);} \ - FORCEINLINE mask_t operator & (mask_t m1, mask_t m2) {return (mask_t)((int)m1 & m2);} \ - FORCEINLINE mask_t operator ^ (mask_t m1, mask_t m2) {return (mask_t)((int)m1 ^ m2);} \ - FORCEINLINE mask_t& operator |= (mask_t& m1, mask_t m2) {m1 = m1 | m2; return m1;} \ - FORCEINLINE mask_t& operator &= (mask_t& m1, mask_t m2) {m1 = m1 & m2; return m1;} \ - FORCEINLINE mask_t& operator ^= (mask_t& m1, mask_t m2) {m1 = m1 ^ m2; return m1;} \ - FORCEINLINE mask_t operator ~(mask_t m) {return (mask_t)(~(int)m);} - -/** probably redundant enum combining operators (as we have conversion functions) */ -#define DECLARE_ENUM_AS_BIT_INDEX(idx_t, mask_t) \ - FORCEINLINE mask_t operator << (int m, idx_t i) {return (mask_t)(m << (int)i);} \ - FORCEINLINE mask_t operator << (mask_t m, int i) {return (mask_t)(((int)m) << i);} \ - FORCEINLINE mask_t operator >> (mask_t m, int i) {return (mask_t)(((int)m) >> i);} - -DECLARE_ENUM_AS_BIT_MASK(TrackBits) -DECLARE_ENUM_AS_BIT_INDEX(Track, TrackBits) - -DECLARE_ENUM_AS_BIT_MASK(TrackdirBits) -DECLARE_ENUM_AS_BIT_INDEX(Trackdir, TrackdirBits) #endif /* TRACK_DIR_HPP */ diff --git a/src/yapf/yapf.h b/src/yapf/yapf.h index 6b58b4e08..76f2dc1cb 100644 --- a/src/yapf/yapf.h +++ b/src/yapf/yapf.h @@ -31,7 +31,7 @@ Trackdir YapfChooseRoadTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir) * @param no_path_found [out] true is returned if no path can be found (returned Trackdir is only a 'guess') * @return the best trackdir for next turn or INVALID_TRACKDIR if the path could not be found */ -Trackdir YapfChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirs, bool *path_not_found); +Trackdir YapfChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found); /** Used by RV multistop feature to find the nearest road stop that has a free slot. * @param v RV (its current tile will be the origin) diff --git a/src/yapf/yapf.hpp b/src/yapf/yapf.hpp index 208f29c46..5aa63de1a 100644 --- a/src/yapf/yapf.hpp +++ b/src/yapf/yapf.hpp @@ -7,7 +7,6 @@ #include "track_dir.hpp" -EXTERN_C_BEGIN #include "../depot.h" #include "../road_map.h" #include "../tunnel_map.h" @@ -22,12 +21,9 @@ EXTERN_C_BEGIN #include "../pathfind.h" #include "../waypoint.h" #include "../debug.h" -EXTERN_C_END -EXTERN_C_BEGIN - extern Patches _patches_newgame; - extern uint64 _rdtsc(void); -EXTERN_C_END +extern Patches _patches_newgame; +extern uint64 _rdtsc(void); #include <limits.h> #include <new> diff --git a/src/yapf/yapf_base.hpp b/src/yapf/yapf_base.hpp index 1d0417987..e4ef5abc3 100644 --- a/src/yapf/yapf_base.hpp +++ b/src/yapf/yapf_base.hpp @@ -3,9 +3,7 @@ #ifndef YAPF_BASE_HPP #define YAPF_BASE_HPP -EXTERN_C_BEGIN #include "../debug.h" -EXTERN_C_END #include "fixedsizearray.hpp" #include "blob.hpp" diff --git a/src/yapf/yapf_common.hpp b/src/yapf/yapf_common.hpp index 869bc820c..87deffeda 100644 --- a/src/yapf/yapf_common.hpp +++ b/src/yapf/yapf_common.hpp @@ -132,8 +132,8 @@ public: * adds it to the actual cost from origin and stores the sum to the Node::m_estimate */ inline bool PfCalcEstimate(Node& n) { - int dx = abs(TileX(n.GetTile()) - TileX(m_destTile)); - int dy = abs(TileY(n.GetTile()) - TileY(m_destTile)); + int dx = delta(TileX(n.GetTile()), TileX(m_destTile)); + int dy = delta(TileY(n.GetTile()), TileY(m_destTile)); assert(dx >= 0 && dy >= 0); int dd = min(dx, dy); int dxy = abs(dx - dy); diff --git a/src/yapf/yapf_costrail.hpp b/src/yapf/yapf_costrail.hpp index 93062b5c2..b48257e46 100644 --- a/src/yapf/yapf_costrail.hpp +++ b/src/yapf/yapf_costrail.hpp @@ -195,7 +195,7 @@ public: Trackdir trackdir = n.m_key.m_td; TileType tile_type = GetTileType(tile); - RailType rail_type = GetTileRailType(tile, trackdir); + RailType rail_type = GetTileRailType(tile, TrackdirToTrack(trackdir)); bool target_seen = Yapf().PfDetectDestination(tile, trackdir); @@ -252,7 +252,7 @@ public: // if tail type changes, finish segment (cached segment can't contain more rail types) { - RailType new_rail_type = GetTileRailType(F.m_new_tile, (Trackdir)FindFirstBit2x64(F.m_new_td_bits)); + RailType new_rail_type = GetTileRailType(F.m_new_tile, TrackdirToTrack(FindFirstTrackdir(F.m_new_td_bits))); if (new_rail_type != rail_type) { break; } diff --git a/src/yapf/yapf_rail.cpp b/src/yapf/yapf_rail.cpp index 1461b9402..5073b8705 100644 --- a/src/yapf/yapf_rail.cpp +++ b/src/yapf/yapf_rail.cpp @@ -103,14 +103,14 @@ public: /// return debug report character to identify the transportation type FORCEINLINE char TransportTypeChar() const {return 't';} - static Trackdir stChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirs, bool *path_not_found) + static Trackdir stChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found) { // create pathfinder instance Tpf pf; - return pf.ChooseRailTrack(v, tile, enterdir, trackdirs, path_not_found); + return pf.ChooseRailTrack(v, tile, enterdir, tracks, path_not_found); } - FORCEINLINE Trackdir ChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirs, bool *path_not_found) + FORCEINLINE Trackdir ChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found) { // set origin and destination nodes Yapf().SetOrigin(v->tile, GetVehicleTrackdir(v), INVALID_TILE, INVALID_TRACKDIR, 1, true); @@ -200,10 +200,10 @@ struct CYapfAnyDepotRail2 : CYapfT<CYapfRail_TypesT<CYapfAnyDepotRail2, CFollowT struct CYapfAnyDepotRail3 : CYapfT<CYapfRail_TypesT<CYapfAnyDepotRail3, CFollowTrackRailNo90, CRailNodeListTrackDir, CYapfDestinationAnyDepotRailT , CYapfFollowAnyDepotRailT> > {}; -Trackdir YapfChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirs, bool *path_not_found) +Trackdir YapfChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found) { // default is YAPF type 2 - typedef Trackdir (*PfnChooseRailTrack)(Vehicle*, TileIndex, DiagDirection, TrackdirBits, bool*); + typedef Trackdir (*PfnChooseRailTrack)(Vehicle*, TileIndex, DiagDirection, TrackBits, bool*); PfnChooseRailTrack pfnChooseRailTrack = &CYapfRail2::stChooseRailTrack; // check if non-default YAPF type needed @@ -212,7 +212,7 @@ Trackdir YapfChooseRailTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, else if (_patches.yapf.disable_node_optimization) pfnChooseRailTrack = &CYapfRail1::stChooseRailTrack; // Trackdir, allow 90-deg - Trackdir td_ret = pfnChooseRailTrack(v, tile, enterdir, trackdirs, path_not_found); + Trackdir td_ret = pfnChooseRailTrack(v, tile, enterdir, tracks, path_not_found); return td_ret; } |