1
0
Fork 0

(svn r3181) -Bracing

-Indentation
-Whitespace
-DeMorgan's Law
-Test with NULL or 0 for non-booleans
-'\0' instead of 0 for chars
-Remove redundantly redundant comments (like DoFoo(); // Do foo)
-Join multiple short lines with a single statement
-Split single lines with multiple statements
-Avoid assignments in if
release/0.4.5
tron 2005-11-14 19:48:04 +00:00
parent d8b56c123e
commit f7abff5f96
63 changed files with 1984 additions and 2359 deletions

13
ai/ai.c
View File

@ -125,9 +125,9 @@ static void AI_RunTick(PlayerID player)
Player *p = GetPlayer(player); Player *p = GetPlayer(player);
_current_player = player; _current_player = player;
if (_patches.ainew_active) if (_patches.ainew_active) {
AiNewDoGameLoop(p); AiNewDoGameLoop(p);
else { } else {
/* Enable all kind of cheats the old AI needs in order to operate correctly... */ /* Enable all kind of cheats the old AI needs in order to operate correctly... */
_is_old_ai_player = true; _is_old_ai_player = true;
AiDoGameLoop(p); AiDoGameLoop(p);
@ -143,8 +143,7 @@ static void AI_RunTick(PlayerID player)
void AI_RunGameLoop(void) void AI_RunGameLoop(void)
{ {
/* Don't do anything if ai is disabled */ /* Don't do anything if ai is disabled */
if (!_ai.enabled) if (!_ai.enabled) return;
return;
/* New tick */ /* New tick */
_ai.tick++; _ai.tick++;
@ -212,11 +211,9 @@ void AI_Initialize(void)
*/ */
void AI_Uninitialize(void) void AI_Uninitialize(void)
{ {
Player *p; Player* p;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (p->is_active && p->is_ai) { if (p->is_active && p->is_ai) AI_PlayerDied(p->index);
AI_PlayerDied(p->index);
}
} }
} }

View File

@ -278,11 +278,12 @@ static void AiHandleGotoDepot(Player *p, int cmd)
static void AiRestoreVehicleOrders(Vehicle *v, BackuppedOrders *bak) static void AiRestoreVehicleOrders(Vehicle *v, BackuppedOrders *bak)
{ {
int i; uint i;
for (i = 0; bak->order[i].type != OT_NOTHING; i++) for (i = 0; bak->order[i].type != OT_NOTHING; i++) {
if (CmdFailed(DoCommandP(0, v->index + (i << 16), PackOrder(&bak->order[i]), NULL, CMD_INSERT_ORDER | CMD_NO_TEST_IF_IN_NETWORK))) if (CmdFailed(DoCommandP(0, v->index + (i << 16), PackOrder(&bak->order[i]), NULL, CMD_INSERT_ORDER | CMD_NO_TEST_IF_IN_NETWORK)))
break; break;
}
} }
static void AiHandleReplaceTrain(Player *p) static void AiHandleReplaceTrain(Player *p)
@ -673,8 +674,7 @@ static void AiWantLongIndustryRoute(Player *p)
return; return;
} }
if (!AiCheckIfRouteIsGood(p, &fr, 1)) if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
return;
// Fill the source field // Fill the source field
p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to); p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
@ -688,9 +688,9 @@ static void AiWantLongIndustryRoute(Player *p)
p->ai.src.buildcmd_a = 0x24; p->ai.src.buildcmd_a = 0x24;
p->ai.src.buildcmd_b = 0xFF; p->ai.src.buildcmd_b = 0xFF;
p->ai.src.direction = AiGetDirectionBetweenTiles( p->ai.src.direction = AiGetDirectionBetweenTiles(
p->ai.src.spec_tile, p->ai.src.spec_tile,
p->ai.dst.spec_tile p->ai.dst.spec_tile
); );
p->ai.src.cargo = fr.cargo | 0x80; p->ai.src.cargo = fr.cargo | 0x80;
// Fill the dest field // Fill the dest field
@ -703,17 +703,17 @@ static void AiWantLongIndustryRoute(Player *p)
p->ai.dst.buildcmd_a = 0x34; p->ai.dst.buildcmd_a = 0x34;
p->ai.dst.buildcmd_b = 0xFF; p->ai.dst.buildcmd_b = 0xFF;
p->ai.dst.direction = AiGetDirectionBetweenTiles( p->ai.dst.direction = AiGetDirectionBetweenTiles(
p->ai.dst.spec_tile, p->ai.dst.spec_tile,
p->ai.src.spec_tile p->ai.src.spec_tile
); );
p->ai.dst.cargo = fr.cargo; p->ai.dst.cargo = fr.cargo;
// Fill middle field 1 // Fill middle field 1
p->ai.mid1.spec_tile = AiGetPctTileBetween( p->ai.mid1.spec_tile = AiGetPctTileBetween(
p->ai.src.spec_tile, p->ai.src.spec_tile,
p->ai.dst.spec_tile, p->ai.dst.spec_tile,
0x55 0x55
); );
p->ai.mid1.use_tile = 0; p->ai.mid1.use_tile = 0;
p->ai.mid1.rand_rng = 6; p->ai.mid1.rand_rng = 6;
p->ai.mid1.cur_building_rule = 0xFF; p->ai.mid1.cur_building_rule = 0xFF;
@ -726,10 +726,10 @@ static void AiWantLongIndustryRoute(Player *p)
// Fill middle field 2 // Fill middle field 2
p->ai.mid2.spec_tile = AiGetPctTileBetween( p->ai.mid2.spec_tile = AiGetPctTileBetween(
p->ai.src.spec_tile, p->ai.src.spec_tile,
p->ai.dst.spec_tile, p->ai.dst.spec_tile,
0xAA 0xAA
); );
p->ai.mid2.use_tile = 0; p->ai.mid2.use_tile = 0;
p->ai.mid2.rand_rng = 6; p->ai.mid2.rand_rng = 6;
p->ai.mid2.cur_building_rule = 0xFF; p->ai.mid2.cur_building_rule = 0xFF;
@ -781,8 +781,7 @@ static void AiWantMediumIndustryRoute(Player *p)
return; return;
} }
if (!AiCheckIfRouteIsGood(p, &fr, 1)) if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
return;
// Fill the source field // Fill the source field
p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from); p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
@ -854,8 +853,7 @@ static void AiWantShortIndustryRoute(Player *p)
return; return;
} }
if (!AiCheckIfRouteIsGood(p, &fr, 1)) if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
return;
// Fill the source field // Fill the source field
p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from); p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
@ -928,8 +926,7 @@ static void AiWantMailRoute(Player *p)
} }
fr.cargo = CT_MAIL; fr.cargo = CT_MAIL;
if (!AiCheckIfRouteIsGood(p, &fr, 1)) if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
return;
// Fill the source field // Fill the source field
p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from); p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
@ -1034,8 +1031,7 @@ static void AiWantPassengerRoute(Player *p)
} }
fr.cargo = CT_PASSENGERS; fr.cargo = CT_PASSENGERS;
if (!AiCheckIfRouteIsGood(p, &fr, 1)) if (!AiCheckIfRouteIsGood(p, &fr, 1)) return;
return;
// Fill the source field // Fill the source field
p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from); p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
@ -1047,9 +1043,9 @@ static void AiWantPassengerRoute(Player *p)
p->ai.src.buildcmd_a = 0x10; p->ai.src.buildcmd_a = 0x10;
p->ai.src.buildcmd_b = 0xFF; p->ai.src.buildcmd_b = 0xFF;
p->ai.src.direction = AiGetDirectionBetweenTiles( p->ai.src.direction = AiGetDirectionBetweenTiles(
GET_TOWN_OR_INDUSTRY_TILE(fr.from), GET_TOWN_OR_INDUSTRY_TILE(fr.from),
GET_TOWN_OR_INDUSTRY_TILE(fr.to) GET_TOWN_OR_INDUSTRY_TILE(fr.to)
); );
p->ai.src.cargo = fr.cargo; p->ai.src.cargo = fr.cargo;
// Fill the dest field // Fill the dest field
@ -1062,9 +1058,9 @@ static void AiWantPassengerRoute(Player *p)
p->ai.dst.buildcmd_a = 0xFF; p->ai.dst.buildcmd_a = 0xFF;
p->ai.dst.buildcmd_b = 0xFF; p->ai.dst.buildcmd_b = 0xFF;
p->ai.dst.direction = AiGetDirectionBetweenTiles( p->ai.dst.direction = AiGetDirectionBetweenTiles(
GET_TOWN_OR_INDUSTRY_TILE(fr.to), GET_TOWN_OR_INDUSTRY_TILE(fr.to),
GET_TOWN_OR_INDUSTRY_TILE(fr.from) GET_TOWN_OR_INDUSTRY_TILE(fr.from)
); );
p->ai.dst.cargo = fr.cargo; p->ai.dst.cargo = fr.cargo;
// Fill common fields // Fill common fields
@ -1126,8 +1122,7 @@ static void AiWantLongRoadIndustryRoute(Player *p)
return; return;
} }
if (!AiCheckIfRouteIsGood(p, &fr, 2)) if (!AiCheckIfRouteIsGood(p, &fr, 2)) return;
return;
// Fill the source field // Fill the source field
p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from); p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
@ -1187,8 +1182,7 @@ static void AiWantMediumRoadIndustryRoute(Player *p)
return; return;
} }
if (!AiCheckIfRouteIsGood(p, &fr, 2)) if (!AiCheckIfRouteIsGood(p, &fr, 2)) return;
return;
// Fill the source field // Fill the source field
p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from); p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
@ -1250,8 +1244,7 @@ static void AiWantLongRoadPassengerRoute(Player *p)
fr.cargo = CT_PASSENGERS; fr.cargo = CT_PASSENGERS;
if (!AiCheckIfRouteIsGood(p, &fr, 2)) if (!AiCheckIfRouteIsGood(p, &fr, 2)) return;
return;
// Fill the source field // Fill the source field
p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to); p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
@ -1309,8 +1302,7 @@ static void AiWantPassengerRouteInsideTown(Player *p)
fr.cargo = CT_PASSENGERS; fr.cargo = CT_PASSENGERS;
fr.from = fr.to = t; fr.from = fr.to = t;
if (!AiCheckIfRouteIsGood(p, &fr, 2)) if (!AiCheckIfRouteIsGood(p, &fr, 2)) return;
return;
// Fill the source field // Fill the source field
p->ai.src.spec_tile = t->xy; p->ai.src.spec_tile = t->xy;
@ -1360,7 +1352,6 @@ static void AiWantRoadRoute(Player *p)
} else { } else {
AiWantPassengerRouteInsideTown(p); AiWantPassengerRouteInsideTown(p);
} }
} }
static void AiWantPassengerAircraftRoute(Player *p) static void AiWantPassengerAircraftRoute(Player *p)
@ -1615,14 +1606,13 @@ clear_town_stuff:;
} }
} else if (p->mode == 2) { } else if (p->mode == 2) {
// Rail // Rail
if (IsTileType(c, MP_RAILWAY)) if (IsTileType(c, MP_RAILWAY)) return CMD_ERROR;
return CMD_ERROR;
j = p->attr; j = p->attr;
k = 0; k = 0;
// Build the rail // Build the rail
for(i=0; i!=6; i++,j>>=1) { for (i = 0; i != 6; i++, j >>= 1) {
if (j&1) { if (j&1) {
k = i; k = i;
ret = DoCommandByTile(c, _cur_ai_player->ai.railtype_to_use, i, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL); ret = DoCommandByTile(c, _cur_ai_player->ai.railtype_to_use, i, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL);
@ -1683,9 +1673,9 @@ static int AiBuildDefaultRailTrack(TileIndex tile, byte p0, byte p1, byte p2, by
int i; int i;
const AiDefaultRailBlock *p; const AiDefaultRailBlock *p;
for(i=0; (p = _default_rail_track_data[i]) != NULL; i++) { for (i = 0; (p = _default_rail_track_data[i]) != NULL; i++) {
if (p->p0 == p0 && p->p1 == p1 && p->p2 == p2 && p->p3 == p3 && if (p->p0 == p0 && p->p1 == p1 && p->p2 == p2 && p->p3 == p3 &&
(p->dir == 0xFF || p->dir == dir || ((p->dir-1)&3) == dir)) { (p->dir == 0xFF || p->dir == dir || ((p->dir - 1) & 3) == dir)) {
*cost = AiDoBuildDefaultRailTrack(tile, p->data, DC_NO_TOWN_RATING); *cost = AiDoBuildDefaultRailTrack(tile, p->data, DC_NO_TOWN_RATING);
if (*cost != CMD_ERROR && AiCheckTrackResources(tile, p->data, cargo)) if (*cost != CMD_ERROR && AiCheckTrackResources(tile, p->data, cargo))
return i; return i;
@ -1762,7 +1752,8 @@ static void AiDoTerraformLand(TileIndex tile, int dir, int unk, int mode)
static void AiStateBuildDefaultRailBlocks(Player *p) static void AiStateBuildDefaultRailBlocks(Player *p)
{ {
int i, j; uint i;
int j;
AiBuildRec *aib; AiBuildRec *aib;
int rule; int rule;
int32 cost; int32 cost;
@ -1823,8 +1814,7 @@ static void AiStateBuildDefaultRailBlocks(Player *p)
aib = &p->ai.src; aib = &p->ai.src;
j = p->ai.num_build_rec; j = p->ai.num_build_rec;
do { do {
if (aib->cur_building_rule == 255) if (aib->cur_building_rule == 255) return;
return;
} while (++aib,--j); } while (++aib,--j);
// yep, all are done. switch state to the rail building state. // yep, all are done. switch state to the rail building state.
@ -1850,16 +1840,14 @@ typedef struct AiRailPathFindData {
static bool AiEnumFollowTrack(TileIndex tile, AiRailPathFindData *a, int track, uint length, byte *state) static bool AiEnumFollowTrack(TileIndex tile, AiRailPathFindData *a, int track, uint length, byte *state)
{ {
if (a->flag) if (a->flag) return true;
return true;
if (length > 20 || tile == a->tile) { if (length > 20 || tile == a->tile) {
a->flag = true; a->flag = true;
return true; return true;
} }
if (DistanceMax(tile, a->tile2) < 4) if (DistanceMax(tile, a->tile2) < 4) a->count++;
a->count++;
return false; return false;
} }
@ -1867,6 +1855,7 @@ static bool AiEnumFollowTrack(TileIndex tile, AiRailPathFindData *a, int track,
static bool AiDoFollowTrack(Player *p) static bool AiDoFollowTrack(Player *p)
{ {
AiRailPathFindData arpfd; AiRailPathFindData arpfd;
arpfd.tile = p->ai.start_tile_a; arpfd.tile = p->ai.start_tile_a;
arpfd.tile2 = p->ai.cur_tile_a; arpfd.tile2 = p->ai.cur_tile_a;
arpfd.flag = false; arpfd.flag = false;
@ -1909,26 +1898,29 @@ static bool AiIsTileBanned(const Player* p, TileIndex tile, byte val)
{ {
int i; int i;
for(i=0; i!=p->ai.banned_tile_count; i++) for (i = 0; i != p->ai.banned_tile_count; i++) {
if (p->ai.banned_tiles[i] == tile && if (p->ai.banned_tiles[i] == tile && p->ai.banned_val[i] == val) {
p->ai.banned_val[i] == val) return true;
return true; }
}
return false; return false;
} }
static void AiBanTile(Player *p, TileIndex tile, byte val) { static void AiBanTile(Player* p, TileIndex tile, byte val)
{
int i; int i;
for(i=lengthof(p->ai.banned_tiles)-1; i!=0; i--) { for (i = lengthof(p->ai.banned_tiles) - 1; i != 0; i--) {
p->ai.banned_tiles[i] = p->ai.banned_tiles[i-1]; p->ai.banned_tiles[i] = p->ai.banned_tiles[i - 1];
p->ai.banned_val[i] = p->ai.banned_val[i-1]; p->ai.banned_val[i] = p->ai.banned_val[i - 1];
} }
p->ai.banned_tiles[0] = tile; p->ai.banned_tiles[0] = tile;
p->ai.banned_val[0] = val; p->ai.banned_val[0] = val;
if (p->ai.banned_tile_count != lengthof(p->ai.banned_tiles)) if (p->ai.banned_tile_count != lengthof(p->ai.banned_tiles)) {
p->ai.banned_tile_count++; p->ai.banned_tile_count++;
}
} }
static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir); static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir);
@ -3201,11 +3193,13 @@ static void AiStateBuildRoadVehicles(Player *p)
loco_id = _new_roadveh_id; loco_id = _new_roadveh_id;
for(i=0; p->ai.order_list_blocks[i] != 0xFF; i++) { for (i = 0; p->ai.order_list_blocks[i] != 0xFF; i++) {
AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i]; AiBuildRec* aib = &p->ai.src + p->ai.order_list_blocks[i];
bool is_pass = (p->ai.cargo_type == CT_PASSENGERS || bool is_pass = (
p->ai.cargo_type == CT_MAIL || p->ai.cargo_type == CT_PASSENGERS ||
(_opt.landscape==LT_NORMAL && p->ai.cargo_type == CT_VALUABLES)); p->ai.cargo_type == CT_MAIL ||
(_opt.landscape == LT_NORMAL && p->ai.cargo_type == CT_VALUABLES)
);
Order order; Order order;
order.type = OT_GOTO_STATION; order.type = OT_GOTO_STATION;
@ -3220,15 +3214,10 @@ static void AiStateBuildRoadVehicles(Player *p)
} }
DoCommandByTile(0, loco_id, 0, DC_EXEC, CMD_START_STOP_ROADVEH); DoCommandByTile(0, loco_id, 0, DC_EXEC, CMD_START_STOP_ROADVEH);
DoCommandByTile(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT); DoCommandByTile(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
if (p->ai.num_want_fullload != 0) if (p->ai.num_want_fullload != 0) p->ai.num_want_fullload--;
p->ai.num_want_fullload--; if (--p->ai.num_loco_to_build == 0) p->ai.state = AIS_0;
if (--p->ai.num_loco_to_build == 0) {
p->ai.state = AIS_0;
}
} }
static void AiStateDeleteRoadBlocks(Player *p) static void AiStateDeleteRoadBlocks(Player *p)

View File

@ -250,8 +250,7 @@ int AiNew_Build_Vehicle(Player *p, TileIndex tile, byte flag)
int i = AiNew_PickVehicle(p); int i = AiNew_PickVehicle(p);
if (i == -1) return CMD_ERROR; if (i == -1) return CMD_ERROR;
if (p->ainew.tbt == AI_TRAIN) if (p->ainew.tbt == AI_TRAIN) return CMD_ERROR;
return CMD_ERROR;
return DoCommandByTile(tile, i, 0, flag, CMD_BUILD_ROAD_VEH); return DoCommandByTile(tile, i, 0, flag, CMD_BUILD_ROAD_VEH);
} }

View File

@ -155,8 +155,9 @@ int32 CmdBuildAircraft(int x, int y, uint32 flags, uint32 p1, uint32 p2)
avi = AircraftVehInfo(p1); avi = AircraftVehInfo(p1);
// allocate 2 or 3 vehicle structs, depending on type // allocate 2 or 3 vehicle structs, depending on type
if (!AllocateVehicles(vl, (avi->subtype & 1) == 0 ? 3 : 2) || if (!AllocateVehicles(vl, (avi->subtype & 1) == 0 ? 3 : 2) ||
IsOrderPoolFull()) IsOrderPoolFull()) {
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME); return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
}
unit_num = GetFreeUnitNumber(VEH_Aircraft); unit_num = GetFreeUnitNumber(VEH_Aircraft);
if (unit_num > _patches.max_aircraft) if (unit_num > _patches.max_aircraft)
@ -546,21 +547,15 @@ static void CheckIfAircraftNeedsService(Vehicle *v)
{ {
const Station* st; const Station* st;
if (_patches.servint_aircraft == 0) if (_patches.servint_aircraft == 0) return;
return; if (!VehicleNeedsService(v)) return;
if (v->vehstatus & VS_STOPPED) return;
if (!VehicleNeedsService(v))
return;
if (v->vehstatus & VS_STOPPED)
return;
if (v->current_order.type == OT_GOTO_DEPOT && if (v->current_order.type == OT_GOTO_DEPOT &&
v->current_order.flags & OF_HALT_IN_DEPOT) v->current_order.flags & OF_HALT_IN_DEPOT)
return; return;
if (_patches.gotodepot && VehicleHasDepotOrders(v)) if (_patches.gotodepot && VehicleHasDepotOrders(v)) return;
return;
st = GetStation(v->current_order.station); st = GetStation(v->current_order.station);
// only goto depot if the target airport has terminals (eg. it is airport) // only goto depot if the target airport has terminals (eg. it is airport)
@ -581,11 +576,9 @@ void OnNewDay_Aircraft(Vehicle *v)
{ {
int32 cost; int32 cost;
if (v->subtype > 2) if (v->subtype > 2) return;
return;
if ((++v->day_counter & 7) == 0) if ((++v->day_counter & 7) == 0) DecreaseVehicleValue(v);
DecreaseVehicleValue(v);
CheckOrders(v->index, OC_INIT); CheckOrders(v->index, OC_INIT);
@ -593,8 +586,7 @@ void OnNewDay_Aircraft(Vehicle *v)
AgeVehicle(v); AgeVehicle(v);
CheckIfAircraftNeedsService(v); CheckIfAircraftNeedsService(v);
if (v->vehstatus & VS_STOPPED) if (v->vehstatus & VS_STOPPED) return;
return;
cost = AircraftVehInfo(v->engine_type)->running_cost * _price.aircraft_running / 364; cost = AircraftVehInfo(v->engine_type)->running_cost * _price.aircraft_running / 364;
@ -622,13 +614,12 @@ void AircraftYearlyLoop(void)
static void AgeAircraftCargo(Vehicle *v) static void AgeAircraftCargo(Vehicle *v)
{ {
if (_age_cargo_skip_counter != 0) if (_age_cargo_skip_counter != 0) return;
return;
do { do {
if (v->cargo_days != 0xFF) if (v->cargo_days != 0xFF) v->cargo_days++;
v->cargo_days++; v = v->next;
} while ( (v=v->next) != NULL ); } while (v != NULL);
} }
static void HelicopterTickHandler(Vehicle *v) static void HelicopterTickHandler(Vehicle *v)
@ -639,8 +630,7 @@ static void HelicopterTickHandler(Vehicle *v)
u = v->next->next; u = v->next->next;
if (u->vehstatus & VS_HIDDEN) if (u->vehstatus & VS_HIDDEN) return;
return;
// if true, helicopter rotors do not rotate. This should only be the case if a helicopter is // if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
// loading/unloading at a terminal or stopped // loading/unloading at a terminal or stopped
@ -707,7 +697,8 @@ static void SetAircraftPosition(Vehicle *v, int x, int y, int z)
VehiclePositionChanged(u); VehiclePositionChanged(u);
EndVehicleMove(u); EndVehicleMove(u);
if ((u=u->next) != NULL) { u = u->next;
if (u != NULL) {
u->x_pos = x; u->x_pos = x;
u->y_pos = y; u->y_pos = y;
u->z_pos = z + 5; u->z_pos = z + 5;
@ -729,7 +720,8 @@ static void ServiceAircraft(Vehicle *v)
u = v->next; u = v->next;
u->vehstatus |= VS_HIDDEN; u->vehstatus |= VS_HIDDEN;
if ((u=u->next) != NULL) { u = u->next;
if (u != NULL) {
u->vehstatus |= VS_HIDDEN; u->vehstatus |= VS_HIDDEN;
u->cur_speed = 0; u->cur_speed = 0;
} }
@ -752,10 +744,10 @@ static bool UpdateAircraftSpeed(Vehicle *v)
byte t; byte t;
v->subspeed = (t=v->subspeed) + (byte)spd; v->subspeed = (t=v->subspeed) + (byte)spd;
spd = min( v->cur_speed + (spd >> 8) + (v->subspeed < t), v->max_speed); spd = min(v->cur_speed + (spd >> 8) + (v->subspeed < t), v->max_speed);
// adjust speed for broken vehicles // adjust speed for broken vehicles
if(v->vehstatus&VS_AIRCRAFT_BROKEN) spd = min(spd, 27); if (v->vehstatus & VS_AIRCRAFT_BROKEN) spd = min(spd, 27);
//updates statusbar only if speed have changed to save CPU time //updates statusbar only if speed have changed to save CPU time
if (spd != v->cur_speed) { if (spd != v->cur_speed) {
@ -764,19 +756,15 @@ static bool UpdateAircraftSpeed(Vehicle *v)
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR);
} }
if (!(v->direction & 1)) { if (!(v->direction & 1)) spd = spd * 3 / 4;
spd = spd * 3 >> 2;
}
if (spd == 0) if (spd == 0) return false;
return false;
if ((byte)++spd == 0) if ((byte)++spd == 0) return true;
return true;
v->progress = (t = v->progress) - (byte)spd; v->progress = (t = v->progress) - (byte)spd;
return (t < v->progress); return t < v->progress;
} }
// get Aircraft running altitude // get Aircraft running altitude
@ -822,9 +810,7 @@ static bool AircraftController(Vehicle *v)
// Make sure the rotors don't rotate too fast // Make sure the rotors don't rotate too fast
if (u->cur_speed > 32) { if (u->cur_speed > 32) {
v->cur_speed = 0; v->cur_speed = 0;
if (--u->cur_speed == 32) { if (--u->cur_speed == 32) SndPlayVehicleFx(SND_18_HELICOPTER, v);
SndPlayVehicleFx(SND_18_HELICOPTER, v);
}
} else { } else {
u->cur_speed = 32; u->cur_speed = 32;
if (UpdateAircraftSpeed(v)) { if (UpdateAircraftSpeed(v)) {
@ -865,9 +851,8 @@ static bool AircraftController(Vehicle *v)
u = v->next->next; u = v->next->next;
// Increase speed of rotors. When speed is 80, we've landed. // Increase speed of rotors. When speed is 80, we've landed.
if (u->cur_speed >= 80) if (u->cur_speed >= 80) return true;
return true; u->cur_speed += 4;
u->cur_speed+=4;
} else if (v->z_pos > z) { } else if (v->z_pos > z) {
SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos-1); SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos-1);
} else { } else {
@ -886,10 +871,7 @@ static bool AircraftController(Vehicle *v)
// At final pos? // At final pos?
if (dist == 0) { if (dist == 0) {
if (v->cur_speed > 12) v->cur_speed = 12;
// Clamp speed to 12.
if (v->cur_speed > 12)
v->cur_speed = 12;
// Change direction smoothly to final direction. // Change direction smoothly to final direction.
dirdiff = amd->direction - v->direction; dirdiff = amd->direction - v->direction;
@ -900,8 +882,7 @@ static bool AircraftController(Vehicle *v)
return true; return true;
} }
if (!UpdateAircraftSpeed(v)) if (!UpdateAircraftSpeed(v)) return false;
return false;
v->direction = (v->direction+((dirdiff&7)<5?1:-1)) & 7; v->direction = (v->direction+((dirdiff&7)<5?1:-1)) & 7;
v->cur_speed >>= 1; v->cur_speed >>= 1;
@ -910,24 +891,17 @@ static bool AircraftController(Vehicle *v)
return false; return false;
} }
// Clamp speed? if (!(amd->flag & AMED_NOSPDCLAMP) && v->cur_speed > 12) v->cur_speed = 12;
if (!(amd->flag & AMED_NOSPDCLAMP) && v->cur_speed > 12)
v->cur_speed = 12;
if (!UpdateAircraftSpeed(v)) if (!UpdateAircraftSpeed(v)) return false;
return false;
// Decrease animation counter. if (v->load_unload_time_rem != 0) v->load_unload_time_rem--;
if (v->load_unload_time_rem != 0)
v->load_unload_time_rem--;
// Turn. Do it slowly if in the air. // Turn. Do it slowly if in the air.
newdir = GetDirectionTowards(v, x + amd->x, y + amd->y); newdir = GetDirectionTowards(v, x + amd->x, y + amd->y);
if (newdir != v->direction) { if (newdir != v->direction) {
if (amd->flag & AMED_SLOWTURN) { if (amd->flag & AMED_SLOWTURN) {
if (v->load_unload_time_rem == 0) { if (v->load_unload_time_rem == 0) v->load_unload_time_rem = 8;
v->load_unload_time_rem = 8;
}
v->direction = newdir; v->direction = newdir;
} else { } else {
v->cur_speed >>= 1; v->cur_speed >>= 1;
@ -940,19 +914,15 @@ static bool AircraftController(Vehicle *v)
v->tile = gp.new_tile; v->tile = gp.new_tile;
// If vehicle is in the air, use tile coordinate 0. // If vehicle is in the air, use tile coordinate 0.
if (amd->flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) { if (amd->flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
v->tile = 0;
}
// Adjust Z for land or takeoff? // Adjust Z for land or takeoff?
z = v->z_pos; z = v->z_pos;
if (amd->flag & AMED_TAKEOFF) { if (amd->flag & AMED_TAKEOFF) {
z+=2; z += 2;
// Determine running altitude
maxz = GetAircraftFlyingAltitude(v); maxz = GetAircraftFlyingAltitude(v);
if (z > maxz) if (z > maxz) z = maxz;
z = maxz;
} }
if (amd->flag & AMED_LAND) { if (amd->flag & AMED_LAND) {
@ -969,7 +939,7 @@ static bool AircraftController(Vehicle *v)
if (curz > z) { if (curz > z) {
z++; z++;
} else { } else {
int t = max(1, dist-4); int t = max(1, dist - 4);
z -= ((z - curz) + t - 1) / t; z -= ((z - curz) + t - 1) / t;
if (z < curz) z = curz; if (z < curz) z = curz;
@ -980,11 +950,13 @@ static bool AircraftController(Vehicle *v)
if (amd->flag & AMED_BRAKE) { if (amd->flag & AMED_BRAKE) {
curz = GetSlopeZ(x, y) + 1; curz = GetSlopeZ(x, y) + 1;
if (z > curz) z--; if (z > curz) {
else if (z < curz) z++; z--;
} else if (z < curz) {
z++;
}
if (dist < 64 && v->cur_speed > 12) if (dist < 64 && v->cur_speed > 12) v->cur_speed -= 4;
v->cur_speed -= 4;
} }
SetAircraftPosition(v, gp.x, gp.y, z); SetAircraftPosition(v, gp.x, gp.y, z);
@ -1061,8 +1033,7 @@ static const int8 _aircraft_smoke_xy[16] = {
static void HandleAircraftSmoke(Vehicle *v) static void HandleAircraftSmoke(Vehicle *v)
{ {
if (!(v->vehstatus&VS_AIRCRAFT_BROKEN)) if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
return;
if (v->cur_speed < 10) { if (v->cur_speed < 10) {
v->vehstatus &= ~VS_AIRCRAFT_BROKEN; v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
@ -1098,8 +1069,7 @@ static void ProcessAircraftOrder(Vehicle *v)
v->cur_order_index++; v->cur_order_index++;
} }
if (v->cur_order_index >= v->num_orders) if (v->cur_order_index >= v->num_orders) v->cur_order_index = 0;
v->cur_order_index = 0;
order = GetVehicleOrder(v, v->cur_order_index); order = GetVehicleOrder(v, v->cur_order_index);
@ -1132,18 +1102,12 @@ static void ProcessAircraftOrder(Vehicle *v)
static void HandleAircraftLoading(Vehicle *v, int mode) static void HandleAircraftLoading(Vehicle *v, int mode)
{ {
if (v->current_order.type == OT_NOTHING) if (v->current_order.type == OT_NOTHING) return;
return;
if (v->current_order.type != OT_DUMMY) { if (v->current_order.type != OT_DUMMY) {
if (v->current_order.type != OT_LOADING) if (v->current_order.type != OT_LOADING) return;
return; if (mode != 0) return;
if (--v->load_unload_time_rem != 0) return;
if (mode != 0)
return;
if (--v->load_unload_time_rem)
return;
if (v->current_order.flags & OF_FULL_LOAD && CanFillVehicle(v)) { if (v->current_order.flags & OF_FULL_LOAD && CanFillVehicle(v)) {
SET_EXPENSES_TYPE(EXPENSES_AIRCRAFT_INC); SET_EXPENSES_TYPE(EXPENSES_AIRCRAFT_INC);
@ -1155,8 +1119,7 @@ static void HandleAircraftLoading(Vehicle *v, int mode)
Order b = v->current_order; Order b = v->current_order;
v->current_order.type = OT_NOTHING; v->current_order.type = OT_NOTHING;
v->current_order.flags = 0; v->current_order.flags = 0;
if (!(b.flags & OF_NON_STOP)) if (!(b.flags & OF_NON_STOP)) return;
return;
} }
} }
v->cur_order_index++; v->cur_order_index++;
@ -1183,7 +1146,7 @@ static void CrashAirplane(Vehicle *v)
v->cargo_count = 0; v->cargo_count = 0;
v->next->cargo_count = 0, v->next->cargo_count = 0,
st = GetStation(v->u.air.targetairport); st = GetStation(v->u.air.targetairport);
if(st->airport_tile==0) { if (st->airport_tile == 0) {
newsitem = STR_PLANE_CRASH_OUT_OF_FUEL; newsitem = STR_PLANE_CRASH_OUT_OF_FUEL;
} else { } else {
SetDParam(1, st->index); SetDParam(1, st->index);
@ -1230,8 +1193,7 @@ static void AircraftEntersTerminal(Vehicle *v)
Station *st; Station *st;
Order old_order; Order old_order;
if (v->current_order.type == OT_GOTO_DEPOT) if (v->current_order.type == OT_GOTO_DEPOT) return;
return;
st = GetStation(v->u.air.targetairport); st = GetStation(v->u.air.targetairport);
v->last_station_visited = v->u.air.targetairport; v->last_station_visited = v->u.air.targetairport;
@ -1267,7 +1229,7 @@ static void AircraftEntersTerminal(Vehicle *v)
InvalidateWindowClasses(WC_AIRCRAFT_LIST); InvalidateWindowClasses(WC_AIRCRAFT_LIST);
} }
static bool ValidateAircraftInHangar( uint data_a, uint data_b ) static bool ValidateAircraftInHangar(uint data_a, uint data_b)
{ {
const Vehicle* v = GetVehicle(data_a); const Vehicle* v = GetVehicle(data_a);
@ -1348,7 +1310,8 @@ static void AircraftLeaveHangar(Vehicle *v)
u->vehstatus &= ~VS_HIDDEN; u->vehstatus &= ~VS_HIDDEN;
// Rotor blades // Rotor blades
if ((u=u->next) != NULL) { u = u->next;
if (u != NULL) {
u->vehstatus &= ~VS_HIDDEN; u->vehstatus &= ~VS_HIDDEN;
u->cur_speed = 80; u->cur_speed = 80;
} }
@ -1452,10 +1415,11 @@ static void AircraftEventHandler_AtTerminal(Vehicle *v, const AirportFTAClass *A
v->u.air.state = (v->subtype != 0) ? TAKEOFF : HELITAKEOFF; v->u.air.state = (v->subtype != 0) ? TAKEOFF : HELITAKEOFF;
break; break;
case OT_GOTO_DEPOT: // visit hangar for serivicing, sale, etc. case OT_GOTO_DEPOT: // visit hangar for serivicing, sale, etc.
if (v->current_order.station == v->u.air.targetairport) if (v->current_order.station == v->u.air.targetairport) {
v->u.air.state = HANGAR; v->u.air.state = HANGAR;
else } else {
v->u.air.state = (v->subtype != 0) ? TAKEOFF : HELITAKEOFF; v->u.air.state = (v->subtype != 0) ? TAKEOFF : HELITAKEOFF;
}
break; break;
default: // orders have been deleted (no orders), goto depot and don't bother us default: // orders have been deleted (no orders), goto depot and don't bother us
v->current_order.type = OT_NOTHING; v->current_order.type = OT_NOTHING;
@ -1498,8 +1462,10 @@ static void AircraftEventHandler_HeliTakeOff(Vehicle *v, const AirportFTAClass *
AircraftNextAirportPos_and_Order(v); AircraftNextAirportPos_and_Order(v);
// check if the aircraft needs to be replaced or renewed and send it to a hangar if needed // check if the aircraft needs to be replaced or renewed and send it to a hangar if needed
if ((v->owner == _local_player && p->engine_replacement[v->engine_type] != INVALID_ENGINE) || if (v->owner == _local_player && (
(v->owner == _local_player && p->engine_renew && v->age - v->max_age > (p->engine_renew_months * 30))) { p->engine_replacement[v->engine_type] != INVALID_ENGINE ||
(p->engine_renew && v->age - v->max_age > p->engine_renew_months * 30)
)) {
_current_player = _local_player; _current_player = _local_player;
DoCommandP(v->tile, v->index, 1, NULL, CMD_SEND_AIRCRAFT_TO_HANGAR | CMD_SHOW_NO_ERROR); DoCommandP(v->tile, v->index, 1, NULL, CMD_SEND_AIRCRAFT_TO_HANGAR | CMD_SHOW_NO_ERROR);
_current_player = OWNER_NONE; _current_player = OWNER_NONE;
@ -1519,9 +1485,9 @@ static void AircraftEventHandler_Flying(Vehicle *v, const AirportFTAClass *Airpo
// all other airports --> all types of flying devices (ALL) // all other airports --> all types of flying devices (ALL)
// heliport/oilrig, etc --> no airplanes (HELICOPTERS_ONLY) // heliport/oilrig, etc --> no airplanes (HELICOPTERS_ONLY)
// runway busy or not allowed to use this airstation, circle // runway busy or not allowed to use this airstation, circle
if (! (v->subtype == Airport->acc_planes || if (v->subtype != Airport->acc_planes &&
st->airport_tile == 0 || (st->owner != OWNER_NONE && st->owner != v->owner) )) { st->airport_tile != 0 &&
(st->owner == OWNER_NONE || st->owner == v->owner)) {
// {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41}, // {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
// if it is an airplane, look for LANDING, for helicopter HELILANDING // if it is an airplane, look for LANDING, for helicopter HELILANDING
// it is possible to choose from multiple landing runways, so loop until a free one is found // it is possible to choose from multiple landing runways, so loop until a free one is found
@ -1636,10 +1602,10 @@ static AircraftStateHandler * const _aircraft_state_handlers[] = {
static void AirportClearBlock(const Vehicle* v, const AirportFTAClass* Airport) static void AirportClearBlock(const Vehicle* v, const AirportFTAClass* Airport)
{ {
Station *st;
// we have left the previous block, and entered the new one. Free the previous block // we have left the previous block, and entered the new one. Free the previous block
if (Airport->layout[v->u.air.previous_pos].block != Airport->layout[v->u.air.pos].block) { if (Airport->layout[v->u.air.previous_pos].block != Airport->layout[v->u.air.pos].block) {
st = GetStation(v->u.air.targetairport); Station* st = GetStation(v->u.air.targetairport);
CLRBITS(st->airport_flags, Airport->layout[v->u.air.previous_pos].block); CLRBITS(st->airport_flags, Airport->layout[v->u.air.previous_pos].block);
} }
} }
@ -1689,10 +1655,10 @@ static bool AirportMove(Vehicle *v, const AirportFTAClass *Airport)
// matches our heading // matches our heading
do { do {
if (v->u.air.state == current->heading || current->heading == TO_ALL) { if (v->u.air.state == current->heading || current->heading == TO_ALL) {
if (AirportSetBlocks(v, current, Airport)) { if (AirportSetBlocks(v, current, Airport)) {
v->u.air.pos = current->next_position; v->u.air.pos = current->next_position;
} // move to next position } // move to next position
return retval; return retval;
} }
current = current->next_in_chain; current = current->next_in_chain;
} while (current != NULL); } while (current != NULL);
@ -1731,16 +1697,15 @@ static bool AirportHasBlock(Vehicle *v, AirportFTA *current_pos, const AirportFT
// returns true on success. Eg, next block was free and we have occupied it // returns true on success. Eg, next block was free and we have occupied it
static bool AirportSetBlocks(Vehicle *v, AirportFTA *current_pos, const AirportFTAClass *Airport) static bool AirportSetBlocks(Vehicle *v, AirportFTA *current_pos, const AirportFTAClass *Airport)
{ {
Station *st; AirportFTA* next = &Airport->layout[current_pos->next_position];
uint32 airport_flags; AirportFTA* reference = &Airport->layout[v->u.air.pos];
AirportFTA *current, *reference, *next; AirportFTA* current;
next = &Airport->layout[current_pos->next_position];
reference = &Airport->layout[v->u.air.pos];
// if the next position is in another block, check it and wait until it is free // if the next position is in another block, check it and wait until it is free
if (Airport->layout[current_pos->position].block != next->block) { if (Airport->layout[current_pos->position].block != next->block) {
airport_flags = next->block; uint32 airport_flags = next->block;
st = GetStation(v->u.air.targetairport); Station* st = GetStation(v->u.air.targetairport);
//search for all all elements in the list with the same state, and blocks != N //search for all all elements in the list with the same state, and blocks != N
// this means more blocks should be checked/set // this means more blocks should be checked/set
current = current_pos; current = current_pos;
@ -1784,12 +1749,12 @@ static bool FreeTerminal(Vehicle *v, byte i, byte last_terminal)
return false; return false;
} }
static int GetNumTerminals(const AirportFTAClass *Airport) static uint GetNumTerminals(const AirportFTAClass *Airport)
{ {
int i, num = 0; uint num = 0;
uint i;
for (i = Airport->terminals[0]; i > 0; i--) for (i = Airport->terminals[0]; i > 0; i--) num += Airport->terminals[i];
num += Airport->terminals[i];
return num; return num;
} }
@ -1846,12 +1811,12 @@ static bool AirportFindFreeTerminal(Vehicle *v, const AirportFTAClass *Airport)
return FreeTerminal(v, 0, GetNumTerminals(Airport)); return FreeTerminal(v, 0, GetNumTerminals(Airport));
} }
static int GetNumHelipads(const AirportFTAClass *Airport) static uint GetNumHelipads(const AirportFTAClass *Airport)
{ {
int i, num = 0; uint num = 0;
uint i;
for (i = Airport->helipads[0]; i > 0; i--) for (i = Airport->helipads[0]; i > 0; i--) num += Airport->helipads[i];
num += Airport->helipads[i];
return num; return num;
} }
@ -1914,9 +1879,7 @@ static void AircraftEventHandler(Vehicle *v, int loop)
return; return;
} }
/* exit if aircraft is stopped */ if (v->vehstatus & VS_STOPPED) return;
if (v->vehstatus & VS_STOPPED)
return;
/* aircraft is broken down? */ /* aircraft is broken down? */
if (v->breakdown_ctr != 0) { if (v->breakdown_ctr != 0) {
@ -1931,8 +1894,7 @@ static void AircraftEventHandler(Vehicle *v, int loop)
ProcessAircraftOrder(v); ProcessAircraftOrder(v);
HandleAircraftLoading(v, loop); HandleAircraftLoading(v, loop);
if (v->current_order.type >= OT_LOADING) if (v->current_order.type >= OT_LOADING) return;
return;
// pass the right airport structure to the functions // pass the right airport structure to the functions
// DEREF_STATION gets target airport (Station *st), its type is passed to GetAirport // DEREF_STATION gets target airport (Station *st), its type is passed to GetAirport
@ -1944,24 +1906,22 @@ void Aircraft_Tick(Vehicle *v)
{ {
int i; int i;
if (v->subtype > 2) if (v->subtype > 2) return;
return;
if (v->subtype == 0) if (v->subtype == 0) HelicopterTickHandler(v);
HelicopterTickHandler(v);
AgeAircraftCargo(v); AgeAircraftCargo(v);
for(i=0; i!=6; i++) { for (i = 0; i != 6; i++) {
AircraftEventHandler(v, i); AircraftEventHandler(v, i);
if (v->type != VEH_Aircraft) // In case it was deleted if (v->type != VEH_Aircraft) // In case it was deleted
break; break;
} }
} }
void UpdateOilRig( void ) void UpdateOilRig(void)
{ {
Station *st; Station* st;
FOR_ALL_STATIONS(st) { FOR_ALL_STATIONS(st) {
if (st->airport_type == 5) st->airport_type = AT_OILRIG; if (st->airport_type == 5) st->airport_type = AT_OILRIG;
@ -1987,7 +1947,7 @@ void UpdateOldAircraft(void)
// skip those // skip those
if (v_oldstyle->type == VEH_Aircraft && v_oldstyle->subtype <= 2) { if (v_oldstyle->type == VEH_Aircraft && v_oldstyle->subtype <= 2) {
// airplane in terminal stopped doesn't hurt anyone, so goto next // airplane in terminal stopped doesn't hurt anyone, so goto next
if ((v_oldstyle->vehstatus & VS_STOPPED) && (v_oldstyle->u.air.state == 0)) { if (v_oldstyle->vehstatus & VS_STOPPED && v_oldstyle->u.air.state == 0) {
v_oldstyle->u.air.state = HANGAR; v_oldstyle->u.air.state = HANGAR;
continue; continue;
} }

View File

@ -65,13 +65,11 @@ static void DrawAircraftImage(const Vehicle *v, int x, int y, VehicleID selectio
{ {
int image = GetAircraftImage(v, 6); int image = GetAircraftImage(v, 6);
uint32 ormod = SPRITE_PALETTE(PLAYER_SPRITE_COLOR(v->owner)); uint32 ormod = SPRITE_PALETTE(PLAYER_SPRITE_COLOR(v->owner));
if (v->vehstatus & VS_CRASHED) if (v->vehstatus & VS_CRASHED) ormod = PALETTE_CRASH;
ormod = PALETTE_CRASH; DrawSprite(image | ormod, x + 25, y + 10);
DrawSprite(image | ormod, x+25, y+10); if (v->subtype == 0) DrawSprite(SPR_ROTOR_STOPPED, x + 25, y + 5);
if (v->subtype == 0)
DrawSprite(SPR_ROTOR_STOPPED, x + 25, y + 5);
if (v->index == selection) { if (v->index == selection) {
DrawFrameRect(x-1, y-1, x+58, y+21, 0xF, FR_BORDERONLY); DrawFrameRect(x - 1, y - 1, x + 58, y + 21, 0xF, FR_BORDERONLY);
} }
} }
@ -90,20 +88,14 @@ void CcBuildAircraft(bool success, TileIndex tile, uint32 p1, uint32 p2)
void CcCloneAircraft(bool success, uint tile, uint32 p1, uint32 p2) void CcCloneAircraft(bool success, uint tile, uint32 p1, uint32 p2)
{ {
if (success) { if (success) ShowAircraftViewWindow(GetVehicle(_new_aircraft_id));
const Vehicle* v = GetVehicle(_new_aircraft_id);
ShowAircraftViewWindow(v);
}
} }
static void NewAircraftWndProc(Window *w, WindowEvent *e) static void NewAircraftWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
if (w->window_number == 0) if (w->window_number == 0) SETBIT(w->disabled_state, 5);
SETBIT(w->disabled_state, 5);
{ {
int count = 0; int count = 0;
@ -111,8 +103,7 @@ static void NewAircraftWndProc(Window *w, WindowEvent *e)
const Engine* e = GetEngine(AIRCRAFT_ENGINES_INDEX); const Engine* e = GetEngine(AIRCRAFT_ENGINES_INDEX);
do { do {
if (HASBIT(e->player_avail, _local_player)) if (HASBIT(e->player_avail, _local_player)) count++;
count++;
} while (++e,--num); } while (++e,--num);
SetVScrollCount(w, count); SetVScrollCount(w, count);
} }
@ -508,7 +499,7 @@ static void AircraftViewWndProc(Window *w, WindowEvent *e)
switch(e->event) { switch(e->event) {
case WE_PAINT: { case WE_PAINT: {
const Vehicle* v = GetVehicle(w->window_number); const Vehicle* v = GetVehicle(w->window_number);
uint32 disabled = 1<<8; uint32 disabled = 1 << 8;
StringID str; StringID str;
{ {
@ -520,8 +511,7 @@ static void AircraftViewWndProc(Window *w, WindowEvent *e)
disabled = 0; disabled = 0;
} }
if (v->owner != _local_player) if (v->owner != _local_player) disabled |= 1 << 8 | 1 << 7;
disabled |= 1<<8 | 1<<7;
w->disabled_state = disabled; w->disabled_state = disabled;
/* draw widgets & caption */ /* draw widgets & caption */
@ -555,8 +545,9 @@ static void AircraftViewWndProc(Window *w, WindowEvent *e)
if (v->num_orders == 0) { if (v->num_orders == 0) {
str = STR_NO_ORDERS + _patches.vehicle_speed; str = STR_NO_ORDERS + _patches.vehicle_speed;
SetDParam(0, v->cur_speed * 8); SetDParam(0, v->cur_speed * 8);
} else } else {
str = STR_EMPTY; str = STR_EMPTY;
}
break; break;
} }
} }
@ -656,9 +647,12 @@ static void DrawAircraftDepotWindow(Window *w)
/* determine amount of items for scroller */ /* determine amount of items for scroller */
num = 0; num = 0;
FOR_ALL_VEHICLES(v) { FOR_ALL_VEHICLES(v) {
if (v->type == VEH_Aircraft && v->subtype <= 2 && v->vehstatus&VS_HIDDEN && if (v->type == VEH_Aircraft &&
v->tile == tile) v->subtype <= 2 &&
num++; v->vehstatus & VS_HIDDEN &&
v->tile == tile) {
num++;
}
} }
SetVScrollCount(w, (num + w->hscroll.cap - 1) / w->hscroll.cap); SetVScrollCount(w, (num + w->hscroll.cap - 1) / w->hscroll.cap);
@ -729,9 +723,12 @@ static void AircraftDepotClickAircraft(Window *w, int x, int y)
int mode = GetVehicleFromAircraftDepotWndPt(w, x, y, &v); int mode = GetVehicleFromAircraftDepotWndPt(w, x, y, &v);
// share / copy orders // share / copy orders
if (_thd.place_mode && mode <= 0) { _place_clicked_vehicle = v; return; } if (_thd.place_mode && mode <= 0) {
_place_clicked_vehicle = v;
return;
}
switch(mode) { switch (mode) {
case 1: case 1:
return; return;
@ -789,30 +786,31 @@ static void AircraftDepotWndProc(Window *w, WindowEvent *e)
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch(e->click.widget) {
case 5: /* click aircraft */ case 5: /* click aircraft */
AircraftDepotClickAircraft(w, e->click.pt.x, e->click.pt.y); AircraftDepotClickAircraft(w, e->click.pt.x, e->click.pt.y);
break; break;
case 7: /* show build aircraft window */
ResetObjectToPlace();
ShowBuildAircraftWindow(w->window_number);
break;
case 8: /* clone button */ case 7: /* show build aircraft window */
InvalidateWidget(w, 8);
TOGGLEBIT(w->click_state, 8);
if (HASBIT(w->click_state, 8)) {
_place_clicked_vehicle = NULL;
SetObjectToPlaceWnd(SPR_CURSOR_CLONE, VHM_RECT, w);
} else {
ResetObjectToPlace(); ResetObjectToPlace();
} ShowBuildAircraftWindow(w->window_number);
break; break;
case 9: /* scroll to tile */ case 8: /* clone button */
ResetObjectToPlace(); InvalidateWidget(w, 8);
ScrollMainWindowToTile(w->window_number); TOGGLEBIT(w->click_state, 8);
break;
if (HASBIT(w->click_state, 8)) {
_place_clicked_vehicle = NULL;
SetObjectToPlaceWnd(SPR_CURSOR_CLONE, VHM_RECT, w);
} else {
ResetObjectToPlace();
}
break;
case 9: /* scroll to tile */
ResetObjectToPlace();
ScrollMainWindowToTile(w->window_number);
break;
} }
break; break;
@ -920,7 +918,7 @@ void ShowAircraftDepotWindow(TileIndex tile)
Window *w; Window *w;
w = AllocateWindowDescFront(&_aircraft_depot_desc, tile); w = AllocateWindowDescFront(&_aircraft_depot_desc, tile);
if (w) { if (w != NULL) {
w->caption_color = GetTileOwner(tile); w->caption_color = GetTileOwner(tile);
w->vscroll.cap = 2; w->vscroll.cap = 2;
w->hscroll.cap = 4; w->hscroll.cap = 4;
@ -950,8 +948,7 @@ static void DrawSmallOrderList(const Vehicle *v, int x, int y) {
DrawString(x, y, STR_A036, 0); DrawString(x, y, STR_A036, 0);
y += 6; y += 6;
if (++i == 4) if (++i == 4) break;
break;
} }
} }
} }
@ -1008,8 +1005,7 @@ static void PlayerAircraftWndProc(Window *w, WindowEvent *e)
SetVScrollCount(w, vl->list_length); SetVScrollCount(w, vl->list_length);
// disable 'Sort By' tooltip on Unsorted sorting criteria // disable 'Sort By' tooltip on Unsorted sorting criteria
if (vl->sort_type == SORT_BY_UNSORTED) if (vl->sort_type == SORT_BY_UNSORTED) w->disabled_state |= (1 << 3);
w->disabled_state |= (1 << 3);
/* draw the widgets */ /* draw the widgets */
{ {
@ -1137,8 +1133,7 @@ static void PlayerAircraftWndProc(Window *w, WindowEvent *e)
_sorting.aircraft.criteria = vl->sort_type; _sorting.aircraft.criteria = vl->sort_type;
// enable 'Sort By' if a sorter criteria is chosen // enable 'Sort By' if a sorter criteria is chosen
if (vl->sort_type != SORT_BY_UNSORTED) if (vl->sort_type != SORT_BY_UNSORTED) CLRBIT(w->disabled_state, 3);
CLRBIT(w->disabled_state, 3);
} }
SetWindowDirty(w); SetWindowDirty(w);
break; break;
@ -1198,7 +1193,7 @@ void ShowPlayerAircraft(PlayerID player, StationID station)
w = AllocateWindowDescFront(&_other_player_aircraft_desc, (station << 16) | player); w = AllocateWindowDescFront(&_other_player_aircraft_desc, (station << 16) | player);
} }
if (w) { if (w != NULL) {
w->caption_color = w->window_number; w->caption_color = w->window_number;
w->vscroll.cap = 4; w->vscroll.cap = 4;
w->widget[7].unkA = (w->vscroll.cap << 8) + 1; w->widget[7].unkA = (w->vscroll.cap << 8) + 1;

View File

@ -376,7 +376,7 @@ uint32 GetValidAirports(void)
// 1980-1-1 is --> 21915 // 1980-1-1 is --> 21915
// 1990-1-1 is --> 25568 // 1990-1-1 is --> 25568
if (_date >= 21915) {SETBIT(bytemask, 3);} // metropilitan airport 1980 if (_date >= 21915) SETBIT(bytemask, 3); // metropilitan airport 1980
if (_date >= 25568) {SETBIT(bytemask, 4);} // international airport 1990 if (_date >= 25568) SETBIT(bytemask, 4); // international airport 1990
return bytemask; return bytemask;
} }

View File

@ -65,7 +65,7 @@ static OnButtonClick * const _build_air_button_proc[] = {
static void BuildAirToolbWndProc(Window *w, WindowEvent *e) static void BuildAirToolbWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
DrawWindowWidgets(w); DrawWindowWidgets(w);
break; break;
@ -156,9 +156,9 @@ static void BuildAirportPickerWndProc(Window *w, WindowEvent *e)
if (!HASBIT(avail_airports, 0) && sel == AT_SMALL) sel = AT_LARGE; if (!HASBIT(avail_airports, 0) && sel == AT_SMALL) sel = AT_LARGE;
if (!HASBIT(avail_airports, 1) && sel == AT_LARGE) sel = AT_SMALL; if (!HASBIT(avail_airports, 1) && sel == AT_LARGE) sel = AT_SMALL;
/* 'Country Airport' starts at widget 3, and if its bit is set, it is available, /* 'Country Airport' starts at widget 3, and if its bit is set, it is
* so take its opposite value to set the disabled_state. There are only 5 available * available, so take its opposite value to set the disabled_state. There
* airports, so XOr with 0x1F (1 1111) */ * are only 5 available airports, so XOR with 0x1F (1 1111) */
w->disabled_state = (avail_airports ^ 0x1F) << 3; w->disabled_state = (avail_airports ^ 0x1F) << 3;
_selected_airport_type = sel; _selected_airport_type = sel;
@ -177,7 +177,7 @@ static void BuildAirportPickerWndProc(Window *w, WindowEvent *e)
} }
} }
if (_station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad); if (_station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
DrawWindowWidgets(w); DrawWindowWidgets(w);
// strings such as 'Size' and 'Coverage Area' // strings such as 'Size' and 'Coverage Area'
@ -188,7 +188,7 @@ static void BuildAirportPickerWndProc(Window *w, WindowEvent *e)
} }
case WE_CLICK: { case WE_CLICK: {
switch(e->click.widget) { switch (e->click.widget) {
case 3: case 4: case 5: case 6: case 7: case 3: case 4: case 5: case 6: case 7:
_selected_airport_type = e->click.widget - 3; _selected_airport_type = e->click.widget - 3;
SndPlayFx(SND_15_BEEP); SndPlayFx(SND_15_BEEP);
@ -212,8 +212,7 @@ static void BuildAirportPickerWndProc(Window *w, WindowEvent *e)
} break; } break;
case WE_DESTROY: case WE_DESTROY:
if (!WP(w,def_d).close) if (!WP(w,def_d).close) ResetObjectToPlace();
ResetObjectToPlace();
break; break;
} }
} }

View File

@ -33,7 +33,8 @@ void CcBuildBridge(bool success, TileIndex tile, uint32 p1, uint32 p2)
static void BuildBridge(Window *w, int i) static void BuildBridge(Window *w, int i)
{ {
DeleteWindow(w); DeleteWindow(w);
DoCommandP(_bridgedata.end_tile, _bridgedata.start_tile, _bridgedata.indexes[i] | (_bridgedata.type << 8), CcBuildBridge, DoCommandP(_bridgedata.end_tile, _bridgedata.start_tile,
_bridgedata.indexes[i] | (_bridgedata.type << 8), CcBuildBridge,
CMD_BUILD_BRIDGE | CMD_AUTO | CMD_MSG(STR_5015_CAN_T_BUILD_BRIDGE_HERE)); CMD_BUILD_BRIDGE | CMD_AUTO | CMD_MSG(STR_5015_CAN_T_BUILD_BRIDGE_HERE));
} }

View File

@ -37,13 +37,11 @@ static int TerraformAllowTileProcess(TerraformerState *ts, TileIndex tile)
TileIndex *t; TileIndex *t;
int count; int count;
if (TileX(tile) == MapMaxX() || TileY(tile) == MapMaxY()) if (TileX(tile) == MapMaxX() || TileY(tile) == MapMaxY()) return -1;
return -1;
t = ts->tile_table; t = ts->tile_table;
for(count = ts->tile_table_count; count != 0; count--,t++) { for (count = ts->tile_table_count; count != 0; count--, t++) {
if (*t == tile) if (*t == tile) return 0;
return 0;
} }
return 1; return 1;
@ -54,9 +52,8 @@ static int TerraformGetHeightOfTile(TerraformerState *ts, TileIndex tile)
TerraformerHeightMod *mod = ts->modheight; TerraformerHeightMod *mod = ts->modheight;
int count; int count;
for(count = ts->modheight_count; count != 0; count--, mod++) { for (count = ts->modheight_count; count != 0; count--, mod++) {
if (mod->tile == tile) if (mod->tile == tile) return mod->height;
return mod->height;
} }
return TileHeight(tile); return TileHeight(tile);
@ -69,12 +66,10 @@ static void TerraformAddDirtyTile(TerraformerState *ts, TileIndex tile)
count = ts->tile_table_count; count = ts->tile_table_count;
if (count >= 625) if (count >= 625) return;
return;
for(t = ts->tile_table; count != 0; count--,t++) { for(t = ts->tile_table; count != 0; count--,t++) {
if (*t == tile) if (*t == tile) return;
return;
} }
ts->tile_table[ts->tile_table_count++] = tile; ts->tile_table[ts->tile_table_count++] = tile;
@ -116,8 +111,7 @@ static int TerraformProc(TerraformerState *ts, TileIndex tile, int mode)
// If we have a single diagonal track there, the other side of // If we have a single diagonal track there, the other side of
// tile can be terraformed. // tile can be terraformed.
if ((_m[tile].m5&~0x40) == _railway_modes[mode]) if ((_m[tile].m5 & ~0x40) == _railway_modes[mode]) return 0;
return 0;
} }
ret = DoCommandByTile(tile, 0,0, ts->flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR); ret = DoCommandByTile(tile, 0,0, ts->flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR);
@ -129,8 +123,7 @@ static int TerraformProc(TerraformerState *ts, TileIndex tile, int mode)
ts->cost += ret; ts->cost += ret;
if (ts->tile_table_count >= 625) if (ts->tile_table_count >= 625) return -1;
return -1;
ts->tile_table[ts->tile_table_count++] = tile; ts->tile_table[ts->tile_table_count++] = tile;
return 0; return 0;
@ -151,12 +144,10 @@ static bool TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height
_error_message = STR_1004_TOO_HIGH; _error_message = STR_1004_TOO_HIGH;
if (height > 0xF) if (height > 15) return false;
return false;
nh = TerraformGetHeightOfTile(ts, tile); nh = TerraformGetHeightOfTile(ts, tile);
if (nh < 0 || height == nh) if (nh < 0 || height == nh) return false;
return false;
if (TerraformProc(ts, tile, 0) < 0) return false; if (TerraformProc(ts, tile, 0) < 0) return false;
if (TerraformProc(ts, tile + TileDiffXY( 0, -1), 1) < 0) return false; if (TerraformProc(ts, tile + TileDiffXY( 0, -1), 1) < 0) return false;
@ -166,7 +157,7 @@ static bool TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height
mod = ts->modheight; mod = ts->modheight;
count = ts->modheight_count; count = ts->modheight_count;
for(;;) { for (;;) {
if (count == 0) { if (count == 0) {
if (ts->modheight_count >= 576) if (ts->modheight_count >= 576)
return false; return false;
@ -280,8 +271,9 @@ int32 CmdTerraformLand(int x, int y, uint32 flags, uint32 p1, uint32 p2)
t = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 1)); t = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 1));
if (t <= z) z = t; if (t <= z) z = t;
if (!CheckTunnelInWay(tile, z*8)) if (!CheckTunnelInWay(tile, z * 8)) {
return_cmd_error(STR_1002_EXCAVATION_WOULD_DAMAGE); return_cmd_error(STR_1002_EXCAVATION_WOULD_DAMAGE);
}
} }
} }
@ -505,8 +497,7 @@ void DrawClearLandFence(const TileInfo *ti)
if (ti->tileh & 2) { if (ti->tileh & 2) {
z += 8; z += 8;
if (ti->tileh == 0x17) if (ti->tileh == 0x17) z += 8;
z += 8;
} }
if (GB(m4, 5, 3) != 0) { if (GB(m4, 5, 3) != 0) {
@ -697,8 +688,7 @@ static void TileLoopClearAlps(TileIndex tile)
static void TileLoopClearDesert(TileIndex tile) static void TileLoopClearDesert(TileIndex tile)
{ {
if ( (_m[tile].m5 & 0x1C) == 0x14) if ((_m[tile].m5 & 0x1C) == 0x14) return;
return;
if (GetMapExtraBits(tile) == 1) { if (GetMapExtraBits(tile) == 1) {
_m[tile].m5 = 0x17; _m[tile].m5 = 0x17;
@ -727,12 +717,10 @@ static void TileLoop_Clear(TileIndex tile)
} }
m5 = _m[tile].m5; m5 = _m[tile].m5;
if ( (m5 & 0x1C) == 0x10 || (m5 & 0x1C) == 0x14) if ((m5 & 0x1C) == 0x10 || (m5 & 0x1C) == 0x14) return;
return;
if ( (m5 & 0x1C) != 0xC) { if ((m5 & 0x1C) != 0xC) {
if ( (m5 & 3) == 3) if ((m5 & 3) == 3) return;
return;
if (_game_mode != GM_EDITOR) { if (_game_mode != GM_EDITOR) {
m5 += 0x20; m5 += 0x20;

View File

@ -76,12 +76,11 @@ void SetDebugString(const char *s)
v = strtoul(s, &end, 0); v = strtoul(s, &end, 0);
s = end; s = end;
for (i = debug_level; i != endof(debug_level); ++i) for (i = debug_level; i != endof(debug_level); ++i) *i->level = v;
*i->level = v;
} }
// individual levels // individual levels
for(;;) { for (;;) {
const DebugLevel *i; const DebugLevel *i;
int *p; int *p;
@ -103,9 +102,9 @@ void SetDebugString(const char *s)
if (*s == '=') s++; if (*s == '=') s++;
v = strtoul(s, &end, 0); v = strtoul(s, &end, 0);
s = end; s = end;
if (p != NULL) if (p != NULL) {
*p = v; *p = v;
else { } else {
ShowInfoF("Unknown debug level '%.*s'", s - t, t); ShowInfoF("Unknown debug level '%.*s'", s - t, t);
return; return;
} }

View File

@ -21,8 +21,7 @@
static void DisasterClearSquare(TileIndex tile) static void DisasterClearSquare(TileIndex tile)
{ {
if (!EnsureNoVehicle(tile)) if (!EnsureNoVehicle(tile)) return;
return;
switch (GetTileType(tile)) { switch (GetTileType(tile)) {
case MP_RAILWAY: case MP_RAILWAY:
@ -352,7 +351,7 @@ static void DisasterTick_2(Vehicle *v)
v->tick_counter++; v->tick_counter++;
v->u.disaster.image_override = v->u.disaster.image_override =
(v->current_order.station == 1 && v->tick_counter&4) ? SPR_F_15_FIRING : 0; (v->current_order.station == 1 && v->tick_counter & 4) ? SPR_F_15_FIRING : 0;
GetNewVehiclePos(v, &gp); GetNewVehiclePos(v, &gp);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos); SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
@ -423,7 +422,7 @@ static void DisasterTick_3(Vehicle *v)
v->tick_counter++; v->tick_counter++;
v->u.disaster.image_override = v->u.disaster.image_override =
(v->current_order.station == 1 && v->tick_counter&4) ? SPR_AH_64A_FIRING : 0; (v->current_order.station == 1 && v->tick_counter & 4) ? SPR_AH_64A_FIRING : 0;
GetNewVehiclePos(v, &gp); GetNewVehiclePos(v, &gp);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos); SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
@ -843,8 +842,7 @@ static void Disaster4_Init(void)
Vehicle *v = ForceAllocateSpecialVehicle(), *u; Vehicle *v = ForceAllocateSpecialVehicle(), *u;
int x,y; int x,y;
if (v == NULL) if (v == NULL) return;
return;
x = TileX(Random()) * 16 + 8; x = TileX(Random()) * 16 + 8;
@ -870,8 +868,7 @@ static void Disaster5_Init(void)
byte dir; byte dir;
uint32 r; uint32 r;
if (v == NULL) if (v == NULL) return;
return;
r = Random(); r = Random();
x = TileX(r) * 16 + 8; x = TileX(r) * 16 + 8;
@ -891,8 +888,7 @@ static void Disaster6_Init(void)
byte dir; byte dir;
uint32 r; uint32 r;
if (v == NULL) if (v == NULL) return;
return;
r = Random(); r = Random();
x = TileX(r) * 16 + 8; x = TileX(r) * 16 + 8;
@ -964,18 +960,17 @@ static const DisasterYears _dis_years[8] = {
static void DoDisaster(void) static void DoDisaster(void)
{ {
byte buf[8]; byte buf[lengthof(_dis_years)];
byte year = _cur_year; byte year = _cur_year;
int i,j; uint i;
uint j;
for(i=j=0; i!=lengthof(_dis_years); i++) { j = 0;
if (year >= _dis_years[i].min && for (i = 0; i != lengthof(_dis_years); i++) {
year < _dis_years[i].max) if (year >= _dis_years[i].min && year < _dis_years[i].max) buf[j++] = i;
buf[j++] = i;
} }
if (j == 0) if (j == 0) return;
return;
_disaster_initprocs[buf[RandomRange(j)]](); _disaster_initprocs[buf[RandomRange(j)]]();
} }
@ -988,13 +983,11 @@ static void ResetDisasterDelay(void)
void DisasterDailyLoop(void) void DisasterDailyLoop(void)
{ {
if (--_disaster_delay != 0) if (--_disaster_delay != 0) return;
return;
ResetDisasterDelay(); ResetDisasterDelay();
if (_opt.diff.disasters != 0) if (_opt.diff.disasters != 0) DoDisaster();
DoDisaster();
} }
void StartupDisasters(void) void StartupDisasters(void)

View File

@ -222,35 +222,39 @@ void ShowBuildDocksToolbar(void)
static void BuildDockStationWndProc(Window *w, WindowEvent *e) static void BuildDockStationWndProc(Window *w, WindowEvent *e)
{ {
int rad; switch (e->event) {
switch(e->event) {
case WE_PAINT: { case WE_PAINT: {
if (WP(w,def_d).close) int rad;
return;
if (WP(w,def_d).close) return;
w->click_state = (1<<3) << _station_show_coverage; w->click_state = (1<<3) << _station_show_coverage;
DrawWindowWidgets(w); DrawWindowWidgets(w);
rad = (_patches.modified_catchment) ? CA_DOCK : 4; rad = (_patches.modified_catchment) ? CA_DOCK : 4;
if (_station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad); if (_station_show_coverage) {
else SetTileSelectBigSize(0, 0, 0, 0); SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
} else {
SetTileSelectBigSize(0, 0, 0, 0);
}
DrawStringCentered(74, 17, STR_3066_COVERAGE_AREA_HIGHLIGHT, 0); DrawStringCentered(74, 17, STR_3066_COVERAGE_AREA_HIGHLIGHT, 0);
DrawStationCoverageAreaText(4, 50, (uint)-1, rad); DrawStationCoverageAreaText(4, 50, (uint)-1, rad);
} break; break;
}
case WE_CLICK: { case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 3: case 4: case 3:
_station_show_coverage = e->click.widget - 3; case 4:
SndPlayFx(SND_15_BEEP); _station_show_coverage = e->click.widget - 3;
SetWindowDirty(w); SndPlayFx(SND_15_BEEP);
break; SetWindowDirty(w);
break;
} }
} break; break;
case WE_MOUSELOOP: { case WE_MOUSELOOP:
if (WP(w,def_d).close) { if (WP(w,def_d).close) {
DeleteWindow(w); DeleteWindow(w);
return; return;
@ -258,11 +262,9 @@ static void BuildDockStationWndProc(Window *w, WindowEvent *e)
CheckRedrawStationCoverage(w); CheckRedrawStationCoverage(w);
break; break;
}
case WE_DESTROY: case WE_DESTROY:
if (!WP(w,def_d).close) if (!WP(w,def_d).close) ResetObjectToPlace();
ResetObjectToPlace();
break; break;
} }
} }
@ -324,13 +326,11 @@ static void BuildDocksDepotWndProc(Window *w, WindowEvent *e)
} break; } break;
case WE_MOUSELOOP: case WE_MOUSELOOP:
if (WP(w,def_d).close) if (WP(w,def_d).close) DeleteWindow(w);
DeleteWindow(w);
break; break;
case WE_DESTROY: case WE_DESTROY:
if (!WP(w,def_d).close) if (!WP(w,def_d).close) ResetObjectToPlace();
ResetObjectToPlace();
break; break;
} }
} }

View File

@ -72,7 +72,7 @@ void UpdatePlayerHouse(Player *p, uint score)
MarkTileDirtyByTile(tile + TileDiffXY(1, 1)); MarkTileDirtyByTile(tile + TileDiffXY(1, 1));
} }
int64 CalculateCompanyValue(const Player *p) int64 CalculateCompanyValue(const Player* p)
{ {
PlayerID owner = p->index; PlayerID owner = p->index;
int64 value; int64 value;
@ -647,8 +647,8 @@ static void AddInflation(void)
int i; int i;
int32 inf = _economy.infl_amount * 54; int32 inf = _economy.infl_amount * 54;
for(i=0; i!=NUM_PRICES; i++) { for (i = 0; i != NUM_PRICES; i++) {
AddSingleInflation( (int32*)&_price + i, _price_frac + i, inf ); AddSingleInflation((int32*)&_price + i, _price_frac + i, inf);
} }
_economy.max_loan_unround += BIGMULUS(_economy.max_loan_unround, inf, 16); _economy.max_loan_unround += BIGMULUS(_economy.max_loan_unround, inf, 16);
@ -657,7 +657,7 @@ static void AddInflation(void)
_economy.max_loan += 50000; _economy.max_loan += 50000;
inf = _economy.infl_amount_pr * 54; inf = _economy.infl_amount_pr * 54;
for(i=0; i!=NUM_CARGO; i++) { for (i = 0; i != NUM_CARGO; i++) {
AddSingleInflation( AddSingleInflation(
(int32*)_cargo_payment_rates + i, (int32*)_cargo_payment_rates + i,
_cargo_payment_rates_frac + i, _cargo_payment_rates_frac + i,
@ -677,8 +677,7 @@ static void PlayersPayInterest(void)
int interest = _economy.interest_rate * 54; int interest = _economy.interest_rate * 54;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (!p->is_active) if (!p->is_active) continue;
continue;
_current_player = p->index; _current_player = p->index;
SET_EXPENSES_TYPE(EXPENSES_LOAN_INT); SET_EXPENSES_TYPE(EXPENSES_LOAN_INT);
@ -692,8 +691,7 @@ static void PlayersPayInterest(void)
static void HandleEconomyFluctuations(void) static void HandleEconomyFluctuations(void)
{ {
if (_opt.diff.economy == 0) if (_opt.diff.economy == 0) return;
return;
if (--_economy.fluct == 0) { if (--_economy.fluct == 0) {
_economy.fluct = - (int)(Random()&3); _economy.fluct = - (int)(Random()&3);
@ -985,9 +983,8 @@ static bool CheckSubsidyDuplicate(Subsidy *s)
{ {
const Subsidy* ss; const Subsidy* ss;
for(ss=_subsidies; ss != endof(_subsidies); ss++) { for (ss = _subsidies; ss != endof(_subsidies); ss++) {
if (s != ss && if (s != ss &&
// ss->age < 12 &&
ss->from == s->from && ss->from == s->from &&
ss->to == s->to && ss->to == s->to &&
ss->cargo_type == s->cargo_type) { ss->cargo_type == s->cargo_type) {
@ -1333,7 +1330,6 @@ int LoadUnloadVehicle(Vehicle *v)
int result = 0; int result = 0;
uint16 last_visited; uint16 last_visited;
Station *st; Station *st;
GoodsEntry *ge;
int t; int t;
uint count, cap; uint count, cap;
PlayerID old_player; PlayerID old_player;
@ -1349,13 +1345,15 @@ int LoadUnloadVehicle(Vehicle *v)
st = GetStation(last_visited = v->last_station_visited); st = GetStation(last_visited = v->last_station_visited);
for (; v != NULL; v = v->next) { for (; v != NULL; v = v->next) {
GoodsEntry* ge;
if (v->cargo_cap == 0) continue; if (v->cargo_cap == 0) continue;
ge = &st->goods[v->cargo_type]; ge = &st->goods[v->cargo_type];
/* unload? */ /* unload? */
if (v->cargo_count != 0) { if (v->cargo_count != 0) {
if ( v->cargo_source != last_visited && ge->waiting_acceptance & 0x8000 && !(u->current_order.flags & OF_TRANSFER) ) { if (v->cargo_source != last_visited && ge->waiting_acceptance & 0x8000 && !(u->current_order.flags & OF_TRANSFER)) {
// deliver goods to the station // deliver goods to the station
st->time_since_unload = 0; st->time_since_unload = 0;
@ -1363,7 +1361,7 @@ int LoadUnloadVehicle(Vehicle *v)
profit += DeliverGoods(v->cargo_count, v->cargo_type, v->cargo_source, last_visited, v->cargo_days); profit += DeliverGoods(v->cargo_count, v->cargo_type, v->cargo_source, last_visited, v->cargo_days);
result |= 1; result |= 1;
v->cargo_count = 0; v->cargo_count = 0;
} else if (u->current_order.flags & ( OF_UNLOAD | OF_TRANSFER) ) { } else if (u->current_order.flags & (OF_UNLOAD | OF_TRANSFER)) {
/* unload goods and let it wait at the station */ /* unload goods and let it wait at the station */
st->time_since_unload = 0; st->time_since_unload = 0;

View File

@ -883,8 +883,7 @@ void EnginesDailyLoop(void)
} else { } else {
e->flags |= ENGINE_PREVIEWING; e->flags |= ENGINE_PREVIEWING;
e->preview_wait = 20; e->preview_wait = 20;
if (IS_INTERACTIVE_PLAYER(best_player)) if (IS_INTERACTIVE_PLAYER(best_player)) ShowEnginePreviewWindow(i);
ShowEnginePreviewWindow(i);
} }
} }
} }
@ -925,12 +924,11 @@ static void NewVehicleAvailable(Engine *e)
// In case the player didn't build the vehicle during the intro period, // In case the player didn't build the vehicle during the intro period,
// prevent that player from getting future intro periods for a while. // prevent that player from getting future intro periods for a while.
if (e->flags&ENGINE_INTRODUCING) { if (e->flags & ENGINE_INTRODUCING) {
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
uint block_preview = p->block_preview; uint block_preview = p->block_preview;
if (!HASBIT(e->player_avail,p->index)) if (!HASBIT(e->player_avail, p->index)) continue;
continue;
/* We assume the user did NOT build it.. prove me wrong ;) */ /* We assume the user did NOT build it.. prove me wrong ;) */
p->block_preview = 20; p->block_preview = 20;
@ -956,8 +954,7 @@ static void NewVehicleAvailable(Engine *e)
e->player_avail = (byte)-1; e->player_avail = (byte)-1;
// Do not introduce new rail wagons // Do not introduce new rail wagons
if (IsWagon(index)) if (IsWagon(index)) return;
return;
// make maglev / monorail available // make maglev / monorail available
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {

View File

@ -65,12 +65,11 @@ static const DrawEngineInfo _draw_engine_list[4] = {
static void EnginePreviewWndProc(Window *w, WindowEvent *e) static void EnginePreviewWndProc(Window *w, WindowEvent *e)
{ {
const DrawEngineInfo *dei; switch (e->event) {
int width;
switch(e->event) {
case WE_PAINT: { case WE_PAINT: {
EngineID engine = w->window_number; EngineID engine = w->window_number;
const DrawEngineInfo* dei;
int width;
DrawWindowWidgets(w); DrawWindowWidgets(w);
@ -91,12 +90,15 @@ static void EnginePreviewWndProc(Window *w, WindowEvent *e)
} }
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 3: DeleteWindow(w); break; case 3:
case 4: DeleteWindow(w);
DoCommandP(0, w->window_number, 0, NULL, CMD_WANT_ENGINE_PREVIEW); break;
DeleteWindow(w);
break; case 4:
DoCommandP(0, w->window_number, 0, NULL, CMD_WANT_ENGINE_PREVIEW);
DeleteWindow(w);
break;
} }
break; break;
} }

View File

@ -151,7 +151,7 @@ void InitializeAnimatedTiles(void);
/* tunnelbridge_cmd.c */ /* tunnelbridge_cmd.c */
bool CheckTunnelInWay(TileIndex tile, int z); bool CheckTunnelInWay(TileIndex tile, int z);
bool CheckBridge_Stuff(byte bridge_type, int bridge_len); bool CheckBridge_Stuff(byte bridge_type, uint bridge_len);
uint32 GetBridgeLength(TileIndex begin, TileIndex end); uint32 GetBridgeLength(TileIndex begin, TileIndex end);
int CalcBridgeLenCostFactor(int x); int CalcBridgeLenCostFactor(int x);

3
gfx.c
View File

@ -1994,7 +1994,6 @@ uint16 GetDrawStringPlayerColor(PlayerID player)
{ {
// Get the color for DrawString-subroutines which matches the color // Get the color for DrawString-subroutines which matches the color
// of the player // of the player
if (player == OWNER_SPECTATOR || player == OWNER_SPECTATOR - 1) if (player == OWNER_SPECTATOR || player == OWNER_SPECTATOR - 1) return 1;
return 1;
return (_color_list[_player_colors[player]].window_color_1b) | IS_PALETTE_COLOR; return (_color_list[_player_colors[player]].window_color_1b) | IS_PALETTE_COLOR;
} }

View File

@ -145,7 +145,7 @@ static bool FileMD5(const MD5File file, bool warn)
fclose(f); fclose(f);
md5_finish(&filemd5state, digest); md5_finish(&filemd5state, digest);
return CheckMD5Digest(file, digest, warn); return CheckMD5Digest(file, digest, warn);
} else { // file not found } else { // file not found
return false; return false;
} }
@ -321,11 +321,9 @@ static byte _sprite_page_to_load = 0xFF;
static void LoadSpriteTables(void) static void LoadSpriteTables(void)
{ {
uint load_index = 0; const FileList* files = _use_dos_palette ? &files_dos : &files_win;
uint load_index;
uint i; uint i;
const FileList *files; // list of grf files to be loaded. Either Windows files or DOS files
files = _use_dos_palette? &files_dos : &files_win;
LoadGrfIndexed(files->basic[0].filename, trg1idx, 0); LoadGrfIndexed(files->basic[0].filename, trg1idx, 0);
DupSprite( 2, 130); // non-breaking space medium DupSprite( 2, 130); // non-breaking space medium

View File

@ -224,15 +224,13 @@ static void GraphLegendWndProc(Window *w, WindowEvent *e)
switch(e->event) { switch(e->event) {
case WE_PAINT: case WE_PAINT:
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (!p->is_active) if (!p->is_active) SETBIT(_legend_excludebits, p->index);
SETBIT(_legend_excludebits, p->index);
} }
w->click_state = ((~_legend_excludebits) << 3); w->click_state = (~_legend_excludebits) << 3;
DrawWindowWidgets(w); DrawWindowWidgets(w);
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (!p->is_active) if (!p->is_active) continue;
continue;
DrawPlayerIcon(p->index, 4, 18+p->index*12); DrawPlayerIcon(p->index, 4, 18+p->index*12);
@ -245,7 +243,7 @@ static void GraphLegendWndProc(Window *w, WindowEvent *e)
case WE_CLICK: case WE_CLICK:
if (IS_INT_INSIDE(e->click.widget, 3, 11)) { if (IS_INT_INSIDE(e->click.widget, 3, 11)) {
_legend_excludebits ^= (1 << (e->click.widget-3)); _legend_excludebits ^= (1 << (e->click.widget - 3));
SetWindowDirty(w); SetWindowDirty(w);
InvalidateWindow(WC_INCOME_GRAPH, 0); InvalidateWindow(WC_INCOME_GRAPH, 0);
InvalidateWindow(WC_OPERATING_PROFIT, 0); InvalidateWindow(WC_OPERATING_PROFIT, 0);

View File

@ -31,8 +31,7 @@ void IndustryPoolNewBlock(uint start_item)
{ {
Industry *i; Industry *i;
FOR_ALL_INDUSTRIES_FROM(i, start_item) FOR_ALL_INDUSTRIES_FROM(i, start_item) i->index = start_item++;
i->index = start_item++;
} }
/* Initialize the industry-pool */ /* Initialize the industry-pool */
@ -251,7 +250,7 @@ static const StringID _industry_close_strings[] = {
STR_4833_SUPPLY_PROBLEMS_CAUSE_TO, STR_4833_SUPPLY_PROBLEMS_CAUSE_TO,
STR_4832_ANNOUNCES_IMMINENT_CLOSURE, STR_4832_ANNOUNCES_IMMINENT_CLOSURE,
STR_4832_ANNOUNCES_IMMINENT_CLOSURE, STR_4832_ANNOUNCES_IMMINENT_CLOSURE,
STR_4832_ANNOUNCES_IMMINENT_CLOSURE , STR_4832_ANNOUNCES_IMMINENT_CLOSURE
}; };
@ -260,19 +259,20 @@ static void IndustryDrawTileProc1(const TileInfo *ti)
const DrawIndustrySpec1Struct *d; const DrawIndustrySpec1Struct *d;
uint32 image; uint32 image;
if (!(_m[ti->tile].m1 & 0x80)) if (!(_m[ti->tile].m1 & 0x80)) return;
return;
d = &_draw_industry_spec1[_m[ti->tile].m3]; d = &_draw_industry_spec1[_m[ti->tile].m3];
AddChildSpriteScreen(0x12A7 + d->image_1, d->x, 0); AddChildSpriteScreen(0x12A7 + d->image_1, d->x, 0);
if ( (image = d->image_2) != 0) image = d->image_2;
AddChildSpriteScreen(0x12B0 + image - 1, 8, 41); if (image != 0) AddChildSpriteScreen(0x12B0 + image - 1, 8, 41);
if ( (image = d->image_3) != 0) image = d->image_3;
if (image != 0) {
AddChildSpriteScreen(0x12AC + image - 1, AddChildSpriteScreen(0x12AC + image - 1,
_drawtile_proc1_x[image-1], _drawtile_proc1_y[image-1]); _drawtile_proc1_x[image - 1], _drawtile_proc1_y[image - 1]);
}
} }
static void IndustryDrawTileProc2(const TileInfo *ti) static void IndustryDrawTileProc2(const TileInfo *ti)
@ -285,17 +285,17 @@ static void IndustryDrawTileProc2(const TileInfo *ti)
x = 0; x = 0;
} }
AddChildSpriteScreen(0x129F, 22-x, x+24); AddChildSpriteScreen(0x129F, 22 - x, 24 + x);
AddChildSpriteScreen(0x129E, 6, 0xE); AddChildSpriteScreen(0x129E, 6, 0xE);
} }
static void IndustryDrawTileProc3(const TileInfo *ti) static void IndustryDrawTileProc3(const TileInfo *ti)
{ {
if (_m[ti->tile].m1 & 0x80) { if (_m[ti->tile].m1 & 0x80) {
AddChildSpriteScreen(0x128B, 5, AddChildSpriteScreen(0x128B, 5, _industry_anim_offs_2[_m[ti->tile].m3]);
_industry_anim_offs_2[_m[ti->tile].m3]); } else {
AddChildSpriteScreen(4746, 3, 67);
} }
AddChildSpriteScreen(4746, 3, 67);
} }
static void IndustryDrawTileProc4(const TileInfo *ti) static void IndustryDrawTileProc4(const TileInfo *ti)
@ -309,7 +309,7 @@ static void IndustryDrawTileProc4(const TileInfo *ti)
} }
if (d->image_2 != 0xFF) { if (d->image_2 != 0xFF) {
AddChildSpriteScreen(0x1270, 0x10 - d->image_2*2, 100 + d->image_2); AddChildSpriteScreen(0x1270, 0x10 - d->image_2 * 2, 100 + d->image_2);
} }
AddChildSpriteScreen(0x126E, 7, d->image_3); AddChildSpriteScreen(0x126E, 7, d->image_3);
@ -323,8 +323,8 @@ static void DrawCoalPlantSparkles(const TileInfo *ti)
image = GB(image, 2, 5); image = GB(image, 2, 5);
if (image != 0 && image < 7) { if (image != 0 && image < 7) {
AddChildSpriteScreen(image + 0x806, AddChildSpriteScreen(image + 0x806,
_coal_plant_sparkles_x[image-1], _coal_plant_sparkles_x[image - 1],
_coal_plant_sparkles_y[image-1] _coal_plant_sparkles_y[image - 1]
); );
} }
} }
@ -348,7 +348,7 @@ static void DrawTile_Industry(TileInfo *ti)
/* Pointer to industry */ /* Pointer to industry */
ind = GetIndustry(_m[ti->tile].m2); ind = GetIndustry(_m[ti->tile].m2);
ormod = (ind->color_map+0x307) << PALETTE_SPRITE_START; ormod = (ind->color_map + 0x307) << PALETTE_SPRITE_START;
/* Retrieve pointer to the draw industry tile struct */ /* Retrieve pointer to the draw industry tile struct */
dits = &_industry_draw_tile_data[(ti->map5 << 2) | GB(_m[ti->tile].m1, 0, 2)]; dits = &_industry_draw_tile_data[(ti->map5 << 2) | GB(_m[ti->tile].m1, 0, 2)];
@ -369,13 +369,12 @@ static void DrawTile_Industry(TileInfo *ti)
} }
/* Add industry on top of the ground? */ /* Add industry on top of the ground? */
if ((image = dits->sprite_2) != 0) { image = dits->sprite_2;
if (image != 0) {
if (image & PALETTE_MODIFIER_COLOR && (image & PALETTE_SPRITE_MASK) == 0) if (image & PALETTE_MODIFIER_COLOR && (image & PALETTE_SPRITE_MASK) == 0)
image |= ormod; image |= ormod;
if (_display_opt & DO_TRANS_BUILDINGS) if (_display_opt & DO_TRANS_BUILDINGS) MAKE_TRANSPARENT(image);
MAKE_TRANSPARENT(image);
AddSortableSpriteToDraw(image, AddSortableSpriteToDraw(image,
ti->x | (dits->subtile_xy>>4), ti->x | (dits->subtile_xy>>4),
@ -385,15 +384,12 @@ static void DrawTile_Industry(TileInfo *ti)
dits->dz, dits->dz,
z); z);
if (_display_opt & DO_TRANS_BUILDINGS) if (_display_opt & DO_TRANS_BUILDINGS) return;
return;
} }
/* TTDBUG: strange code here, return if AddSortableSpriteToDraw failed? */ {
{ int proc = dits->proc - 1;
int proc; if (proc >= 0) _industry_draw_tile_procs[proc](ti);
if ((proc=dits->proc-1) >= 0 )
_industry_draw_tile_procs[proc](ti);
} }
} }
@ -451,9 +447,7 @@ static int32 ClearTile_Industry(TileIndex tile, byte flags)
return_cmd_error(STR_4800_IN_THE_WAY); return_cmd_error(STR_4800_IN_THE_WAY);
} }
if (flags & DC_EXEC) { if (flags & DC_EXEC) DeleteIndustry(i);
DeleteIndustry(i);
}
return 0; return 0;
} }
@ -468,20 +462,17 @@ static const byte _industry_min_cargo[] = {
static void TransportIndustryGoods(TileIndex tile) static void TransportIndustryGoods(TileIndex tile)
{ {
Industry *i; Industry* i = GetIndustry(_m[tile].m2);
int type;
uint cw, am; uint cw, am;
byte m5;
i = GetIndustry(_m[tile].m2);
type = i->type;
cw = min(i->cargo_waiting[0], 255); cw = min(i->cargo_waiting[0], 255);
if (cw > _industry_min_cargo[type]/* && i->produced_cargo[0] != 0xFF*/) { if (cw > _industry_min_cargo[i->type]/* && i->produced_cargo[0] != 0xFF*/) {
byte m5;
i->cargo_waiting[0] -= cw; i->cargo_waiting[0] -= cw;
/* fluctuating economy? */ /* fluctuating economy? */
if (_economy.fluct <= 0) cw = (cw + 1) >> 1; if (_economy.fluct <= 0) cw = (cw + 1) / 2;
i->last_mo_production[0] += cw; i->last_mo_production[0] += cw;
@ -494,12 +485,11 @@ static void TransportIndustryGoods(TileIndex tile)
} }
} }
type = i->type;
cw = min(i->cargo_waiting[1], 255); cw = min(i->cargo_waiting[1], 255);
if (cw > _industry_min_cargo[type]) { if (cw > _industry_min_cargo[i->type]) {
i->cargo_waiting[1] -= cw; i->cargo_waiting[1] -= cw;
if (_economy.fluct <= 0) cw = (cw + 1) >> 1; if (_economy.fluct <= 0) cw = (cw + 1) / 2;
i->last_mo_production[1] += cw; i->last_mo_production[1] += cw;
@ -717,7 +707,6 @@ static void MakeIndustryTileBigger(TileIndex tile, byte size)
} }
static void TileLoopIndustryCase161(TileIndex tile) static void TileLoopIndustryCase161(TileIndex tile)
{ {
int dir; int dir;
@ -739,8 +728,7 @@ static void TileLoopIndustryCase161(TileIndex tile)
EV_BUBBLE EV_BUBBLE
); );
if (v != NULL) if (v != NULL) v->u.special.unk2 = dir;
v->u.special.unk2 = dir;
} }
static void TileLoop_Industry(TileIndex tile) static void TileLoop_Industry(TileIndex tile)
@ -752,8 +740,7 @@ static void TileLoop_Industry(TileIndex tile)
return; return;
} }
if (_game_mode == GM_EDITOR) if (_game_mode == GM_EDITOR) return;
return;
TransportIndustryGoods(tile); TransportIndustryGoods(tile);
@ -768,7 +755,7 @@ static void TileLoop_Industry(TileIndex tile)
#define SET_AND_ANIMATE(tile, a, b) { _m[tile].m5 = a; _m[tile].m1 = b; AddAnimatedTile(tile); } #define SET_AND_ANIMATE(tile, a, b) { _m[tile].m5 = a; _m[tile].m1 = b; AddAnimatedTile(tile); }
#define SET_AND_UNANIMATE(tile, a, b) { _m[tile].m5 = a; _m[tile].m1 = b; DeleteAnimatedTile(tile); } #define SET_AND_UNANIMATE(tile, a, b) { _m[tile].m5 = a; _m[tile].m1 = b; DeleteAnimatedTile(tile); }
switch(_m[tile].m5) { switch (_m[tile].m5) {
case 0x18: // coast line at oilrigs case 0x18: // coast line at oilrigs
case 0x19: case 0x19:
case 0x1A: case 0x1A:
@ -819,9 +806,9 @@ static void TileLoop_Industry(TileIndex tile)
} }
break; break;
case 49: { case 49:
CreateEffectVehicleAbove(TileX(tile) * 16 + 6, TileY(tile) * 16 + 6, 43, EV_SMOKE); CreateEffectVehicleAbove(TileX(tile) * 16 + 6, TileY(tile) * 16 + 6, 43, EV_SMOKE);
} break; break;
case 143: { case 143: {
@ -843,9 +830,7 @@ static void TileLoop_Industry(TileIndex tile)
break; break;
case 174: case 174:
if (CHANCE16(1,3)) { if (CHANCE16(1, 3)) AddAnimatedTile(tile);
AddAnimatedTile(tile);
}
break; break;
} }
} }
@ -1030,15 +1015,17 @@ static void ChopLumberMillTrees(Industry *i)
}; };
TileIndex tile = i->xy; TileIndex tile = i->xy;
int dir, a, j; int a;
if ((_m[tile].m1 & 0x80) == 0) if ((_m[tile].m1 & 0x80) == 0) return;
return;
/* search outwards as a rectangular spiral */ /* search outwards as a rectangular spiral */
for(a=1; a!=41; a+=2) { for (a = 1; a != 41; a += 2) {
for(dir=0; dir!=4; dir++) { uint dir;
j = a;
for (dir = 0; dir != 4; dir++) {
int j = a;
do { do {
tile = TILE_MASK(tile); tile = TILE_MASK(tile);
if (IsTileType(tile, MP_TREES)) { if (IsTileType(tile, MP_TREES)) {
@ -1127,10 +1114,11 @@ static void ProduceIndustryGoods(Industry *i)
i->cargo_waiting[0] = min(0xffff, i->cargo_waiting[0] + i->production_rate[0]); i->cargo_waiting[0] = min(0xffff, i->cargo_waiting[0] + i->production_rate[0]);
i->cargo_waiting[1] = min(0xffff, i->cargo_waiting[1] + i->production_rate[1]); i->cargo_waiting[1] = min(0xffff, i->cargo_waiting[1] + i->production_rate[1]);
if (i->type == IT_FARM) if (i->type == IT_FARM) {
MaybePlantFarmField(i); MaybePlantFarmField(i);
else if (i->type == IT_LUMBER_MILL && (i->counter & 0x1FF) == 0) } else if (i->type == IT_LUMBER_MILL && (i->counter & 0x1FF) == 0) {
ChopLumberMillTrees(i); ChopLumberMillTrees(i);
}
} }
} }
@ -1149,12 +1137,10 @@ void OnTick_Industry(void)
} }
} }
if (_game_mode == GM_EDITOR) if (_game_mode == GM_EDITOR) return;
return;
FOR_ALL_INDUSTRIES(i) { FOR_ALL_INDUSTRIES(i) {
if (i->xy != 0) if (i->xy != 0) ProduceIndustryGoods(i);
ProduceIndustryGoods(i);
} }
} }
@ -1180,14 +1166,9 @@ extern bool _ignore_restrictions;
/* Oil Rig and Oil Refinery */ /* Oil Rig and Oil Refinery */
static bool CheckNewIndustry_Oil(TileIndex tile, int type) static bool CheckNewIndustry_Oil(TileIndex tile, int type)
{ {
if(_ignore_restrictions && _game_mode == GM_EDITOR) if (_game_mode == GM_EDITOR && _ignore_restrictions) return true;
return true; if (_game_mode == GM_EDITOR && type != IT_OIL_RIG) return true;
if (DistanceFromEdge(TILE_ADDXY(tile, 1, 1)) < 16) return true;
if (type != IT_OIL_RIG && _game_mode == GM_EDITOR)
return true;
if (DistanceFromEdge(TILE_ADDXY(tile, 1, 1)) < 16)
return true;
_error_message = STR_483B_CAN_ONLY_BE_POSITIONED; _error_message = STR_483B_CAN_ONLY_BE_POSITIONED;
return false; return false;
@ -1255,7 +1236,7 @@ static bool CheckSuitableIndustryPos(TileIndex tile)
uint x = TileX(tile); uint x = TileX(tile);
uint y = TileY(tile); uint y = TileY(tile);
if ( x < 2 || y < 2 || x > MapMaxX() - 3 || y > MapMaxY() - 3) { if (x < 2 || y < 2 || x > MapMaxX() - 3 || y > MapMaxY() - 3) {
_error_message = STR_0239_SITE_UNSUITABLE; _error_message = STR_0239_SITE_UNSUITABLE;
return false; return false;
} }
@ -1270,8 +1251,7 @@ static const Town* CheckMultipleIndustryInTown(TileIndex tile, int type)
t = ClosestTownFromTile(tile, (uint)-1); t = ClosestTownFromTile(tile, (uint)-1);
if (_patches.multiple_industry_per_town) if (_patches.multiple_industry_per_town) return t;
return t;
FOR_ALL_INDUSTRIES(i) { FOR_ALL_INDUSTRIES(i) {
if (i->xy != 0 && if (i->xy != 0 &&
@ -1320,26 +1300,21 @@ static bool CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileTable*
TileIndex cur_tile = tile + ToTileIndexDiff(it->ti); TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
if (!IsValidTile(cur_tile)) { if (!IsValidTile(cur_tile)) {
if (it->map5 == 0xff) if (it->map5 == 0xff) continue;
continue;
return false; return false;
} }
FindLandscapeHeightByTile(&ti, cur_tile); FindLandscapeHeightByTile(&ti, cur_tile);
if (it->map5 == 0xFF) { if (it->map5 == 0xFF) {
if (ti.type != MP_WATER || ti.tileh != 0) if (ti.type != MP_WATER || ti.tileh != 0) return false;
return false;
} else { } else {
if (!EnsureNoVehicle(cur_tile)) if (!EnsureNoVehicle(cur_tile)) return false;
return false;
if (type == IT_OIL_RIG) { if (type == IT_OIL_RIG) {
if (ti.type != MP_WATER || ti.map5 != 0) if (ti.type != MP_WATER || ti.map5 != 0) return false;
return false;
} else { } else {
if (ti.type == MP_WATER && ti.map5 == 0) if (ti.type == MP_WATER && ti.map5 == 0) return false;
return false;
if (IsSteepTileh(ti.tileh)) if (IsSteepTileh(ti.tileh))
return false; return false;
@ -1347,22 +1322,14 @@ static bool CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileTable*
int t; int t;
byte bits = _industry_map5_bits[it->map5]; byte bits = _industry_map5_bits[it->map5];
if (bits & 0x10) if (bits & 0x10) return false;
return false;
t = ~ti.tileh; t = ~ti.tileh;
if (bits & 1 && (t & (1+8))) if (bits & 1 && (t & (1 + 8))) return false;
return false; if (bits & 2 && (t & (4 + 8))) return false;
if (bits & 4 && (t & (1 + 2))) return false;
if (bits & 2 && (t & (4+8))) if (bits & 8 && (t & (2 + 4))) return false;
return false;
if (bits & 4 && (t & (1+2)))
return false;
if (bits & 8 && (t & (2+4)))
return false;
} }
if (type == IT_BANK) { if (type == IT_BANK) {
@ -1376,8 +1343,7 @@ static bool CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileTable*
return false; return false;
} }
} else if (type == IT_TOY_SHOP) { } else if (type == IT_TOY_SHOP) {
if (DistanceMax(t->xy, cur_tile) > 9) if (DistanceMax(t->xy, cur_tile) > 9) return false;
return false;
if (ti.type != MP_HOUSE) goto do_clear; if (ti.type != MP_HOUSE) goto do_clear;
} else if (type == IT_WATER_TOWER) { } else if (type == IT_WATER_TOWER) {
if (ti.type != MP_HOUSE) { if (ti.type != MP_HOUSE) {
@ -1398,9 +1364,8 @@ do_clear:
static bool CheckIfTooCloseToIndustry(TileIndex tile, int type) static bool CheckIfTooCloseToIndustry(TileIndex tile, int type)
{ {
const IndustrySpec* spec = &_industry_spec[type];
const Industry* i; const Industry* i;
const IndustrySpec *spec;
spec = &_industry_spec[type];
// accepting industries won't be close, not even with patch // accepting industries won't be close, not even with patch
if (_patches.same_industry_close && spec->accepts_cargo[0] == CT_INVALID) if (_patches.same_industry_close && spec->accepts_cargo[0] == CT_INVALID)
@ -1409,15 +1374,16 @@ static bool CheckIfTooCloseToIndustry(TileIndex tile, int type)
FOR_ALL_INDUSTRIES(i) { FOR_ALL_INDUSTRIES(i) {
// check if an industry that accepts the same goods is nearby // check if an industry that accepts the same goods is nearby
if (i->xy != 0 && if (i->xy != 0 &&
(DistanceMax(tile, i->xy) <= 14) && DistanceMax(tile, i->xy) <= 14 &&
spec->accepts_cargo[0] != CT_INVALID && spec->accepts_cargo[0] != CT_INVALID &&
spec->accepts_cargo[0] == i->accepts_cargo[0] && spec->accepts_cargo[0] == i->accepts_cargo[0] && (
!(_game_mode == GM_EDITOR && _game_mode != GM_EDITOR ||
_patches.same_industry_close && !_patches.same_industry_close ||
_patches.multiple_industry_per_town)) { !_patches.multiple_industry_per_town
_error_message = STR_INDUSTRY_TOO_CLOSE; )) {
return false; _error_message = STR_INDUSTRY_TOO_CLOSE;
} return false;
}
// check "not close to" field. // check "not close to" field.
if (i->xy != 0 && if (i->xy != 0 &&
@ -1438,10 +1404,9 @@ static Industry *AllocateIndustry(void)
if (i->xy == 0) { if (i->xy == 0) {
uint index = i->index; uint index = i->index;
if (i->index > _total_industries) if (i->index > _total_industries) _total_industries = i->index;
_total_industries = i->index;
memset(i, 0, sizeof(Industry)); memset(i, 0, sizeof(*i));
i->index = index; i->index = index;
return i; return i;
@ -1498,8 +1463,7 @@ static void DoCreateNewIndustry(Industry* i, TileIndex tile, int type, const Ind
i->total_production[0] = i->production_rate[0] * 8; i->total_production[0] = i->production_rate[0] * 8;
i->total_production[1] = i->production_rate[1] * 8; i->total_production[1] = i->production_rate[1] * 8;
if (_generating_world == 0) if (!_generating_world) i->total_production[0] = i->total_production[1] = 0;
i->total_production[0] = i->total_production[1] = 0;
i->prod_level = 0x10; i->prod_level = 0x10;
@ -1528,13 +1492,12 @@ static void DoCreateNewIndustry(Industry* i, TileIndex tile, int type, const Ind
if (i->type == IT_FARM || i->type == IT_FARM_2) { if (i->type == IT_FARM || i->type == IT_FARM_2) {
tile = i->xy + TileDiffXY(i->width / 2, i->height / 2); tile = i->xy + TileDiffXY(i->width / 2, i->height / 2);
for(j=0; j!=50; j++) { for (j = 0; j != 50; j++) {
int x = Random() % 31 - 16; int x = Random() % 31 - 16;
int y = Random() % 31 - 16; int y = Random() % 31 - 16;
TileIndex new_tile = TileAddWrap(tile, x, y); TileIndex new_tile = TileAddWrap(tile, x, y);
if (new_tile != INVALID_TILE) if (new_tile != INVALID_TILE) PlantFarmField(new_tile);
PlantFarmField(new_tile);
} }
} }
_industry_sort_dirty = true; _industry_sort_dirty = true;
@ -1562,10 +1525,15 @@ int32 CmdBuildIndustry(int x, int y, uint32 flags, uint32 p1, uint32 p2)
/* Check if the to-be built/founded industry is available for this climate. /* Check if the to-be built/founded industry is available for this climate.
* Unfortunately we have no easy way of checking, except for looping the table */ * Unfortunately we have no easy way of checking, except for looping the table */
{ const byte *i; {
const byte* i;
bool found = false; bool found = false;
for (i = &_build_industry_types[_opt_ptr->landscape][0]; i != endof(_build_industry_types[_opt_ptr->landscape]); i++) { for (i = &_build_industry_types[_opt_ptr->landscape][0]; i != endof(_build_industry_types[_opt_ptr->landscape]); i++) {
if (*i == p1) {found = true; break;} if (*i == p1) {
found = true;
break;
}
} }
if (!found) return CMD_ERROR; if (!found) return CMD_ERROR;
} }
@ -1584,7 +1552,8 @@ int32 CmdBuildIndustry(int x, int y, uint32 flags, uint32 p1, uint32 p2)
if (!_check_new_industry_procs[spec->check_proc](tile, p1)) return CMD_ERROR; if (!_check_new_industry_procs[spec->check_proc](tile, p1)) return CMD_ERROR;
if ((t = CheckMultipleIndustryInTown(tile, p1)) == NULL) return CMD_ERROR; t = CheckMultipleIndustryInTown(tile, p1);
if (t == NULL) return CMD_ERROR;
num = spec->num_table; num = spec->num_table;
itt = spec->table; itt = spec->table;
@ -1596,10 +1565,10 @@ int32 CmdBuildIndustry(int x, int y, uint32 flags, uint32 p1, uint32 p2)
if (!CheckIfTooCloseToIndustry(tile, p1)) return CMD_ERROR; if (!CheckIfTooCloseToIndustry(tile, p1)) return CMD_ERROR;
if ( (i = AllocateIndustry()) == NULL) return CMD_ERROR; i = AllocateIndustry();
if (i == NULL) return CMD_ERROR;
if (flags & DC_EXEC) if (flags & DC_EXEC) DoCreateNewIndustry(i, tile, p1, it, t, OWNER_NONE);
DoCreateNewIndustry(i, tile, p1, it, t, OWNER_NONE);
return (_price.build_industry >> 5) * _industry_type_costs[p1]; return (_price.build_industry >> 5) * _industry_type_costs[p1];
} }
@ -1613,28 +1582,23 @@ Industry *CreateNewIndustry(TileIndex tile, int type)
const IndustrySpec *spec; const IndustrySpec *spec;
if (!CheckSuitableIndustryPos(tile)) if (!CheckSuitableIndustryPos(tile)) return NULL;
return NULL;
spec = &_industry_spec[type]; spec = &_industry_spec[type];
if (!_check_new_industry_procs[spec->check_proc](tile, type)) if (!_check_new_industry_procs[spec->check_proc](tile, type)) return NULL;
return NULL;
if (!(t=CheckMultipleIndustryInTown(tile, type))) t = CheckMultipleIndustryInTown(tile, type);
return NULL; if (t == NULL) return NULL;
/* pick a random layout */ /* pick a random layout */
it = spec->table[RandomRange(spec->num_table)];; it = spec->table[RandomRange(spec->num_table)];
if (!CheckIfIndustryTilesAreFree(tile, it, type, t)) if (!CheckIfIndustryTilesAreFree(tile, it, type, t)) return NULL;
return NULL; if (!CheckIfTooCloseToIndustry(tile, type)) return NULL;
if (!CheckIfTooCloseToIndustry(tile, type)) i = AllocateIndustry();
return NULL; if (i == NULL) return NULL;
if ( (i = AllocateIndustry()) == NULL)
return NULL;
DoCreateNewIndustry(i, tile, type, it, t, OWNER_NONE); DoCreateNewIndustry(i, tile, type, it, t, OWNER_NONE);
@ -1659,18 +1623,17 @@ static void PlaceInitialIndustry(byte type, int amount)
num = ScaleByMapSize(num); num = ScaleByMapSize(num);
} }
if (_opt.diff.number_industries != 0) if (_opt.diff.number_industries != 0) {
{
PlayerID old_player = _current_player; PlayerID old_player = _current_player;
_current_player = OWNER_NONE; _current_player = OWNER_NONE;
assert(num > 0); assert(num > 0);
do { do {
int i = 2000; uint i;
do {
if (CreateNewIndustry(RandomTile(), type) != NULL) for (i = 0; i < 2000; i++) {
break; if (CreateNewIndustry(RandomTile(), type) != NULL) break;
} while (--i != 0); }
} while (--num); } while (--num);
_current_player = old_player; _current_player = old_player;
@ -1713,7 +1676,6 @@ static void ExtChangeIndustryProduction(Industry *i)
if (CHANCE16I(20 + (i->pct_transported[j] * 20 >> 8), 1024, r >> 16)) if (CHANCE16I(20 + (i->pct_transported[j] * 20 >> 8), 1024, r >> 16))
new += ((RandomRange(50) + 10) * old) >> 8; new += ((RandomRange(50) + 10) * old) >> 8;
// make sure it doesn't exceed 255 or goes below 0
new = clamp(new, 0, 255); new = clamp(new, 0, 255);
if (new == old) { if (new == old) {
closeit = false; closeit = false;
@ -1731,9 +1693,11 @@ static void ExtChangeIndustryProduction(Industry *i)
SetDParam(2, mag); SetDParam(2, mag);
SetDParam(0, _cargoc.names_s[i->produced_cargo[j]]); SetDParam(0, _cargoc.names_s[i->produced_cargo[j]]);
SetDParam(1, i->index); SetDParam(1, i->index);
AddNewsItem(percent >= 0 ? STR_INDUSTRY_PROD_GOUP : STR_INDUSTRY_PROD_GODOWN, AddNewsItem(
NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_TILE, NT_ECONOMY, 0), percent >= 0 ? STR_INDUSTRY_PROD_GOUP : STR_INDUSTRY_PROD_GODOWN,
i->xy + TileDiffXY(1, 1), 0); NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_TILE, NT_ECONOMY, 0),
i->xy + TileDiffXY(1, 1), 0
);
} }
} }
break; break;
@ -1742,9 +1706,11 @@ static void ExtChangeIndustryProduction(Industry *i)
if (closeit) { if (closeit) {
i->prod_level = 0; i->prod_level = 0;
SetDParam(0, i->index); SetDParam(0, i->index);
AddNewsItem(_industry_close_strings[i->type], AddNewsItem(
NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_TILE, NT_ECONOMY, 0), _industry_close_strings[i->type],
i->xy + TileDiffXY(1, 1), 0); NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_TILE, NT_ECONOMY, 0),
i->xy + TileDiffXY(1, 1), 0
);
} }
} }
@ -1787,10 +1753,11 @@ static void UpdateIndustryStatistics(Industry *i)
if (i->produced_cargo[0] != CT_INVALID || i->produced_cargo[1] != CT_INVALID) if (i->produced_cargo[0] != CT_INVALID || i->produced_cargo[1] != CT_INVALID)
InvalidateWindow(WC_INDUSTRY_VIEW, i->index); InvalidateWindow(WC_INDUSTRY_VIEW, i->index);
if (i->prod_level == 0) if (i->prod_level == 0) {
DeleteIndustry(i); DeleteIndustry(i);
else if (_patches.smooth_economy) } else if (_patches.smooth_economy) {
ExtChangeIndustryProduction(i); ExtChangeIndustryProduction(i);
}
} }
static const byte _new_industry_rand[4][32] = { static const byte _new_industry_rand[4][32] = {
@ -1807,19 +1774,15 @@ static void MaybeNewIndustry(uint32 r)
Industry *i; Industry *i;
type = _new_industry_rand[_opt.landscape][GB(r, 16, 5)]; type = _new_industry_rand[_opt.landscape][GB(r, 16, 5)];
if (type == IT_OIL_WELL && _date > 10958)
return;
if (type == IT_OIL_RIG && _date < 14610) if (type == IT_OIL_WELL && _date > 10958) return;
return; if (type == IT_OIL_RIG && _date < 14610) return;
j = 2000; j = 2000;
for(;;) { for (;;) {
i = CreateNewIndustry(RandomTile(), type); i = CreateNewIndustry(RandomTile(), type);
if (i != NULL) if (i != NULL) break;
break; if (--j == 0) return;
if (--j == 0)
return;
} }
SetDParam(0, type + STR_4802_COAL_MINE); SetDParam(0, type + STR_4802_COAL_MINE);
@ -1905,8 +1868,7 @@ void IndustryMonthlyLoop(void)
_current_player = OWNER_NONE; _current_player = OWNER_NONE;
FOR_ALL_INDUSTRIES(i) { FOR_ALL_INDUSTRIES(i) {
if (i->xy != 0) if (i->xy != 0) UpdateIndustryStatistics(i);
UpdateIndustryStatistics(i);
} }
/* 3% chance that we start a new industry */ /* 3% chance that we start a new industry */
@ -1914,8 +1876,7 @@ void IndustryMonthlyLoop(void)
MaybeNewIndustry(Random()); MaybeNewIndustry(Random());
} else if (!_patches.smooth_economy && _total_industries > 0) { } else if (!_patches.smooth_economy && _total_industries > 0) {
i = GetIndustry(RandomRange(_total_industries)); i = GetIndustry(RandomRange(_total_industries));
if (i->xy != 0) if (i->xy != 0) ChangeIndustryProduction(i);
ChangeIndustryProduction(i);
} }
_current_player = old_player; _current_player = old_player;
@ -1928,7 +1889,6 @@ void IndustryMonthlyLoop(void)
void InitializeIndustries(void) void InitializeIndustries(void)
{ {
CleanPool(&_industry_pool); CleanPool(&_industry_pool);
AddBlockToPool(&_industry_pool); AddBlockToPool(&_industry_pool);
@ -2012,8 +1972,7 @@ static void Load_INDY(void)
i = GetIndustry(index); i = GetIndustry(index);
SlObject(i, _industry_desc); SlObject(i, _industry_desc);
if (index > _total_industries) if (index > _total_industries) _total_industries = index;
_total_industries = index;
} }
} }

View File

@ -154,8 +154,9 @@ static const Widget _ask_abandon_game_widgets[] = {
{ WIDGETS_END }, { WIDGETS_END },
}; };
static void AskAbandonGameWndProc(Window *w, WindowEvent *e) { static void AskAbandonGameWndProc(Window* w, WindowEvent* e)
switch(e->event) { {
switch (e->event) {
case WE_PAINT: case WE_PAINT:
DrawWindowWidgets(w); DrawWindowWidgets(w);
#if defined(_WIN32) #if defined(_WIN32)
@ -173,7 +174,7 @@ static void AskAbandonGameWndProc(Window *w, WindowEvent *e) {
#else #else
SetDParam(0, STR_0134_UNIX); SetDParam(0, STR_0134_UNIX);
#endif #endif
DrawStringMultiCenter(0x5A, 0x26, STR_00CA_ARE_YOU_SURE_YOU_WANT_TO, 178); DrawStringMultiCenter(90, 38, STR_00CA_ARE_YOU_SURE_YOU_WANT_TO, 178);
return; return;
case WE_CLICK: case WE_CLICK:
@ -217,32 +218,29 @@ static const Widget _ask_quit_game_widgets[] = {
{ WIDGETS_END }, { WIDGETS_END },
}; };
static void AskQuitGameWndProc(Window *w, WindowEvent *e) { static void AskQuitGameWndProc(Window* w, WindowEvent* e)
switch(e->event) { {
case WE_PAINT: switch (e->event) {
DrawWindowWidgets(w); case WE_PAINT:
DrawStringMultiCenter(0x5A, 0x26, DrawWindowWidgets(w);
_game_mode != GM_EDITOR ? STR_0160_ARE_YOU_SURE_YOU_WANT_TO : DrawStringMultiCenter(
STR_029B_ARE_YOU_SURE_YOU_WANT_TO, 90, 38,
178); _game_mode != GM_EDITOR ?
return; STR_0160_ARE_YOU_SURE_YOU_WANT_TO : STR_029B_ARE_YOU_SURE_YOU_WANT_TO,
178
case WE_CLICK: );
switch(e->click.widget) {
case 3:
DeleteWindow(w);
break; break;
case 4:
_switch_mode = SM_MENU; case WE_CLICK:
switch (e->click.widget) {
case 3: DeleteWindow(w); break;
case 4: _switch_mode = SM_MENU; break;
}
break; break;
}
break;
case WE_KEYPRESS: /* Return to main menu on pressing 'Enter' */
if (e->keypress.keycode == WKC_RETURN)
_switch_mode = SM_MENU;
break;
case WE_KEYPRESS: /* Return to main menu on pressing 'Enter' */
if (e->keypress.keycode == WKC_RETURN) _switch_mode = SM_MENU;
break;
} }
} }

View File

@ -208,16 +208,16 @@ void DrawFoundation(TileInfo *ti, uint f)
uint32 sprite_base = SPR_SLOPES_BASE-14; uint32 sprite_base = SPR_SLOPES_BASE-14;
TileInfo ti2; TileInfo ti2;
FindLandscapeHeight(&ti2, ti->x, ti->y-1); FindLandscapeHeight(&ti2, ti->x, ti->y - 1);
if(hasFoundation( &ti2, true )) sprite_base += 22; // foundation in NW direction if (hasFoundation(&ti2, true)) sprite_base += 22; // foundation in NW direction
FindLandscapeHeight(&ti2, ti->x-1, ti->y); FindLandscapeHeight(&ti2, ti->x - 1, ti->y);
if(hasFoundation( &ti2, false )) sprite_base += 22*2; // foundation in NE direction if (hasFoundation(&ti2, false)) sprite_base += 22 * 2; // foundation in NE direction
if (f < 15) { if (f < 15) {
// leveled foundation // leveled foundation
if (sprite_base < SPR_SLOPES_BASE) sprite_base = SPR_FOUNDATION_BASE + 1; // use original slope sprites if (sprite_base < SPR_SLOPES_BASE) sprite_base = SPR_FOUNDATION_BASE + 1; // use original slope sprites
AddSortableSpriteToDraw(f-1 + sprite_base, ti->x, ti->y, 16, 16, 7, ti->z); AddSortableSpriteToDraw(f - 1 + sprite_base, ti->x, ti->y, 16, 16, 7, ti->z);
ti->z += 8; ti->z += 8;
ti->tileh = 0; ti->tileh = 0;
OffsetGroundSprite(31, 1); OffsetGroundSprite(31, 1);

View File

@ -47,7 +47,7 @@ extern bool GenerateTowns(void);
void HandleOnEditTextCancel(void) void HandleOnEditTextCancel(void)
{ {
switch(_rename_what) { switch (_rename_what) {
#ifdef ENABLE_NETWORK #ifdef ENABLE_NETWORK
case 4: case 4:
NetworkDisconnect(); NetworkDisconnect();
@ -119,13 +119,11 @@ void HandleOnEditText(WindowEvent *e)
* @return true if the button is clicked, false if it's unclicked * @return true if the button is clicked, false if it's unclicked
*/ */
bool HandlePlacePushButton(Window *w, int widget, CursorID cursor, int mode, PlaceProc *placeproc) bool HandlePlacePushButton(Window *w, int widget, CursorID cursor, int mode, PlaceProc *placeproc)
{ {
uint32 mask = 1 << widget; uint32 mask = 1 << widget;
if (w->disabled_state & mask) if (w->disabled_state & mask) return false;
return false;
SndPlayFx(SND_15_BEEP); SndPlayFx(SND_15_BEEP);
SetWindowDirty(w); SetWindowDirty(w);
@ -148,14 +146,11 @@ void CcPlaySound10(bool success, TileIndex tile, uint32 p1, uint32 p2)
} }
typedef void ToolbarButtonProc(Window *w);
static void ToolbarPauseClick(Window *w) static void ToolbarPauseClick(Window *w)
{ {
if (_networking && !_network_server) return; // only server can pause the game if (_networking && !_network_server) return; // only server can pause the game
if (DoCommandP(0, _pause ? 0 : 1, 0, NULL, CMD_PAUSE)) if (DoCommandP(0, _pause ? 0 : 1, 0, NULL, CMD_PAUSE)) SndPlayFx(SND_15_BEEP);
SndPlayFx(SND_15_BEEP);
} }
static void ToolbarFastForwardClick(Window *w) static void ToolbarFastForwardClick(Window *w)
@ -164,8 +159,6 @@ static void ToolbarFastForwardClick(Window *w)
SndPlayFx(SND_15_BEEP); SndPlayFx(SND_15_BEEP);
} }
typedef void MenuClickedProc(int index);
static void MenuClickSettings(int index) static void MenuClickSettings(int index)
{ {
@ -389,9 +382,9 @@ void ShowRenameWaypointWindow(const Waypoint *wp)
static void SelectSignTool(void) static void SelectSignTool(void)
{ {
if (_cursor.sprite == SPR_CURSOR_SIGN) if (_cursor.sprite == SPR_CURSOR_SIGN) {
ResetObjectToPlace(); ResetObjectToPlace();
else { } else {
SetObjectToPlace(SPR_CURSOR_SIGN, 1, 1, 0); SetObjectToPlace(SPR_CURSOR_SIGN, 1, 1, 0);
_place_proc = PlaceProc_Sign; _place_proc = PlaceProc_Sign;
} }
@ -431,6 +424,9 @@ static void MenuClickHelp(int index)
} }
} }
typedef void MenuClickedProc(int index);
static MenuClickedProc * const _menu_clicked_procs[] = { static MenuClickedProc * const _menu_clicked_procs[] = {
NULL, /* 0 */ NULL, /* 0 */
NULL, /* 1 */ NULL, /* 1 */
@ -463,7 +459,7 @@ static MenuClickedProc * const _menu_clicked_procs[] = {
static void MenuWndProc(Window *w, WindowEvent *e) static void MenuWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
int count,sel; int count,sel;
int x,y; int x,y;
@ -519,16 +515,15 @@ static void MenuWndProc(Window *w, WindowEvent *e)
action_id = WP(w,menu_d).action_id; action_id = WP(w,menu_d).action_id;
DeleteWindow(w); DeleteWindow(w);
if (index >= 0) if (index >= 0) _menu_clicked_procs[action_id](index);
_menu_clicked_procs[action_id](index);
break; break;
} }
case WE_POPUPMENU_OVER: { case WE_POPUPMENU_OVER: {
int index = GetMenuItemIndex(w, e->popupmenu.pt.x, e->popupmenu.pt.y); int index = GetMenuItemIndex(w, e->popupmenu.pt.x, e->popupmenu.pt.y);
if (index == -1 || index == WP(w,menu_d).sel_index) if (index == -1 || index == WP(w,menu_d).sel_index) return;
return;
WP(w,menu_d).sel_index = index; WP(w,menu_d).sel_index = index;
SetWindowDirty(w); SetWindowDirty(w);
@ -555,10 +550,7 @@ static int GetPlayerIndexFromMenu(int index)
const Player* p; const Player* p;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (p->is_active) { if (p->is_active && --index < 0) return p->index;
if (--index < 0)
return p->index;
}
} }
} }
return -1; return -1;
@ -566,19 +558,15 @@ static int GetPlayerIndexFromMenu(int index)
static void UpdatePlayerMenuHeight(Window *w) static void UpdatePlayerMenuHeight(Window *w)
{ {
int num = 0; uint num = 0;
const Player* p; const Player* p;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (p->is_active) if (p->is_active) num++;
num++;
} }
// Increase one to fit in PlayerList in the menu when // Increase one to fit in PlayerList in the menu when in network
// in network if (_networking && WP(w,menu_d).main_button == 9) num++;
if (_networking && WP(w,menu_d).main_button == 9) {
num++;
}
if (WP(w,menu_d).item_count != num) { if (WP(w,menu_d).item_count != num) {
WP(w,menu_d).item_count = num; WP(w,menu_d).item_count = num;
@ -594,7 +582,7 @@ extern void DrawPlayerIcon(int p, int x, int y);
static void PlayerMenuWndProc(Window *w, WindowEvent *e) static void PlayerMenuWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
int x,y; int x,y;
byte sel, color; byte sel, color;
@ -657,10 +645,10 @@ static void PlayerMenuWndProc(Window *w, WindowEvent *e)
// We have a new entry at the top of the list of menu 9 when networking // We have a new entry at the top of the list of menu 9 when networking
// so keep that in count // so keep that in count
if (_networking && WP(w,menu_d).main_button == 9) { if (_networking && WP(w,menu_d).main_button == 9) {
if (index > 0) if (index > 0) index = GetPlayerIndexFromMenu(index - 1) + 1;
index = GetPlayerIndexFromMenu(index - 1) + 1; } else {
} else
index = GetPlayerIndexFromMenu(index); index = GetPlayerIndexFromMenu(index);
}
if (index < 0) { if (index < 0) {
Window *w2 = FindWindowById(WC_MAIN_TOOLBAR,0); Window *w2 = FindWindowById(WC_MAIN_TOOLBAR,0);
@ -684,13 +672,12 @@ static void PlayerMenuWndProc(Window *w, WindowEvent *e)
// We have a new entry at the top of the list of menu 9 when networking // We have a new entry at the top of the list of menu 9 when networking
// so keep that in count // so keep that in count
if (_networking && WP(w,menu_d).main_button == 9) { if (_networking && WP(w,menu_d).main_button == 9) {
if (index > 0) if (index > 0) index = GetPlayerIndexFromMenu(index - 1) + 1;
index = GetPlayerIndexFromMenu(index - 1) + 1; } else {
} else
index = GetPlayerIndexFromMenu(index); index = GetPlayerIndexFromMenu(index);
}
if (index == -1 || index == WP(w,menu_d).sel_index) if (index == -1 || index == WP(w,menu_d).sel_index) return;
return;
WP(w,menu_d).sel_index = index; WP(w,menu_d).sel_index = index;
SetWindowDirty(w); SetWindowDirty(w);
@ -740,11 +727,12 @@ static Window *PopupMainPlayerToolbMenu(Window *w, int x, int main_button, int g
WP(w,menu_d).item_count = 0; WP(w,menu_d).item_count = 0;
WP(w,menu_d).sel_index = (_local_player != OWNER_SPECTATOR) ? _local_player : GetPlayerIndexFromMenu(0); WP(w,menu_d).sel_index = (_local_player != OWNER_SPECTATOR) ? _local_player : GetPlayerIndexFromMenu(0);
if (_networking && main_button == 9) { if (_networking && main_button == 9) {
if (_local_player != OWNER_SPECTATOR) if (_local_player != OWNER_SPECTATOR) {
WP(w,menu_d).sel_index++; WP(w,menu_d).sel_index++;
else } else {
/* Select client list by default for spectators */ /* Select client list by default for spectators */
WP(w,menu_d).sel_index = 0; WP(w,menu_d).sel_index = 0;
}
} }
WP(w,menu_d).action_id = main_button; WP(w,menu_d).action_id = main_button;
WP(w,menu_d).main_button = main_button; WP(w,menu_d).main_button = main_button;
@ -809,8 +797,10 @@ static void ToolbarTrainClick(Window *w)
{ {
const Vehicle* v; const Vehicle* v;
int dis = -1; int dis = -1;
FOR_ALL_VEHICLES(v)
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_Train && v->subtype == TS_Front_Engine) CLRBIT(dis, v->owner); if (v->type == VEH_Train && v->subtype == TS_Front_Engine) CLRBIT(dis, v->owner);
}
PopupMainPlayerToolbMenu(w, 310, 13, dis); PopupMainPlayerToolbMenu(w, 310, 13, dis);
} }
@ -818,8 +808,10 @@ static void ToolbarRoadClick(Window *w)
{ {
const Vehicle* v; const Vehicle* v;
int dis = -1; int dis = -1;
FOR_ALL_VEHICLES(v)
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_Road) CLRBIT(dis, v->owner); if (v->type == VEH_Road) CLRBIT(dis, v->owner);
}
PopupMainPlayerToolbMenu(w, 332, 14, dis); PopupMainPlayerToolbMenu(w, 332, 14, dis);
} }
@ -827,8 +819,10 @@ static void ToolbarShipClick(Window *w)
{ {
const Vehicle* v; const Vehicle* v;
int dis = -1; int dis = -1;
FOR_ALL_VEHICLES(v)
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_Ship) CLRBIT(dis, v->owner); if (v->type == VEH_Ship) CLRBIT(dis, v->owner);
}
PopupMainPlayerToolbMenu(w, 354, 15, dis); PopupMainPlayerToolbMenu(w, 354, 15, dis);
} }
@ -836,8 +830,10 @@ static void ToolbarAirClick(Window *w)
{ {
const Vehicle* v; const Vehicle* v;
int dis = -1; int dis = -1;
FOR_ALL_VEHICLES(v)
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_Aircraft) CLRBIT(dis, v->owner); if (v->type == VEH_Aircraft) CLRBIT(dis, v->owner);
}
PopupMainPlayerToolbMenu(w, 376, 16, dis); PopupMainPlayerToolbMenu(w, 376, 16, dis);
} }
@ -882,15 +878,17 @@ bool DoZoomInOutWindow(int how, Window *w)
// routine to disable/enable the zoom buttons. Didn't know where to place these otherwise // routine to disable/enable the zoom buttons. Didn't know where to place these otherwise
{ {
Window *wt = NULL; Window* wt = NULL;
switch (w->window_class) { switch (w->window_class) {
case WC_MAIN_WINDOW: case WC_MAIN_WINDOW:
wt = FindWindowById(WC_MAIN_TOOLBAR, 0); wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
break; break;
case WC_EXTRA_VIEW_PORT:
wt = FindWindowById(WC_EXTRA_VIEW_PORT, w->window_number); case WC_EXTRA_VIEW_PORT:
button = 5; wt = FindWindowById(WC_EXTRA_VIEW_PORT, w->window_number);
break; button = 5;
break;
} }
assert(wt); assert(wt);
@ -1003,8 +1001,7 @@ static void ToolbarScenDateBackward(Window *w)
HandleButtonClick(w, 6); HandleButtonClick(w, 6);
InvalidateWidget(w, 5); InvalidateWidget(w, 5);
if (_date > MinDate) if (_date > MinDate) SetDate(ConvertYMDToDay(_cur_year - 1, 0, 1));
SetDate(ConvertYMDToDay(_cur_year - 1, 0, 1));
} }
_left_button_clicked = false; _left_button_clicked = false;
} }
@ -1016,8 +1013,7 @@ static void ToolbarScenDateForward(Window *w)
HandleButtonClick(w, 7); HandleButtonClick(w, 7);
InvalidateWidget(w, 5); InvalidateWidget(w, 5);
if (_date < MaxDate) if (_date < MaxDate) SetDate(ConvertYMDToDay(_cur_year + 1, 0, 1));
SetDate(ConvertYMDToDay(_cur_year + 1, 0, 1));
} }
_left_button_clicked = false; _left_button_clicked = false;
} }
@ -1070,7 +1066,7 @@ static void ResetLandscape(void)
_random_seeds[0][0] = InteractiveRandom(); _random_seeds[0][0] = InteractiveRandom();
_random_seeds[0][1] = InteractiveRandom(); _random_seeds[0][1] = InteractiveRandom();
GenerateWorld(1, 1<<_patches.map_x, 1<<_patches.map_y); GenerateWorld(1, 1 << _patches.map_x, 1 << _patches.map_y);
MarkWholeScreenDirty(); MarkWholeScreenDirty();
} }
@ -1088,13 +1084,17 @@ static void AskResetLandscapeWndProc(Window *w, WindowEvent *e)
{ {
uint mode = w->window_number; uint mode = w->window_number;
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
DrawWindowWidgets(w); DrawWindowWidgets(w);
DrawStringMultiCenter(90, 38, mode?STR_022D_ARE_YOU_SURE_YOU_WANT_TO:STR_GENERATE_RANDOM_LANDSCAPE , 168); DrawStringMultiCenter(
90, 38,
mode ? STR_022D_ARE_YOU_SURE_YOU_WANT_TO : STR_GENERATE_RANDOM_LANDSCAPE,
168
);
break; break;
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 3: case 3:
DeleteWindow(w); DeleteWindow(w);
break; break;
@ -1110,7 +1110,6 @@ static void AskResetLandscapeWndProc(Window *w, WindowEvent *e)
SndPlayFx(SND_15_BEEP); SndPlayFx(SND_15_BEEP);
_switch_mode = SM_GENRANDLAND; _switch_mode = SM_GENRANDLAND;
} }
break; break;
} }
break; break;
@ -1358,7 +1357,7 @@ static void ScenEditLandGenWndProc(Window *w, WindowEvent *e)
break; break;
case WE_KEYPRESS: { case WE_KEYPRESS: {
int i; uint i;
for (i = 0; i != lengthof(_editor_terraform_keycodes); i++) { for (i = 0; i != lengthof(_editor_terraform_keycodes); i++) {
if (e->keypress.keycode == _editor_terraform_keycodes[i]) { if (e->keypress.keycode == _editor_terraform_keycodes[i]) {
@ -1471,7 +1470,7 @@ static const Widget _scen_edit_town_gen_widgets[] = {
static void ScenEditTownGenWndProc(Window *w, WindowEvent *e) static void ScenEditTownGenWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
w->click_state = (w->click_state & ~(1<<7 | 1<<8 | 1<<9) ) | (1 << (_new_town_size + 7)); w->click_state = (w->click_state & ~(1<<7 | 1<<8 | 1<<9) ) | (1 << (_new_town_size + 7));
DrawWindowWidgets(w); DrawWindowWidgets(w);
@ -1493,8 +1492,9 @@ static void ScenEditTownGenWndProc(Window *w, WindowEvent *e)
if (t == NULL) { if (t == NULL) {
ShowErrorMessage(STR_NO_SPACE_FOR_TOWN, STR_CANNOT_GENERATE_TOWN, 0, 0); ShowErrorMessage(STR_NO_SPACE_FOR_TOWN, STR_CANNOT_GENERATE_TOWN, 0, 0);
} else } else {
ScrollMainWindowToTile(t->xy); ScrollMainWindowToTile(t->xy);
}
break; break;
} }
@ -1503,8 +1503,9 @@ static void ScenEditTownGenWndProc(Window *w, WindowEvent *e)
_generating_world = true; _generating_world = true;
_game_mode = GM_NORMAL; // little hack to avoid towns of the same size _game_mode = GM_NORMAL; // little hack to avoid towns of the same size
if (!GenerateTowns()) if (!GenerateTowns()) {
ShowErrorMessage(STR_NO_SPACE_FOR_TOWN, STR_CANNOT_GENERATE_TOWN, 0, 0); ShowErrorMessage(STR_NO_SPACE_FOR_TOWN, STR_CANNOT_GENERATE_TOWN, 0, 0);
}
_generating_world = false; _generating_world = false;
_game_mode = GM_EDITOR; _game_mode = GM_EDITOR;
@ -1642,8 +1643,7 @@ static bool AnyTownExists(void)
const Town* t; const Town* t;
FOR_ALL_TOWNS(t) { FOR_ALL_TOWNS(t) {
if (t->xy) if (t->xy != 0) return true;
return true;
} }
return false; return false;
} }
@ -1695,13 +1695,13 @@ static void ScenEditIndustryWndProc(Window *w, WindowEvent *e)
break; break;
case WE_CLICK: case WE_CLICK:
if ((button=e->click.widget) == 3) { if (e->click.widget == 3) {
HandleButtonClick(w, 3); HandleButtonClick(w, 3);
if (!AnyTownExists()) { if (!AnyTownExists()) {
ShowErrorMessage(STR_0286_MUST_BUILD_TOWN_FIRST, STR_CAN_T_GENERATE_INDUSTRIES, 0, 0); ShowErrorMessage(STR_0286_MUST_BUILD_TOWN_FIRST, STR_CAN_T_GENERATE_INDUSTRIES, 0, 0);
return; return;
} }
_generating_world = true; _generating_world = true;
GenerateIndustries(); GenerateIndustries();
@ -1729,7 +1729,7 @@ static void ScenEditIndustryWndProc(Window *w, WindowEvent *e)
_ignore_restrictions = true; _ignore_restrictions = true;
if (!TryBuildIndustry(e->place.tile,type)) { if (!TryBuildIndustry(e->place.tile,type)) {
SetDParam(0, type + STR_4802_COAL_MINE); SetDParam(0, type + STR_4802_COAL_MINE);
ShowErrorMessage(_error_message, STR_0285_CAN_T_BUILD_HERE,e->place.pt.x, e->place.pt.y); ShowErrorMessage(_error_message, STR_0285_CAN_T_BUILD_HERE, e->place.pt.x, e->place.pt.y);
} }
_ignore_restrictions = false; _ignore_restrictions = false;
_generating_world = false; _generating_world = false;
@ -1817,6 +1817,9 @@ static void ToolbarBtn_NULL(Window *w)
{ {
} }
typedef void ToolbarButtonProc(Window *w);
static ToolbarButtonProc* const _toolbar_button_procs[] = { static ToolbarButtonProc* const _toolbar_button_procs[] = {
ToolbarPauseClick, ToolbarPauseClick,
ToolbarFastForwardClick, ToolbarFastForwardClick,
@ -1875,7 +1878,7 @@ static void MainToolbarWndProc(Window *w, WindowEvent *e)
case WE_KEYPRESS: { case WE_KEYPRESS: {
PlayerID local = (_local_player != OWNER_SPECTATOR) ? _local_player : 0; PlayerID local = (_local_player != OWNER_SPECTATOR) ? _local_player : 0;
switch(e->keypress.keycode) { switch (e->keypress.keycode) {
case WKC_F1: case WKC_PAUSE: case WKC_F1: case WKC_PAUSE:
ToolbarPauseClick(w); ToolbarPauseClick(w);
break; break;
@ -1924,7 +1927,6 @@ static void MainToolbarWndProc(Window *w, WindowEvent *e)
case WE_ON_EDIT_TEXT: HandleOnEditText(e); break; case WE_ON_EDIT_TEXT: HandleOnEditText(e); break;
case WE_MOUSELOOP: case WE_MOUSELOOP:
if (((w->click_state) & 1) != (uint)!!_pause) { if (((w->click_state) & 1) != (uint)!!_pause) {
w->click_state ^= (1 << 0); w->click_state ^= (1 << 0);
SetWindowDirty(w); SetWindowDirty(w);
@ -2068,14 +2070,16 @@ static void ScenEditToolbarWndProc(Window *w, WindowEvent *e)
switch(e->event) { switch(e->event) {
case WE_PAINT: case WE_PAINT:
/* XXX look for better place for these */ /* XXX look for better place for these */
if (_date <= MinDate) if (_date <= MinDate) {
SETBIT(w->disabled_state, 6); SETBIT(w->disabled_state, 6);
else } else {
CLRBIT(w->disabled_state, 6); CLRBIT(w->disabled_state, 6);
if (_date >= MaxDate) }
if (_date >= MaxDate) {
SETBIT(w->disabled_state, 7); SETBIT(w->disabled_state, 7);
else } else {
CLRBIT(w->disabled_state, 7); CLRBIT(w->disabled_state, 7);
}
// Draw brown-red toolbar bg. // Draw brown-red toolbar bg.
GfxFillRect(0, 0, w->width-1, w->height-1, 0xB2); GfxFillRect(0, 0, w->width-1, w->height-1, 0xB2);
@ -2093,8 +2097,7 @@ static void ScenEditToolbarWndProc(Window *w, WindowEvent *e)
break; break;
case WE_CLICK: { case WE_CLICK: {
if (_game_mode == GM_MENU) if (_game_mode == GM_MENU) return;
return;
_scen_toolbar_button_procs[e->click.widget](w); _scen_toolbar_button_procs[e->click.widget](w);
} break; } break;
@ -2111,8 +2114,8 @@ static void ScenEditToolbarWndProc(Window *w, WindowEvent *e)
case WKC_F9: ToolbarScenPlaceSign(w); break; case WKC_F9: ToolbarScenPlaceSign(w); break;
case WKC_F10: ShowMusicWindow(); break; case WKC_F10: ShowMusicWindow(); break;
case WKC_F11: PlaceLandBlockInfo(); break; case WKC_F11: PlaceLandBlockInfo(); break;
case WKC_CTRL | 'S': _make_screenshot = 1; break; case WKC_CTRL | 'S': _make_screenshot = 1; break;
case WKC_CTRL | 'G': _make_screenshot = 2; break; case WKC_CTRL | 'G': _make_screenshot = 2; break;
case 'L': ShowEditorTerraformToolBar(); break; case 'L': ShowEditorTerraformToolBar(); break;
} break; } break;
} break; } break;
@ -2176,20 +2179,19 @@ static bool DrawScrollingStatusText(const NewsItem *ni, int pos)
s = buf; s = buf;
d = buffer; d = buffer;
for(;;s++) { for (;; s++) {
if (*s == 0) { if (*s == '\0') {
*d = 0; *d = '\0';
break; break;
} else if (*s == 0x0D) { } else if (*s == 0x0D) {
d[0] = d[1] = d[2] = d[3] = ' '; d[0] = d[1] = d[2] = d[3] = ' ';
d+=4; d += 4;
} else if ((byte)*s >= ' ' && ((byte)*s < 0x88 || (byte)*s >= 0x99)) { } else if ((byte)*s >= ' ' && ((byte)*s < 0x88 || (byte)*s >= 0x99)) {
*d++ = *s; *d++ = *s;
} }
} }
if (!FillDrawPixelInfo(&tmp_dpi, NULL, 141, 1, 358, 11)) if (!FillDrawPixelInfo(&tmp_dpi, NULL, 141, 1, 358, 11)) return true;
return true;
old_dpi = _cur_dpi; old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi; _cur_dpi = &tmp_dpi;
@ -2208,7 +2210,9 @@ static void StatusBarWndProc(Window *w, WindowEvent *e)
DrawWindowWidgets(w); DrawWindowWidgets(w);
SetDParam(0, _date); SetDParam(0, _date);
DrawStringCentered(70, 1, ((_pause||_patches.status_long_date)?STR_00AF:STR_00AE), 0); DrawStringCentered(
70, 1, (_pause || _patches.status_long_date) ? STR_00AF : STR_00AE, 0
);
if (p != NULL) { if (p != NULL) {
// Draw player money // Draw player money
@ -2228,7 +2232,7 @@ static void StatusBarWndProc(Window *w, WindowEvent *e)
if (!DrawScrollingStatusText(&_statusbar_news_item, WP(w,def_d).data_1)) if (!DrawScrollingStatusText(&_statusbar_news_item, WP(w,def_d).data_1))
WP(w,def_d).data_1 = -1280; WP(w,def_d).data_1 = -1280;
} else { } else {
if (p) { if (p != NULL) {
// This is the default text // This is the default text
SetDParam(0, p->name_1); SetDParam(0, p->name_1);
SetDParam(1, p->name_2); SetDParam(1, p->name_2);
@ -2334,65 +2338,64 @@ static void MainWindowWndProc(Window *w, WindowEvent *e) {
break; break;
} }
// check to see if Command-Q has been pressed on a Mac switch (e->keypress.keycode) {
// must be done before checking if we are at the main menu case 'Q' | WKC_CTRL:
if ( (e->keypress.keycode == ('Q' | WKC_CTRL)) || (e->keypress.keycode == ('Q' | WKC_META)) ) case 'Q' | WKC_META:
{ AskExitGame();
AskExitGame(); break;
} }
if (_game_mode == GM_MENU) break; if (_game_mode == GM_MENU) break;
switch (e->keypress.keycode) { switch (e->keypress.keycode) {
case 'C': case 'Z': { case 'C':
Point pt = GetTileBelowCursor(); case 'Z': {
if (pt.x != -1) { Point pt = GetTileBelowCursor();
ScrollMainWindowTo(pt.x, pt.y); if (pt.x != -1) {
if (e->keypress.keycode == 'Z') ScrollMainWindowTo(pt.x, pt.y);
MaxZoomIn(); if (e->keypress.keycode == 'Z') MaxZoomIn();
}
break;
} }
break;
}
case WKC_ESC: ResetObjectToPlace(); break; case WKC_ESC: ResetObjectToPlace(); break;
case WKC_DELETE: DeleteNonVitalWindows(); break; case WKC_DELETE: DeleteNonVitalWindows(); break;
case WKC_DELETE | WKC_SHIFT: DeleteAllNonVitalWindows(); break; case WKC_DELETE | WKC_SHIFT: DeleteAllNonVitalWindows(); break;
case 'R' | WKC_CTRL: MarkWholeScreenDirty(); break; case 'R' | WKC_CTRL: MarkWholeScreenDirty(); break;
#if defined(_DEBUG) #if defined(_DEBUG)
case '0' | WKC_ALT: /* Crash the game */ case '0' | WKC_ALT: /* Crash the game */
*(byte*)0 = 0; *(byte*)0 = 0;
break; break;
case '1' | WKC_ALT: /* Gimme money */
/* Server can not cheat in advertise mode either! */ case '1' | WKC_ALT: /* Gimme money */
#ifdef ENABLE_NETWORK /* Server can not cheat in advertise mode either! */
if (!_networking || !_network_server || !_network_advertise) #ifdef ENABLE_NETWORK
#endif if (!_networking || !_network_server || !_network_advertise)
DoCommandP(0, -10000000, 0, NULL, CMD_MONEY_CHEAT); #endif
break; DoCommandP(0, -10000000, 0, NULL, CMD_MONEY_CHEAT);
case '2' | WKC_ALT: /* Update the coordinates of all station signs */ break;
UpdateAllStationVirtCoord();
break; case '2' | WKC_ALT: /* Update the coordinates of all station signs */
case '3' | WKC_ALT: UpdateAllStationVirtCoord();
case '4' | WKC_ALT: break;
break;
#endif #endif
case 'X': case 'X':
_display_opt ^= DO_TRANS_BUILDINGS; _display_opt ^= DO_TRANS_BUILDINGS;
MarkWholeScreenDirty(); MarkWholeScreenDirty();
break; break;
#ifdef ENABLE_NETWORK #ifdef ENABLE_NETWORK
case WKC_RETURN: case 'T' | WKC_SHIFT: case WKC_RETURN: case 'T' | WKC_SHIFT:
if (_networking) ShowNetworkChatQueryWindow(DESTTYPE_BROADCAST, 0); if (_networking) ShowNetworkChatQueryWindow(DESTTYPE_BROADCAST, 0);
break; break;
#endif #endif
default: return; default: return;
} }
e->keypress.cont = false; e->keypress.cont = false;
break; break;
} }
} }
@ -2402,11 +2405,11 @@ extern void ShowJoinStatusWindowAfterJoin(void);
void SetupColorsAndInitialWindow(void) void SetupColorsAndInitialWindow(void)
{ {
int i; uint i;
Window *w; Window *w;
int width,height; int width,height;
for(i=0; i!=16; i++) { for (i = 0; i != 16; i++) {
const byte* b = GetNonSprite(0x307 + i); const byte* b = GetNonSprite(0x307 + i);
assert(b); assert(b);
@ -2417,7 +2420,7 @@ void SetupColorsAndInitialWindow(void)
height = _screen.height; height = _screen.height;
// XXX: these are not done // XXX: these are not done
switch(_game_mode) { switch (_game_mode) {
case GM_MENU: case GM_MENU:
w = AllocateWindow(0, 0, width, height, MainWindowWndProc, WC_MAIN_WINDOW, NULL); w = AllocateWindow(0, 0, width, height, MainWindowWndProc, WC_MAIN_WINDOW, NULL);
AssignWindowViewport(w, 0, 0, width, height, TileXY(32, 32), 0); AssignWindowViewport(w, 0, 0, width, height, TileXY(32, 32), 0);

View File

@ -86,7 +86,10 @@ static void LandInfoWndProc(Window *w, WindowEvent *e)
for (i = 0; i < NUM_CARGO; ++i) { for (i = 0; i < NUM_CARGO; ++i) {
if (lid->ac[i] > 0) { if (lid->ac[i] > 0) {
// Add a comma between each item. // Add a comma between each item.
if (found) { *p++ = ','; *p++ = ' '; } if (found) {
*p++ = ',';
*p++ = ' ';
}
found = true; found = true;
// If the accepted value is less than 8, show it in 1/8:ths // If the accepted value is less than 8, show it in 1/8:ths
@ -101,8 +104,7 @@ static void LandInfoWndProc(Window *w, WindowEvent *e)
} }
} }
if (found) if (found) DrawStringMultiCenter(140, 76, BindCString(buf), 276);
DrawStringMultiCenter(140, 76, BindCString(buf), 276);
} }
if (lid->td.build_date != 0) { if (lid->td.build_date != 0) {
@ -221,7 +223,7 @@ static const char *credits[] = {
static void AboutWindowProc(Window *w, WindowEvent *e) static void AboutWindowProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_CREATE: /* Set up window counter and start position of scroller */ case WE_CREATE: /* Set up window counter and start position of scroller */
WP(w, scroller_d).counter = 0; WP(w, scroller_d).counter = 0;
WP(w, scroller_d).height = w->height - 40; WP(w, scroller_d).height = w->height - 40;
@ -292,7 +294,7 @@ static const uint32 _tree_sprites[] = {
static void BuildTreesWndProc(Window *w, WindowEvent *e) static void BuildTreesWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
int x,y; int x,y;
int i, count; int i, count;
@ -308,24 +310,24 @@ static void BuildTreesWndProc(Window *w, WindowEvent *e)
DrawSprite(_tree_sprites[i], x, y); DrawSprite(_tree_sprites[i], x, y);
x += 35; x += 35;
if (!(++i & 3)) { if (!(++i & 3)) {
x -= 35*4; x -= 35 * 4;
y += 47; y += 47;
} }
} while (--count); } while (--count);
} break; } break;
case WE_CLICK: { case WE_CLICK: {
int wid; int wid = e->click.widget;
switch(wid=e->click.widget) { switch (wid) {
case 0: case 0:
ResetObjectToPlace(); ResetObjectToPlace();
return; break;
case 3: case 4: case 5: case 6: case 3: case 4: case 5: case 6:
case 7: case 8: case 9: case 10: case 7: case 8: case 9: case 10:
case 11:case 12: case 13: case 14: case 11:case 12: case 13: case 14:
if ( (uint)(wid-3) >= (uint)WP(w,tree_d).count) if (wid - 3 >= WP(w,tree_d).count) break;
return;
if (HandlePlacePushButton(w, wid, SPR_CURSOR_TREE, 1, NULL)) if (HandlePlacePushButton(w, wid, SPR_CURSOR_TREE, 1, NULL))
_tree_to_plant = WP(w,tree_d).base + wid - 3; _tree_to_plant = WP(w,tree_d).base + wid - 3;
@ -462,7 +464,7 @@ static const Widget _errmsg_face_widgets[] = {
static void ErrmsgWndProc(Window *w, WindowEvent *e) static void ErrmsgWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
COPY_IN_DPARAM(0, _errmsg_decode_params, lengthof(_errmsg_decode_params)); COPY_IN_DPARAM(0, _errmsg_decode_params, lengthof(_errmsg_decode_params));
DrawWindowWidgets(w); DrawWindowWidgets(w);
@ -498,18 +500,17 @@ static void ErrmsgWndProc(Window *w, WindowEvent *e)
break; break;
case WE_MOUSELOOP: case WE_MOUSELOOP:
if (_right_button_down) if (_right_button_down) DeleteWindow(w);
DeleteWindow(w);
break; break;
case WE_4: case WE_4:
if (!--_errmsg_duration) if (--_errmsg_duration == 0) DeleteWindow(w);
DeleteWindow(w);
break; break;
case WE_DESTROY: {
case WE_DESTROY:
SetRedErrorSquare(0); SetRedErrorSquare(0);
_switch_mode_errorstr = INVALID_STRING_ID; _switch_mode_errorstr = INVALID_STRING_ID;
break; break;
}
case WE_KEYPRESS: case WE_KEYPRESS:
if (e->keypress.keycode == WKC_SPACE) { if (e->keypress.keycode == WKC_SPACE) {
@ -619,18 +620,16 @@ static const Widget _tooltips_widgets[] = {
static void TooltipsWndProc(Window *w, WindowEvent *e) static void TooltipsWndProc(Window *w, WindowEvent *e)
{ {
switch (e->event) {
case WE_PAINT:
GfxFillRect(0, 0, w->width - 1, w->height - 1, 0);
GfxFillRect(1, 1, w->width - 2, w->height - 2, 0x44);
DrawStringMultiCenter((w->width >> 1), (w->height >> 1) - 5, WP(w,tooltips_d).string_id, 197);
break;
switch(e->event) { case WE_MOUSELOOP:
case WE_PAINT: { if (!_right_button_down) DeleteWindow(w);
GfxFillRect(0, 0, w->width - 1, w->height - 1, 0); break;
GfxFillRect(1, 1, w->width - 2, w->height - 2, 0x44);
DrawStringMultiCenter((w->width>>1), (w->height>>1)-5, WP(w,tooltips_d).string_id, 197);
break;
}
case WE_MOUSELOOP:
if (!_right_button_down)
DeleteWindow(w);
break;
} }
} }
@ -641,8 +640,7 @@ void GuiShowTooltips(StringID string_id)
int right,bottom; int right,bottom;
int x,y; int x,y;
if (string_id == 0) if (string_id == 0) return;
return;
w = FindWindowById(WC_TOOLTIPS, 0); w = FindWindowById(WC_TOOLTIPS, 0);
if (w != NULL) { if (w != NULL) {
@ -941,8 +939,7 @@ bool HandleCaret(Textbuf *tb)
void HandleEditBox(Window *w, int wid) void HandleEditBox(Window *w, int wid)
{ {
if (HandleCaret(&WP(w, querystr_d).text)) if (HandleCaret(&WP(w, querystr_d).text)) InvalidateWidget(w, wid);
InvalidateWidget(w, wid);
} }
void DrawEditBox(Window *w, int wid) void DrawEditBox(Window *w, int wid)
@ -1012,7 +1009,7 @@ press_ok:;
} break; } break;
case WE_KEYPRESS: { case WE_KEYPRESS: {
switch(HandleEditBoxKey(w, 5, e)) { switch (HandleEditBoxKey(w, 5, e)) {
case 1: // Return case 1: // Return
goto press_ok; goto press_ok;
case 2: // Escape case 2: // Escape
@ -1240,12 +1237,16 @@ static void SaveLoadDlgWndProc(Window *w, WindowEvent *e)
case WE_CREATE: { /* Set up OPENTTD button */ case WE_CREATE: { /* Set up OPENTTD button */
o_dir.type = FIOS_TYPE_DIRECT; o_dir.type = FIOS_TYPE_DIRECT;
switch (_saveload_mode) { switch (_saveload_mode) {
case SLD_SAVE_GAME: case SLD_LOAD_GAME: case SLD_SAVE_GAME:
case SLD_LOAD_GAME:
ttd_strlcpy(&o_dir.name[0], _path.save_dir, sizeof(o_dir.name)); ttd_strlcpy(&o_dir.name[0], _path.save_dir, sizeof(o_dir.name));
break; break;
case SLD_SAVE_SCENARIO: case SLD_LOAD_SCENARIO:
case SLD_SAVE_SCENARIO:
case SLD_LOAD_SCENARIO:
ttd_strlcpy(&o_dir.name[0], _path.scenario_dir, sizeof(o_dir.name)); ttd_strlcpy(&o_dir.name[0], _path.scenario_dir, sizeof(o_dir.name));
break; break;
default: default:
ttd_strlcpy(&o_dir.name[0], _path.personal_dir, sizeof(o_dir.name)); ttd_strlcpy(&o_dir.name[0], _path.personal_dir, sizeof(o_dir.name));
} }
@ -1308,12 +1309,12 @@ static void SaveLoadDlgWndProc(Window *w, WindowEvent *e)
char *name; char *name;
const FiosItem *file; const FiosItem *file;
if (y < 0 || (y += w->vscroll.pos) >= w->vscroll.count) if (y < 0 || (y += w->vscroll.pos) >= w->vscroll.count) return;
return;
file = _fios_list + y; file = _fios_list + y;
if ((name = FiosBrowseTo(file)) != NULL) { name = FiosBrowseTo(file);
if (name != NULL) {
if (_saveload_mode == SLD_LOAD_GAME || _saveload_mode == SLD_LOAD_SCENARIO) { if (_saveload_mode == SLD_LOAD_GAME || _saveload_mode == SLD_LOAD_SCENARIO) {
_switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD; _switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD;
@ -1474,8 +1475,9 @@ void ShowSaveLoadDialog(int mode)
// pause is only used in single-player, non-editor mode, non-menu mode. It // pause is only used in single-player, non-editor mode, non-menu mode. It
// will be unpaused in the WE_DESTROY event handler. // will be unpaused in the WE_DESTROY event handler.
if(_game_mode != GM_MENU && !_networking && _game_mode != GM_EDITOR) if (_game_mode != GM_MENU && !_networking && _game_mode != GM_EDITOR) {
DoCommandP(0, 1, 0, NULL, CMD_PAUSE); DoCommandP(0, 1, 0, NULL, CMD_PAUSE);
}
BuildFileList(); BuildFileList();
@ -1500,9 +1502,11 @@ static const Widget _select_scenario_widgets[] = {
{ WIDGETS_END}, { WIDGETS_END},
}; };
static void SelectScenarioWndProc(Window *w, WindowEvent *e) { static void SelectScenarioWndProc(Window* w, WindowEvent* e)
{
const int list_start = 45; const int list_start = 45;
switch(e->event) {
switch (e->event) {
case WE_PAINT: case WE_PAINT:
{ {
int y,pos; int y,pos;
@ -1642,8 +1646,8 @@ static int32 ClickMoneyCheat(int32 p1, int32 p2)
// p1 player to set to, p2 is -1 or +1 (down/up) // p1 player to set to, p2 is -1 or +1 (down/up)
static int32 ClickChangePlayerCheat(int32 p1, int32 p2) static int32 ClickChangePlayerCheat(int32 p1, int32 p2)
{ {
while(p1 >= 0 && p1 < MAX_PLAYERS) { while (p1 >= 0 && p1 < MAX_PLAYERS) {
if (_players[p1].is_active) { if (_players[p1].is_active) {
_local_player = p1; _local_player = p1;
MarkWholeScreenDirty(); MarkWholeScreenDirty();
return _local_player; return _local_player;
@ -1657,8 +1661,8 @@ static int32 ClickChangePlayerCheat(int32 p1, int32 p2)
// p1 -1 or +1 (down/up) // p1 -1 or +1 (down/up)
static int32 ClickChangeClimateCheat(int32 p1, int32 p2) static int32 ClickChangeClimateCheat(int32 p1, int32 p2)
{ {
if(p1==-1) p1 = 3; if (p1 == -1) p1 = 3;
if(p1==4) p1 = 0; if (p1 == 4) p1 = 0;
_opt.landscape = p1; _opt.landscape = p1;
GfxLoadSprites(); GfxLoadSprites();
MarkWholeScreenDirty(); MarkWholeScreenDirty();
@ -1673,7 +1677,7 @@ static int32 ClickChangeDateCheat(int32 p1, int32 p2)
YearMonthDay ymd; YearMonthDay ymd;
ConvertDayToYMD(&ymd, _date); ConvertDayToYMD(&ymd, _date);
if((ymd.year==0 && p2==-1) || (ymd.year==170 && p2==1)) return _cur_year; if ((ymd.year == 0 && p2 == -1) || (ymd.year == 170 && p2 == 1)) return _cur_year;
SetDate(ConvertYMDToDay(_cur_year + p2, ymd.month, ymd.day)); SetDate(ConvertYMDToDay(_cur_year + p2, ymd.month, ymd.day));
EnginesMonthlyLoop(); EnginesMonthlyLoop();
@ -1761,11 +1765,9 @@ extern void DrawPlayerIcon(int p, int x, int y);
static void CheatsWndProc(Window *w, WindowEvent *e) static void CheatsWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
int clk = WP(w,def_d).data_1; int clk = WP(w,def_d).data_1;
const CheatEntry *ce = &_cheats_ui[0];
int32 val;
int x, y; int x, y;
int i; int i;
@ -1773,53 +1775,55 @@ static void CheatsWndProc(Window *w, WindowEvent *e)
DrawStringMultiCenter(200, 25, STR_CHEATS_WARNING, 350); DrawStringMultiCenter(200, 25, STR_CHEATS_WARNING, 350);
x=0; x = 0;
y=45; y = 45;
for (i = 0; i != lengthof(_cheats_ui); i++) {
const CheatEntry* ce = &_cheats_ui[i];
for(i=0; i!=lengthof(_cheats_ui); i++,ce++) {
DrawSprite((*ce->been_used) ? SPR_BOX_CHECKED : SPR_BOX_EMPTY, x + 5, y + 2); DrawSprite((*ce->been_used) ? SPR_BOX_CHECKED : SPR_BOX_EMPTY, x + 5, y + 2);
if (ce->type == CE_BOOL) { if (ce->type == CE_BOOL) {
DrawFrameRect(x+20, y+1, x+30+9, y+9, (*(bool*)ce->variable) ? 6 : 4, (*(bool*)ce->variable) ? FR_LOWERED : 0); DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, (*(bool*)ce->variable) ? 6 : 4, (*(bool*)ce->variable) ? FR_LOWERED : 0);
SetDParam(0, *(bool*)ce->variable ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF); SetDParam(0, *(bool*)ce->variable ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF);
} else if (ce->type == CE_CLICK) { } else if (ce->type == CE_CLICK) {
DrawFrameRect(x+20, y+1, x+30+9, y+9, 0, (WP(w,def_d).data_1 == i*2+1) ? FR_LOWERED : 0); DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, 0, (WP(w,def_d).data_1 == i * 2 + 1) ? FR_LOWERED : 0);
if (i == 0) if (i == 0) {
SetDParam64(0, (int64) 10000000); SetDParam64(0, 10000000);
else } else {
SetDParam(0, false); SetDParam(0, false);
}
} else { } else {
DrawFrameRect(x+20, y+1, x+20+9, y+9, 3, clk == i*2+1 ? FR_LOWERED : 0); int32 val;
DrawFrameRect(x+30, y+1, x+30+9, y+9, 3, clk == i*2+2 ? FR_LOWERED : 0);
DrawStringCentered(x+25, y+1, STR_6819, 0); DrawFrameRect(x + 20, y + 1, x + 20 + 9, y + 9, 3, clk == i * 2 + 1 ? FR_LOWERED : 0);
DrawStringCentered(x+35, y+1, STR_681A, 0); DrawFrameRect(x + 30, y + 1, x + 30 + 9, y + 9, 3, clk == i * 2 + 2 ? FR_LOWERED : 0);
DrawStringCentered(x + 25, y + 1, STR_6819, 0);
DrawStringCentered(x + 35, y + 1, STR_681A, 0);
val = ReadCE(ce); val = ReadCE(ce);
// set correct string for switch climate cheat // set correct string for switch climate cheat
if(ce->str==STR_CHEAT_SWITCH_CLIMATE) if (ce->str == STR_CHEAT_SWITCH_CLIMATE) val += STR_TEMPERATE_LANDSCAPE;
val += STR_TEMPERATE_LANDSCAPE;
SetDParam(0, val); SetDParam(0, val);
// display date for change date cheat // display date for change date cheat
if(ce->str==STR_CHEAT_CHANGE_DATE) if (ce->str == STR_CHEAT_CHANGE_DATE) SetDParam(0, _date);
SetDParam(0, _date);
// draw colored flag for change player cheat // draw colored flag for change player cheat
if(ce->str==STR_CHEAT_CHANGE_PLAYER) if (ce->str == STR_CHEAT_CHANGE_PLAYER) {
DrawPlayerIcon(_current_player, 156, y+2); DrawPlayerIcon(_current_player, 156, y + 2);
}
} }
DrawString(50, y+1, ce->str, 0); DrawString(50, y + 1, ce->str, 0);
y+=12; y += 12;
} }
break; break;
} }
case WE_CLICK: { case WE_CLICK: {
const CheatEntry *ce; const CheatEntry *ce;
uint btn = (e->click.pt.y - 46) / 12; uint btn = (e->click.pt.y - 46) / 12;
@ -1827,19 +1831,17 @@ static void CheatsWndProc(Window *w, WindowEvent *e)
uint x = e->click.pt.x; uint x = e->click.pt.x;
// not clicking a button? // not clicking a button?
if(!IS_INT_INSIDE(x, 20, 40) || btn>=lengthof(_cheats_ui)) if (!IS_INT_INSIDE(x, 20, 40) || btn >= lengthof(_cheats_ui)) break;
break;
ce = &_cheats_ui[btn]; ce = &_cheats_ui[btn];
oval = val = ReadCE(ce); oval = val = ReadCE(ce);
*ce->been_used = true; *ce->been_used = true;
switch(ce->type) { switch (ce->type) {
case CE_BOOL: { case CE_BOOL: {
val ^= 1; val ^= 1;
if (ce->click_proc != NULL) if (ce->click_proc != NULL) ce->click_proc(val, 0);
ce->click_proc(val, 0);
break; break;
} }
@ -1861,11 +1863,11 @@ static void CheatsWndProc(Window *w, WindowEvent *e)
} }
// take whatever the function returns // take whatever the function returns
val = ce->click_proc(val, (x>=30) ? 1 : -1); val = ce->click_proc(val, (x >= 30) ? 1 : -1);
if (val != oval)
WP(w,def_d).data_1 = btn * 2 + 1 + ((x>=30) ? 1 : 0);
if (val != oval) {
WP(w,def_d).data_1 = btn * 2 + 1 + ((x >= 30) ? 1 : 0);
}
break; break;
} }
} }
@ -1886,6 +1888,7 @@ static void CheatsWndProc(Window *w, WindowEvent *e)
break; break;
} }
} }
static const WindowDesc _cheats_desc = { static const WindowDesc _cheats_desc = {
240, 22, 400, 160, 240, 22, 400, 160,
WC_CHEATS,0, WC_CHEATS,0,

View File

@ -20,11 +20,11 @@ static byte _cur_playlist[33];
static byte _playlist_all[] = { static byte _playlist_all[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0
}; };
static byte _playlist_old_style[] = { static byte _playlist_old_style[] = {
1, 8, 2, 9, 14, 15, 19, 13, 0, 1, 8, 2, 9, 14, 15, 19, 13, 0
}; };
static byte _playlist_new_style[] = { static byte _playlist_new_style[] = {
@ -45,7 +45,7 @@ static byte * const _playlists[] = {
}; };
// Map the order of the song names to the numbers of the midi filenames // Map the order of the song names to the numbers of the midi filenames
static const int midi_idx[] = { static const byte midi_idx[] = {
0, // Tycoon DELUXE Theme 0, // Tycoon DELUXE Theme
2, // Easy Driver 2, // Easy Driver
3, // Little Red Diesel 3, // Little Red Diesel
@ -78,8 +78,7 @@ static void SkipToPrevSong(void)
byte t; byte t;
// empty playlist // empty playlist
if (b[0] == 0) if (b[0] == 0) return;
return;
// find the end // find the end
do p++; while (p[0] != 0); do p++; while (p[0] != 0);
@ -97,10 +96,12 @@ static void SkipToPrevSong(void)
static void SkipToNextSong(void) static void SkipToNextSong(void)
{ {
byte *b = _cur_playlist, t; byte* b = _cur_playlist;
byte t;
if ((t=b[0]) != 0) { t = b[0];
while (b[1]) { if (t != 0) {
while (b[1] != 0) {
b[0] = b[1]; b[0] = b[1];
b++; b++;
} }
@ -165,8 +166,7 @@ static void PlayPlaylistSong(void)
{ {
if (_cur_playlist[0] == 0) { if (_cur_playlist[0] == 0) {
SelectSongToPlay(); SelectSongToPlay();
if (_cur_playlist[0] == 0) if (_cur_playlist[0] == 0) return;
return;
} }
_music_wnd_cursong = _cur_playlist[0]; _music_wnd_cursong = _cur_playlist[0];
DoPlaySong(); DoPlaySong();
@ -189,16 +189,16 @@ void MusicLoop(void)
PlayPlaylistSong(); PlayPlaylistSong();
} }
if (_song_is_active == false) if (_song_is_active == false) return;
return;
if (!_music_driver->is_song_playing()) { if (!_music_driver->is_song_playing()) {
if (_game_mode != GM_MENU) { if (_game_mode != GM_MENU) {
StopMusic(); StopMusic();
SkipToNextSong(); SkipToNextSong();
PlayPlaylistSong(); PlayPlaylistSong();
} else } else {
ResetMusic(); ResetMusic();
}
} }
} }
@ -229,18 +229,18 @@ static void MusicTrackSelectionWndProc(Window *w, WindowEvent *e)
DrawString(4, 23+(i-1)*6, (i < 10) ? STR_01EC_0 : STR_01ED, 0); DrawString(4, 23+(i-1)*6, (i < 10) ? STR_01EC_0 : STR_01ED, 0);
} }
for(i=0; i!=6; i++) { for (i = 0; i != 6; i++) {
DrawStringCentered(216, 45 + i*8, STR_01D5_ALL + i, (i==msf.playlist) ? 0xC : 0x10); DrawStringCentered(216, 45 + i * 8, STR_01D5_ALL + i, (i == msf.playlist) ? 0xC : 0x10);
} }
DrawStringCentered(216, 45+8*6+16, STR_01F0_CLEAR, 0); DrawStringCentered(216, 45+8*6+16, STR_01F0_CLEAR, 0);
DrawStringCentered(216, 45+8*6+16*2, STR_01F1_SAVE, 0); DrawStringCentered(216, 45+8*6+16*2, STR_01F1_SAVE, 0);
y = 23; y = 23;
for(p = _playlists[msf.playlist],i=0; (i=*p) != 0; p++) { for (p = _playlists[msf.playlist], i = 0; (i = *p) != 0; p++) {
SetDParam(0, i); SetDParam(0, i);
SetDParam(2, i);
SetDParam(1, SPECSTR_SONGNAME); SetDParam(1, SPECSTR_SONGNAME);
SetDParam(2, i);
DrawString(252, y, (i < 10) ? STR_01EC_0 : STR_01ED, 0); DrawString(252, y, (i < 10) ? STR_01EC_0 : STR_01ED, 0);
y += 6; y += 6;
} }
@ -248,19 +248,20 @@ static void MusicTrackSelectionWndProc(Window *w, WindowEvent *e)
} }
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 3: { /* add to playlist */ case 3: { /* add to playlist */
int y = (e->click.pt.y - 23) / 6; int y = (e->click.pt.y - 23) / 6;
int i; uint i;
byte *p; byte *p;
if (msf.playlist < 4) return; if (msf.playlist < 4) return;
if ((uint)y >= NUM_SONGS_AVAILABLE) return; if (!IS_INT_INSIDE(y, 0, NUM_SONGS_AVAILABLE)) return;
p = _playlists[msf.playlist]; p = _playlists[msf.playlist];
for(i=0; i!=32; i++) { for (i = 0; i != 32; i++) {
if (p[i] == 0) { if (p[i] == 0) {
p[i] = (byte)(y + 1); p[i] = y + 1;
p[i+1] = 0; p[i + 1] = 0;
SetWindowDirty(w); SetWindowDirty(w);
SelectSongToPlay(); SelectSongToPlay();
break; break;
@ -323,7 +324,7 @@ static void MusicWindowWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch(e->event) {
case WE_PAINT: { case WE_PAINT: {
int i,num; uint i;
StringID str; StringID str;
w->click_state |= 0x280; w->click_state |= 0x280;
@ -331,8 +332,7 @@ static void MusicWindowWndProc(Window *w, WindowEvent *e)
GfxFillRect(187, 16, 200, 33, 0); GfxFillRect(187, 16, 200, 33, 0);
num = 8; for (i = 0; i != 8; i++) {
for (i=0; i!=num; i++) {
int color = 0xD0; int color = 0xD0;
if (i > 4) { if (i > 4) {
color = 0xBF; color = 0xBF;
@ -340,17 +340,16 @@ static void MusicWindowWndProc(Window *w, WindowEvent *e)
color = 0xB8; color = 0xB8;
} }
} }
GfxFillRect(187, 33 - i*2, 200, 33 - i*2, color); GfxFillRect(187, 33 - i * 2, 200, 33 - i * 2, color);
} }
GfxFillRect(60, 46, 239, 52, 0); GfxFillRect(60, 46, 239, 52, 0);
str = STR_01E3; if (_song_is_active == 0 || _music_wnd_cursong == 0) {
if (_song_is_active != 0 && _music_wnd_cursong != 0) { str = STR_01E3;
str = STR_01E4_0; } else {
SetDParam(0, _music_wnd_cursong); SetDParam(0, _music_wnd_cursong);
if (_music_wnd_cursong >= 10) str = (_music_wnd_cursong < 10) ? STR_01E4_0 : STR_01E5;
str = STR_01E5;
} }
DrawString(62, 46, str, 0); DrawString(62, 46, str, 0);
@ -365,8 +364,8 @@ static void MusicWindowWndProc(Window *w, WindowEvent *e)
DrawString(60, 38, STR_01E8_TRACK_XTITLE, 0); DrawString(60, 38, STR_01E8_TRACK_XTITLE, 0);
for(i=0; i!=6; i++) { for (i = 0; i != 6; i++) {
DrawStringCentered(25+i*50, 59, STR_01D5_ALL+i, msf.playlist == i ? 0xC : 0x10); DrawStringCentered(25 + i * 50, 59, STR_01D5_ALL + i, msf.playlist == i ? 0xC : 0x10);
} }
DrawStringCentered(31, 43, STR_01E9_SHUFFLE, (msf.shuffle ? 0xC : 0x10)); DrawStringCentered(31, 43, STR_01E9_SHUFFLE, (msf.shuffle ? 0xC : 0x10));

View File

@ -1257,7 +1257,7 @@ static void NetworkGenerateUniqueId(void)
/* Generate the MD5 hash */ /* Generate the MD5 hash */
md5_init(&state); md5_init(&state);
md5_append(&state, coding_string, strlen(coding_string)); md5_append(&state, (const md5_byte_t*)coding_string, strlen(coding_string));
md5_finish(&state, digest); md5_finish(&state, digest);
for (di = 0; di < 16; ++di) for (di = 0; di < 16; ++di)

View File

@ -62,11 +62,10 @@ static FiosItem *_selected_map = NULL; // to highlight slected map
// called when a new server is found on the network // called when a new server is found on the network
void UpdateNetworkGameWindow(bool unselect) void UpdateNetworkGameWindow(bool unselect)
{ {
Window *w; Window* w = FindWindowById(WC_NETWORK_WINDOW, 0);
w = FindWindowById(WC_NETWORK_WINDOW, 0);
if (w != NULL) { if (w != NULL) {
if (unselect) if (unselect) _selected_item = NULL;
_selected_item = NULL;
w->vscroll.count = _network_game_count; w->vscroll.count = _network_game_count;
SetWindowDirty(w); SetWindowDirty(w);
} }
@ -123,8 +122,8 @@ static void NetworkGameWindowWndProc(Window *w, WindowEvent *e)
while (cur_item != NULL) { while (cur_item != NULL) {
bool compatible = bool compatible =
!strncmp(cur_item->info.server_revision, _openttd_revision, NETWORK_REVISION_LENGTH - 1) || strncmp(cur_item->info.server_revision, _openttd_revision, NETWORK_REVISION_LENGTH - 1) == 0 ||
!strncmp(cur_item->info.server_revision, NOREV_STRING, sizeof(cur_item->info.server_revision)); strncmp(cur_item->info.server_revision, NOREV_STRING, sizeof(cur_item->info.server_revision) == 0);
if (cur_item == sel) if (cur_item == sel)
GfxFillRect(11, y - 2, 218, y + 9, 10); // show highlighted item with a different colour GfxFillRect(11, y - 2, 218, y + 9, 10); // show highlighted item with a different colour
@ -138,10 +137,8 @@ static void NetworkGameWindowWndProc(Window *w, WindowEvent *e)
// only draw icons if the server is online // only draw icons if the server is online
if (cur_item->online) { if (cur_item->online) {
// draw a lock if the server is password protected. // draw a lock if the server is password protected.
if(cur_item->info.use_password) if (cur_item->info.use_password) DrawSprite(SPR_LOCK, 186, y - 1);
DrawSprite(SPR_LOCK, 186, y-1);
// draw red or green icon, depending on compatibility with server. // draw red or green icon, depending on compatibility with server.
DrawSprite(SPR_BLOT | (compatible ? PALETTE_TO_GREEN : PALETTE_TO_RED), 195, y); DrawSprite(SPR_BLOT | (compatible ? PALETTE_TO_GREEN : PALETTE_TO_RED), 195, y);
@ -180,43 +177,43 @@ static void NetworkGameWindowWndProc(Window *w, WindowEvent *e)
SetDParam(0, sel->info.clients_on); SetDParam(0, sel->info.clients_on);
SetDParam(1, sel->info.clients_max); SetDParam(1, sel->info.clients_max);
DrawString(260, y, STR_NETWORK_CLIENTS, 2); // clients on the server / maximum slots DrawString(260, y, STR_NETWORK_CLIENTS, 2); // clients on the server / maximum slots
y+=10; y += 10;
if (sel->info.server_lang < NETWORK_NUM_LANGUAGES) { if (sel->info.server_lang < NETWORK_NUM_LANGUAGES) {
SetDParam(0, STR_NETWORK_LANG_ANY+sel->info.server_lang); SetDParam(0, STR_NETWORK_LANG_ANY + sel->info.server_lang);
DrawString(260, y, STR_NETWORK_LANGUAGE, 2); // server language DrawString(260, y, STR_NETWORK_LANGUAGE, 2); // server language
} }
y+=10; y += 10;
if (sel->info.map_set < NUM_LANDSCAPE ) { if (sel->info.map_set < NUM_LANDSCAPE ) {
SetDParam(0, STR_TEMPERATE_LANDSCAPE+sel->info.map_set); SetDParam(0, STR_TEMPERATE_LANDSCAPE + sel->info.map_set);
DrawString(260, y, STR_NETWORK_TILESET, 2); // tileset DrawString(260, y, STR_NETWORK_TILESET, 2); // tileset
} }
y+=10; y += 10;
SetDParam(0, sel->info.map_width); SetDParam(0, sel->info.map_width);
SetDParam(1, sel->info.map_height); SetDParam(1, sel->info.map_height);
DrawString(260, y, STR_NETWORK_MAP_SIZE, 2); // map size DrawString(260, y, STR_NETWORK_MAP_SIZE, 2); // map size
y+=10; y += 10;
SetDParamStr(0, sel->info.server_revision); SetDParamStr(0, sel->info.server_revision);
DrawString(260, y, STR_NETWORK_SERVER_VERSION, 2); // server version DrawString(260, y, STR_NETWORK_SERVER_VERSION, 2); // server version
y+=10; y += 10;
SetDParamStr(0, sel->info.hostname); SetDParamStr(0, sel->info.hostname);
SetDParam(1, sel->port); SetDParam(1, sel->port);
DrawString(260, y, STR_NETWORK_SERVER_ADDRESS, 2); // server address DrawString(260, y, STR_NETWORK_SERVER_ADDRESS, 2); // server address
y+=10; y += 10;
SetDParam(0, sel->info.start_date); SetDParam(0, sel->info.start_date);
DrawString(260, y, STR_NETWORK_START_DATE, 2); // start date DrawString(260, y, STR_NETWORK_START_DATE, 2); // start date
y+=10; y += 10;
SetDParam(0, sel->info.game_date); SetDParam(0, sel->info.game_date);
DrawString(260, y, STR_NETWORK_CURRENT_DATE, 2); // current date DrawString(260, y, STR_NETWORK_CURRENT_DATE, 2); // current date
y+=10; y += 10;
y+=2; y += 2;
if (strncmp(sel->info.server_revision, _openttd_revision, NETWORK_REVISION_LENGTH - 1) != 0) { if (strncmp(sel->info.server_revision, _openttd_revision, NETWORK_REVISION_LENGTH - 1) != 0) {
if (strncmp(sel->info.server_revision, NOREV_STRING, sizeof(sel->info.server_revision)) != 0) if (strncmp(sel->info.server_revision, NOREV_STRING, sizeof(sel->info.server_revision)) != 0)
@ -224,10 +221,11 @@ static void NetworkGameWindowWndProc(Window *w, WindowEvent *e)
} else if (sel->info.clients_on == sel->info.clients_max) { } else if (sel->info.clients_on == sel->info.clients_max) {
// Show: server full, when clients_on == clients_max // Show: server full, when clients_on == clients_max
DrawStringMultiCenter(365, y, STR_NETWORK_SERVER_FULL, 2); // server full DrawStringMultiCenter(365, y, STR_NETWORK_SERVER_FULL, 2); // server full
} else if (sel->info.use_password) } else if (sel->info.use_password) {
DrawStringMultiCenter(365, y, STR_NETWORK_PASSWORD, 2); // password warning DrawStringMultiCenter(365, y, STR_NETWORK_PASSWORD, 2); // password warning
}
y+=10; y += 10;
} }
} break; } break;
@ -306,9 +304,7 @@ static void NetworkGameWindowWndProc(Window *w, WindowEvent *e)
break; break;
case WE_MOUSELOOP: case WE_MOUSELOOP:
if (_selected_field == 3) if (_selected_field == 3) HandleEditBox(w, 3);
HandleEditBox(w, 3);
break; break;
case WE_KEYPRESS: case WE_KEYPRESS:
@ -331,10 +327,11 @@ static void NetworkGameWindowWndProc(Window *w, WindowEvent *e)
if (HandleEditBoxKey(w, 3, e) == 1) break; // enter pressed if (HandleEditBoxKey(w, 3, e) == 1) break; // enter pressed
// The name is only allowed when it starts with a letter! // The name is only allowed when it starts with a letter!
if (_edit_str_buf[0] != '\0' && _edit_str_buf[0] != ' ') if (_edit_str_buf[0] != '\0' && _edit_str_buf[0] != ' ') {
ttd_strlcpy(_network_player_name, _edit_str_buf, lengthof(_network_player_name)); ttd_strlcpy(_network_player_name, _edit_str_buf, lengthof(_network_player_name));
else } else {
ttd_strlcpy(_network_player_name, "Player", lengthof(_network_player_name)); ttd_strlcpy(_network_player_name, "Player", lengthof(_network_player_name));
}
break; break;
@ -396,7 +393,7 @@ void ShowNetworkGameWindow(void)
if (_first_time_show_network_game_window) { if (_first_time_show_network_game_window) {
_first_time_show_network_game_window = false; _first_time_show_network_game_window = false;
// add all servers from the config file to our list // add all servers from the config file to our list
for (i=0; i != lengthof(_network_host_list); i++) { for (i = 0; i != lengthof(_network_host_list); i++) {
if (_network_host_list[i] == NULL) break; if (_network_host_list[i] == NULL) break;
NetworkAddServer(_network_host_list[i]); NetworkAddServer(_network_host_list[i]);
} }
@ -489,18 +486,22 @@ static void NetworkStartServerWindowWndProc(Window *w, WindowEvent *e)
case WE_CLICK: case WE_CLICK:
_selected_field = e->click.widget; _selected_field = e->click.widget;
switch(e->click.widget) { switch (e->click.widget) {
case 0: case 15: /* Close 'X' | Cancel button */ case 0: /* Close 'X' */
case 15: /* Cancel button */
ShowNetworkGameWindow(); ShowNetworkGameWindow();
break; break;
case 4: { /* Set password button */
case 4: /* Set password button */
ShowQueryString(BindCString(_network_server_password), ShowQueryString(BindCString(_network_server_password),
STR_NETWORK_SET_PASSWORD, 20, 250, w->window_class, w->window_number); STR_NETWORK_SET_PASSWORD, 20, 250, w->window_class, w->window_number);
} break; break;
case 5: { /* Select map */ case 5: { /* Select map */
int y = (e->click.pt.y - NSSWND_START) / NSSWND_ROWSIZE; int y = (e->click.pt.y - NSSWND_START) / NSSWND_ROWSIZE;
if ((y += w->vscroll.pos) >= w->vscroll.count)
return; y += w->vscroll.pos;
if (y >= w->vscroll.count) return;
_selected_map = (y == 0) ? NULL : _fios_list + y - 1; _selected_map = (y == 0) ? NULL : _fios_list + y - 1;
SetWindowDirty(w); SetWindowDirty(w);
@ -561,18 +562,15 @@ static void NetworkStartServerWindowWndProc(Window *w, WindowEvent *e)
break; break;
case WE_MOUSELOOP: case WE_MOUSELOOP:
if (_selected_field == 3) if (_selected_field == 3) HandleEditBox(w, 3);
HandleEditBox(w, 3);
break; break;
case WE_KEYPRESS: case WE_KEYPRESS:
if (_selected_field == 3) if (_selected_field == 3) HandleEditBoxKey(w, 3, e);
HandleEditBoxKey(w, 3, e);
break; break;
case WE_ON_EDIT_TEXT: { case WE_ON_EDIT_TEXT: {
const char *b = e->edittext.str; ttd_strlcpy(_network_server_password, e->edittext.str, lengthof(_network_server_password));
ttd_strlcpy(_network_server_password, b, sizeof(_network_server_password));
_network_game_info.use_password = (_network_server_password[0] != '\0'); _network_game_info.use_password = (_network_server_password[0] != '\0');
SetWindowDirty(w); SetWindowDirty(w);
} break; } break;
@ -636,12 +634,12 @@ static void ShowNetworkStartServerWindow(void)
static byte NetworkLobbyFindCompanyIndex(byte pos) static byte NetworkLobbyFindCompanyIndex(byte pos)
{ {
byte i; byte i;
/* Scroll through all _network_player_info and get the 'pos' item /* Scroll through all _network_player_info and get the 'pos' item
that is not empty */ that is not empty */
for (i = 0; i < MAX_PLAYERS; i++) { for (i = 0; i < MAX_PLAYERS; i++) {
if (_network_player_info[i].company_name[0] != '\0') { if (_network_player_info[i].company_name[0] != '\0') {
if (pos-- == 0) if (pos-- == 0) return i;
return i;
} }
} }
@ -650,7 +648,7 @@ static byte NetworkLobbyFindCompanyIndex(byte pos)
static void NetworkLobbyWindowWndProc(Window *w, WindowEvent *e) static void NetworkLobbyWindowWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
int y = NET_PRC__OFFSET_TOP_WIDGET_COMPANY, pos; int y = NET_PRC__OFFSET_TOP_WIDGET_COMPANY, pos;
@ -678,7 +676,7 @@ static void NetworkLobbyWindowWndProc(Window *w, WindowEvent *e)
GfxFillRect(11, y - 1, 154, y + 10, 155); // show highlighted item with a different colour GfxFillRect(11, y - 1, 154, y + 10, 155); // show highlighted item with a different colour
DoDrawString(_network_player_info[index].company_name, 13, y, 2); DoDrawString(_network_player_info[index].company_name, 13, y, 2);
if(_network_player_info[index].use_password != 0) if (_network_player_info[index].use_password != 0)
DrawSprite(SPR_LOCK, 135, y); DrawSprite(SPR_LOCK, 135, y);
/* If the company's income was positive puts a green dot else a red dot */ /* If the company's income was positive puts a green dot else a red dot */
@ -688,8 +686,7 @@ static void NetworkLobbyWindowWndProc(Window *w, WindowEvent *e)
pos++; pos++;
y += NET_PRC__SIZE_OF_ROW_COMPANY; y += NET_PRC__SIZE_OF_ROW_COMPANY;
if (pos >= w->vscroll.cap) if (pos >= w->vscroll.cap) break;
break;
} }
// draw info about selected company // draw info about selected company
@ -1087,7 +1084,7 @@ static Window *PopupClientList(Window *w, int client_no, int x, int y)
// Main handle for the popup // Main handle for the popup
static void ClientListPopupWndProc(Window *w, WindowEvent *e) static void ClientListPopupWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
int i, y, sel; int i, y, sel;
byte colour; byte colour;
@ -1141,7 +1138,7 @@ static void ClientListPopupWndProc(Window *w, WindowEvent *e)
// Main handle for clientlist // Main handle for clientlist
static void ClientListWndProc(Window *w, WindowEvent *e) static void ClientListWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
NetworkClientInfo *ci; NetworkClientInfo *ci;
int y, i = 0; int y, i = 0;
@ -1166,8 +1163,9 @@ static void ClientListWndProc(Window *w, WindowEvent *e)
if (ci->client_index == NETWORK_SERVER_INDEX) { if (ci->client_index == NETWORK_SERVER_INDEX) {
DrawString(4, y, STR_NETWORK_SERVER, colour); DrawString(4, y, STR_NETWORK_SERVER, colour);
} else } else {
DrawString(4, y, STR_NETWORK_CLIENT, colour); DrawString(4, y, STR_NETWORK_CLIENT, colour);
}
// Filter out spectators // Filter out spectators
if (ci->client_playas > 0 && ci->client_playas <= MAX_PLAYERS) if (ci->client_playas > 0 && ci->client_playas <= MAX_PLAYERS)
@ -1220,15 +1218,14 @@ static void ClientListWndProc(Window *w, WindowEvent *e)
void ShowClientList(void) void ShowClientList(void)
{ {
Window *w = AllocateWindowDescFront(&_client_list_desc, 0); Window *w = AllocateWindowDescFront(&_client_list_desc, 0);
if (w) if (w != NULL) w->window_number = 0;
w->window_number = 0;
} }
extern void SwitchMode(int new_mode); extern void SwitchMode(int new_mode);
static void NetworkJoinStatusWindowWndProc(Window *w, WindowEvent *e) static void NetworkJoinStatusWindowWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
uint8 progress; // used for progress bar uint8 progress; // used for progress bar
DrawWindowWidgets(w); DrawWindowWidgets(w);
@ -1258,13 +1255,14 @@ static void NetworkJoinStatusWindowWndProc(Window *w, WindowEvent *e)
} break; } break;
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 0: case 3: /* Close 'X' | Disconnect button */ case 0: /* Close 'X' */
NetworkDisconnect(); case 3: /* Disconnect button */
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0); NetworkDisconnect();
SwitchMode(SM_MENU); DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
ShowNetworkGameWindow(); SwitchMode(SM_MENU);
break; ShowNetworkGameWindow();
break;
} }
break; break;
@ -1311,6 +1309,7 @@ void ShowJoinStatusWindowAfterJoin(void)
static void ChatWindowWndProc(Window *w, WindowEvent *e) static void ChatWindowWndProc(Window *w, WindowEvent *e)
{ {
static bool closed = false; static bool closed = false;
switch (e->event) { switch (e->event) {
case WE_CREATE: case WE_CREATE:
SendWindowMessage(WC_NEWS_WINDOW, 0, WE_CREATE, w->height, 0); SendWindowMessage(WC_NEWS_WINDOW, 0, WE_CREATE, w->height, 0);
@ -1324,7 +1323,7 @@ static void ChatWindowWndProc(Window *w, WindowEvent *e)
break; break;
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 3: DeleteWindow(w); break; // Cancel case 3: DeleteWindow(w); break; // Cancel
case 2: // Send case 2: // Send
press_ok:; press_ok:;

View File

@ -376,8 +376,7 @@ static void ShowNewspaper(NewsItem *ni)
ni->duration = 555; ni->duration = 555;
sound = _news_sounds[ni->type]; sound = _news_sounds[ni->type];
if (sound != 0) if (sound != 0) SndPlayFx(sound);
SndPlayFx(sound);
top = _screen.height; top = _screen.height;
switch (ni->display_mode) { switch (ni->display_mode) {
@ -422,8 +421,7 @@ static void ShowTicker(const NewsItem *ni)
_statusbar_news_item = *ni; _statusbar_news_item = *ni;
w = FindWindowById(WC_STATUS_BAR, 0); w = FindWindowById(WC_STATUS_BAR, 0);
if (w != NULL) if (w != NULL) WP(w, def_d).data_1 = 360;
WP(w, def_d).data_1 = 360;
} }
@ -441,8 +439,7 @@ static bool ReadyForNextItem(void)
// Ticker message // Ticker message
// Check if the status bar message is still being displayed? // Check if the status bar message is still being displayed?
w = FindWindowById(WC_STATUS_BAR, 0); w = FindWindowById(WC_STATUS_BAR, 0);
if (w != NULL && WP(w, def_d).data_1 > -1280) if (w != NULL && WP(w, const def_d).data_1 > -1280) return false;
return false;
// Newspaper message // Newspaper message
// Wait until duration reaches 0 // Wait until duration reaches 0
@ -468,31 +465,33 @@ static void MoveToNexItem(void)
ni = &_news_items[_current_news]; ni = &_news_items[_current_news];
// check the date, don't show too old items // check the date, don't show too old items
if (_date - _news_items_age[ni->type] > ni->date) if (_date - _news_items_age[ni->type] > ni->date) return;
return;
// execute the validation function to see if this item is still valid // execute the validation function to see if this item is still valid
if ( ni->isValid != NULL && !ni->isValid(ni->data_a, ni->data_b) ) if (ni->isValid != NULL && !ni->isValid(ni->data_a, ni->data_b)) return;
return;
switch (GetNewsDisplayValue(ni->type)) {
case 0: { /* Off - show nothing only a small reminder in the status bar */
Window* w = FindWindowById(WC_STATUS_BAR, 0);
switch (GetNewsDisplayValue(ni->type)) {
case 0: { /* Off - show nothing only a small reminder in the status bar */
Window *w = FindWindowById(WC_STATUS_BAR, 0);
if (w != NULL) { if (w != NULL) {
WP(w, def_d).data_2 = 91; WP(w, def_d).data_2 = 91;
SetWindowDirty(w); SetWindowDirty(w);
} }
} break; break;
case 1: /* Summary - show ticker, but if forced big, cascade to full */ }
if (!(ni->flags & NF_FORCE_BIG)) {
ShowTicker(ni); case 1: /* Summary - show ticker, but if forced big, cascade to full */
break; if (!(ni->flags & NF_FORCE_BIG)) {
} ShowTicker(ni);
/* Fallthrough */ break;
case 2: /* Full - show newspaper*/ }
ShowNewspaper(ni); /* Fallthrough */
break;
} case 2: /* Full - show newspaper*/
ShowNewspaper(ni);
break;
}
} }
} }
@ -501,8 +500,7 @@ void NewsLoop(void)
// no news item yet // no news item yet
if (_total_news == 0) return; if (_total_news == 0) return;
if (ReadyForNextItem()) if (ReadyForNextItem()) MoveToNexItem();
MoveToNexItem();
} }
/* Do a forced show of a specific message */ /* Do a forced show of a specific message */
@ -541,13 +539,13 @@ void ShowLastNewsMessage(void)
recent news. Returns INVALID_NEWS if end of queue reached. */ recent news. Returns INVALID_NEWS if end of queue reached. */
static byte getNews(byte i) static byte getNews(byte i)
{ {
if (i >= _total_news) if (i >= _total_news) return INVALID_NEWS;
return INVALID_NEWS;
if (_latest_news < i) if (_latest_news < i) {
i = _latest_news + MAX_NEWS - i; i = _latest_news + MAX_NEWS - i;
else } else {
i = _latest_news - i; i = _latest_news - i;
}
i %= MAX_NEWS; i %= MAX_NEWS;
return i; return i;
@ -636,10 +634,11 @@ static void MessageHistoryWndProc(Window *w, WindowEvent *e)
p = y + w->vscroll.pos; p = y + w->vscroll.pos;
if (p > _total_news - 1) break; if (p > _total_news - 1) break;
if (_latest_news >= p) if (_latest_news >= p) {
q = _latest_news - p; q = _latest_news - p;
else } else {
q = _latest_news + MAX_NEWS - p; q = _latest_news + MAX_NEWS - p;
}
ShowNewsMessage(q); ShowNewsMessage(q);
break; break;

138
openttd.c
View File

@ -69,16 +69,17 @@ bool _dbg_screen_rect;
* caused by the user, i.e. missing files or fatal configuration errors. * caused by the user, i.e. missing files or fatal configuration errors.
* Post-0.4.0 since Celestar doesn't want this in SVN before. --pasky */ * Post-0.4.0 since Celestar doesn't want this in SVN before. --pasky */
void CDECL error(const char *s, ...) { void CDECL error(const char* s, ...)
{
va_list va; va_list va;
char buf[512]; char buf[512];
va_start(va, s); va_start(va, s);
vsprintf(buf, s, va); vsprintf(buf, s, va);
va_end(va); va_end(va);
ShowOSErrorBox(buf); ShowOSErrorBox(buf);
if (_video_driver) if (_video_driver != NULL) _video_driver->stop();
_video_driver->stop();
assert(0); assert(0);
exit(1); exit(1);
@ -102,8 +103,7 @@ void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize)
size_t len; size_t len;
in = fopen(filename, "rb"); in = fopen(filename, "rb");
if (in == NULL) if (in == NULL) return NULL;
return NULL;
fseek(in, 0, SEEK_END); fseek(in, 0, SEEK_END);
len = ftell(in); len = ftell(in);
@ -178,12 +178,12 @@ static int MyGetOpt(MyGetOptData *md)
{ {
char *s,*r,*t; char *s,*r,*t;
if ((s=md->cont) != NULL) s = md->cont;
if (s != NULL)
goto md_continue_here; goto md_continue_here;
while(true) { for (;;) {
if (--md->numleft < 0) if (--md->numleft < 0) return -1;
return -1;
s = *md->argv++; s = *md->argv++;
if (*s == '-') { if (*s == '-') {
@ -347,9 +347,9 @@ int ttd_main(int argc, char* argv[])
case 's': ttd_strlcpy(sounddriver, mgo.opt, sizeof(sounddriver)); break; case 's': ttd_strlcpy(sounddriver, mgo.opt, sizeof(sounddriver)); break;
case 'v': ttd_strlcpy(videodriver, mgo.opt, sizeof(videodriver)); break; case 'v': ttd_strlcpy(videodriver, mgo.opt, sizeof(videodriver)); break;
case 'D': { case 'D': {
sprintf(musicdriver,"null"); strcpy(musicdriver, "null");
sprintf(sounddriver,"null"); strcpy(sounddriver, "null");
sprintf(videodriver,"dedicated"); strcpy(videodriver, "dedicated");
dedicated = true; dedicated = true;
} break; } break;
case 'f': { case 'f': {
@ -364,23 +364,18 @@ int ttd_main(int argc, char* argv[])
network_conn = NULL; network_conn = NULL;
} break; } break;
case 'r': ParseResolution(resolution, mgo.opt); break; case 'r': ParseResolution(resolution, mgo.opt); break;
case 'l': { case 'l': language = mgo.opt; break;
language = mgo.opt; case 't': startdate = atoi(mgo.opt); break;
} break;
case 't': {
startdate = atoi(mgo.opt);
} break;
case 'd': { case 'd': {
#if defined(WIN32) #if defined(WIN32)
CreateConsole(); CreateConsole();
#endif #endif
if (mgo.opt) if (mgo.opt != NULL) SetDebugString(mgo.opt);
SetDebugString(mgo.opt);
} break; } break;
case 'e': _switch_mode = SM_EDITOR; break; case 'e': _switch_mode = SM_EDITOR; break;
case 'i': _use_dos_palette = true; break; case 'i': _use_dos_palette = true; break;
case 'g': case 'g':
if (mgo.opt) { if (mgo.opt != NULL) {
strcpy(_file_to_saveload.name, mgo.opt); strcpy(_file_to_saveload.name, mgo.opt);
_switch_mode = SM_LOAD; _switch_mode = SM_LOAD;
} else } else
@ -598,7 +593,7 @@ static void MakeNewGame(void)
// Copy in game options // Copy in game options
_opt_ptr = &_opt; _opt_ptr = &_opt;
memcpy(_opt_ptr, &_opt_newgame, sizeof(GameOptions)); memcpy(_opt_ptr, &_opt_newgame, sizeof(*_opt_ptr));
GfxLoadSprites(); GfxLoadSprites();
@ -643,7 +638,7 @@ static void MakeNewEditorWorld(void)
SetupColorsAndInitialWindow(); SetupColorsAndInitialWindow();
// Startup the game system // Startup the game system
GenerateWorld(1, 1<<_patches.map_x, 1<<_patches.map_y); GenerateWorld(1, 1 << _patches.map_x, 1 << _patches.map_y);
_local_player = OWNER_NONE; _local_player = OWNER_NONE;
MarkWholeScreenDirty(); MarkWholeScreenDirty();
@ -716,8 +711,9 @@ bool SafeSaveOrLoad(const char *filename, int mode, int newgm)
} else if (r != SL_OK) { } else if (r != SL_OK) {
_game_mode = ogm; _game_mode = ogm;
return false; return false;
} else } else {
return true; return true;
}
} }
void SwitchMode(int new_mode) void SwitchMode(int new_mode)
@ -804,9 +800,9 @@ void SwitchMode(int new_mode)
_generating_world = false; _generating_world = false;
// delete all stations owned by a player // delete all stations owned by a player
DeleteAllPlayerStations(); DeleteAllPlayerStations();
} else } else {
ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0); ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
}
break; break;
} }
@ -816,10 +812,11 @@ void SwitchMode(int new_mode)
break; break;
case SM_SAVE: /* Save game */ case SM_SAVE: /* Save game */
if (SaveOrLoad(_file_to_saveload.name, SL_SAVE) != SL_OK) if (SaveOrLoad(_file_to_saveload.name, SL_SAVE) != SL_OK) {
ShowErrorMessage(INVALID_STRING_ID, STR_4007_GAME_SAVE_FAILED, 0, 0); ShowErrorMessage(INVALID_STRING_ID, STR_4007_GAME_SAVE_FAILED, 0, 0);
else } else {
DeleteWindowById(WC_SAVELOAD, 0); DeleteWindowById(WC_SAVELOAD, 0);
}
break; break;
case SM_GENRANDLAND: /* Generate random land within scenario editor */ case SM_GENRANDLAND: /* Generate random land within scenario editor */
@ -847,8 +844,7 @@ void StateGameLoop(void)
// _frame_counter is increased somewhere else when in network-mode // _frame_counter is increased somewhere else when in network-mode
// Sidenote: _frame_counter is ONLY used for _savedump in non-MP-games // Sidenote: _frame_counter is ONLY used for _savedump in non-MP-games
// Should that not be deleted? If so, the next 2 lines can also be deleted // Should that not be deleted? If so, the next 2 lines can also be deleted
if (!_networking) if (!_networking) _frame_counter++;
_frame_counter++;
if (_savedump_path[0] && (uint)_frame_counter >= _savedump_first && (uint)(_frame_counter -_savedump_first) % _savedump_freq == 0 ) { if (_savedump_path[0] && (uint)_frame_counter >= _savedump_first && (uint)(_frame_counter -_savedump_first) % _savedump_freq == 0 ) {
char buf[100]; char buf[100];
@ -951,7 +947,6 @@ void GameLoop(void)
int m; int m;
ThreadMsg message; ThreadMsg message;
if ((message = OTTD_PollThreadEvent()) != 0) ProcessSentMessage(message); if ((message = OTTD_PollThreadEvent()) != 0) ProcessSentMessage(message);
// autosave game? // autosave game?
@ -987,13 +982,14 @@ void GameLoop(void)
IncreaseSpriteLRU(); IncreaseSpriteLRU();
InteractiveRandom(); InteractiveRandom();
if (_scroller_click_timeout > 3) if (_scroller_click_timeout > 3) {
_scroller_click_timeout -= 3; _scroller_click_timeout -= 3;
else } else {
_scroller_click_timeout = 0; _scroller_click_timeout = 0;
}
_caret_timer += 3; _caret_timer += 3;
_timer_counter+=8; _timer_counter += 8;
CursorTick(); CursorTick();
#ifdef ENABLE_NETWORK #ifdef ENABLE_NETWORK
@ -1016,11 +1012,9 @@ void GameLoop(void)
StateGameLoop(); StateGameLoop();
#endif /* ENABLE_NETWORK */ #endif /* ENABLE_NETWORK */
if (!_pause && _display_opt&DO_FULL_ANIMATION) if (!_pause && _display_opt & DO_FULL_ANIMATION) DoPaletteAnimations();
DoPaletteAnimations();
if (!_pause || _cheats.build_in_pause.value) if (!_pause || _cheats.build_in_pause.value) MoveAllTextEffects();
MoveAllTextEffects();
InputLoop(); InputLoop();
@ -1044,8 +1038,7 @@ static void ConvertTownOwner(void)
for (tile = 0; tile != MapSize(); tile++) { for (tile = 0; tile != MapSize(); tile++) {
if (IsTileType(tile, MP_STREET)) { if (IsTileType(tile, MP_STREET)) {
if (IsLevelCrossing(tile) && _m[tile].m3 & 0x80) if (IsLevelCrossing(tile) && _m[tile].m3 & 0x80) _m[tile].m3 = OWNER_TOWN;
_m[tile].m3 = OWNER_TOWN;
if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN); if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
} else if (IsTileType(tile, MP_TUNNELBRIDGE)) { } else if (IsTileType(tile, MP_TUNNELBRIDGE)) {
@ -1057,20 +1050,20 @@ static void ConvertTownOwner(void)
// before savegame version 4, the name of the company determined if it existed // before savegame version 4, the name of the company determined if it existed
static void CheckIsPlayerActive(void) static void CheckIsPlayerActive(void)
{ {
Player *p; Player* p;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (p->name_1 != 0) { if (p->name_1 != 0) p->is_active = true;
p->is_active = true;
}
} }
} }
// since savegame version 4.1, exclusive transport rights are stored at towns // since savegame version 4.1, exclusive transport rights are stored at towns
static void UpdateExclusiveRights(void) static void UpdateExclusiveRights(void)
{ {
Town *t; Town* t;
FOR_ALL_TOWNS(t) if (t->xy != 0) {
t->exclusivity=(byte)-1; FOR_ALL_TOWNS(t) {
if (t->xy != 0) t->exclusivity = (byte)-1;
} }
/* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete) /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
@ -1113,9 +1106,8 @@ static void UpdateVoidTiles(void)
static void UpdateSignOwner(void) static void UpdateSignOwner(void)
{ {
SignStruct *ss; SignStruct *ss;
FOR_ALL_SIGNS(ss) {
ss->owner = OWNER_NONE; // no owner FOR_ALL_SIGNS(ss) ss->owner = OWNER_NONE;
}
} }
extern void UpdateOldAircraft( void ); extern void UpdateOldAircraft( void );
@ -1128,24 +1120,16 @@ bool AfterLoadGame(uint version)
Player *p; Player *p;
// in version 2.1 of the savegame, town owner was unified. // in version 2.1 of the savegame, town owner was unified.
if (version <= 0x200) { if (version <= 0x200) ConvertTownOwner();
ConvertTownOwner();
}
// from version 4.1 of the savegame, exclusive rights are stored at towns // from version 4.1 of the savegame, exclusive rights are stored at towns
if (version <= 0x400) { if (version <= 0x400) UpdateExclusiveRights();
UpdateExclusiveRights();
}
// from version 4.2 of the savegame, currencies are in a different order // from version 4.2 of the savegame, currencies are in a different order
if (version <= 0x401) { if (version <= 0x401) UpdateCurrencies();
UpdateCurrencies();
}
// from version 6.0 of the savegame, signs have an "owner" // from version 6.0 of the savegame, signs have an "owner"
if (version <= 0x600) { if (version <= 0x600) UpdateSignOwner();
UpdateSignOwner();
}
/* In old version there seems to be a problem that water is owned by /* In old version there seems to be a problem that water is owned by
OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
@ -1178,15 +1162,12 @@ bool AfterLoadGame(uint version)
AfterLoadVehicles(); AfterLoadVehicles();
// Update all waypoints // Update all waypoints
if (version < 0x0C00) if (version < 0x0C00) FixOldWaypoints();
FixOldWaypoints();
UpdateAllWaypointSigns(); UpdateAllWaypointSigns();
// in version 2.2 of the savegame, we have new airports // in version 2.2 of the savegame, we have new airports
if (version <= 0x201) { if (version <= 0x201) UpdateOldAircraft();
UpdateOldAircraft();
}
UpdateAllStationVirtCoord(); UpdateAllStationVirtCoord();
@ -1195,8 +1176,7 @@ bool AfterLoadGame(uint version)
UpdateAllSignVirtCoords(); UpdateAllSignVirtCoords();
// make sure there is a town in the game // make sure there is a town in the game
if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) {
{
_error_message = STR_NO_TOWN_IN_SCENARIO; _error_message = STR_NO_TOWN_IN_SCENARIO;
return false; return false;
} }
@ -1215,16 +1195,12 @@ bool AfterLoadGame(uint version)
vp->virtual_width = vp->width << vp->zoom; vp->virtual_width = vp->width << vp->zoom;
vp->virtual_height = vp->height << vp->zoom; vp->virtual_height = vp->height << vp->zoom;
// in version 4.0 of the savegame, is_active was introduced to determine // in version 4.0 of the savegame, is_active was introduced to determine
// if a player does exist, rather then checking name_1 // if a player does exist, rather then checking name_1
if (version <= 0x400) { if (version <= 0x400) CheckIsPlayerActive();
CheckIsPlayerActive();
}
// the void tiles on the southern border used to belong to a wrong class. // the void tiles on the southern border used to belong to a wrong class.
if (version <= 0x402) if (version <= 0x402) UpdateVoidTiles();
UpdateVoidTiles();
// If Load Scenario / New (Scenario) Game is used, // If Load Scenario / New (Scenario) Game is used,
// a player does not exist yet. So create one here. // a player does not exist yet. So create one here.
@ -1237,9 +1213,7 @@ bool AfterLoadGame(uint version)
MarkWholeScreenDirty(); MarkWholeScreenDirty();
//In 5.1, Oilrigs have been moved (again) //In 5.1, Oilrigs have been moved (again)
if (version <= 0x500) { if (version <= 0x500) UpdateOilRig();
UpdateOilRig();
}
if (version <= 0x600) { if (version <= 0x600) {
BEGIN_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0) { BEGIN_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0) {
@ -1265,9 +1239,7 @@ bool AfterLoadGame(uint version)
if (version < 0x900) { if (version < 0x900) {
Town *t; Town *t;
FOR_ALL_TOWNS(t) { FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
UpdateTownMaxPass(t);
}
} }
if (version < 0xF00) { if (version < 0xF00) {
@ -1320,9 +1292,7 @@ bool AfterLoadGame(uint version)
} }
} }
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) p->avail_railtypes = GetPlayerRailtypes(p->index);
p->avail_railtypes = GetPlayerRailtypes(p->index);
}
return true; return true;
} }

View File

@ -29,8 +29,7 @@ static void OrderPoolNewBlock(uint start_item)
{ {
Order *order; Order *order;
FOR_ALL_ORDERS_FROM(order, start_item) FOR_ALL_ORDERS_FROM(order, start_item) order->index = start_item++;
order->index = start_item++;
} }
/* Initialize the order-pool */ /* Initialize the order-pool */
@ -117,7 +116,7 @@ static Order *AllocateOrder(void)
if (order->type == OT_NOTHING) { if (order->type == OT_NOTHING) {
uint index = order->index; uint index = order->index;
memset(order, 0, sizeof(Order)); memset(order, 0, sizeof(*order));
order->index = index; order->index = index;
order->next = NULL; order->next = NULL;
@ -126,8 +125,7 @@ static Order *AllocateOrder(void)
} }
/* Check if we can add a block to the pool */ /* Check if we can add a block to the pool */
if (AddBlockToPool(&_order_pool)) if (AddBlockToPool(&_order_pool)) return AllocateOrder();
return AllocateOrder();
return NULL; return NULL;
} }
@ -207,19 +205,19 @@ int32 CmdInsertOrder(int x, int y, uint32 flags, uint32 p1, uint32 p2)
* [full-load | unload] [+ transfer] [+ non-stop] * [full-load | unload] [+ transfer] [+ non-stop]
* non-stop orders (if any) are only valid for trains */ * non-stop orders (if any) are only valid for trains */
switch (new_order.flags) { switch (new_order.flags) {
case 0: /* Fallthrough */ case 0:
case OF_FULL_LOAD: case OF_FULL_LOAD:
case OF_FULL_LOAD | OF_TRANSFER: /* Fallthrough */ case OF_FULL_LOAD | OF_TRANSFER:
case OF_UNLOAD: case OF_UNLOAD:
case OF_UNLOAD | OF_TRANSFER: /* Fallthrough */ case OF_UNLOAD | OF_TRANSFER:
case OF_TRANSFER: case OF_TRANSFER:
break; break;
case OF_NON_STOP: case OF_NON_STOP:
case OF_NON_STOP | OF_FULL_LOAD: case OF_NON_STOP | OF_FULL_LOAD:
case OF_NON_STOP | OF_FULL_LOAD | OF_TRANSFER: /* Fallthrough */ case OF_NON_STOP | OF_FULL_LOAD | OF_TRANSFER:
case OF_NON_STOP | OF_UNLOAD: case OF_NON_STOP | OF_UNLOAD:
case OF_NON_STOP | OF_UNLOAD | OF_TRANSFER: /* Fallthrough */ case OF_NON_STOP | OF_UNLOAD | OF_TRANSFER:
case OF_NON_STOP | OF_TRANSFER: case OF_NON_STOP | OF_TRANSFER:
if (v->type != VEH_Train) return CMD_ERROR; if (v->type != VEH_Train) return CMD_ERROR;
break; break;
@ -407,9 +405,7 @@ int32 CmdInsertOrder(int x, int y, uint32 flags, uint32 p1, uint32 p2)
static int32 DecloneOrder(Vehicle *dst, uint32 flags) static int32 DecloneOrder(Vehicle *dst, uint32 flags)
{ {
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
/* Delete orders from vehicle */
DeleteVehicleOrders(dst); DeleteVehicleOrders(dst);
InvalidateVehicleOrder(dst); InvalidateVehicleOrder(dst);
RebuildVehicleLists(); RebuildVehicleLists();
} }
@ -568,8 +564,7 @@ int32 CmdModifyOrder(int x, int y, uint32 flags, uint32 p1, uint32 p2)
switch (p2) { switch (p2) {
case OFB_FULL_LOAD: case OFB_FULL_LOAD:
TOGGLEBIT(order->flags, OFB_FULL_LOAD); TOGGLEBIT(order->flags, OFB_FULL_LOAD);
if (order->type != OT_GOTO_DEPOT) if (order->type != OT_GOTO_DEPOT) CLRBIT(order->flags, OFB_UNLOAD);
CLRBIT(order->flags, OFB_UNLOAD);
break; break;
case OFB_UNLOAD: case OFB_UNLOAD:
TOGGLEBIT(order->flags, OFB_UNLOAD); TOGGLEBIT(order->flags, OFB_UNLOAD);
@ -750,7 +745,7 @@ void BackupVehicleOrders(const Vehicle *v, BackuppedOrders *bak)
/* Safe custom string, if any */ /* Safe custom string, if any */
if ((v->string_id & 0xF800) != 0x7800) { if ((v->string_id & 0xF800) != 0x7800) {
bak->name[0] = 0; bak->name[0] = '\0';
} else { } else {
GetName(v->string_id & 0x7FF, bak->name); GetName(v->string_id & 0x7FF, bak->name);
} }
@ -899,8 +894,7 @@ bool CheckOrders(uint data_a, uint data_b)
n_st++; n_st++;
st = GetStation(order->station); st = GetStation(order->station);
required_tile = GetStationTileForVehicle(v, st); required_tile = GetStationTileForVehicle(v, st);
if (!required_tile) if (required_tile == 0) problem_type = 3;
problem_type = 3;
} }
} }
@ -912,8 +906,7 @@ bool CheckOrders(uint data_a, uint data_b)
problem_type = 2; problem_type = 2;
/* Do we only have 1 station in our order list? */ /* Do we only have 1 station in our order list? */
if ((n_st < 2) && (problem_type == -1)) if (n_st < 2 && problem_type == -1) problem_type = 0;
problem_type = 0;
/* We don't have a problem */ /* We don't have a problem */
if (problem_type < 0) { if (problem_type < 0) {
@ -1104,9 +1097,7 @@ bool CheckForValidOrders(const Vehicle* v)
{ {
const Order *order; const Order *order;
FOR_VEHICLE_ORDERS(v, order) FOR_VEHICLE_ORDERS(v, order) if (order->type != OT_DUMMY) return true;
if (order->type != OT_DUMMY)
return true;
return false; return false;
} }

View File

@ -472,13 +472,15 @@ static void OrdersWndProc(Window *w, WindowEvent *e)
} }
case WE_RCLICK: { case WE_RCLICK: {
Vehicle *v = GetVehicle(w->window_number); Vehicle* v = GetVehicle(w->window_number);
int sel = OrderGetSel(w); int s = OrderGetSel(w);
if (e->click.widget != 8) break;
if (sel == v->num_orders || GetVehicleOrder(v, sel)->type != OT_GOTO_DEPOT) if (e->click.widget != 8) break;
if (s == v->num_orders || GetVehicleOrder(v, s)->type != OT_GOTO_DEPOT) {
GuiShowTooltips(STR_8857_MAKE_THE_HIGHLIGHTED_ORDER); GuiShowTooltips(STR_8857_MAKE_THE_HIGHLIGHTED_ORDER);
else } else {
GuiShowTooltips(STR_SERVICE_HINT); GuiShowTooltips(STR_SERVICE_HINT);
}
} break; } break;
case WE_4: { case WE_4: {

View File

@ -685,10 +685,10 @@ static const WindowDesc _other_player_company_desc = {
void ShowPlayerCompany(PlayerID player) void ShowPlayerCompany(PlayerID player)
{ {
Window *w; Window* w;
w = AllocateWindowDescFront(player == _local_player ? &_my_player_company_desc : &_other_player_company_desc, player);
if (w) w = AllocateWindowDescFront(player == _local_player ? &_my_player_company_desc : &_other_player_company_desc, player);
w->caption_color = w->window_number; if (w != NULL) w->caption_color = w->window_number;
} }
@ -881,7 +881,7 @@ void ShowHighscoreTable(int difficulty, int8 ranking)
if (!_networking) DoCommandP(0, 1, 0, NULL, CMD_PAUSE); if (!_networking) DoCommandP(0, 1, 0, NULL, CMD_PAUSE);
/* Close all always on-top windows to get a clean screen */ /* Close all always on-top windows to get a clean screen */
if (_game_mode != GM_MENU) HideVitalWindows(); if (_game_mode != GM_MENU) HideVitalWindows();
DeleteWindowByClass(WC_HIGHSCORE); DeleteWindowByClass(WC_HIGHSCORE);
w = AllocateWindowDesc(&_highscore_desc); w = AllocateWindowDesc(&_highscore_desc);

View File

@ -135,17 +135,17 @@ void DrawPlayerFace(uint32 face, int color, int x, int y)
/* draw the hair */ /* draw the hair */
{ {
uint val = GB(face, 16, 4); uint val = GB(face, 16, 4);
if (!(flag&2)) { if (flag & 2) {
if (!(flag&1)) { if (flag & 1) {
DrawSprite(0x382 + (val*9>>4), x, y); DrawSprite(0x3D9 + (val * 5 >> 4), x, y);
} else { } else {
DrawSprite(0x38B + (val*5>>4), x, y); DrawSprite(0x3D4 + (val * 5 >> 4), x, y);
} }
} else { } else {
if (!(flag&1)) { if (flag & 1) {
DrawSprite(0x3D4 + (val*5>>4), x, y); DrawSprite(0x38B + (val * 5 >> 4), x, y);
} else { } else {
DrawSprite(0x3D9 + (val*5>>4), x, y); DrawSprite(0x382 + (val * 9 >> 4), x, y);
} }
} }
} }
@ -163,9 +163,7 @@ void DrawPlayerFace(uint32 face, int color, int x, int y)
DrawSprite(0x37B + (GB(val, 2, 2) * 4 >> 2), x, y); DrawSprite(0x37B + (GB(val, 2, 2) * 4 >> 2), x, y);
val >>= 4; val >>= 4;
if (val < 3) { if (val < 3) DrawSprite((flag & 2 ? 0x3D1 : 0x37F) + val, x, y);
DrawSprite((flag&2 ? 0x3D1 : 0x37F) + val, x, y);
}
} }
} }
@ -173,14 +171,10 @@ void DrawPlayerFace(uint32 face, int color, int x, int y)
{ {
uint val = GB(face, 28, 3); uint val = GB(face, 28, 3);
if (!(flag&2)) { if (flag & 2) {
if (val<=1) { if (val <= 1) DrawSprite(0x3AE + val, x, y);
DrawSprite(0x347 + val, x, y);
}
} else { } else {
if (val<=1) { if (val <= 1) DrawSprite(0x347 + val, x, y);
DrawSprite(0x3AE + val, x, y);
}
} }
} }
} }

View File

@ -224,7 +224,7 @@ uint GetRailFoundation(uint tileh, uint bits)
return 0; return 0;
} }
//
static uint32 CheckRailSlope(uint tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile) static uint32 CheckRailSlope(uint tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
{ {
// never allow building on top of steep tiles // never allow building on top of steep tiles
@ -689,8 +689,7 @@ int32 CmdBuildTrainDepot(int x, int y, uint32 flags, uint32 p1, uint32 p2)
cost = ret; cost = ret;
d = AllocateDepot(); d = AllocateDepot();
if (d == NULL) if (d == NULL) return CMD_ERROR;
return CMD_ERROR;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
if (IsLocalPlayer()) _last_built_train_depot_tile = tile; if (IsLocalPlayer()) _last_built_train_depot_tile = tile;
@ -820,10 +819,11 @@ int32 CmdBuildSingleSignal(int x, int y, uint32 flags, uint32 p1, uint32 p2)
_m[tile].m3 &= ~SignalOnTrack(track); _m[tile].m3 &= ~SignalOnTrack(track);
_m[tile].m3 |= p2 & SignalOnTrack(track); _m[tile].m3 |= p2 & SignalOnTrack(track);
// convert between signal<->semaphores when dragging // convert between signal<->semaphores when dragging
if (semaphore) if (semaphore) {
SETBIT(_m[tile].m4, 3); SETBIT(_m[tile].m4, 3);
else } else {
CLRBIT(_m[tile].m4, 3); CLRBIT(_m[tile].m4, 3);
}
} }
MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile);
@ -859,8 +859,7 @@ static int32 CmdSignalTrackHelper(int x, int y, uint32 flags, uint32 p1, uint32
if (p1 > MapSize()) return CMD_ERROR; if (p1 > MapSize()) return CMD_ERROR;
if (signal_density == 0 || signal_density > 20) return CMD_ERROR; if (signal_density == 0 || signal_density > 20) return CMD_ERROR;
if (!IsTileType(tile, MP_RAILWAY)) if (!IsTileType(tile, MP_RAILWAY)) return CMD_ERROR;
return CMD_ERROR;
SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION); SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);
@ -1290,8 +1289,7 @@ static void DrawTrackFence_NE_SW(const TileInfo *ti)
static void DrawTrackFence_NS_1(const TileInfo *ti) static void DrawTrackFence_NS_1(const TileInfo *ti)
{ {
int z = ti->z; int z = ti->z;
if (ti->tileh & 1) if (ti->tileh & 1) z += 8;
z += 8;
AddSortableSpriteToDraw(0x517 | _drawtile_track_palette, AddSortableSpriteToDraw(0x517 | _drawtile_track_palette,
ti->x + 8, ti->y + 8, 1, 1, 4, z); ti->x + 8, ti->y + 8, 1, 1, 4, z);
} }
@ -1299,8 +1297,7 @@ static void DrawTrackFence_NS_1(const TileInfo *ti)
static void DrawTrackFence_NS_2(const TileInfo *ti) static void DrawTrackFence_NS_2(const TileInfo *ti)
{ {
int z = ti->z; int z = ti->z;
if (ti->tileh & 4) if (ti->tileh & 4) z += 8;
z += 8;
AddSortableSpriteToDraw(0x517 | _drawtile_track_palette, AddSortableSpriteToDraw(0x517 | _drawtile_track_palette,
ti->x + 8, ti->y + 8, 1, 1, 4, z); ti->x + 8, ti->y + 8, 1, 1, 4, z);
} }
@ -1308,8 +1305,7 @@ static void DrawTrackFence_NS_2(const TileInfo *ti)
static void DrawTrackFence_WE_1(const TileInfo *ti) static void DrawTrackFence_WE_1(const TileInfo *ti)
{ {
int z = ti->z; int z = ti->z;
if (ti->tileh & 8) if (ti->tileh & 8) z += 8;
z += 8;
AddSortableSpriteToDraw(0x518 | _drawtile_track_palette, AddSortableSpriteToDraw(0x518 | _drawtile_track_palette,
ti->x + 8, ti->y + 8, 1, 1, 4, z); ti->x + 8, ti->y + 8, 1, 1, 4, z);
} }
@ -1317,8 +1313,7 @@ static void DrawTrackFence_WE_1(const TileInfo *ti)
static void DrawTrackFence_WE_2(const TileInfo *ti) static void DrawTrackFence_WE_2(const TileInfo *ti)
{ {
int z = ti->z; int z = ti->z;
if (ti->tileh & 2) if (ti->tileh & 2) z += 8;
z += 8;
AddSortableSpriteToDraw(0x518 | _drawtile_track_palette, AddSortableSpriteToDraw(0x518 | _drawtile_track_palette,
ti->x + 8, ti->y + 8, 1, 1, 4, z); ti->x + 8, ti->y + 8, 1, 1, 4, z);
} }
@ -1795,8 +1790,7 @@ static void SetSignalsAfterProc(TrackPathFinder *tpf)
/* Go through all the PF tiles */ /* Go through all the PF tiles */
for (i = 0; i < lengthof(tpf->hash_head); i++) { for (i = 0; i < lengthof(tpf->hash_head); i++) {
/* Empty hash item */ /* Empty hash item */
if (tpf->hash_head[i] == 0) if (tpf->hash_head[i] == 0) continue;
continue;
/* If 0x8000 is not set, there is only 1 item */ /* If 0x8000 is not set, there is only 1 item */
if (!(tpf->hash_head[i] & 0x8000)) { if (!(tpf->hash_head[i] & 0x8000)) {
@ -1917,8 +1911,7 @@ bool UpdateSignalsOnSegment(TileIndex tile, byte direction)
if (result < 0) result = ssd.stop; if (result < 0) result = ssd.stop;
// if any exit signals were changed, we need to keep going to modify the stuff behind those. // if any exit signals were changed, we need to keep going to modify the stuff behind those.
if(!ssd.cur_stack) if (ssd.cur_stack == 0) break;
break;
// one or more exit signals were changed, so we need to update another segment too. // one or more exit signals were changed, so we need to update another segment too.
tile = ssd.next_tile[--ssd.cur_stack]; tile = ssd.next_tile[--ssd.cur_stack];
@ -2020,8 +2013,7 @@ static void TileLoop_Track(TileIndex tile)
} }
// Don't continue tile loop for depots // Don't continue tile loop for depots
if (_m[tile].m5 & RAIL_TYPE_SPECIAL) if (_m[tile].m5 & RAIL_TYPE_SPECIAL) return;
return;
a2 = RAIL_GROUND_GREEN; a2 = RAIL_GROUND_GREEN;
@ -2085,8 +2077,7 @@ static uint32 GetTileTrackStatus_Track(TileIndex tile, TransportType mode)
uint16 b; uint16 b;
uint32 ret; uint32 ret;
if (mode != TRANSPORT_RAIL) if (mode != TRANSPORT_RAIL) return 0;
return 0;
m5 = _m[tile].m5; m5 = _m[tile].m5;
@ -2111,10 +2102,10 @@ static uint32 GetTileTrackStatus_Track(TileIndex tile, TransportType mode)
if ((a & 0xC0) == 0) b |= 0xC0; if ((a & 0xC0) == 0) b |= 0xC0;
if ((a & 0x30) == 0) b |= 0x30; if ((a & 0x30) == 0) b |= 0x30;
if ( (b & 0x80) == 0) ret |= 0x10070000; if ((b & 0x80) == 0) ret |= 0x10070000;
if ( (b & 0x40) == 0) ret |= 0x7100000; if ((b & 0x40) == 0) ret |= 0x07100000;
if ( (b & 0x20) == 0) ret |= 0x20080000; if ((b & 0x20) == 0) ret |= 0x20080000;
if ( (b & 0x10) == 0) ret |= 0x8200000; if ((b & 0x10) == 0) ret |= 0x08200000;
} }
} else if (m5 & 0x40) { } else if (m5 & 0x40) {
static const byte _train_spec_tracks[6] = {1,2,1,2,1,2}; static const byte _train_spec_tracks[6] = {1,2,1,2,1,2};
@ -2193,8 +2184,7 @@ static uint32 VehicleEnter_Track(Vehicle *v, TileIndex tile, int x, int y)
int length; int length;
// this routine applies only to trains in depot tiles // this routine applies only to trains in depot tiles
if (v->type != VEH_Train || !IsTileDepotType(tile, TRANSPORT_RAIL)) if (v->type != VEH_Train || !IsTileDepotType(tile, TRANSPORT_RAIL)) return 0;
return 0;
/* depot direction */ /* depot direction */
dir = GetDepotDirection(tile, TRANSPORT_RAIL); dir = GetDepotDirection(tile, TRANSPORT_RAIL);

View File

@ -24,7 +24,7 @@
static RailType _cur_railtype; static RailType _cur_railtype;
static bool _remove_button_clicked; static bool _remove_button_clicked;
static byte _build_depot_direction; static byte _build_depot_direction;
static byte _waypoint_count=1; static byte _waypoint_count = 1;
static byte _cur_waypoint_type; static byte _cur_waypoint_type;
static struct { static struct {
@ -40,8 +40,6 @@ static void ShowBuildTrainDepotPicker(void);
static void ShowBuildWaypointPicker(void); static void ShowBuildWaypointPicker(void);
static void ShowStationBuilder(void); static void ShowStationBuilder(void);
typedef void OnButtonClick(Window *w);
void CcPlaySound1E(bool success, TileIndex tile, uint32 p1, uint32 p2) void CcPlaySound1E(bool success, TileIndex tile, uint32 p1, uint32 p2)
{ {
if (success) SndPlayTileFx(SND_20_SPLAT_2, tile); if (success) SndPlayTileFx(SND_20_SPLAT_2, tile);
@ -53,7 +51,7 @@ static void GenericPlaceRail(TileIndex tile, int cmd)
_remove_button_clicked ? _remove_button_clicked ?
CMD_REMOVE_SINGLE_RAIL | CMD_MSG(STR_1012_CAN_T_REMOVE_RAILROAD_TRACK) | CMD_AUTO | CMD_NO_WATER : CMD_REMOVE_SINGLE_RAIL | CMD_MSG(STR_1012_CAN_T_REMOVE_RAILROAD_TRACK) | CMD_AUTO | CMD_NO_WATER :
CMD_BUILD_SINGLE_RAIL | CMD_MSG(STR_1011_CAN_T_BUILD_RAILROAD_TRACK) | CMD_AUTO | CMD_NO_WATER CMD_BUILD_SINGLE_RAIL | CMD_MSG(STR_1011_CAN_T_BUILD_RAILROAD_TRACK) | CMD_AUTO | CMD_NO_WATER
); );
} }
static void PlaceRail_N(TileIndex tile) static void PlaceRail_N(TileIndex tile)
@ -159,7 +157,7 @@ static void PlaceRail_Station(TileIndex tile)
static void GenericPlaceSignals(TileIndex tile) static void GenericPlaceSignals(TileIndex tile)
{ {
uint trackstat; uint trackstat;
int i; uint i;
trackstat = (byte)GetTileTrackStatus(tile, TRANSPORT_RAIL); trackstat = (byte)GetTileTrackStatus(tile, TRANSPORT_RAIL);
@ -171,7 +169,9 @@ static void GenericPlaceSignals(TileIndex tile)
// Lookup the bit index // Lookup the bit index
i = 0; i = 0;
if (trackstat != 0) { while (!(trackstat & 1)) { i++; trackstat >>= 1; }} if (trackstat != 0) {
for (; !(trackstat & 1); trackstat >>= 1) i++;
}
if (!_remove_button_clicked) { if (!_remove_button_clicked) {
DoCommandP(tile, i + (_ctrl_pressed ? 8 : 0), 0, CcPlaySound1E, DoCommandP(tile, i + (_ctrl_pressed ? 8 : 0), 0, CcPlaySound1E,
@ -258,9 +258,10 @@ static void BuildRailClick_Depot(Window *w)
static void BuildRailClick_Waypoint(Window *w) static void BuildRailClick_Waypoint(Window *w)
{ {
_waypoint_count = GetNumCustomStations(STAT_CLASS_WAYP); _waypoint_count = GetNumCustomStations(STAT_CLASS_WAYP);
if (HandlePlacePushButton(w, 11, SPR_CURSOR_WAYPOINT, 1, PlaceRail_Waypoint) if (HandlePlacePushButton(w, 11, SPR_CURSOR_WAYPOINT, 1, PlaceRail_Waypoint) &&
&& _waypoint_count > 1) _waypoint_count > 1) {
ShowBuildWaypointPicker(); ShowBuildWaypointPicker();
}
} }
static void BuildRailClick_Station(Window *w) static void BuildRailClick_Station(Window *w)
@ -295,10 +296,11 @@ static void BuildRailClick_Remove(Window *w)
// handle station builder // handle station builder
if (HASBIT(w->click_state, 16)) { if (HASBIT(w->click_state, 16)) {
if(_remove_button_clicked) if (_remove_button_clicked) {
SetTileSelectSize(1, 1); SetTileSelectSize(1, 1);
else } else {
BringWindowToFrontById(WC_BUILD_STATION, 0); BringWindowToFrontById(WC_BUILD_STATION, 0);
}
} }
} }
@ -346,13 +348,20 @@ static void HandleAutoSignalPlacement(void)
// _patches.drag_signals_density is given as a parameter such that each user in a network // _patches.drag_signals_density is given as a parameter such that each user in a network
// game can specify his/her own signal density // game can specify his/her own signal density
DoCommandP(TileVirtXY(thd->selstart.x, thd->selstart.y), TileVirtXY(thd->selend.x, thd->selend.y), DoCommandP(
(_ctrl_pressed ? 1 << 3 : 0) | (trackstat << 4) | (_patches.drag_signals_density << 24), TileVirtXY(thd->selstart.x, thd->selstart.y),
CcPlaySound1E, TileVirtXY(thd->selend.x, thd->selend.y),
(_remove_button_clicked ? CMD_REMOVE_SIGNAL_TRACK | CMD_AUTO | CMD_NO_WATER | CMD_MSG(STR_1013_CAN_T_REMOVE_SIGNALS_FROM) : (_ctrl_pressed ? 1 << 3 : 0) | (trackstat << 4) | (_patches.drag_signals_density << 24),
CMD_BUILD_SIGNAL_TRACK | CMD_AUTO | CMD_NO_WATER | CMD_MSG(STR_1010_CAN_T_BUILD_SIGNALS_HERE) ) ); CcPlaySound1E,
_remove_button_clicked ?
CMD_REMOVE_SIGNAL_TRACK | CMD_AUTO | CMD_NO_WATER | CMD_MSG(STR_1013_CAN_T_REMOVE_SIGNALS_FROM) :
CMD_BUILD_SIGNAL_TRACK | CMD_AUTO | CMD_NO_WATER | CMD_MSG(STR_1010_CAN_T_BUILD_SIGNALS_HERE)
);
} }
typedef void OnButtonClick(Window *w);
static OnButtonClick * const _build_railroad_button_proc[] = { static OnButtonClick * const _build_railroad_button_proc[] = {
BuildRailClick_N, BuildRailClick_N,
BuildRailClick_NE, BuildRailClick_NE,
@ -390,11 +399,9 @@ static const uint16 _rail_keycodes[] = {
}; };
static void BuildRailToolbWndProc(Window *w, WindowEvent *e) static void BuildRailToolbWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
w->disabled_state &= ~(1 << 16); w->disabled_state &= ~(1 << 16);
if (!(w->click_state & ((1<<4)|(1<<5)|(1<<6)|(1<<7)|(1<<8)|(1<<11)|(1<<12)|(1<<13)))) { if (!(w->click_state & ((1<<4)|(1<<5)|(1<<6)|(1<<7)|(1<<8)|(1<<11)|(1<<12)|(1<<13)))) {
@ -412,9 +419,9 @@ static void BuildRailToolbWndProc(Window *w, WindowEvent *e)
break; break;
case WE_KEYPRESS: { case WE_KEYPRESS: {
int i; uint i;
for(i=0; i!=lengthof(_rail_keycodes); i++) { for (i = 0; i != lengthof(_rail_keycodes); i++) {
if (e->keypress.keycode == _rail_keycodes[i]) { if (e->keypress.keycode == _rail_keycodes[i]) {
e->keypress.cont = false; e->keypress.cont = false;
_remove_button_clicked = false; _remove_button_clicked = false;
@ -467,16 +474,16 @@ static void BuildRailToolbWndProc(Window *w, WindowEvent *e)
SetWindowDirty(w); SetWindowDirty(w);
w = FindWindowById(WC_BUILD_STATION, 0); w = FindWindowById(WC_BUILD_STATION, 0);
if (w != NULL) WP(w,def_d).close=true; if (w != NULL) WP(w,def_d).close = true;
w = FindWindowById(WC_BUILD_DEPOT, 0); w = FindWindowById(WC_BUILD_DEPOT, 0);
if (w != NULL) WP(w,def_d).close=true; if (w != NULL) WP(w,def_d).close = true;
break; break;
case WE_PLACE_PRESIZE: { case WE_PLACE_PRESIZE: {
TileIndex tile = e->place.tile; TileIndex tile = e->place.tile;
DoCommandByTile(tile, 0, 0, DC_AUTO, CMD_BUILD_TUNNEL); DoCommandByTile(tile, 0, 0, DC_AUTO, CMD_BUILD_TUNNEL);
VpSetPresizeRange(tile, _build_tunnel_endtile==0?tile:_build_tunnel_endtile); VpSetPresizeRange(tile, _build_tunnel_endtile == 0 ? tile : _build_tunnel_endtile);
} break; } break;
case WE_DESTROY: case WE_DESTROY:
@ -541,7 +548,7 @@ typedef enum {
* @param railtype the railtype to display * @param railtype the railtype to display
* @param w the window to modify * @param w the window to modify
*/ */
static void SetupRailToolbar(RailType railtype, Window *w) static void SetupRailToolbar(RailType railtype, Window* w)
{ {
const RailtypeInfo *rti = GetRailTypeInfo(railtype); const RailtypeInfo *rti = GetRailTypeInfo(railtype);
@ -703,17 +710,16 @@ static void StationBuildWndProc(Window *w, WindowEvent *e)
} }
} break; } break;
case WE_MOUSELOOP: { case WE_MOUSELOOP:
if (WP(w,def_d).close) { if (WP(w,def_d).close) {
DeleteWindow(w); DeleteWindow(w);
return; return;
} }
CheckRedrawStationCoverage(w); CheckRedrawStationCoverage(w);
} break; break;
case WE_DESTROY: case WE_DESTROY:
if (!WP(w,def_d).close) if (!WP(w,def_d).close) ResetObjectToPlace();
ResetObjectToPlace();
break; break;
} }
} }
@ -772,28 +778,30 @@ static void BuildTrainDepotWndProc(Window *w, WindowEvent *e)
r = _cur_railtype; r = _cur_railtype;
DrawTrainDepotSprite(70, 17, 0, r); DrawTrainDepotSprite(70, 17, 0, r);
DrawTrainDepotSprite(70, 69, 1, r); DrawTrainDepotSprite(70, 69, 1, r);
DrawTrainDepotSprite(2, 69, 2, r); DrawTrainDepotSprite( 2, 69, 2, r);
DrawTrainDepotSprite(2, 17, 3, r); DrawTrainDepotSprite( 2, 17, 3, r);
break; break;
} }
case WE_CLICK: {
switch(e->click.widget) { case WE_CLICK:
case 3: case 4: case 5: case 6: switch (e->click.widget) {
_build_depot_direction = e->click.widget - 3; case 3:
SndPlayFx(SND_15_BEEP); case 4:
SetWindowDirty(w); case 5:
break; case 6:
_build_depot_direction = e->click.widget - 3;
SndPlayFx(SND_15_BEEP);
SetWindowDirty(w);
break;
} }
} break; break;
case WE_MOUSELOOP: case WE_MOUSELOOP:
if (WP(w,def_d).close) if (WP(w,def_d).close) DeleteWindow(w);
DeleteWindow(w);
return; return;
case WE_DESTROY: case WE_DESTROY:
if (!WP(w,def_d).close) if (!WP(w,def_d).close) ResetObjectToPlace();
ResetObjectToPlace();
break; break;
} }
} }
@ -827,15 +835,16 @@ static void BuildWaypointWndProc(Window *w, WindowEvent *e)
{ {
switch (e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
int i; uint i;
w->click_state = (1 << 3) << (_cur_waypoint_type - w->hscroll.pos); w->click_state = (1 << 3) << (_cur_waypoint_type - w->hscroll.pos);
DrawWindowWidgets(w); DrawWindowWidgets(w);
for (i = 0; i < 5; i++) { for (i = 0; i < 5; i++) {
if (w->hscroll.pos + i < _waypoint_count) if (w->hscroll.pos + i < _waypoint_count) {
DrawWaypointSprite(2 + i * 68, 25, w->hscroll.pos + i, _cur_railtype); DrawWaypointSprite(2 + i * 68, 25, w->hscroll.pos + i, _cur_railtype);
}
} }
break; break;
} }
case WE_CLICK: { case WE_CLICK: {
@ -850,13 +859,11 @@ static void BuildWaypointWndProc(Window *w, WindowEvent *e)
} }
case WE_MOUSELOOP: case WE_MOUSELOOP:
if (WP(w,def_d).close) if (WP(w,def_d).close) DeleteWindow(w);
DeleteWindow(w);
break; break;
case WE_DESTROY: case WE_DESTROY:
if (!WP(w,def_d).close) if (!WP(w,def_d).close) ResetObjectToPlace();
ResetObjectToPlace();
break; break;
} }
} }

View File

@ -377,7 +377,7 @@ int32 CmdBuildRoad(int x, int y, uint32 flags, uint32 p1, uint32 p2)
if (ti.type == MP_STREET) { if (ti.type == MP_STREET) {
if (!(ti.map5 & 0xF0)) { if (!(ti.map5 & 0xF0)) {
if ( (pieces & (byte)(ti.map5)) == (pieces)) if ((pieces & (byte)ti.map5) == pieces)
return_cmd_error(STR_1007_ALREADY_BUILT); return_cmd_error(STR_1007_ALREADY_BUILT);
existing = ti.map5; existing = ti.map5;
} else { } else {
@ -680,12 +680,9 @@ static int32 RemoveRoadDepot(TileIndex tile, uint32 flags)
if (!CheckTileOwnership(tile) && _current_player != OWNER_WATER) if (!CheckTileOwnership(tile) && _current_player != OWNER_WATER)
return CMD_ERROR; return CMD_ERROR;
if (!EnsureNoVehicle(tile)) if (!EnsureNoVehicle(tile)) return CMD_ERROR;
return CMD_ERROR;
if (flags & DC_EXEC) { if (flags & DC_EXEC) DoDeleteDepot(tile);
DoDeleteDepot(tile);
}
return _price.remove_road_depot; return _price.remove_road_depot;
} }
@ -790,21 +787,16 @@ void DrawRoadBits(TileInfo *ti, byte road, byte ground_type, bool snow, bool fla
foundation = GetRoadFoundation(ti->tileh, road); foundation = GetRoadFoundation(ti->tileh, road);
} }
if (foundation != 0) if (foundation != 0) DrawFoundation(ti, foundation);
DrawFoundation(ti, foundation);
// DrawFoundation() modifies ti. // DrawFoundation() modifies ti.
// Default sloped sprites.. // Default sloped sprites..
if (ti->tileh != 0) { if (ti->tileh != 0) image = _road_sloped_sprites[ti->tileh - 1] + 0x53F;
image = _road_sloped_sprites[ti->tileh - 1] + 0x53F;
}
} }
if (image == 0) if (image == 0) image = _road_tile_sprites_1[road];
image = _road_tile_sprites_1[road];
if (ground_type == 0) if (ground_type == 0) image |= PALETTE_TO_BARE_LAND;
image |= PALETTE_TO_BARE_LAND;
if (snow) { if (snow) {
image += 19; image += 19;
@ -816,8 +808,7 @@ void DrawRoadBits(TileInfo *ti, byte road, byte ground_type, bool snow, bool fla
DrawGroundSprite(image); DrawGroundSprite(image);
// Return if full detail is disabled, or we are zoomed fully out. // Return if full detail is disabled, or we are zoomed fully out.
if (!(_display_opt & DO_FULL_DETAIL) || _cur_dpi->zoom == 2) if (!(_display_opt & DO_FULL_DETAIL) || _cur_dpi->zoom == 2) return;
return;
if (ground_type >= 6) { if (ground_type >= 6) {
// Road works // Road works
@ -831,8 +822,7 @@ void DrawRoadBits(TileInfo *ti, byte road, byte ground_type, bool snow, bool fla
int x = ti->x | drts->subcoord_x; int x = ti->x | drts->subcoord_x;
int y = ti->y | drts->subcoord_y; int y = ti->y | drts->subcoord_y;
byte z = ti->z; byte z = ti->z;
if (ti->tileh != 0) if (ti->tileh != 0) z = GetSlopeZ(x, y);
z = GetSlopeZ(x, y);
AddSortableSpriteToDraw(image, x, y, 2, 2, 0x10, z); AddSortableSpriteToDraw(image, x, y, 2, 2, 0x10, z);
drts++; drts++;
} }
@ -915,8 +905,8 @@ void DrawRoadDepotSprite(int x, int y, int image)
dtss = _road_display_datas[image]; dtss = _road_display_datas[image];
x+=33; x += 33;
y+=17; y += 17;
DrawSprite(dtss++->image, x, y); DrawSprite(dtss++->image, x, y);
@ -924,8 +914,7 @@ void DrawRoadDepotSprite(int x, int y, int image)
Point pt = RemapCoords(dtss->subcoord_x, dtss->subcoord_y, 0); Point pt = RemapCoords(dtss->subcoord_x, dtss->subcoord_y, 0);
image = dtss->image; image = dtss->image;
if (image & PALETTE_MODIFIER_COLOR) if (image & PALETTE_MODIFIER_COLOR) image |= ormod;
image |= ormod;
DrawSprite(image, x + pt.x, y + pt.y); DrawSprite(image, x + pt.x, y + pt.y);
} }
@ -986,9 +975,7 @@ static void GetAcceptedCargo_Road(TileIndex tile, AcceptedCargo ac)
static void AnimateTile_Road(TileIndex tile) static void AnimateTile_Road(TileIndex tile)
{ {
if (IsLevelCrossing(tile)) { if (IsLevelCrossing(tile)) MarkTileDirtyByTile(tile);
MarkTileDirtyByTile(tile);
}
} }
static const byte _town_road_types[5][2] = { static const byte _town_road_types[5][2] = {

View File

@ -171,7 +171,7 @@ static void BuildRoadClick_Landscaping(Window *w)
ShowTerraformToolbar(); ShowTerraformToolbar();
} }
static OnButtonClick * const _build_road_button_proc[] = { static OnButtonClick* const _build_road_button_proc[] = {
BuildRoadClick_NE, BuildRoadClick_NE,
BuildRoadClick_NW, BuildRoadClick_NW,
BuildRoadClick_Demolish, BuildRoadClick_Demolish,
@ -184,8 +184,9 @@ static OnButtonClick * const _build_road_button_proc[] = {
BuildRoadClick_Landscaping, BuildRoadClick_Landscaping,
}; };
static void BuildRoadToolbWndProc(Window *w, WindowEvent *e) { static void BuildRoadToolbWndProc(Window* w, WindowEvent* e)
switch(e->event) { {
switch (e->event) {
case WE_PAINT: case WE_PAINT:
w->disabled_state &= ~(1 << 11); w->disabled_state &= ~(1 << 11);
if (!(w->click_state & ((1<<3)|(1<<4)))) { if (!(w->click_state & ((1<<3)|(1<<4)))) {
@ -196,8 +197,7 @@ static void BuildRoadToolbWndProc(Window *w, WindowEvent *e) {
break; break;
case WE_CLICK: { case WE_CLICK: {
if (e->click.widget >= 3) if (e->click.widget >= 3) _build_road_button_proc[e->click.widget - 3](w);
_build_road_button_proc[e->click.widget - 3](w);
} break; } break;
case WE_KEYPRESS: case WE_KEYPRESS:
@ -228,11 +228,11 @@ static void BuildRoadToolbWndProc(Window *w, WindowEvent *e) {
SetWindowDirty(w); SetWindowDirty(w);
w = FindWindowById(WC_BUS_STATION, 0); w = FindWindowById(WC_BUS_STATION, 0);
if (w != NULL) WP(w,def_d).close=true; if (w != NULL) WP(w,def_d).close = true;
w = FindWindowById(WC_TRUCK_STATION, 0); w = FindWindowById(WC_TRUCK_STATION, 0);
if (w != NULL) WP(w,def_d).close=true; if (w != NULL) WP(w,def_d).close = true;
w = FindWindowById(WC_BUILD_DEPOT, 0); w = FindWindowById(WC_BUILD_DEPOT, 0);
if (w != NULL) WP(w,def_d).close=true; if (w != NULL) WP(w,def_d).close = true;
break; break;
case WE_PLACE_DRAG: { case WE_PLACE_DRAG: {
@ -351,16 +351,17 @@ void ShowBuildRoadScenToolbar(void)
AllocateWindowDescFront(&_build_road_scen_desc, 0); AllocateWindowDescFront(&_build_road_scen_desc, 0);
} }
static void BuildRoadDepotWndProc(Window *w, WindowEvent *e) { static void BuildRoadDepotWndProc(Window* w, WindowEvent* e)
switch(e->event) { {
switch (e->event) {
case WE_PAINT: case WE_PAINT:
w->click_state = (1<<3) << _road_depot_orientation; w->click_state = (1<<3) << _road_depot_orientation;
DrawWindowWidgets(w); DrawWindowWidgets(w);
DrawRoadDepotSprite(70, 17, 0); DrawRoadDepotSprite(70, 17, 0);
DrawRoadDepotSprite(70, 69, 1); DrawRoadDepotSprite(70, 69, 1);
DrawRoadDepotSprite(2, 69, 2); DrawRoadDepotSprite( 2, 69, 2);
DrawRoadDepotSprite(2, 17, 3); DrawRoadDepotSprite( 2, 17, 3);
break; break;
case WE_CLICK: { case WE_CLICK: {
@ -374,13 +375,11 @@ static void BuildRoadDepotWndProc(Window *w, WindowEvent *e) {
} break; } break;
case WE_MOUSELOOP: case WE_MOUSELOOP:
if (WP(w,def_d).close) if (WP(w,def_d).close) DeleteWindow(w);
DeleteWindow(w);
break; break;
case WE_DESTROY: case WE_DESTROY:
if (!WP(w,def_d).close) if (!WP(w,def_d).close) ResetObjectToPlace();
ResetObjectToPlace();
break; break;
} }
} }
@ -466,8 +465,7 @@ static void RoadStationPickerWndProc(Window *w, WindowEvent *e)
} break; } break;
case WE_DESTROY: case WE_DESTROY:
if (!WP(w,def_d).close) if (!WP(w,def_d).close) ResetObjectToPlace();
ResetObjectToPlace();
break; break;
} }
} }

View File

@ -65,12 +65,11 @@ static void DrawRoadVehImage(const Vehicle *v, int x, int y, VehicleID selection
{ {
int image = GetRoadVehImage(v, 6); int image = GetRoadVehImage(v, 6);
uint32 ormod = SPRITE_PALETTE(PLAYER_SPRITE_COLOR(v->owner)); uint32 ormod = SPRITE_PALETTE(PLAYER_SPRITE_COLOR(v->owner));
if (v->vehstatus & VS_CRASHED) if (v->vehstatus & VS_CRASHED) ormod = PALETTE_CRASH;
ormod = PALETTE_CRASH; DrawSprite(image | ormod, x + 14, y + 6);
DrawSprite(image | ormod, x+14, y+6);
if (v->index == selection) { if (v->index == selection) {
DrawFrameRect(x-1, y-1, x+28, y+12, 15, FR_BORDERONLY); DrawFrameRect(x - 1, y - 1, x + 28, y + 12, 15, FR_BORDERONLY);
} }
} }
@ -215,6 +214,7 @@ static void ShowRoadVehDetailsWindow(const Vehicle* v)
{ {
Window *w; Window *w;
VehicleID veh = v->index; VehicleID veh = v->index;
DeleteWindowById(WC_VEHICLE_ORDERS, veh); DeleteWindowById(WC_VEHICLE_ORDERS, veh);
DeleteWindowById(WC_VEHICLE_DETAILS, veh); DeleteWindowById(WC_VEHICLE_DETAILS, veh);
_alloc_wnd_parent_num = veh; _alloc_wnd_parent_num = veh;
@ -225,11 +225,7 @@ static void ShowRoadVehDetailsWindow(const Vehicle* v)
void CcCloneRoadVeh(bool success, uint tile, uint32 p1, uint32 p2) void CcCloneRoadVeh(bool success, uint tile, uint32 p1, uint32 p2)
{ {
if (success) { if (success) ShowRoadVehViewWindow(GetVehicle(_new_roadveh_id));
const Vehicle* v = GetVehicle(_new_roadveh_id);
ShowRoadVehViewWindow(v);
}
} }
static void RoadVehViewWndProc(Window *w, WindowEvent *e) static void RoadVehViewWndProc(Window *w, WindowEvent *e)
@ -445,7 +441,7 @@ void CcBuildRoadVeh(bool success, TileIndex tile, uint32 p1, uint32 p2)
static void NewRoadVehWndProc(Window *w, WindowEvent *e) static void NewRoadVehWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
DrawNewRoadVehWindow(w); DrawNewRoadVehWindow(w);
break; break;
@ -1073,7 +1069,7 @@ void ShowPlayerRoadVehicles(PlayerID player, StationID station)
} else { } else {
w = AllocateWindowDescFront(&_other_player_roadveh_desc, (station << 16) | player); w = AllocateWindowDescFront(&_other_player_roadveh_desc, (station << 16) | player);
} }
if (w) { if (w != NULL) {
w->caption_color = player; w->caption_color = player;
w->vscroll.cap = 7; // maximum number of vehicles shown w->vscroll.cap = 7; // maximum number of vehicles shown
w->widget[7].unkA = (w->vscroll.cap << 8) + 1; w->widget[7].unkA = (w->vscroll.cap << 8) + 1;

View File

@ -63,16 +63,20 @@ static StringID *BuildDynamicDropdown(StringID base, int num)
static int GetCurRes(void) static int GetCurRes(void)
{ {
int i; int i;
for(i = 0; i != _num_resolutions; i++)
for (i = 0; i != _num_resolutions; i++) {
if (_resolutions[i][0] == _screen.width && if (_resolutions[i][0] == _screen.width &&
_resolutions[i][1] == _screen.height) _resolutions[i][1] == _screen.height) {
break; break;
}
}
return i; return i;
} }
static inline bool RoadVehiclesAreBuilt(void) static inline bool RoadVehiclesAreBuilt(void)
{ {
const Vehicle *v; const Vehicle* v;
FOR_ALL_VEHICLES(v) { FOR_ALL_VEHICLES(v) {
if (v->type == VEH_Road) return true; if (v->type == VEH_Road) return true;
} }
@ -551,30 +555,23 @@ void ShowGameDifficulty(void)
// virtual PositionMainToolbar function, calls the right one. // virtual PositionMainToolbar function, calls the right one.
static int32 v_PositionMainToolbar(int32 p1) static int32 v_PositionMainToolbar(int32 p1)
{ {
if (_game_mode != GM_MENU) if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
PositionMainToolbar(NULL);
return 0; return 0;
} }
static int32 AiNew_PatchActive_Warning(int32 p1) static int32 AiNew_PatchActive_Warning(int32 p1)
{ {
if (p1 == 1) if (p1 == 1) ShowErrorMessage(-1, TEMP_AI_ACTIVATED, 0, 0);
ShowErrorMessage(-1, TEMP_AI_ACTIVATED, 0, 0); return 0;
return 0;
} }
static int32 PopulationInLabelActive(int32 p1) static int32 PopulationInLabelActive(int32 p1)
{ {
Town *t; Town* t;
FOR_ALL_TOWNS(t) { FOR_ALL_TOWNS(t) {
if (t->xy) { if (t->xy != 0) UpdateTownVirtCoord(t);
UpdateTownVirtCoord(t);
}
} }
return 0; return 0;
} }
@ -639,14 +636,14 @@ static int32 EngineRenewMoneyUpdate(int32 p1)
typedef int32 PatchButtonClick(int32); typedef int32 PatchButtonClick(int32);
typedef struct PatchEntry { typedef struct PatchEntry {
byte type; // type of selector byte type; // type of selector
byte flags; // selector flags byte flags; // selector flags
StringID str; // string with descriptive text StringID str; // string with descriptive text
char console_name[40]; // the name this patch has in console char console_name[40]; // the name this patch has in console
void *variable; // pointer to the variable void* variable; // pointer to the variable
int32 min, max; // range for spinbox setting int32 min, max; // range for spinbox setting
uint32 step; // step for spinbox uint32 step; // step for spinbox
PatchButtonClick *click_proc; // callback procedure PatchButtonClick* click_proc; // callback procedure
} PatchEntry; } PatchEntry;
enum { enum {
@ -821,7 +818,6 @@ static void WritePE(const PatchEntry* p, int32 v)
static void PatchesSelectionWndProc(Window *w, WindowEvent *e) static void PatchesSelectionWndProc(Window *w, WindowEvent *e)
{ {
uint i;
switch (e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
int x,y; int x,y;
@ -829,6 +825,7 @@ static void PatchesSelectionWndProc(Window *w, WindowEvent *e)
const PatchPage *page; const PatchPage *page;
uint clk; uint clk;
int32 val; int32 val;
uint i;
w->click_state = 1 << (WP(w,def_d).data_1 + 4); w->click_state = 1 << (WP(w,def_d).data_1 + 4);
@ -1116,8 +1113,9 @@ void IConsoleGetPatchSetting(const char *name)
if (pe->type == PE_BOOL) { if (pe->type == PE_BOOL) {
snprintf(value, sizeof(value), (ReadPE(pe) == 1) ? "on" : "off"); snprintf(value, sizeof(value), (ReadPE(pe) == 1) ? "on" : "off");
} else } else {
snprintf(value, sizeof(value), "%d", ReadPE(pe)); snprintf(value, sizeof(value), "%d", ReadPE(pe));
}
IConsolePrintF(_icolour_warn, "Current value for '%s' is: '%s'", name, value); IConsolePrintF(_icolour_warn, "Current value for '%s' is: '%s'", name, value);
} }
@ -1175,9 +1173,9 @@ static void NewgrfWndProc(Window *w, WindowEvent *e)
// draw list of all grf files // draw list of all grf files
while (c != NULL) { while (c != NULL) {
if (i >= w->vscroll.pos) { // draw files according to scrollbar position if (i >= w->vscroll.pos) { // draw files according to scrollbar position
bool h = (_sel_grffile==c); bool h = (_sel_grffile == c);
// show highlighted item with a different background and highlighted text // show highlighted item with a different background and highlighted text
if(h) GfxFillRect(1, y + 1, 267, y + 12, 156); if (h) GfxFillRect(1, y + 1, 267, y + 12, 156);
// XXX - will be grf name later // XXX - will be grf name later
DoDrawString(c->filename, 25, y + 2, h ? 0xC : 0x10); DoDrawString(c->filename, 25, y + 2, h ? 0xC : 0x10);
DrawSprite(SPRITE_PALETTE(SPR_SQUARE | PALETTE_TO_RED), 5, y + 2); DrawSprite(SPRITE_PALETTE(SPR_SQUARE | PALETTE_TO_RED), 5, y + 2);
@ -1448,23 +1446,27 @@ static void CustCurrencyWndProc(Window *w, WindowEvent *e)
val = atoi(b); val = atoi(b);
val = clamp(val, 1, 5000); val = clamp(val, 1, 5000);
_custom_currency.rate = val; _custom_currency.rate = val;
break; break;
case 1: /* Thousands seperator */ case 1: /* Thousands seperator */
_custom_currency.separator = (b[0] == '\0') ? ' ' : b[0]; _custom_currency.separator = (b[0] == '\0') ? ' ' : b[0];
ttd_strlcpy(_str_separator, b, lengthof(_str_separator)); ttd_strlcpy(_str_separator, b, lengthof(_str_separator));
break; break;
case 2: /* Currency prefix */ case 2: /* Currency prefix */
ttd_strlcpy(_custom_currency.prefix, b, lengthof(_custom_currency.prefix)); ttd_strlcpy(_custom_currency.prefix, b, lengthof(_custom_currency.prefix));
break; break;
case 3: /* Currency suffix */ case 3: /* Currency suffix */
ttd_strlcpy(_custom_currency.suffix, b, lengthof(_custom_currency.suffix)); ttd_strlcpy(_custom_currency.suffix, b, lengthof(_custom_currency.suffix));
break; break;
case 4: /* Year to switch to euro */ case 4: /* Year to switch to euro */
val = atoi(b); val = atoi(b);
val = clamp(val, 1999, MAX_YEAR_END_REAL); val = clamp(val, 1999, MAX_YEAR_END_REAL);
if (val == 1999) val = 0; if (val == 1999) val = 0;
_custom_currency.to_euro = val; _custom_currency.to_euro = val;
break; break;
} }
MarkWholeScreenDirty(); MarkWholeScreenDirty();
@ -1500,11 +1502,9 @@ static const WindowDesc _cust_currency_desc = {
void ShowCustCurrency(void) void ShowCustCurrency(void)
{ {
Window *w;
_str_separator[0] = _custom_currency.separator; _str_separator[0] = _custom_currency.separator;
_str_separator[1] = '\0'; _str_separator[1] = '\0';
DeleteWindowById(WC_CUSTOM_CURRENCY, 0); DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
w = AllocateWindowDesc(&_cust_currency_desc); AllocateWindowDesc(&_cust_currency_desc);
} }

View File

@ -35,7 +35,7 @@ void DrawShipEngine(int x, int y, EngineID engine, uint32 image_ormod)
if (is_custom_sprite(spritenum)) { if (is_custom_sprite(spritenum)) {
int sprite = GetCustomVehicleIcon(engine, 6); int sprite = GetCustomVehicleIcon(engine, 6);
if (sprite) { if (sprite != 0) {
DrawSprite(sprite | image_ormod, x, y); DrawSprite(sprite | image_ormod, x, y);
return; return;
} }
@ -51,7 +51,7 @@ int GetShipImage(const Vehicle *v, byte direction)
if (is_custom_sprite(spritenum)) { if (is_custom_sprite(spritenum)) {
int sprite = GetCustomVehicleSprite(v, direction); int sprite = GetCustomVehicleSprite(v, direction);
if (sprite) return sprite; if (sprite != 0) return sprite;
spritenum = orig_ship_vehicle_info[v->engine_type - SHIP_ENGINES_INDEX].image_index; spritenum = orig_ship_vehicle_info[v->engine_type - SHIP_ENGINES_INDEX].image_index;
} }
return _ship_sprites[spritenum] + direction; return _ship_sprites[spritenum] + direction;
@ -70,10 +70,11 @@ static const Depot* FindClosestShipDepot(const Vehicle* v)
NPFFoundTargetData ftd; NPFFoundTargetData ftd;
byte trackdir = GetVehicleTrackdir(v); byte trackdir = GetVehicleTrackdir(v);
ftd = NPFRouteToDepotTrialError(v->tile, trackdir, TRANSPORT_WATER, v->owner, INVALID_RAILTYPE); ftd = NPFRouteToDepotTrialError(v->tile, trackdir, TRANSPORT_WATER, v->owner, INVALID_RAILTYPE);
if (ftd.best_bird_dist == 0) if (ftd.best_bird_dist == 0) {
best_depot = GetDepotByTile(ftd.node.tile); /* Found target */ best_depot = GetDepotByTile(ftd.node.tile); /* Found target */
else } else {
best_depot = NULL; /* Did not find target */ best_depot = NULL; /* Did not find target */
}
} else { } else {
FOR_ALL_DEPOTS(depot) { FOR_ALL_DEPOTS(depot) {
tile = depot->xy; tile = depot->xy;
@ -93,21 +94,15 @@ static void CheckIfShipNeedsService(Vehicle *v)
{ {
const Depot* depot; const Depot* depot;
if (_patches.servint_ships == 0) if (_patches.servint_ships == 0) return;
return; if (!VehicleNeedsService(v)) return;
if (v->vehstatus & VS_STOPPED) return;
if (!VehicleNeedsService(v))
return;
if (v->vehstatus & VS_STOPPED)
return;
if (v->current_order.type == OT_GOTO_DEPOT && if (v->current_order.type == OT_GOTO_DEPOT &&
v->current_order.flags & OF_HALT_IN_DEPOT) v->current_order.flags & OF_HALT_IN_DEPOT)
return; return;
if (_patches.gotodepot && VehicleHasDepotOrders(v)) if (_patches.gotodepot && VehicleHasDepotOrders(v)) return;
return;
depot = FindClosestShipDepot(v); depot = FindClosestShipDepot(v);
@ -140,10 +135,7 @@ void OnNewDay_Ship(Vehicle *v)
CheckOrders(v->index, OC_INIT); CheckOrders(v->index, OC_INIT);
if (v->vehstatus & VS_STOPPED) if (v->vehstatus & VS_STOPPED) return;
return;
cost = ShipVehInfo(v->engine_type)->running_cost * _price.ship_running / 364; cost = ShipVehInfo(v->engine_type)->running_cost * _price.ship_running / 364;
v->profit_this_year -= cost >> 8; v->profit_this_year -= cost >> 8;
@ -173,8 +165,7 @@ static void HandleBrokenShip(Vehicle *v)
if (!(v->vehstatus & VS_HIDDEN)) { if (!(v->vehstatus & VS_HIDDEN)) {
Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE); Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
if (u) if (u != NULL) u->u.special.unk0 = v->breakdown_delay * 2;
u->u.special.unk0 = v->breakdown_delay * 2;
} }
} }
@ -268,15 +259,11 @@ static void ProcessShipOrder(Vehicle *v)
static void HandleShipLoading(Vehicle *v) static void HandleShipLoading(Vehicle *v)
{ {
if (v->current_order.type == OT_NOTHING) if (v->current_order.type == OT_NOTHING) return;
return;
if (v->current_order.type != OT_DUMMY) { if (v->current_order.type != OT_DUMMY) {
if (v->current_order.type != OT_LOADING) if (v->current_order.type != OT_LOADING) return;
return; if (--v->load_unload_time_rem) return;
if (--v->load_unload_time_rem)
return;
if (v->current_order.flags & OF_FULL_LOAD && CanFillVehicle(v)) { if (v->current_order.flags & OF_FULL_LOAD && CanFillVehicle(v)) {
SET_EXPENSES_TYPE(EXPENSES_SHIP_INC); SET_EXPENSES_TYPE(EXPENSES_SHIP_INC);
@ -292,8 +279,7 @@ static void HandleShipLoading(Vehicle *v)
Order b = v->current_order; Order b = v->current_order;
v->current_order.type = OT_LEAVESTATION; v->current_order.type = OT_LEAVESTATION;
v->current_order.flags = 0; v->current_order.flags = 0;
if (!(b.flags & OF_NON_STOP)) if (!(b.flags & OF_NON_STOP)) return;
return;
} }
} }
@ -341,8 +327,7 @@ static void CheckShipLeaveDepot(Vehicle *v)
int d; int d;
uint m; uint m;
if (v->u.ship.state != 0x80) if (v->u.ship.state != 0x80) return;
return;
tile = v->tile; tile = v->tile;
d = (_m[tile].m5&2) ? 1 : 0; d = (_m[tile].m5&2) ? 1 : 0;
@ -383,15 +368,10 @@ static bool ShipAccelerate(Vehicle *v)
} }
// Decrease somewhat when turning // Decrease somewhat when turning
if (!(v->direction&1)) { if (!(v->direction & 1)) spd = spd * 3 / 4;
spd = spd * 3 >> 2;
}
if (spd == 0) if (spd == 0) return false;
return false; if ((byte)++spd == 0) return true;
if ((byte)++spd == 0)
return true;
v->progress = (t = v->progress) - (byte)spd; v->progress = (t = v->progress) - (byte)spd;
@ -447,7 +427,9 @@ static void ShipArrivesAt(const Vehicle* v, Station* st)
/* Check if station was ever visited before */ /* Check if station was ever visited before */
if (!(st->had_vehicle_of_type & HVOT_SHIP)) { if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
uint32 flags; uint32 flags;
st->had_vehicle_of_type |= HVOT_SHIP; st->had_vehicle_of_type |= HVOT_SHIP;
SetDParam(0, st->index); SetDParam(0, st->index);
flags = (v->owner == _local_player) ? NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ARRIVAL_PLAYER, 0) : NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ARRIVAL_OTHER, 0); flags = (v->owner == _local_player) ? NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ARRIVAL_PLAYER, 0) : NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ARRIVAL_OTHER, 0);
AddNewsItem( AddNewsItem(
@ -564,14 +546,15 @@ static int ChooseShipTrack(Vehicle *v, TileIndex tile, int enterdir, uint tracks
ftd = NPFRouteToStationOrTile(src_tile, trackdir, &fstd, TRANSPORT_WATER, v->owner, INVALID_RAILTYPE, PBS_MODE_NONE); ftd = NPFRouteToStationOrTile(src_tile, trackdir, &fstd, TRANSPORT_WATER, v->owner, INVALID_RAILTYPE, PBS_MODE_NONE);
if (ftd.best_trackdir != 0xff) if (ftd.best_trackdir != 0xff) {
/* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains /* 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, 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 we did not find our target, but ftd.best_trackdir contains the direction leading
to the tile closest to our target. */ to the tile closest to our target. */
return ftd.best_trackdir & 7; /* TODO: Wrapper function? */ return ftd.best_trackdir & 7; /* TODO: Wrapper function? */
else } else {
return -1; /* Already at target, reverse? */ return -1; /* Already at target, reverse? */
}
} else { } else {
uint b; uint b;
uint tot_dist, dist; uint tot_dist, dist;
@ -676,19 +659,16 @@ static void ShipController(Vehicle *v)
v->breakdown_ctr--; v->breakdown_ctr--;
} }
if (v->vehstatus & VS_STOPPED) if (v->vehstatus & VS_STOPPED) return;
return;
ProcessShipOrder(v); ProcessShipOrder(v);
HandleShipLoading(v); HandleShipLoading(v);
if (v->current_order.type == OT_LOADING) if (v->current_order.type == OT_LOADING) return;
return;
CheckShipLeaveDepot(v); CheckShipLeaveDepot(v);
if (!ShipAccelerate(v)) if (!ShipAccelerate(v)) return;
return;
BeginVehicleMove(v); BeginVehicleMove(v);
@ -811,10 +791,8 @@ reverse_direction:
static void AgeShipCargo(Vehicle *v) static void AgeShipCargo(Vehicle *v)
{ {
if (_age_cargo_skip_counter != 0) if (_age_cargo_skip_counter != 0) return;
return; if (v->cargo_days != 255) v->cargo_days++;
if (v->cargo_days != 255)
v->cargo_days++;
} }
void Ship_Tick(Vehicle *v) void Ship_Tick(Vehicle *v)

View File

@ -66,10 +66,10 @@ static void DrawShipImage(const Vehicle *v, int x, int y, VehicleID selection)
{ {
int image = GetShipImage(v, 6); int image = GetShipImage(v, 6);
uint32 ormod = SPRITE_PALETTE(PLAYER_SPRITE_COLOR(v->owner)); uint32 ormod = SPRITE_PALETTE(PLAYER_SPRITE_COLOR(v->owner));
DrawSprite(image | ormod, x+32, y+10); DrawSprite(image | ormod, x + 32, y + 10);
if (v->index == selection) { if (v->index == selection) {
DrawFrameRect(x-5, y-1, x+67, y+21, 15, FR_BORDERONLY); DrawFrameRect(x - 5, y - 1, x + 67, y + 21, 15, FR_BORDERONLY);
} }
} }
@ -100,7 +100,7 @@ static void ShipRefitWndProc(Window *w, WindowEvent *e)
} break; } break;
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 2: { /* listbox */ case 2: { /* listbox */
int y = e->click.pt.y - 25; int y = e->click.pt.y - 25;
if (y >= 0) { if (y >= 0) {
@ -291,6 +291,7 @@ static void ShowShipDetailsWindow(const Vehicle* v)
{ {
Window *w; Window *w;
VehicleID veh = v->index; VehicleID veh = v->index;
DeleteWindowById(WC_VEHICLE_ORDERS, veh); DeleteWindowById(WC_VEHICLE_ORDERS, veh);
DeleteWindowById(WC_VEHICLE_DETAILS, veh); DeleteWindowById(WC_VEHICLE_DETAILS, veh);
_alloc_wnd_parent_num = veh; _alloc_wnd_parent_num = veh;
@ -314,19 +315,14 @@ void CcBuildShip(bool success, TileIndex tile, uint32 p1, uint32 p2)
void CcCloneShip(bool success, uint tile, uint32 p1, uint32 p2) void CcCloneShip(bool success, uint tile, uint32 p1, uint32 p2)
{ {
if (success) { if (success) ShowShipViewWindow(GetVehicle(_new_ship_id));
const Vehicle* v = GetVehicle(_new_ship_id);
ShowShipViewWindow(v);
}
} }
static void NewShipWndProc(Window *w, WindowEvent *e) static void NewShipWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
if (w->window_number == 0) if (w->window_number == 0) w->disabled_state = 1 << 5;
w->disabled_state = 1 << 5;
// Setup scroll count // Setup scroll count
{ {
@ -335,8 +331,7 @@ static void NewShipWndProc(Window *w, WindowEvent *e)
const Engine* e = GetEngine(SHIP_ENGINES_INDEX); const Engine* e = GetEngine(SHIP_ENGINES_INDEX);
do { do {
if (HASBIT(e->player_avail, _local_player)) if (HASBIT(e->player_avail, _local_player)) count++;
count++;
} while (++e,--num); } while (++e,--num);
SetVScrollCount(w, count); SetVScrollCount(w, count);
} }
@ -760,8 +755,9 @@ static void ClonePlaceObj(TileIndex tile, const Window* w)
if (v != NULL) HandleCloneVehClick(v, w); if (v != NULL) HandleCloneVehClick(v, w);
} }
static void ShipDepotWndProc(Window *w, WindowEvent *e) { static void ShipDepotWndProc(Window* w, WindowEvent* e)
switch(e->event) { {
switch (e->event) {
case WE_PAINT: case WE_PAINT:
DrawShipDepotWindow(w); DrawShipDepotWindow(w);
break; break;
@ -896,10 +892,9 @@ static const WindowDesc _ship_depot_desc = {
void ShowShipDepotWindow(TileIndex tile) void ShowShipDepotWindow(TileIndex tile)
{ {
Window *w; Window* w = AllocateWindowDescFront(&_ship_depot_desc,tile);
w = AllocateWindowDescFront(&_ship_depot_desc,tile); if (w != NULL) {
if (w) {
w->caption_color = GetTileOwner(w->window_number); w->caption_color = GetTileOwner(w->window_number);
w->vscroll.cap = 2; w->vscroll.cap = 2;
w->hscroll.cap = 3; w->hscroll.cap = 3;
@ -911,7 +906,8 @@ void ShowShipDepotWindow(TileIndex tile)
} }
static void DrawSmallOrderList(const Vehicle *v, int x, int y) { static void DrawSmallOrderList(const Vehicle* v, int x, int y)
{
const Order *order; const Order *order;
int sel, i = 0; int sel, i = 0;
@ -920,7 +916,7 @@ static void DrawSmallOrderList(const Vehicle *v, int x, int y) {
FOR_VEHICLE_ORDERS(v, order) { FOR_VEHICLE_ORDERS(v, order) {
if (sel == 0) { if (sel == 0) {
_stringwidth_base = 0xE0; _stringwidth_base = 0xE0;
DoDrawString( "\xAF", x-6, y, 16); DoDrawString("\xAF", x - 6, y, 16);
_stringwidth_base = 0; _stringwidth_base = 0;
} }
sel--; sel--;
@ -931,8 +927,7 @@ static void DrawSmallOrderList(const Vehicle *v, int x, int y) {
DrawString(x, y, STR_A036, 0); DrawString(x, y, STR_A036, 0);
y += 6; y += 6;
if (++i == 4) if (++i == 4) break;
break;
} }
} }
} }
@ -1081,9 +1076,7 @@ static void PlayerShipsWndProc(Window *w, WindowEvent *e)
case 9: { /* Build new Vehicle */ case 9: { /* Build new Vehicle */
TileIndex tile; TileIndex tile;
if (!IsWindowOfPrototype(w, _player_ships_widgets)) if (!IsWindowOfPrototype(w, _player_ships_widgets)) break;
break;
tile = _last_built_ship_depot_tile; tile = _last_built_ship_depot_tile;
do { do {
@ -1100,8 +1093,7 @@ static void PlayerShipsWndProc(Window *w, WindowEvent *e)
} break; } break;
case 10: { case 10: {
if (!IsWindowOfPrototype(w, _player_ships_widgets)) if (!IsWindowOfPrototype(w, _player_ships_widgets)) break;
break;
ShowReplaceVehicleWindow(VEH_Ship); ShowReplaceVehicleWindow(VEH_Ship);
break; break;
@ -1173,12 +1165,12 @@ void ShowPlayerShips(PlayerID player, StationID station)
{ {
Window *w; Window *w;
if ( player == _local_player) { if (player == _local_player) {
w = AllocateWindowDescFront(&_player_ships_desc, (station << 16) | player); w = AllocateWindowDescFront(&_player_ships_desc, (station << 16) | player);
} else { } else {
w = AllocateWindowDescFront(&_other_player_ships_desc, (station << 16) | player); w = AllocateWindowDescFront(&_other_player_ships_desc, (station << 16) | player);
} }
if (w) { if (w != NULL) {
w->caption_color = w->window_number; w->caption_color = w->window_number;
w->vscroll.cap = 4; w->vscroll.cap = 4;
w->widget[7].unkA = (w->vscroll.cap << 8) + 1; w->widget[7].unkA = (w->vscroll.cap << 8) + 1;

View File

@ -44,8 +44,7 @@ static void StationPoolNewBlock(uint start_item)
{ {
Station *st; Station *st;
FOR_ALL_STATIONS_FROM(st, start_item) FOR_ALL_STATIONS_FROM(st, start_item) st->index = start_item++;
st->index = start_item++;
} }
/** /**
@ -55,8 +54,7 @@ static void RoadStopPoolNewBlock(uint start_item)
{ {
RoadStop *rs; RoadStop *rs;
FOR_ALL_ROADSTOPS_FROM(rs, start_item) FOR_ALL_ROADSTOPS_FROM(rs, start_item) rs->index = start_item++;
rs->index = start_item++;
} }
/* Initialize the station-pool and roadstop-pool */ /* Initialize the station-pool and roadstop-pool */
@ -96,7 +94,7 @@ static void InitializeRoadStop(RoadStop *road_stop, RoadStop *previous, TileInde
road_stop->station = index; road_stop->station = index;
} }
RoadStop * GetPrimaryRoadStop(const Station *st, RoadStopType type) RoadStop* GetPrimaryRoadStop(const Station* st, RoadStopType type)
{ {
switch (type) { switch (type) {
case RS_BUS: return st->bus_stops; case RS_BUS: return st->bus_stops;
@ -107,13 +105,14 @@ RoadStop * GetPrimaryRoadStop(const Station *st, RoadStopType type)
return NULL; return NULL;
} }
RoadStop * GetRoadStopByTile(TileIndex tile, RoadStopType type) RoadStop* GetRoadStopByTile(TileIndex tile, RoadStopType type)
{ {
const Station *st = GetStation(_m[tile].m2); const Station* st = GetStation(_m[tile].m2);
RoadStop *rs; RoadStop* rs;
for ( rs = GetPrimaryRoadStop(st, type); rs->xy != tile; rs = rs->next) for (rs = GetPrimaryRoadStop(st, type); rs->xy != tile; rs = rs->next) {
assert(rs->next != NULL); assert(rs->next != NULL);
}
return rs; return rs;
} }
@ -145,8 +144,7 @@ RoadStop *AllocateRoadStop(void)
} }
/* Check if we can add a block to the pool */ /* Check if we can add a block to the pool */
if (AddBlockToPool(&_roadstop_pool)) if (AddBlockToPool(&_roadstop_pool)) return AllocateRoadStop();
return AllocateRoadStop();
return NULL; return NULL;
} }
@ -266,8 +264,7 @@ static Station *AllocateStation(void)
} }
/* Check if we can add a block to the pool */ /* Check if we can add a block to the pool */
if (AddBlockToPool(&_station_pool)) if (AddBlockToPool(&_station_pool)) return AllocateStation();
return AllocateStation();
_error_message = STR_3008_TOO_MANY_STATIONS_LOADING; _error_message = STR_3008_TOO_MANY_STATIONS_LOADING;
return NULL; return NULL;
@ -480,10 +477,10 @@ static void UpdateStationVirtCoord(Station *st)
// Update the virtual coords needed to draw the station sign for all stations. // Update the virtual coords needed to draw the station sign for all stations.
void UpdateAllStationVirtCoord(void) void UpdateAllStationVirtCoord(void)
{ {
Station *st; Station* st;
FOR_ALL_STATIONS(st) { FOR_ALL_STATIONS(st) {
if (st->xy != 0) if (st->xy != 0) UpdateStationVirtCoord(st);
UpdateStationVirtCoord(st);
} }
} }
@ -602,8 +599,7 @@ void GetAcceptanceAroundTiles(AcceptedCargo accepts, TileIndex tile,
uint i; uint i;
GetAcceptedCargo(tile, ac); GetAcceptedCargo(tile, ac);
for (i = 0; i < lengthof(ac); ++i) for (i = 0; i < lengthof(ac); ++i) accepts[i] += ac[i];
accepts[i] += ac[i];
} }
} }
} }
@ -642,8 +638,7 @@ static void UpdateStationAcceptance(Station *st, bool show_msg)
rect.min_y = MapSizeY(); rect.min_y = MapSizeY();
rect.max_x = rect.max_y = 0; rect.max_x = rect.max_y = 0;
// Don't update acceptance for a buoy // Don't update acceptance for a buoy
if (IsBuoy(st)) if (IsBuoy(st)) return;
return;
/* old accepted goods types */ /* old accepted goods types */
old_acc = GetAcceptanceMask(st); old_acc = GetAcceptanceMask(st);
@ -732,7 +727,8 @@ static void UpdateStationAcceptance(Station *st, bool show_msg)
// This is called right after a station was deleted. // This is called right after a station was deleted.
// It checks if the whole station is free of substations, and if so, the station will be // It checks if the whole station is free of substations, and if so, the station will be
// deleted after a little while. // deleted after a little while.
static void DeleteStationIfEmpty(Station *st) { static void DeleteStationIfEmpty(Station* st)
{
if (st->facilities == 0) { if (st->facilities == 0) {
st->delete_ctr = 0; st->delete_ctr = 0;
InvalidateWindow(WC_STATION_LIST, st->owner); InvalidateWindow(WC_STATION_LIST, st->owner);
@ -753,8 +749,7 @@ int32 CheckFlatLandBelow(TileIndex tile, uint w, uint h, uint flags, uint invali
int flat_z; int flat_z;
BEGIN_TILE_LOOP(tile_cur, w, h, tile) BEGIN_TILE_LOOP(tile_cur, w, h, tile)
if (!EnsureNoVehicle(tile_cur)) if (!EnsureNoVehicle(tile_cur)) return CMD_ERROR;
return CMD_ERROR;
tileh = GetTileSlope(tile_cur, &z); tileh = GetTileSlope(tile_cur, &z);
@ -767,9 +762,7 @@ int32 CheckFlatLandBelow(TileIndex tile, uint w, uint h, uint flags, uint invali
b) the build_on_slopes switch is disabled b) the build_on_slopes switch is disabled
*/ */
if (IsSteepTileh(tileh) || if (IsSteepTileh(tileh) ||
((_is_old_ai_player || !_patches.build_on_slopes) ((_is_old_ai_player || !_patches.build_on_slopes) && tileh != 0)) {
&& tileh != 0)) {
_error_message = STR_0007_FLAT_LAND_REQUIRED; _error_message = STR_0007_FLAT_LAND_REQUIRED;
return CMD_ERROR; return CMD_ERROR;
} }
@ -897,7 +890,6 @@ static inline byte *CreateMulti(byte *layout, int n, byte b)
return layout; return layout;
} }
// stolen from TTDPatch
static void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *spec) static void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *spec)
{ {
if (spec != NULL && spec->lengths >= plat_len && if (spec != NULL && spec->lengths >= plat_len &&
@ -912,9 +904,8 @@ static void GetStationLayout(byte *layout, int numtracks, int plat_len, const St
if (plat_len == 1) { if (plat_len == 1) {
CreateSingle(layout, numtracks); CreateSingle(layout, numtracks);
} else { } else {
if (numtracks & 1) if (numtracks & 1) layout = CreateSingle(layout, plat_len);
layout = CreateSingle(layout, plat_len); numtracks >>= 1;
numtracks>>=1;
while (--numtracks >= 0) { while (--numtracks >= 0) {
layout = CreateMulti(layout, plat_len, 4); layout = CreateMulti(layout, plat_len, 4);
@ -1004,24 +995,19 @@ int32 CmdBuildRailroadStation(int x, int y, uint32 flags, uint32 p1, uint32 p2)
} }
//XXX can't we pack this in the "else" part of the if above? //XXX can't we pack this in the "else" part of the if above?
if (!CheckStationSpreadOut(st, tile_org, w_org, h_org)) if (!CheckStationSpreadOut(st, tile_org, w_org, h_org)) return CMD_ERROR;
return CMD_ERROR;
} else { } else {
// Create a new station // Create a new station
st = AllocateStation(); st = AllocateStation();
if (st == NULL) if (st == NULL) return CMD_ERROR;
return CMD_ERROR;
st->town = ClosestTownFromTile(tile_org, (uint)-1); st->town = ClosestTownFromTile(tile_org, (uint)-1);
if (_current_player < MAX_PLAYERS && flags&DC_EXEC) if (_current_player < MAX_PLAYERS && flags & DC_EXEC)
SETBIT(st->town->have_ratings, _current_player); SETBIT(st->town->have_ratings, _current_player);
if (!GenerateStationName(st, tile_org, 0)) if (!GenerateStationName(st, tile_org, 0)) return CMD_ERROR;
return CMD_ERROR;
if (flags & DC_EXEC) if (flags & DC_EXEC) StationInitialize(st, tile_org);
StationInitialize(st, tile_org);
} }
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
@ -1176,20 +1162,26 @@ uint GetStationPlatforms(const Station *st, TileIndex tile)
TileIndex t; TileIndex t;
TileIndexDiff delta; TileIndexDiff delta;
int dir; int dir;
int len; uint len;
assert(TileBelongsToRailStation(st, tile)); assert(TileBelongsToRailStation(st, tile));
len = 0; len = 0;
dir = _m[tile].m5&1; dir = _m[tile].m5 & 1;
delta = dir ? TileDiffXY(0, 1) : TileDiffXY(1, 0); delta = dir ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
// find starting tile.. // find starting tile..
t = tile; t = tile;
do { t -= delta; len++; } while (TileBelongsToRailStation(st, t) && (_m[t].m5&1) == dir); do {
t -= delta;
len++;
} while (TileBelongsToRailStation(st, t) && (_m[t].m5 & 1) == dir);
// find ending tile // find ending tile
t = tile; t = tile;
do { t += delta; len++; }while (TileBelongsToRailStation(st, t) && (_m[t].m5&1) == dir); do {
t += delta;
len++;
} while (TileBelongsToRailStation(st, t) && (_m[t].m5 & 1) == dir);
return len - 1; return len - 1;
} }
@ -1396,17 +1388,15 @@ int32 CmdBuildRoadStop(int x, int y, uint32 flags, uint32 p1, uint32 p2)
return CMD_ERROR; return CMD_ERROR;
cost = CheckFlatLandBelow(tile, 1, 1, flags, 1 << p1, NULL); cost = CheckFlatLandBelow(tile, 1, 1, flags, 1 << p1, NULL);
if (cost == CMD_ERROR) if (cost == CMD_ERROR) return CMD_ERROR;
return CMD_ERROR;
st = GetStationAround(tile, 1, 1, -1); st = GetStationAround(tile, 1, 1, -1);
if (st == CHECK_STATIONS_ERR) if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
return CMD_ERROR;
/* Find a station close to us */ /* Find a station close to us */
if (st == NULL) { if (st == NULL) {
st = GetClosestStationFromTile(tile, 8, _current_player); st = GetClosestStationFromTile(tile, 8, _current_player);
if (st!=NULL && st->facilities) st = NULL; if (st != NULL && st->facilities) st = NULL;
} }
//give us a road stop in the list, and check if something went wrong //give us a road stop in the list, and check if something went wrong
@ -1429,8 +1419,7 @@ int32 CmdBuildRoadStop(int x, int y, uint32 flags, uint32 p1, uint32 p2)
Town *t; Town *t;
st = AllocateStation(); st = AllocateStation();
if (st == NULL) if (st == NULL) return CMD_ERROR;
return CMD_ERROR;
st->town = t = ClosestTownFromTile(tile, (uint)-1); st->town = t = ClosestTownFromTile(tile, (uint)-1);
@ -1441,11 +1430,9 @@ int32 CmdBuildRoadStop(int x, int y, uint32 flags, uint32 p1, uint32 p2)
st->sign.width_1 = 0; st->sign.width_1 = 0;
if (!GenerateStationName(st, tile, 0)) if (!GenerateStationName(st, tile, 0)) return CMD_ERROR;
return CMD_ERROR;
if (flags & DC_EXEC) if (flags & DC_EXEC) StationInitialize(st, tile);
StationInitialize(st, tile);
} }
cost += (type) ? _price.build_truck_station : _price.build_bus_station; cost += (type) ? _price.build_truck_station : _price.build_bus_station;
@ -1489,7 +1476,7 @@ static int32 RemoveRoadStop(Station *st, uint32 flags, TileIndex tile)
if (_current_player != OWNER_WATER && !CheckOwnership(st->owner)) if (_current_player != OWNER_WATER && !CheckOwnership(st->owner))
return CMD_ERROR; return CMD_ERROR;
if (is_truck) { //truck stop if (is_truck) { // truck stop
primary_stop = &st->truck_stops; primary_stop = &st->truck_stops;
cur_stop = GetRoadStopByTile(tile, RS_TRUCK); cur_stop = GetRoadStopByTile(tile, RS_TRUCK);
} else { } else {
@ -1503,7 +1490,7 @@ static int32 RemoveRoadStop(Station *st, uint32 flags, TileIndex tile)
return CMD_ERROR; return CMD_ERROR;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
int i; uint i;
DoClearSquare(tile); DoClearSquare(tile);
/* Clear all vehicles destined for this station */ /* Clear all vehicles destined for this station */
@ -1515,19 +1502,14 @@ static int32 RemoveRoadStop(Station *st, uint32 flags, TileIndex tile)
} }
cur_stop->used = false; cur_stop->used = false;
if (cur_stop->prev != NULL) //alter previous stop if (cur_stop->prev != NULL) cur_stop->prev->next = cur_stop->next;
cur_stop->prev->next = cur_stop->next; if (cur_stop->next != NULL) cur_stop->next->prev = cur_stop->prev;
if (cur_stop->next != NULL) //alter next stop
cur_stop->next->prev = cur_stop->prev;
//we only had one stop left //we only had one stop left
if (cur_stop->next == NULL && cur_stop->prev == NULL) { if (cur_stop->next == NULL && cur_stop->prev == NULL) {
//so we remove ALL stops //so we remove ALL stops
*primary_stop = NULL; *primary_stop = NULL;
st->facilities &= (is_truck) ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP; st->facilities &= (is_truck) ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP;
} else if (cur_stop == *primary_stop) { } else if (cur_stop == *primary_stop) {
//removed the first stop in the list //removed the first stop in the list
//need to set the primary element to the next stop //need to set the primary element to the next stop
@ -1666,7 +1648,7 @@ int32 CmdBuildAirport(int x, int y, uint32 flags, uint32 p1, uint32 p2)
st->town = t; st->town = t;
if (_current_player < MAX_PLAYERS && flags&DC_EXEC) if (_current_player < MAX_PLAYERS && flags & DC_EXEC)
SETBIT(t->have_ratings, _current_player); SETBIT(t->have_ratings, _current_player);
st->sign.width_1 = 0; st->sign.width_1 = 0;
@ -1697,12 +1679,13 @@ int32 CmdBuildAirport(int x, int y, uint32 flags, uint32 p1, uint32 p2)
st->build_date = _date; st->build_date = _date;
/* if airport was demolished while planes were en-route to it, the positions can no longer /* if airport was demolished while planes were en-route to it, the
be the same (v->u.air.pos), since different airports have different indexes. So update * positions can no longer be the same (v->u.air.pos), since different
all planes en-route to this airport. Only update if * airports have different indexes. So update all planes en-route to this
1. airport is upgraded * airport. Only update if
2. airport is added to existing station (unfortunately unavoideable) * 1. airport is upgraded
*/ * 2. airport is added to existing station (unfortunately unavoideable)
*/
if (airport_upgrade) UpdateAirplanesOnNewStation(st); if (airport_upgrade) UpdateAirplanesOnNewStation(st);
{ {
@ -1850,11 +1833,8 @@ static int32 RemoveBuoy(Station *st, uint32 flags)
tile = st->dock_tile; tile = st->dock_tile;
if (CheckShipsOnBuoy(st)) if (CheckShipsOnBuoy(st)) return_cmd_error(STR_BUOY_IS_IN_USE);
return_cmd_error(STR_BUOY_IS_IN_USE); if (!EnsureNoVehicle(tile)) return CMD_ERROR;
if (!EnsureNoVehicle(tile))
return CMD_ERROR;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
st->dock_tile = 0; st->dock_tile = 0;
@ -1963,8 +1943,7 @@ int32 CmdBuildDock(int x, int y, uint32 flags, uint32 p1, uint32 p2)
if (!GenerateStationName(st, tile, 3)) return CMD_ERROR; if (!GenerateStationName(st, tile, 3)) return CMD_ERROR;
if (flags & DC_EXEC) if (flags & DC_EXEC) StationInitialize(st, tile);
StationInitialize(st, tile);
} }
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
@ -2001,17 +1980,13 @@ static int32 RemoveDock(Station *st, uint32 flags)
TileIndex tile1; TileIndex tile1;
TileIndex tile2; TileIndex tile2;
if (!CheckOwnership(st->owner)) if (!CheckOwnership(st->owner)) return CMD_ERROR;
return CMD_ERROR;
tile1 = st->dock_tile; tile1 = st->dock_tile;
tile2 = tile1 + TileOffsByDir(_m[tile1].m5 - 0x4C); tile2 = tile1 + TileOffsByDir(_m[tile1].m5 - 0x4C);
if (!EnsureNoVehicle(tile1)) if (!EnsureNoVehicle(tile1)) return CMD_ERROR;
return CMD_ERROR; if (!EnsureNoVehicle(tile2)) return CMD_ERROR;
if (!EnsureNoVehicle(tile2))
return CMD_ERROR;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
DoClearSquare(tile1); DoClearSquare(tile1);
@ -2048,8 +2023,7 @@ static void DrawTile_Station(TileInfo *ti)
{ {
PlayerID owner = GetTileOwner(ti->tile); PlayerID owner = GetTileOwner(ti->tile);
image_or_modificator = PALETTE_TO_GREY; /* NOTE: possible bug in ttd here? */ image_or_modificator = PALETTE_TO_GREY; /* NOTE: possible bug in ttd here? */
if (owner < MAX_PLAYERS) if (owner < MAX_PLAYERS) image_or_modificator = PLAYER_SPRITE_COLOR(owner);
image_or_modificator = PLAYER_SPRITE_COLOR(owner);
} }
// don't show foundation for docks (docks are between 76 (0x4C) and 81 (0x51)) // don't show foundation for docks (docks are between 76 (0x4C) and 81 (0x51))
@ -2074,8 +2048,7 @@ static void DrawTile_Station(TileInfo *ti)
if (t == NULL) t = &_station_display_datas[ti->map5]; if (t == NULL) t = &_station_display_datas[ti->map5];
image = t->ground_sprite; image = t->ground_sprite;
if (image & PALETTE_MODIFIER_COLOR) if (image & PALETTE_MODIFIER_COLOR) image |= image_or_modificator;
image |= image_or_modificator;
// For custom sprites, there's no railtype-based pitching. // For custom sprites, there's no railtype-based pitching.
offset = (image & SPRITE_MASK) < _custom_sprites_base ? rti->total_offset : railtype; offset = (image & SPRITE_MASK) < _custom_sprites_base ? rti->total_offset : railtype;
@ -2124,8 +2097,7 @@ void StationPickerDrawSprite(int x, int y, RailType railtype, int image)
t = &_station_display_datas[image]; t = &_station_display_datas[image];
img = t->ground_sprite; img = t->ground_sprite;
if (img & PALETTE_MODIFIER_COLOR) if (img & PALETTE_MODIFIER_COLOR) img |= ormod;
img |= ormod;
DrawSprite(img + rti->total_offset, x, y); DrawSprite(img + rti->total_offset, x, y);
foreach_draw_tile_seq(dtss, t->seq) { foreach_draw_tile_seq(dtss, t->seq) {
@ -2280,7 +2252,6 @@ static uint32 VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
{ {
StationID station_id; StationID station_id;
byte dir; byte dir;
uint16 spd;
if (v->type == VEH_Train) { if (v->type == VEH_Train) {
if (IS_BYTE_INSIDE(_m[tile].m5, 0, 8) && v->subtype == TS_Front_Engine && if (IS_BYTE_INSIDE(_m[tile].m5, 0, 8) && v->subtype == TS_Front_Engine &&
@ -2289,7 +2260,6 @@ static uint32 VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
station_id = _m[tile].m2; station_id = _m[tile].m2;
if ((!(v->current_order.flags & OF_NON_STOP) && !_patches.new_nonstop) || if ((!(v->current_order.flags & OF_NON_STOP) && !_patches.new_nonstop) ||
(v->current_order.type == OT_GOTO_STATION && v->current_order.station == station_id)) { (v->current_order.type == OT_GOTO_STATION && v->current_order.station == station_id)) {
if (!(_patches.new_nonstop && v->current_order.flags & OF_NON_STOP) && if (!(_patches.new_nonstop && v->current_order.flags & OF_NON_STOP) &&
v->current_order.type != OT_LEAVESTATION && v->current_order.type != OT_LEAVESTATION &&
v->last_station_visited != station_id) { v->last_station_visited != station_id) {
@ -2299,15 +2269,14 @@ static uint32 VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
dir = v->direction & 6; dir = v->direction & 6;
if (dir & 2) intswap(x,y); if (dir & 2) intswap(x,y);
if (y == 8) { if (y == 8) {
if (dir != 2 && dir != 4) { if (dir != 2 && dir != 4) x = ~x & 0xF;
x = (~x)&0xF;
}
if (x == 12) return 2 | (station_id << 8); /* enter station */ if (x == 12) return 2 | (station_id << 8); /* enter station */
if (x < 12) { if (x < 12) {
uint16 spd;
v->vehstatus |= VS_TRAIN_SLOWING; v->vehstatus |= VS_TRAIN_SLOWING;
spd = _enter_station_speedtable[x]; spd = _enter_station_speedtable[x];
if (spd < v->cur_speed) if (spd < v->cur_speed) v->cur_speed = spd;
v->cur_speed = spd;
} }
} }
} }
@ -2391,8 +2360,7 @@ static void DeleteStation(Station *st)
} }
} }
//Orders for the vehicle have been changed, invalidate the window //Orders for the vehicle have been changed, invalidate the window
if (invalidate) if (invalidate) InvalidateWindow(WC_VEHICLE_ORDERS, v->index);
InvalidateWindow(WC_VEHICLE_ORDERS, v->index);
} }
//Subsidies need removal as well //Subsidies need removal as well
@ -2404,8 +2372,7 @@ void DeleteAllPlayerStations(void)
Station *st; Station *st;
FOR_ALL_STATIONS(st) { FOR_ALL_STATIONS(st) {
if (st->xy && st->owner < MAX_PLAYERS) if (st->xy != 0 && st->owner < MAX_PLAYERS) DeleteStation(st);
DeleteStation(st);
} }
} }
@ -2435,10 +2402,7 @@ static void StationHandleBigTick(Station *st)
{ {
UpdateStationAcceptance(st, true); UpdateStationAcceptance(st, true);
if (st->facilities == 0) { if (st->facilities == 0 && ++st->delete_ctr >= 8) DeleteStation(st);
if (++st->delete_ctr >= 8)
DeleteStation(st);
}
// Here we saveguard against orphaned slots // Here we saveguard against orphaned slots
CheckOrphanedSlots(st, RS_BUS); CheckOrphanedSlots(st, RS_BUS);
@ -2546,15 +2510,13 @@ static void StationHandleSmallTick(Station *st)
{ {
byte b; byte b;
if (st->facilities == 0) if (st->facilities == 0) return;
return;
b = st->delete_ctr + 1; b = st->delete_ctr + 1;
if (b >= 185) b = 0; if (b >= 185) b = 0;
st->delete_ctr = b; st->delete_ctr = b;
if (b == 0) if (b == 0) UpdateStationRating(st);
UpdateStationRating(st);
} }
void OnTick_Station(void) void OnTick_Station(void)
@ -2562,22 +2524,17 @@ void OnTick_Station(void)
uint i; uint i;
Station *st; Station *st;
if (_game_mode == GM_EDITOR) if (_game_mode == GM_EDITOR) return;
return;
i = _station_tick_ctr; i = _station_tick_ctr;
if (++_station_tick_ctr == GetStationPoolSize()) if (++_station_tick_ctr == GetStationPoolSize()) _station_tick_ctr = 0;
_station_tick_ctr = 0;
st = GetStation(i); st = GetStation(i);
if (st->xy != 0) if (st->xy != 0) StationHandleBigTick(st);
StationHandleBigTick(st);
FOR_ALL_STATIONS(st) { FOR_ALL_STATIONS(st) {
if (st->xy != 0) if (st->xy != INVALID_TILE) StationHandleSmallTick(st);
StationHandleSmallTick(st);
} }
} }
void StationMonthlyLoop(void) void StationMonthlyLoop(void)
@ -2623,7 +2580,7 @@ static void UpdateStationWaiting(Station *st, int type, uint amount)
*/ */
int32 CmdRenameStation(int x, int y, uint32 flags, uint32 p1, uint32 p2) int32 CmdRenameStation(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{ {
StringID str,old_str; StringID str;
Station *st; Station *st;
if (!IsStationIndex(p1) || _cmd_text[0] == '\0') return CMD_ERROR; if (!IsStationIndex(p1) || _cmd_text[0] == '\0') return CMD_ERROR;
@ -2635,7 +2592,8 @@ int32 CmdRenameStation(int x, int y, uint32 flags, uint32 p1, uint32 p2)
if (str == 0) return CMD_ERROR; if (str == 0) return CMD_ERROR;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
old_str = st->string_id; StringID old_str = st->string_id;
st->string_id = str; st->string_id = str;
UpdateStationVirtCoord(st); UpdateStationVirtCoord(st);
DeleteName(old_str); DeleteName(old_str);
@ -2686,7 +2644,7 @@ uint MoveGoodsToStation(TileIndex tile, int w, int h, int type, uint amount)
cur_tile = TILE_MASK(cur_tile); cur_tile = TILE_MASK(cur_tile);
if (IsTileType(cur_tile, MP_STATION)) { if (IsTileType(cur_tile, MP_STATION)) {
st_index = _m[cur_tile].m2; st_index = _m[cur_tile].m2;
for(i=0; i!=8; i++) { for (i = 0; i != 8; i++) {
if (around[i] == INVALID_STATION) { if (around[i] == INVALID_STATION) {
st = GetStation(st_index); st = GetStation(st_index);
if (!IsBuoy(st) && if (!IsBuoy(st) &&
@ -2788,7 +2746,7 @@ uint MoveGoodsToStation(TileIndex tile, int w, int h, int type, uint amount)
void BuildOilRig(TileIndex tile) void BuildOilRig(TileIndex tile)
{ {
int j; uint j;
Station *st = AllocateStation(); Station *st = AllocateStation();
if (st == NULL) { if (st == NULL) {
@ -2804,11 +2762,11 @@ void BuildOilRig(TileIndex tile)
st->sign.width_1 = 0; st->sign.width_1 = 0;
SetTileType(tile, MP_STATION); SetTileType(tile, MP_STATION);
_m[tile].m5 = 0x4B;
SetTileOwner(tile, OWNER_NONE); SetTileOwner(tile, OWNER_NONE);
_m[tile].m2 = st->index;
_m[tile].m3 = 0; _m[tile].m3 = 0;
_m[tile].m4 = 0; _m[tile].m4 = 0;
_m[tile].m2 = st->index; _m[tile].m5 = 0x4B;
st->owner = OWNER_NONE; st->owner = OWNER_NONE;
st->airport_flags = 0; st->airport_flags = 0;
@ -2887,24 +2845,14 @@ static int32 ClearTile_Station(TileIndex tile, byte flags)
st = GetStation(_m[tile].m2); st = GetStation(_m[tile].m2);
if (m5 < 8) if (m5 < 8) return RemoveRailroadStation(st, tile, flags);
return RemoveRailroadStation(st, tile, flags);
// original airports < 67, new airports between 83 - 114 // original airports < 67, new airports between 83 - 114
if (m5 < 0x43 || ( m5 >= 83 && m5 <= 114) ) if (m5 < 0x43 || (m5 >= 83 && m5 <= 114)) return RemoveAirport(st, flags);
return RemoveAirport(st, flags); if (m5 < 0x4B) return RemoveRoadStop(st, flags, tile);
if (m5 == 0x52) return RemoveBuoy(st, flags);
if (m5 < 0x4B) if (m5 != 0x4B && m5 < 0x53) return RemoveDock(st, flags);
return RemoveRoadStop(st, flags, tile);
if (m5 == 0x52)
return RemoveBuoy(st, flags);
if (m5 != 0x4B && m5 < 0x53)
return RemoveDock(st, flags);
return CMD_ERROR; return CMD_ERROR;
} }
void InitializeStations(void) void InitializeStations(void)
@ -3036,8 +2984,9 @@ static void SaveLoad_STNS(Station *st)
SlObject(&st->goods[i], _goods_desc); SlObject(&st->goods[i], _goods_desc);
/* In older versions, enroute_from had 0xFF as INVALID_STATION, is now 0xFFFF */ /* In older versions, enroute_from had 0xFF as INVALID_STATION, is now 0xFFFF */
if (_sl_full_version < 0x700 && st->goods[i].enroute_from == 0xFF) if (_sl_full_version < 0x700 && st->goods[i].enroute_from == 0xFF) {
st->goods[i].enroute_from = INVALID_STATION; st->goods[i].enroute_from = INVALID_STATION;
}
} }
} }
@ -3066,10 +3015,11 @@ static void Load_STNS(void)
SaveLoad_STNS(st); SaveLoad_STNS(st);
// this means it's an oldstyle savegame without support for nonuniform stations // this means it's an oldstyle savegame without support for nonuniform stations
if (st->train_tile && st->trainst_h == 0) { if (st->train_tile != 0 && st->trainst_h == 0) {
int w = st->trainst_w >> 4; int w = st->trainst_w >> 4;
int h = st->trainst_w & 0xF; int h = st->trainst_w & 0xF;
if (_m[st->train_tile].m5&1) intswap(w,h);
if (_m[st->train_tile].m5 & 1) intswap(w, h);
st->trainst_w = w; st->trainst_w = w;
st->trainst_h = h; st->trainst_h = h;
} }
@ -3094,8 +3044,7 @@ static void Load_STNS(void)
} }
/* This is to ensure all pointers are within the limits of _stations_size */ /* This is to ensure all pointers are within the limits of _stations_size */
if (_station_tick_ctr > GetStationPoolSize()) if (_station_tick_ctr > GetStationPoolSize()) _station_tick_ctr = 0;
_station_tick_ctr = 0;
} }
static void Save_ROADSTOP(void) static void Save_ROADSTOP(void)

View File

@ -22,34 +22,33 @@ static void StationsWndShowStationRating(int x, int y, int type, uint acceptance
int color = _rating_colors[type]; int color = _rating_colors[type];
uint w; uint w;
if (acceptance > 575) if (acceptance > 575) acceptance = 575;
acceptance = 575;
acceptance = (acceptance + 7) >> 3; acceptance = (acceptance + 7) / 8;
/* draw cargo */ /* draw cargo */
if ( (w=acceptance>>3) != 0) { w = acceptance / 8;
GfxFillRect(x, y, x+w-1, y+6, color); if (w != 0) {
GfxFillRect(x, y, x + w - 1, y + 6, color);
x += w; x += w;
} }
if ( (w=acceptance&7) != 0) { w = acceptance % 8;
if (w==7) w--; if (w != 0) {
GfxFillRect(x, y+(w-1), x, y+6, color); if (w == 7) w--;
GfxFillRect(x, y + (w - 1), x, y + 6, color);
} }
x -= (acceptance>>3); x -= acceptance / 8;
DrawString(x+1, y, _cargoc.names_short[type], 0x10); DrawString(x + 1, y, _cargoc.names_short[type], 0x10);
/* draw green/red ratings bar */ /* draw green/red ratings bar */
GfxFillRect(x+1, y+8, x+7, y+8, 0xB8); GfxFillRect(x + 1, y + 8, x + 7, y + 8, 0xB8);
rating = (rating >> 5); rating >>= 5;
if (rating != 0) { if (rating != 0) GfxFillRect(x + 1, y + 8, x + rating, y + 8, 0xD0);
GfxFillRect(x+1, y+8, x+rating, y+8, 0xD0);
}
} }
static uint16 _num_station_sort[MAX_PLAYERS]; static uint16 _num_station_sort[MAX_PLAYERS];
@ -67,7 +66,7 @@ static int CDECL StationNameSorter(const void *a, const void *b)
argv[0] = cmp1->index; argv[0] = cmp1->index;
GetStringWithArgs(buf1, STR_STATION, argv); GetStringWithArgs(buf1, STR_STATION, argv);
if ( cmp2->index != _last_station_idx) { if (cmp2->index != _last_station_idx) {
_last_station_idx = cmp2->index; _last_station_idx = cmp2->index;
argv[0] = cmp2->index; argv[0] = cmp2->index;
GetStringWithArgs(_bufcache, STR_STATION, argv); GetStringWithArgs(_bufcache, STR_STATION, argv);
@ -91,7 +90,7 @@ static void GlobalSortStationList(void)
error("Could not allocate memory for the station-sorting-list"); error("Could not allocate memory for the station-sorting-list");
FOR_ALL_STATIONS(st) { FOR_ALL_STATIONS(st) {
if(st->xy && st->owner != OWNER_NONE) { if (st->xy != 0 && st->owner != OWNER_NONE) {
_station_sort[n].index = st->index; _station_sort[n].index = st->index;
_station_sort[n++].owner = st->owner; _station_sort[n++].owner = st->owner;
_num_station_sort[st->owner]++; // add number of stations of player _num_station_sort[st->owner]++; // add number of stations of player
@ -101,7 +100,9 @@ static void GlobalSortStationList(void)
// create cumulative station-ownership // create cumulative station-ownership
// stations are stored as a cummulative index, eg 25, 41, 43. This means // stations are stored as a cummulative index, eg 25, 41, 43. This means
// Player0: 25; Player1: (41-25) 16; Player2: (43-41) 2 // Player0: 25; Player1: (41-25) 16; Player2: (43-41) 2
for (i = &_num_station_sort[1]; i != endof(_num_station_sort); i++) {*i += *(i-1);} for (i = &_num_station_sort[1]; i != endof(_num_station_sort); i++) {
*i += *(i - 1);
}
qsort(_station_sort, n, sizeof(_station_sort[0]), GeneralOwnerSorter); // sort by owner qsort(_station_sort, n, sizeof(_station_sort[0]), GeneralOwnerSorter); // sort by owner
@ -135,18 +136,14 @@ static void MakeSortedStationList(PlayerID owner)
static void PlayerStationsWndProc(Window *w, WindowEvent *e) static void PlayerStationsWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
const PlayerID owner = w->window_number; const PlayerID owner = w->window_number;
uint32 i; uint32 i;
// resort station window if stations have been added/removed // resort station window if stations have been added/removed
if (_global_station_sort_dirty) if (_global_station_sort_dirty) GlobalSortStationList();
GlobalSortStationList(); if (_station_sort_dirty[owner]) MakeSortedStationList(owner);
if (_station_sort_dirty[owner]) { // resort in case of a station rename.
MakeSortedStationList(owner);
}
// stations are stored as a cummulative index, eg 25, 41, 43. This means // stations are stored as a cummulative index, eg 25, 41, 43. This means
// Player0: 25; Player1: (41-25) 16; Player2: (43-41) 2 stations // Player0: 25; Player1: (41-25) 16; Player2: (43-41) 2 stations
@ -187,8 +184,9 @@ static void PlayerStationsWndProc(Window *w, WindowEvent *e)
x = DrawString(xb, y, STR_3049_0, 0) + 5; x = DrawString(xb, y, STR_3049_0, 0) + 5;
// show cargo waiting and station ratings // show cargo waiting and station ratings
for(j=0; j!=NUM_CARGO; j++) { for (j = 0; j != NUM_CARGO; j++) {
int acc = GB(st->goods[j].waiting_acceptance, 0, 12); uint acc = GB(st->goods[j].waiting_acceptance, 0, 12);
if (acc != 0) { if (acc != 0) {
StationsWndShowStationRating(x, y, j, acc, st->goods[j].rating); StationsWndShowStationRating(x, y, j, acc, st->goods[j].rating);
x += 10; x += 10;
@ -196,16 +194,16 @@ static void PlayerStationsWndProc(Window *w, WindowEvent *e)
} }
y += 10; y += 10;
i++; // next station i++; // next station
if (++p == w->vscroll.cap) { break;} // max number of stations in 1 window if (++p == w->vscroll.cap) break; // max number of stations in 1 window
} }
} }
} break; } break;
case WE_CLICK: { case WE_CLICK: {
switch(e->click.widget) { switch (e->click.widget) {
case 3: { case 3: {
uint32 id_v = (e->click.pt.y - 15) / 10; uint32 id_v = (e->click.pt.y - 15) / 10;
if (id_v >= w->vscroll.cap) { return;} // click out of bounds if (id_v >= w->vscroll.cap) return; // click out of bounds
id_v += w->vscroll.pos; id_v += w->vscroll.pos;
@ -215,7 +213,7 @@ static void PlayerStationsWndProc(Window *w, WindowEvent *e)
id_v += (owner == 0) ? 0 : _num_station_sort[owner - 1]; // first element in list id_v += (owner == 0) ? 0 : _num_station_sort[owner - 1]; // first element in list
if (id_v >= _num_station_sort[owner]) { return;} // click out of station bound if (id_v >= _num_station_sort[owner]) return; // click out of station bound
st = GetStation(_station_sort[id_v].index); st = GetStation(_station_sort[id_v].index);
@ -229,7 +227,7 @@ static void PlayerStationsWndProc(Window *w, WindowEvent *e)
case WE_4: case WE_4:
WP(w,plstations_d).refresh_counter++; WP(w,plstations_d).refresh_counter++;
if (WP(w,plstations_d).refresh_counter==5) { if (WP(w,plstations_d).refresh_counter == 5) {
WP(w,plstations_d).refresh_counter = 0; WP(w,plstations_d).refresh_counter = 0;
SetWindowDirty(w); SetWindowDirty(w);
} }
@ -320,11 +318,10 @@ static void DrawStationViewWindow(Window *w)
StringID str; StringID str;
num = 1; num = 1;
for(i=0; i!=NUM_CARGO; i++) { for (i = 0; i != NUM_CARGO; i++) {
if (GB(st->goods[i].waiting_acceptance, 0, 12) != 0) { if (GB(st->goods[i].waiting_acceptance, 0, 12) != 0) {
num++; num++;
if (st->goods[i].enroute_from != station_id) if (st->goods[i].enroute_from != station_id) num++;
num++;
} }
} }
SetVScrollCount(w, num); SetVScrollCount(w, num);
@ -347,8 +344,9 @@ static void DrawStationViewWindow(Window *w)
if (--pos < 0) { if (--pos < 0) {
str = STR_00D0_NOTHING; str = STR_00D0_NOTHING;
for(i=0; i!=NUM_CARGO; i++) for (i = 0; i != NUM_CARGO; i++) {
if (GB(st->goods[i].waiting_acceptance, 0, 12) != 0) str = STR_EMPTY; if (GB(st->goods[i].waiting_acceptance, 0, 12) != 0) str = STR_EMPTY;
}
SetDParam(0, str); SetDParam(0, str);
DrawString(x, y, STR_0008_WAITING, 0); DrawString(x, y, STR_0008_WAITING, 0);
y += 10; y += 10;
@ -357,8 +355,7 @@ static void DrawStationViewWindow(Window *w)
i = 0; i = 0;
do { do {
uint waiting = GB(st->goods[i].waiting_acceptance, 0, 12); uint waiting = GB(st->goods[i].waiting_acceptance, 0, 12);
if (waiting == 0) if (waiting == 0) continue;
continue;
num = (waiting + 5) / 10; num = (waiting + 5) / 10;
if (num != 0) { if (num != 0) {
@ -417,11 +414,10 @@ static void DrawStationViewWindow(Window *w)
DrawStringMultiLine(2, 67, STR_SPEC_USERSTRING, 245); DrawStringMultiLine(2, 67, STR_SPEC_USERSTRING, 245);
} else { } else {
DrawString(2, 67, STR_3034_LOCAL_RATING_OF_TRANSPORT, 0); DrawString(2, 67, STR_3034_LOCAL_RATING_OF_TRANSPORT, 0);
y = 77; y = 77;
for(i=0; i!=NUM_CARGO; i++) { for (i = 0; i != NUM_CARGO; i++) {
if (st->goods[i].enroute_from != INVALID_STATION) { if (st->goods[i].enroute_from != INVALID_STATION) {
SetDParam(0, _cargoc.names_s[i]); SetDParam(0, _cargoc.names_s[i]);
SetDParam(2, st->goods[i].rating * 101 >> 8); SetDParam(2, st->goods[i].rating * 101 >> 8);
@ -436,13 +432,13 @@ static void DrawStationViewWindow(Window *w)
static void StationViewWndProc(Window *w, WindowEvent *e) static void StationViewWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
DrawStationViewWindow(w); DrawStationViewWindow(w);
break; break;
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 7: case 7:
ScrollMainWindowToTile(GetStation(w->window_number)->xy); ScrollMainWindowToTile(GetStation(w->window_number)->xy);
break; break;

View File

@ -198,21 +198,21 @@ typedef unsigned char byte;
static inline uint16 TO_LE16(uint16 x) { return BSWAP16(x); } static inline uint16 TO_LE16(uint16 x) { return BSWAP16(x); }
static inline uint32 FROM_LE32(uint32 x) { return BSWAP32(x); } static inline uint32 FROM_LE32(uint32 x) { return BSWAP32(x); }
static inline uint16 FROM_LE16(uint16 x) { return BSWAP16(x); } static inline uint16 FROM_LE16(uint16 x) { return BSWAP16(x); }
# define TO_BE32(x) x # define TO_BE32(x) (x)
# define TO_BE16(x) x # define TO_BE16(x) (x)
# define FROM_BE32(x) x # define FROM_BE32(x) (x)
# define FROM_BE16(x) x # define FROM_BE16(x) (x)
# define TO_BE32X(x) x # define TO_BE32X(x) (x)
#else #else
static inline uint32 TO_BE32(uint32 x) { return BSWAP32(x); } static inline uint32 TO_BE32(uint32 x) { return BSWAP32(x); }
static inline uint16 TO_BE16(uint16 x) { return BSWAP16(x); } static inline uint16 TO_BE16(uint16 x) { return BSWAP16(x); }
static inline uint32 FROM_BE32(uint32 x) { return BSWAP32(x); } static inline uint32 FROM_BE32(uint32 x) { return BSWAP32(x); }
static inline uint16 FROM_BE16(uint16 x) { return BSWAP16(x); } static inline uint16 FROM_BE16(uint16 x) { return BSWAP16(x); }
# define TO_LE32(x) x # define TO_LE32(x) (x)
# define TO_LE16(x) x # define TO_LE16(x) (x)
# define TO_BE32X(x) BSWAP32(x) # define TO_BE32X(x) BSWAP32(x)
# define FROM_LE32(x) x # define FROM_LE32(x) (x)
# define FROM_LE16(x) x # define FROM_LE16(x) (x)
#endif /* TTD_BIG_ENDIAN */ #endif /* TTD_BIG_ENDIAN */
#if !defined(GAME_DATA_DIR) #if !defined(GAME_DATA_DIR)
@ -241,7 +241,7 @@ typedef unsigned char byte;
assert_compile(sizeof(uint32) == 4); assert_compile(sizeof(uint32) == 4);
assert_compile(sizeof(uint16) == 2); assert_compile(sizeof(uint16) == 2);
assert_compile(sizeof(uint8) == 1); assert_compile(sizeof(uint8) == 1);
#define lengthof(x) (sizeof(x)/sizeof(x[0])) #define lengthof(x) (sizeof(x)/sizeof(x[0]))
#define endof(x) (&x[lengthof(x)]) #define endof(x) (&x[lengthof(x)])

View File

@ -188,11 +188,12 @@ char *GetStringWithArgs(char *buffr, uint string, const int32 *argv)
return FormatString(buffr, _userstring, NULL, 0); return FormatString(buffr, _userstring, NULL, 0);
} }
if (index >= _langtab_num[tab]) if (index >= _langtab_num[tab]) {
error( error(
"!String 0x%X is invalid. " "!String 0x%X is invalid. "
"Probably because an old version of the .lng file.\n", string "Probably because an old version of the .lng file.\n", string
); );
}
return FormatString(buffr, GetStringPtr(GB(string, 0, 16)), argv, GB(string, 24, 8)); return FormatString(buffr, GetStringPtr(GB(string, 0, 16)), argv, GB(string, 24, 8));
} }
@ -317,7 +318,7 @@ static char *FormatYmdString(char *buff, uint16 number)
memcpy(buff, GetStringPtr(STR_0162_JAN + ymd.month), 4); memcpy(buff, GetStringPtr(STR_0162_JAN + ymd.month), 4);
buff[3] = ' '; buff[3] = ' ';
return FormatNoCommaNumber(buff+4, ymd.year + MAX_YEAR_BEGIN_REAL); return FormatNoCommaNumber(buff + 4, ymd.year + MAX_YEAR_BEGIN_REAL);
} }
static char *FormatMonthAndYear(char *buff, uint16 number) static char *FormatMonthAndYear(char *buff, uint16 number)
@ -615,8 +616,7 @@ static char *FormatString(char *buff, const char *str, const int32 *argv, uint c
byte *s = (byte*)GetStringPtr(argv_orig[(byte)*str++]); // contains the string that determines gender. byte *s = (byte*)GetStringPtr(argv_orig[(byte)*str++]); // contains the string that determines gender.
int len; int len;
int gender = 0; int gender = 0;
if (s && s[0] == 0x87) if (s != NULL && s[0] == 0x87) gender = s[1];
gender = s[1];
str = ParseStringChoice(str, gender, buff, &len); str = ParseStringChoice(str, gender, buff, &len);
buff += len; buff += len;
break; break;
@ -715,7 +715,8 @@ static char *FormatString(char *buff, const char *str, const int32 *argv, uint c
case 0x9B: { // {TOWN} case 0x9B: { // {TOWN}
const Town* t = GetTown(GetInt32(&argv)); const Town* t = GetTown(GetInt32(&argv));
int32 temp[1]; int32 temp[1];
assert(t->xy);
assert(t->xy != 0);
temp[0] = t->townnameparts; temp[0] = t->townnameparts;
buff = GetStringWithArgs(buff, t->townnametype, temp); buff = GetStringWithArgs(buff, t->townnametype, temp);
@ -728,7 +729,7 @@ static char *FormatString(char *buff, const char *str, const int32 *argv, uint c
} }
case 0x9D: { // {SETCASE} case 0x9D: { // {SETCASE}
// This is a pseudo command, it's outputted when someone does {STRING.ack} // This is a pseudo command, it's outputted when someone does {STRING.ack}
// The modifier is added to all subsequent GetStringWithArgs that accept the modifier. // The modifier is added to all subsequent GetStringWithArgs that accept the modifier.
modifier = (byte)*str++ << 24; modifier = (byte)*str++ << 24;
break; break;

View File

@ -17,14 +17,14 @@
static void HandleSubsidyClick(int y) static void HandleSubsidyClick(int y)
{ {
const Subsidy* s; const Subsidy* s;
int num,offs; uint num;
int offs;
TileIndex xy; TileIndex xy;
if (y < 0) if (y < 0) return;
return;
num = 0; num = 0;
for(s=_subsidies; s != endof(_subsidies); s++) { for (s = _subsidies; s != endof(_subsidies); s++) {
if (s->cargo_type != CT_INVALID && s->age < 12) { if (s->cargo_type != CT_INVALID && s->age < 12) {
y -= 10; y -= 10;
if (y < 0) goto handle_click; if (y < 0) goto handle_click;
@ -40,7 +40,7 @@ static void HandleSubsidyClick(int y)
y -= 11; y -= 11;
if (y < 0) return; if (y < 0) return;
for(s=_subsidies; s != endof(_subsidies); s++) { for (s = _subsidies; s != endof(_subsidies); s++) {
if (s->cargo_type != CT_INVALID && s->age >= 12) { if (s->cargo_type != CT_INVALID && s->age >= 12) {
y -= 10; y -= 10;
if (y < 0) goto handle_click; if (y < 0) goto handle_click;
@ -78,7 +78,9 @@ static void DrawSubsidiesWindow(const Window* w)
{ {
YearMonthDay ymd; YearMonthDay ymd;
const Subsidy* s; const Subsidy* s;
int x,xt,y,num,x2; uint num;
int x;
int y;
DrawWindowWidgets(w); DrawWindowWidgets(w);
@ -90,10 +92,12 @@ static void DrawSubsidiesWindow(const Window* w)
y += 10; y += 10;
num = 0; num = 0;
for(s=_subsidies; s != endof(_subsidies); s++) { for (s = _subsidies; s != endof(_subsidies); s++) {
if (s->cargo_type != CT_INVALID && s->age < 12) { if (s->cargo_type != CT_INVALID && s->age < 12) {
int x2;
SetupSubsidyDecodeParam(s, 1); SetupSubsidyDecodeParam(s, 1);
x2 = DrawString(x+2, y, STR_2027_FROM_TO, 0); x2 = DrawString(x + 2, y, STR_2027_FROM_TO, 0);
SetDParam(0, _date - ymd.day + 384 - s->age * 32); SetDParam(0, _date - ymd.day + 384 - s->age * 32);
DrawString(x2, y, STR_2028_BY, 0); DrawString(x2, y, STR_2028_BY, 0);
@ -103,17 +107,18 @@ static void DrawSubsidiesWindow(const Window* w)
} }
if (num == 0) { if (num == 0) {
DrawString(x+2, y, STR_202A_NONE, 0); DrawString(x + 2, y, STR_202A_NONE, 0);
y += 10; y += 10;
} }
DrawString(x, y+1, STR_202B_SERVICES_ALREADY_SUBSIDISED, 0); DrawString(x, y + 1, STR_202B_SERVICES_ALREADY_SUBSIDISED, 0);
y += 10; y += 10;
num = 0; num = 0;
for(s=_subsidies; s != endof(_subsidies); s++) { for (s = _subsidies; s != endof(_subsidies); s++) {
if (s->cargo_type != CT_INVALID && s->age >= 12) { if (s->cargo_type != CT_INVALID && s->age >= 12) {
const Player* p; const Player* p;
int xt;
SetupSubsidyDecodeParam(s, 1); SetupSubsidyDecodeParam(s, 1);
@ -121,7 +126,7 @@ static void DrawSubsidiesWindow(const Window* w)
SetDParam(3, p->name_1); SetDParam(3, p->name_1);
SetDParam(4, p->name_2); SetDParam(4, p->name_2);
xt = DrawString(x+2, y, STR_202C_FROM_TO, 0); xt = DrawString(x + 2, y, STR_202C_FROM_TO, 0);
SetDParam(0, _date - ymd.day + 768 - s->age * 32); SetDParam(0, _date - ymd.day + 768 - s->age * 32);
DrawString(xt, y, STR_202D_UNTIL, 0); DrawString(xt, y, STR_202D_UNTIL, 0);
@ -130,21 +135,19 @@ static void DrawSubsidiesWindow(const Window* w)
} }
} }
if (num == 0) { if (num == 0) DrawString(x + 2, y, STR_202A_NONE, 0);
DrawString(x+2, y, STR_202A_NONE, 0);
}
} }
static void SubsidiesListWndProc(Window *w, WindowEvent *e) static void SubsidiesListWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: DrawSubsidiesWindow(w); break; case WE_PAINT: DrawSubsidiesWindow(w); break;
case WE_CLICK: {
switch(e->click.widget) { case WE_CLICK:
case 2: HandleSubsidyClick(e->click.pt.y - 25); break; switch (e->click.widget) {
} case 2: HandleSubsidyClick(e->click.pt.y - 25); break;
} }
break; break;
} }
} }

View File

@ -469,7 +469,7 @@ const AircraftVehicleInfo orig_aircraft_vehicle_info[NUM_AIRCRAFT_ENGINES] = {
{ 6, 18, 240, 3, SND_09_JET, 40, 74, 30, 200 }, /* 5 */ { 6, 18, 240, 3, SND_09_JET, 40, 74, 30, 200 }, /* 5 */
{ 2, 17, 150, 1, SND_09_JET, 35, 74, 15, 100 }, /* 6 */ { 2, 17, 150, 1, SND_09_JET, 35, 74, 15, 100 }, /* 6 */
{ 2, 18, 245, 3, SND_09_JET, 40, 74, 30, 150 }, /* 7 */ { 2, 18, 245, 3, SND_09_JET, 40, 74, 30, 150 }, /* 7 */
{ 3, 19, 192, 3, SND_09_JET, 40, 74, 40, 220 }, /* 8 */ { 3, 19, 192, 3, SND_09_JET, 40, 74, 40, 220 }, /* 8 */
{ 3, 20, 190, 3, SND_09_JET, 40, 74, 25, 230 }, /* 9 */ { 3, 20, 190, 3, SND_09_JET, 40, 74, 25, 230 }, /* 9 */
{ 2, 16, 135, 3, SND_09_JET, 35, 74, 10, 95 }, /* 10 */ { 2, 16, 135, 3, SND_09_JET, 35, 74, 10, 95 }, /* 10 */
{ 2, 18, 240, 3, SND_09_JET, 40, 74, 35, 170 }, /* 11 */ { 2, 18, 240, 3, SND_09_JET, 40, 74, 35, 170 }, /* 11 */

View File

@ -51,7 +51,7 @@ enum Sprites {
SPR_CANALS_BASE = 5382, SPR_CANALS_BASE = 5382,
SPR_SLOPES_BASE = SPR_CANALS_BASE + 70, SPR_SLOPES_BASE = SPR_CANALS_BASE + 70,
SPR_AUTORAIL_BASE = SPR_SLOPES_BASE + 78, SPR_AUTORAIL_BASE = SPR_SLOPES_BASE + 78,
SPR_OPENTTD_BASE = SPR_AUTORAIL_BASE + 55, // can be lowered once autorail.grf is finalized SPR_OPENTTD_BASE = SPR_AUTORAIL_BASE + 55,
SPR_BLOT = SPR_OPENTTD_BASE + 29, // colored circle (mainly used as vehicle profit marker and for sever compatibility) SPR_BLOT = SPR_OPENTTD_BASE + 29, // colored circle (mainly used as vehicle profit marker and for sever compatibility)
@ -963,7 +963,6 @@ typedef enum CursorSprites {
SPR_CURSOR_EW_MAGLEV = 1273, SPR_CURSOR_EW_MAGLEV = 1273,
SPR_CURSOR_NWSE_MAGLEV = 1274, SPR_CURSOR_NWSE_MAGLEV = 1274,
SPR_CURSOR_RAIL_DEPOT = 1296,
SPR_CURSOR_RAIL_STATION = 1300, SPR_CURSOR_RAIL_STATION = 1300,
SPR_CURSOR_TUNNEL_RAIL = 2434, SPR_CURSOR_TUNNEL_RAIL = 2434,
@ -975,6 +974,8 @@ typedef enum CursorSprites {
SPR_CURSOR_AUTOMAGLEV = SPR_OPENTTD_BASE + 6, SPR_CURSOR_AUTOMAGLEV = SPR_OPENTTD_BASE + 6,
SPR_CURSOR_WAYPOINT = SPR_OPENTTD_BASE + 7, SPR_CURSOR_WAYPOINT = SPR_OPENTTD_BASE + 7,
SPR_CURSOR_RAIL_DEPOT = 1296,
SPR_CURSOR_MONO_DEPOT = SPR_OPENTTD_BASE + 11, SPR_CURSOR_MONO_DEPOT = SPR_OPENTTD_BASE + 11,
SPR_CURSOR_MAGLEV_DEPOT = SPR_OPENTTD_BASE + 12, SPR_CURSOR_MAGLEV_DEPOT = SPR_OPENTTD_BASE + 12,
@ -1004,15 +1005,15 @@ enum AnimCursors {
}; };
/** /**
* Bitmask setup. For the graphics system, 32 bits are used to define * Bitmask setup. For the graphics system, 32 bits are used to define
* the sprite to be displayed. This variable contains various information:<p> * the sprite to be displayed. This variable contains various information:<p>
* <ul><li> SPRITE_WIDTH is the number of bits used for the actual sprite to be displayed. * <ul><li> SPRITE_WIDTH is the number of bits used for the actual sprite to be displayed.
* This always starts at bit 0.</li> * This always starts at bit 0.</li>
* <li> TRANSPARENT_BIT is the bit number which toggles sprite transparency</li> * <li> TRANSPARENT_BIT is the bit number which toggles sprite transparency</li>
* <li> RECOLOR_BIT toggles the recoloring system</li> * <li> RECOLOR_BIT toggles the recoloring system</li>
* <li> PALETTE_SPRITE_WIDTH and PALETTE_SPRITE_START determine the position and number of * <li> PALETTE_SPRITE_WIDTH and PALETTE_SPRITE_START determine the position and number of
* bits used for the recoloring process. For transparency, it must be 0x322.</li> * bits used for the recoloring process. For transparency, it must be 0x322.</li>
*/ */
enum SpriteSetup { enum SpriteSetup {
TRANSPARENT_BIT = 31, ///< toggles transparency in the sprite TRANSPARENT_BIT = 31, ///< toggles transparency in the sprite
RECOLOR_BIT = 15, ///< toggles recoloring in the sprite RECOLOR_BIT = 15, ///< toggles recoloring in the sprite
@ -1022,13 +1023,13 @@ enum SpriteSetup {
}; };
/** /**
these masks change the colors of the palette for a sprite. * these masks change the colors of the palette for a sprite.
Apart from this bit, a sprite number is needed to define * Apart from this bit, a sprite number is needed to define
the palette used for recoloring. This palette is stored * the palette used for recoloring. This palette is stored
in the bits marked by PALETTE_SPRITE_MASK. * in the bits marked by PALETTE_SPRITE_MASK.
@note Do not modify this enum. Alter SpriteSetup instead * @note Do not modify this enum. Alter SpriteSetup instead
@see SpriteSetup * @see SpriteSetup
*/ */
enum Modifiers { enum Modifiers {
///when a sprite is to be displayed transparently, this bit needs to be set. ///when a sprite is to be displayed transparently, this bit needs to be set.
PALETTE_MODIFIER_TRANSPARENT = 1 << TRANSPARENT_BIT, PALETTE_MODIFIER_TRANSPARENT = 1 << TRANSPARENT_BIT,

View File

@ -209,24 +209,23 @@ static void TerraformToolbWndProc(Window *w, WindowEvent *e)
case WE_PAINT: case WE_PAINT:
DrawWindowWidgets(w); DrawWindowWidgets(w);
break; break;
case WE_CLICK: case WE_CLICK:
if (e->click.widget >= 4) { if (e->click.widget >= 4) _terraform_button_proc[e->click.widget - 4](w);
_terraform_button_proc[e->click.widget - 4](w);
}
break; break;
case WE_KEYPRESS: case WE_KEYPRESS: {
{ uint i;
int i;
for(i=0; i!=lengthof(_terraform_keycodes); i++) for (i = 0; i != lengthof(_terraform_keycodes); i++) {
if (e->keypress.keycode == _terraform_keycodes[i]) { if (e->keypress.keycode == _terraform_keycodes[i]) {
e->keypress.cont = false; e->keypress.cont = false;
_terraform_button_proc[i](w); _terraform_button_proc[i](w);
break; break;
} }
} }
break; break;
}
case WE_PLACE_OBJ: case WE_PLACE_OBJ:
_place_proc(e->place.tile); _place_proc(e->place.tile);

View File

@ -95,9 +95,11 @@ void CDECL AddTextMessage(uint16 color, uint8 duration, const char *message, ...
void InitTextMessage(void) void InitTextMessage(void)
{ {
int i; uint i;
for (i = 0; i < MAX_CHAT_MESSAGES; i++)
for (i = 0; i < MAX_CHAT_MESSAGES; i++) {
_text_message_list[i].message[0] = '\0'; _text_message_list[i].message[0] = '\0';
}
_textmessage_width = _textmessage_box_max_width; _textmessage_width = _textmessage_box_max_width;
} }
@ -142,10 +144,10 @@ void UndrawTextMessage(void)
// Check if a message is expired every day // Check if a message is expired every day
void TextMessageDailyLoop(void) void TextMessageDailyLoop(void)
{ {
int i; uint i;
for (i = 0; i < MAX_CHAT_MESSAGES; i++) { for (i = 0; i < MAX_CHAT_MESSAGES; i++) {
if (_text_message_list[i].message[0] == '\0') if (_text_message_list[i].message[0] == '\0') continue;
continue;
if (_date > _text_message_list[i].end_date) { if (_date > _text_message_list[i].end_date) {
/* Move the remaining messages over the current message */ /* Move the remaining messages over the current message */
@ -168,8 +170,7 @@ void DrawTextMessage(void)
int i, j; int i, j;
bool has_message; bool has_message;
if (!_textmessage_dirty) if (!_textmessage_dirty) return;
return;
// First undraw if needed // First undraw if needed
UndrawTextMessage(); UndrawTextMessage();
@ -180,13 +181,11 @@ void DrawTextMessage(void)
/* Check if we have anything to draw at all */ /* Check if we have anything to draw at all */
has_message = false; has_message = false;
for ( i = 0; i < MAX_CHAT_MESSAGES; i++) { for ( i = 0; i < MAX_CHAT_MESSAGES; i++) {
if (_text_message_list[i].message[0] == '\0') if (_text_message_list[i].message[0] == '\0') break;
break;
has_message = true; has_message = true;
} }
if (!has_message) if (!has_message) return;
return;
// Make a copy of the screen as it is before painting (for undraw) // Make a copy of the screen as it is before painting (for undraw)
memcpy_pitch( memcpy_pitch(
@ -200,8 +199,7 @@ void DrawTextMessage(void)
j = 0; j = 0;
// Paint the messages // Paint the messages
for (i = MAX_CHAT_MESSAGES - 1; i >= 0; i--) { for (i = MAX_CHAT_MESSAGES - 1; i >= 0; i--) {
if (_text_message_list[i].message[0] == '\0') if (_text_message_list[i].message[0] == '\0') continue;
continue;
j++; j++;
GfxFillRect(_textmessage_box_left, _screen.height-_textmessage_box_bottom-j*13-2, _textmessage_box_left+_textmessage_width - 1, _screen.height-_textmessage_box_bottom-j*13+10, /* black, but with some alpha */ 0x322 | USE_COLORTABLE); GfxFillRect(_textmessage_box_left, _screen.height-_textmessage_box_bottom-j*13-2, _textmessage_box_left+_textmessage_width - 1, _screen.height-_textmessage_box_bottom-j*13+10, /* black, but with some alpha */ 0x322 | USE_COLORTABLE);
@ -237,8 +235,7 @@ void AddTextEffect(StringID msg, int x, int y, uint16 duration)
return; return;
for (te = _text_effect_list; te->string_id != INVALID_STRING_ID; ) { for (te = _text_effect_list; te->string_id != INVALID_STRING_ID; ) {
if (++te == endof(_text_effect_list)) if (++te == endof(_text_effect_list)) return;
return;
} }
te->string_id = msg; te->string_id = msg;

View File

@ -120,9 +120,9 @@ static void DrawTile_Town(TileInfo *ti)
} }
/* Add a house on top of the ground? */ /* Add a house on top of the ground? */
if ((image = dcts->sprite_2) != 0) { image = dcts->sprite_2;
if (_display_opt & DO_TRANS_BUILDINGS) if (image != 0) {
MAKE_TRANSPARENT(image); if (_display_opt & DO_TRANS_BUILDINGS) MAKE_TRANSPARENT(image);
AddSortableSpriteToDraw(image, AddSortableSpriteToDraw(image,
ti->x + dcts->subtile_x, ti->x + dcts->subtile_x,
@ -132,14 +132,13 @@ static void DrawTile_Town(TileInfo *ti)
dcts->dz, dcts->dz,
z); z);
if (_display_opt & DO_TRANS_BUILDINGS) if (_display_opt & DO_TRANS_BUILDINGS) return;
return;
} }
{ {
int proc; int proc = dcts->proc - 1;
if ((proc=dcts->proc-1) >= 0 )
_town_draw_tile_procs[proc](ti); if (proc >= 0) _town_draw_tile_procs[proc](ti);
} }
} }
@ -158,11 +157,9 @@ static uint GetSlopeTileh_Town(const TileInfo *ti)
static void AnimateTile_Town(TileIndex tile) static void AnimateTile_Town(TileIndex tile)
{ {
int old; int old;
int i;
int a,b; int a,b;
if (_tick_counter & 3) if (_tick_counter & 3) return;
return;
// If the house is not one with a lift anymore, then stop this animating. // If the house is not one with a lift anymore, then stop this animating.
// Not exactly sure when this happens, but probably when a house changes. // Not exactly sure when this happens, but probably when a house changes.
@ -174,11 +171,13 @@ static void AnimateTile_Town(TileIndex tile)
} }
if (!((old = _m[tile].m1) & 0x80)) { if (!((old = _m[tile].m1) & 0x80)) {
int i;
_m[tile].m1 |= 0x80; _m[tile].m1 |= 0x80;
do { do {
i = (Random()&7) - 1; i = (Random() & 7) - 1;
} while (i < 0 || i == 1 || i*6==old); } while (i < 0 || i == 1 || i * 6 == old);
SB(_m[tile].m5, 0, 6, i); SB(_m[tile].m5, 0, 6, i);
} }
@ -204,8 +203,7 @@ static bool IsCloseToTown(TileIndex tile, uint dist)
const Town* t; const Town* t;
FOR_ALL_TOWNS(t) { FOR_ALL_TOWNS(t) {
if (t->xy != 0 && DistanceManhattan(tile, t->xy) < dist) if (t->xy != 0 && DistanceManhattan(tile, t->xy) < dist) return true;
return true;
} }
return false; return false;
} }
@ -248,9 +246,7 @@ uint32 GetWorldPopulation(void)
const Town* t; const Town* t;
pop = 0; pop = 0;
FOR_ALL_TOWNS(t) { FOR_ALL_TOWNS(t) pop += t->population;
pop += t->population;
}
return pop; return pop;
} }
@ -265,7 +261,7 @@ static void MakeSingleHouseBigger(TileIndex tile)
_m[tile].m3 = _m[tile].m3 + 0x40; _m[tile].m3 = _m[tile].m3 + 0x40;
if ( (_m[tile].m3 & 0xC0) == 0xC0) { if ((_m[tile].m3 & 0xC0) == 0xC0) {
ChangePopulation(GetTown(_m[tile].m2), _housetype_population[_m[tile].m4]); ChangePopulation(GetTown(_m[tile].m2), _housetype_population[_m[tile].m4]);
} }
MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile);
@ -294,9 +290,9 @@ static void TileLoop_Town(TileIndex tile)
house = _m[tile].m4; house = _m[tile].m4;
if (_housetype_extra_flags[house] & 0x20 && if (_housetype_extra_flags[house] & 0x20 &&
!(_m[tile].m5 & 0x80) && !(_m[tile].m5 & 0x80) &&
CHANCE16(1,2) && CHANCE16(1, 2) &&
AddAnimatedTile(tile)) { AddAnimatedTile(tile)) {
_m[tile].m5 = (_m[tile].m5 & 0x40)|0x80; _m[tile].m5 = (_m[tile].m5 & 0x40) | 0x80;
} }
t = GetTown(_m[tile].m2); t = GetTown(_m[tile].m2);
@ -323,7 +319,7 @@ static void TileLoop_Town(TileIndex tile)
t->new_act_mail += moved; t->new_act_mail += moved;
} }
if (_house_more_flags[house]&8 && (t->flags12&1) && --t->time_until_rebuild == 0) { if (_house_more_flags[house] & 8 && (t->flags12 & 1) && --t->time_until_rebuild == 0) {
t->time_until_rebuild = GB(r, 16, 6) + 130; t->time_until_rebuild = GB(r, 16, 6) + 130;
_current_player = OWNER_TOWN; _current_player = OWNER_TOWN;
@ -376,12 +372,12 @@ static int32 ClearTile_Town(TileIndex tile, byte flags)
static void GetAcceptedCargo_Town(TileIndex tile, AcceptedCargo ac) static void GetAcceptedCargo_Town(TileIndex tile, AcceptedCargo ac)
{ {
int type = _m[tile].m4; byte type = _m[tile].m4;
ac[CT_PASSENGERS] = _housetype_cargo_passengers[type]; ac[CT_PASSENGERS] = _housetype_cargo_passengers[type];
ac[CT_MAIL] = _housetype_cargo_mail[type]; ac[CT_MAIL] = _housetype_cargo_mail[type];
ac[CT_GOODS] = _housetype_cargo_goods[type]; ac[CT_GOODS] = _housetype_cargo_goods[type];
ac[CT_FOOD] = _housetype_cargo_food[type]; ac[CT_FOOD] = _housetype_cargo_food[type];
} }
static void GetTileDesc_Town(TileIndex tile, TileDesc *td) static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
@ -439,8 +435,7 @@ static void TownTickHandler(Town *t)
void OnTick_Town(void) void OnTick_Town(void)
{ {
if (_game_mode == GM_EDITOR) if (_game_mode == GM_EDITOR) return;
return;
/* Make sure each town's tickhandler invocation frequency is about the /* Make sure each town's tickhandler invocation frequency is about the
* same - TOWN_GROWTH_FREQUENCY - independent on the number of towns. */ * same - TOWN_GROWTH_FREQUENCY - independent on the number of towns. */
@ -455,21 +450,21 @@ void OnTick_Town(void)
t = GetTown(i); t = GetTown(i);
if (t->xy != 0) if (t->xy != 0) TownTickHandler(t);
TownTickHandler(t);
} }
} }
static byte GetTownRoadMask(TileIndex tile) static byte GetTownRoadMask(TileIndex tile)
{ {
byte b = GetRoadBitsByTile(tile); byte b = GetRoadBitsByTile(tile);
byte r=0; byte r = 0;
if (b&1) r|=10;
if (b&2) r|=5; if (b & 0x01) r |= 10;
if (b&4) r|=9; if (b & 0x02) r |= 5;
if (b&8) r|=6; if (b & 0x04) r |= 9;
if (b&16) r|=3; if (b & 0x08) r |= 6;
if (b&32) r|=12; if (b & 0x10) r |= 3;
if (b & 0x20) r |= 12;
return r; return r;
} }
@ -482,7 +477,7 @@ static bool IsRoadAllowedHere(TileIndex tile, int dir)
// land at the edges. This is not ok. // land at the edges. This is not ok.
TILE_ASSERT(tile); TILE_ASSERT(tile);
for(;;) { for (;;) {
// Check if there already is a road at this point? // Check if there already is a road at this point?
if (GetRoadBitsByTile(tile) == 0) { if (GetRoadBitsByTile(tile) == 0) {
// No, try to build one in the direction. // No, try to build one in the direction.
@ -513,24 +508,22 @@ no_slope:
if ((k = (dir&1)?0xC:0x9) != slope && (k^0xF) != slope) { if ((k = (dir&1)?0xC:0x9) != slope && (k^0xF) != slope) {
uint32 r = Random(); uint32 r = Random();
if (CHANCE16I(1,8, r) && !_generating_world) { if (CHANCE16I(1, 8, r) && !_generating_world) {
int32 res; int32 res;
if (CHANCE16I(1,16,r)) if (CHANCE16I(1, 16, r)) {
res = DoCommandByTile(tile, slope, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, res = DoCommandByTile(tile, slope, 0, DC_EXEC | DC_AUTO | DC_NO_WATER,
CMD_TERRAFORM_LAND); CMD_TERRAFORM_LAND);
else } else {
res = DoCommandByTile(tile, slope^0xF, 1, DC_EXEC | DC_AUTO | DC_NO_WATER, res = DoCommandByTile(tile, slope^0xF, 1, DC_EXEC | DC_AUTO | DC_NO_WATER,
CMD_TERRAFORM_LAND); CMD_TERRAFORM_LAND);
}
if (res == CMD_ERROR && CHANCE16I(1,3,r)) if (res == CMD_ERROR && CHANCE16I(1,3,r))
// We can consider building on the slope, though. // We can consider building on the slope, though.
goto no_slope; goto no_slope;
} }
return false; return false;
} }
/* Can somebody explain for what this is needed? :s */
// tile = TILE_ADD(tile, _roadblock_tileadd[dir]);
return true; return true;
} }
} }
@ -556,8 +549,7 @@ static void LevelTownLand(TileIndex tile)
// Don't terraform if land is plain or if there's a house there. // Don't terraform if land is plain or if there's a house there.
FindLandscapeHeightByTile(&ti, tile); FindLandscapeHeightByTile(&ti, tile);
if (ti.tileh == 0 || ti.type == MP_HOUSE) if (ti.tileh == 0 || ti.type == MP_HOUSE) return;
return;
// First try up, then down // First try up, then down
if (!TerraformTownTile(tile, ~ti.tileh & 0xF, 1)) { if (!TerraformTownTile(tile, ~ti.tileh & 0xF, 1)) {
@ -587,8 +579,7 @@ static void GrowTownInTile(TileIndex *tile_ptr, uint mask, int block, Town *t1)
LevelTownLand(tile); LevelTownLand(tile);
// Is a road allowed here? // Is a road allowed here?
if (!IsRoadAllowedHere(tile, block)) if (!IsRoadAllowedHere(tile, block)) return;
return;
// Randomize new road block numbers // Randomize new road block numbers
a = block; a = block;
@ -602,8 +593,7 @@ static void GrowTownInTile(TileIndex *tile_ptr, uint mask, int block, Town *t1)
if (!IsRoadAllowedHere(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a])), a)) { if (!IsRoadAllowedHere(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a])), a)) {
// A road is not allowed to continue the randomized road, // A road is not allowed to continue the randomized road,
// return if the road we're trying to build is curved. // return if the road we're trying to build is curved.
if ( a != (b^2)) if (a != (b ^ 2)) return;
return;
// Return if neither side of the new road is a house // Return if neither side of the new road is a house
if (!IsTileType(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a + 1])), MP_HOUSE) && if (!IsTileType(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a + 1])), MP_HOUSE) &&
@ -619,7 +609,7 @@ static void GrowTownInTile(TileIndex *tile_ptr, uint mask, int block, Town *t1)
// Continue building on a partial road. // Continue building on a partial road.
// Always OK. // Always OK.
_grow_town_result = 0; _grow_town_result = 0;
rcmd = 1 << (block^2); rcmd = 1 << (block ^ 2);
} else { } else {
// Reached a tunnel? Then continue at the other side of it. // Reached a tunnel? Then continue at the other side of it.
@ -630,25 +620,22 @@ static void GrowTownInTile(TileIndex *tile_ptr, uint mask, int block, Town *t1)
} }
// For any other kind of tunnel/bridge, bail out. // For any other kind of tunnel/bridge, bail out.
if (IsTileType(tile, MP_TUNNELBRIDGE)) if (IsTileType(tile, MP_TUNNELBRIDGE)) return;
return;
// Possibly extend the road in a direction. // Possibly extend the road in a direction.
// Randomize a direction and if it has a road, bail out. // Randomize a direction and if it has a road, bail out.
i = GB(Random(), 0, 2); i = GB(Random(), 0, 2);
if (HASBIT(mask, i)) if (HASBIT(mask, i)) return;
return;
// This is the tile we will reach if we extend to this direction. // This is the tile we will reach if we extend to this direction.
tmptile = TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[i])); tmptile = TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[i]));
// Don't do it if it reaches to water. // Don't do it if it reaches to water.
if (IS_WATER_TILE(tmptile)) if (IS_WATER_TILE(tmptile)) return;
return;
// Build a house at the edge. 60% chance or // Build a house at the edge. 60% chance or
// always ok if no road allowed. // always ok if no road allowed.
if (!IsRoadAllowedHere(tmptile, i) || CHANCE16(6,10)) { if (!IsRoadAllowedHere(tmptile, i) || CHANCE16(6, 10)) {
// But not if there already is a house there. // But not if there already is a house there.
if (!IsTileType(tmptile, MP_HOUSE)) { if (!IsTileType(tmptile, MP_HOUSE)) {
// Level the land if possible // Level the land if possible
@ -656,8 +643,7 @@ static void GrowTownInTile(TileIndex *tile_ptr, uint mask, int block, Town *t1)
// And build a house. // And build a house.
// Set result to -1 if we managed to build it. // Set result to -1 if we managed to build it.
if (BuildTownHouse(t1, tmptile)) if (BuildTownHouse(t1, tmptile)) _grow_town_result = -1;
_grow_town_result = -1;
} }
return; return;
} }
@ -669,8 +655,7 @@ static void GrowTownInTile(TileIndex *tile_ptr, uint mask, int block, Town *t1)
FindLandscapeHeightByTile(&ti, tile); FindLandscapeHeightByTile(&ti, tile);
// Return if a water tile // Return if a water tile
if (ti.type == MP_WATER && ti.map5==0) if (ti.type == MP_WATER && ti.map5 == 0) return;
return;
// Determine direction of slope, // Determine direction of slope,
// and build a road if not a special slope. // and build a road if not a special slope.
@ -823,7 +808,7 @@ bool GrowTown(Town *t)
FindLandscapeHeightByTile(&ti, tile); FindLandscapeHeightByTile(&ti, tile);
// Only work with plain land that not already has a house with map5=0 // Only work with plain land that not already has a house with map5=0
if (ti.tileh == 0 && !(ti.type==MP_HOUSE && ti.map5==0)) { if (ti.tileh == 0 && (ti.type != MP_HOUSE || ti.map5 != 0)) {
if (DoCommandByTile(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR) != CMD_ERROR) { if (DoCommandByTile(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR) != CMD_ERROR) {
DoCommandByTile(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD); DoCommandByTile(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
_current_player = old_player; _current_player = old_player;
@ -906,8 +891,7 @@ restart:
GetString(buf1, townnametype); GetString(buf1, townnametype);
// Check size and width // Check size and width
if (strlen(buf1) >= 31 || GetStringWidth(buf1) > 130) if (strlen(buf1) >= 31 || GetStringWidth(buf1) > 130) continue;
continue;
FOR_ALL_TOWNS(t2) { FOR_ALL_TOWNS(t2) {
if (t2->xy != 0) { if (t2->xy != 0) {
@ -916,8 +900,7 @@ restart:
SetDParam(0, t2->index); SetDParam(0, t2->index);
GetString(buf2, STR_TOWN); GetString(buf2, STR_TOWN);
if (strcmp(buf1, buf2) == 0) { if (strcmp(buf1, buf2) == 0) {
if (tries-- < 0) if (tries-- < 0) return false;
return false;
goto restart; goto restart;
} }
} }
@ -1583,8 +1566,7 @@ static bool DoBuildStatueOfCompany(TileIndex tile)
int32 r; int32 r;
FindLandscapeHeightByTile(&ti, tile); FindLandscapeHeightByTile(&ti, tile);
if (ti.tileh != 0) if (ti.tileh != 0) return false;
return false;
if (ti.type != MP_HOUSE && ti.type != MP_CLEAR && ti.type != MP_TREES) if (ti.type != MP_HOUSE && ti.type != MP_CLEAR && ti.type != MP_TREES)
return false; return false;
@ -1634,8 +1616,7 @@ static void TownActionBuildStatue(Town *t, int action)
SETBIT(t->statues, _current_player); SETBIT(t->statues, _current_player);
for (p = _statue_tiles; p != endof(_statue_tiles); ++p) { for (p = _statue_tiles; p != endof(_statue_tiles); ++p) {
if (DoBuildStatueOfCompany(tile)) if (DoBuildStatueOfCompany(tile)) return;
return;
tile = TILE_ADD(tile, ToTileIndexDiff(*p)); tile = TILE_ADD(tile, ToTileIndexDiff(*p));
} }
} }
@ -1873,8 +1854,11 @@ void ChangeTownRating(Town *t, int add, int max)
int rating; int rating;
// if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff // if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff
if (t == NULL || _current_player >= MAX_PLAYERS || (_cheats.magic_bulldozer.value && add < 0) ) if (t == NULL ||
_current_player >= MAX_PLAYERS ||
(_cheats.magic_bulldozer.value && add < 0)) {
return; return;
}
SETBIT(t->have_ratings, _current_player); SETBIT(t->have_ratings, _current_player);

View File

@ -45,7 +45,8 @@ uint GetMaskOfTownActions(int *nump, PlayerID pid, const Town *t)
uint buttons = 0; uint buttons = 0;
if (pid != OWNER_SPECTATOR) { if (pid != OWNER_SPECTATOR) {
int i; uint i;
// bribe option enabled? // bribe option enabled?
if (_patches.bribe) { if (_patches.bribe) {
// if unwanted, disable everything. // if unwanted, disable everything.
@ -81,11 +82,12 @@ uint GetMaskOfTownActions(int *nump, PlayerID pid, const Town *t)
static int GetNthSetBit(uint32 bits, int n) static int GetNthSetBit(uint32 bits, int n)
{ {
int i = 0; int i = 0;
if (n >= 0) { if (n >= 0) {
do { do {
if (bits&1 && --n < 0) return i; if (bits & 1 && --n < 0) return i;
i++; i++;
} while (bits>>=1); } while (bits >>= 1);
} }
return -1; return -1;
} }
@ -119,7 +121,7 @@ static void TownAuthorityWndProc(Window *w, WindowEvent *e)
// Draw list of players // Draw list of players
y = 25; y = 25;
FOR_ALL_PLAYERS(p) { FOR_ALL_PLAYERS(p) {
if (p->is_active && (HASBIT(t->have_ratings, p->index) || t->exclusivity==p->index)) { if (p->is_active && (HASBIT(t->have_ratings, p->index) || t->exclusivity == p->index)) {
DrawPlayerIcon(p->index, 2, y); DrawPlayerIcon(p->index, 2, y);
SetDParam(0, p->name_1); SetDParam(0, p->name_1);
@ -138,10 +140,10 @@ static void TownAuthorityWndProc(Window *w, WindowEvent *e)
SetDParam(4, str); SetDParam(4, str);
if (t->exclusivity == p->index) // red icon for player with exclusive rights if (t->exclusivity == p->index) // red icon for player with exclusive rights
DrawSprite((SPR_BLOT) | PALETTE_TO_RED, 18, y); DrawSprite(SPR_BLOT | PALETTE_TO_RED, 18, y);
DrawString(28, y, STR_2024, 0); DrawString(28, y, STR_2024, 0);
y+=10; y += 10;
} }
} }
} }
@ -153,11 +155,10 @@ static void TownAuthorityWndProc(Window *w, WindowEvent *e)
if (--pos < 0) { if (--pos < 0) {
DrawString(2, y, STR_2045_ACTIONS_AVAILABLE, 0); DrawString(2, y, STR_2045_ACTIONS_AVAILABLE, 0);
y+=10; y += 10;
} }
for(i=0; buttons; i++,buttons>>=1) { for (i = 0; buttons; i++, buttons >>= 1) {
if (pos <= -5) if (pos <= -5) break;
break;
if (buttons&1 && --pos < 0) { if (buttons&1 && --pos < 0) {
DrawString(3, y, STR_2046_SMALL_ADVERTISING_CAMPAIGN + i, 6); DrawString(3, y, STR_2046_SMALL_ADVERTISING_CAMPAIGN + i, 6);
@ -167,8 +168,9 @@ static void TownAuthorityWndProc(Window *w, WindowEvent *e)
} }
{ {
int i; int i = WP(w,def_d).data_1;
if ((i=WP(w,def_d).data_1) != -1) {
if (i != -1) {
SetDParam(1, (_price.build_industry >> 8) * _town_action_costs[i]); SetDParam(1, (_price.build_industry >> 8) * _town_action_costs[i]);
SetDParam(0, STR_2046_SMALL_ADVERTISING_CAMPAIGN + i); SetDParam(0, STR_2046_SMALL_ADVERTISING_CAMPAIGN + i);
DrawStringMultiLine(2, 159, STR_204D_INITIATE_A_SMALL_LOCAL + i, 313); DrawStringMultiLine(2, 159, STR_204D_INITIATE_A_SMALL_LOCAL + i, 313);
@ -182,8 +184,8 @@ static void TownAuthorityWndProc(Window *w, WindowEvent *e)
case 3: { /* listbox */ case 3: { /* listbox */
const Town *t = GetTown(w->window_number); const Town *t = GetTown(w->window_number);
int y = (e->click.pt.y - 0x6B) / 10; int y = (e->click.pt.y - 0x6B) / 10;
if (!IS_INT_INSIDE(y, 0, 5))
return; if (!IS_INT_INSIDE(y, 0, 5)) return;
y = GetNthSetBit(GetMaskOfTownActions(NULL, _local_player, t), y + w->vscroll.pos - 1); y = GetNthSetBit(GetMaskOfTownActions(NULL, _local_player, t), y + w->vscroll.pos - 1);
if (y >= 0) { if (y >= 0) {
@ -216,10 +218,9 @@ static const WindowDesc _town_authority_desc = {
static void ShowTownAuthorityWindow(uint town) static void ShowTownAuthorityWindow(uint town)
{ {
Window *w; Window* w = AllocateWindowDescFront(&_town_authority_desc, town);
w = AllocateWindowDescFront(&_town_authority_desc, town); if (w != NULL) {
if (w) {
w->vscroll.cap = 5; w->vscroll.cap = 5;
WP(w,def_d).data_1 = -1; WP(w,def_d).data_1 = -1;
} }
@ -229,7 +230,7 @@ static void TownViewWndProc(Window *w, WindowEvent *e)
{ {
Town *t = GetTown(w->window_number); Town *t = GetTown(w->window_number);
switch(e->event) { switch (e->event) {
case WE_PAINT: case WE_PAINT:
// disable renaming town in network games if you are not the server // disable renaming town in network games if you are not the server
if (_networking && !_network_server) SETBIT(w->disabled_state, 8); if (_networking && !_network_server) SETBIT(w->disabled_state, 8);
@ -239,37 +240,41 @@ static void TownViewWndProc(Window *w, WindowEvent *e)
SetDParam(0, t->population); SetDParam(0, t->population);
SetDParam(1, t->num_houses); SetDParam(1, t->num_houses);
DrawString(2,107,STR_2006_POPULATION,0); DrawString(2, 107, STR_2006_POPULATION, 0);
SetDParam(0, t->act_pass); SetDParam(0, t->act_pass);
SetDParam(1, t->max_pass); SetDParam(1, t->max_pass);
DrawString(2,117,STR_200D_PASSENGERS_LAST_MONTH_MAX,0); DrawString(2, 117, STR_200D_PASSENGERS_LAST_MONTH_MAX, 0);
SetDParam(0, t->act_mail); SetDParam(0, t->act_mail);
SetDParam(1, t->max_mail); SetDParam(1, t->max_mail);
DrawString(2,127,STR_200E_MAIL_LAST_MONTH_MAX,0); DrawString(2, 127, STR_200E_MAIL_LAST_MONTH_MAX, 0);
DrawWindowViewport(w); DrawWindowViewport(w);
break; break;
case WE_CLICK: case WE_CLICK:
switch(e->click.widget) { switch (e->click.widget) {
case 6: /* scroll to location */ case 6: /* scroll to location */
ScrollMainWindowToTile(t->xy); ScrollMainWindowToTile(t->xy);
break; break;
case 7: /* town authority */
ShowTownAuthorityWindow(w->window_number); case 7: /* town authority */
break; ShowTownAuthorityWindow(w->window_number);
case 8: /* rename */ break;
SetDParam(0, w->window_number);
ShowQueryString(STR_TOWN, STR_2007_RENAME_TOWN, 31, 130, w->window_class, w->window_number); case 8: /* rename */
break; SetDParam(0, w->window_number);
case 9: /* expand town */ ShowQueryString(STR_TOWN, STR_2007_RENAME_TOWN, 31, 130, w->window_class, w->window_number);
ExpandTown(t); break;
break;
case 10: /* delete town */ case 9: /* expand town */
DeleteTown(t); ExpandTown(t);
break; break;
case 10: /* delete town */
DeleteTown(t);
break;
} }
break; break;
@ -331,7 +336,6 @@ static const WindowDesc _town_view_scen_desc = {
void ShowTownViewWindow(uint town) void ShowTownViewWindow(uint town)
{ {
Window *w; Window *w;
Town *t;
if (_game_mode != GM_EDITOR) { if (_game_mode != GM_EDITOR) {
w = AllocateWindowDescFront(&_town_view_desc, town); w = AllocateWindowDescFront(&_town_view_desc, town);
@ -339,10 +343,9 @@ void ShowTownViewWindow(uint town)
w = AllocateWindowDescFront(&_town_view_scen_desc, town); w = AllocateWindowDescFront(&_town_view_scen_desc, town);
} }
if (w) { if (w != NULL) {
w->flags4 |= WF_DISABLE_VP_SCROLL; w->flags4 |= WF_DISABLE_VP_SCROLL;
t = GetTown(w->window_number); AssignWindowViewport(w, 3, 17, 0xFE, 0x56, GetTown(town)->xy, 1);
AssignWindowViewport(w, 3, 17, 0xFE, 0x56, t->xy, 1);
} }
} }
@ -403,16 +406,16 @@ static int CDECL TownPopSorter(const void *a, const void *b)
static void MakeSortedTownList(void) static void MakeSortedTownList(void)
{ {
const Town* t; const Town* t;
int n = 0; uint n = 0;
/* Create array for sorting */ /* Create array for sorting */
_town_sort = realloc(_town_sort, GetTownPoolSize() * sizeof(_town_sort[0])); _town_sort = realloc(_town_sort, GetTownPoolSize() * sizeof(_town_sort[0]));
if (_town_sort == NULL) if (_town_sort == NULL)
error("Could not allocate memory for the town-sorting-list"); error("Could not allocate memory for the town-sorting-list");
FOR_ALL_TOWNS(t) FOR_ALL_TOWNS(t) {
if (t->xy) if (t->xy != 0) _town_sort[n++] = t->index;
_town_sort[n++] = t->index; }
_num_town_sort = n; _num_town_sort = n;
@ -425,9 +428,8 @@ static void MakeSortedTownList(void)
static void TownDirectoryWndProc(Window *w, WindowEvent *e) static void TownDirectoryWndProc(Window *w, WindowEvent *e)
{ {
switch(e->event) { switch (e->event) {
case WE_PAINT: { case WE_PAINT: {
if (_town_sort_dirty) { if (_town_sort_dirty) {
_town_sort_dirty = false; _town_sort_dirty = false;
MakeSortedTownList(); MakeSortedTownList();
@ -516,10 +518,9 @@ static const WindowDesc _town_directory_desc = {
void ShowTownDirectory(void) void ShowTownDirectory(void)
{ {
Window *w; Window* w = AllocateWindowDescFront(&_town_directory_desc, 0);
w = AllocateWindowDescFront(&_town_directory_desc, 0); if (w != NULL) {
if (w) {
w->vscroll.cap = 16; w->vscroll.cap = 16;
w->resize.step_height = 10; w->resize.step_height = 10;
w->resize.height = w->height - 10 * 6; // minimum of 10 items in the list, each item 10 high w->resize.height = w->height - 10 * 6; // minimum of 10 items in the list, each item 10 high

View File

@ -38,7 +38,8 @@ static const byte _state_dir_table[4] = { 0x20, 8, 0x10, 4 };
* the consist changes. * the consist changes.
* @param v First vehicle of the consist. * @param v First vehicle of the consist.
*/ */
void TrainCargoChanged(Vehicle *v) { void TrainCargoChanged(Vehicle* v)
{
Vehicle *u; Vehicle *u;
uint16 weight = 0; uint16 weight = 0;
@ -75,7 +76,8 @@ void TrainCargoChanged(Vehicle *v) {
* Note: this needs to be called too for 'wagon chains' (in the depot, without an engine) * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
* @param v First vehicle of the chain. * @param v First vehicle of the chain.
*/ */
void TrainConsistChanged(Vehicle *v) { void TrainConsistChanged(Vehicle* v)
{
const RailVehicleInfo *rvi_v; const RailVehicleInfo *rvi_v;
Vehicle *u; Vehicle *u;
uint16 max_speed = 0xFFFF; uint16 max_speed = 0xFFFF;
@ -383,8 +385,7 @@ int GetTrainImage(const Vehicle *v, byte direction)
base = _engine_sprite_base[img] + ((direction + _engine_sprite_add[img]) & _engine_sprite_and[img]); base = _engine_sprite_base[img] + ((direction + _engine_sprite_add[img]) & _engine_sprite_and[img]);
if (v->cargo_count >= (v->cargo_cap >> 1)) if (v->cargo_count >= v->cargo_cap / 2) base += _wagon_full_adder[img];
base += _wagon_full_adder[img];
return base; return base;
} }
@ -431,13 +432,11 @@ static uint CountArticulatedParts(const RailVehicleInfo *rvi, EngineID engine_ty
uint16 callback; uint16 callback;
uint i; uint i;
if (!HASBIT(rvi->callbackmask, CBM_ARTIC_ENGINE)) if (!HASBIT(rvi->callbackmask, CBM_ARTIC_ENGINE)) return 0;
return 0;
for (i = 1; i < 10; i++) { for (i = 1; i < 10; i++) {
callback = GetCallBackResult(CBID_ARTIC_ENGINE + (i << 8), engine_type, NULL); callback = GetCallBackResult(CBID_ARTIC_ENGINE + (i << 8), engine_type, NULL);
if (callback == CALLBACK_FAILED || callback == 0xFF) if (callback == CALLBACK_FAILED || callback == 0xFF) break;
break;
} }
return i - 1; return i - 1;
@ -502,10 +501,7 @@ static void AddArticulatedParts(const RailVehicleInfo *rvi, Vehicle **vl)
static int32 CmdBuildRailWagon(EngineID engine, TileIndex tile, uint32 flags) static int32 CmdBuildRailWagon(EngineID engine, TileIndex tile, uint32 flags)
{ {
int32 value; int32 value;
Vehicle *v;
const RailVehicleInfo *rvi; const RailVehicleInfo *rvi;
const Engine *e;
int x,y;
uint num_vehicles; uint num_vehicles;
SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES); SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES);
@ -517,17 +513,19 @@ static int32 CmdBuildRailWagon(EngineID engine, TileIndex tile, uint32 flags)
if (!(flags & DC_QUERY_COST)) { if (!(flags & DC_QUERY_COST)) {
Vehicle *vl[11]; // Allow for wagon and upto 10 artic parts. Vehicle *vl[11]; // Allow for wagon and upto 10 artic parts.
Vehicle* v;
int x;
int y;
if (!AllocateVehicles(vl, num_vehicles)) if (!AllocateVehicles(vl, num_vehicles))
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME); return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
byte img = rvi->image_index;
Vehicle *u, *w; Vehicle *u, *w;
uint dir; uint dir;
v = vl[0]; v = vl[0];
v->spritenum = img; v->spritenum = rvi->image_index;
u = NULL; u = NULL;
@ -568,8 +566,7 @@ static int32 CmdBuildRailWagon(EngineID engine, TileIndex tile, uint32 flags)
v->value = value; v->value = value;
// v->day_counter = 0; // v->day_counter = 0;
e = GetEngine(engine); v->u.rail.railtype = GetEngine(engine)->railtype;
v->u.rail.railtype = e->railtype;
v->build_year = _cur_year; v->build_year = _cur_year;
v->type = VEH_Train; v->type = VEH_Train;
@ -861,8 +858,8 @@ static Vehicle *FindGoodVehiclePos(const Vehicle *src)
/** Move a rail vehicle around inside the depot. /** Move a rail vehicle around inside the depot.
* @param x,y unused * @param x,y unused
* @param p1 various bitstuffed elements * @param p1 various bitstuffed elements
* - p1 (bit 0 - 15) source vehicle index (p1 & 0xFFFF) * - p1 (bit 0 - 15) source vehicle index
* - p1 (bit 16 - 31) what wagon to put the source wagon AFTER (p1 & 0xFFFF0000) XXX - 0xFFFF0000 to make a new line * - p1 (bit 16 - 31) what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
* @param p2 (bit 0) move all vehicles following the source vehicle * @param p2 (bit 0) move all vehicles following the source vehicle
*/ */
int32 CmdMoveRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2) int32 CmdMoveRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
@ -898,7 +895,7 @@ int32 CmdMoveRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
if (src == dst) return 0; if (src == dst) return 0;
/* the player must be the owner */ /* the player must be the owner */
if (!CheckOwnership(src->owner) || (dst!=NULL && !CheckOwnership(dst->owner))) if (!CheckOwnership(src->owner) || (dst != NULL && !CheckOwnership(dst->owner)))
return CMD_ERROR; return CMD_ERROR;
/* locate the head of the two chains */ /* locate the head of the two chains */
@ -1293,7 +1290,8 @@ static void UpdateVarsAfterSwap(Vehicle *v)
EndVehicleMove(v); EndVehicleMove(v);
} }
static void SetLastSpeed(Vehicle *v, int spd) { static void SetLastSpeed(Vehicle* v, int spd)
{
int old = v->u.rail.last_speed; int old = v->u.rail.last_speed;
if (spd != old) { if (spd != old) {
v->u.rail.last_speed = spd; v->u.rail.last_speed = spd;
@ -1377,24 +1375,18 @@ static void ReverseTrainSwapVeh(Vehicle *v, int l, int r)
/* Check if the vehicle is a train and is on the tile we are testing */ /* Check if the vehicle is a train and is on the tile we are testing */
static void *TestTrainOnCrossing(Vehicle *v, void *data) static void *TestTrainOnCrossing(Vehicle *v, void *data)
{ {
if (v->tile != *(const TileIndex*)data || v->type != VEH_Train) if (v->tile != *(const TileIndex*)data || v->type != VEH_Train) return NULL;
return NULL;
return v; return v;
} }
static void DisableTrainCrossing(TileIndex tile) static void DisableTrainCrossing(TileIndex tile)
{ {
/* Test if we have a rail/road-crossing */ if (IsTileType(tile, MP_STREET) &&
if (IsTileType(tile, MP_STREET) && IsLevelCrossing(tile)) { IsLevelCrossing(tile) &&
/* Check if there is a train on the tile itself */ VehicleFromPos(tile, &tile, TestTrainOnCrossing) == NULL && // empty?
if (VehicleFromPos(tile, &tile, TestTrainOnCrossing) == NULL) { GB(_m[tile].m5, 2, 1) != 0) { // Lights on?
/* If light is on, switch light off */ SB(_m[tile].m5, 2, 1, 0); // Switch lights off
if (GB(_m[tile].m5, 2, 1) != 0) { MarkTileDirtyByTile(tile);
SB(_m[tile].m5, 2, 1, 0);
MarkTileDirtyByTile(tile);
}
}
} }
} }
@ -1406,34 +1398,35 @@ static void DisableTrainCrossing(TileIndex tile)
*/ */
static void AdvanceWagons(Vehicle *v, bool before) static void AdvanceWagons(Vehicle *v, bool before)
{ {
Vehicle *base, *first, *last, *tempnext; Vehicle* base;
int i, length; Vehicle* first;
int differential; int length;
base = v; base = v;
first = base->next; first = base->next;
length = CountVehiclesInChain(v); length = CountVehiclesInChain(v);
while (length > 2) { while (length > 2) {
Vehicle* last;
int differential;
int i;
// find pairwise matching wagon // find pairwise matching wagon
// start<>end, start+1<>end-1, ... */ // start<>end, start+1<>end-1, ... */
last = first; last = first;
for (i = length - 3; i; i--) { for (i = length - 3; i > 0; i--) last = last->next;
last = last->next;
}
differential = last->u.rail.cached_veh_length - base->u.rail.cached_veh_length; differential = last->u.rail.cached_veh_length - base->u.rail.cached_veh_length;
if (before) if (before) differential *= -1;
differential *= -1;
if (differential > 0) { if (differential > 0) {
Vehicle* tempnext;
// disconnect last car to make sure only this subset moves // disconnect last car to make sure only this subset moves
tempnext = last->next; tempnext = last->next;
last->next = NULL; last->next = NULL;
for (i = 0; i < differential; i++) { for (i = 0; i < differential; i++) TrainController(first);
TrainController(first);
}
last->next = tempnext; last->next = tempnext;
} }
@ -1450,15 +1443,13 @@ static TileIndex GetVehicleTileOutOfTunnel(const Vehicle* v, bool reverse)
byte direction = (!reverse) ? DirToDiagdir(v->direction) : ReverseDiagdir(v->direction >> 1); byte direction = (!reverse) ? DirToDiagdir(v->direction) : ReverseDiagdir(v->direction >> 1);
TileIndexDiff delta = TileOffsByDir(direction); TileIndexDiff delta = TileOffsByDir(direction);
if (v->u.rail.track != 0x40) if (v->u.rail.track != 0x40) return v->tile;
return v->tile;
for (tile = v->tile;; tile += delta) { for (tile = v->tile;; tile += delta) {
if (IsTunnelTile(tile) && GB(_m[tile].m5, 0, 2) != direction && GetTileZ(tile) == v->z_pos) if (IsTunnelTile(tile) && GB(_m[tile].m5, 0, 2) != direction && GetTileZ(tile) == v->z_pos)
break; break;
} }
return tile; return tile;
} }
static void ReverseTrainDirection(Vehicle *v) static void ReverseTrainDirection(Vehicle *v)
@ -1491,7 +1482,7 @@ static void ReverseTrainDirection(Vehicle *v)
return; return;
} }
// we found a way out of the pbs block // we found a way out of the pbs block
if (NPFGetFlag(&ftd.node, NPF_FLAG_PBS_EXIT)) { if (NPFGetFlag(&ftd.node, NPF_FLAG_PBS_EXIT)) {
if (NPFGetFlag(&ftd.node, NPF_FLAG_PBS_BLOCKED)) { if (NPFGetFlag(&ftd.node, NPF_FLAG_PBS_BLOCKED)) {
CLRBIT(v->u.rail.flags, VRF_REVERSING); CLRBIT(v->u.rail.flags, VRF_REVERSING);
@ -1610,8 +1601,7 @@ int32 CmdForceTrainProceed(int x, int y, uint32 flags, uint32 p1, uint32 p2)
if (v->type != VEH_Train || !CheckOwnership(v->owner)) return CMD_ERROR; if (v->type != VEH_Train || !CheckOwnership(v->owner)) return CMD_ERROR;
if (flags & DC_EXEC) if (flags & DC_EXEC) v->u.rail.force_proceed = 0x50;
v->u.rail.force_proceed = 0x50;
return 0; return 0;
} }
@ -1676,8 +1666,7 @@ int32 CmdRefitRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
}; };
if (amount != 0) { if (amount != 0) {
if (new_cid != v->cargo_type) if (new_cid != v->cargo_type) cost += _price.build_railvehicle >> 8;
cost += (_price.build_railvehicle >> 8);
num += amount; num += amount;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
v->cargo_count = 0; v->cargo_count = 0;
@ -1700,8 +1689,8 @@ typedef struct TrainFindDepotData {
TileIndex tile; TileIndex tile;
PlayerID owner; PlayerID owner;
/** /**
* true if reversing is necesarry for the train to get to this depot This * true if reversing is necessary for the train to get to this depot
* value is unused when new depot finding and NPF are both disabled * This value is unused when new depot finding and NPF are both disabled
*/ */
bool reverse; bool reverse;
} TrainFindDepotData; } TrainFindDepotData;
@ -1763,13 +1752,13 @@ static TrainFindDepotData FindClosestTrainDepot(Vehicle *v)
} else { } else {
// search in the forward direction first. // search in the forward direction first.
i = v->direction >> 1; i = v->direction >> 1;
if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[i]) { i = (i - 1) & 3; } if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[i]) i = (i - 1) & 3;
NewTrainPathfind(tile, 0, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd); NewTrainPathfind(tile, 0, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd);
if (tfdd.best_length == (uint)-1){ if (tfdd.best_length == (uint)-1){
tfdd.reverse = true; tfdd.reverse = true;
// search in backwards direction // search in backwards direction
i = (v->direction^4) >> 1; i = (v->direction^4) >> 1;
if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[i]) { i = (i - 1) & 3; } if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[i]) i = (i - 1) & 3;
NewTrainPathfind(tile, 0, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd); NewTrainPathfind(tile, 0, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd);
} }
} }
@ -1880,8 +1869,10 @@ static void HandleLocomotiveSmokeCloud(const Vehicle* v)
if ((RailVehInfo(engtype)->flags & RVI_WAGON && effect_type == 0) || if ((RailVehInfo(engtype)->flags & RVI_WAGON && effect_type == 0) ||
disable_effect || disable_effect ||
GetEngine(engtype)->railtype > RAILTYPE_RAIL || GetEngine(engtype)->railtype > RAILTYPE_RAIL ||
(v->vehstatus & VS_HIDDEN) || (v->u.rail.track & 0xC0)) v->vehstatus & VS_HIDDEN ||
v->u.rail.track & 0xC0) {
continue; continue;
}
// No smoke in depots or tunnels // No smoke in depots or tunnels
if (IsTileDepotType(v->tile, TRANSPORT_RAIL) || IsTunnelTile(v->tile)) if (IsTileDepotType(v->tile, TRANSPORT_RAIL) || IsTunnelTile(v->tile))
@ -1952,9 +1943,9 @@ static bool CheckTrainStayInDepot(Vehicle *v)
Vehicle *u; Vehicle *u;
// bail out if not all wagons are in the same depot or not in a depot at all // bail out if not all wagons are in the same depot or not in a depot at all
for (u = v; u != NULL; u = u->next) for (u = v; u != NULL; u = u->next) {
if (u->u.rail.track != 0x80 || u->tile != v->tile) if (u->u.rail.track != 0x80 || u->tile != v->tile) return false;
return false; }
if (v->u.rail.force_proceed == 0) { if (v->u.rail.force_proceed == 0) {
Trackdir trackdir = GetVehicleTrackdir(v); Trackdir trackdir = GetVehicleTrackdir(v);
@ -1970,8 +1961,7 @@ static bool CheckTrainStayInDepot(Vehicle *v)
NPFFindStationOrTileData fstd; NPFFindStationOrTileData fstd;
NPFFoundTargetData ftd; NPFFoundTargetData ftd;
if (PBSTileUnavail(v->tile) & (1 << trackdir)) if (PBSTileUnavail(v->tile) & (1 << trackdir)) return true;
return true;
NPFFillWithOrderData(&fstd, v); NPFFillWithOrderData(&fstd, v);
@ -1980,9 +1970,9 @@ static bool CheckTrainStayInDepot(Vehicle *v)
// we found a way out of the pbs block // we found a way out of the pbs block
if (NPFGetFlag(&ftd.node, NPF_FLAG_PBS_EXIT)) { if (NPFGetFlag(&ftd.node, NPF_FLAG_PBS_EXIT)) {
if (NPFGetFlag(&ftd.node, NPF_FLAG_PBS_BLOCKED) || NPFGetFlag(&ftd.node, NPF_FLAG_PBS_RED)) if (NPFGetFlag(&ftd.node, NPF_FLAG_PBS_BLOCKED) || NPFGetFlag(&ftd.node, NPF_FLAG_PBS_RED)) {
return true; return true;
else { } else {
v->u.rail.pbs_end_tile = ftd.node.tile; v->u.rail.pbs_end_tile = ftd.node.tile;
v->u.rail.pbs_end_trackdir = ftd.node.direction; v->u.rail.pbs_end_trackdir = ftd.node.direction;
goto green; goto green;
@ -1990,7 +1980,6 @@ static bool CheckTrainStayInDepot(Vehicle *v)
} }
} }
if (UpdateSignalsOnSegment(v->tile, v->direction)) { if (UpdateSignalsOnSegment(v->tile, v->direction)) {
InvalidateWindowClasses(WC_TRAINS_LIST); InvalidateWindowClasses(WC_TRAINS_LIST);
return true; return true;
@ -2002,8 +1991,7 @@ green:
TrainPlayLeaveStationSound(v); TrainPlayLeaveStationSound(v);
v->u.rail.track = 1; v->u.rail.track = 1;
if (v->direction & 2) if (v->direction & 2) v->u.rail.track = 2;
v->u.rail.track = 2;
v->vehstatus &= ~VS_HIDDEN; v->vehstatus &= ~VS_HIDDEN;
v->cur_speed = 0; v->cur_speed = 0;
@ -2057,12 +2045,12 @@ static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, in
static void FillWithStationData(TrainTrackFollowerData* fd, const Vehicle* v) static void FillWithStationData(TrainTrackFollowerData* fd, const Vehicle* v)
{ {
fd->dest_coords = v->dest_tile; fd->dest_coords = v->dest_tile;
if (v->current_order.type == OT_GOTO_STATION) if (v->current_order.type == OT_GOTO_STATION) {
fd->station_index = v->current_order.station; fd->station_index = v->current_order.station;
else } else {
fd->station_index = INVALID_STATION; fd->station_index = INVALID_STATION;
}
} }
static const byte _initial_tile_subcoord[6][4][3] = { static const byte _initial_tile_subcoord[6][4][3] = {
@ -2095,10 +2083,10 @@ static const byte _pick_track_table[6] = {1, 3, 2, 2, 0, 0};
#if !defined(_MSC_VER) #if !defined(_MSC_VER)
unsigned int _rdtsc() unsigned int _rdtsc()
{ {
unsigned int high, low; unsigned int high, low;
__asm__ __volatile__ ("rdtsc" : "=a" (low), "=d" (high)); __asm__ __volatile__ ("rdtsc" : "=a" (low), "=d" (high));
return low; return low;
} }
#else #else
#ifndef _M_AMD64 #ifndef _M_AMD64
@ -2332,8 +2320,7 @@ static bool ProcessTrainOrder(Vehicle *v)
} }
// Get the current order // Get the current order
if (v->cur_order_index >= v->num_orders) if (v->cur_order_index >= v->num_orders) v->cur_order_index = 0;
v->cur_order_index = 0;
order = GetVehicleOrder(v, v->cur_order_index); order = GetVehicleOrder(v, v->cur_order_index);
@ -2407,27 +2394,22 @@ static void MarkTrainDirty(Vehicle *v)
do { do {
v->cur_image = GetTrainImage(v, v->direction); v->cur_image = GetTrainImage(v, v->direction);
MarkAllViewportsDirty(v->left_coord, v->top_coord, v->right_coord + 1, v->bottom_coord + 1); MarkAllViewportsDirty(v->left_coord, v->top_coord, v->right_coord + 1, v->bottom_coord + 1);
} while ( (v=v->next) != NULL); } while ((v = v->next) != NULL);
} }
static void HandleTrainLoading(Vehicle *v, bool mode) static void HandleTrainLoading(Vehicle *v, bool mode)
{ {
if (v->current_order.type == OT_NOTHING) if (v->current_order.type == OT_NOTHING) return;
return;
if (v->current_order.type != OT_DUMMY) { if (v->current_order.type != OT_DUMMY) {
if (v->current_order.type != OT_LOADING) if (v->current_order.type != OT_LOADING) return;
return; if (mode) return;
if (mode)
return;
// don't mark the train as lost if we're loading on the final station. // don't mark the train as lost if we're loading on the final station.
if (v->current_order.flags & OF_NON_STOP) if (v->current_order.flags & OF_NON_STOP)
v->u.rail.days_since_order_progr = 0; v->u.rail.days_since_order_progr = 0;
if (--v->load_unload_time_rem) if (--v->load_unload_time_rem) return;
return;
if (v->current_order.flags & OF_FULL_LOAD && CanFillVehicle(v)) { if (v->current_order.flags & OF_FULL_LOAD && CanFillVehicle(v)) {
v->u.rail.days_since_order_progr = 0; /* Prevent a train lost message for full loading trains */ v->u.rail.days_since_order_progr = 0; /* Prevent a train lost message for full loading trains */
@ -2451,8 +2433,7 @@ static void HandleTrainLoading(Vehicle *v, bool mode)
v->current_order.flags = 0; v->current_order.flags = 0;
// If this was not the final order, don't remove it from the list. // If this was not the final order, don't remove it from the list.
if (!(b.flags & OF_NON_STOP)) if (!(b.flags & OF_NON_STOP)) return;
return;
} }
} }
@ -2467,15 +2448,17 @@ static int UpdateTrainSpeed(Vehicle *v)
uint accel; uint accel;
if (v->vehstatus & VS_STOPPED || HASBIT(v->u.rail.flags, VRF_REVERSING)) { if (v->vehstatus & VS_STOPPED || HASBIT(v->u.rail.flags, VRF_REVERSING)) {
if (_patches.realistic_acceleration) if (_patches.realistic_acceleration) {
accel = GetTrainAcceleration(v, AM_BRAKE) * 2; accel = GetTrainAcceleration(v, AM_BRAKE) * 2;
else } else {
accel = v->acceleration * -2; accel = v->acceleration * -2;
}
} else { } else {
if (_patches.realistic_acceleration) if (_patches.realistic_acceleration) {
accel = GetTrainAcceleration(v, AM_ACCEL); accel = GetTrainAcceleration(v, AM_ACCEL);
else } else {
accel = v->acceleration; accel = v->acceleration;
}
} }
spd = v->subspeed + accel * 2; spd = v->subspeed + accel * 2;
@ -2682,8 +2665,7 @@ static void AffectSpeedByDirChange(Vehicle *v, byte new_dir)
static void AffectSpeedByZChange(Vehicle *v, byte old_z) static void AffectSpeedByZChange(Vehicle *v, byte old_z)
{ {
const RailtypeSlowdownParams *rsp; const RailtypeSlowdownParams *rsp;
if (old_z == v->z_pos || _patches.realistic_acceleration) if (old_z == v->z_pos || _patches.realistic_acceleration) return;
return;
rsp = &_railtype_slowdown[v->u.rail.railtype]; rsp = &_railtype_slowdown[v->u.rail.railtype];
@ -2691,8 +2673,7 @@ static void AffectSpeedByZChange(Vehicle *v, byte old_z)
v->cur_speed -= (v->cur_speed * rsp->z_up >> 8); v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
} else { } else {
uint16 spd = v->cur_speed + rsp->z_down; uint16 spd = v->cur_speed + rsp->z_down;
if (spd <= v->max_speed) if (spd <= v->max_speed) v->cur_speed = spd;
v->cur_speed = spd;
} }
} }
@ -2703,9 +2684,8 @@ static const byte _otherside_signal_directions[14] = {
static void TrainMovedChangeSignals(TileIndex tile, int dir) static void TrainMovedChangeSignals(TileIndex tile, int dir)
{ {
int i;
if (IsTileType(tile, MP_RAILWAY) && (_m[tile].m5 & 0xC0) == 0x40) { if (IsTileType(tile, MP_RAILWAY) && (_m[tile].m5 & 0xC0) == 0x40) {
i = FindFirstBit2x64((_m[tile].m5+(_m[tile].m5<<8)) & _reachable_tracks[dir]); uint i = FindFirstBit2x64((_m[tile].m5 + (_m[tile].m5 << 8)) & _reachable_tracks[dir]);
UpdateSignalsOnSegment(tile, _otherside_signal_directions[i]); UpdateSignalsOnSegment(tile, _otherside_signal_directions[i]);
} }
} }
@ -2770,11 +2750,10 @@ static void CheckTrainCollision(Vehicle *v)
TrainCollideChecker tcc; TrainCollideChecker tcc;
Vehicle *coll; Vehicle *coll;
Vehicle *realcoll; Vehicle *realcoll;
int num; uint num;
/* can't collide in depot */ /* can't collide in depot */
if (v->u.rail.track == 0x80) if (v->u.rail.track == 0x80) return;
return;
assert(v->u.rail.track == 0x40 || TileVirtXY(v->x_pos, v->y_pos) == v->tile); assert(v->u.rail.track == 0x40 || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
@ -2783,9 +2762,7 @@ static void CheckTrainCollision(Vehicle *v)
/* find colliding vehicle */ /* find colliding vehicle */
realcoll = VehicleFromPos(TileVirtXY(v->x_pos, v->y_pos), &tcc, FindTrainCollideEnum); realcoll = VehicleFromPos(TileVirtXY(v->x_pos, v->y_pos), &tcc, FindTrainCollideEnum);
if (realcoll == NULL) if (realcoll == NULL) return;
return;
coll = GetFirstVehicleInChain(realcoll); coll = GetFirstVehicleInChain(realcoll);
@ -2801,12 +2778,9 @@ static void CheckTrainCollision(Vehicle *v)
num += 2 + CountPassengersInTrain(coll); num += 2 + CountPassengersInTrain(coll);
SetVehicleCrashed(v); SetVehicleCrashed(v);
if (coll->subtype == TS_Front_Engine) if (coll->subtype == TS_Front_Engine) SetVehicleCrashed(coll);
SetVehicleCrashed(coll);
SetDParam(0, num); SetDParam(0, num);
AddNewsItem(STR_8868_TRAIN_CRASH_DIE_IN_FIREBALL, AddNewsItem(STR_8868_TRAIN_CRASH_DIE_IN_FIREBALL,
NEWS_FLAGS(NM_THIN, NF_VIEWPORT | NF_VEHICLE, NT_ACCIDENT, 0), NEWS_FLAGS(NM_THIN, NF_VIEWPORT | NF_VEHICLE, NT_ACCIDENT, 0),
v->index, v->index,
@ -3052,9 +3026,7 @@ green_light:
invalid_rail: invalid_rail:
/* We've reached end of line?? */ /* We've reached end of line?? */
if (prev != NULL) { if (prev != NULL) error("!Disconnecting train");
error("!Disconnecting train");
}
goto reverse_train_direction; goto reverse_train_direction;
red_light: { red_light: {
@ -3091,7 +3063,6 @@ reverse_train_direction:
v->cur_speed = 0; v->cur_speed = 0;
v->subspeed = 0; v->subspeed = 0;
ReverseTrainDirection(v); ReverseTrainDirection(v);
} }
extern TileIndex CheckTunnelBusy(TileIndex tile, uint *length); extern TileIndex CheckTunnelBusy(TileIndex tile, uint *length);
@ -3188,7 +3159,7 @@ static void HandleCrashedTrain(Vehicle *v)
uint32 r; uint32 r;
Vehicle *u; Vehicle *u;
if ( (state == 4) && (v->u.rail.track != 0x40) ) { if (state == 4 && v->u.rail.track != 0x40) {
CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE); CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
} }
@ -3272,13 +3243,8 @@ static bool TrainCheckIfLineEnds(Vehicle *v)
v->vehstatus &= ~VS_TRAIN_SLOWING; v->vehstatus &= ~VS_TRAIN_SLOWING;
} }
// exit if inside a tunnel if (v->u.rail.track & 0x40) return true; // exit if inside a tunnel
if (v->u.rail.track & 0x40) if (v->u.rail.track & 0x80) return true; // exit if inside a depot
return true;
// exit if inside a depot
if (v->u.rail.track & 0x80)
return true;
tile = v->tile; tile = v->tile;
@ -3312,7 +3278,7 @@ static bool TrainCheckIfLineEnds(Vehicle *v)
x = v->x_pos & 0xF; x = v->x_pos & 0xF;
y = v->y_pos & 0xF; y = v->y_pos & 0xF;
switch(v->direction) { switch (v->direction) {
case 0: case 0:
x = (~x) + (~y) + 24; x = (~x) + (~y) + 24;
break; break;
@ -3494,8 +3460,7 @@ void TrainEnterDepot(Vehicle *v, TileIndex tile)
{ {
SetSignalsOnBothDir(tile, _depot_track_ind[GB(_m[tile].m5, 0, 2)]); SetSignalsOnBothDir(tile, _depot_track_ind[GB(_m[tile].m5, 0, 2)]);
if (v->subtype != TS_Front_Engine) if (v->subtype != TS_Front_Engine) v = GetFirstVehicleInChain(v);
v = GetFirstVehicleInChain(v);
VehicleServiceInDepot(v); VehicleServiceInDepot(v);
@ -3539,23 +3504,12 @@ static void CheckIfTrainNeedsService(Vehicle *v)
const Depot* depot; const Depot* depot;
TrainFindDepotData tfdd; TrainFindDepotData tfdd;
if (PBSTileReserved(v->tile) & v->u.rail.track) if (PBSTileReserved(v->tile) & v->u.rail.track) return;
return; if (v->u.rail.pbs_status == PBS_STAT_HAS_PATH) return;
if (_patches.servint_trains == 0) return;
if (v->u.rail.pbs_status == PBS_STAT_HAS_PATH) if (!VehicleNeedsService(v)) return;
return; if (v->vehstatus & VS_STOPPED) return;
if (_patches.gotodepot && VehicleHasDepotOrders(v)) return;
if (_patches.servint_trains == 0)
return;
if (!VehicleNeedsService(v))
return;
if (v->vehstatus & VS_STOPPED)
return;
if (_patches.gotodepot && VehicleHasDepotOrders(v))
return;
// Don't interfere with a depot visit scheduled by the user, or a // Don't interfere with a depot visit scheduled by the user, or a
// depot visit by the order list. // depot visit by the order list.
@ -3632,8 +3586,9 @@ void OnNewDay_Train(Vehicle *v)
/* update destination */ /* update destination */
if (v->current_order.type == OT_GOTO_STATION && if (v->current_order.type == OT_GOTO_STATION &&
(tile = GetStation(v->current_order.station)->train_tile) != 0) (tile = GetStation(v->current_order.station)->train_tile) != 0) {
v->dest_tile = tile; v->dest_tile = tile;
}
if ((v->vehstatus & VS_STOPPED) == 0) { if ((v->vehstatus & VS_STOPPED) == 0) {
/* running costs */ /* running costs */

View File

@ -150,8 +150,7 @@ void CcBuildLoco(bool success, TileIndex tile, uint32 p1, uint32 p2)
{ {
const Vehicle* v; const Vehicle* v;
if (!success) if (!success) return;
return;
v = GetVehicle(_new_train_id); v = GetVehicle(_new_train_id);
if (tile == _backup_orders_tile) { if (tile == _backup_orders_tile) {
@ -163,11 +162,7 @@ void CcBuildLoco(bool success, TileIndex tile, uint32 p1, uint32 p2)
void CcCloneTrain(bool success, uint tile, uint32 p1, uint32 p2) void CcCloneTrain(bool success, uint tile, uint32 p1, uint32 p2)
{ {
if (success) { if (success) ShowTrainViewWindow(GetVehicle(_new_train_id));
const Vehicle* v = GetVehicle(_new_train_id);
ShowTrainViewWindow(v);
}
} }
static void engine_drawing_loop(int *x, int *y, int *pos, int *sel, static void engine_drawing_loop(int *x, int *y, int *pos, int *sel,

View File

@ -306,8 +306,7 @@ static void DrawTile_Trees(TileInfo *ti)
i = (ti->map5 >> 6) + 1; i = (ti->map5 >> 6) + 1;
do { do {
uint32 image = s[0] + (--i == 0 ? GB(ti->map5, 0, 3) : 3); uint32 image = s[0] + (--i == 0 ? GB(ti->map5, 0, 3) : 3);
if (_display_opt & DO_TRANS_BUILDINGS) if (_display_opt & DO_TRANS_BUILDINGS) MAKE_TRANSPARENT(image);
MAKE_TRANSPARENT(image);
te[i].image = image; te[i].image = image;
te[i].x = d[0]; te[i].x = d[0];
te[i].y = d[1]; te[i].y = d[1];

View File

@ -58,10 +58,12 @@ const Bridge orig_bridge[] = {
// basically the cost delta is 1,1, 1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5,5, 6,6,6,6,6,6, 7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8, // basically the cost delta is 1,1, 1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5,5, 6,6,6,6,6,6, 7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,
int CalcBridgeLenCostFactor(int x) int CalcBridgeLenCostFactor(int x)
{ {
int n,r; int n;
int r;
if (x < 2) return x; if (x < 2) return x;
x -= 2; x -= 2;
for(n=0,r=2;;n++) { for (n = 0, r = 2;; n++) {
if (x <= n) return r + x * n; if (x <= n) return r + x * n;
r += n * n; r += n * n;
x -= n; x -= n;
@ -115,79 +117,68 @@ static inline int GetBridgeType(TileIndex tile)
*/ */
static uint32 CheckBridgeSlope(uint direction, uint tileh, bool is_start_tile) static uint32 CheckBridgeSlope(uint direction, uint tileh, bool is_start_tile)
{ {
if (!IsSteepTileh(tileh)) { // disable building on very steep slopes if (IsSteepTileh(tileh)) return CMD_ERROR;
if (is_start_tile) { if (is_start_tile) {
/* check slope at start tile /* check slope at start tile
- no extra cost - no extra cost
- direction X: tiles 0,12 - direction X: tiles 0, 12
- direction Y: tiles 0, 9 - direction Y: tiles 0, 9
*/ */
if ((direction?0x201:0x1001) & (1 << tileh)) if ((direction ? 0x201 : 0x1001) & (1 << tileh)) return 0;
return 0;
// disallow certain start tiles to avoid certain crooked bridges // disallow certain start tiles to avoid certain crooked bridges
if (tileh == 2) if (tileh == 2) return CMD_ERROR;
return CMD_ERROR; } else {
/* check slope at end tile
- no extra cost
- direction X: tiles 0, 3
- direction Y: tiles 0, 6
*/
if ((direction? 0x41 : 0x9) & (1 << tileh)) return 0;
} // disallow certain end tiles to avoid certain crooked bridges
else { if (tileh == 8) return CMD_ERROR;
/* check slope at end tile
- no extra cost
- direction X: tiles 0, 3
- direction Y: tiles 0, 6
*/
if ((direction?0x41:0x9) & (1 << tileh))
return 0;
// disallow certain end tiles to avoid certain crooked bridges
if (tileh == 8)
return CMD_ERROR;
}
/* disallow common start/end tiles to avoid certain crooked bridges e.g.
* start-tile: X 2,1 Y 2,4 (2 was disabled before)
* end-tile: X 8,4 Y 8,1 (8 was disabled before)
*/
if ( (tileh == 1 && (is_start_tile != (bool)direction)) ||
(tileh == 4 && (is_start_tile == (bool)direction)) )
return CMD_ERROR;
// slope foundations
if (BRIDGE_FULL_LEVELED_FOUNDATION & (1 << tileh) || BRIDGE_PARTLY_LEVELED_FOUNDATION & (1 << tileh))
return _price.terraform;
} }
/* disallow common start/end tiles to avoid certain crooked bridges e.g.
* start-tile: X 2,1 Y 2,4 (2 was disabled before)
* end-tile: X 8,4 Y 8,1 (8 was disabled before)
*/
if ((tileh == 1 && is_start_tile != (bool)direction) ||
(tileh == 4 && is_start_tile == (bool)direction)) {
return CMD_ERROR;
}
// slope foundations
if (BRIDGE_FULL_LEVELED_FOUNDATION & (1 << tileh) || BRIDGE_PARTLY_LEVELED_FOUNDATION & (1 << tileh))
return _price.terraform;
return CMD_ERROR; return CMD_ERROR;
} }
uint32 GetBridgeLength(TileIndex begin, TileIndex end) uint32 GetBridgeLength(TileIndex begin, TileIndex end)
{ {
int x1, y1, x2, y2; // coordinates of starting and end tiles int x1 = TileX(begin);
x1 = TileX(begin); int y1 = TileY(begin);
y1 = TileY(begin); int x2 = TileX(end);
x2 = TileX(end); int y2 = TileY(end);
y2 = TileY(end);
return abs((x2 + y2 - x1 - y1)) - 1; return abs(x2 + y2 - x1 - y1) - 1;
} }
bool CheckBridge_Stuff(byte bridge_type, int bridge_len) bool CheckBridge_Stuff(byte bridge_type, uint bridge_len)
{ {
int max; // max possible length of a bridge (with patch 100)
const Bridge *b = &_bridge[bridge_type]; const Bridge *b = &_bridge[bridge_type];
uint max; // max possible length of a bridge (with patch 100)
if (bridge_type >= MAX_BRIDGES) return false; if (bridge_type >= MAX_BRIDGES) return false;
if (b->avail_year > _cur_year) return false; if (b->avail_year > _cur_year) return false;
max = b->max_length; max = b->max_length;
if (max >= 16 && _patches.longbridges) if (max >= 16 && _patches.longbridges) max = 100;
max = 100;
if (bridge_len < b->min_length || bridge_len > max) return false; return b->min_length <= bridge_len && bridge_len <= max;
return true;
} }
/** Build a Bridge /** Build a Bridge
@ -203,9 +194,10 @@ int32 CmdBuildBridge(int x, int y, uint32 flags, uint32 p1, uint32 p2)
byte rail_or_road, railtype, m5; byte rail_or_road, railtype, m5;
int sx,sy; int sx,sy;
TileInfo ti_start, ti_end, ti; /* OPT: only 2 of those are ever used */ TileInfo ti_start, ti_end, ti; /* OPT: only 2 of those are ever used */
int bridge_len, odd_middle_part; uint bridge_len;
uint odd_middle_part;
uint direction; uint direction;
int i; uint i;
int32 cost, terraformcost, ret; int32 cost, terraformcost, ret;
bool allow_on_slopes; bool allow_on_slopes;
@ -233,8 +225,7 @@ int32 CmdBuildBridge(int x, int y, uint32 flags, uint32 p1, uint32 p2)
/* check if valid, and make sure that (x,y) are smaller than (sx,sy) */ /* check if valid, and make sure that (x,y) are smaller than (sx,sy) */
if (x == sx) { if (x == sx) {
if (y == sy) if (y == sy) return_cmd_error(STR_5008_CANNOT_START_AND_END_ON);
return_cmd_error(STR_5008_CANNOT_START_AND_END_ON);
direction = 1; direction = 1;
if (y > sy) { if (y > sy) {
intswap(y,sy); intswap(y,sy);
@ -245,8 +236,9 @@ int32 CmdBuildBridge(int x, int y, uint32 flags, uint32 p1, uint32 p2)
intswap(y,sy); intswap(y,sy);
intswap(x,sx); intswap(x,sx);
} }
} else } else {
return_cmd_error(STR_500A_START_AND_END_MUST_BE_IN); return_cmd_error(STR_500A_START_AND_END_MUST_BE_IN);
}
/* set and test bridge length, availability */ /* set and test bridge length, availability */
bridge_len = ((sx + sy - x - y) >> 4) - 1; bridge_len = ((sx + sy - x - y) >> 4) - 1;
@ -292,8 +284,8 @@ int32 CmdBuildBridge(int x, int y, uint32 flags, uint32 p1, uint32 p2)
/* Try and clear the end landscape */ /* Try and clear the end landscape */
if (CmdFailed(ret = DoCommandByTile(ti_end.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR))) ret = DoCommandByTile(ti_end.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
return CMD_ERROR; if (CmdFailed(ret)) return CMD_ERROR;
cost += ret; cost += ret;
// false - end tile slope check // false - end tile slope check
@ -330,18 +322,17 @@ int32 CmdBuildBridge(int x, int y, uint32 flags, uint32 p1, uint32 p2)
for (i = 0; i != bridge_len; i++) { for (i = 0; i != bridge_len; i++) {
if (direction != 0) { if (direction != 0) {
y += 16; y += 16;
} else } else {
x += 16; x += 16;
}
FindLandscapeHeight(&ti, x, y); FindLandscapeHeight(&ti, x, y);
_error_message = STR_5009_LEVEL_LAND_OR_WATER_REQUIRED; _error_message = STR_5009_LEVEL_LAND_OR_WATER_REQUIRED;
if (ti.tileh != 0 && ti.z >= ti_start.z) if (ti.tileh != 0 && ti.z >= ti_start.z) return CMD_ERROR;
return CMD_ERROR;
// Find ship below // Find ship below
if ( ti.type == MP_WATER && !EnsureNoVehicle(ti.tile) ) if (ti.type == MP_WATER && !EnsureNoVehicle(ti.tile)) {
{
_error_message = STR_980E_SHIP_IN_THE_WAY; _error_message = STR_980E_SHIP_IN_THE_WAY;
return CMD_ERROR; return CMD_ERROR;
} }
@ -366,8 +357,8 @@ int32 CmdBuildBridge(int x, int y, uint32 flags, uint32 p1, uint32 p2)
} else { } else {
not_valid_below:; not_valid_below:;
/* try and clear the middle landscape */ /* try and clear the middle landscape */
if (CmdFailed(ret = DoCommandByTile(ti.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR))) ret = DoCommandByTile(ti.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
return CMD_ERROR; if (CmdFailed(ret)) return CMD_ERROR;
cost += ret; cost += ret;
m5 = 0xC0; m5 = 0xC0;
} }
@ -385,21 +376,21 @@ not_valid_below:;
// bridge len 5: 0 2 5 3 1 // bridge len 5: 0 2 5 3 1
// bridge len 6: 0 2 3 2 3 1 // bridge len 6: 0 2 3 2 3 1
// bridge len 7: 0 2 3 4 2 3 1 // bridge len 7: 0 2 3 4 2 3 1
// #0 - alwats as first, #1 - always as last (if len>1) // #0 - always as first, #1 - always as last (if len>1)
// #2,#3 are to pair in order // #2,#3 are to pair in order
// for odd bridges: #5 is going in the bridge middle if on even position, #4 on odd (counting from 0) // for odd bridges: #5 is going in the bridge middle if on even position, #4 on odd (counting from 0)
if(i==0) //first tile if (i == 0) { // first tile
m5 = 0; m5 = 0;
else if (i==bridge_len-1) //last tile } else if (i == bridge_len - 1) { // last tile
m5 = 1; m5 = 1;
else if(i==odd_middle_part) //we are on the middle of odd bridge: #5 on even pos, #4 on odd } else if (i == odd_middle_part) { // we are on the middle of odd bridge: #5 on even pos, #4 on odd
m5 = 5 - (i%2); m5 = 5 - (i % 2);
else { } else {
// generate #2 and #3 in turns [i%2==0], after the middle of odd bridge // generate #2 and #3 in turns [i%2==0], after the middle of odd bridge
// this sequence swaps [... XOR (i>odd_middle_part)], // this sequence swaps [... XOR (i>odd_middle_part)],
// for even bridges XOR does not apply as odd_middle_part==bridge_len // for even bridges XOR does not apply as odd_middle_part==bridge_len
m5 = 2 + ((i%2==0)^(i>odd_middle_part)); m5 = 2 + ((i % 2 == 0) ^ (i > odd_middle_part));
} }
_m[ti.tile].m2 = (bridge_type << 4) | m5; _m[ti.tile].m2 = (bridge_type << 4) | m5;
@ -409,7 +400,7 @@ not_valid_below:;
} }
} }
SetSignalsOnBothDir(ti_start.tile, (direction&1) ? 1 : 0); SetSignalsOnBothDir(ti_start.tile, (direction & 1) ? 1 : 0);
/* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST) /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
It's unnecessary to execute this command every time for every bridge. So it is done only It's unnecessary to execute this command every time for every bridge. So it is done only
@ -496,7 +487,7 @@ static int32 DoBuildTunnel(int x, int y, int x2, int y2, uint32 flags, uint exc_
z = ti.z; z = ti.z;
if (exc_tile != 3) { if (exc_tile != 3) {
if ( (direction ? 9U : 12U) != ti.tileh) if ((direction ? 9U : 12U) != ti.tileh)
return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION); return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
ret = DoCommandByTile(ti.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); ret = DoCommandByTile(ti.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return CMD_ERROR; if (CmdFailed(ret)) return CMD_ERROR;
@ -504,11 +495,10 @@ static int32 DoBuildTunnel(int x, int y, int x2, int y2, uint32 flags, uint exc_
} }
cost += _price.build_tunnel; cost += _price.build_tunnel;
for(;;) { for (;;) {
if (direction) y2-=16; else x2-=16; if (direction) y2-=16; else x2-=16;
if (x2 == x && y2 == y) if (x2 == x && y2 == y) break;
break;
FindLandscapeHeight(&ti, x2, y2); FindLandscapeHeight(&ti, x2, y2);
if (ti.z <= z) return CMD_ERROR; if (ti.z <= z) return CMD_ERROR;
@ -519,15 +509,14 @@ static int32 DoBuildTunnel(int x, int y, int x2, int y2, uint32 flags, uint exc_
cost += _price.build_tunnel; cost += _price.build_tunnel;
cost += (cost >> 3); cost += (cost >> 3);
if (cost >= 400000000) if (cost >= 400000000) cost = 400000000;
cost = 400000000;
} }
FindLandscapeHeight(&ti, x2, y2); FindLandscapeHeight(&ti, x2, y2);
if (ti.z != z) return CMD_ERROR; if (ti.z != z) return CMD_ERROR;
if (exc_tile != 1) { if (exc_tile != 1) {
if ( (direction ? 6U : 3U) != ti.tileh) if ((direction ? 6U : 3U) != ti.tileh)
return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION); return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
ret = DoCommandByTile(ti.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); ret = DoCommandByTile(ti.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
@ -559,7 +548,7 @@ static int32 DoBuildTunnel(int x, int y, int x2, int y2, uint32 flags, uint exc_
/** Build Tunnel. /** Build Tunnel.
* @param x,y start tile coord of tunnel * @param x,y start tile coord of tunnel
* @param p1 railtype, 0x200 for road tunnel * @param p1 railtype, 0x200 for road tunnel
* @param p2 unused (XXX - ptr to uint that recieves end tile; wtf?????) * @param p2 unused
*/ */
int32 CmdBuildTunnel(int x, int y, uint32 flags, uint32 p1, uint32 p2) int32 CmdBuildTunnel(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{ {
@ -585,11 +574,12 @@ int32 CmdBuildTunnel(int x, int y, uint32 flags, uint32 p1, uint32 p2)
if (!EnsureNoVehicle(tiorg.tile)) if (!EnsureNoVehicle(tiorg.tile))
return CMD_ERROR; return CMD_ERROR;
if (!(direction=0, tiorg.tileh==12) && if (!(direction=0, tiorg.tileh == 12) &&
!(direction++, tiorg.tileh==6) && !(direction++, tiorg.tileh == 6) &&
!(direction++, tiorg.tileh==3) && !(direction++, tiorg.tileh == 3) &&
!(direction++, tiorg.tileh==9) ) !(direction++, tiorg.tileh == 9)) {
return_cmd_error(STR_500B_SITE_UNSUITABLE_FOR_TUNNEL); return_cmd_error(STR_500B_SITE_UNSUITABLE_FOR_TUNNEL);
}
z = tiorg.z; z = tiorg.z;
do { do {
@ -600,8 +590,7 @@ int32 CmdBuildTunnel(int x, int y, uint32 flags, uint32 p1, uint32 p2)
_build_tunnel_endtile = ti.tile; _build_tunnel_endtile = ti.tile;
if (!EnsureNoVehicle(ti.tile)) if (!EnsureNoVehicle(ti.tile)) return CMD_ERROR;
return CMD_ERROR;
if (ti.tileh != _build_tunnel_tileh[direction]) { if (ti.tileh != _build_tunnel_tileh[direction]) {
if (CmdFailed(DoCommandByTile(ti.tile, ti.tileh & ~_build_tunnel_tileh[direction], 0, flags, CMD_TERRAFORM_LAND))) if (CmdFailed(DoCommandByTile(ti.tile, ti.tileh & ~_build_tunnel_tileh[direction], 0, flags, CMD_TERRAFORM_LAND)))
@ -684,7 +673,7 @@ static int32 DoClearTunnel(TileIndex tile, uint32 flags)
if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR)
ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM); ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM);
} }
return _price.clear_tunnel * (length + 1); return _price.clear_tunnel * (length + 1);
} }
static TileIndex FindEdgesOfBridge(TileIndex tile, TileIndex *endtile) static TileIndex FindEdgesOfBridge(TileIndex tile, TileIndex *endtile)
@ -746,8 +735,7 @@ static int32 DoClearBridge(TileIndex tile, uint32 flags)
int32 cost; int32 cost;
// check for vehicles under bridge // check for vehicles under bridge
if (!EnsureNoVehicleZ(tile, TilePixelHeight(tile))) if (!EnsureNoVehicleZ(tile, TilePixelHeight(tile))) return CMD_ERROR;
return CMD_ERROR;
cost = _price.clear_water; cost = _price.clear_water;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
_m[tile].m5 = _m[tile].m5 & ~0x38; _m[tile].m5 = _m[tile].m5 & ~0x38;
@ -765,8 +753,7 @@ static int32 DoClearBridge(TileIndex tile, uint32 flags)
return CMD_ERROR; return CMD_ERROR;
} }
if (!EnsureNoVehicle(tile) || !EnsureNoVehicle(endtile)) if (!EnsureNoVehicle(tile) || !EnsureNoVehicle(endtile)) return CMD_ERROR;
return CMD_ERROR;
/* Make sure there's no vehicle on the bridge /* Make sure there's no vehicle on the bridge
Omit tile and endtile, since these are already checked, thus solving the problem Omit tile and endtile, since these are already checked, thus solving the problem
@ -775,7 +762,8 @@ static int32 DoClearBridge(TileIndex tile, uint32 flags)
tile += direction ? TileDiffXY(0, 1) : TileDiffXY(1, 0); tile += direction ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
endtile -= direction ? TileDiffXY(0, 1) : TileDiffXY(1, 0); endtile -= direction ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
/* Bridges on slopes might have their Z-value offset..correct this */ /* Bridges on slopes might have their Z-value offset..correct this */
if ((v = FindVehicleBetween(tile, endtile, TilePixelHeight(tile) + 8 + GetCorrectTileHeight(tile))) != NULL) { v = FindVehicleBetween(tile, endtile, TilePixelHeight(tile) + 8 + GetCorrectTileHeight(tile));
if (v != NULL) {
VehicleInTheWayErrMsg(v); VehicleInTheWayErrMsg(v);
return CMD_ERROR; return CMD_ERROR;
} }
@ -811,7 +799,7 @@ static int32 DoClearBridge(TileIndex tile, uint32 flags)
if (m5 & 0x40) { if (m5 & 0x40) {
if (m5 & 0x20) { if (m5 & 0x20) {
static const uint16 _new_data_table[] = {0x1002, 0x1001, 0x2005, 0x200A, 0, 0, 0, 0}; static const uint16 _new_data_table[] = {0x1002, 0x1001, 0x2005, 0x200A, 0, 0, 0, 0};
new_data = _new_data_table[((m5 & 0x18) >> 2) | (m5&1)]; new_data = _new_data_table[((m5 & 0x18) >> 2) | (m5 & 1)];
} else { } else {
if (GB(m5, 3, 2) == 0) goto clear_it; if (GB(m5, 3, 2) == 0) goto clear_it;
new_data = (GetTileSlope(c, NULL) == 0) ? 0x6000 : 0x6001; new_data = (GetTileSlope(c, NULL) == 0) ? 0x6000 : 0x6001;
@ -846,13 +834,11 @@ static int32 ClearTile_TunnelBridge(TileIndex tile, byte flags)
byte m5 = _m[tile].m5; byte m5 = _m[tile].m5;
if ((m5 & 0xF0) == 0) { if ((m5 & 0xF0) == 0) {
if (flags & DC_AUTO) if (flags & DC_AUTO) return_cmd_error(STR_5006_MUST_DEMOLISH_TUNNEL_FIRST);
return_cmd_error(STR_5006_MUST_DEMOLISH_TUNNEL_FIRST);
return DoClearTunnel(tile, flags); return DoClearTunnel(tile, flags);
} else if (m5 & 0x80) { } else if (m5 & 0x80) {
if (flags & DC_AUTO) if (flags & DC_AUTO) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
return DoClearBridge(tile, flags); return DoClearBridge(tile, flags);
} }
@ -896,7 +882,7 @@ int32 DoConvertTunnelBridgeRail(TileIndex tile, uint totype, bool exec)
MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile);
} }
return _price.build_rail >> 1; return _price.build_rail >> 1;
} else if ((_m[tile].m5&0xC6) == 0x80) { } else if ((_m[tile].m5 & 0xC6) == 0x80) {
TileIndex starttile; TileIndex starttile;
int32 cost; int32 cost;
uint z = TilePixelHeight(tile); uint z = TilePixelHeight(tile);
@ -908,7 +894,8 @@ int32 DoConvertTunnelBridgeRail(TileIndex tile, uint totype, bool exec)
// railway bridge // railway bridge
starttile = tile = FindEdgesOfBridge(tile, &endtile); starttile = tile = FindEdgesOfBridge(tile, &endtile);
// Make sure there's no vehicle on the bridge // Make sure there's no vehicle on the bridge
if ((v=FindVehicleBetween(tile, endtile, z)) != NULL) { v = FindVehicleBetween(tile, endtile, z);
if (v != NULL) {
VehicleInTheWayErrMsg(v); VehicleInTheWayErrMsg(v);
return CMD_ERROR; return CMD_ERROR;
} }
@ -929,7 +916,7 @@ int32 DoConvertTunnelBridgeRail(TileIndex tile, uint totype, bool exec)
} }
MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile);
} }
cost += (_price.build_rail>>1); cost += _price.build_rail >> 1;
tile += GB(_m[tile].m5, 0, 1) ? TileDiffXY(0, 1) : TileDiffXY(1, 0); tile += GB(_m[tile].m5, 0, 1) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
} while (tile <= endtile); } while (tile <= endtile);
@ -1016,7 +1003,8 @@ static void DrawBridgePillars(const TileInfo *ti, int x, int y, int z)
} }
} }
uint GetBridgeFoundation(uint tileh, byte direction) { uint GetBridgeFoundation(uint tileh, byte direction)
{
int i; int i;
// normal level sloped building (7, 11, 13, 14) // normal level sloped building (7, 11, 13, 14)
if (BRIDGE_FULL_LEVELED_FOUNDATION & (1 << tileh)) if (BRIDGE_FULL_LEVELED_FOUNDATION & (1 << tileh))
@ -1089,7 +1077,6 @@ static void DrawTile_TunnelBridge(TileInfo *ti)
assert( (base_offset & 0x07) == 0x00); assert( (base_offset & 0x07) == 0x00);
if (!(ti->map5 & 0x40)) { // bridge ramps if (!(ti->map5 & 0x40)) { // bridge ramps
if (!(BRIDGE_NO_FOUNDATION & (1 << ti->tileh))) { // no foundations for 0, 3, 6, 9, 12 if (!(BRIDGE_NO_FOUNDATION & (1 << ti->tileh))) { // no foundations for 0, 3, 6, 9, 12
int f = GetBridgeFoundation(ti->tileh, ti->map5 & 0x1); // pass direction int f = GetBridgeFoundation(ti->tileh, ti->map5 & 0x1); // pass direction
if (f) DrawFoundation(ti, f); if (f) DrawFoundation(ti, f);
@ -1228,11 +1215,10 @@ static uint GetSlopeZ_TunnelBridge(const TileInfo* ti)
// to the side of the tunnel/bridge? // to the side of the tunnel/bridge?
if (IS_INT_INSIDE(y, 5, 10+1)) { if (IS_INT_INSIDE(y, 5, 10+1)) {
// tunnel? // tunnel?
if ( (ti->map5 & 0xF0) == 0) if ((ti->map5 & 0xF0) == 0) return z;
return z;
// bridge? // bridge?
if ( ti->map5 & 0x80 ) { if (ti->map5 & 0x80) {
// bridge ending? // bridge ending?
if (!(ti->map5 & 0x40)) { if (!(ti->map5 & 0x40)) {
if (BRIDGE_FULL_LEVELED_FOUNDATION & (1 << tileh)) // 7, 11, 13, 14 if (BRIDGE_FULL_LEVELED_FOUNDATION & (1 << tileh)) // 7, 11, 13, 14
@ -1241,7 +1227,6 @@ static uint GetSlopeZ_TunnelBridge(const TileInfo* ti)
// no ramp for bridge ending // no ramp for bridge ending
if ((BRIDGE_PARTLY_LEVELED_FOUNDATION & (1 << tileh) || BRIDGE_NO_FOUNDATION & (1 << tileh)) && tileh != 0) { if ((BRIDGE_PARTLY_LEVELED_FOUNDATION & (1 << tileh) || BRIDGE_NO_FOUNDATION & (1 << tileh)) && tileh != 0) {
return z + 8; return z + 8;
} else if (!(ti->map5 & 0x20)) { // northern / southern ending } else if (!(ti->map5 & 0x20)) { // northern / southern ending
// ramp // ramp
return (z + (x>>1) + 1); return (z + (x>>1) + 1);
@ -1256,12 +1241,10 @@ static uint GetSlopeZ_TunnelBridge(const TileInfo* ti)
if (tileh != 0) z += 8; if (tileh != 0) z += 8;
// keep the same elevation because we're on the bridge? // keep the same elevation because we're on the bridge?
if (_get_z_hint >= z + 8) if (_get_z_hint >= z + 8) return _get_z_hint;
return _get_z_hint;
// actually on the bridge, but not yet in the shared area. // actually on the bridge, but not yet in the shared area.
if (!IS_INT_INSIDE(x, 5, 10+1)) if (!IS_INT_INSIDE(x, 5, 10 + 1)) return GetBridgeHeight(ti) + 8;
return GetBridgeHeight(ti) + 8;
// in the shared area, assume that we're below the bridge, cause otherwise the hint would've caught it. // in the shared area, assume that we're below the bridge, cause otherwise the hint would've caught it.
// if rail or road below then it means it's possibly build on slope below the bridge. // if rail or road below then it means it's possibly build on slope below the bridge.
@ -1279,21 +1262,21 @@ static uint GetSlopeZ_TunnelBridge(const TileInfo* ti)
} }
} else { } else {
// if it's a bridge middle with transport route below, then we need to compensate for build on slopes // if it's a bridge middle with transport route below, then we need to compensate for build on slopes
if ( (ti->map5 & (0x80 + 0x40 + 0x20)) == (0x80 + 0x40 + 0x20)) { if ((ti->map5 & (0x80 | 0x40 | 0x20)) == (0x80 | 0x40 | 0x20)) {
uint f; uint f;
if (tileh != 0) z += 8; if (tileh != 0) z += 8;
f = _bridge_foundations[ti->map5&1][tileh]; f = _bridge_foundations[ti->map5 & 1][tileh];
if (IS_BYTE_INSIDE(f, 1, 15)) return z; if (IS_BYTE_INSIDE(f, 1, 15)) return z;
if (f != 0) tileh = _inclined_tileh[f - 15]; if (f != 0) tileh = _inclined_tileh[f - 15];
} }
} }
// default case // default case
z = ti->z; return GetPartialZ(ti->x & 0xF, ti->y & 0xF, tileh) + ti->z;
return GetPartialZ(ti->x & 0xF, ti->y & 0xF, tileh) + z;
} }
static uint GetSlopeTileh_TunnelBridge(const TileInfo *ti) { static uint GetSlopeTileh_TunnelBridge(const TileInfo* ti)
{
// not accurate, but good enough for slope graphics drawing // not accurate, but good enough for slope graphics drawing
return 0; return 0;
} }
@ -1363,7 +1346,7 @@ static void AnimateTile_TunnelBridge(TileIndex tile)
static void TileLoop_TunnelBridge(TileIndex tile) static void TileLoop_TunnelBridge(TileIndex tile)
{ {
if (_opt.landscape == LT_HILLY) { if (_opt.landscape == LT_HILLY) {
if ( GetTileZ(tile) > _opt.snow_line) { if (GetTileZ(tile) > _opt.snow_line) {
if (!(_m[tile].m4 & 0x80)) { if (!(_m[tile].m4 & 0x80)) {
_m[tile].m4 |= 0x80; _m[tile].m4 |= 0x80;
MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile);
@ -1407,29 +1390,30 @@ static uint32 GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode
result = 0; result = 0;
if (GB(m5, 1, 2) == mode) { if (GB(m5, 1, 2) == mode) {
/* Transport over the bridge is compatible */ /* Transport over the bridge is compatible */
result = m5&1 ? 0x202 : 0x101; result = m5 & 1 ? 0x202 : 0x101;
} }
if (m5 & 0x40) { if (m5 & 0x40) {
/* Bridge middle part */ /* Bridge middle part */
if (!(m5 & 0x20)) { if (!(m5 & 0x20)) {
/* Clear ground or water underneath */ /* Clear ground or water underneath */
if ((m5 & 0x18) != 8) if ((m5 & 0x18) != 8) {
/* Clear ground */ /* Clear ground */
return result; return result;
else } else {
if (mode != TRANSPORT_WATER) if (mode != TRANSPORT_WATER) return result;
return result; }
} else { } else {
/* Transport underneath */ /* Transport underneath */
if (GB(m5, 3, 2) != mode) if (GB(m5, 3, 2) != mode) {
/* Incompatible transport underneath */ /* Incompatible transport underneath */
return result; return result;
}
} }
/* If we've not returned yet, there is a compatible /* If we've not returned yet, there is a compatible
* transport or water beneath, so we can add it to * transport or water beneath, so we can add it to
* result */ * result */
/* Why is this xor'd ? Can't it just be or'd? */ /* Why is this xor'd ? Can't it just be or'd? */
result ^= m5&1 ? 0x101 : 0x202; result ^= m5 & 1 ? 0x101 : 0x202;
} }
return result; return result;
} else { } else {
@ -1445,7 +1429,7 @@ static void ChangeTileOwner_TunnelBridge(TileIndex tile, PlayerID old_player, Pl
if (new_player != OWNER_SPECTATOR) { if (new_player != OWNER_SPECTATOR) {
SetTileOwner(tile, new_player); SetTileOwner(tile, new_player);
} else { } else {
if((_m[tile].m5 & 0xC0)==0xC0) { if ((_m[tile].m5 & 0xC0) == 0xC0) {
// the stuff BELOW the middle part is owned by the deleted player. // the stuff BELOW the middle part is owned by the deleted player.
if (!(_m[tile].m5 & (1 << 4 | 1 << 3))) { if (!(_m[tile].m5 & (1 << 4 | 1 << 3))) {
// convert railway into grass. // convert railway into grass.
@ -1556,9 +1540,8 @@ static uint32 VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y
myabs(h - v->z_pos) > 2) { // high above the ground -> on the bridge myabs(h - v->z_pos) > 2) { // high above the ground -> on the bridge
/* modify speed of vehicle */ /* modify speed of vehicle */
uint16 spd = _bridge[GetBridgeType(tile)].speed; uint16 spd = _bridge[GetBridgeType(tile)].speed;
if (v->type == VEH_Road) spd<<=1; if (v->type == VEH_Road) spd *= 2;
if (spd < v->cur_speed) if (spd < v->cur_speed) v->cur_speed = spd;
v->cur_speed = spd;
} }
} }
} }

117
vehicle.c
View File

@ -80,8 +80,7 @@ static void VehiclePoolNewBlock(uint start_item)
{ {
Vehicle *v; Vehicle *v;
FOR_ALL_VEHICLES_FROM(v, start_item) FOR_ALL_VEHICLES_FROM(v, start_item) v->index = start_item++;
v->index = start_item++;
} }
/* Initialize the vehicle-pool */ /* Initialize the vehicle-pool */
@ -230,9 +229,7 @@ void AfterLoadVehicles(void)
case VEH_Aircraft: case VEH_Aircraft:
if (v->subtype == 0 || v->subtype == 2) { if (v->subtype == 0 || v->subtype == 2) {
v->cur_image = GetAircraftImage(v, v->direction); v->cur_image = GetAircraftImage(v, v->direction);
if (v->next != NULL) { if (v->next != NULL) v->next->cur_image = v->cur_image;
v->next->cur_image = v->cur_image;
}
} }
break; break;
default: break; default: break;
@ -325,12 +322,14 @@ static Vehicle *AllocateSingleVehicle(VehicleID *skip_vehicles)
return NULL; return NULL;
} }
Vehicle *AllocateVehicle(void) Vehicle *AllocateVehicle(void)
{ {
VehicleID counter = 0; VehicleID counter = 0;
return AllocateSingleVehicle(&counter); return AllocateSingleVehicle(&counter);
} }
/** Allocates a lot of vehicles and frees them again /** Allocates a lot of vehicles and frees them again
* @param vl pointer to an array of vehicles to get allocated. Can be NULL if the vehicles aren't needed (makes it test only) * @param vl pointer to an array of vehicles to get allocated. Can be NULL if the vehicles aren't needed (makes it test only)
* @param num number of vehicles to allocate room for * @param num number of vehicles to allocate room for
@ -359,7 +358,6 @@ bool AllocateVehicles(Vehicle **vl, int num)
void *VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc) void *VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
{ {
int x,y,x2,y2; int x,y,x2,y2;
VehicleID veh;
Point pt = RemapCoords(TileX(tile) * 16, TileY(tile) * 16, 0); Point pt = RemapCoords(TileX(tile) * 16, TileY(tile) * 16, 0);
x2 = ((pt.x + 104) & 0x1F80) >> 7; x2 = ((pt.x + 104) & 0x1F80) >> 7;
@ -368,16 +366,16 @@ void *VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
y2 = ((pt.y + 56) & 0xFC0); y2 = ((pt.y + 56) & 0xFC0);
y = ((pt.y - 294) & 0xFC0); y = ((pt.y - 294) & 0xFC0);
for(;;) { for (;;) {
int xb = x; int xb = x;
for(;;) { for (;;) {
veh = _vehicle_position_hash[ (x+y)&0xFFFF ]; VehicleID veh = _vehicle_position_hash[(x + y) & 0xFFFF];
while (veh != INVALID_VEHICLE) { while (veh != INVALID_VEHICLE) {
Vehicle *v = GetVehicle(veh); Vehicle *v = GetVehicle(veh);
void *a; void *a;
if ((a = proc(v, data)) != NULL) a = proc(v, data);
return a; if (a != NULL) return a;
veh = v->next_hash; veh = v->next_hash;
} }
@ -408,8 +406,7 @@ void UpdateVehiclePosHash(Vehicle *v, int x, int y)
new_hash = (x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(x,y)]; new_hash = (x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(x,y)];
old_hash = (old_x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(old_x, old_y)]; old_hash = (old_x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(old_x, old_y)];
if (old_hash == new_hash) if (old_hash == new_hash) return;
return;
/* remove from hash table? */ /* remove from hash table? */
if (old_hash != NULL) { if (old_hash != NULL) {
@ -421,10 +418,11 @@ void UpdateVehiclePosHash(Vehicle *v, int x, int y)
last = u; last = u;
} }
if (last == NULL) if (last == NULL) {
*old_hash = v->next_hash; *old_hash = v->next_hash;
else } else {
last->next_hash = v->next_hash; last->next_hash = v->next_hash;
}
} }
/* insert into hash table? */ /* insert into hash table? */
@ -525,8 +523,8 @@ Vehicle *GetFirstVehicleInChain(const Vehicle *v)
uint CountVehiclesInChain(const Vehicle* v) uint CountVehiclesInChain(const Vehicle* v)
{ {
int count = 0; uint count = 0;
do count++; while ( (v=v->next) != NULL); do count++; while ((v = v->next) != NULL);
return count; return count;
} }
@ -719,7 +717,7 @@ void ViewportAddVehicles(DrawPixelInfo *dpi)
for(;;) { for(;;) {
xb = x; xb = x;
for(;;) { for(;;) {
veh = _vehicle_position_hash[ (x+y)&0xFFFF ]; veh = _vehicle_position_hash[(x + y) & 0xFFFF];
while (veh != INVALID_VEHICLE) { while (veh != INVALID_VEHICLE) {
v = GetVehicle(veh); v = GetVehicle(veh);
@ -1411,9 +1409,10 @@ void CheckVehicleBreakdown(Vehicle *v)
if ((rel_old >> 8) != (rel >> 8)) if ((rel_old >> 8) != (rel >> 8))
InvalidateWindow(WC_VEHICLE_DETAILS, v->index); InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
if (v->breakdown_ctr != 0 || (v->vehstatus & VS_STOPPED) != 0 || if (v->breakdown_ctr != 0 || v->vehstatus & VS_STOPPED ||
v->cur_speed < 5 || _game_mode == GM_MENU) v->cur_speed < 5 || _game_mode == GM_MENU) {
return; return;
}
r = Random(); r = Random();
@ -1427,8 +1426,7 @@ void CheckVehicleBreakdown(Vehicle *v)
if (v->type == VEH_Ship) rel += 0x6666; if (v->type == VEH_Ship) rel += 0x6666;
/* disabled breakdowns? */ /* disabled breakdowns? */
if (_opt.diff.vehicle_breakdowns < 1) if (_opt.diff.vehicle_breakdowns < 1) return;
return;
/* reduced breakdowns? */ /* reduced breakdowns? */
if (_opt.diff.vehicle_breakdowns == 1) rel += 0x6666; if (_opt.diff.vehicle_breakdowns == 1) rel += 0x6666;
@ -1450,12 +1448,10 @@ static const StringID _vehicle_type_names[4] = {
static void ShowVehicleGettingOld(Vehicle *v, StringID msg) static void ShowVehicleGettingOld(Vehicle *v, StringID msg)
{ {
if (v->owner != _local_player) if (v->owner != _local_player) return;
return;
// Do not show getting-old message if autorenew is active // Do not show getting-old message if autorenew is active
if (GetPlayer(v->owner)->engine_renew) if (GetPlayer(v->owner)->engine_renew) return;
return;
SetDParam(0, _vehicle_type_names[v->type - 0x10]); SetDParam(0, _vehicle_type_names[v->type - 0x10]);
SetDParam(1, v->unitnumber); SetDParam(1, v->unitnumber);
@ -1492,20 +1488,19 @@ static Vehicle *GetNextEnginePart(Vehicle *v)
{ {
switch (v->type) { switch (v->type) {
case VEH_Train: case VEH_Train:
{ if (RailVehInfo(v->engine_type)->flags & RVI_MULTIHEAD) {
const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
if (rvi->flags & RVI_MULTIHEAD)
return GetRearEngine(v, v->engine_type); return GetRearEngine(v, v->engine_type);
if (v->next != NULL && v->next->subtype == TS_Artic_Part) }
return v->next; if (v->next != NULL && v->next->subtype == TS_Artic_Part) return v->next;
}
break; break;
case VEH_Aircraft: case VEH_Aircraft:
return v->next; return v->next;
break;
case VEH_Road: case VEH_Road:
case VEH_Ship: case VEH_Ship:
break; break;
default: NOT_REACHED(); default: NOT_REACHED();
} }
return NULL; return NULL;
@ -1523,8 +1518,7 @@ int32 CmdCloneVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
Vehicle *w_front, *w, *w_rear; Vehicle *w_front, *w, *w_rear;
int cost, total_cost = 0; int cost, total_cost = 0;
if (!IsVehicleIndex(p1)) if (!IsVehicleIndex(p1)) return CMD_ERROR;
return CMD_ERROR;
v = GetVehicle(p1); v = GetVehicle(p1);
v_front = v; v_front = v;
w = NULL; w = NULL;
@ -1540,8 +1534,7 @@ int32 CmdCloneVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
* w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
*/ */
if (!CheckOwnership(v->owner)) if (!CheckOwnership(v->owner)) return CMD_ERROR;
return CMD_ERROR;
if (v->type == VEH_Train && v->subtype != TS_Front_Engine) return CMD_ERROR; if (v->type == VEH_Train && v->subtype != TS_Front_Engine) return CMD_ERROR;
@ -1567,7 +1560,7 @@ int32 CmdCloneVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
total_cost += cost; total_cost += cost;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
w= GetVehicle(_new_vehicle_id); w = GetVehicle(_new_vehicle_id);
if (v->type != VEH_Road) { // road vehicles can't be refitted if (v->type != VEH_Road) { // road vehicles can't be refitted
if (v->cargo_type != w->cargo_type) { if (v->cargo_type != w->cargo_type) {
@ -1636,11 +1629,11 @@ static void MoveVehicleCargo(Vehicle *dest, Vehicle *source)
} }
/* Replaces a vehicle (used to be called autorenew) /* Replaces a vehicle (used to be called autorenew)
* This function is only called from MaybeReplaceVehicle(), which is the next one * This function is only called from MaybeReplaceVehicle()
* Must be called with _current_player set to the owner of the vehicle * Must be called with _current_player set to the owner of the vehicle
* @param w Vehicle to replace * @param w Vehicle to replace
* @param flags is the flags to use when calling DoCommand(). Mainly DC_EXEC counts * @param flags is the flags to use when calling DoCommand(). Mainly DC_EXEC counts
* return value is cost of the replacement or CMD_ERROR * @return value is cost of the replacement or CMD_ERROR
*/ */
static int32 ReplaceVehicle(Vehicle **w, byte flags) static int32 ReplaceVehicle(Vehicle **w, byte flags)
{ {
@ -1652,11 +1645,9 @@ static int32 ReplaceVehicle(Vehicle **w, byte flags)
bool new_front = false; bool new_front = false;
Vehicle *new_v = NULL; Vehicle *new_v = NULL;
new_engine_type = p->engine_replacement[old_v->engine_type] == INVALID_ENGINE ? old_v->engine_type: p->engine_replacement[old_v->engine_type]; new_engine_type = p->engine_replacement[old_v->engine_type] == INVALID_ENGINE ? old_v->engine_type : p->engine_replacement[old_v->engine_type];
cost = DoCommand(old_v->x_pos, old_v->y_pos, new_engine_type, 2, flags, CMD_BUILD_VEH(old_v->type)); cost = DoCommand(old_v->x_pos, old_v->y_pos, new_engine_type, 2, flags, CMD_BUILD_VEH(old_v->type));
//check if the new engine is buildable
if (CmdFailed(cost)) return cost; if (CmdFailed(cost)) return cost;
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
@ -1708,11 +1699,12 @@ static int32 ReplaceVehicle(Vehicle **w, byte flags)
return cost; return cost;
} }
/** replaces a vehicle if it's set for autoreplace or is too old(used to be called autorenew) /** replaces a vehicle if it's set for autoreplace or is too old
* @param v The vehicle to replace * (used to be called autorenew)
* if the vehicle is a train, v needs to be the front engine * @param v The vehicle to replace
* return value is a pointer to the new vehicle, which is the same as the argument if nothing happened * if the vehicle is a train, v needs to be the front engine
*/ * return value is a pointer to the new vehicle, which is the same as the argument if nothing happened
*/
static void MaybeReplaceVehicle(Vehicle *v) static void MaybeReplaceVehicle(Vehicle *v)
{ {
Vehicle *w; Vehicle *w;
@ -1739,14 +1731,15 @@ static void MaybeReplaceVehicle(Vehicle *v)
train_fits_in_station = true; train_fits_in_station = true;
} }
while (true) { for (;;) {
cost = 0; cost = 0;
w = v; w = v;
do { do {
// check if the vehicle should be replaced // check if the vehicle should be replaced
if (!p->engine_renew || w->age - w->max_age < (p->engine_renew_months * 30) //replace if engine is too old if (!p->engine_renew ||
|| (w->max_age == 0)) { // rail cars got a max age of 0 w->age - w->max_age < (p->engine_renew_months * 30) || // replace if engine is too old
if (p->engine_replacement[w->engine_type] == INVALID_ENGINE) // updates to a new model w->max_age == 0) { // rail cars got a max age of 0
if (p->engine_replacement[w->engine_type] == INVALID_ENGINE) // updates to a new model
continue; continue;
} }
@ -1760,14 +1753,16 @@ static void MaybeReplaceVehicle(Vehicle *v)
/* Now replace the vehicle */ /* Now replace the vehicle */
temp_cost = ReplaceVehicle(&w, flags); temp_cost = ReplaceVehicle(&w, flags);
if (flags & DC_EXEC && !(w->type == VEH_Train && w->u.rail.first_engine != INVALID_VEHICLE)){ if (flags & DC_EXEC &&
// now we bought a new engine and sold the old one. We need to fix the pointers in order to avoid pointing to the old one (w->type != VEH_Train || w->u.rail.first_engine == INVALID_VEHICLE)) {
// for trains: these pointers should point to the front engine and not the cars /* now we bought a new engine and sold the old one. We need to fix the
* pointers in order to avoid pointing to the old one for trains: these
* pointers should point to the front engine and not the cars
*/
v = w; v = w;
} }
if (CmdFailed(temp_cost)) if (CmdFailed(temp_cost)) break;
break;
cost += temp_cost; cost += temp_cost;
} while (w->type == VEH_Train && (w = GetNextVehicle(w)) != NULL); } while (w->type == VEH_Train && (w = GetNextVehicle(w)) != NULL);
@ -1787,8 +1782,7 @@ static void MaybeReplaceVehicle(Vehicle *v)
AddNewsItem(message, NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0), v->index, 0); AddNewsItem(message, NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0), v->index, 0);
} }
if (stopped) if (stopped) v->vehstatus &= ~VS_STOPPED;
v->vehstatus &= ~VS_STOPPED; //we start the vehicle again
_current_player = OWNER_NONE; _current_player = OWNER_NONE;
return; return;
} }
@ -1823,8 +1817,7 @@ static void MaybeReplaceVehicle(Vehicle *v)
if (IsLocalPlayer()) ShowCostOrIncomeAnimation(v->x_pos, v->y_pos, v->z_pos, cost); if (IsLocalPlayer()) ShowCostOrIncomeAnimation(v->x_pos, v->y_pos, v->z_pos, cost);
if (stopped) if (stopped) v->vehstatus &= ~VS_STOPPED;
v->vehstatus &= ~VS_STOPPED; //we start the vehicle again
_current_player = OWNER_NONE; _current_player = OWNER_NONE;
} }

View File

@ -166,7 +166,7 @@ struct WorldSprite {
struct Vehicle { struct Vehicle {
byte type; // type, ie roadven,train,ship,aircraft,special byte type; // type, ie roadven,train,ship,aircraft,special
byte subtype; // subtype (Filled with values from EffectVehicles or TrainSubTypes)(Filled with values from EffectVehicles or TrainSubTypes) byte subtype; // subtype (Filled with values from EffectVehicles or TrainSubTypes)
VehicleID index; // NOSAVE: Index in vehicle array VehicleID index; // NOSAVE: Index in vehicle array
@ -184,7 +184,6 @@ struct Vehicle {
int32 x_pos; // coordinates int32 x_pos; // coordinates
int32 y_pos; int32 y_pos;
byte z_pos; byte z_pos;
byte direction; // facing byte direction; // facing
@ -263,8 +262,6 @@ struct Vehicle {
int32 profit_last_year; int32 profit_last_year;
uint32 value; uint32 value;
union { union {
VehicleRail rail; VehicleRail rail;
VehicleAir air; VehicleAir air;

View File

@ -105,9 +105,9 @@ void ResortVehicleLists(void)
void BuildVehicleList(vehiclelist_d* vl, int type, PlayerID owner, StationID station) void BuildVehicleList(vehiclelist_d* vl, int type, PlayerID owner, StationID station)
{ {
int subtype = (type != VEH_Aircraft) ? TS_Front_Engine : 2; uint subtype = (type != VEH_Aircraft) ? TS_Front_Engine : 2;
int n = 0; uint n = 0;
int i; uint i;
if (!(vl->flags & VL_REBUILD)) return; if (!(vl->flags & VL_REBUILD)) return;
@ -185,14 +185,15 @@ void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
uint32 ormod; uint32 ormod;
// draw profit-based colored icons // draw profit-based colored icons
if(v->age <= 365 * 2) if (v->age <= 365 * 2) {
ormod = PALETTE_TO_GREY; ormod = PALETTE_TO_GREY;
else if(v->profit_last_year < 0) } else if (v->profit_last_year < 0) {
ormod = PALETTE_TO_RED; ormod = PALETTE_TO_RED;
else if(v->profit_last_year < 10000) } else if (v->profit_last_year < 10000) {
ormod = PALETTE_TO_YELLOW; ormod = PALETTE_TO_YELLOW;
else } else {
ormod = PALETTE_TO_GREEN; ormod = PALETTE_TO_GREEN;
}
DrawSprite(SPR_BLOT | ormod, x, y); DrawSprite(SPR_BLOT | ormod, x, y);
} }
@ -282,7 +283,7 @@ static int CDECL VehicleNameSorter(const void *a, const void *b)
GetString(buf1, STR_JUST_STRING); GetString(buf1, STR_JUST_STRING);
} }
if ( cmp2->index != _last_vehicle_idx) { if (cmp2->index != _last_vehicle_idx) {
_last_vehicle_idx = cmp2->index; _last_vehicle_idx = cmp2->index;
_bufcache[0] = '\0'; _bufcache[0] = '\0';
if (vb->string_id != _internal_name_sorter_id) { if (vb->string_id != _internal_name_sorter_id) {
@ -415,9 +416,9 @@ static void train_engine_drawing_loop(int *x, int *y, int *pos, int *sel, int *s
const RailVehicleInfo *rvi = RailVehInfo(i); const RailVehicleInfo *rvi = RailVehInfo(i);
const EngineInfo *info = &_engine_info[i]; const EngineInfo *info = &_engine_info[i];
if (p->engine_replacement[i] == INVALID_ENGINE && _player_num_engines[i] == 0 && show_outdated ) continue; if (p->engine_replacement[i] == INVALID_ENGINE && _player_num_engines[i] == 0 && show_outdated) continue;
if ( rvi->power == 0 && !(show_cars) ) // disables display of cars (works since they do not have power) if (rvi->power == 0 && !show_cars) // disables display of cars (works since they do not have power)
continue; continue;
if (*sel == 0) *selected_id = i; if (*sel == 0) *selected_id = i;
@ -473,14 +474,14 @@ static void SetupScrollStuffForReplaceWindow(Window *w)
const Engine *e = GetEngine(engine_id); const Engine *e = GetEngine(engine_id);
const EngineInfo *info = &_engine_info[engine_id]; const EngineInfo *info = &_engine_info[engine_id];
if (ENGINE_AVAILABLE && RailVehInfo(engine_id)->power && e->railtype == railtype ) { if (ENGINE_AVAILABLE && RailVehInfo(engine_id)->power && e->railtype == railtype) {
if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) { if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) {
if (sel[0]==0) selected_id[0] = engine_id; if (sel[0] == 0) selected_id[0] = engine_id;
count++; count++;
sel[0]--; sel[0]--;
} }
if (HASBIT(e->player_avail, _local_player)) { if (HASBIT(e->player_avail, _local_player)) {
if (sel[1]==0) selected_id[1] = engine_id; if (sel[1] == 0) selected_id[1] = engine_id;
count2++; count2++;
sel[1]--; sel[1]--;
} }
@ -498,22 +499,22 @@ static void SetupScrollStuffForReplaceWindow(Window *w)
do { do {
info = &_engine_info[engine_id]; info = &_engine_info[engine_id];
if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) { if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) {
if (sel[0]==0) selected_id[0] = engine_id; if (sel[0] == 0) selected_id[0] = engine_id;
count++; count++;
sel[0]--; sel[0]--;
} }
} while (++engine_id,++e,--num); } while (++engine_id,++e,--num);
if ( selected_id[0] != -1 ) { // only draw right array if we have anything in the left one if (selected_id[0] != -1) { // only draw right array if we have anything in the left one
num = NUM_ROAD_ENGINES; num = NUM_ROAD_ENGINES;
engine_id = ROAD_ENGINES_INDEX; engine_id = ROAD_ENGINES_INDEX;
e = GetEngine(ROAD_ENGINES_INDEX); e = GetEngine(ROAD_ENGINES_INDEX);
cargo = RoadVehInfo(selected_id[0])->cargo_type; cargo = RoadVehInfo(selected_id[0])->cargo_type;
do { do {
if ( cargo == RoadVehInfo(engine_id)->cargo_type && HASBIT(e->player_avail, _local_player)) { if (cargo == RoadVehInfo(engine_id)->cargo_type && HASBIT(e->player_avail, _local_player)) {
count2++; count2++;
if (sel[1]==0) selected_id[1] = engine_id; if (sel[1] == 0) selected_id[1] = engine_id;
sel[1]--; sel[1]--;
} }
} while (++engine_id,++e,--num); } while (++engine_id,++e,--num);
@ -531,13 +532,13 @@ static void SetupScrollStuffForReplaceWindow(Window *w)
do { do {
info = &_engine_info[engine_id]; info = &_engine_info[engine_id];
if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) { if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) {
if ( sel[0] == 0 ) selected_id[0] = engine_id; if (sel[0] == 0) selected_id[0] = engine_id;
count++; count++;
sel[0]--; sel[0]--;
} }
} while (++engine_id,++e,--num); } while (++engine_id,++e,--num);
if ( selected_id[0] != -1 ) { if (selected_id[0] != -1) {
num = NUM_SHIP_ENGINES; num = NUM_SHIP_ENGINES;
e = GetEngine(SHIP_ENGINES_INDEX); e = GetEngine(SHIP_ENGINES_INDEX);
engine_id = SHIP_ENGINES_INDEX; engine_id = SHIP_ENGINES_INDEX;
@ -545,10 +546,9 @@ static void SetupScrollStuffForReplaceWindow(Window *w)
refittable = ShipVehInfo(selected_id[0])->refittable; refittable = ShipVehInfo(selected_id[0])->refittable;
do { do {
if (HASBIT(e->player_avail, _local_player) if (HASBIT(e->player_avail, _local_player) &&
&& ( cargo == ShipVehInfo(engine_id)->cargo_type || refittable & ShipVehInfo(engine_id)->refittable)) { (cargo == ShipVehInfo(engine_id)->cargo_type || refittable & ShipVehInfo(engine_id)->refittable)) {
if (sel[1] == 0) selected_id[1] = engine_id;
if ( sel[1]==0) selected_id[1] = engine_id;
sel[1]--; sel[1]--;
count2++; count2++;
} }
@ -568,12 +568,12 @@ static void SetupScrollStuffForReplaceWindow(Window *w)
info = &_engine_info[engine_id]; info = &_engine_info[engine_id];
if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) { if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) {
count++; count++;
if (sel[0]==0) selected_id[0] = engine_id; if (sel[0] == 0) selected_id[0] = engine_id;
sel[0]--; sel[0]--;
} }
} while (++engine_id,++e,--num); } while (++engine_id,++e,--num);
if ( selected_id[0] != -1 ) { if (selected_id[0] != -1) {
num = NUM_AIRCRAFT_ENGINES; num = NUM_AIRCRAFT_ENGINES;
e = GetEngine(AIRCRAFT_ENGINES_INDEX); e = GetEngine(AIRCRAFT_ENGINES_INDEX);
subtype = AircraftVehInfo(selected_id[0])->subtype; subtype = AircraftVehInfo(selected_id[0])->subtype;
@ -582,7 +582,7 @@ static void SetupScrollStuffForReplaceWindow(Window *w)
if (HASBIT(e->player_avail, _local_player)) { if (HASBIT(e->player_avail, _local_player)) {
if (HASBIT(subtype, 0) == HASBIT(AircraftVehInfo(engine_id)->subtype, 0)) { if (HASBIT(subtype, 0) == HASBIT(AircraftVehInfo(engine_id)->subtype, 0)) {
count2++; count2++;
if (sel[1]==0) selected_id[1] = engine_id; if (sel[1] == 0) selected_id[1] = engine_id;
sel[1]--; sel[1]--;
} }
} }
@ -640,7 +640,7 @@ static void DrawEngineArrayInReplaceWindow(Window *w, int x, int y, int x2, int
byte cargo; byte cargo;
const EngineInfo* info; const EngineInfo* info;
if ( selected_id[0] >= ROAD_ENGINES_INDEX && selected_id[0] <= SHIP_ENGINES_INDEX ) { if (selected_id[0] >= ROAD_ENGINES_INDEX && selected_id[0] < SHIP_ENGINES_INDEX) {
cargo = RoadVehInfo(selected_id[0])->cargo_type; cargo = RoadVehInfo(selected_id[0])->cargo_type;
do { do {
@ -656,7 +656,7 @@ static void DrawEngineArrayInReplaceWindow(Window *w, int x, int y, int x2, int
sel[0]--; sel[0]--;
} }
if ( RoadVehInfo(engine_id)->cargo_type == cargo && HASBIT(e->player_avail, _local_player) ) { if (RoadVehInfo(engine_id)->cargo_type == cargo && HASBIT(e->player_avail, _local_player)) {
if (IS_INT_INSIDE(--pos2, -w->vscroll.cap, 0) && RoadVehInfo(engine_id)->cargo_type == cargo) { if (IS_INT_INSIDE(--pos2, -w->vscroll.cap, 0) && RoadVehInfo(engine_id)->cargo_type == cargo) {
DrawString(x2+59, y2+2, GetCustomEngineName(engine_id), sel[1]==0 ? 0xC : 0x10); DrawString(x2+59, y2+2, GetCustomEngineName(engine_id), sel[1]==0 ? 0xC : 0x10);
DrawRoadVehEngine(x2+29, y2+6, engine_id, SPRITE_PALETTE(PLAYER_SPRITE_COLOR(_local_player))); DrawRoadVehEngine(x2+29, y2+6, engine_id, SPRITE_PALETTE(PLAYER_SPRITE_COLOR(_local_player)));
@ -676,7 +676,7 @@ static void DrawEngineArrayInReplaceWindow(Window *w, int x, int y, int x2, int
byte cargo, refittable; byte cargo, refittable;
const EngineInfo* info; const EngineInfo* info;
if ( selected_id[0] != -1 ) { if (selected_id[0] != -1) {
cargo = ShipVehInfo(selected_id[0])->cargo_type; cargo = ShipVehInfo(selected_id[0])->cargo_type;
refittable = ShipVehInfo(selected_id[0])->refittable; refittable = ShipVehInfo(selected_id[0])->refittable;
@ -708,7 +708,7 @@ static void DrawEngineArrayInReplaceWindow(Window *w, int x, int y, int x2, int
} //end of ship } //end of ship
case VEH_Aircraft: { case VEH_Aircraft: {
if ( selected_id[0] != -1 ) { if (selected_id[0] != -1) {
int num = NUM_AIRCRAFT_ENGINES; int num = NUM_AIRCRAFT_ENGINES;
const Engine* e = GetEngine(AIRCRAFT_ENGINES_INDEX); const Engine* e = GetEngine(AIRCRAFT_ENGINES_INDEX);
EngineID engine_id = AIRCRAFT_ENGINES_INDEX; EngineID engine_id = AIRCRAFT_ENGINES_INDEX;
@ -718,7 +718,7 @@ static void DrawEngineArrayInReplaceWindow(Window *w, int x, int y, int x2, int
do { do {
info = &_engine_info[engine_id]; info = &_engine_info[engine_id];
if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) { if (_player_num_engines[engine_id] > 0 || p->engine_replacement[engine_id] != INVALID_ENGINE) {
if (sel[0]==0) selected_id[0] = engine_id; if (sel[0] == 0) selected_id[0] = engine_id;
if (IS_INT_INSIDE(--pos, -w->vscroll.cap, 0)) { if (IS_INT_INSIDE(--pos, -w->vscroll.cap, 0)) {
DrawString(x+62, y+7, GetCustomEngineName(engine_id), sel[0]==0 ? 0xC : 0x10); DrawString(x+62, y+7, GetCustomEngineName(engine_id), sel[0]==0 ? 0xC : 0x10);
DrawAircraftEngine(x+29, y+10, engine_id, _player_num_engines[engine_id] > 0 ? SPRITE_PALETTE(PLAYER_SPRITE_COLOR(_local_player)) : PALETTE_CRASH); DrawAircraftEngine(x+29, y+10, engine_id, _player_num_engines[engine_id] > 0 ? SPRITE_PALETTE(PLAYER_SPRITE_COLOR(_local_player)) : PALETTE_CRASH);
@ -728,9 +728,9 @@ static void DrawEngineArrayInReplaceWindow(Window *w, int x, int y, int x2, int
} }
sel[0]--; sel[0]--;
} }
if ( (HASBIT(subtype, 0) == HASBIT(AircraftVehInfo(engine_id)->subtype, 0)) if (HASBIT(subtype, 0) == HASBIT(AircraftVehInfo(engine_id)->subtype, 0) &&
&& HASBIT(e->player_avail, _local_player) ) { HASBIT(e->player_avail, _local_player)) {
if (sel[1]==0) selected_id[1] = engine_id; if (sel[1] == 0) selected_id[1] = engine_id;
if (IS_INT_INSIDE(--pos2, -w->vscroll.cap, 0)) { if (IS_INT_INSIDE(--pos2, -w->vscroll.cap, 0)) {
DrawString(x2+62, y2+7, GetCustomEngineName(engine_id), sel[1]==0 ? 0xC : 0x10); DrawString(x2+62, y2+7, GetCustomEngineName(engine_id), sel[1]==0 ? 0xC : 0x10);
DrawAircraftEngine(x2+29, y2+10, engine_id, SPRITE_PALETTE(PLAYER_SPRITE_COLOR(_local_player))); DrawAircraftEngine(x2+29, y2+10, engine_id, SPRITE_PALETTE(PLAYER_SPRITE_COLOR(_local_player)));
@ -743,11 +743,17 @@ static void DrawEngineArrayInReplaceWindow(Window *w, int x, int y, int x2, int
break; break;
} // end of aircraft } // end of aircraft
} }
} }
static void ReplaceVehicleWndProc(Window *w, WindowEvent *e) static void ReplaceVehicleWndProc(Window *w, WindowEvent *e)
{ {
static const StringID _vehicle_type_names[4] = {STR_019F_TRAIN, STR_019C_ROAD_VEHICLE, STR_019E_SHIP,STR_019D_AIRCRAFT}; static const StringID _vehicle_type_names[] = {
STR_019F_TRAIN,
STR_019C_ROAD_VEHICLE,
STR_019E_SHIP,
STR_019D_AIRCRAFT
};
const Player *p = GetPlayer(_local_player); const Player *p = GetPlayer(_local_player);
switch (e->event) { switch (e->event) {
@ -771,11 +777,11 @@ static void ReplaceVehicleWndProc(Window *w, WindowEvent *e)
_player_num_engines[i] = 0; _player_num_engines[i] = 0;
} }
FOR_ALL_VEHICLES(vehicle) { FOR_ALL_VEHICLES(vehicle) {
if ( vehicle->owner == _local_player ) { if (vehicle->owner == _local_player) {
if (vehicle->type == VEH_Aircraft && vehicle->subtype > 2) continue; if (vehicle->type == VEH_Aircraft && vehicle->subtype > 2) continue;
// do not count the vehicles, that contains only 0 in all var // do not count the vehicles, that contains only 0 in all var
if (vehicle->engine_type == 0 && vehicle->spritenum == 0 ) continue; if (vehicle->engine_type == 0 && vehicle->spritenum == 0) continue;
if (vehicle->type != GetEngine(vehicle->engine_type)->type) continue; if (vehicle->type != GetEngine(vehicle->engine_type)->type) continue;
@ -791,7 +797,7 @@ static void ReplaceVehicleWndProc(Window *w, WindowEvent *e)
// sets the selected left item to the top one if it's greater than the number of vehicles in the left side // sets the selected left item to the top one if it's greater than the number of vehicles in the left side
if ( WP(w,replaceveh_d).count[0] <= sel[0] ) { if (WP(w,replaceveh_d).count[0] <= sel[0]) {
if (WP(w,replaceveh_d).count[0]) { if (WP(w,replaceveh_d).count[0]) {
sel[0] = 0; sel[0] = 0;
WP(w,replaceveh_d).sel_index[0] = 0; WP(w,replaceveh_d).sel_index[0] = 0;
@ -804,7 +810,7 @@ static void ReplaceVehicleWndProc(Window *w, WindowEvent *e)
} }
} }
if ( WP(w,replaceveh_d).count[1] <= sel[1] ) { if (WP(w,replaceveh_d).count[1] <= sel[1]) {
if (WP(w,replaceveh_d).count[1]) { if (WP(w,replaceveh_d).count[1]) {
sel[1] = 0; sel[1] = 0;
WP(w,replaceveh_d).sel_index[1] = 0; WP(w,replaceveh_d).sel_index[1] = 0;
@ -821,21 +827,24 @@ static void ReplaceVehicleWndProc(Window *w, WindowEvent *e)
// Either list is empty // Either list is empty
// or Both lists have the same vehicle selected // or Both lists have the same vehicle selected
// or The right list (new replacement) has the existing replacement vehicle selected // or The right list (new replacement) has the existing replacement vehicle selected
if (selected_id[0] == -1 || selected_id[1] == -1 || if (selected_id[0] == -1 ||
selected_id[1] == -1 ||
selected_id[0] == selected_id[1] || selected_id[0] == selected_id[1] ||
p->engine_replacement[selected_id[0]] == selected_id[1]) p->engine_replacement[selected_id[0]] == selected_id[1]) {
SETBIT(w->disabled_state, 4); SETBIT(w->disabled_state, 4);
else } else {
CLRBIT(w->disabled_state, 4); CLRBIT(w->disabled_state, 4);
}
// Disable the "Stop Replacing" button if: // Disable the "Stop Replacing" button if:
// The left list (existing vehicle) is empty // The left list (existing vehicle) is empty
// or The selected vehicle has no replacement set up // or The selected vehicle has no replacement set up
if (selected_id[0] == -1 || if (selected_id[0] == -1 ||
p->engine_replacement[selected_id[0]] == INVALID_ENGINE) p->engine_replacement[selected_id[0]] == INVALID_ENGINE) {
SETBIT(w->disabled_state, 6); SETBIT(w->disabled_state, 6);
else } else {
CLRBIT(w->disabled_state, 6); CLRBIT(w->disabled_state, 6);
}
// now the actual drawing of the window itself takes place // now the actual drawing of the window itself takes place
SetDParam(0, _vehicle_type_names[WP(w, replaceveh_d).vehicletype - VEH_Train]); SetDParam(0, _vehicle_type_names[WP(w, replaceveh_d).vehicletype - VEH_Train]);
@ -848,18 +857,17 @@ static void ReplaceVehicleWndProc(Window *w, WindowEvent *e)
DrawWindowWidgets(w); DrawWindowWidgets(w);
// sets up the string for the vehicle that is being replaced to // sets up the string for the vehicle that is being replaced to
if ( selected_id[0] != -1 ) { if (selected_id[0] != -1) {
if (p->engine_replacement[selected_id[0]] == INVALID_ENGINE) if (p->engine_replacement[selected_id[0]] == INVALID_ENGINE) {
SetDParam(0, STR_NOT_REPLACING); SetDParam(0, STR_NOT_REPLACING);
else } else {
SetDParam(0, GetCustomEngineName(p->engine_replacement[selected_id[0]])); SetDParam(0, GetCustomEngineName(p->engine_replacement[selected_id[0]]));
}
} else { } else {
SetDParam(0, STR_NOT_REPLACING_VEHICLE_SELECTED); SetDParam(0, STR_NOT_REPLACING_VEHICLE_SELECTED);
} }
DrawString(145, (w->resize.step_height == 24 ? 67 : 87) + w->resize.step_height * w->vscroll.cap, STR_02BD, 0x10);
DrawString(145, (w->resize.step_height == 24 ? 67 : 87 ) + ( w->resize.step_height * w->vscroll.cap), STR_02BD, 0x10);
/* now we draw the two arrays according to what we just counted */ /* now we draw the two arrays according to what we just counted */
DrawEngineArrayInReplaceWindow(w, x, y, x2, y2, pos, pos2, sel[0], sel[1], selected_id[0], selected_id[1]); DrawEngineArrayInReplaceWindow(w, x, y, x2, y2, pos, pos2, sel[0], sel[1], selected_id[0], selected_id[1]);
@ -872,9 +880,8 @@ static void ReplaceVehicleWndProc(Window *w, WindowEvent *e)
byte i = 0; byte i = 0;
int offset = 0; int offset = 0;
for ( i = 0 ; i < 2 ; i++) { for (i = 0 ; i < 2 ; i++) {
if ( i ) if (i > 0) offset = 228;
offset = 228;
if (selected_id[i] != -1) { if (selected_id[i] != -1) {
if (!(RailVehInfo(selected_id[i])->flags & RVI_WAGON)) { if (!(RailVehInfo(selected_id[i])->flags & RVI_WAGON)) {
/* it's an engine */ /* it's an engine */
@ -1101,37 +1108,34 @@ void InitializeGUI(void)
} }
/** Assigns an already open vehicle window to a new vehicle. /** Assigns an already open vehicle window to a new vehicle.
* Assigns an already open vehicle window to a new vehicle. If the vehicle got any sub window open (orders and so on) it will change owner too * Assigns an already open vehicle window to a new vehicle. If the vehicle got
* @param *from_v the current owner of the window * any sub window open (orders and so on) it will change owner too.
* @param *to_v the new owner of the window * @param *from_v the current owner of the window
*/ * @param *to_v the new owner of the window
*/
void ChangeVehicleViewWindow(const Vehicle *from_v, const Vehicle *to_v) void ChangeVehicleViewWindow(const Vehicle *from_v, const Vehicle *to_v)
{ {
Window *w; Window *w;
w = FindWindowById(WC_VEHICLE_VIEW, from_v->index); w = FindWindowById(WC_VEHICLE_VIEW, from_v->index);
if (w != NULL) { if (w != NULL) {
w->window_number = to_v->index; w->window_number = to_v->index;
WP(w, vp_d).follow_vehicle = to_v->index; // tell the viewport to follow the new vehicle WP(w, vp_d).follow_vehicle = to_v->index;
SetWindowDirty(w); SetWindowDirty(w);
w = FindWindowById(WC_VEHICLE_ORDERS, from_v->index); w = FindWindowById(WC_VEHICLE_ORDERS, from_v->index);
if (w != NULL) { if (w != NULL) {
w->window_number = to_v->index; w->window_number = to_v->index;
SetWindowDirty(w); SetWindowDirty(w);
} }
w = FindWindowById(WC_VEHICLE_REFIT, from_v->index); w = FindWindowById(WC_VEHICLE_REFIT, from_v->index);
if (w != NULL) { if (w != NULL) {
w->window_number = to_v->index; w->window_number = to_v->index;
SetWindowDirty(w); SetWindowDirty(w);
} }
w = FindWindowById(WC_VEHICLE_DETAILS, from_v->index); w = FindWindowById(WC_VEHICLE_DETAILS, from_v->index);
if (w != NULL) { if (w != NULL) {
w->window_number = to_v->index; w->window_number = to_v->index;
SetWindowDirty(w); SetWindowDirty(w);

View File

@ -502,12 +502,12 @@ static void TileLoopWaterHelper(TileIndex tile, const TileIndexDiffC *offs)
TileIndex target = TILE_ADD(tile, ToTileIndexDiff(offs[0])); TileIndex target = TILE_ADD(tile, ToTileIndexDiff(offs[0]));
// type of this tile mustn't be water already. // type of this tile mustn't be water already.
if (IsTileType(target, MP_WATER)) if (IsTileType(target, MP_WATER)) return;
return;
if (TileHeight(TILE_ADD(tile, ToTileIndexDiff(offs[1]))) != 0 || if (TileHeight(TILE_ADD(tile, ToTileIndexDiff(offs[1]))) != 0 ||
TileHeight(TILE_ADD(tile, ToTileIndexDiff(offs[2]))) != 0) TileHeight(TILE_ADD(tile, ToTileIndexDiff(offs[2]))) != 0) {
return; return;
}
if (TileHeight(TILE_ADD(tile, ToTileIndexDiff(offs[3]))) != 0 || if (TileHeight(TILE_ADD(tile, ToTileIndexDiff(offs[3]))) != 0 ||
TileHeight(TILE_ADD(tile, ToTileIndexDiff(offs[4]))) != 0) { TileHeight(TILE_ADD(tile, ToTileIndexDiff(offs[4]))) != 0) {
@ -639,8 +639,9 @@ void TileLoop_Water(TileIndex tile)
if (IS_INT_INSIDE(TileX(tile), 1, MapSizeX() - 3 + 1) && if (IS_INT_INSIDE(TileX(tile), 1, MapSizeX() - 3 + 1) &&
IS_INT_INSIDE(TileY(tile), 1, MapSizeY() - 3 + 1)) { IS_INT_INSIDE(TileY(tile), 1, MapSizeY() - 3 + 1)) {
for(i=0; i!=4; i++) for (i = 0; i != lengthof(_tile_loop_offs_array); i++) {
TileLoopWaterHelper(tile, _tile_loop_offs_array[i]); TileLoopWaterHelper(tile, _tile_loop_offs_array[i]);
}
} }
// _current_player can be changed by TileLoopWaterHelper.. reset it back // _current_player can be changed by TileLoopWaterHelper.. reset it back
// here // here
@ -650,15 +651,17 @@ void TileLoop_Water(TileIndex tile)
if (TileX(tile) == 0 && IS_INT_INSIDE(TileY(tile), 1, MapSizeY() - 3 + 1)) //NE if (TileX(tile) == 0 && IS_INT_INSIDE(TileY(tile), 1, MapSizeY() - 3 + 1)) //NE
TileLoopWaterHelper(tile, _tile_loop_offs_array[2]); TileLoopWaterHelper(tile, _tile_loop_offs_array[2]);
if (TileX(tile) == (MapSizeX() - 2) && IS_INT_INSIDE(TileY(tile), 1, MapSizeY() - 3 + 1)) //SW if (TileX(tile) == MapSizeX() - 2 && IS_INT_INSIDE(TileY(tile), 1, MapSizeY() - 3 + 1)) { //SW
TileLoopWaterHelper(tile, _tile_loop_offs_array[0]); TileLoopWaterHelper(tile, _tile_loop_offs_array[0]);
}
if (TileY(tile) == 0 && IS_INT_INSIDE(TileX(tile), 1, MapSizeX() - 3 + 1)) //NW if (TileY(tile) == 0 && IS_INT_INSIDE(TileX(tile), 1, MapSizeX() - 3 + 1)) { //NW
TileLoopWaterHelper(tile, _tile_loop_offs_array[1]); TileLoopWaterHelper(tile, _tile_loop_offs_array[1]);
}
if (TileY(tile) == (MapSizeY() - 2) && IS_INT_INSIDE(TileX(tile), 1, MapSizeX() - 3 + 1)) //SE if (TileY(tile) == MapSizeY() - 2 && IS_INT_INSIDE(TileX(tile), 1, MapSizeX() - 3 + 1)) { //SE
TileLoopWaterHelper(tile, _tile_loop_offs_array[3]); TileLoopWaterHelper(tile, _tile_loop_offs_array[3]);
}
} }

View File

@ -27,8 +27,7 @@ static Point HandleScrollbarHittest(const Scrollbar *sb, int top, int bottom)
if (count != 0) top += height * pos / count; if (count != 0) top += height * pos / count;
if (cap > count) cap = count; if (cap > count) cap = count;
if (count != 0) if (count != 0) bottom -= (count - pos - cap) * height / count;
bottom -= (count - pos - cap) * height / count;
pt.x = top; pt.x = top;
pt.y = bottom - 1; pt.y = bottom - 1;
@ -139,12 +138,11 @@ int GetWidgetFromPos(const Window *w, int x, int y)
// Go through the widgets and check if we find the widget that the coordinate is // Go through the widgets and check if we find the widget that the coordinate is
// inside. // inside.
for (index = 0,wi = w->widget; wi->type != WWT_LAST; index++, wi++) { for (index = 0,wi = w->widget; wi->type != WWT_LAST; index++, wi++) {
if (wi->type == WWT_EMPTY || wi->type == WWT_FRAME) if (wi->type == WWT_EMPTY || wi->type == WWT_FRAME) continue;
continue;
if (x >= wi->left && x <= wi->right && y >= wi->top && y <= wi->bottom && if (x >= wi->left && x <= wi->right && y >= wi->top && y <= wi->bottom &&
!HASBIT(w->hidden_state,index)) { !HASBIT(w->hidden_state,index)) {
found_index = index; found_index = index;
} }
} }
@ -169,11 +167,12 @@ void DrawWindowWidgets(const Window *w)
bool clicked = (cur_click & 1); bool clicked = (cur_click & 1);
if (dpi->left > (r.right=/*w->left + */wi->right) || if (dpi->left > (r.right=/*w->left + */wi->right) ||
dpi->left + dpi->width <= (r.left=wi->left/* + w->left*/) || dpi->left + dpi->width <= (r.left=wi->left/* + w->left*/) ||
dpi->top > (r.bottom=/*w->top +*/ wi->bottom) || dpi->top > (r.bottom=/*w->top +*/ wi->bottom) ||
dpi->top + dpi->height <= (r.top = /*w->top +*/ wi->top) || dpi->top + dpi->height <= (r.top = /*w->top +*/ wi->top) ||
(cur_hidden&1)) cur_hidden & 1) {
continue; continue;
}
switch (wi->type & WWT_MASK) { switch (wi->type & WWT_MASK) {
case WWT_PANEL: /* WWT_IMGBTN */ case WWT_PANEL: /* WWT_IMGBTN */
@ -182,8 +181,10 @@ void DrawWindowWidgets(const Window *w)
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 : 0);
if ((img = wi->unkA) != 0) { // has an image img = wi->unkA;
if ((wi->type & WWT_MASK) == WWT_PANEL_2 && clicked) img++; // show diff image when clicked if (img != 0) { // has an image
// show diff image when clicked
if ((wi->type & WWT_MASK) == WWT_PANEL_2 && clicked) img++;
DrawSprite(img, r.left + 1 + clicked, r.top + 1 + clicked); DrawSprite(img, r.left + 1 + clicked, r.top + 1 + clicked);
} }
@ -210,9 +211,8 @@ void DrawWindowWidgets(const Window *w)
StringID str; StringID str;
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, FR_LOWERED | FR_DARKENED); DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, FR_LOWERED | FR_DARKENED);
if ((str = wi->unkA) != 0) { str = wi->unkA;
DrawString(r.left+2, r.top+1, str, 0); if (str != 0) DrawString(r.left + 2, r.top + 1, str, 0);
}
goto draw_default; goto draw_default;
} }
@ -229,30 +229,30 @@ void DrawWindowWidgets(const Window *w)
d = (wi->unkA >> 8); d = (wi->unkA >> 8);
amt2 = (wi->bottom - wi->top + 1) / d; amt2 = (wi->bottom - wi->top + 1) / d;
color = _color_list[wi->color&0xF].window_color_bgb; color = _color_list[wi->color & 0xF].window_color_bgb;
x = r.left; x = r.left;
for(ctr=c; --ctr; ) { for (ctr = c; ctr > 0; ctr--) {
x += amt1; x += amt1;
GfxFillRect(x, r.top+1, x, r.bottom-1, color); GfxFillRect(x, r.top + 1, x, r.bottom - 1, color);
} }
x = r.top; x = r.top;
for(ctr=d; --ctr; ) { for (ctr = d; ctr > 0; ctr--) {
x += amt2; x += amt2;
GfxFillRect(r.left+1, x, r.right-1, x, color); GfxFillRect(r.left + 1, x, r.right - 1, x, color);
} }
color = _color_list[wi->color&0xF].window_color_1b; color = _color_list[wi->color&0xF].window_color_1b;
x = r.left-1; x = r.left - 1;
for(ctr=c; --ctr; ) { for (ctr = c; ctr > 0; ctr--) {
x += amt1; x += amt1;
GfxFillRect(x, r.top+1, x, r.bottom-1, color); GfxFillRect(x, r.top + 1, x, r.bottom - 1, color);
} }
x = r.top-1; x = r.top - 1;
for(ctr=d; --ctr; ) { for (ctr = d; ctr > 0; ctr--) {
x += amt2; x += amt2;
GfxFillRect(r.left+1, x, r.right-1, x, color); GfxFillRect(r.left+1, x, r.right-1, x, color);
} }
@ -365,9 +365,7 @@ void DrawWindowWidgets(const Window *w)
int c1,c2; int c1,c2;
int x2 = r.left; // by default the left side is the left side of the widget int x2 = r.left; // by default the left side is the left side of the widget
if (wi->unkA != 0) { if (wi->unkA != 0) x2 = DrawString(r.left + 6, r.top, wi->unkA, 0);
x2 = DrawString(r.left+6, r.top, wi->unkA, 0);
}
c1 = _color_list[wi->color].window_color_1a; c1 = _color_list[wi->color].window_color_1a;
c2 = _color_list[wi->color].window_color_2; c2 = _color_list[wi->color].window_color_2;
@ -485,20 +483,20 @@ static void DropdownMenuWndProc(Window *w, WindowEvent *e)
continue; continue;
} }
if (WP(w,dropdown_d).items[i] != 0) { if (WP(w,dropdown_d).items[i] != 0) {
if (sel == 0) { if (sel == 0) GfxFillRect(x + 1, y, x + w->width - 4, y + 9, 0);
GfxFillRect(x+1, y, x+w->width-4, y + 9, 0); DrawString(x + 2, y, WP(w,dropdown_d).items[i], sel == 0 ? 12 : 16);
}
DrawString(x+2, y, WP(w,dropdown_d).items[i], sel==0 ? 12 : 16);
if (HASBIT(w->disabled_state, i)) { if (HASBIT(w->disabled_state, i)) {
GfxFillRect(x, y, x+w->width-3, y + 9, PALETTE_MODIFIER_GREYOUT | GfxFillRect(x, y, x + w->width - 3, y + 9,
_color_list[_dropdown_menu_widgets[0].color].window_color_bga); PALETTE_MODIFIER_GREYOUT | _color_list[_dropdown_menu_widgets[0].color].window_color_bga
);
} }
} else { } else {
int color_1 = _color_list[_dropdown_menu_widgets[0].color].window_color_1a; int c1 = _color_list[_dropdown_menu_widgets[0].color].window_color_1a;
int color_2 = _color_list[_dropdown_menu_widgets[0].color].window_color_2; int c2 = _color_list[_dropdown_menu_widgets[0].color].window_color_2;
GfxFillRect(x+1, y+3, x+w->width-5, y+3, color_1);
GfxFillRect(x+1, y+4, x+w->width-5, y+4, color_2); GfxFillRect(x + 1, y + 3, x + w->width - 5, y + 3, c1);
GfxFillRect(x + 1, y + 4, x + w->width - 5, y + 4, c2);
} }
y += 10; y += 10;
sel--; sel--;
@ -536,12 +534,10 @@ static void DropdownMenuWndProc(Window *w, WindowEvent *e)
if (!_left_button_clicked) { if (!_left_button_clicked) {
WP(w,dropdown_d).drag_mode = false; WP(w,dropdown_d).drag_mode = false;
if (item < 0) if (item < 0) return;
return;
WP(w,dropdown_d).click_delay = 2; WP(w,dropdown_d).click_delay = 2;
} else { } else {
if (item < 0) if (item < 0) return;
return;
} }
WP(w,dropdown_d).selected_index = item; WP(w,dropdown_d).selected_index = item;
@ -573,25 +569,22 @@ void ShowDropDownMenu(Window *w, const StringID *strings, int selected, int butt
DeleteWindowById(WC_DROPDOWN_MENU, 0); DeleteWindowById(WC_DROPDOWN_MENU, 0);
w = FindWindowById(cls, num); w = FindWindowById(cls, num);
if (HASBIT(old_click_state, button)) if (HASBIT(old_click_state, button)) return;
return;
SETBIT(w->click_state, button); SETBIT(w->click_state, button);
InvalidateWidget(w, button); InvalidateWidget(w, button);
for (i = 0; strings[i] != INVALID_STRING_ID; i++); for (i = 0; strings[i] != INVALID_STRING_ID; i++) {}
if (i == 0) if (i == 0) return;
return;
wi = &w->widget[button]; wi = &w->widget[button];
if (hidden_mask != 0) { if (hidden_mask != 0) {
int j; uint j;
for (j = 0; strings[j] != INVALID_STRING_ID; j++) { for (j = 0; strings[j] != INVALID_STRING_ID; j++) {
if (HASBIT(hidden_mask, j)) { if (HASBIT(hidden_mask, j)) i--;
i--;
}
} }
} }

View File

@ -922,7 +922,6 @@ char *FiosBrowseTo(const FiosItem *item)
sprintf(path, "%s\\", item->name); sprintf(path, "%s\\", item->name);
s = strrchr(path, '\\'); s = strrchr(path, '\\');
if (s[1] == '\0') s[0] = '\0'; // strip trailing slash if (s[1] == '\0') s[0] = '\0'; // strip trailing slash
break; break;
case FIOS_TYPE_FILE: case FIOS_TYPE_FILE:

312
window.c
View File

@ -146,13 +146,13 @@ void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
DrawPixelInfo bk; DrawPixelInfo bk;
_cur_dpi = &bk; _cur_dpi = &bk;
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (right > w->left && if (right > w->left &&
bottom > w->top && bottom > w->top &&
left < w->left + w->width && left < w->left + w->width &&
top < w->top + w->height) { top < w->top + w->height) {
DrawOverlappedWindow(w, left, top, right, bottom); DrawOverlappedWindow(w, left, top, right, bottom);
} }
} }
} }
@ -166,7 +166,6 @@ void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
bottom > v->top && bottom > v->top &&
left < v->left + v->width && left < v->left + v->width &&
top < v->top + v->height) { top < v->top + v->height) {
if (left < (x=v->left)) { if (left < (x=v->left)) {
DrawOverlappedWindow(w, left, top, x, bottom); DrawOverlappedWindow(w, left, top, x, bottom);
DrawOverlappedWindow(w, x, top, right, bottom); DrawOverlappedWindow(w, x, top, right, bottom);
@ -230,8 +229,7 @@ void DeleteWindow(Window *w)
Window *v; Window *v;
int count; int count;
if (w == NULL) if (w == NULL) return;
return;
if (_thd.place_mode != 0 && _thd.window_class == w->window_class && _thd.window_number == w->window_number) { if (_thd.place_mode != 0 && _thd.window_class == w->window_class && _thd.window_number == w->window_number) {
ResetObjectToPlace(); ResetObjectToPlace();
@ -264,11 +262,8 @@ Window *FindWindowById(WindowClass cls, WindowNumber number)
{ {
Window *w; Window *w;
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->window_class == cls && if (w->window_class == cls && w->window_number == number) return w;
w->window_number == number) {
return w;
}
} }
return NULL; return NULL;
@ -282,12 +277,14 @@ void DeleteWindowById(WindowClass cls, WindowNumber number)
void DeleteWindowByClass(WindowClass cls) void DeleteWindowByClass(WindowClass cls)
{ {
Window *w; Window *w;
for (w = _windows; w != _last_window;) { for (w = _windows; w != _last_window;) {
if (w->window_class == cls) { if (w->window_class == cls) {
DeleteWindow(w); DeleteWindow(w);
w = _windows; w = _windows;
} else } else {
w++; w++;
}
} }
} }
@ -323,12 +320,10 @@ Window *BringWindowToFront(Window *w)
v = _last_window; v = _last_window;
do { do {
if (--v < _windows) if (--v < _windows) return w;
return w;
} while (IsVitalWindow(v)); } while (IsVitalWindow(v));
if (w == v) if (w == v) return w;
return w;
assert(w < v); assert(w < v);
@ -351,9 +346,11 @@ Window *BringWindowToFront(Window *w)
static Window *FindDeletableWindow(void) static Window *FindDeletableWindow(void)
{ {
Window *w; Window *w;
for (w = _windows; w < endof(_windows); w++) { for (w = _windows; w < endof(_windows); w++) {
if (w->window_class != WC_MAIN_WINDOW && !IsVitalWindow(w) && !(w->flags4 & WF_STICKY) ) if (w->window_class != WC_MAIN_WINDOW && !IsVitalWindow(w) && !(w->flags4 & WF_STICKY)) {
return w; return w;
}
} }
return NULL; return NULL;
} }
@ -367,11 +364,10 @@ static Window *FindDeletableWindow(void)
static Window *ForceFindDeletableWindow(void) static Window *ForceFindDeletableWindow(void)
{ {
Window *w; Window *w;
for (w = _windows;; w++) { for (w = _windows;; w++) {
assert(w < _last_window); assert(w < _last_window);
if (w->window_class != WC_MAIN_WINDOW && !IsVitalWindow(w)) return w;
if (w->window_class != WC_MAIN_WINDOW && !IsVitalWindow(w))
return w;
} }
} }
@ -386,17 +382,16 @@ void AssignWidgetToWindow(Window *w, const Widget *widget)
w->original_widget = widget; w->original_widget = widget;
if (widget != NULL) { if (widget != NULL) {
const Widget *wi = widget;
uint index = 1; uint index = 1;
while (wi->type != WWT_LAST) { const Widget* wi;
wi++;
index++;
}
w->widget = realloc(w->widget, sizeof(Widget) * index); for (wi = widget; wi->type != WWT_LAST; wi++) index++;
memcpy(w->widget, widget, sizeof(Widget) * index);
} else w->widget = realloc(w->widget, sizeof(*w->widget) * index);
memcpy(w->widget, widget, sizeof(*w->widget) * index);
} else {
w->widget = NULL; w->widget = NULL;
}
} }
/** Open a new window. If there is no space for a new window, close an open /** Open a new window. If there is no space for a new window, close an open
@ -422,8 +417,7 @@ Window *AllocateWindow(
if (w >= endof(_windows)) { if (w >= endof(_windows)) {
w = FindDeletableWindow(); w = FindDeletableWindow();
if (w == NULL) // no window found, force it! if (w == NULL) w = ForceFindDeletableWindow();
w = ForceFindDeletableWindow();
DeleteWindow(w); DeleteWindow(w);
w = _last_window; w = _last_window;
@ -503,10 +497,9 @@ Window *AllocateWindowAutoPlace2(
} }
x = w->left; x = w->left;
if (x > _screen.width - width) if (x > _screen.width - width) x = _screen.width - width - 20;
x = (_screen.width - width) - 20;
return AllocateWindow(x+10,w->top+10,width,height,proc,cls,widget); return AllocateWindow(x + 10, w->top + 10, width, height, proc, cls, widget);
} }
@ -531,15 +524,15 @@ static bool IsGoodAutoPlace1(int left, int top)
return false; return false;
// Make sure it is not obscured by any window. // Make sure it is not obscured by any window.
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->window_class == WC_MAIN_WINDOW) if (w->window_class == WC_MAIN_WINDOW) continue;
continue;
if (right > w->left && if (right > w->left &&
w->left + w->width > left && w->left + w->width > left &&
bottom > w->top && bottom > w->top &&
w->top + w->height > top) w->top + w->height > top) {
return false; return false;
}
} }
return true; return true;
@ -561,15 +554,15 @@ static bool IsGoodAutoPlace2(int left, int top)
return false; return false;
// Make sure it is not obscured by any window. // Make sure it is not obscured by any window.
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->window_class == WC_MAIN_WINDOW) if (w->window_class == WC_MAIN_WINDOW) continue;
continue;
if (left + width > w->left && if (left + width > w->left &&
w->left + w->width > left && w->left + w->width > left &&
top + height > w->top && top + height > w->top &&
w->top + w->height > top) w->top + w->height > top) {
return false; return false;
}
} }
return true; return true;
@ -585,9 +578,8 @@ static Point GetAutoPlacePosition(int width, int height)
if (IsGoodAutoPlace1(0, 24)) goto ok_pos; if (IsGoodAutoPlace1(0, 24)) goto ok_pos;
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->window_class == WC_MAIN_WINDOW) if (w->window_class == WC_MAIN_WINDOW) continue;
continue;
if (IsGoodAutoPlace1(w->left+w->width+2,w->top)) goto ok_pos; if (IsGoodAutoPlace1(w->left+w->width+2,w->top)) goto ok_pos;
if (IsGoodAutoPlace1(w->left- width-2,w->top)) goto ok_pos; if (IsGoodAutoPlace1(w->left- width-2,w->top)) goto ok_pos;
@ -599,9 +591,8 @@ static Point GetAutoPlacePosition(int width, int height)
if (IsGoodAutoPlace1(w->left+w->width-width,w->top- height-2)) goto ok_pos; if (IsGoodAutoPlace1(w->left+w->width-width,w->top- height-2)) goto ok_pos;
} }
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->window_class == WC_MAIN_WINDOW) if (w->window_class == WC_MAIN_WINDOW) continue;
continue;
if (IsGoodAutoPlace2(w->left+w->width+2,w->top)) goto ok_pos; if (IsGoodAutoPlace2(w->left+w->width+2,w->top)) goto ok_pos;
if (IsGoodAutoPlace2(w->left- width-2,w->top)) goto ok_pos; if (IsGoodAutoPlace2(w->left- width-2,w->top)) goto ok_pos;
@ -613,7 +604,7 @@ static Point GetAutoPlacePosition(int width, int height)
int left=0,top=24; int left=0,top=24;
restart:; restart:;
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->left == left && w->top == top) { if (w->left == left && w->top == top) {
left += 5; left += 5;
top += 5; top += 5;
@ -647,8 +638,7 @@ Window *AllocateWindowDescFront(const WindowDesc *desc, int value)
{ {
Window *w; Window *w;
if (BringWindowToFrontById(desc->cls, value)) if (BringWindowToFrontById(desc->cls, value)) return NULL;
return NULL;
w = AllocateWindowDesc(desc); w = AllocateWindowDesc(desc);
w->window_number = value; w->window_number = value;
return w; return w;
@ -696,11 +686,12 @@ Window *FindWindowFromPt(int x, int y)
{ {
Window *w; Window *w;
for(w=_last_window; w != _windows;) { for (w = _last_window; w != _windows;) {
--w; --w;
if (IS_INSIDE_1D(x, w->left, w->width) && if (IS_INSIDE_1D(x, w->left, w->width) &&
IS_INSIDE_1D(y, w->top, w->height)) IS_INSIDE_1D(y, w->top, w->height)) {
return w; return w;
}
} }
return NULL; return NULL;
@ -755,8 +746,7 @@ static void DecreaseWindowCounters(void)
if (w->flags4&WF_TIMEOUT_MASK && !(--w->flags4&WF_TIMEOUT_MASK)) { if (w->flags4&WF_TIMEOUT_MASK && !(--w->flags4&WF_TIMEOUT_MASK)) {
CallWindowEventNP(w, WE_TIMEOUT); CallWindowEventNP(w, WE_TIMEOUT);
if (w->desc_flags & WDF_UNCLICK_BUTTONS) if (w->desc_flags & WDF_UNCLICK_BUTTONS) UnclickWindowButtons(w);
UnclickWindowButtons(w);
} }
} }
} }
@ -771,11 +761,10 @@ static void HandlePlacePresize(void)
Window *w; Window *w;
WindowEvent e; WindowEvent e;
if (_special_mouse_mode != WSM_PRESIZE) if (_special_mouse_mode != WSM_PRESIZE) return;
return;
if ((w = GetCallbackWnd()) == NULL) w = GetCallbackWnd();
return; if (w == NULL) return;
e.place.pt = GetTileBelowCursor(); e.place.pt = GetTileBelowCursor();
if (e.place.pt.x == -1) { if (e.place.pt.x == -1) {
@ -792,17 +781,15 @@ static bool HandleDragDrop(void)
Window *w; Window *w;
WindowEvent e; WindowEvent e;
if (_special_mouse_mode != WSM_DRAGDROP) if (_special_mouse_mode != WSM_DRAGDROP) return true;
return true;
if (_left_button_down) if (_left_button_down) return false;
return false;
w = GetCallbackWnd(); w = GetCallbackWnd();
ResetObjectToPlace(); ResetObjectToPlace();
if (w) { if (w != NULL) {
// send an event in client coordinates. // send an event in client coordinates.
e.event = WE_DRAGDROP; e.event = WE_DRAGDROP;
e.dragdrop.pt.x = _cursor.pos.x - w->left; e.dragdrop.pt.x = _cursor.pos.x - w->left;
@ -818,8 +805,7 @@ static bool HandlePopupMenu(void)
Window *w; Window *w;
WindowEvent e; WindowEvent e;
if (!_popup_menu_active) if (!_popup_menu_active) return true;
return true;
w = FindWindowById(WC_TOOLBAR_MENU, 0); w = FindWindowById(WC_TOOLBAR_MENU, 0);
if (w == NULL) { if (w == NULL) {
@ -850,16 +836,15 @@ static bool HandleMouseOver(void)
w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y); w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
// We changed window, put a MOUSEOVER event to the last window // We changed window, put a MOUSEOVER event to the last window
if (last_w && last_w != w) { if (last_w != NULL && last_w != w) {
e.event = WE_MOUSEOVER; e.event = WE_MOUSEOVER;
e.mouseover.pt.x = -1; e.mouseover.pt.x = -1;
e.mouseover.pt.y = -1; e.mouseover.pt.y = -1;
if (last_w->wndproc) if (last_w->wndproc) last_w->wndproc(last_w, &e);
last_w->wndproc(last_w, &e);
} }
last_w = w; last_w = w;
if (w) { if (w != NULL) {
// send an event in client coordinates. // send an event in client coordinates.
e.event = WE_MOUSEOVER; e.event = WE_MOUSEOVER;
e.mouseover.pt.x = _cursor.pos.x - w->left; e.mouseover.pt.x = _cursor.pos.x - w->left;
@ -881,8 +866,7 @@ static bool HandleWindowDragging(void)
{ {
Window *w; Window *w;
// Get out immediately if no window is being dragged at all. // Get out immediately if no window is being dragged at all.
if (!_dragging_window) if (!_dragging_window) return true;
return true;
// Otherwise find the window... // Otherwise find the window...
for (w = _windows; w != _last_window; w++) { for (w = _windows; w != _last_window; w++) {
@ -998,12 +982,13 @@ static bool HandleWindowDragging(void)
} else { } else {
if (nx + t->left > v->left - 13 && if (nx + t->left > v->left - 13 &&
nx + t->right < v_right + 13) { nx + t->right < v_right + 13) {
if (w->top >= v_bottom) if (w->top >= v_bottom) {
ny = v_bottom; ny = v_bottom;
else if (w->left < nx) } else if (w->left < nx) {
nx = v->left - 13 - t->left; nx = v->left - 13 - t->left;
else } else {
nx = v_right + 13 - t->right; nx = v_right + 13 - t->right;
}
} }
} }
} }
@ -1033,11 +1018,9 @@ static bool HandleWindowDragging(void)
y = _cursor.pos.y - _drag_delta.y; y = _cursor.pos.y - _drag_delta.y;
/* X and Y has to go by step.. calculate it */ /* X and Y has to go by step.. calculate it */
if (w->resize.step_width > 1) if (w->resize.step_width > 1) x = x - (x % w->resize.step_width);
x = x - (x % (int)w->resize.step_width);
if (w->resize.step_height > 1) if (w->resize.step_height > 1) y = y - (y % w->resize.step_height);
y = y - (y % (int)w->resize.step_height);
/* Check if we don't go below the minimum set size */ /* Check if we don't go below the minimum set size */
if ((int)w->width + x < (int)w->resize.width) if ((int)w->width + x < (int)w->resize.width)
@ -1046,8 +1029,7 @@ static bool HandleWindowDragging(void)
y = w->resize.height - w->height; y = w->resize.height - w->height;
/* Window already on size */ /* Window already on size */
if (x == 0 && y == 0) if (x == 0 && y == 0) return false;
return false;
/* Now find the new cursor pos.. this is NOT _cursor, because /* Now find the new cursor pos.. this is NOT _cursor, because
we move in steps. */ we move in steps. */
@ -1087,10 +1069,8 @@ static bool HandleWindowDragging(void)
} }
/* We resized at least 1 widget, so let's rezise the window totally */ /* We resized at least 1 widget, so let's rezise the window totally */
if (resize_width) if (resize_width) w->width = x + w->width;
w->width = x + w->width; if (resize_height) w->height = y + w->height;
if (resize_height)
w->height = y + w->height;
} }
e.event = WE_RESIZE; e.event = WE_RESIZE;
@ -1145,11 +1125,10 @@ static bool HandleScrollbarScrolling(void)
Scrollbar *sb; Scrollbar *sb;
// Get out quickly if no item is being scrolled // Get out quickly if no item is being scrolled
if (!_scrolling_scrollbar) if (!_scrolling_scrollbar) return true;
return true;
// Find the scrolling window // Find the scrolling window
for(w=_windows; w != _last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->flags4 & WF_SCROLL_MIDDLE) { if (w->flags4 & WF_SCROLL_MIDDLE) {
// Abort if no button is clicked any more. // Abort if no button is clicked any more.
if (!_left_button_down) { if (!_left_button_down) {
@ -1189,8 +1168,7 @@ static bool HandleViewportScroll(void)
ViewPort *vp; ViewPort *vp;
int dx,dy, x, y, sub; int dx,dy, x, y, sub;
if (!_scrolling_viewport) if (!_scrolling_viewport) return true;
return true;
if (!_right_button_down) { if (!_right_button_down) {
stop_capt:; stop_capt:;
@ -1249,10 +1227,22 @@ stop_capt:;
hy = (w->widget[4].bottom - w->widget[4].top ) / 2; hy = (w->widget[4].bottom - w->widget[4].top ) / 2;
hvx = hx * -4 + hy * 8; hvx = hx * -4 + hy * 8;
hvy = hx * 4 + hy * 8; hvy = hx * 4 + hy * 8;
if (x < -hvx) { x = -hvx; sub = 0; } if (x < -hvx) {
if (x > (int)MapMaxX() * 16 - hvx) { x = MapMaxX() * 16 - hvx; sub = 0; } x = -hvx;
if (y < -hvy) { y = -hvy; sub = 0; } sub = 0;
if (y > (int)MapMaxY() * 16 - hvy) { y = MapMaxY() * 16 - hvy; sub = 0; } }
if (x > (int)MapMaxX() * 16 - hvx) {
x = MapMaxX() * 16 - hvx;
sub = 0;
}
if (y < -hvy) {
y = -hvy;
sub = 0;
}
if (y > (int)MapMaxY() * 16 - hvy) {
y = MapMaxY() * 16 - hvy;
sub = 0;
}
WP(w,smallmap_d).scroll_x = x; WP(w,smallmap_d).scroll_x = x;
WP(w,smallmap_d).scroll_y = y; WP(w,smallmap_d).scroll_y = y;
@ -1269,20 +1259,27 @@ static Window *MaybeBringWindowToFront(Window *w)
{ {
Window *u; Window *u;
if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || if (w->window_class == WC_MAIN_WINDOW ||
w->window_class == WC_TOOLTIPS || w->window_class == WC_DROPDOWN_MENU) IsVitalWindow(w) ||
return w; w->window_class == WC_TOOLTIPS ||
w->window_class == WC_DROPDOWN_MENU) {
return w;
}
for (u = w; ++u != _last_window;) { for (u = w; ++u != _last_window;) {
if (u->window_class == WC_MAIN_WINDOW || IsVitalWindow(u) || if (u->window_class == WC_MAIN_WINDOW ||
u->window_class == WC_TOOLTIPS || u->window_class == WC_DROPDOWN_MENU) IsVitalWindow(u) ||
continue; u->window_class == WC_TOOLTIPS ||
u->window_class == WC_DROPDOWN_MENU) {
continue;
}
if (w->left + w->width <= u->left || if (w->left + w->width <= u->left ||
u->left + u->width <= w->left || u->left + u->width <= w->left ||
w->top + w->height <= u->top || w->top + w->height <= u->top ||
u->top + u->height <= w->top) u->top + u->height <= w->top) {
continue; continue;
}
return BringWindowToFront(w); return BringWindowToFront(w);
} }
@ -1337,18 +1334,26 @@ static void HandleKeypress(uint32 key)
we.keypress.cont = true; we.keypress.cont = true;
// check if we have a query string window open before allowing hotkeys // check if we have a query string window open before allowing hotkeys
if(FindWindowById(WC_QUERY_STRING, 0)!=NULL || FindWindowById(WC_SEND_NETWORK_MSG, 0)!=NULL || FindWindowById(WC_CONSOLE, 0)!=NULL || FindWindowById(WC_SAVELOAD, 0)!=NULL) if (FindWindowById(WC_QUERY_STRING, 0) != NULL ||
FindWindowById(WC_SEND_NETWORK_MSG, 0) != NULL ||
FindWindowById(WC_CONSOLE, 0) != NULL ||
FindWindowById(WC_SAVELOAD, 0) != NULL) {
query_open = true; query_open = true;
}
// Call the event, start with the uppermost window. // Call the event, start with the uppermost window.
for(w=_last_window; w != _windows;) { for (w = _last_window; w != _windows;) {
--w; --w;
// if a query window is open, only call the event for certain window types // if a query window is open, only call the event for certain window types
if(query_open && w->window_class!=WC_QUERY_STRING && w->window_class!=WC_SEND_NETWORK_MSG && w->window_class!=WC_CONSOLE && w->window_class!=WC_SAVELOAD) if (query_open &&
w->window_class != WC_QUERY_STRING &&
w->window_class != WC_SEND_NETWORK_MSG &&
w->window_class != WC_CONSOLE &&
w->window_class != WC_SAVELOAD) {
continue; continue;
}
w->wndproc(w, &we); w->wndproc(w, &we);
if (!we.keypress.cont) if (!we.keypress.cont) break;
break;
} }
if (we.keypress.cont) { if (we.keypress.cont) {
@ -1370,26 +1375,13 @@ static void MouseLoop(int click, int mousewheel)
DecreaseWindowCounters(); DecreaseWindowCounters();
HandlePlacePresize(); HandlePlacePresize();
UpdateTileSelection(); UpdateTileSelection();
if (!VpHandlePlaceSizingDrag()) if (!VpHandlePlaceSizingDrag()) return;
return; if (!HandleDragDrop()) return;
if (!HandlePopupMenu()) return;
if (!HandleDragDrop()) if (!HandleWindowDragging()) return;
return; if (!HandleScrollbarScrolling()) return;
if (!HandleViewportScroll()) return;
if (!HandlePopupMenu()) if (!HandleMouseOver()) return;
return;
if (!HandleWindowDragging())
return;
if (!HandleScrollbarScrolling())
return;
if (!HandleViewportScroll())
return;
if (!HandleMouseOver())
return;
x = _cursor.pos.x; x = _cursor.pos.x;
y = _cursor.pos.y; y = _cursor.pos.y;
@ -1422,17 +1414,18 @@ static void MouseLoop(int click, int mousewheel)
} }
w = FindWindowFromPt(x, y); w = FindWindowFromPt(x, y);
if (w == NULL) if (w == NULL) return;
return;
w = MaybeBringWindowToFront(w); w = MaybeBringWindowToFront(w);
vp = IsPtInWindowViewport(w, x, y); vp = IsPtInWindowViewport(w, x, y);
if (vp != NULL) { if (vp != NULL) {
if (_game_mode == GM_MENU) if (_game_mode == GM_MENU) return;
return;
// only allow zooming in-out in main window, or in viewports // only allow zooming in-out in main window, or in viewports
if ( mousewheel && !(w->flags4 & WF_DISABLE_VP_SCROLL) && if (mousewheel &&
(w->window_class == WC_MAIN_WINDOW || w->window_class == WC_EXTRA_VIEW_PORT) ) { !(w->flags4 & WF_DISABLE_VP_SCROLL) && (
w->window_class == WC_MAIN_WINDOW ||
w->window_class == WC_EXTRA_VIEW_PORT
)) {
ZoomInOrOutToCursorWindow(mousewheel < 0,w); ZoomInOrOutToCursorWindow(mousewheel < 0,w);
} }
@ -1509,9 +1502,9 @@ void UpdateWindows(void)
Window *w; Window *w;
int t; int t;
t = _we4_timer + 1;
if ((t=_we4_timer+1) >= 100) { if (t >= 100) {
for(w = _last_window; w != _windows;) { for (w = _last_window; w != _windows;) {
w--; w--;
CallWindowEventNP(w, WE_4); CallWindowEventNP(w, WE_4);
} }
@ -1519,7 +1512,7 @@ void UpdateWindows(void)
} }
_we4_timer = t; _we4_timer = t;
for(w = _last_window; w != _windows;) { for (w = _last_window; w != _windows;) {
w--; w--;
if (w->flags4 & WF_WHITE_BORDER_MASK) { if (w->flags4 & WF_WHITE_BORDER_MASK) {
w->flags4 -= WF_WHITE_BORDER_ONE; w->flags4 -= WF_WHITE_BORDER_ONE;
@ -1531,9 +1524,8 @@ void UpdateWindows(void)
DrawDirtyBlocks(); DrawDirtyBlocks();
for(w = _windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->viewport != NULL) if (w->viewport != NULL) UpdateViewportPosition(w);
UpdateViewportPosition(w);
} }
DrawTextMessage(); DrawTextMessage();
// Redraw mouse cursor in case it was hidden // Redraw mouse cursor in case it was hidden
@ -1546,8 +1538,10 @@ int GetMenuItemIndex(const Window *w, int x, int y)
if ((x -= w->left) >= 0 && x < w->width && (y -= w->top + 1) >= 0) { if ((x -= w->left) >= 0 && x < w->width && (y -= w->top + 1) >= 0) {
y /= 10; y /= 10;
if (y < WP(w,menu_d).item_count && !HASBIT(WP(w,menu_d).disabled_items, y)) if (y < WP(w, const menu_d).item_count &&
!HASBIT(WP(w, const menu_d).disabled_items, y)) {
return y; return y;
}
} }
return -1; return -1;
} }
@ -1556,9 +1550,8 @@ void InvalidateWindow(byte cls, WindowNumber number)
{ {
Window *w; Window *w;
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->window_class==cls && w->window_number==number) if (w->window_class == cls && w->window_number == number) SetWindowDirty(w);
SetWindowDirty(w);
} }
} }
@ -1576,8 +1569,8 @@ void InvalidateWindowWidget(byte cls, WindowNumber number, byte widget_index)
{ {
const Window* w; const Window* w;
for(w=_windows; w!=_last_window; w++) { for (w = _windows; w != _last_window; w++) {
if (w->window_class==cls && w->window_number==number) { if (w->window_class == cls && w->window_number == number) {
InvalidateWidget(w, widget_index); InvalidateWidget(w, widget_index);
} }
} }
@ -1586,9 +1579,9 @@ void InvalidateWindowWidget(byte cls, WindowNumber number, byte widget_index)
void InvalidateWindowClasses(byte cls) void InvalidateWindowClasses(byte cls)
{ {
const Window* w; const Window* w;
for(w=_windows; w!=_last_window; w++) {
if (w->window_class==cls) for (w = _windows; w != _last_window; w++) {
SetWindowDirty(w); if (w->window_class == cls) SetWindowDirty(w);
} }
} }
@ -1596,7 +1589,8 @@ void InvalidateWindowClasses(byte cls)
void CallWindowTickEvent(void) void CallWindowTickEvent(void)
{ {
Window *w; Window *w;
for(w=_last_window; w != _windows;) {
for (w = _last_window; w != _windows;) {
--w; --w;
CallWindowEventNP(w, WE_TICK); CallWindowEventNP(w, WE_TICK);
} }
@ -1605,7 +1599,8 @@ void CallWindowTickEvent(void)
void DeleteNonVitalWindows(void) void DeleteNonVitalWindows(void)
{ {
Window *w; Window *w;
for(w=_windows; w!=_last_window;) {
for (w = _windows; w != _last_window;) {
if (w->window_class != WC_MAIN_WINDOW && if (w->window_class != WC_MAIN_WINDOW &&
w->window_class != WC_SELECT_GAME && w->window_class != WC_SELECT_GAME &&
w->window_class != WC_MAIN_TOOLBAR && w->window_class != WC_MAIN_TOOLBAR &&
@ -1629,6 +1624,7 @@ void DeleteNonVitalWindows(void)
void DeleteAllNonVitalWindows(void) void DeleteAllNonVitalWindows(void)
{ {
Window *w; Window *w;
// Delete every window except for stickied ones // Delete every window except for stickied ones
DeleteNonVitalWindows(); DeleteNonVitalWindows();
// Delete all sticked windows // Delete all sticked windows
@ -1668,7 +1664,7 @@ void RelocateAllWindows(int neww, int newh)
{ {
Window *w; Window *w;
for(w=_windows; w!= _last_window ;w++) { for (w = _windows; w != _last_window; w++) {
int left, top; int left, top;
if (w->window_class == WC_MAIN_WINDOW) { if (w->window_class == WC_MAIN_WINDOW) {
@ -1704,7 +1700,7 @@ void RelocateAllWindows(int neww, int newh)
if (top + (w->height>>1) >= newh) top = newh - w->height; if (top + (w->height>>1) >= newh) top = newh - w->height;
} }
if (w->viewport) { if (w->viewport != NULL) {
w->viewport->left += left - w->left; w->viewport->left += left - w->left;
w->viewport->top += top - w->top; w->viewport->top += top - w->top;
} }