tunnelbridge_cmd.cpp

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