tunnelbridge_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: tunnelbridge_cmd.cpp 15718 2009-03-15 00:32:18Z 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 as SpriteCombine */
00997     if (transport_type == TRANSPORT_ROAD) 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 (_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       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01032         DrawCatenary(ti);
01033       }
01034     }
01035 
01036     DrawBridgeMiddle(ti);
01037   }
01038 }
01039 
01040 
01058 static BridgePieces CalcBridgePiece(uint north, uint south)
01059 {
01060   if (north == 1) {
01061     return BRIDGE_PIECE_NORTH;
01062   } else if (south == 1) {
01063     return BRIDGE_PIECE_SOUTH;
01064   } else if (north < south) {
01065     return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
01066   } else if (north > south) {
01067     return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
01068   } else {
01069     return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
01070   }
01071 }
01072 
01073 
01074 void DrawBridgeMiddle(const TileInfo *ti)
01075 {
01076   /* Sectional view of bridge bounding boxes:
01077    *
01078    *  1           2                                1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
01079    *  1           2                                  3 = empty helper BB
01080    *  1     7     2                                4,5 = pillars under higher bridges
01081    *  1 6 88888 6 2                                  6 = elrail-pylons
01082    *  1 6 88888 6 2                                  7 = elrail-wire
01083    *  1 6 88888 6 2  <- TILE_HEIGHT                  8 = rail-vehicle on bridge
01084    *  3333333333333  <- BB_Z_SEPARATOR
01085    *                 <- unused
01086    *    4       5    <- BB_HEIGHT_UNDER_BRIDGE
01087    *    4       5
01088    *    4       5
01089    *
01090    */
01091 
01092   /* Z position of the bridge sprites relative to bridge height (downwards) */
01093   static const int BRIDGE_Z_START = 3;
01094 
01095   if (!IsBridgeAbove(ti->tile)) return;
01096 
01097   TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
01098   TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
01099   TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
01100 
01101   Axis axis = GetBridgeAxis(ti->tile);
01102   BridgePieces piece = CalcBridgePiece(
01103     GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
01104     GetTunnelBridgeLength(ti->tile, rampsouth) + 1
01105   );
01106 
01107   const PalSpriteID *psid;
01108   bool drawfarpillar;
01109   if (transport_type != TRANSPORT_WATER) {
01110     BridgeType type =  GetBridgeType(rampsouth);
01111     drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
01112 
01113     uint base_offset;
01114     if (transport_type == TRANSPORT_RAIL) {
01115       base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
01116     } else {
01117       base_offset = 8;
01118     }
01119 
01120     psid = base_offset + GetBridgeSpriteTable(type, piece);
01121   } else {
01122     drawfarpillar = true;
01123     psid = _aqueduct_sprites;
01124   }
01125 
01126   if (axis != AXIS_X) psid += 4;
01127 
01128   int x = ti->x;
01129   int y = ti->y;
01130   uint bridge_z = GetBridgeHeight(rampsouth);
01131   uint z = bridge_z - BRIDGE_Z_START;
01132 
01133   /* Add a bounding box, that separates the bridge from things below it. */
01134   AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
01135 
01136   /* Draw Trambits as SpriteCombine */
01137   if (transport_type == TRANSPORT_ROAD) StartSpriteCombine();
01138 
01139   /* Draw floor and far part of bridge*/
01140   if (!IsInvisibilitySet(TO_BRIDGES)) {
01141     if (axis == AXIS_X) {
01142       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01143     } else {
01144       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01145     }
01146   }
01147 
01148   psid++;
01149 
01150   if (transport_type == TRANSPORT_ROAD) {
01151     RoadTypes rts = GetRoadTypes(rampsouth);
01152 
01153     if (HasBit(rts, ROADTYPE_TRAM)) {
01154       /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01155       DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
01156     } else {
01157       EndSpriteCombine();
01158       StartSpriteCombine();
01159     }
01160   } else if (transport_type == TRANSPORT_RAIL) {
01161     if (HasCatenaryDrawn(GetRailType(rampsouth))) {
01162       DrawCatenaryOnBridge(ti);
01163     }
01164   }
01165 
01166   /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
01167   if (!IsInvisibilitySet(TO_BRIDGES)) {
01168     if (axis == AXIS_X) {
01169       y += 12;
01170       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
01171     } else {
01172       x += 12;
01173       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
01174     }
01175   }
01176 
01177   /* Draw TramFront as SpriteCombine */
01178   if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
01179 
01180   /* Do not draw anything more if bridges are invisible */
01181   if (IsInvisibilitySet(TO_BRIDGES)) return;
01182 
01183   psid++;
01184   if (ti->z + 5 == z) {
01185     /* draw poles below for small bridges */
01186     if (psid->sprite != 0) {
01187       SpriteID image = psid->sprite;
01188       SpriteID pal   = psid->pal;
01189       if (IsTransparencySet(TO_BRIDGES)) {
01190         SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
01191         pal = PALETTE_TO_TRANSPARENT;
01192       }
01193 
01194       DrawGroundSpriteAt(image, pal, x, y, z);
01195     }
01196   } else if (_settings_client.gui.bridge_pillars) {
01197     /* draw pillars below for high bridges */
01198     DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
01199   }
01200 }
01201 
01202 
01203 static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y)
01204 {
01205   uint z;
01206   Slope tileh = GetTileSlope(tile, &z);
01207 
01208   x &= 0xF;
01209   y &= 0xF;
01210 
01211   if (IsTunnel(tile)) {
01212     uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
01213 
01214     /* In the tunnel entrance? */
01215     if (5 <= pos && pos <= 10) return z;
01216   } else { // IsBridge(tile)
01217     DiagDirection dir = GetTunnelBridgeDirection(tile);
01218     uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
01219 
01220     z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
01221 
01222     /* On the bridge ramp? */
01223     if (5 <= pos && pos <= 10) {
01224       uint delta;
01225 
01226       if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
01227 
01228       switch (dir) {
01229         default: NOT_REACHED();
01230         case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
01231         case DIAGDIR_SE: delta = y / 2; break;
01232         case DIAGDIR_SW: delta = x / 2; break;
01233         case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
01234       }
01235       return z + 1 + delta;
01236     }
01237   }
01238 
01239   return z + GetPartialZ(x, y, tileh);
01240 }
01241 
01242 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
01243 {
01244   return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
01245 }
01246 
01247 
01248 static void GetAcceptedCargo_TunnelBridge(TileIndex tile, AcceptedCargo ac)
01249 {
01250   /* not used */
01251 }
01252 
01253 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
01254 {
01255   TransportType tt = GetTunnelBridgeTransportType(tile);
01256 
01257   if (IsTunnel(tile)) {
01258     td->str = (tt == TRANSPORT_RAIL) ? STR_5017_RAILROAD_TUNNEL : STR_5018_ROAD_TUNNEL;
01259   } else { // IsBridge(tile)
01260     td->str = (tt == TRANSPORT_WATER) ? STR_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
01261   }
01262   td->owner[0] = GetTileOwner(tile);
01263 
01264   Owner road_owner = INVALID_OWNER;
01265   Owner tram_owner = INVALID_OWNER;
01266   RoadTypes rts = GetRoadTypes(tile);
01267   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01268   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01269 
01270   /* Is there a mix of owners? */
01271   if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
01272       (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
01273     uint i = 1;
01274     if (road_owner != INVALID_OWNER) {
01275       td->owner_type[i] = STR_ROAD_OWNER;
01276       td->owner[i] = road_owner;
01277       i++;
01278     }
01279     if (tram_owner != INVALID_OWNER) {
01280       td->owner_type[i] = STR_TRAM_OWNER;
01281       td->owner[i] = tram_owner;
01282     }
01283   }
01284 }
01285 
01286 
01287 static void AnimateTile_TunnelBridge(TileIndex tile)
01288 {
01289   /* not used */
01290 }
01291 
01292 static void TileLoop_TunnelBridge(TileIndex tile)
01293 {
01294   bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
01295   switch (_settings_game.game_creation.landscape) {
01296     case LT_ARCTIC:
01297       if (snow_or_desert != (GetTileZ(tile) > GetSnowLine())) {
01298         SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
01299         MarkTileDirtyByTile(tile);
01300       }
01301       break;
01302 
01303     case LT_TROPIC:
01304       if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
01305         SetTunnelBridgeSnowOrDesert(tile, true);
01306         MarkTileDirtyByTile(tile);
01307       }
01308       break;
01309 
01310     default:
01311       break;
01312   }
01313 }
01314 
01315 static bool ClickTile_TunnelBridge(TileIndex tile)
01316 {
01317   /* not used */
01318   return false;
01319 }
01320 
01321 
01322 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
01323 {
01324   TransportType transport_type = GetTunnelBridgeTransportType(tile);
01325   if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
01326 
01327   DiagDirection dir = GetTunnelBridgeDirection(tile);
01328   if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
01329   return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
01330 }
01331 
01332 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
01333 {
01334   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01335     /* Update all roadtypes, no matter if they are present */
01336     if (GetRoadOwner(tile, rt) == old_owner) {
01337       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
01338     }
01339   }
01340 
01341   if (!IsTileOwner(tile, old_owner)) return;
01342 
01343   if (new_owner != INVALID_OWNER) {
01344     SetTileOwner(tile, new_owner);
01345   } else {
01346     if (CmdFailed(DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR))) {
01347       /* When clearing the bridge/tunnel failed there are still vehicles on/in
01348        * the bridge/tunnel. As all *our* vehicles are already removed, they
01349        * must be of another owner. Therefore this can't be rail tunnel/bridge.
01350        * In that case we can safely reassign the ownership to OWNER_NONE. */
01351       assert(GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL);
01352       SetTileOwner(tile, OWNER_NONE);
01353     }
01354   }
01355 }
01356 
01357 
01358 static const byte _tunnel_fractcoord_1[4]    = {0x8E, 0x18, 0x81, 0xE8};
01359 static const byte _tunnel_fractcoord_2[4]    = {0x81, 0x98, 0x87, 0x38};
01360 static const byte _tunnel_fractcoord_3[4]    = {0x82, 0x88, 0x86, 0x48};
01361 static const byte _exit_tunnel_track[4]      = {1, 2, 1, 2};
01362 
01364 static const Trackdir _road_exit_tunnel_state[DIAGDIR_END] = {
01365   TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
01366 };
01367 static const byte _road_exit_tunnel_frame[4] = {2, 7, 9, 4};
01368 
01369 static const byte _tunnel_fractcoord_4[4]    = {0x52, 0x85, 0x98, 0x29};
01370 static const byte _tunnel_fractcoord_5[4]    = {0x92, 0x89, 0x58, 0x25};
01371 static const byte _tunnel_fractcoord_6[4]    = {0x92, 0x89, 0x56, 0x45};
01372 static const byte _tunnel_fractcoord_7[4]    = {0x52, 0x85, 0x96, 0x49};
01373 
01374 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
01375 {
01376   int z = GetSlopeZ(x, y) - v->z_pos;
01377 
01378   if (abs(z) > 2) return VETSB_CANNOT_ENTER;
01379   const DiagDirection dir = GetTunnelBridgeDirection(tile);
01380 
01381   if (IsTunnel(tile)) {
01382     byte fc;
01383     DiagDirection vdir;
01384 
01385     if (v->type == VEH_TRAIN) {
01386       fc = (x & 0xF) + (y << 4);
01387 
01388       vdir = DirToDiagDir(v->direction);
01389 
01390       if (v->u.rail.track != TRACK_BIT_WORMHOLE && dir == vdir) {
01391         if (IsFrontEngine(v) && fc == _tunnel_fractcoord_1[dir]) {
01392           if (!PlayVehicleSound(v, VSE_TUNNEL) && RailVehInfo(v->engine_type)->engclass == 0) {
01393             SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
01394           }
01395           return VETSB_CONTINUE;
01396         }
01397         if (fc == _tunnel_fractcoord_2[dir]) {
01398           v->tile = tile;
01399           v->u.rail.track = TRACK_BIT_WORMHOLE;
01400           v->vehstatus |= VS_HIDDEN;
01401           return VETSB_ENTERED_WORMHOLE;
01402         }
01403       }
01404 
01405       if (dir == ReverseDiagDir(vdir) && fc == _tunnel_fractcoord_3[dir] && z == 0) {
01406         /* We're at the tunnel exit ?? */
01407         v->tile = tile;
01408         v->u.rail.track = (TrackBits)_exit_tunnel_track[dir];
01409         assert(v->u.rail.track);
01410         v->vehstatus &= ~VS_HIDDEN;
01411         return VETSB_ENTERED_WORMHOLE;
01412       }
01413     } else if (v->type == VEH_ROAD) {
01414       fc = (x & 0xF) + (y << 4);
01415       vdir = DirToDiagDir(v->direction);
01416 
01417       /* Enter tunnel? */
01418       if (v->u.road.state != RVSB_WORMHOLE && dir == vdir) {
01419         if (fc == _tunnel_fractcoord_4[dir] ||
01420             fc == _tunnel_fractcoord_5[dir]) {
01421           v->tile = tile;
01422           v->u.road.state = RVSB_WORMHOLE;
01423           v->vehstatus |= VS_HIDDEN;
01424           return VETSB_ENTERED_WORMHOLE;
01425         } else {
01426           return VETSB_CONTINUE;
01427         }
01428       }
01429 
01430       if (dir == ReverseDiagDir(vdir) && (
01431             /* We're at the tunnel exit ?? */
01432             fc == _tunnel_fractcoord_6[dir] ||
01433             fc == _tunnel_fractcoord_7[dir]
01434           ) &&
01435           z == 0) {
01436         v->tile = tile;
01437         v->u.road.state = _road_exit_tunnel_state[dir];
01438         v->u.road.frame = _road_exit_tunnel_frame[dir];
01439         v->vehstatus &= ~VS_HIDDEN;
01440         return VETSB_ENTERED_WORMHOLE;
01441       }
01442     }
01443   } else { // IsBridge(tile)
01444 
01445     if (v->IsPrimaryVehicle() && v->type != VEH_SHIP) {
01446       /* modify speed of vehicle */
01447       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01448 
01449       if (v->type == VEH_ROAD) spd *= 2;
01450       if (v->cur_speed > spd) v->cur_speed = spd;
01451     }
01452 
01453     if (DirToDiagDir(v->direction) == dir) {
01454       switch (dir) {
01455         default: NOT_REACHED();
01456         case DIAGDIR_NE: if ((x & 0xF) != 0)             return VETSB_CONTINUE; break;
01457         case DIAGDIR_SE: if ((y & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
01458         case DIAGDIR_SW: if ((x & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
01459         case DIAGDIR_NW: if ((y & 0xF) != 0)             return VETSB_CONTINUE; break;
01460       }
01461       switch (v->type) {
01462         case VEH_TRAIN:
01463           v->u.rail.track = TRACK_BIT_WORMHOLE;
01464           ClrBit(v->u.rail.flags, VRF_GOINGUP);
01465           ClrBit(v->u.rail.flags, VRF_GOINGDOWN);
01466           break;
01467 
01468         case VEH_ROAD:
01469           v->u.road.state = RVSB_WORMHOLE;
01470           break;
01471 
01472         case VEH_SHIP:
01473           v->u.ship.state = TRACK_BIT_WORMHOLE;
01474           break;
01475 
01476         default: NOT_REACHED();
01477       }
01478       return VETSB_ENTERED_WORMHOLE;
01479     } else if (DirToDiagDir(v->direction) == ReverseDiagDir(dir)) {
01480       v->tile = tile;
01481       switch (v->type) {
01482         case VEH_TRAIN:
01483           if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
01484             v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
01485             return VETSB_ENTERED_WORMHOLE;
01486           }
01487           break;
01488 
01489         case VEH_ROAD:
01490           if (v->u.road.state == RVSB_WORMHOLE) {
01491             v->u.road.state = _road_exit_tunnel_state[dir];
01492             v->u.road.frame = 0;
01493             return VETSB_ENTERED_WORMHOLE;
01494           }
01495           break;
01496 
01497         case VEH_SHIP:
01498           if (v->u.ship.state == TRACK_BIT_WORMHOLE) {
01499             v->u.ship.state = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
01500             return VETSB_ENTERED_WORMHOLE;
01501           }
01502           break;
01503 
01504         default: NOT_REACHED();
01505       }
01506     }
01507   }
01508   return VETSB_CONTINUE;
01509 }
01510 
01511 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
01512 {
01513   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
01514     DiagDirection direction = GetTunnelBridgeDirection(tile);
01515     Axis axis = DiagDirToAxis(direction);
01516     CommandCost res;
01517     uint z_old;
01518     Slope tileh_old = GetTileSlope(tile, &z_old);
01519 
01520     /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
01521     if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
01522       CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
01523       res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
01524     } else {
01525       CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
01526       res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
01527     }
01528 
01529     /* Surface slope is valid and remains unchanged? */
01530     if (!CmdFailed(res) && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
01531   }
01532 
01533   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01534 }
01535 
01536 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
01537   DrawTile_TunnelBridge,           // draw_tile_proc
01538   GetSlopeZ_TunnelBridge,          // get_slope_z_proc
01539   ClearTile_TunnelBridge,          // clear_tile_proc
01540   GetAcceptedCargo_TunnelBridge,   // get_accepted_cargo_proc
01541   GetTileDesc_TunnelBridge,        // get_tile_desc_proc
01542   GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
01543   ClickTile_TunnelBridge,          // click_tile_proc
01544   AnimateTile_TunnelBridge,        // animate_tile_proc
01545   TileLoop_TunnelBridge,           // tile_loop_clear
01546   ChangeTileOwner_TunnelBridge,    // change_tile_owner_clear
01547   NULL,                            // get_produced_cargo_proc
01548   VehicleEnter_TunnelBridge,       // vehicle_enter_tile_proc
01549   GetFoundation_TunnelBridge,      // get_foundation_proc
01550   TerraformTile_TunnelBridge,      // terraform_tile_proc
01551 };

Generated on Sun Mar 15 22:49:51 2009 for openttd by  doxygen 1.5.6