tunnelbridge_cmd.cpp

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