# tunnelbridge_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: tunnelbridge_cmd.cpp 19056 2010-02-07 22:22:54Z peter1138 $ */
    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
    00015 #include "stdafx.h"
    00016 #include "rail_map.h"
    00017 #include "landscape.h"
    00018 #include "unmovable_map.h"
    00019 #include "viewport_func.h"
    00020 #include "command_func.h"
    00021 #include "town.h"
    00022 #include "variables.h"
    00023 #include "train.h"
    00024 #include "ship.h"
    00025 #include "roadveh.h"
    00026 #include "water_map.h"
    00027 #include "pathfinder/yapf/yapf_cache.h"
    00028 #include "newgrf_sound.h"
    00029 #include "autoslope.h"
    00030 #include "tunnelbridge_map.h"
    00031 #include "strings_func.h"
    00032 #include "date_func.h"
    00033 #include "functions.h"
    00034 #include "vehicle_func.h"
    00035 #include "sound_func.h"
    00036 #include "tunnelbridge.h"
    00037 #include "cheat_type.h"
    00038 #include "elrail_func.h"
    00039 #include "landscape_type.h"
    00040 #include "pbs.h"
    00041 #include "company_base.h"
    00042 #include "engine_base.h"
    00043 #include "newgrf_railtype.h"
    00044
    00045 #include "table/sprites.h"
    00046 #include "table/strings.h"
    00047 #include "table/bridge_land.h"
    00048
    00049 BridgeSpec _bridge[MAX_BRIDGES];
    00050 TileIndex _build_tunnel_endtile;
    00051
    00053 void ResetBridges()
    00054 {
    00055   /* First, free sprite table data */
    00056   for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
    00057     if (_bridge[i].sprite_table != NULL) {
    00058       for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
    00059       free(_bridge[i].sprite_table);
    00060     }
    00061   }
    00062
    00063   /* Then, wipe out current bidges */
    00064   memset(&_bridge, 0, sizeof(_bridge));
    00065   /* And finally, reinstall default data */
    00066   memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
    00067 }
    00068
    00072 int CalcBridgeLenCostFactor(int x)
    00073 {
    00074   int n;
    00075   int r;
    00076
    00077   if (x < 2) return x;
    00078   x -= 2;
    00079   for (n = 0, r = 2;; n++) {
    00080     if (x <= n) return r + x * n;
    00081     r += n * n;
    00082     x -= n;
    00083   }
    00084 }
    00085
    00086 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
    00087 {
    00088   if ((tileh == SLOPE_FLAT) ||
    00089       (((tileh == SLOPE_NE) || (tileh == SLOPE_SW)) && (axis == AXIS_X)) ||
    00090       (((tileh == SLOPE_NW) || (tileh == SLOPE_SE)) && (axis == AXIS_Y))) return FOUNDATION_NONE;
    00091
    00092   return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
    00093 }
    00094
    00102 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
    00103 {
    00104   ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
    00105   /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
    00106   return (tileh != SLOPE_FLAT);
    00107 }
    00108
    00109 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
    00110 {
    00111   const BridgeSpec *bridge = GetBridgeSpec(index);
    00112   assert(table < BRIDGE_PIECE_INVALID);
    00113   if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
    00114     return _bridge_sprite_table[index][table];
    00115   } else {
    00116     return bridge->sprite_table[table];
    00117   }
    00118 }
    00119
    00120
    00129 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, uint *z)
    00130 {
    00131   Foundation f = GetBridgeFoundation(*tileh, axis);
    00132   *z += ApplyFoundationToSlope(f, tileh);
    00133
    00134   Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
    00135   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
    00136
    00137   if (f == FOUNDATION_NONE) return CommandCost();
    00138
    00139   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    00140 }
    00141
    00150 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, uint *z)
    00151 {
    00152   Foundation f = GetBridgeFoundation(*tileh, axis);
    00153   *z += ApplyFoundationToSlope(f, tileh);
    00154
    00155   Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
    00156   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
    00157
    00158   if (f == FOUNDATION_NONE) return CommandCost();
    00159
    00160   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    00161 }
    00162
    00163 bool CheckBridge_Stuff(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
    00164 {
    00165   if (flags & DC_QUERY_COST) {
    00166     return bridge_len <= (_settings_game.construction.longbridges ? 100U : 16U);
    00167   }
    00168
    00169   if (bridge_type >= MAX_BRIDGES) return false;
    00170
    00171   const BridgeSpec *b = GetBridgeSpec(bridge_type);
    00172   if (b->avail_year > _cur_year) return false;
    00173
    00174   uint max = b->max_length;
    00175   if (max >= 16 && _settings_game.construction.longbridges) max = 100;
    00176
    00177   return b->min_length <= bridge_len && bridge_len <= max;
    00178 }
    00179
    00191 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00192 {
    00193   RailType railtype = INVALID_RAILTYPE;
    00194   RoadTypes roadtypes = ROADTYPES_NONE;
    00195   CommandCost cost(EXPENSES_CONSTRUCTION);
    00196   Owner owner;
    00197
    00198   /* unpack parameters */
    00199   BridgeType bridge_type = GB(p2, 0, 8);
    00200
    00201   if (p1 >= MapSize()) return CMD_ERROR;
    00202
    00203   TransportType transport_type = (TransportType)GB(p2, 15, 2);
    00204
    00205   /* type of bridge */
    00206   switch (transport_type) {
    00207     case TRANSPORT_ROAD:
    00208       roadtypes = (RoadTypes)GB(p2, 8, 2);
    00209       if (!AreValidRoadTypes(roadtypes) || !HasRoadTypesAvail(_current_company, roadtypes)) return CMD_ERROR;
    00210       break;
    00211
    00212     case TRANSPORT_RAIL:
    00213       railtype = (RailType)GB(p2, 8, 7);
    00214       if (!ValParamRailtype(railtype)) return CMD_ERROR;
    00215       break;
    00216
    00217     case TRANSPORT_WATER:
    00218       break;
    00219
    00220     default:
    00221       /* Airports don't have bridges. */
    00222       return CMD_ERROR;
    00223   }
    00224   TileIndex tile_start = p1;
    00225   TileIndex tile_end = end_tile;
    00226
    00227   if (tile_start == tile_end) {
    00228     return_cmd_error(STR_ERROR_CAN_T_START_AND_END_ON);
    00229   }
    00230
    00231   Axis direction;
    00232   if (TileX(tile_start) == TileX(tile_end)) {
    00233     direction = AXIS_Y;
    00234   } else if (TileY(tile_start) == TileY(tile_end)) {
    00235     direction = AXIS_X;
    00236   } else {
    00237     return_cmd_error(STR_ERROR_START_AND_END_MUST_BE_IN);
    00238   }
    00239
    00240   if (tile_end < tile_start) Swap(tile_start, tile_end);
    00241
    00242   uint bridge_len = GetTunnelBridgeLength(tile_start, tile_end);
    00243   if (transport_type != TRANSPORT_WATER) {
    00244     /* set and test bridge length, availability */
    00245     if (!CheckBridge_Stuff(bridge_type, bridge_len, flags)) return_cmd_error(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE);
    00246   } else {
    00247     if (bridge_len > (_settings_game.construction.longbridges ? 100U : 16U)) return_cmd_error(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE);
    00248   }
    00249
    00250   /* retrieve landscape height and ensure it's on land */
    00251   if (IsWaterTile(tile_start) || IsWaterTile(tile_end)) {
    00252     return_cmd_error(STR_ERROR_ENDS_OF_BRIDGE_MUST_BOTH);
    00253   }
    00254
    00255   uint z_start;
    00256   uint z_end;
    00257   Slope tileh_start = GetTileSlope(tile_start, &z_start);
    00258   Slope tileh_end = GetTileSlope(tile_end, &z_end);
    00259
    00260   CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
    00261   CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end,   &z_end);
    00262
    00263   if (z_start != z_end) return_cmd_error(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT);
    00264
    00265   if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
    00266       GetOtherBridgeEnd(tile_start) == tile_end &&
    00267       GetTunnelBridgeTransportType(tile_start) == transport_type) {
    00268     /* Replace a current bridge. */
    00269
    00270     /* If this is a railway bridge, make sure the railtypes match. */
    00271     if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
    00272       return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00273     }
    00274
    00275     /* Do not replace town bridges with lower speed bridges. */
    00276     if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
    00277         GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed) {
    00278       Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
    00279
    00280       if (t == NULL) {
    00281         return CMD_ERROR;
    00282       } else {
    00283         SetDParam(0, t->index);
    00284         return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
    00285       }
    00286     }
    00287
    00288     /* Do not replace the bridge with the same bridge type. */
    00289     if (!(flags & DC_QUERY_COST) && bridge_type == GetBridgeType(tile_start)) {
    00290       return_cmd_error(STR_ERROR_ALREADY_BUILT);
    00291     }
    00292
    00293     /* Do not allow replacing another company's bridges. */
    00294     if (!IsTileOwner(tile_start, _current_company) && !IsTileOwner(tile_start, OWNER_TOWN)) {
    00295       return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
    00296     }
    00297
    00298     cost.AddCost((bridge_len + 1) * _price[PR_CLEAR_BRIDGE]); // The cost of clearing the current bridge.
    00299     owner = GetTileOwner(tile_start);
    00300
    00301     /* Do not remove road types when upgrading a bridge */
    00302     roadtypes |= GetRoadTypes(tile_start);
    00303   } else {
    00304     /* Build a new bridge. */
    00305
    00306     bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
    00307
    00308     /* Try and clear the start landscape */
    00309     CommandCost ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00310     if (ret.Failed()) return ret;
    00311     cost = ret;
    00312
    00313     if (terraform_cost_north.Failed() || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes))
    00314       return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
    00315     cost.AddCost(terraform_cost_north);
    00316
    00317     /* Try and clear the end landscape */
    00318     ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00319     if (ret.Failed()) return ret;
    00320     cost.AddCost(ret);
    00321
    00322     /* false - end tile slope check */
    00323     if (terraform_cost_south.Failed() || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes))
    00324       return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
    00325     cost.AddCost(terraform_cost_south);
    00326
    00327     if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
    00328
    00329     const TileIndex heads[] = {tile_start, tile_end};
    00330     for (int i = 0; i < 2; i++) {
    00331       if (MayHaveBridgeAbove(heads[i])) {
    00332         if (IsBridgeAbove(heads[i])) {
    00333           TileIndex north_head = GetNorthernBridgeEnd(heads[i]);
    00334
    00335           if (direction == GetBridgeAxis(heads[i])) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00336
    00337           if (z_start + TILE_HEIGHT == GetBridgeHeight(north_head)) {
    00338             return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00339           }
    00340         }
    00341       }
    00342     }
    00343
    00344     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
    00345     for (TileIndex tile = tile_start + delta; tile != tile_end; tile += delta) {
    00346       if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN);
    00347
    00348       if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
    00349         /* Disallow crossing bridges for the time being */
    00350         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00351       }
    00352
    00353       switch (GetTileType(tile)) {
    00354         case MP_WATER:
    00355           if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
    00356           break;
    00357
    00358         case MP_RAILWAY:
    00359           if (!IsPlainRail(tile)) goto not_valid_below;
    00360           break;
    00361
    00362         case MP_ROAD:
    00363           if (IsRoadDepot(tile)) goto not_valid_below;
    00364           break;
    00365
    00366         case MP_TUNNELBRIDGE:
    00367           if (IsTunnel(tile)) break;
    00368           if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
    00369           if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
    00370           break;
    00371
    00372         case MP_UNMOVABLE:
    00373           if (!IsOwnedLand(tile)) goto not_valid_below;
    00374           break;
    00375
    00376         case MP_CLEAR:
    00377           break;
    00378
    00379         default:
    00380   not_valid_below:;
    00381           /* try and clear the middle landscape */
    00382           ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00383           if (ret.Failed()) return ret;
    00384           cost.AddCost(ret);
    00385           break;
    00386       }
    00387
    00388       if (flags & DC_EXEC) {
    00389         /* We do this here because when replacing a bridge with another
    00390          * type calling SetBridgeMiddle isn't needed. After all, the
    00391          * tile alread has the has_bridge_above bits set. */
    00392         SetBridgeMiddle(tile, direction);
    00393       }
    00394     }
    00395
    00396     owner = _current_company;
    00397   }
    00398
    00399   /* do the drill? */
    00400   if (flags & DC_EXEC) {
    00401     DiagDirection dir = AxisToDiagDir(direction);
    00402
    00403     switch (transport_type) {
    00404       case TRANSPORT_RAIL:
    00405         MakeRailBridgeRamp(tile_start, owner, bridge_type, dir,                 railtype);
    00406         MakeRailBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), railtype);
    00407         break;
    00408
    00409       case TRANSPORT_ROAD:
    00410         MakeRoadBridgeRamp(tile_start, owner, bridge_type, dir,                 roadtypes);
    00411         MakeRoadBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), roadtypes);
    00412         break;
    00413
    00414       case TRANSPORT_WATER:
    00415         MakeAqueductBridgeRamp(tile_start, owner, dir);
    00416         MakeAqueductBridgeRamp(tile_end,   owner, ReverseDiagDir(dir));
    00417         break;
    00418
    00419       default:
    00420         NOT_REACHED();
    00421     }
    00422
    00423     /* Mark all tiles dirty */
    00424     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
    00425     for (TileIndex tile = tile_start; tile <= tile_end; tile += delta) {
    00426       MarkTileDirtyByTile(tile);
    00427     }
    00428   }
    00429
    00430   if ((flags & DC_EXEC) && transport_type == TRANSPORT_RAIL) {
    00431     Track track = AxisToTrack(direction);
    00432     AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, _current_company);
    00433     YapfNotifyTrackLayoutChange(tile_start, track);
    00434   }
    00435
    00436   /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
    00437    * It's unnecessary to execute this command every time for every bridge. So it is done only
    00438    * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
    00439    */
    00440   Company *c = Company::GetIfValid(_current_company);
    00441   if (!(flags & DC_QUERY_COST) || (c != NULL && c->is_ai)) {
    00442     bridge_len += 2; // begin and end tiles/ramps
    00443
    00444     if (c != NULL) bridge_len = CalcBridgeLenCostFactor(bridge_len);
    00445
    00446     cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
    00447
    00448     /* Aqueducts are a little more expensive. */
    00449     if (transport_type == TRANSPORT_WATER) cost.AddCost((int64)bridge_len * _price[PR_CLEAR_WATER]);
    00450   }
    00451
    00452   return cost;
    00453 }
    00454
    00455
    00464 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00465 {
    00466   TransportType transport_type = (TransportType)GB(p1, 9, 1);
    00467   CommandCost cost(EXPENSES_CONSTRUCTION);
    00468
    00469   _build_tunnel_endtile = 0;
    00470   if (transport_type == TRANSPORT_RAIL) {
    00471     if (!ValParamRailtype((RailType)p1)) return CMD_ERROR;
    00472   } else {
    00473     const RoadTypes rts = (RoadTypes)GB(p1, 0, 2);
    00474     if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
    00475   }
    00476
    00477   uint start_z;
    00478   uint end_z;
    00479   Slope start_tileh = GetTileSlope(start_tile, &start_z);
    00480   DiagDirection direction = GetInclinedSlopeDirection(start_tileh);
    00481   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
    00482
    00483   if (IsWaterTile(start_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
    00484
    00485   CommandCost ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00486   if (ret.Failed()) return ret;
    00487
    00488   /* XXX - do NOT change 'ret' in the loop, as it is used as the price
    00489    * for the clearing of the entrance of the tunnel. Assigning it to
    00490    * cost before the loop will yield different costs depending on start-
    00491    * position, because of increased-cost-by-length: 'cost += cost >> 3' */
    00492
    00493   TileIndexDiff delta = TileOffsByDiagDir(direction);
    00494   DiagDirection tunnel_in_way_dir;
    00495   if (DiagDirToAxis(direction) == AXIS_Y) {
    00496     tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
    00497   } else {
    00498     tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
    00499   }
    00500
    00501   TileIndex end_tile = start_tile;
    00502
    00503   /* Tile shift coeficient. Will decrease for very long tunnels to avoid exponential growth of price*/
    00504   int tiles_coef = 3;
    00505   /* Number of tiles from start of tunnel */
    00506   int tiles = 0;
    00507   /* Number of tiles at which the cost increase coefficient per tile is halved */
    00508   int tiles_bump = 25;
    00509
    00510   Slope end_tileh;
    00511   for (;;) {
    00512     end_tile += delta;
    00513     if (!IsValidTile(end_tile)) return_cmd_error(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
    00514     end_tileh = GetTileSlope(end_tile, &end_z);
    00515
    00516     if (start_z == end_z) break;
    00517
    00518     if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
    00519       return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
    00520     }
    00521
    00522     tiles++;
    00523     if (tiles == tiles_bump) {
    00524       tiles_coef++;
    00525       tiles_bump *= 2;
    00526     }
    00527
    00528     cost.AddCost(_price[PR_BUILD_TUNNEL]);
    00529     cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
    00530   }
    00531
    00532   /* Add the cost of the entrance */
    00533   cost.AddCost(_price[PR_BUILD_TUNNEL]);
    00534   cost.AddCost(ret);
    00535
    00536   /* if the command fails from here on we want the end tile to be highlighted */
    00537   _build_tunnel_endtile = end_tile;
    00538
    00539   if (IsWaterTile(end_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
    00540
    00541   /* slope of end tile must be complementary to the slope of the start tile */
    00542   if (end_tileh != ComplementSlope(start_tileh)) {
    00543     /* Check if there is a structure on the terraformed tile. Do not add the cost, that will be done by the terraforming
    00544      * Note: Currently the town rating is also affected by this clearing-test. So effectivly the player is punished twice for clearing
    00545      *       the tree on end_tile.
    00546      */
    00547     ret = DoCommand(end_tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR);
    00548     if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
    00549
    00550     ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
    00551     if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
    00552   } else {
    00553     ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00554     if (ret.Failed()) return ret;
    00555   }
    00556   cost.AddCost(_price[PR_BUILD_TUNNEL]);
    00557   cost.AddCost(ret);
    00558
    00559   if (flags & DC_EXEC) {
    00560     if (transport_type == TRANSPORT_RAIL) {
    00561       MakeRailTunnel(start_tile, _current_company, direction,                 (RailType)GB(p1, 0, 4));
    00562       MakeRailTunnel(end_tile,   _current_company, ReverseDiagDir(direction), (RailType)GB(p1, 0, 4));
    00563       AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, _current_company);
    00564       YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
    00565     } else {
    00566       MakeRoadTunnel(start_tile, _current_company, direction,                 (RoadTypes)GB(p1, 0, 2));
    00567       MakeRoadTunnel(end_tile,   _current_company, ReverseDiagDir(direction), (RoadTypes)GB(p1, 0, 2));
    00568     }
    00569   }
    00570
    00571   return cost;
    00572 }
    00573
    00574
    00575 static inline bool CheckAllowRemoveTunnelBridge(TileIndex tile)
    00576 {
    00577   /* Floods can remove anything as well as the scenario editor */
    00578   if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return true;
    00579
    00580   switch (GetTunnelBridgeTransportType(tile)) {
    00581     case TRANSPORT_ROAD: {
    00582       RoadTypes rts = GetRoadTypes(tile);
    00583       Owner road_owner = _current_company;
    00584       Owner tram_owner = _current_company;
    00585
    00586       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    00587       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    00588
    00589       /* We can remove unowned road and if the town allows it */
    00590       if (road_owner == OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) return CheckTileOwnership(tile);
    00591       if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
    00592       if (tram_owner == OWNER_NONE) tram_owner = _current_company;
    00593
    00594       return CheckOwnership(road_owner, tile) && CheckOwnership(tram_owner, tile);
    00595     }
    00596
    00597     case TRANSPORT_RAIL:
    00598     case TRANSPORT_WATER:
    00599       return CheckOwnership(GetTileOwner(tile));
    00600
    00601     default: NOT_REACHED();
    00602   }
    00603 }
    00604
    00605 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
    00606 {
    00607   Town *t = NULL;
    00608   TileIndex endtile;
    00609
    00610   if (!CheckAllowRemoveTunnelBridge(tile)) return CMD_ERROR;
    00611
    00612   endtile = GetOtherTunnelEnd(tile);
    00613
    00614   if (HasVehicleOnTunnelBridge(tile, endtile)) return CMD_ERROR;
    00615
    00616   _build_tunnel_endtile = endtile;
    00617
    00618   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
    00619     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
    00620
    00621     /* Check if you are allowed to remove the tunnel owned by a town
    00622      * Removal depends on difficulty settings */
    00623     if (!CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE)) {
    00624       SetDParam(0, t->index);
    00625       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
    00626     }
    00627   }
    00628
    00629   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
    00630    * you have a "Poor" (0) town rating */
    00631   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
    00632     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
    00633   }
    00634
    00635   if (flags & DC_EXEC) {
    00636     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
    00637       /* We first need to request values before calling DoClearSquare */
    00638       DiagDirection dir = GetTunnelBridgeDirection(tile);
    00639       Track track = DiagDirToDiagTrack(dir);
    00640       Owner owner = GetTileOwner(tile);
    00641
    00642       Train *v = NULL;
    00643       if (HasTunnelBridgeReservation(tile)) {
    00644         v = GetTrainForReservation(tile, track);
    00645         if (v != NULL) FreeTrainTrackReservation(v);
    00646       }
    00647
    00648       DoClearSquare(tile);
    00649       DoClearSquare(endtile);
    00650
    00651       /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
    00652       AddSideToSignalBuffer(tile,    ReverseDiagDir(dir), owner);
    00653       AddSideToSignalBuffer(endtile, dir,                 owner);
    00654
    00655       YapfNotifyTrackLayoutChange(tile,    track);
    00656       YapfNotifyTrackLayoutChange(endtile, track);
    00657
    00658       if (v != NULL) TryPathReserve(v);
    00659     } else {
    00660       DoClearSquare(tile);
    00661       DoClearSquare(endtile);
    00662     }
    00663   }
    00664   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_TUNNEL] * (GetTunnelBridgeLength(tile, endtile) + 2));
    00665 }
    00666
    00667
    00668 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
    00669 {
    00670   DiagDirection direction;
    00671   TileIndexDiff delta;
    00672   TileIndex endtile;
    00673   Town *t = NULL;
    00674
    00675   if (!CheckAllowRemoveTunnelBridge(tile)) return CMD_ERROR;
    00676
    00677   endtile = GetOtherBridgeEnd(tile);
    00678
    00679   if (HasVehicleOnTunnelBridge(tile, endtile)) return CMD_ERROR;
    00680
    00681   direction = GetTunnelBridgeDirection(tile);
    00682   delta = TileOffsByDiagDir(direction);
    00683
    00684   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
    00685     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
    00686
    00687     /* Check if you are allowed to remove the bridge owned by a town
    00688      * Removal depends on difficulty settings */
    00689     if (!CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE)) {
    00690       SetDParam(0, t->index);
    00691       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
    00692     }
    00693   }
    00694
    00695   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
    00696    * you have a "Poor" (0) town rating */
    00697   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
    00698     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
    00699   }
    00700
    00701   if (flags & DC_EXEC) {
    00702     /* read this value before actual removal of bridge */
    00703     bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
    00704     Owner owner = GetTileOwner(tile);
    00705     uint height = GetBridgeHeight(tile);
    00706     Train *v = NULL;
    00707
    00708     if (rail && HasTunnelBridgeReservation(tile)) {
    00709       v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
    00710       if (v != NULL) FreeTrainTrackReservation(v);
    00711     }
    00712
    00713     DoClearSquare(tile);
    00714     DoClearSquare(endtile);
    00715     for (TileIndex c = tile + delta; c != endtile; c += delta) {
    00716       /* do not let trees appear from 'nowhere' after removing bridge */
    00717       if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
    00718         uint minz = GetTileMaxZ(c) + 3 * TILE_HEIGHT;
    00719         if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
    00720       }
    00721       ClearBridgeMiddle(c);
    00722       MarkTileDirtyByTile(c);
    00723     }
    00724
    00725     if (rail) {
    00726       /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
    00727       AddSideToSignalBuffer(tile,    ReverseDiagDir(direction), owner);
    00728       AddSideToSignalBuffer(endtile, direction,                 owner);
    00729
    00730       Track track = DiagDirToDiagTrack(direction);
    00731       YapfNotifyTrackLayoutChange(tile,    track);
    00732       YapfNotifyTrackLayoutChange(endtile, track);
    00733
    00734       if (v != NULL) TryPathReserve(v, true);
    00735     }
    00736   }
    00737
    00738   return CommandCost(EXPENSES_CONSTRUCTION, (GetTunnelBridgeLength(tile, endtile) + 2) * _price[PR_CLEAR_BRIDGE]);
    00739 }
    00740
    00741 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
    00742 {
    00743   if (IsTunnel(tile)) {
    00744     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
    00745     return DoClearTunnel(tile, flags);
    00746   } else { // IsBridge(tile)
    00747     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00748     return DoClearBridge(tile, flags);
    00749   }
    00750
    00751   return CMD_ERROR;
    00752 }
    00753
    00765 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
    00766 {
    00767   /* Do not draw bridge pillars if they are invisible */
    00768   if (IsInvisibilitySet(TO_BRIDGES)) return;
    00769
    00770   SpriteID image = psid->sprite;
    00771
    00772   if (image != 0) {
    00773     /* "side" specifies the side the pillars stand on.
    00774      * The length of the pillars is then set to the height of the bridge over the corners of this edge.
    00775      *
    00776      *                axis==AXIS_X  axis==AXIS_Y
    00777      *   side==false      SW            NW
    00778      *   side==true       NE            SE
    00779      *
    00780      * I have no clue, why this was done this way.
    00781      */
    00782     bool side = HasBit(image, 0);
    00783
    00784     /* "dir" means the edge the pillars stand on */
    00785     DiagDirection dir = AxisToDiagDir(axis);
    00786     if (side != (axis == AXIS_Y)) dir = ReverseDiagDir(dir);
    00787
    00788     /* Determine ground height under pillars */
    00789     int front_height = ti->z;
    00790     int back_height = ti->z;
    00791     GetSlopeZOnEdge(ti->tileh, dir, &front_height, &back_height);
    00792
    00793     /* x and y size of bounding-box of pillars */
    00794     int w = (axis == AXIS_X ? 16 : 2);
    00795     int h = (axis == AXIS_X ? 2 : 16);
    00796     /* sprite position of back facing pillar */
    00797     int x_back = x - (axis == AXIS_X ? 0 : 9);
    00798     int y_back = y - (axis == AXIS_X ? 9 : 0);
    00799
    00800     for (int cur_z = z_bridge; cur_z >= front_height || cur_z >= back_height; cur_z -= TILE_HEIGHT) {
    00801       /* Draw front facing pillar */
    00802       if (cur_z >= front_height) {
    00803         AddSortableSpriteToDraw(image, psid->pal, x, y, w, h, BB_HEIGHT_UNDER_BRIDGE - 5, cur_z, IsTransparencySet(TO_BRIDGES), 0, 0, -5);
    00804       }
    00805
    00806       /* Draw back facing pillar, but not the highest part directly under the bridge-floor */
    00807       if (drawfarpillar && cur_z >= back_height && cur_z < z_bridge - TILE_HEIGHT) {
    00808         AddSortableSpriteToDraw(image, psid->pal, x_back, y_back, w, h, BB_HEIGHT_UNDER_BRIDGE - 5, cur_z, IsTransparencySet(TO_BRIDGES), 0, 0, -5);
    00809       }
    00810     }
    00811   }
    00812 }
    00813
    00823 static void DrawBridgeTramBits(int x, int y, byte z, int offset, bool overlay, bool head)
    00824 {
    00825   static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
    00826   static const SpriteID back_offsets[6]    =   {  95,  96,  99, 102, 100, 101 };
    00827   static const SpriteID front_offsets[6]   =   {  97,  98, 103, 106, 104, 105 };
    00828
    00829   static const uint size_x[6] = {  1, 16, 16,  1, 16,  1 };
    00830   static const uint size_y[6] = { 16,  1,  1, 16,  1, 16 };
    00831   static const uint front_bb_offset_x[6] = { 15,  0,  0, 15,  0, 15 };
    00832   static const uint front_bb_offset_y[6] = {  0, 15, 15,  0, 15,  0 };
    00833
    00834   /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
    00835    * The bounding boxes here are the same as for bridge front/roof */
    00836   if (head || !IsInvisibilitySet(TO_BRIDGES)) {
    00837     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
    00838       x, y, size_x[offset], size_y[offset], 0x28, z,
    00839       !head && IsTransparencySet(TO_BRIDGES));
    00840   }
    00841
    00842   /* Do not draw catenary if it is set invisible */
    00843   if (!IsInvisibilitySet(TO_CATENARY)) {
    00844     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
    00845       x, y, size_x[offset], size_y[offset], 0x28, z,
    00846       IsTransparencySet(TO_CATENARY));
    00847   }
    00848
    00849   /* Start a new SpriteCombine for the front part */
    00850   EndSpriteCombine();
    00851   StartSpriteCombine();
    00852
    00853   /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
    00854   if (!IsInvisibilitySet(TO_CATENARY)) {
    00855     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
    00856       x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
    00857       IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
    00858   }
    00859 }
    00860
    00874 static void DrawTile_TunnelBridge(TileInfo *ti)
    00875 {
    00876   SpriteID image;
    00877   TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
    00878   DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
    00879
    00880   if (IsTunnel(ti->tile)) {
    00881     /* Front view of tunnel bounding boxes:
    00882      *
    00883      *   122223  <- BB_Z_SEPARATOR
    00884      *   1    3
    00885      *   1    3                1,3 = empty helper BB
    00886      *   1    3                  2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
    00887      *
    00888      */
    00889
    00890     static const int _tunnel_BB[4][12] = {
    00891       /*  tunnnel-roof  |  Z-separator  | tram-catenary
    00892        * w  h  bb_x bb_y| x   y   w   h |bb_x bb_y w h */
    00893       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // NE
    00894       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // SE
    00895       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // SW
    00896       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // NW
    00897     };
    00898     const int *BB_data = _tunnel_BB[tunnelbridge_direction];
    00899
    00900     bool catenary = false;
    00901
    00902     if (transport_type == TRANSPORT_RAIL) {
    00903       image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.tunnel;
    00904     } else {
    00905       image = SPR_TUNNEL_ENTRY_REAR_ROAD;
    00906     }
    00907
    00908     if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += 32;
    00909
    00910     image += tunnelbridge_direction * 2;
    00911     DrawGroundSprite(image, PAL_NONE);
    00912
    00913     /* PBS debugging, draw reserved tracks darker */
    00914     if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && (transport_type == TRANSPORT_RAIL && HasTunnelBridgeReservation(ti->tile))) {
    00915       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
    00916       DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
    00917     }
    00918
    00919     if (transport_type == TRANSPORT_ROAD) {
    00920       RoadTypes rts = GetRoadTypes(ti->tile);
    00921
    00922       if (HasBit(rts, ROADTYPE_TRAM)) {
    00923         static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, {  5, 76, 77,  4 } };
    00924
    00925         DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
    00926
    00927         /* Do not draw wires if they are invisible */
    00928         if (!IsInvisibilitySet(TO_CATENARY)) {
    00929           catenary = true;
    00930           StartSpriteCombine();
    00931           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);
    00932         }
    00933       }
    00934     } else {
    00935       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
    00936       if (rti->UsesOverlay()) {
    00937         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
    00938         if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
    00939       }
    00940
    00941       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
    00942         /* Maybe draw pylons on the entry side */
    00943         DrawCatenary(ti);
    00944
    00945         catenary = true;
    00946         StartSpriteCombine();
    00947         /* Draw wire above the ramp */
    00948         DrawCatenaryOnTunnel(ti);
    00949       }
    00950     }
    00951
    00952     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);
    00953
    00954     if (catenary) EndSpriteCombine();
    00955
    00956     /* Add helper BB for sprite sorting, that separate the tunnel from things beside of it */
    00957     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x,              ti->y,              BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
    00958     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);
    00959
    00960     DrawBridgeMiddle(ti);
    00961   } else { // IsBridge(ti->tile)
    00962     const PalSpriteID *psid;
    00963     int base_offset;
    00964     bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
    00965
    00966     if (transport_type == TRANSPORT_RAIL) {
    00967       base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
    00968       assert(base_offset != 8); // This one is used for roads
    00969     } else {
    00970       base_offset = 8;
    00971     }
    00972
    00973     /* as the lower 3 bits are used for other stuff, make sure they are clear */
    00974     assert( (base_offset & 0x07) == 0x00);
    00975
    00976     DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
    00977
    00978     /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
    00979     base_offset += (6 - tunnelbridge_direction) % 4;
    00980
    00981     if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
    00982
    00983     /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
    00984     if (transport_type != TRANSPORT_WATER) {
    00985       psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
    00986     } else {
    00987       psid = _aqueduct_sprites + base_offset;
    00988     }
    00989
    00990     if (!ice) {
    00991       DrawClearLandTile(ti, 3);
    00992     } else {
    00993       DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + _tileh_to_sprite[ti->tileh], PAL_NONE);
    00994     }
    00995
    00996     /* draw ramp */
    00997
    00998     /* Draw Trambits and PBS Reservation as SpriteCombine */
    00999     if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
    01000
    01001     /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
    01002      * it doesn't disappear behind it
    01003      */
    01004     /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
    01005     AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
    01006
    01007     if (transport_type == TRANSPORT_ROAD) {
    01008       RoadTypes rts = GetRoadTypes(ti->tile);
    01009
    01010       if (HasBit(rts, ROADTYPE_TRAM)) {
    01011         uint offset = tunnelbridge_direction;
    01012         uint z = ti->z;
    01013         if (ti->tileh != SLOPE_FLAT) {
    01014           offset = (offset + 1) & 1;
    01015           z += TILE_HEIGHT;
    01016         } else {
    01017           offset += 2;
    01018         }
    01019         /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
    01020         DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
    01021       }
    01022       EndSpriteCombine();
    01023     } else if (transport_type == TRANSPORT_RAIL) {
    01024       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
    01025       if (rti->UsesOverlay()) {
    01026         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
    01027         if (surface != 0) {
    01028           if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
    01029             AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
    01030           } else {
    01031             AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
    01032           }
    01033         }
    01034         /* Don't fallback to non-overlay sprite -- the spec states that
    01035          * if an overlay is present then the bridge surface must be
    01036          * present. */
    01037       } else if (_game_mode != GM_MENU &&_settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
    01038         if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
    01039           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);
    01040         } else {
    01041           AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
    01042         }
    01043       }
    01044       EndSpriteCombine();
    01045       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
    01046         DrawCatenary(ti);
    01047       }
    01048     }
    01049
    01050     DrawBridgeMiddle(ti);
    01051   }
    01052 }
    01053
    01054
    01072 static BridgePieces CalcBridgePiece(uint north, uint south)
    01073 {
    01074   if (north == 1) {
    01075     return BRIDGE_PIECE_NORTH;
    01076   } else if (south == 1) {
    01077     return BRIDGE_PIECE_SOUTH;
    01078   } else if (north < south) {
    01079     return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
    01080   } else if (north > south) {
    01081     return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
    01082   } else {
    01083     return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
    01084   }
    01085 }
    01086
    01087
    01088 void DrawBridgeMiddle(const TileInfo *ti)
    01089 {
    01090   /* Sectional view of bridge bounding boxes:
    01091    *
    01092    *  1           2                                1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
    01093    *  1           2                                  3 = empty helper BB
    01094    *  1     7     2                                4,5 = pillars under higher bridges
    01095    *  1 6 88888 6 2                                  6 = elrail-pylons
    01096    *  1 6 88888 6 2                                  7 = elrail-wire
    01097    *  1 6 88888 6 2  <- TILE_HEIGHT                  8 = rail-vehicle on bridge
    01098    *  3333333333333  <- BB_Z_SEPARATOR
    01099    *                 <- unused
    01100    *    4       5    <- BB_HEIGHT_UNDER_BRIDGE
    01101    *    4       5
    01102    *    4       5
    01103    *
    01104    */
    01105
    01106   /* Z position of the bridge sprites relative to bridge height (downwards) */
    01107   static const int BRIDGE_Z_START = 3;
    01108
    01109   if (!IsBridgeAbove(ti->tile)) return;
    01110
    01111   TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
    01112   TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
    01113   TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
    01114
    01115   Axis axis = GetBridgeAxis(ti->tile);
    01116   BridgePieces piece = CalcBridgePiece(
    01117     GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
    01118     GetTunnelBridgeLength(ti->tile, rampsouth) + 1
    01119   );
    01120
    01121   const PalSpriteID *psid;
    01122   bool drawfarpillar;
    01123   if (transport_type != TRANSPORT_WATER) {
    01124     BridgeType type =  GetBridgeType(rampsouth);
    01125     drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
    01126
    01127     uint base_offset;
    01128     if (transport_type == TRANSPORT_RAIL) {
    01129       base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
    01130     } else {
    01131       base_offset = 8;
    01132     }
    01133
    01134     psid = base_offset + GetBridgeSpriteTable(type, piece);
    01135   } else {
    01136     drawfarpillar = true;
    01137     psid = _aqueduct_sprites;
    01138   }
    01139
    01140   if (axis != AXIS_X) psid += 4;
    01141
    01142   int x = ti->x;
    01143   int y = ti->y;
    01144   uint bridge_z = GetBridgeHeight(rampsouth);
    01145   uint z = bridge_z - BRIDGE_Z_START;
    01146
    01147   /* Add a bounding box, that separates the bridge from things below it. */
    01148   AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
    01149
    01150   /* Draw Trambits as SpriteCombine */
    01151   if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
    01152
    01153   /* Draw floor and far part of bridge*/
    01154   if (!IsInvisibilitySet(TO_BRIDGES)) {
    01155     if (axis == AXIS_X) {
    01156       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
    01157     } else {
    01158       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
    01159     }
    01160   }
    01161
    01162   psid++;
    01163
    01164   if (transport_type == TRANSPORT_ROAD) {
    01165     RoadTypes rts = GetRoadTypes(rampsouth);
    01166
    01167     if (HasBit(rts, ROADTYPE_TRAM)) {
    01168       /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
    01169       DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
    01170     } else {
    01171       EndSpriteCombine();
    01172       StartSpriteCombine();
    01173     }
    01174   } else if (transport_type == TRANSPORT_RAIL) {
    01175     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
    01176     if (rti->UsesOverlay()) {
    01177       SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
    01178       if (surface != 0) {
    01179         AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
    01180       }
    01181     }
    01182     EndSpriteCombine();
    01183
    01184     if (HasCatenaryDrawn(GetRailType(rampsouth))) {
    01185       DrawCatenaryOnBridge(ti);
    01186     }
    01187   }
    01188
    01189   /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
    01190   if (!IsInvisibilitySet(TO_BRIDGES)) {
    01191     if (axis == AXIS_X) {
    01192       y += 12;
    01193       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
    01194     } else {
    01195       x += 12;
    01196       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
    01197     }
    01198   }
    01199
    01200   /* Draw TramFront as SpriteCombine */
    01201   if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
    01202
    01203   /* Do not draw anything more if bridges are invisible */
    01204   if (IsInvisibilitySet(TO_BRIDGES)) return;
    01205
    01206   psid++;
    01207   if (ti->z + 5 == z) {
    01208     /* draw poles below for small bridges */
    01209     if (psid->sprite != 0) {
    01210       SpriteID image = psid->sprite;
    01211       SpriteID pal   = psid->pal;
    01212       if (IsTransparencySet(TO_BRIDGES)) {
    01213         SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
    01214         pal = PALETTE_TO_TRANSPARENT;
    01215       }
    01216
    01217       DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
    01218     }
    01219   } else if (_settings_client.gui.bridge_pillars) {
    01220     /* draw pillars below for high bridges */
    01221     DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
    01222   }
    01223 }
    01224
    01225
    01226 static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y)
    01227 {
    01228   uint z;
    01229   Slope tileh = GetTileSlope(tile, &z);
    01230
    01231   x &= 0xF;
    01232   y &= 0xF;
    01233
    01234   if (IsTunnel(tile)) {
    01235     uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
    01236
    01237     /* In the tunnel entrance? */
    01238     if (5 <= pos && pos <= 10) return z;
    01239   } else { // IsBridge(tile)
    01240     DiagDirection dir = GetTunnelBridgeDirection(tile);
    01241     uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
    01242
    01243     z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
    01244
    01245     /* On the bridge ramp? */
    01246     if (5 <= pos && pos <= 10) {
    01247       uint delta;
    01248
    01249       if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
    01250
    01251       switch (dir) {
    01252         default: NOT_REACHED();
    01253         case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
    01254         case DIAGDIR_SE: delta = y / 2; break;
    01255         case DIAGDIR_SW: delta = x / 2; break;
    01256         case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
    01257       }
    01258       return z + 1 + delta;
    01259     }
    01260   }
    01261
    01262   return z + GetPartialZ(x, y, tileh);
    01263 }
    01264
    01265 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
    01266 {
    01267   return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
    01268 }
    01269
    01270 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
    01271 {
    01272   TransportType tt = GetTunnelBridgeTransportType(tile);
    01273
    01274   if (IsTunnel(tile)) {
    01275     td->str = (tt == TRANSPORT_RAIL) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
    01276   } else { // IsBridge(tile)
    01277     td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
    01278   }
    01279   td->owner[0] = GetTileOwner(tile);
    01280
    01281   Owner road_owner = INVALID_OWNER;
    01282   Owner tram_owner = INVALID_OWNER;
    01283   RoadTypes rts = GetRoadTypes(tile);
    01284   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    01285   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    01286
    01287   /* Is there a mix of owners? */
    01288   if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
    01289       (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
    01290     uint i = 1;
    01291     if (road_owner != INVALID_OWNER) {
    01292       td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
    01293       td->owner[i] = road_owner;
    01294       i++;
    01295     }
    01296     if (tram_owner != INVALID_OWNER) {
    01297       td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
    01298       td->owner[i] = tram_owner;
    01299     }
    01300   }
    01301 }
    01302
    01303
    01304 static void TileLoop_TunnelBridge(TileIndex tile)
    01305 {
    01306   bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
    01307   switch (_settings_game.game_creation.landscape) {
    01308     case LT_ARCTIC:
    01309       if (snow_or_desert != (GetTileZ(tile) > GetSnowLine())) {
    01310         SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
    01311         MarkTileDirtyByTile(tile);
    01312       }
    01313       break;
    01314
    01315     case LT_TROPIC:
    01316       if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
    01317         SetTunnelBridgeSnowOrDesert(tile, true);
    01318         MarkTileDirtyByTile(tile);
    01319       }
    01320       break;
    01321
    01322     default:
    01323       break;
    01324   }
    01325 }
    01326
    01327 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
    01328 {
    01329   TransportType transport_type = GetTunnelBridgeTransportType(tile);
    01330   if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
    01331
    01332   DiagDirection dir = GetTunnelBridgeDirection(tile);
    01333   if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
    01334   return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
    01335 }
    01336
    01337 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
    01338 {
    01339   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
    01340     /* Update all roadtypes, no matter if they are present */
    01341     if (GetRoadOwner(tile, rt) == old_owner) {
    01342       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
    01343     }
    01344   }
    01345
    01346   if (!IsTileOwner(tile, old_owner)) return;
    01347
    01348   if (new_owner != INVALID_OWNER) {
    01349     SetTileOwner(tile, new_owner);
    01350   } else {
    01351     if (DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR).Failed()) {
    01352       /* When clearing the bridge/tunnel failed there are still vehicles on/in
    01353        * the bridge/tunnel. As all *our* vehicles are already removed, they
    01354        * must be of another owner. Therefore this can't be rail tunnel/bridge.
    01355        * In that case we can safely reassign the ownership to OWNER_NONE. */
    01356       assert(GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL);
    01357       SetTileOwner(tile, OWNER_NONE);
    01358     }
    01359   }
    01360 }
    01361
    01362
    01363 static const byte _tunnel_fractcoord_1[4]    = {0x8E, 0x18, 0x81, 0xE8};
    01364 static const byte _tunnel_fractcoord_2[4]    = {0x81, 0x98, 0x87, 0x38};
    01365 static const byte _tunnel_fractcoord_3[4]    = {0x82, 0x88, 0x86, 0x48};
    01366 static const byte _exit_tunnel_track[4]      = {1, 2, 1, 2};
    01367
    01369 static const Trackdir _road_exit_tunnel_state[DIAGDIR_END] = {
    01370   TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
    01371 };
    01372 static const byte _road_exit_tunnel_frame[4] = {2, 7, 9, 4};
    01373
    01374 static const byte _tunnel_fractcoord_4[4]    = {0x52, 0x85, 0x98, 0x29};
    01375 static const byte _tunnel_fractcoord_5[4]    = {0x92, 0x89, 0x58, 0x25};
    01376 static const byte _tunnel_fractcoord_6[4]    = {0x92, 0x89, 0x56, 0x45};
    01377 static const byte _tunnel_fractcoord_7[4]    = {0x52, 0x85, 0x96, 0x49};
    01378
    01379 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
    01380 {
    01381   int z = GetSlopeZ(x, y) - v->z_pos;
    01382
    01383   if (abs(z) > 2) return VETSB_CANNOT_ENTER;
    01384   const DiagDirection dir = GetTunnelBridgeDirection(tile);
    01385
    01386   if (IsTunnel(tile)) {
    01387     byte fc;
    01388     DiagDirection vdir;
    01389
    01390     if (v->type == VEH_TRAIN) {
    01391       Train *t = Train::From(v);
    01392       fc = (x & 0xF) + (y << 4);
    01393
    01394       vdir = DirToDiagDir(t->direction);
    01395
    01396       if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
    01397         if (t->IsFrontEngine() && fc == _tunnel_fractcoord_1[dir]) {
    01398           if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
    01399             SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
    01400           }
    01401           return VETSB_CONTINUE;
    01402         }
    01403         if (fc == _tunnel_fractcoord_2[dir]) {
    01404           t->tile = tile;
    01405           t->track = TRACK_BIT_WORMHOLE;
    01406           t->vehstatus |= VS_HIDDEN;
    01407           return VETSB_ENTERED_WORMHOLE;
    01408         }
    01409       }
    01410
    01411       if (dir == ReverseDiagDir(vdir) && fc == _tunnel_fractcoord_3[dir] && z == 0) {
    01412         /* We're at the tunnel exit ?? */
    01413         t->tile = tile;
    01414         t->track = (TrackBits)_exit_tunnel_track[dir];
    01415         assert(t->track);
    01416         t->vehstatus &= ~VS_HIDDEN;
    01417         return VETSB_ENTERED_WORMHOLE;
    01418       }
    01419     } else if (v->type == VEH_ROAD) {
    01420       RoadVehicle *rv = RoadVehicle::From(v);
    01421       fc = (x & 0xF) + (y << 4);
    01422       vdir = DirToDiagDir(v->direction);
    01423
    01424       /* Enter tunnel? */
    01425       if (rv->state != RVSB_WORMHOLE && dir == vdir) {
    01426         if (fc == _tunnel_fractcoord_4[dir] ||
    01427             fc == _tunnel_fractcoord_5[dir]) {
    01428           rv->tile = tile;
    01429           rv->state = RVSB_WORMHOLE;
    01430           rv->vehstatus |= VS_HIDDEN;
    01431           return VETSB_ENTERED_WORMHOLE;
    01432         } else {
    01433           return VETSB_CONTINUE;
    01434         }
    01435       }
    01436
    01437       if (dir == ReverseDiagDir(vdir) && (
    01438             /* We're at the tunnel exit ?? */
    01439             fc == _tunnel_fractcoord_6[dir] ||
    01440             fc == _tunnel_fractcoord_7[dir]
    01441           ) &&
    01442           z == 0) {
    01443         rv->tile = tile;
    01444         rv->state = _road_exit_tunnel_state[dir];
    01445         rv->frame = _road_exit_tunnel_frame[dir];
    01446         rv->vehstatus &= ~VS_HIDDEN;
    01447         return VETSB_ENTERED_WORMHOLE;
    01448       }
    01449     }
    01450   } else { // IsBridge(tile)
    01451
    01452     if (v->IsPrimaryVehicle() && v->type != VEH_SHIP) {
    01453       /* modify speed of vehicle */
    01454       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
    01455
    01456       if (v->type == VEH_ROAD) spd *= 2;
    01457       if (v->cur_speed > spd) v->cur_speed = spd;
    01458     }
    01459
    01460     if (DirToDiagDir(v->direction) == dir) {
    01461       switch (dir) {
    01462         default: NOT_REACHED();
    01463         case DIAGDIR_NE: if ((x & 0xF) != 0)             return VETSB_CONTINUE; break;
    01464         case DIAGDIR_SE: if ((y & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
    01465         case DIAGDIR_SW: if ((x & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
    01466         case DIAGDIR_NW: if ((y & 0xF) != 0)             return VETSB_CONTINUE; break;
    01467       }
    01468       switch (v->type) {
    01469         case VEH_TRAIN: {
    01470           Train *t = Train::From(v);
    01471           t->track = TRACK_BIT_WORMHOLE;
    01472           ClrBit(t->flags, VRF_GOINGUP);
    01473           ClrBit(t->flags, VRF_GOINGDOWN);
    01474         } break;
    01475
    01476         case VEH_ROAD:
    01477           RoadVehicle::From(v)->state = RVSB_WORMHOLE;
    01478           break;
    01479
    01480         case VEH_SHIP:
    01481           Ship::From(v)->state = TRACK_BIT_WORMHOLE;
    01482           break;
    01483
    01484         default: NOT_REACHED();
    01485       }
    01486       return VETSB_ENTERED_WORMHOLE;
    01487     } else if (DirToDiagDir(v->direction) == ReverseDiagDir(dir)) {
    01488       v->tile = tile;
    01489       switch (v->type) {
    01490         case VEH_TRAIN: {
    01491           Train *t = Train::From(v);
    01492           if (t->track == TRACK_BIT_WORMHOLE) {
    01493             t->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
    01494             return VETSB_ENTERED_WORMHOLE;
    01495           }
    01496         } break;
    01497
    01498         case VEH_ROAD: {
    01499           RoadVehicle *rv = RoadVehicle::From(v);
    01500           if (rv->state == RVSB_WORMHOLE) {
    01501             rv->state = _road_exit_tunnel_state[dir];
    01502             rv->frame = 0;
    01503             return VETSB_ENTERED_WORMHOLE;
    01504           }
    01505         } break;
    01506
    01507         case VEH_SHIP: {
    01508           Ship *ship = Ship::From(v);
    01509           if (ship->state == TRACK_BIT_WORMHOLE) {
    01510             ship->state = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
    01511             return VETSB_ENTERED_WORMHOLE;
    01512           }
    01513         } break;
    01514
    01515         default: NOT_REACHED();
    01516       }
    01517     }
    01518   }
    01519   return VETSB_CONTINUE;
    01520 }
    01521
    01522 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
    01523 {
    01524   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
    01525     DiagDirection direction = GetTunnelBridgeDirection(tile);
    01526     Axis axis = DiagDirToAxis(direction);
    01527     CommandCost res;
    01528     uint z_old;
    01529     Slope tileh_old = GetTileSlope(tile, &z_old);
    01530
    01531     /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
    01532     if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
    01533       CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
    01534       res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
    01535     } else {
    01536       CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
    01537       res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
    01538     }
    01539
    01540     /* Surface slope is valid and remains unchanged? */
    01541     if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    01542   }
    01543
    01544   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    01545 }
    01546
    01547 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
    01548   DrawTile_TunnelBridge,           // draw_tile_proc
    01549   GetSlopeZ_TunnelBridge,          // get_slope_z_proc
    01550   ClearTile_TunnelBridge,          // clear_tile_proc
    01551   NULL,                            // add_accepted_cargo_proc
    01552   GetTileDesc_TunnelBridge,        // get_tile_desc_proc
    01553   GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
    01554   NULL,                            // click_tile_proc
    01555   NULL,                            // animate_tile_proc
    01556   TileLoop_TunnelBridge,           // tile_loop_clear
    01557   ChangeTileOwner_TunnelBridge,    // change_tile_owner_clear
    01558   NULL,                            // add_produced_cargo_proc
    01559   VehicleEnter_TunnelBridge,       // vehicle_enter_tile_proc
    01560   GetFoundation_TunnelBridge,      // get_foundation_proc
    01561   TerraformTile_TunnelBridge,      // terraform_tile_proc
    01562 };