tunnelbridge_cmd.cpp

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

Generated on Wed Jul 15 20:36:03 2009 for OpenTTD by  doxygen 1.5.6