# tunnelbridge_cmd.cpp

Go to the documentation of this file.

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