tunnelbridge_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00016 #include "stdafx.h"
00017 #include "newgrf_object.h"
00018 #include "viewport_func.h"
00019 #include "cmd_helper.h"
00020 #include "command_func.h"
00021 #include "town.h"
00022 #include "train.h"
00023 #include "ship.h"
00024 #include "roadveh.h"
00025 #include "pathfinder/yapf/yapf_cache.h"
00026 #include "newgrf_sound.h"
00027 #include "autoslope.h"
00028 #include "tunnelbridge_map.h"
00029 #include "strings_func.h"
00030 #include "date_func.h"
00031 #include "clear_func.h"
00032 #include "vehicle_func.h"
00033 #include "sound_func.h"
00034 #include "tunnelbridge.h"
00035 #include "cheat_type.h"
00036 #include "elrail_func.h"
00037 #include "pbs.h"
00038 #include "company_base.h"
00039 #include "newgrf_railtype.h"
00040 #include "object_base.h"
00041 #include "water.h"
00042 #include "company_gui.h"
00043 
00044 #include "table/strings.h"
00045 #include "table/bridge_land.h"
00046 
00047 BridgeSpec _bridge[MAX_BRIDGES]; 
00048 TileIndex _build_tunnel_endtile; 
00049 
00051 static const int BRIDGE_Z_START = 3;
00052 
00054 void ResetBridges()
00055 {
00056   /* First, free sprite table data */
00057   for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
00058     if (_bridge[i].sprite_table != NULL) {
00059       for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
00060       free(_bridge[i].sprite_table);
00061     }
00062   }
00063 
00064   /* Then, wipe out current bidges */
00065   memset(&_bridge, 0, sizeof(_bridge));
00066   /* And finally, reinstall default data */
00067   memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
00068 }
00069 
00076 int CalcBridgeLenCostFactor(int length)
00077 {
00078   if (length < 2) return length;
00079 
00080   length -= 2;
00081   int sum = 2;
00082   for (int delta = 1;; delta++) {
00083     for (int count = 0; count < delta; count++) {
00084       if (length == 0) return sum;
00085       sum += delta;
00086       length--;
00087     }
00088   }
00089 }
00090 
00097 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
00098 {
00099   if (tileh == SLOPE_FLAT ||
00100       ((tileh == SLOPE_NE || tileh == SLOPE_SW) && axis == AXIS_X) ||
00101       ((tileh == SLOPE_NW || tileh == SLOPE_SE) && axis == AXIS_Y)) return FOUNDATION_NONE;
00102 
00103   return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
00104 }
00105 
00113 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
00114 {
00115   ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
00116   /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
00117   return (tileh != SLOPE_FLAT);
00118 }
00119 
00120 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
00121 {
00122   const BridgeSpec *bridge = GetBridgeSpec(index);
00123   assert(table < BRIDGE_PIECE_INVALID);
00124   if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
00125     return _bridge_sprite_table[index][table];
00126   } else {
00127     return bridge->sprite_table[table];
00128   }
00129 }
00130 
00131 
00140 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, int *z)
00141 {
00142   Foundation f = GetBridgeFoundation(*tileh, axis);
00143   *z += ApplyFoundationToSlope(f, tileh);
00144 
00145   Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
00146   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00147 
00148   if (f == FOUNDATION_NONE) return CommandCost();
00149 
00150   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00151 }
00152 
00161 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, int *z)
00162 {
00163   Foundation f = GetBridgeFoundation(*tileh, axis);
00164   *z += ApplyFoundationToSlope(f, tileh);
00165 
00166   Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
00167   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00168 
00169   if (f == FOUNDATION_NONE) return CommandCost();
00170 
00171   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00172 }
00173 
00180 CommandCost CheckBridgeAvailability(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
00181 {
00182   if (flags & DC_QUERY_COST) {
00183     if (bridge_len <= _settings_game.construction.max_bridge_length) return CommandCost();
00184     return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00185   }
00186 
00187   if (bridge_type >= MAX_BRIDGES) return CMD_ERROR;
00188 
00189   const BridgeSpec *b = GetBridgeSpec(bridge_type);
00190   if (b->avail_year > _cur_year) return CMD_ERROR;
00191 
00192   uint max = min(b->max_length, _settings_game.construction.max_bridge_length);
00193 
00194   if (b->min_length > bridge_len) return CMD_ERROR;
00195   if (bridge_len <= max) return CommandCost();
00196   return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00197 }
00198 
00211 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00212 {
00213   CompanyID company = _current_company;
00214 
00215   RailType railtype = INVALID_RAILTYPE;
00216   RoadTypes roadtypes = ROADTYPES_NONE;
00217 
00218   /* unpack parameters */
00219   BridgeType bridge_type = GB(p2, 0, 8);
00220 
00221   if (!IsValidTile(p1)) return_cmd_error(STR_ERROR_BRIDGE_THROUGH_MAP_BORDER);
00222 
00223   TransportType transport_type = Extract<TransportType, 15, 2>(p2);
00224 
00225   /* type of bridge */
00226   switch (transport_type) {
00227     case TRANSPORT_ROAD:
00228       roadtypes = Extract<RoadTypes, 8, 2>(p2);
00229       if (!HasExactlyOneBit(roadtypes) || !HasRoadTypesAvail(company, roadtypes)) return CMD_ERROR;
00230       break;
00231 
00232     case TRANSPORT_RAIL:
00233       railtype = Extract<RailType, 8, 4>(p2);
00234       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00235       break;
00236 
00237     case TRANSPORT_WATER:
00238       break;
00239 
00240     default:
00241       /* Airports don't have bridges. */
00242       return CMD_ERROR;
00243   }
00244   TileIndex tile_start = p1;
00245   TileIndex tile_end = end_tile;
00246 
00247   if (company == OWNER_DEITY) {
00248     if (transport_type != TRANSPORT_ROAD) return CMD_ERROR;
00249     const Town *town = CalcClosestTownFromTile(tile_start);
00250 
00251     company = OWNER_TOWN;
00252 
00253     /* If we are not within a town, we are not owned by the town */
00254     if (town == NULL || DistanceSquare(tile_start, town->xy) > town->squared_town_zone_radius[HZB_TOWN_EDGE]) {
00255       company = OWNER_NONE;
00256     }
00257   }
00258 
00259   if (tile_start == tile_end) {
00260     return_cmd_error(STR_ERROR_CAN_T_START_AND_END_ON);
00261   }
00262 
00263   Axis direction;
00264   if (TileX(tile_start) == TileX(tile_end)) {
00265     direction = AXIS_Y;
00266   } else if (TileY(tile_start) == TileY(tile_end)) {
00267     direction = AXIS_X;
00268   } else {
00269     return_cmd_error(STR_ERROR_START_AND_END_MUST_BE_IN);
00270   }
00271 
00272   if (tile_end < tile_start) Swap(tile_start, tile_end);
00273 
00274   uint bridge_len = GetTunnelBridgeLength(tile_start, tile_end);
00275   if (transport_type != TRANSPORT_WATER) {
00276     /* set and test bridge length, availability */
00277     CommandCost ret = CheckBridgeAvailability(bridge_type, bridge_len, flags);
00278     if (ret.Failed()) return ret;
00279   } else {
00280     if (bridge_len > _settings_game.construction.max_bridge_length) return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00281   }
00282 
00283   int z_start;
00284   int z_end;
00285   Slope tileh_start = GetTileSlope(tile_start, &z_start);
00286   Slope tileh_end = GetTileSlope(tile_end, &z_end);
00287   bool pbs_reservation = false;
00288 
00289   CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
00290   CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end,   &z_end);
00291 
00292   /* Aqueducts can't be built of flat land. */
00293   if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00294   if (z_start != z_end) return_cmd_error(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT);
00295 
00296   CommandCost cost(EXPENSES_CONSTRUCTION);
00297   Owner owner;
00298   if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
00299       GetOtherBridgeEnd(tile_start) == tile_end &&
00300       GetTunnelBridgeTransportType(tile_start) == transport_type) {
00301     /* Replace a current bridge. */
00302 
00303     /* If this is a railway bridge, make sure the railtypes match. */
00304     if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
00305       return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00306     }
00307 
00308     /* Do not replace town bridges with lower speed bridges. */
00309     if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
00310         GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed) {
00311       Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
00312 
00313       if (t == NULL) {
00314         return CMD_ERROR;
00315       } else {
00316         SetDParam(0, t->index);
00317         return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00318       }
00319     }
00320 
00321     /* Do not replace the bridge with the same bridge type. */
00322     if (!(flags & DC_QUERY_COST) && bridge_type == GetBridgeType(tile_start)) {
00323       return_cmd_error(STR_ERROR_ALREADY_BUILT);
00324     }
00325 
00326     /* Do not allow replacing another company's bridges. */
00327     if (!IsTileOwner(tile_start, company) && !IsTileOwner(tile_start, OWNER_TOWN)) {
00328       return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
00329     }
00330 
00331     cost.AddCost((bridge_len + 1) * _price[PR_CLEAR_BRIDGE]); // The cost of clearing the current bridge.
00332     owner = GetTileOwner(tile_start);
00333 
00334     switch (transport_type) {
00335       case TRANSPORT_RAIL:
00336         /* Keep the reservation, the path stays valid. */
00337         pbs_reservation = HasTunnelBridgeReservation(tile_start);
00338         break;
00339 
00340       case TRANSPORT_ROAD:
00341         /* Do not remove road types when upgrading a bridge */
00342         roadtypes |= GetRoadTypes(tile_start);
00343         break;
00344 
00345       default: break;
00346     }
00347   } else {
00348     /* Build a new bridge. */
00349 
00350     bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
00351 
00352     /* Try and clear the start landscape */
00353     CommandCost ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00354     if (ret.Failed()) return ret;
00355     cost = ret;
00356 
00357     if (terraform_cost_north.Failed() || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00358     cost.AddCost(terraform_cost_north);
00359 
00360     /* Try and clear the end landscape */
00361     ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00362     if (ret.Failed()) return ret;
00363     cost.AddCost(ret);
00364 
00365     /* false - end tile slope check */
00366     if (terraform_cost_south.Failed() || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00367     cost.AddCost(terraform_cost_south);
00368 
00369     const TileIndex heads[] = {tile_start, tile_end};
00370     for (int i = 0; i < 2; i++) {
00371       if (MayHaveBridgeAbove(heads[i])) {
00372         if (IsBridgeAbove(heads[i])) {
00373           TileIndex north_head = GetNorthernBridgeEnd(heads[i]);
00374 
00375           if (direction == GetBridgeAxis(heads[i])) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00376 
00377           if (z_start + 1 == GetBridgeHeight(north_head)) {
00378             return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00379           }
00380         }
00381       }
00382     }
00383 
00384     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00385     for (TileIndex tile = tile_start + delta; tile != tile_end; tile += delta) {
00386       if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN);
00387 
00388       if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00389         /* Disallow crossing bridges for the time being */
00390         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00391       }
00392 
00393       switch (GetTileType(tile)) {
00394         case MP_WATER:
00395           if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
00396           break;
00397 
00398         case MP_RAILWAY:
00399           if (!IsPlainRail(tile)) goto not_valid_below;
00400           break;
00401 
00402         case MP_ROAD:
00403           if (IsRoadDepot(tile)) goto not_valid_below;
00404           break;
00405 
00406         case MP_TUNNELBRIDGE:
00407           if (IsTunnel(tile)) break;
00408           if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
00409           if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
00410           break;
00411 
00412         case MP_OBJECT: {
00413           const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
00414           if ((spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) == 0) goto not_valid_below;
00415           if (GetTileMaxZ(tile) + spec->height > z_start) goto not_valid_below;
00416           break;
00417         }
00418 
00419         case MP_CLEAR:
00420           break;
00421 
00422         default:
00423   not_valid_below:;
00424           /* try and clear the middle landscape */
00425           ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00426           if (ret.Failed()) return ret;
00427           cost.AddCost(ret);
00428           break;
00429       }
00430 
00431       if (flags & DC_EXEC) {
00432         /* We do this here because when replacing a bridge with another
00433          * type calling SetBridgeMiddle isn't needed. After all, the
00434          * tile alread has the has_bridge_above bits set. */
00435         SetBridgeMiddle(tile, direction);
00436       }
00437     }
00438 
00439     owner = company;
00440   }
00441 
00442   /* do the drill? */
00443   if (flags & DC_EXEC) {
00444     DiagDirection dir = AxisToDiagDir(direction);
00445 
00446     Company *c = Company::GetIfValid(owner);
00447     switch (transport_type) {
00448       case TRANSPORT_RAIL:
00449         /* Add to company infrastructure count if building a new bridge. */
00450         if (!IsBridgeTile(tile_start) && c != NULL) c->infrastructure.rail[railtype] += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
00451         MakeRailBridgeRamp(tile_start, owner, bridge_type, dir,                 railtype);
00452         MakeRailBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), railtype);
00453         SetTunnelBridgeReservation(tile_start, pbs_reservation);
00454         SetTunnelBridgeReservation(tile_end,   pbs_reservation);
00455         break;
00456 
00457       case TRANSPORT_ROAD:
00458         if (c != NULL) {
00459           /* Add all new road types to the company infrastructure counter. */
00460           RoadType new_rt;
00461           FOR_EACH_SET_ROADTYPE(new_rt, roadtypes ^ (IsBridgeTile(tile_start) ? GetRoadTypes(tile_start) : ROADTYPES_NONE)) {
00462             /* A full diagonal road tile has two road bits. */
00463             Company::Get(owner)->infrastructure.road[new_rt] += (bridge_len + 2) * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
00464           }
00465         }
00466         MakeRoadBridgeRamp(tile_start, owner, bridge_type, dir,                 roadtypes);
00467         MakeRoadBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), roadtypes);
00468         break;
00469 
00470       case TRANSPORT_WATER:
00471         if (!IsBridgeTile(tile_start) && c != NULL) c->infrastructure.water += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
00472         MakeAqueductBridgeRamp(tile_start, owner, dir);
00473         MakeAqueductBridgeRamp(tile_end,   owner, ReverseDiagDir(dir));
00474         break;
00475 
00476       default:
00477         NOT_REACHED();
00478     }
00479 
00480     /* Mark all tiles dirty */
00481     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00482     for (TileIndex tile = tile_start; tile <= tile_end; tile += delta) {
00483       MarkTileDirtyByTile(tile);
00484     }
00485     DirtyCompanyInfrastructureWindows(owner);
00486   }
00487 
00488   if ((flags & DC_EXEC) && transport_type == TRANSPORT_RAIL) {
00489     Track track = AxisToTrack(direction);
00490     AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, company);
00491     YapfNotifyTrackLayoutChange(tile_start, track);
00492   }
00493 
00494   /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
00495    * It's unnecessary to execute this command every time for every bridge. So it is done only
00496    * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
00497    */
00498   Company *c = Company::GetIfValid(company);
00499   if (!(flags & DC_QUERY_COST) || (c != NULL && c->is_ai)) {
00500     bridge_len += 2; // begin and end tiles/ramps
00501 
00502     switch (transport_type) {
00503       case TRANSPORT_ROAD: cost.AddCost(bridge_len * _price[PR_BUILD_ROAD] * 2 * CountBits(roadtypes)); break;
00504       case TRANSPORT_RAIL: cost.AddCost(bridge_len * RailBuildCost(railtype)); break;
00505       default: break;
00506     }
00507 
00508     if (c != NULL) bridge_len = CalcBridgeLenCostFactor(bridge_len);
00509 
00510     if (transport_type != TRANSPORT_WATER) {
00511       cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
00512     } else {
00513       /* Aqueducts use a separate base cost. */
00514       cost.AddCost((int64)bridge_len * _price[PR_BUILD_AQUEDUCT]);
00515     }
00516 
00517   }
00518 
00519   return cost;
00520 }
00521 
00522 
00533 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00534 {
00535   CompanyID company = _current_company;
00536 
00537   TransportType transport_type = Extract<TransportType, 8, 2>(p1);
00538 
00539   RailType railtype = INVALID_RAILTYPE;
00540   RoadTypes rts = ROADTYPES_NONE;
00541   _build_tunnel_endtile = 0;
00542   switch (transport_type) {
00543     case TRANSPORT_RAIL:
00544       railtype = Extract<RailType, 0, 4>(p1);
00545       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00546       break;
00547 
00548     case TRANSPORT_ROAD:
00549       rts = Extract<RoadTypes, 0, 2>(p1);
00550       if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(company, rts)) return CMD_ERROR;
00551       break;
00552 
00553     default: return CMD_ERROR;
00554   }
00555 
00556   if (company == OWNER_DEITY) {
00557     if (transport_type != TRANSPORT_ROAD) return CMD_ERROR;
00558     const Town *town = CalcClosestTownFromTile(start_tile);
00559 
00560     company = OWNER_TOWN;
00561 
00562     /* If we are not within a town, we are not owned by the town */
00563     if (town == NULL || DistanceSquare(start_tile, town->xy) > town->squared_town_zone_radius[HZB_TOWN_EDGE]) {
00564       company = OWNER_NONE;
00565     }
00566   }
00567 
00568   int start_z;
00569   int end_z;
00570   Slope start_tileh = GetTileSlope(start_tile, &start_z);
00571   DiagDirection direction = GetInclinedSlopeDirection(start_tileh);
00572   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
00573 
00574   if (HasTileWaterGround(start_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00575 
00576   CommandCost ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00577   if (ret.Failed()) return ret;
00578 
00579   /* XXX - do NOT change 'ret' in the loop, as it is used as the price
00580    * for the clearing of the entrance of the tunnel. Assigning it to
00581    * cost before the loop will yield different costs depending on start-
00582    * position, because of increased-cost-by-length: 'cost += cost >> 3' */
00583 
00584   TileIndexDiff delta = TileOffsByDiagDir(direction);
00585   DiagDirection tunnel_in_way_dir;
00586   if (DiagDirToAxis(direction) == AXIS_Y) {
00587     tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
00588   } else {
00589     tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
00590   }
00591 
00592   TileIndex end_tile = start_tile;
00593 
00594   /* Tile shift coeficient. Will decrease for very long tunnels to avoid exponential growth of price*/
00595   int tiles_coef = 3;
00596   /* Number of tiles from start of tunnel */
00597   int tiles = 0;
00598   /* Number of tiles at which the cost increase coefficient per tile is halved */
00599   int tiles_bump = 25;
00600 
00601   CommandCost cost(EXPENSES_CONSTRUCTION);
00602   Slope end_tileh;
00603   for (;;) {
00604     end_tile += delta;
00605     if (!IsValidTile(end_tile)) return_cmd_error(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
00606     end_tileh = GetTileSlope(end_tile, &end_z);
00607 
00608     if (start_z == end_z) break;
00609 
00610     if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
00611       return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
00612     }
00613 
00614     tiles++;
00615     if (tiles == tiles_bump) {
00616       tiles_coef++;
00617       tiles_bump *= 2;
00618     }
00619 
00620     cost.AddCost(_price[PR_BUILD_TUNNEL]);
00621     cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
00622   }
00623 
00624   /* Add the cost of the entrance */
00625   cost.AddCost(_price[PR_BUILD_TUNNEL]);
00626   cost.AddCost(ret);
00627 
00628   /* if the command fails from here on we want the end tile to be highlighted */
00629   _build_tunnel_endtile = end_tile;
00630 
00631   if (tiles > _settings_game.construction.max_tunnel_length) return_cmd_error(STR_ERROR_TUNNEL_TOO_LONG);
00632 
00633   if (HasTileWaterGround(end_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00634 
00635   /* Clear the tile in any case */
00636   ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00637   if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
00638   cost.AddCost(ret);
00639 
00640   /* slope of end tile must be complementary to the slope of the start tile */
00641   if (end_tileh != ComplementSlope(start_tileh)) {
00642     /* Mark the tile as already cleared for the terraform command.
00643      * Do this for all tiles (like trees), not only objects. */
00644     ClearedObjectArea *coa = FindClearedObject(end_tile);
00645     if (coa == NULL) {
00646       coa = _cleared_object_areas.Append();
00647       coa->first_tile = end_tile;
00648       coa->area = TileArea(end_tile, 1, 1);
00649     }
00650 
00651     /* Hide the tile from the terraforming command */
00652     TileIndex old_first_tile = coa->first_tile;
00653     coa->first_tile = INVALID_TILE;
00654     ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
00655     coa->first_tile = old_first_tile;
00656     if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
00657     cost.AddCost(ret);
00658   }
00659   cost.AddCost(_price[PR_BUILD_TUNNEL]);
00660 
00661   /* Pay for the rail/road in the tunnel including entrances */
00662   switch (transport_type) {
00663     case TRANSPORT_ROAD: cost.AddCost((tiles + 2) * _price[PR_BUILD_ROAD] * 2); break;
00664     case TRANSPORT_RAIL: cost.AddCost((tiles + 2) * RailBuildCost(railtype)); break;
00665     default: break;
00666   }
00667 
00668   if (flags & DC_EXEC) {
00669     Company *c = Company::GetIfValid(company);
00670     uint num_pieces = (tiles + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
00671     if (transport_type == TRANSPORT_RAIL) {
00672       if (!IsTunnelTile(start_tile) && c != NULL) c->infrastructure.rail[railtype] += num_pieces;
00673       MakeRailTunnel(start_tile, company, direction,                 railtype);
00674       MakeRailTunnel(end_tile,   company, ReverseDiagDir(direction), railtype);
00675       AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, company);
00676       YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
00677     } else {
00678       if (c != NULL) {
00679         RoadType rt;
00680         FOR_EACH_SET_ROADTYPE(rt, rts ^ (IsTunnelTile(start_tile) ? GetRoadTypes(start_tile) : ROADTYPES_NONE)) {
00681           c->infrastructure.road[rt] += num_pieces * 2; // A full diagonal road has two road bits.
00682         }
00683       }
00684       MakeRoadTunnel(start_tile, company, direction,                 rts);
00685       MakeRoadTunnel(end_tile,   company, ReverseDiagDir(direction), rts);
00686     }
00687     DirtyCompanyInfrastructureWindows(company);
00688   }
00689 
00690   return cost;
00691 }
00692 
00693 
00699 static inline CommandCost CheckAllowRemoveTunnelBridge(TileIndex tile)
00700 {
00701   /* Floods can remove anything as well as the scenario editor */
00702   if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return CommandCost();
00703 
00704   switch (GetTunnelBridgeTransportType(tile)) {
00705     case TRANSPORT_ROAD: {
00706       RoadTypes rts = GetRoadTypes(tile);
00707       Owner road_owner = _current_company;
00708       Owner tram_owner = _current_company;
00709 
00710       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
00711       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
00712 
00713       /* We can remove unowned road and if the town allows it */
00714       if (road_owner == OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) {
00715         return CheckTileOwnership(tile);
00716       }
00717       if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
00718       if (tram_owner == OWNER_NONE) tram_owner = _current_company;
00719 
00720       CommandCost ret = CheckOwnership(road_owner, tile);
00721       if (ret.Succeeded()) ret = CheckOwnership(tram_owner, tile);
00722       return ret;
00723     }
00724 
00725     case TRANSPORT_RAIL:
00726       return CheckOwnership(GetTileOwner(tile));
00727 
00728     case TRANSPORT_WATER: {
00729       /* Always allow to remove aqueducts without owner. */
00730       Owner aqueduct_owner = GetTileOwner(tile);
00731       if (aqueduct_owner == OWNER_NONE) aqueduct_owner = _current_company;
00732       return CheckOwnership(aqueduct_owner);
00733     }
00734 
00735     default: NOT_REACHED();
00736   }
00737 }
00738 
00745 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
00746 {
00747   CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
00748   if (ret.Failed()) return ret;
00749 
00750   TileIndex endtile = GetOtherTunnelEnd(tile);
00751 
00752   ret = TunnelBridgeIsFree(tile, endtile);
00753   if (ret.Failed()) return ret;
00754 
00755   _build_tunnel_endtile = endtile;
00756 
00757   Town *t = NULL;
00758   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00759     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00760 
00761     /* Check if you are allowed to remove the tunnel owned by a town
00762      * Removal depends on difficulty settings */
00763     CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
00764     if (ret.Failed()) return ret;
00765   }
00766 
00767   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00768    * you have a "Poor" (0) town rating */
00769   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00770     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00771   }
00772 
00773   uint len = GetTunnelBridgeLength(tile, endtile) + 2; // Don't forget the end tiles.
00774 
00775   if (flags & DC_EXEC) {
00776     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
00777       /* We first need to request values before calling DoClearSquare */
00778       DiagDirection dir = GetTunnelBridgeDirection(tile);
00779       Track track = DiagDirToDiagTrack(dir);
00780       Owner owner = GetTileOwner(tile);
00781 
00782       Train *v = NULL;
00783       if (HasTunnelBridgeReservation(tile)) {
00784         v = GetTrainForReservation(tile, track);
00785         if (v != NULL) FreeTrainTrackReservation(v);
00786       }
00787 
00788       if (Company::IsValidID(owner)) {
00789         Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
00790         DirtyCompanyInfrastructureWindows(owner);
00791       }
00792 
00793       DoClearSquare(tile);
00794       DoClearSquare(endtile);
00795 
00796       /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
00797       AddSideToSignalBuffer(tile,    ReverseDiagDir(dir), owner);
00798       AddSideToSignalBuffer(endtile, dir,                 owner);
00799 
00800       YapfNotifyTrackLayoutChange(tile,    track);
00801       YapfNotifyTrackLayoutChange(endtile, track);
00802 
00803       if (v != NULL) TryPathReserve(v);
00804     } else {
00805       RoadType rt;
00806       FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
00807         /* A full diagonal road tile has two road bits. */
00808         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
00809         if (c != NULL) {
00810           c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
00811           DirtyCompanyInfrastructureWindows(c->index);
00812         }
00813       }
00814 
00815       DoClearSquare(tile);
00816       DoClearSquare(endtile);
00817     }
00818   }
00819   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_TUNNEL] * len);
00820 }
00821 
00822 
00829 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
00830 {
00831   CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
00832   if (ret.Failed()) return ret;
00833 
00834   TileIndex endtile = GetOtherBridgeEnd(tile);
00835 
00836   ret = TunnelBridgeIsFree(tile, endtile);
00837   if (ret.Failed()) return ret;
00838 
00839   DiagDirection direction = GetTunnelBridgeDirection(tile);
00840   TileIndexDiff delta = TileOffsByDiagDir(direction);
00841 
00842   Town *t = NULL;
00843   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00844     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00845 
00846     /* Check if you are allowed to remove the bridge owned by a town
00847      * Removal depends on difficulty settings */
00848     CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
00849     if (ret.Failed()) return ret;
00850   }
00851 
00852   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00853    * you have a "Poor" (0) town rating */
00854   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00855     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00856   }
00857 
00858   Money base_cost = (GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) ? _price[PR_CLEAR_BRIDGE] : _price[PR_CLEAR_AQUEDUCT];
00859   uint len = GetTunnelBridgeLength(tile, endtile) + 2; // Don't forget the end tiles.
00860 
00861   if (flags & DC_EXEC) {
00862     /* read this value before actual removal of bridge */
00863     bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
00864     Owner owner = GetTileOwner(tile);
00865     int height = GetBridgeHeight(tile);
00866     Train *v = NULL;
00867 
00868     if (rail && HasTunnelBridgeReservation(tile)) {
00869       v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
00870       if (v != NULL) FreeTrainTrackReservation(v);
00871     }
00872 
00873     /* Update company infrastructure counts. */
00874     if (rail) {
00875       if (Company::IsValidID(owner)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
00876     } else if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
00877       RoadType rt;
00878       FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
00879         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
00880         if (c != NULL) {
00881           /* A full diagonal road tile has two road bits. */
00882           c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
00883           DirtyCompanyInfrastructureWindows(c->index);
00884         }
00885       }
00886     } else { // Aqueduct
00887       if (Company::IsValidID(owner)) Company::Get(owner)->infrastructure.water -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
00888     }
00889     DirtyCompanyInfrastructureWindows(owner);
00890 
00891     DoClearSquare(tile);
00892     DoClearSquare(endtile);
00893     for (TileIndex c = tile + delta; c != endtile; c += delta) {
00894       /* do not let trees appear from 'nowhere' after removing bridge */
00895       if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
00896         int minz = GetTileMaxZ(c) + 3;
00897         if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
00898       }
00899       ClearBridgeMiddle(c);
00900       MarkTileDirtyByTile(c);
00901     }
00902 
00903     if (rail) {
00904       /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
00905       AddSideToSignalBuffer(tile,    ReverseDiagDir(direction), owner);
00906       AddSideToSignalBuffer(endtile, direction,                 owner);
00907 
00908       Track track = DiagDirToDiagTrack(direction);
00909       YapfNotifyTrackLayoutChange(tile,    track);
00910       YapfNotifyTrackLayoutChange(endtile, track);
00911 
00912       if (v != NULL) TryPathReserve(v, true);
00913     }
00914   }
00915 
00916   return CommandCost(EXPENSES_CONSTRUCTION, len * base_cost);
00917 }
00918 
00925 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
00926 {
00927   if (IsTunnel(tile)) {
00928     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
00929     return DoClearTunnel(tile, flags);
00930   } else { // IsBridge(tile)
00931     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00932     return DoClearBridge(tile, flags);
00933   }
00934 }
00935 
00946 static inline void DrawPillar(const PalSpriteID *psid, int x, int y, int z, int w, int h, const SubSprite *subsprite)
00947 {
00948   static const int PILLAR_Z_OFFSET = TILE_HEIGHT - BRIDGE_Z_START; 
00949   AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, w, h, BB_HEIGHT_UNDER_BRIDGE - PILLAR_Z_OFFSET, z, IsTransparencySet(TO_BRIDGES), 0, 0, -PILLAR_Z_OFFSET, subsprite);
00950 }
00951 
00963 static int DrawPillarColumn(int z_bottom, int z_top, const PalSpriteID *psid, int x, int y, int w, int h)
00964 {
00965   int cur_z;
00966   for (cur_z = z_top; cur_z >= z_bottom; cur_z -= TILE_HEIGHT) {
00967     DrawPillar(psid, x, y, cur_z, w, h, NULL);
00968   }
00969   return cur_z;
00970 }
00971 
00983 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
00984 {
00985   static const int bounding_box_size[2]  = {16, 2}; 
00986   static const int back_pillar_offset[2] = { 0, 9}; 
00987 
00988   static const int INF = 1000; 
00989   static const SubSprite half_pillar_sub_sprite[2][2] = {
00990     { {  -14, -INF, INF, INF }, { -INF, -INF, -15, INF } }, // X axis, north and south
00991     { { -INF, -INF,  15, INF }, {   16, -INF, INF, INF } }, // Y axis, north and south
00992   };
00993 
00994   if (psid->sprite == 0) return;
00995 
00996   /* Determine ground height under pillars */
00997   DiagDirection south_dir = AxisToDiagDir(axis);
00998   int z_front_north = ti->z;
00999   int z_back_north = ti->z;
01000   int z_front_south = ti->z;
01001   int z_back_south = ti->z;
01002   GetSlopePixelZOnEdge(ti->tileh, south_dir, &z_front_south, &z_back_south);
01003   GetSlopePixelZOnEdge(ti->tileh, ReverseDiagDir(south_dir), &z_front_north, &z_back_north);
01004 
01005   /* Shared height of pillars */
01006   int z_front = max(z_front_north, z_front_south);
01007   int z_back = max(z_back_north, z_back_south);
01008 
01009   /* x and y size of bounding-box of pillars */
01010   int w = bounding_box_size[axis];
01011   int h = bounding_box_size[OtherAxis(axis)];
01012   /* sprite position of back facing pillar */
01013   int x_back = x - back_pillar_offset[axis];
01014   int y_back = y - back_pillar_offset[OtherAxis(axis)];
01015 
01016   /* Draw front pillars */
01017   int bottom_z = DrawPillarColumn(z_front, z_bridge, psid, x, y, w, h);
01018   if (z_front_north < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
01019   if (z_front_south < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
01020 
01021   /* Draw back pillars, skip top two parts, which are hidden by the bridge */
01022   int z_bridge_back = z_bridge - 2 * (int)TILE_HEIGHT;
01023   if (drawfarpillar && (z_back_north <= z_bridge_back || z_back_south <= z_bridge_back)) {
01024     bottom_z = DrawPillarColumn(z_back, z_bridge_back, psid, x_back, y_back, w, h);
01025     if (z_back_north < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
01026     if (z_back_south < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
01027   }
01028 }
01029 
01039 static void DrawBridgeTramBits(int x, int y, int z, int offset, bool overlay, bool head)
01040 {
01041   static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
01042   static const SpriteID back_offsets[6]    =   {  95,  96,  99, 102, 100, 101 };
01043   static const SpriteID front_offsets[6]   =   {  97,  98, 103, 106, 104, 105 };
01044 
01045   static const uint size_x[6] = {  1, 16, 16,  1, 16,  1 };
01046   static const uint size_y[6] = { 16,  1,  1, 16,  1, 16 };
01047   static const uint front_bb_offset_x[6] = { 15,  0,  0, 15,  0, 15 };
01048   static const uint front_bb_offset_y[6] = {  0, 15, 15,  0, 15,  0 };
01049 
01050   /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
01051    * The bounding boxes here are the same as for bridge front/roof */
01052   if (head || !IsInvisibilitySet(TO_BRIDGES)) {
01053     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
01054       x, y, size_x[offset], size_y[offset], 0x28, z,
01055       !head && IsTransparencySet(TO_BRIDGES));
01056   }
01057 
01058   /* Do not draw catenary if it is set invisible */
01059   if (!IsInvisibilitySet(TO_CATENARY)) {
01060     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
01061       x, y, size_x[offset], size_y[offset], 0x28, z,
01062       IsTransparencySet(TO_CATENARY));
01063   }
01064 
01065   /* Start a new SpriteCombine for the front part */
01066   EndSpriteCombine();
01067   StartSpriteCombine();
01068 
01069   /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
01070   if (!IsInvisibilitySet(TO_CATENARY)) {
01071     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
01072       x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
01073       IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
01074   }
01075 }
01076 
01090 static void DrawTile_TunnelBridge(TileInfo *ti)
01091 {
01092   TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
01093   DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
01094 
01095   if (IsTunnel(ti->tile)) {
01096     /* Front view of tunnel bounding boxes:
01097      *
01098      *   122223  <- BB_Z_SEPARATOR
01099      *   1    3
01100      *   1    3                1,3 = empty helper BB
01101      *   1    3                  2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
01102      *
01103      */
01104 
01105     static const int _tunnel_BB[4][12] = {
01106       /*  tunnnel-roof  |  Z-separator  | tram-catenary
01107        * w  h  bb_x bb_y| x   y   w   h |bb_x bb_y w h */
01108       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // NE
01109       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // SE
01110       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // SW
01111       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // NW
01112     };
01113     const int *BB_data = _tunnel_BB[tunnelbridge_direction];
01114 
01115     bool catenary = false;
01116 
01117     SpriteID image;
01118     if (transport_type == TRANSPORT_RAIL) {
01119       image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.tunnel;
01120     } else {
01121       image = SPR_TUNNEL_ENTRY_REAR_ROAD;
01122     }
01123 
01124     if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += 32;
01125 
01126     image += tunnelbridge_direction * 2;
01127     DrawGroundSprite(image, PAL_NONE);
01128 
01129     if (transport_type == TRANSPORT_ROAD) {
01130       RoadTypes rts = GetRoadTypes(ti->tile);
01131 
01132       if (HasBit(rts, ROADTYPE_TRAM)) {
01133         static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, {  5, 76, 77,  4 } };
01134 
01135         DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
01136 
01137         /* Do not draw wires if they are invisible */
01138         if (!IsInvisibilitySet(TO_CATENARY)) {
01139           catenary = true;
01140           StartSpriteCombine();
01141           AddSortableSpriteToDraw(SPR_TRAMWAY_TUNNEL_WIRES + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, BB_data[10], BB_data[11], TILE_HEIGHT, ti->z, IsTransparencySet(TO_CATENARY), BB_data[8], BB_data[9], BB_Z_SEPARATOR);
01142         }
01143       }
01144     } else {
01145       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01146       if (rti->UsesOverlay()) {
01147         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
01148         if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
01149       }
01150 
01151       /* PBS debugging, draw reserved tracks darker */
01152       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
01153         DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
01154       }
01155 
01156       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01157         /* Maybe draw pylons on the entry side */
01158         DrawCatenary(ti);
01159 
01160         catenary = true;
01161         StartSpriteCombine();
01162         /* Draw wire above the ramp */
01163         DrawCatenaryOnTunnel(ti);
01164       }
01165     }
01166 
01167     AddSortableSpriteToDraw(image + 1, PAL_NONE, ti->x + TILE_SIZE - 1, ti->y + TILE_SIZE - 1, BB_data[0], BB_data[1], TILE_HEIGHT, ti->z, false, BB_data[2], BB_data[3], BB_Z_SEPARATOR);
01168 
01169     if (catenary) EndSpriteCombine();
01170 
01171     /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
01172     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x,              ti->y,              BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
01173     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x + BB_data[4], ti->y + BB_data[5], BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
01174 
01175     DrawBridgeMiddle(ti);
01176   } else { // IsBridge(ti->tile)
01177     const PalSpriteID *psid;
01178     int base_offset;
01179     bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
01180 
01181     if (transport_type == TRANSPORT_RAIL) {
01182       base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
01183       assert(base_offset != 8); // This one is used for roads
01184     } else {
01185       base_offset = 8;
01186     }
01187 
01188     /* as the lower 3 bits are used for other stuff, make sure they are clear */
01189     assert( (base_offset & 0x07) == 0x00);
01190 
01191     DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
01192 
01193     /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
01194     base_offset += (6 - tunnelbridge_direction) % 4;
01195 
01196     if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
01197 
01198     /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
01199     if (transport_type != TRANSPORT_WATER) {
01200       psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
01201     } else {
01202       psid = _aqueduct_sprites + base_offset;
01203     }
01204 
01205     if (!ice) {
01206       TileIndex next = ti->tile + TileOffsByDiagDir(tunnelbridge_direction);
01207       if (ti->tileh != SLOPE_FLAT && ti->z == 0 && HasTileWaterClass(next) && GetWaterClass(next) == WATER_CLASS_SEA) {
01208         DrawShoreTile(ti->tileh);
01209       } else {
01210         DrawClearLandTile(ti, 3);
01211       }
01212     } else {
01213       DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
01214     }
01215 
01216     /* draw ramp */
01217 
01218     /* Draw Trambits and PBS Reservation as SpriteCombine */
01219     if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01220 
01221     /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
01222      * it doesn't disappear behind it
01223      */
01224     /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
01225     AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
01226 
01227     if (transport_type == TRANSPORT_ROAD) {
01228       RoadTypes rts = GetRoadTypes(ti->tile);
01229 
01230       if (HasBit(rts, ROADTYPE_TRAM)) {
01231         uint offset = tunnelbridge_direction;
01232         int z = ti->z;
01233         if (ti->tileh != SLOPE_FLAT) {
01234           offset = (offset + 1) & 1;
01235           z += TILE_HEIGHT;
01236         } else {
01237           offset += 2;
01238         }
01239         /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01240         DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
01241       }
01242       EndSpriteCombine();
01243     } else if (transport_type == TRANSPORT_RAIL) {
01244       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01245       if (rti->UsesOverlay()) {
01246         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
01247         if (surface != 0) {
01248           if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01249             AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
01250           } else {
01251             AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
01252           }
01253         }
01254         /* Don't fallback to non-overlay sprite -- the spec states that
01255          * if an overlay is present then the bridge surface must be
01256          * present. */
01257       }
01258 
01259       /* PBS debugging, draw reserved tracks darker */
01260       if (_game_mode != GM_MENU &&_settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
01261         if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01262           AddSortableSpriteToDraw(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
01263         } else {
01264           AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
01265         }
01266       }
01267 
01268       EndSpriteCombine();
01269       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01270         DrawCatenary(ti);
01271       }
01272     }
01273 
01274     DrawBridgeMiddle(ti);
01275   }
01276 }
01277 
01278 
01297 static BridgePieces CalcBridgePiece(uint north, uint south)
01298 {
01299   if (north == 1) {
01300     return BRIDGE_PIECE_NORTH;
01301   } else if (south == 1) {
01302     return BRIDGE_PIECE_SOUTH;
01303   } else if (north < south) {
01304     return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
01305   } else if (north > south) {
01306     return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
01307   } else {
01308     return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
01309   }
01310 }
01311 
01316 void DrawBridgeMiddle(const TileInfo *ti)
01317 {
01318   /* Sectional view of bridge bounding boxes:
01319    *
01320    *  1           2                                1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
01321    *  1           2                                  3 = empty helper BB
01322    *  1     7     2                                4,5 = pillars under higher bridges
01323    *  1 6 88888 6 2                                  6 = elrail-pylons
01324    *  1 6 88888 6 2                                  7 = elrail-wire
01325    *  1 6 88888 6 2  <- TILE_HEIGHT                  8 = rail-vehicle on bridge
01326    *  3333333333333  <- BB_Z_SEPARATOR
01327    *                 <- unused
01328    *    4       5    <- BB_HEIGHT_UNDER_BRIDGE
01329    *    4       5
01330    *    4       5
01331    *
01332    */
01333 
01334   if (!IsBridgeAbove(ti->tile)) return;
01335 
01336   TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
01337   TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
01338   TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
01339 
01340   Axis axis = GetBridgeAxis(ti->tile);
01341   BridgePieces piece = CalcBridgePiece(
01342     GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
01343     GetTunnelBridgeLength(ti->tile, rampsouth) + 1
01344   );
01345 
01346   const PalSpriteID *psid;
01347   bool drawfarpillar;
01348   if (transport_type != TRANSPORT_WATER) {
01349     BridgeType type =  GetBridgeType(rampsouth);
01350     drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
01351 
01352     uint base_offset;
01353     if (transport_type == TRANSPORT_RAIL) {
01354       base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
01355     } else {
01356       base_offset = 8;
01357     }
01358 
01359     psid = base_offset + GetBridgeSpriteTable(type, piece);
01360   } else {
01361     drawfarpillar = true;
01362     psid = _aqueduct_sprites;
01363   }
01364 
01365   if (axis != AXIS_X) psid += 4;
01366 
01367   int x = ti->x;
01368   int y = ti->y;
01369   uint bridge_z = GetBridgePixelHeight(rampsouth);
01370   int z = bridge_z - BRIDGE_Z_START;
01371 
01372   /* Add a bounding box that separates the bridge from things below it. */
01373   AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
01374 
01375   /* Draw Trambits as SpriteCombine */
01376   if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01377 
01378   /* Draw floor and far part of bridge*/
01379   if (!IsInvisibilitySet(TO_BRIDGES)) {
01380     if (axis == AXIS_X) {
01381       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01382     } else {
01383       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01384     }
01385   }
01386 
01387   psid++;
01388 
01389   if (transport_type == TRANSPORT_ROAD) {
01390     RoadTypes rts = GetRoadTypes(rampsouth);
01391 
01392     if (HasBit(rts, ROADTYPE_TRAM)) {
01393       /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01394       DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
01395     } else {
01396       EndSpriteCombine();
01397       StartSpriteCombine();
01398     }
01399   } else if (transport_type == TRANSPORT_RAIL) {
01400     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
01401     if (rti->UsesOverlay()) {
01402       SpriteID surface = GetCustomRailSprite(rti, rampsouth, RTSG_BRIDGE, TCX_ON_BRIDGE);
01403       if (surface != 0) {
01404         AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
01405       }
01406     }
01407     EndSpriteCombine();
01408 
01409     if (HasCatenaryDrawn(GetRailType(rampsouth))) {
01410       DrawCatenaryOnBridge(ti);
01411     }
01412   }
01413 
01414   /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
01415   if (!IsInvisibilitySet(TO_BRIDGES)) {
01416     if (axis == AXIS_X) {
01417       y += 12;
01418       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
01419     } else {
01420       x += 12;
01421       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
01422     }
01423   }
01424 
01425   /* Draw TramFront as SpriteCombine */
01426   if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
01427 
01428   /* Do not draw anything more if bridges are invisible */
01429   if (IsInvisibilitySet(TO_BRIDGES)) return;
01430 
01431   psid++;
01432   if (ti->z + 5 == z) {
01433     /* draw poles below for small bridges */
01434     if (psid->sprite != 0) {
01435       SpriteID image = psid->sprite;
01436       SpriteID pal   = psid->pal;
01437       if (IsTransparencySet(TO_BRIDGES)) {
01438         SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
01439         pal = PALETTE_TO_TRANSPARENT;
01440       }
01441 
01442       DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
01443     }
01444   } else {
01445     /* draw pillars below for high bridges */
01446     DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
01447   }
01448 }
01449 
01450 
01451 static int GetSlopePixelZ_TunnelBridge(TileIndex tile, uint x, uint y)
01452 {
01453   int z;
01454   Slope tileh = GetTilePixelSlope(tile, &z);
01455 
01456   x &= 0xF;
01457   y &= 0xF;
01458 
01459   if (IsTunnel(tile)) {
01460     uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
01461 
01462     /* In the tunnel entrance? */
01463     if (5 <= pos && pos <= 10) return z;
01464   } else { // IsBridge(tile)
01465     DiagDirection dir = GetTunnelBridgeDirection(tile);
01466     uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
01467 
01468     z += ApplyPixelFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
01469 
01470     /* On the bridge ramp? */
01471     if (5 <= pos && pos <= 10) {
01472       int delta;
01473 
01474       if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
01475 
01476       switch (dir) {
01477         default: NOT_REACHED();
01478         case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
01479         case DIAGDIR_SE: delta = y / 2; break;
01480         case DIAGDIR_SW: delta = x / 2; break;
01481         case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
01482       }
01483       return z + 1 + delta;
01484     }
01485   }
01486 
01487   return z + GetPartialPixelZ(x, y, tileh);
01488 }
01489 
01490 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
01491 {
01492   return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
01493 }
01494 
01495 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
01496 {
01497   TransportType tt = GetTunnelBridgeTransportType(tile);
01498 
01499   if (IsTunnel(tile)) {
01500     td->str = (tt == TRANSPORT_RAIL) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
01501   } else { // IsBridge(tile)
01502     td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
01503   }
01504   td->owner[0] = GetTileOwner(tile);
01505 
01506   Owner road_owner = INVALID_OWNER;
01507   Owner tram_owner = INVALID_OWNER;
01508   RoadTypes rts = GetRoadTypes(tile);
01509   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01510   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01511 
01512   /* Is there a mix of owners? */
01513   if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
01514       (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
01515     uint i = 1;
01516     if (road_owner != INVALID_OWNER) {
01517       td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
01518       td->owner[i] = road_owner;
01519       i++;
01520     }
01521     if (tram_owner != INVALID_OWNER) {
01522       td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
01523       td->owner[i] = tram_owner;
01524     }
01525   }
01526 
01527   if (tt == TRANSPORT_RAIL) {
01528     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
01529     td->rail_speed = rti->max_speed;
01530 
01531     if (!IsTunnel(tile)) {
01532       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01533       if (td->rail_speed == 0 || spd < td->rail_speed) {
01534         td->rail_speed = spd;
01535       }
01536     }
01537   }
01538 }
01539 
01540 
01541 static void TileLoop_TunnelBridge(TileIndex tile)
01542 {
01543   bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
01544   switch (_settings_game.game_creation.landscape) {
01545     case LT_ARCTIC: {
01546       /* As long as we do not have a snow density, we want to use the density
01547        * from the entry endge. For tunnels this is the lowest point for bridges the highest point.
01548        * (Independent of foundations) */
01549       int z = IsBridge(tile) ? GetTileMaxZ(tile) : GetTileZ(tile);
01550       if (snow_or_desert != (z > GetSnowLine())) {
01551         SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
01552         MarkTileDirtyByTile(tile);
01553       }
01554       break;
01555     }
01556 
01557     case LT_TROPIC:
01558       if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
01559         SetTunnelBridgeSnowOrDesert(tile, true);
01560         MarkTileDirtyByTile(tile);
01561       }
01562       break;
01563 
01564     default:
01565       break;
01566   }
01567 }
01568 
01569 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
01570 {
01571   TransportType transport_type = GetTunnelBridgeTransportType(tile);
01572   if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
01573 
01574   DiagDirection dir = GetTunnelBridgeDirection(tile);
01575   if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
01576   return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
01577 }
01578 
01579 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
01580 {
01581   TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
01582   /* Set number of pieces to zero if it's the southern tile as we
01583    * don't want to update the infrastructure counts twice. */
01584   uint num_pieces = tile < other_end ? (GetTunnelBridgeLength(tile, other_end) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR : 0;
01585 
01586   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01587     /* Update all roadtypes, no matter if they are present */
01588     if (GetRoadOwner(tile, rt) == old_owner) {
01589       if (HasBit(GetRoadTypes(tile), rt)) {
01590         /* Update company infrastructure counts. A full diagonal road tile has two road bits.
01591          * No need to dirty windows here, we'll redraw the whole screen anyway. */
01592         Company::Get(old_owner)->infrastructure.road[rt] -= num_pieces * 2;
01593         if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += num_pieces * 2;
01594       }
01595 
01596       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
01597     }
01598   }
01599 
01600   if (!IsTileOwner(tile, old_owner)) return;
01601 
01602   /* Update company infrastructure counts for rail and water as well.
01603    * No need to dirty windows here, we'll redraw the whole screen anyway. */
01604   TransportType tt = GetTunnelBridgeTransportType(tile);
01605   Company *old = Company::Get(old_owner);
01606   if (tt == TRANSPORT_RAIL) {
01607     old->infrastructure.rail[GetRailType(tile)] -= num_pieces;
01608     if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += num_pieces;
01609   } else if (tt == TRANSPORT_WATER) {
01610     old->infrastructure.water -= num_pieces;
01611     if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.water += num_pieces;
01612   }
01613 
01614   if (new_owner != INVALID_OWNER) {
01615     SetTileOwner(tile, new_owner);
01616   } else {
01617     if (tt == TRANSPORT_RAIL) {
01618       /* Since all of our vehicles have been removed, it is safe to remove the rail
01619        * bridge / tunnel. */
01620       CommandCost ret = DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
01621       assert(ret.Succeeded());
01622     } else {
01623       /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
01624       SetTileOwner(tile, OWNER_NONE);
01625     }
01626   }
01627 }
01628 
01634 static const byte TUNNEL_SOUND_FRAME = 1;
01635 
01644 extern const byte _tunnel_visibility_frame[DIAGDIR_END] = {12, 8, 8, 12};
01645 
01646 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
01647 {
01648   int z = GetSlopePixelZ(x, y) - v->z_pos;
01649 
01650   if (abs(z) > 2) return VETSB_CANNOT_ENTER;
01651   /* Direction into the wormhole */
01652   const DiagDirection dir = GetTunnelBridgeDirection(tile);
01653   /* Direction of the vehicle */
01654   const DiagDirection vdir = DirToDiagDir(v->direction);
01655   /* New position of the vehicle on the tile */
01656   byte pos = (DiagDirToAxis(vdir) == AXIS_X ? x : y) & TILE_UNIT_MASK;
01657   /* Number of units moved by the vehicle since entering the tile */
01658   byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
01659 
01660   if (IsTunnel(tile)) {
01661     if (v->type == VEH_TRAIN) {
01662       Train *t = Train::From(v);
01663 
01664       if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
01665         if (t->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
01666           if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
01667             SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
01668           }
01669           return VETSB_CONTINUE;
01670         }
01671         if (frame == _tunnel_visibility_frame[dir]) {
01672           t->tile = tile;
01673           t->track = TRACK_BIT_WORMHOLE;
01674           t->vehstatus |= VS_HIDDEN;
01675           return VETSB_ENTERED_WORMHOLE;
01676         }
01677       }
01678 
01679       if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
01680         /* We're at the tunnel exit ?? */
01681         t->tile = tile;
01682         t->track = DiagDirToDiagTrackBits(vdir);
01683         assert(t->track);
01684         t->vehstatus &= ~VS_HIDDEN;
01685         return VETSB_ENTERED_WORMHOLE;
01686       }
01687     } else if (v->type == VEH_ROAD) {
01688       RoadVehicle *rv = RoadVehicle::From(v);
01689 
01690       /* Enter tunnel? */
01691       if (rv->state != RVSB_WORMHOLE && dir == vdir) {
01692         if (frame == _tunnel_visibility_frame[dir]) {
01693           /* Frame should be equal to the next frame number in the RV's movement */
01694           assert(frame == rv->frame + 1);
01695           rv->tile = tile;
01696           rv->state = RVSB_WORMHOLE;
01697           rv->vehstatus |= VS_HIDDEN;
01698           return VETSB_ENTERED_WORMHOLE;
01699         } else {
01700           return VETSB_CONTINUE;
01701         }
01702       }
01703 
01704       /* We're at the tunnel exit ?? */
01705       if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
01706         rv->tile = tile;
01707         rv->state = DiagDirToDiagTrackdir(vdir);
01708         rv->frame = frame;
01709         rv->vehstatus &= ~VS_HIDDEN;
01710         return VETSB_ENTERED_WORMHOLE;
01711       }
01712     }
01713   } else { // IsBridge(tile)
01714     if (v->type != VEH_SHIP) {
01715       /* modify speed of vehicle */
01716       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01717 
01718       if (v->type == VEH_ROAD) spd *= 2;
01719       Vehicle *first = v->First();
01720       first->cur_speed = min(first->cur_speed, spd);
01721     }
01722 
01723     if (vdir == dir) {
01724       /* Vehicle enters bridge at the last frame inside this tile. */
01725       if (frame != TILE_SIZE - 1) return VETSB_CONTINUE;
01726       switch (v->type) {
01727         case VEH_TRAIN: {
01728           Train *t = Train::From(v);
01729           t->track = TRACK_BIT_WORMHOLE;
01730           ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
01731           ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
01732           break;
01733         }
01734 
01735         case VEH_ROAD: {
01736           RoadVehicle *rv = RoadVehicle::From(v);
01737           rv->state = RVSB_WORMHOLE;
01738           /* There are no slopes inside bridges / tunnels. */
01739           ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
01740           ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
01741           break;
01742         }
01743 
01744         case VEH_SHIP:
01745           Ship::From(v)->state = TRACK_BIT_WORMHOLE;
01746           break;
01747 
01748         default: NOT_REACHED();
01749       }
01750       return VETSB_ENTERED_WORMHOLE;
01751     } else if (vdir == ReverseDiagDir(dir)) {
01752       v->tile = tile;
01753       switch (v->type) {
01754         case VEH_TRAIN: {
01755           Train *t = Train::From(v);
01756           if (t->track == TRACK_BIT_WORMHOLE) {
01757             t->track = DiagDirToDiagTrackBits(vdir);
01758             return VETSB_ENTERED_WORMHOLE;
01759           }
01760           break;
01761         }
01762 
01763         case VEH_ROAD: {
01764           RoadVehicle *rv = RoadVehicle::From(v);
01765           if (rv->state == RVSB_WORMHOLE) {
01766             rv->state = DiagDirToDiagTrackdir(vdir);
01767             rv->frame = 0;
01768             return VETSB_ENTERED_WORMHOLE;
01769           }
01770           break;
01771         }
01772 
01773         case VEH_SHIP: {
01774           Ship *ship = Ship::From(v);
01775           if (ship->state == TRACK_BIT_WORMHOLE) {
01776             ship->state = DiagDirToDiagTrackBits(vdir);
01777             return VETSB_ENTERED_WORMHOLE;
01778           }
01779           break;
01780         }
01781 
01782         default: NOT_REACHED();
01783       }
01784     }
01785   }
01786   return VETSB_CONTINUE;
01787 }
01788 
01789 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
01790 {
01791   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
01792     DiagDirection direction = GetTunnelBridgeDirection(tile);
01793     Axis axis = DiagDirToAxis(direction);
01794     CommandCost res;
01795     int z_old;
01796     Slope tileh_old = GetTileSlope(tile, &z_old);
01797 
01798     /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
01799     if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
01800       CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
01801       res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
01802     } else {
01803       CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
01804       res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
01805     }
01806 
01807     /* Surface slope is valid and remains unchanged? */
01808     if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
01809   }
01810 
01811   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01812 }
01813 
01814 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
01815   DrawTile_TunnelBridge,           // draw_tile_proc
01816   GetSlopePixelZ_TunnelBridge,     // get_slope_z_proc
01817   ClearTile_TunnelBridge,          // clear_tile_proc
01818   NULL,                            // add_accepted_cargo_proc
01819   GetTileDesc_TunnelBridge,        // get_tile_desc_proc
01820   GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
01821   NULL,                            // click_tile_proc
01822   NULL,                            // animate_tile_proc
01823   TileLoop_TunnelBridge,           // tile_loop_proc
01824   ChangeTileOwner_TunnelBridge,    // change_tile_owner_proc
01825   NULL,                            // add_produced_cargo_proc
01826   VehicleEnter_TunnelBridge,       // vehicle_enter_tile_proc
01827   GetFoundation_TunnelBridge,      // get_foundation_proc
01828   TerraformTile_TunnelBridge,      // terraform_tile_proc
01829 };