4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
11 * @file tunnelbridge_cmd.cpp
12 * This file deals with tunnels and bridges (non-gui stuff)
13 * @todo separate this file into two
17 #include "newgrf_object.h"
18 #include "viewport_func.h"
19 #include "cmd_helper.h"
20 #include "command_func.h"
25 #include "pathfinder/yapf/yapf_cache.h"
26 #include "newgrf_sound.h"
27 #include "autoslope.h"
28 #include "tunnelbridge_map.h"
29 #include "bridge_signal_map.h"
30 #include "tunnel_base.h"
31 #include "strings_func.h"
32 #include "date_func.h"
33 #include "clear_func.h"
34 #include "vehicle_func.h"
35 #include "vehicle_gui.h"
36 #include "sound_func.h"
37 #include "tunnelbridge.h"
38 #include "cheat_type.h"
39 #include "elrail_func.h"
41 #include "company_base.h"
42 #include "newgrf_railtype.h"
43 #include "newgrf_roadtype.h"
44 #include "object_base.h"
46 #include "company_gui.h"
47 #include "viewport_func.h"
48 #include "station_map.h"
49 #include "industry_map.h"
51 #include "table/strings.h"
52 #include "table/bridge_land.h"
54 #include "safeguards.h"
56 BridgeSpec _bridge
[MAX_BRIDGES
]; ///< The specification of all bridges.
57 TileIndex _build_tunnel_endtile
; ///< The end of a tunnel; as hidden return from the tunnel build command for GUI purposes.
59 /** Z position of the bridge sprites relative to bridge height (downwards) */
60 static const int BRIDGE_Z_START
= 3;
62 extern void DrawRoadBits(TileInfo
*ti
);
63 extern const RoadBits _invalid_tileh_slopes_road
[2][15];
67 * Mark bridge tiles dirty.
68 * Note: The bridge does not need to exist, everything is passed via parameters.
69 * @param begin Start tile.
70 * @param end End tile.
71 * @param direction Direction from \a begin to \a end.
72 * @param bridge_height Bridge height level.
74 void MarkBridgeDirty(TileIndex begin
, TileIndex end
, DiagDirection direction
, uint bridge_height
, const ZoomLevel mark_dirty_if_zoomlevel_is_below
)
76 TileIndexDiff delta
= TileOffsByDiagDir(direction
);
77 for (TileIndex t
= begin
; t
!= end
; t
+= delta
) {
78 MarkTileDirtyByTile(t
, mark_dirty_if_zoomlevel_is_below
, bridge_height
- TileHeight(t
));
80 MarkTileDirtyByTile(end
, mark_dirty_if_zoomlevel_is_below
);
84 * Mark bridge tiles dirty.
85 * @param tile Bridge head.
87 void MarkBridgeDirty(TileIndex tile
, const ZoomLevel mark_dirty_if_zoomlevel_is_below
)
89 MarkBridgeDirty(tile
, GetOtherTunnelBridgeEnd(tile
), GetTunnelBridgeDirection(tile
), GetBridgeHeight(tile
), mark_dirty_if_zoomlevel_is_below
);
93 * Mark bridge or tunnel tiles dirty.
94 * @param tile Bridge head or tunnel entrance.
96 void MarkBridgeOrTunnelDirty(TileIndex tile
, const ZoomLevel mark_dirty_if_zoomlevel_is_below
)
99 MarkBridgeDirty(tile
, mark_dirty_if_zoomlevel_is_below
);
101 MarkTileDirtyByTile(tile
);
102 MarkTileDirtyByTile(GetOtherTunnelBridgeEnd(tile
));
107 * Get number of signals on bridge or tunnel with signal simulation.
108 * @param length Length of bridge/tunnel middle
109 * @return Number of signals on signalled bridge/tunnel of this length
111 uint
GetTunnelBridgeSignalSimulationSignalCount(uint length
)
113 return 2 + (length
/ _settings_game
.construction
.simulated_wormhole_signals
);
116 /** Reset the data been eventually changed by the grf loaded. */
119 /* First, free sprite table data */
120 for (BridgeType i
= 0; i
< MAX_BRIDGES
; i
++) {
121 if (_bridge
[i
].sprite_table
!= nullptr) {
122 for (BridgePieces j
= BRIDGE_PIECE_NORTH
; j
< BRIDGE_PIECE_INVALID
; j
++) free(_bridge
[i
].sprite_table
[j
]);
123 free(_bridge
[i
].sprite_table
);
127 /* Then, wipe out current bridges */
128 memset(&_bridge
, 0, sizeof(_bridge
));
129 /* And finally, reinstall default data */
130 memcpy(&_bridge
, &_orig_bridge
, sizeof(_orig_bridge
));
134 * Calculate the price factor for building a long bridge.
135 * Basically the cost delta is 1,1, 1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5,5, 6,6,6,6,6,6, 7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,
136 * @param length Length of the bridge.
137 * @return Price factor for the bridge.
139 int CalcBridgeLenCostFactor(int length
)
141 if (length
< 2) return length
;
145 for (int delta
= 1;; delta
++) {
146 for (int count
= 0; count
< delta
; count
++) {
147 if (length
== 0) return sum
;
155 * Get the foundation for a bridge.
156 * @param tileh The slope to build the bridge on.
157 * @param axis The axis of the bridge entrance.
158 * @return The foundation required.
160 Foundation
GetBridgeFoundation(Slope tileh
, Axis axis
)
162 if (tileh
== SLOPE_FLAT
||
163 ((tileh
== SLOPE_NE
|| tileh
== SLOPE_SW
) && axis
== AXIS_X
) ||
164 ((tileh
== SLOPE_NW
|| tileh
== SLOPE_SE
) && axis
== AXIS_Y
)) return FOUNDATION_NONE
;
166 return (HasSlopeHighestCorner(tileh
) ? InclinedFoundation(axis
) : FlatteningFoundation(tileh
));
170 * Determines if the track on a bridge ramp is flat or goes up/down.
172 * @param tileh Slope of the tile under the bridge head
173 * @param axis Orientation of bridge
174 * @return true iff the track is flat.
176 bool HasBridgeFlatRamp(Slope tileh
, Axis axis
)
178 ApplyFoundationToSlope(GetBridgeFoundation(tileh
, axis
), &tileh
);
179 /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
180 return (tileh
!= SLOPE_FLAT
);
183 static inline const PalSpriteID
*GetBridgeSpriteTable(int index
, BridgePieces table
)
185 const BridgeSpec
*bridge
= GetBridgeSpec(index
);
186 assert(table
< BRIDGE_PIECE_INVALID
);
187 if (bridge
->sprite_table
== nullptr || bridge
->sprite_table
[table
] == nullptr) {
188 return _bridge_sprite_table
[index
][table
];
190 return bridge
->sprite_table
[table
];
196 * Determines the foundation for the north bridge head, and tests if the resulting slope is valid.
198 * @param axis Axis of the bridge
199 * @param tileh Slope of the tile under the north bridge head; returns slope on top of foundation
200 * @param z TileZ corresponding to tileh, gets modified as well
201 * @return Error or cost for bridge foundation
203 static CommandCost
CheckBridgeSlopeNorth(Axis axis
, Slope
*tileh
, int *z
)
205 Foundation f
= GetBridgeFoundation(*tileh
, axis
);
206 *z
+= ApplyFoundationToSlope(f
, tileh
);
208 Slope valid_inclined
= (axis
== AXIS_X
? SLOPE_NE
: SLOPE_NW
);
209 if ((*tileh
!= SLOPE_FLAT
) && (*tileh
!= valid_inclined
)) return CommandError();
211 if (f
== FOUNDATION_NONE
) return CommandCost();
213 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
217 * Determines the foundation for the south bridge head, and tests if the resulting slope is valid.
219 * @param axis Axis of the bridge
220 * @param tileh Slope of the tile under the south bridge head; returns slope on top of foundation
221 * @param z TileZ corresponding to tileh, gets modified as well
222 * @return Error or cost for bridge foundation
224 static CommandCost
CheckBridgeSlopeSouth(Axis axis
, Slope
*tileh
, int *z
)
226 Foundation f
= GetBridgeFoundation(*tileh
, axis
);
227 *z
+= ApplyFoundationToSlope(f
, tileh
);
229 Slope valid_inclined
= (axis
== AXIS_X
? SLOPE_SW
: SLOPE_SE
);
230 if ((*tileh
!= SLOPE_FLAT
) && (*tileh
!= valid_inclined
)) return CommandError();
232 if (f
== FOUNDATION_NONE
) return CommandCost();
234 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
238 * Is a bridge of the specified type and length available?
239 * @param bridge_type Wanted type of bridge.
240 * @param bridge_len Wanted length of the bridge.
241 * @return A succeeded (the requested bridge is available) or failed (it cannot be built) command.
243 CommandCost
CheckBridgeAvailability(BridgeType bridge_type
, uint bridge_len
, DoCommandFlag flags
)
245 if (flags
& DC_QUERY_COST
) {
246 if (bridge_len
<= _settings_game
.construction
.max_bridge_length
) return CommandCost();
247 return CommandError(STR_ERROR_BRIDGE_TOO_LONG
);
250 if (bridge_type
>= MAX_BRIDGES
) return CommandError();
252 const BridgeSpec
*b
= GetBridgeSpec(bridge_type
);
253 if (b
->avail_year
> _cur_year
) return CommandError();
255 uint max
= min(b
->max_length
, _settings_game
.construction
.max_bridge_length
);
257 if (b
->min_length
> bridge_len
) return CommandError();
258 if (bridge_len
<= max
) return CommandCost();
259 return CommandError(STR_ERROR_BRIDGE_TOO_LONG
);
264 * @param end_tile end tile
265 * @param flags type of operation
266 * @param p1 packed start tile coords (~ dx)
267 * @param p2 various bitstuffed elements
268 * - p2 = (bit 0- 7) - bridge type (hi bh)
269 * - p2 = (bit 8-13) - rail type or road types.
270 * - p2 = (bit 15-16) - transport type.
272 * @return the cost of this operation or an error
274 CommandCost
CmdBuildBridge(TileIndex end_tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
276 CompanyID company
= _current_company
;
278 RailType railtype
= INVALID_RAILTYPE
;
279 RoadTypeIdentifier rtid
;
281 /* unpack parameters */
282 BridgeType bridge_type
= GB(p2
, 0, 8);
284 if (!IsValidTile(p1
)) return CommandError(STR_ERROR_BRIDGE_THROUGH_MAP_BORDER
);
286 TransportType transport_type
= Extract
<TransportType
, 15, 2>(p2
);
289 switch (transport_type
) {
290 case TRANSPORT_ROAD
: {
291 if (!rtid
.UnpackIfValid(GB(p2
, 8, 6))) return CommandError();
292 if (!ValParamRoadType(rtid
)) return CommandError();
297 railtype
= Extract
<RailType
, 8, 5>(p2
);
298 if (!ValParamRailtype(railtype
)) return CommandError();
301 case TRANSPORT_WATER
:
305 /* Airports don't have bridges. */
306 return CommandError();
308 TileIndex tile_start
= p1
;
309 TileIndex tile_end
= end_tile
;
311 if (company
== OWNER_DEITY
) {
312 if (transport_type
!= TRANSPORT_ROAD
) return CommandError();
313 const Town
*town
= CalcClosestTownFromTile(tile_start
);
315 company
= OWNER_TOWN
;
317 /* If we are not within a town, we are not owned by the town */
318 if (town
== nullptr || DistanceSquare(tile_start
, town
->xy
) > town
->cache
.squared_town_zone_radius
[HZB_TOWN_EDGE
]) {
319 company
= OWNER_NONE
;
323 if (tile_start
== tile_end
) {
324 return CommandError(STR_ERROR_CAN_T_START_AND_END_ON
);
328 if (TileX(tile_start
) == TileX(tile_end
)) {
330 } else if (TileY(tile_start
) == TileY(tile_end
)) {
333 return CommandError(STR_ERROR_START_AND_END_MUST_BE_IN
);
336 if (tile_end
< tile_start
) Swap(tile_start
, tile_end
);
338 uint bridge_len
= GetTunnelBridgeLength(tile_start
, tile_end
);
339 if (transport_type
!= TRANSPORT_WATER
) {
340 /* set and test bridge length, availability */
341 CommandCost ret
= CheckBridgeAvailability(bridge_type
, bridge_len
, flags
);
342 if (ret
.Failed()) return ret
;
344 if (bridge_len
> _settings_game
.construction
.max_bridge_length
) return CommandError(STR_ERROR_BRIDGE_TOO_LONG
);
349 Slope tileh_start
= GetTileSlope(tile_start
, &z_start
);
350 Slope tileh_end
= GetTileSlope(tile_end
, &z_end
);
351 bool pbs_reservation
= false;
353 CommandCost terraform_cost_north
= CheckBridgeSlopeNorth(direction
, &tileh_start
, &z_start
);
354 CommandCost terraform_cost_south
= CheckBridgeSlopeSouth(direction
, &tileh_end
, &z_end
);
356 /* Aqueducts can't be built of flat land. */
357 if (transport_type
== TRANSPORT_WATER
&& (tileh_start
== SLOPE_FLAT
|| tileh_end
== SLOPE_FLAT
)) return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
358 if (z_start
!= z_end
) return CommandError(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT
);
360 CommandCost
cost(EXPENSES_CONSTRUCTION
);
363 bool is_upgrade
= false;
364 RoadTypeIdentifiers rtids
;
365 if (IsBridgeTile(tile_start
) && IsBridgeTile(tile_end
) &&
366 GetOtherBridgeEnd(tile_start
) == tile_end
&&
367 GetTunnelBridgeTransportType(tile_start
) == transport_type
) {
368 /* Replace a current bridge. */
370 switch (transport_type
) {
372 /* Keep the reservation, the path stays valid. */
373 pbs_reservation
= HasTunnelBridgeReservation(tile_start
);
377 /* Do not remove road types when upgrading a bridge */
378 rtids
= RoadTypeIdentifiers::FromTile(tile_start
);
384 /* If this is a railway bridge, make sure the railtypes match. */
385 if (transport_type
== TRANSPORT_RAIL
&& GetRailType(tile_start
) != railtype
) {
386 return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
389 /* If this is a road bridge, make sure the roadtype matches. */
390 if (transport_type
== TRANSPORT_ROAD
&& rtids
.HasType(rtid
.basetype
) && rtids
.GetType(rtid
.basetype
) != rtid
) {
391 return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
394 /* Do not replace town bridges with lower speed bridges, unless in scenario editor. */
395 if (!(flags
& DC_QUERY_COST
) && IsTileOwner(tile_start
, OWNER_TOWN
) &&
396 GetBridgeSpec(bridge_type
)->speed
< GetBridgeSpec(GetBridgeType(tile_start
))->speed
&&
397 _game_mode
!= GM_EDITOR
) {
398 Town
*t
= ClosestTownFromTile(tile_start
, UINT_MAX
);
401 return CommandError();
403 SetDParam(0, t
->index
);
404 return CommandError(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
408 /* Do not replace the bridge with the same bridge type. */
409 if (!(flags
& DC_QUERY_COST
) && (bridge_type
== GetBridgeType(tile_start
)) && (transport_type
!= TRANSPORT_ROAD
|| rtids
.HasType(rtid
.basetype
))) {
410 return CommandError(STR_ERROR_ALREADY_BUILT
);
413 /* Do not allow replacing another company's bridges. */
414 if (!IsTileOwner(tile_start
, company
) && !IsTileOwner(tile_start
, OWNER_TOWN
) && !IsTileOwner(tile_start
, OWNER_NONE
)) {
415 return CommandError(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER
);
418 cost
.AddCost((bridge_len
+ 1) * _price
[PR_CLEAR_BRIDGE
]); // The cost of clearing the current bridge.
419 owner
= GetTileOwner(tile_start
);
421 /* If bridge belonged to bankrupt company, it has a new owner now */
422 is_new_owner
= (owner
== OWNER_NONE
);
423 if (is_new_owner
) owner
= company
;
427 /* Build a new bridge. */
429 bool allow_on_slopes
= (_settings_game
.construction
.build_on_slopes
&& transport_type
!= TRANSPORT_WATER
);
431 /* Try and clear the start landscape */
432 CommandCost ret
= DoCommand(tile_start
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
433 if (ret
.Failed()) return ret
;
436 if (terraform_cost_north
.Failed() || (terraform_cost_north
.GetCost() != 0 && !allow_on_slopes
)) return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
437 cost
.AddCost(terraform_cost_north
);
439 /* Try and clear the end landscape */
440 ret
= DoCommand(tile_end
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
441 if (ret
.Failed()) return ret
;
444 /* false - end tile slope check */
445 if (terraform_cost_south
.Failed() || (terraform_cost_south
.GetCost() != 0 && !allow_on_slopes
)) return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
446 cost
.AddCost(terraform_cost_south
);
448 const TileIndex heads
[] = {tile_start
, tile_end
};
449 for (int i
= 0; i
< 2; i
++) {
450 if (IsBridgeAbove(heads
[i
])) {
451 TileIndex north_head
= GetNorthernBridgeEnd(heads
[i
]);
453 if (direction
== GetBridgeAxis(heads
[i
])) return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
455 if (z_start
+ 1 == GetBridgeHeight(north_head
)) {
456 return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
461 TileIndexDiff delta
= (direction
== AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
462 for (TileIndex tile
= tile_start
+ delta
; tile
!= tile_end
; tile
+= delta
) {
463 if (GetTileMaxZ(tile
) > z_start
) return CommandError(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN
);
465 if (z_start
>= (GetTileZ(tile
) + _settings_game
.construction
.max_bridge_height
)) {
467 * Disallow too high bridges.
468 * Properly rendering a map where very high bridges (might) exist is expensive.
469 * See http://www.tt-forums.net/viewtopic.php?f=33&t=40844&start=980#p1131762
470 * for a detailed discussion. z_start here is one heightlevel below the bridge level.
472 return CommandError(STR_ERROR_BRIDGE_TOO_HIGH_FOR_TERRAIN
);
475 if (IsBridgeAbove(tile
)) {
476 /* Disallow crossing bridges for the time being */
477 return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
480 switch (GetTileType(tile
)) {
482 if (!IsWater(tile
) && !IsCoast(tile
)) goto not_valid_below
;
486 if (!IsPlainRail(tile
)) goto not_valid_below
;
490 if (IsRoadDepot(tile
)) goto not_valid_below
;
493 case MP_TUNNELBRIDGE
:
494 if (IsTunnel(tile
)) break;
495 if (direction
== DiagDirToAxis(GetTunnelBridgeDirection(tile
))) goto not_valid_below
;
496 if (z_start
< GetBridgeHeight(tile
)) goto not_valid_below
;
500 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
501 if ((spec
->flags
& OBJECT_FLAG_ALLOW_UNDER_BRIDGE
) == 0) goto not_valid_below
;
502 if (GetTileMaxZ(tile
) + spec
->height
> z_start
) goto not_valid_below
;
511 /* try and clear the middle landscape */
512 ret
= DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
513 if (ret
.Failed()) return ret
;
518 if (flags
& DC_EXEC
) {
519 /* We do this here because when replacing a bridge with another
520 * type calling SetBridgeMiddle isn't needed. After all, the
521 * tile already has the has_bridge_above bits set. */
522 SetBridgeMiddle(tile
, direction
);
530 RoadTypes prev_roadtypes
= rtids
.PresentRoadTypes();
531 if (transport_type
== TRANSPORT_ROAD
) rtids
.MergeRoadType(rtid
);
534 if (flags
& DC_EXEC
) {
535 DiagDirection dir
= AxisToDiagDir(direction
);
537 Company
*c
= Company::GetIfValid(company
);
538 switch (transport_type
) {
540 /* Add to company infrastructure count if required. */
541 if (is_new_owner
&& c
!= nullptr) c
->infrastructure
.rail
[railtype
] += (bridge_len
+ 2) * TUNNELBRIDGE_TRACKBIT_FACTOR
;
542 MakeRailBridgeRamp(tile_start
, owner
, bridge_type
, dir
, railtype
, is_upgrade
);
543 MakeRailBridgeRamp(tile_end
, owner
, bridge_type
, ReverseDiagDir(dir
), railtype
, is_upgrade
);
544 SetTunnelBridgeReservation(tile_start
, pbs_reservation
);
545 SetTunnelBridgeReservation(tile_end
, pbs_reservation
);
548 case TRANSPORT_ROAD
: {
550 /* Also give unowned present roadtypes to new owner */
551 if (HasBit(prev_roadtypes
, ROADTYPE_ROAD
) && GetRoadOwner(tile_start
, ROADTYPE_ROAD
) == OWNER_NONE
) ClrBit(prev_roadtypes
, ROADTYPE_ROAD
);
552 if (HasBit(prev_roadtypes
, ROADTYPE_TRAM
) && GetRoadOwner(tile_start
, ROADTYPE_TRAM
) == OWNER_NONE
) ClrBit(prev_roadtypes
, ROADTYPE_TRAM
);
555 /* Add all new road types to the company infrastructure counter. */
556 RoadTypeIdentifier new_rtid
;
557 FOR_EACH_SET_ROADTYPEIDENTIFIER(new_rtid
, rtids
) {
558 if (!HasBit(prev_roadtypes
, new_rtid
.basetype
)) {
559 /* A full diagonal road tile has two road bits. */
560 c
->infrastructure
.road
[new_rtid
.basetype
][new_rtid
.subtype
] += (bridge_len
+ 2) * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR
;
564 Owner owner_road
= HasBit(prev_roadtypes
, ROADTYPE_ROAD
) ? GetRoadOwner(tile_start
, ROADTYPE_ROAD
) : company
;
565 Owner owner_tram
= HasBit(prev_roadtypes
, ROADTYPE_TRAM
) ? GetRoadOwner(tile_start
, ROADTYPE_TRAM
) : company
;
566 MakeRoadBridgeRamp(tile_start
, owner
, owner_road
, owner_tram
, bridge_type
, dir
, rtids
, is_upgrade
);
567 MakeRoadBridgeRamp(tile_end
, owner
, owner_road
, owner_tram
, bridge_type
, ReverseDiagDir(dir
), rtids
, is_upgrade
);
571 case TRANSPORT_WATER
:
572 if (is_new_owner
&& c
!= nullptr) c
->infrastructure
.water
+= (bridge_len
+ 2) * TUNNELBRIDGE_TRACKBIT_FACTOR
;
573 MakeAqueductBridgeRamp(tile_start
, owner
, dir
);
574 MakeAqueductBridgeRamp(tile_end
, owner
, ReverseDiagDir(dir
));
581 /* Mark all tiles dirty */
582 MarkBridgeDirty(tile_start
, tile_end
, AxisToDiagDir(direction
), z_start
);
583 DirtyCompanyInfrastructureWindows(company
);
586 if ((flags
& DC_EXEC
) && transport_type
== TRANSPORT_RAIL
) {
587 Track track
= AxisToTrack(direction
);
588 AddSideToSignalBuffer(tile_start
, INVALID_DIAGDIR
, company
);
589 YapfNotifyTrackLayoutChange(tile_start
, track
);
592 /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
593 * It's unnecessary to execute this command every time for every bridge. So it is done only
594 * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
596 Company
*c
= Company::GetIfValid(company
);
597 if (!(flags
& DC_QUERY_COST
) || (c
!= nullptr && c
->is_ai
)) {
598 bridge_len
+= 2; // begin and end tiles/ramps
600 switch (transport_type
) {
601 case TRANSPORT_ROAD
: {
602 RoadTypeIdentifier cost_rtid
;
603 FOR_EACH_SET_ROADTYPEIDENTIFIER(cost_rtid
, rtids
) {
604 cost
.AddCost(bridge_len
* 2 * RoadBuildCost(cost_rtid
));
608 case TRANSPORT_RAIL
: cost
.AddCost(bridge_len
* RailBuildCost(railtype
)); break;
612 if (c
!= nullptr) bridge_len
= CalcBridgeLenCostFactor(bridge_len
);
614 if (transport_type
!= TRANSPORT_WATER
) {
615 cost
.AddCost((int64
)bridge_len
* _price
[PR_BUILD_BRIDGE
] * GetBridgeSpec(bridge_type
)->price
>> 8);
617 /* Aqueducts use a separate base cost. */
618 cost
.AddCost((int64
)bridge_len
* _price
[PR_BUILD_AQUEDUCT
]);
627 * Check if the amount of tiles of the chunnel ramp is between allowed limits.
628 * @param tile the actual tile.
629 * @param ramp ramp_start tile.
630 * @param delta the tile offset.
631 * @return an empty string if between limits or a formatted string for the error message.
633 static inline StringID
IsRampBetweenLimits(TileIndex ramp_start
, TileIndex tile
, TileIndexDiff delta
)
637 if (Delta(ramp_start
, tile
) < (uint
)abs(delta
) * min_length
|| (uint
)abs(delta
) * max_length
< Delta(ramp_start
, tile
)) {
638 /* Add 1 in message to have consistency with cursor count in game. */
639 SetDParam(0, max_length
+ 1);
640 return STR_ERROR_CHUNNEL_RAMP
;
647 * See if chunnel building is possible.
648 * All chunnel related issues are tucked away in one procedure
649 * @pre only on z level 0.
650 * @param tile start tile of tunnel.
651 * @param direction the direction we want to build.
652 * @param is_chunnel pointer to set if chunnel is allowed or not.
653 * @param sea_tiles pointer for the amount of tiles used to cross a sea.
654 * @return an error message or if success the is_chunnel flag is set to true and the amount of tiles needed to cross the water is returned.
656 static inline CommandCost
CanBuildChunnel(TileIndex tile
, DiagDirection direction
, bool &is_chunnel
, int &sea_tiles
)
658 const int start_z
= 0;
659 bool crossed_sea
= false;
660 TileIndex ramp_start
= tile
;
662 if (GetTileZ(tile
) > 0) return CommandError(STR_ERROR_CHUNNEL_ONLY_OVER_SEA
);
664 const TileIndexDiff delta
= TileOffsByDiagDir(direction
);
667 if (!IsValidTile(tile
)) return CommandError(STR_ERROR_CHUNNEL_THROUGH_MAP_BORDER
);
668 _build_tunnel_endtile
= tile
;
670 Slope end_tileh
= GetTileSlope(tile
, &end_z
);
672 if (start_z
== end_z
) {
673 /* Handle chunnels only on sea level and only one time crossing. */
675 (IsCoastTile(tile
) ||
676 (IsValidTile(tile
+ delta
) && HasTileWaterGround(tile
+ delta
)) ||
677 (IsValidTile(tile
+ delta
* 2) && HasTileWaterGround(tile
+ delta
* 2)))) {
679 /* A shore was found, check if start ramp was too short or too long. */
680 StringID err_msg
= IsRampBetweenLimits(ramp_start
, tile
, delta
);
681 if (err_msg
> STR_NULL
) return CommandError(err_msg
);
683 /* Pass the water and find a proper shore tile that potentially
684 * could have a tunnel portal behind. */
686 end_tileh
= GetTileSlope(tile
);
687 if (direction
== DIAGDIR_NE
&& (end_tileh
& SLOPE_NE
) == SLOPE_NE
) break;
688 if (direction
== DIAGDIR_SE
&& (end_tileh
& SLOPE_SE
) == SLOPE_SE
) break;
689 if (direction
== DIAGDIR_SW
&& (end_tileh
& SLOPE_SW
) == SLOPE_SW
) break;
690 if (direction
== DIAGDIR_NW
&& (end_tileh
& SLOPE_NW
) == SLOPE_NW
) break;
692 /* No drilling under oil rigs.*/
693 if ((IsTileType(tile
, MP_STATION
) && IsOilRig(tile
)) ||
694 (IsTileType(tile
, MP_INDUSTRY
) &&
695 GetIndustryGfx(tile
) >= GFX_OILRIG_1
&&
696 GetIndustryGfx(tile
) <= GFX_OILRIG_5
)) return CommandError(STR_ERROR_NO_DRILLING_ABOVE_CHUNNEL
);
698 if (IsTileType(tile
, MP_WATER
) && IsSea(tile
)) crossed_sea
= true;
699 if (!_cheats
.crossing_tunnels
.value
&& IsTunnelInWay(tile
, start_z
)) return CommandError(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY
);
701 if (!IsValidTile(tile
)) return CommandError(STR_ERROR_CHUNNEL_THROUGH_MAP_BORDER
);
702 _build_tunnel_endtile
= tile
;
705 if (!crossed_sea
) return CommandError(STR_ERROR_CHUNNEL_ONLY_OVER_SEA
);
708 /* Check if end ramp was too short or too long after crossing the sea. */
710 StringID err_msg
= IsRampBetweenLimits(ramp_start
, tile
, delta
);
711 if (err_msg
> STR_NULL
) return CommandError(err_msg
);
717 is_chunnel
= crossed_sea
;
719 return CommandCost();
725 * @param start_tile start tile of tunnel
726 * @param flags type of operation
727 * @param p1 bit 0-5 railtype or roadtypes
728 * bit 8-9 transport type
731 * @return the cost of this operation or an error
733 CommandCost
CmdBuildTunnel(TileIndex start_tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
735 CompanyID company
= _current_company
;
737 TransportType transport_type
= Extract
<TransportType
, 8, 2>(p1
);
738 RailType railtype
= INVALID_RAILTYPE
;
739 RoadTypeIdentifier rtid
;
740 _build_tunnel_endtile
= 0;
741 switch (transport_type
) {
743 railtype
= Extract
<RailType
, 0, 5>(p1
);
744 if (!ValParamRailtype(railtype
)) return CommandError();
747 case TRANSPORT_ROAD
: {
748 if (!rtid
.UnpackIfValid(GB(p1
, 0, 6))) return CommandError();
749 if (!ValParamRoadType(rtid
)) return CommandError();
753 default: return CommandError();
756 if (company
== OWNER_DEITY
) {
757 if (transport_type
!= TRANSPORT_ROAD
) return CommandError();
758 const Town
*town
= CalcClosestTownFromTile(start_tile
);
760 company
= OWNER_TOWN
;
762 /* If we are not within a town, we are not owned by the town */
763 if (town
== nullptr || DistanceSquare(start_tile
, town
->xy
) > town
->cache
.squared_town_zone_radius
[HZB_TOWN_EDGE
]) {
764 company
= OWNER_NONE
;
770 Slope start_tileh
= GetTileSlope(start_tile
, &start_z
);
771 DiagDirection direction
= GetInclinedSlopeDirection(start_tileh
);
772 if (direction
== INVALID_DIAGDIR
) return CommandError(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL
);
774 if (HasTileWaterGround(start_tile
)) return CommandError(STR_ERROR_CAN_T_BUILD_ON_WATER
);
776 CommandCost ret
= DoCommand(start_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
777 if (ret
.Failed()) return ret
;
779 /* XXX - do NOT change 'ret' in the loop, as it is used as the price
780 * for the clearing of the entrance of the tunnel. Assigning it to
781 * cost before the loop will yield different costs depending on start-
782 * position, because of increased-cost-by-length: 'cost += cost >> 3' */
784 TileIndexDiff delta
= TileOffsByDiagDir(direction
);
786 TileIndex end_tile
= start_tile
;
788 /* Tile shift coefficient. Will decrease for very long tunnels to avoid exponential growth of price*/
790 /* Number of tiles from start of tunnel */
792 /* Number of tiles at which the cost increase coefficient per tile is halved */
794 /* flags for chunnels. */
795 bool is_chunnel
= false;
796 bool crossed_sea
= false;
797 /* Number of tiles counted for crossing sea */
800 if (start_z
== 0 && _settings_game
.construction
.chunnel
) {
801 CommandCost chunnel_test
= CanBuildChunnel(start_tile
, direction
, is_chunnel
, sea_tiles
);
802 if (chunnel_test
.Failed()) return chunnel_test
;
808 if (!IsValidTile(end_tile
)) return CommandError(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER
);
809 end_tileh
= GetTileSlope(end_tile
, &end_z
);
811 if (start_z
== end_z
) {
812 if (is_chunnel
&& !crossed_sea
) {
813 end_tile
+= sea_tiles
* delta
;
824 /* The cost of the digging. */
825 CommandCost
cost(EXPENSES_CONSTRUCTION
);
826 for (int i
= 1; i
<= tiles
; i
++) {
827 if (i
== tiles_bump
) {
832 cost
.AddCost(_price
[PR_BUILD_TUNNEL
]);
833 cost
.AddCost(cost
.GetCost() >> tiles_coef
); // add a multiplier for longer tunnels
836 /* Add the cost of the entrance */
837 cost
.AddCost(_price
[PR_BUILD_TUNNEL
]);
840 /* if the command fails from here on we want the end tile to be highlighted */
841 _build_tunnel_endtile
= end_tile
;
843 if (tiles
> _settings_game
.construction
.max_tunnel_length
) return CommandError(STR_ERROR_TUNNEL_TOO_LONG
);
845 if (HasTileWaterGround(end_tile
)) return CommandError(STR_ERROR_CAN_T_BUILD_ON_WATER
);
847 /* Clear the tile in any case */
848 ret
= DoCommand(end_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
849 if (ret
.Failed()) return CommandError(STR_ERROR_UNABLE_TO_EXCAVATE_LAND
);
852 /* slope of end tile must be complementary to the slope of the start tile */
853 if (end_tileh
!= ComplementSlope(start_tileh
)) {
854 /* Mark the tile as already cleared for the terraform command.
855 * Do this for all tiles (like trees), not only objects. */
856 ClearedObjectArea
*coa
= FindClearedObject(end_tile
);
857 if (coa
== nullptr) {
858 coa
= _cleared_object_areas
.Append();
859 coa
->first_tile
= end_tile
;
860 coa
->area
= TileArea(end_tile
, 1, 1);
863 /* Hide the tile from the terraforming command */
864 TileIndex old_first_tile
= coa
->first_tile
;
865 coa
->first_tile
= INVALID_TILE
;
866 ret
= DoCommand(end_tile
, end_tileh
& start_tileh
, 0, flags
, CMD_TERRAFORM_LAND
);
867 coa
->first_tile
= old_first_tile
;
868 if (ret
.Failed()) return CommandError(STR_ERROR_UNABLE_TO_EXCAVATE_LAND
);
871 cost
.AddCost(_price
[PR_BUILD_TUNNEL
]);
873 /* Pay for the rail/road in the tunnel including entrances */
874 switch (transport_type
) {
875 case TRANSPORT_ROAD
: cost
.AddCost((tiles
+ 2) * RoadBuildCost(rtid
) * 2); break;
876 case TRANSPORT_RAIL
: cost
.AddCost((tiles
+ 2) * RailBuildCost(railtype
)); break;
877 default: NOT_REACHED();
880 if (is_chunnel
) cost
.MultiplyCost(2);
882 if (flags
& DC_EXEC
) {
883 Company
*c
= Company::GetIfValid(company
);
884 uint num_pieces
= (tiles
+ 2) * TUNNELBRIDGE_TRACKBIT_FACTOR
;
886 /* The most northern tile first. */
887 TileIndex tn
= start_tile
;
888 TileIndex ts
= end_tile
;
889 if(start_tile
> end_tile
) Swap(tn
, ts
);
891 if (!Tunnel::CanAllocateItem()) return CommandError(STR_ERROR_TUNNEL_TOO_MANY
);
892 const Tunnel
* tunnel
= new Tunnel(tn
, ts
, TileHeight(tn
), is_chunnel
);
894 if (transport_type
== TRANSPORT_RAIL
) {
895 if (c
!= nullptr) c
->infrastructure
.rail
[railtype
] += num_pieces
;
896 MakeRailTunnel(start_tile
, company
, tunnel
->index
, direction
, railtype
);
897 MakeRailTunnel(end_tile
, company
, tunnel
->index
, ReverseDiagDir(direction
), railtype
);
898 AddSideToSignalBuffer(start_tile
, INVALID_DIAGDIR
, company
);
899 YapfNotifyTrackLayoutChange(start_tile
, DiagDirToDiagTrack(direction
));
901 RoadTypeIdentifiers rtids
;
902 rtids
.MergeRoadType(rtid
);
904 RoadTypeIdentifier new_rtid
;
905 FOR_EACH_SET_ROADTYPEIDENTIFIER(new_rtid
, rtids
) {
906 c
->infrastructure
.road
[new_rtid
.basetype
][new_rtid
.subtype
] += num_pieces
* 2; // A full diagonal road has two road bits.
909 MakeRoadTunnel(start_tile
, company
, tunnel
->index
, direction
, rtids
);
910 MakeRoadTunnel(end_tile
, company
, tunnel
->index
, ReverseDiagDir(direction
), rtids
);
912 DirtyCompanyInfrastructureWindows(company
);
920 * Are we allowed to remove the tunnel or bridge at \a tile?
921 * @param tile End point of the tunnel or bridge.
922 * @return A succeeded command if the tunnel or bridge may be removed, a failed command otherwise.
924 static inline CommandCost
CheckAllowRemoveTunnelBridge(TileIndex tile
)
926 /* Floods can remove anything as well as the scenario editor */
927 if (_current_company
== OWNER_WATER
|| _game_mode
== GM_EDITOR
) return CommandCost();
929 switch (GetTunnelBridgeTransportType(tile
)) {
930 case TRANSPORT_ROAD
: {
931 RoadTypes rts
= GetRoadTypes(tile
);
932 Owner road_owner
= _current_company
;
933 Owner tram_owner
= _current_company
;
935 if (HasBit(rts
, ROADTYPE_ROAD
)) road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
936 if (HasBit(rts
, ROADTYPE_TRAM
)) tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
938 /* We can remove unowned road and if the town allows it */
939 if (road_owner
== OWNER_TOWN
&& _current_company
!= OWNER_TOWN
&& !(_settings_game
.construction
.extra_dynamite
|| _cheats
.magic_bulldozer
.value
)) {
940 /* Town does not allow */
941 return CheckTileOwnership(tile
);
943 if (road_owner
== OWNER_NONE
|| road_owner
== OWNER_TOWN
) road_owner
= _current_company
;
944 if (tram_owner
== OWNER_NONE
) tram_owner
= _current_company
;
946 CommandCost ret
= CheckOwnership(road_owner
, tile
);
947 if (ret
.Succeeded()) ret
= CheckOwnership(tram_owner
, tile
);
952 return CheckOwnership(GetTileOwner(tile
));
954 case TRANSPORT_WATER
: {
955 /* Always allow to remove aqueducts without owner. */
956 Owner aqueduct_owner
= GetTileOwner(tile
);
957 if (aqueduct_owner
== OWNER_NONE
) aqueduct_owner
= _current_company
;
958 return CheckOwnership(aqueduct_owner
);
961 default: NOT_REACHED();
966 * Remove a tunnel from the game, update town rating, etc.
967 * @param tile Tile containing one of the endpoints of the tunnel.
968 * @param flags Command flags.
969 * @return Succeeded or failed command.
971 static CommandCost
DoClearTunnel(TileIndex tile
, DoCommandFlag flags
)
973 CommandCost ret
= CheckAllowRemoveTunnelBridge(tile
);
974 if (ret
.Failed()) return ret
;
976 TileIndex endtile
= GetOtherTunnelEnd(tile
);
978 ret
= TunnelBridgeIsFree(tile
, endtile
);
979 if (ret
.Failed()) return ret
;
981 _build_tunnel_endtile
= endtile
;
984 if (IsTileOwner(tile
, OWNER_TOWN
) && _game_mode
!= GM_EDITOR
) {
985 t
= ClosestTownFromTile(tile
, UINT_MAX
); // town penalty rating
987 /* Check if you are allowed to remove the tunnel owned by a town
988 * Removal depends on difficulty settings */
989 CommandCost ret
= CheckforTownRating(flags
, t
, TUNNELBRIDGE_REMOVE
);
990 if (ret
.Failed()) return ret
;
993 /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
994 * you have a "Poor" (0) town rating */
995 if (IsTileOwner(tile
, OWNER_TOWN
) && _game_mode
!= GM_EDITOR
) {
996 ChangeTownRating(t
, RATING_TUNNEL_BRIDGE_DOWN_STEP
, RATING_TUNNEL_BRIDGE_MINIMUM
, flags
);
999 const bool is_chunnel
= Tunnel::GetByTile(tile
)->is_chunnel
;
1001 uint len
= GetTunnelBridgeLength(tile
, endtile
) + 2; // Don't forget the end tiles.
1003 if (flags
& DC_EXEC
) {
1004 if (GetTunnelBridgeTransportType(tile
) == TRANSPORT_RAIL
) {
1005 /* We first need to request values before calling DoClearSquare */
1006 DiagDirection dir
= GetTunnelBridgeDirection(tile
);
1007 Track track
= DiagDirToDiagTrack(dir
);
1008 Owner owner
= GetTileOwner(tile
);
1011 if (HasTunnelBridgeReservation(tile
)) {
1012 v
= GetTrainForReservation(tile
, track
);
1013 if (v
!= nullptr) FreeTrainTrackReservation(v
);
1016 if (Company::IsValidID(owner
)) {
1017 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)] -= len
* TUNNELBRIDGE_TRACKBIT_FACTOR
;
1018 if (IsTunnelBridgeWithSignalSimulation(tile
)) { // handle tunnel/bridge signals.
1019 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
-= GetTunnelBridgeSignalSimulationSignalCount(tile
, endtile
);
1021 DirtyCompanyInfrastructureWindows(owner
);
1024 delete Tunnel::GetByTile(tile
);
1026 DoClearSquare(tile
);
1027 DoClearSquare(endtile
);
1029 /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
1030 AddSideToSignalBuffer(tile
, ReverseDiagDir(dir
), owner
);
1031 AddSideToSignalBuffer(endtile
, dir
, owner
);
1033 YapfNotifyTrackLayoutChange(tile
, track
);
1034 YapfNotifyTrackLayoutChange(endtile
, track
);
1036 if (v
!= nullptr) TryPathReserve(v
);
1038 RoadTypeIdentifiers rtids
= RoadTypeIdentifiers::FromTile(tile
);
1039 RoadTypeIdentifier rtid
;
1040 FOR_EACH_SET_ROADTYPEIDENTIFIER(rtid
, rtids
) {
1041 /* A full diagonal road tile has two road bits. */
1042 Company
*c
= Company::GetIfValid(GetRoadOwner(tile
, rtid
.basetype
));
1044 c
->infrastructure
.road
[rtid
.basetype
][rtid
.subtype
] -= len
* 2 * TUNNELBRIDGE_TRACKBIT_FACTOR
;
1045 DirtyCompanyInfrastructureWindows(c
->index
);
1049 delete Tunnel::GetByTile(tile
);
1051 DoClearSquare(tile
);
1052 DoClearSquare(endtile
);
1054 ViewportMapInvalidateTunnelCacheByTile(tile
);
1055 ViewportMapInvalidateTunnelCacheByTile(endtile
);
1057 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_TUNNEL
] * len
* (is_chunnel
? 2 : 1));
1062 * Remove a bridge from the game, update town rating, etc.
1063 * @param tile Tile containing one of the endpoints of the bridge.
1064 * @param flags Command flags.
1065 * @return Succeeded or failed command.
1067 static CommandCost
DoClearBridge(TileIndex tile
, DoCommandFlag flags
)
1069 CommandCost ret
= CheckAllowRemoveTunnelBridge(tile
);
1070 if (ret
.Failed()) return ret
;
1072 TileIndex endtile
= GetOtherBridgeEnd(tile
);
1074 ret
= TunnelBridgeIsFree(tile
, endtile
);
1075 if (ret
.Failed()) return ret
;
1077 DiagDirection direction
= GetTunnelBridgeDirection(tile
);
1078 TileIndexDiff delta
= TileOffsByDiagDir(direction
);
1081 if (IsTileOwner(tile
, OWNER_TOWN
) && _game_mode
!= GM_EDITOR
) {
1082 t
= ClosestTownFromTile(tile
, UINT_MAX
); // town penalty rating
1084 /* Check if you are allowed to remove the bridge owned by a town
1085 * Removal depends on difficulty settings */
1086 CommandCost ret
= CheckforTownRating(flags
, t
, TUNNELBRIDGE_REMOVE
);
1087 if (ret
.Failed()) return ret
;
1090 /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
1091 * you have a "Poor" (0) town rating */
1092 if (IsTileOwner(tile
, OWNER_TOWN
) && _game_mode
!= GM_EDITOR
) {
1093 ChangeTownRating(t
, RATING_TUNNEL_BRIDGE_DOWN_STEP
, RATING_TUNNEL_BRIDGE_MINIMUM
, flags
);
1096 Money base_cost
= (GetTunnelBridgeTransportType(tile
) != TRANSPORT_WATER
) ? _price
[PR_CLEAR_BRIDGE
] : _price
[PR_CLEAR_AQUEDUCT
];
1097 uint len
= GetTunnelBridgeLength(tile
, endtile
) + 2; // Don't forget the end tiles.
1099 if (flags
& DC_EXEC
) {
1100 /* read this value before actual removal of bridge */
1101 bool rail
= GetTunnelBridgeTransportType(tile
) == TRANSPORT_RAIL
;
1102 Owner owner
= GetTileOwner(tile
);
1103 int height
= GetBridgeHeight(tile
);
1106 if (rail
&& HasTunnelBridgeReservation(tile
)) {
1107 v
= GetTrainForReservation(tile
, DiagDirToDiagTrack(direction
));
1108 if (v
!= nullptr) FreeTrainTrackReservation(v
);
1111 /* Update company infrastructure counts. */
1113 if (Company::IsValidID(owner
)) {
1114 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)] -= len
* TUNNELBRIDGE_TRACKBIT_FACTOR
;
1115 if (IsTunnelBridgeWithSignalSimulation(tile
)) { // handle tunnel/bridge signals.
1116 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
-= GetTunnelBridgeSignalSimulationSignalCount(tile
, endtile
);
1119 } else if (GetTunnelBridgeTransportType(tile
) == TRANSPORT_ROAD
) {
1120 SubtractRoadTunnelBridgeInfrastructure(tile
, endtile
);
1121 } else { // Aqueduct
1122 if (Company::IsValidID(owner
)) Company::Get(owner
)->infrastructure
.water
-= len
* TUNNELBRIDGE_TRACKBIT_FACTOR
;
1124 DirtyAllCompanyInfrastructureWindows();
1126 if (IsTunnelBridgeSignalSimulationEntrance(tile
)) ClearBridgeEntranceSimulatedSignals(tile
);
1127 if (IsTunnelBridgeSignalSimulationEntrance(endtile
)) ClearBridgeEntranceSimulatedSignals(endtile
);
1129 DoClearSquare(tile
);
1130 DoClearSquare(endtile
);
1131 for (TileIndex c
= tile
+ delta
; c
!= endtile
; c
+= delta
) {
1132 /* do not let trees appear from 'nowhere' after removing bridge */
1133 if (IsNormalRoadTile(c
) && GetRoadside(c
) == ROADSIDE_TREES
) {
1134 int minz
= GetTileMaxZ(c
) + 3;
1135 if (height
< minz
) SetRoadside(c
, ROADSIDE_PAVED
);
1137 ClearBridgeMiddle(c
);
1138 MarkTileDirtyByTile(c
, ZOOM_LVL_DRAW_MAP
, height
- TileHeight(c
));
1142 /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
1143 AddSideToSignalBuffer(tile
, ReverseDiagDir(direction
), owner
);
1144 AddSideToSignalBuffer(endtile
, direction
, owner
);
1146 Track track
= DiagDirToDiagTrack(direction
);
1147 YapfNotifyTrackLayoutChange(tile
, track
);
1148 YapfNotifyTrackLayoutChange(endtile
, track
);
1150 if (v
!= nullptr) TryPathReserve(v
, true);
1154 return CommandCost(EXPENSES_CONSTRUCTION
, len
* base_cost
);
1158 * Remove a tunnel or a bridge from the game.
1159 * @param tile Tile containing one of the endpoints.
1160 * @param flags Command flags.
1161 * @return Succeeded or failed command.
1163 static CommandCost
ClearTile_TunnelBridge(TileIndex tile
, DoCommandFlag flags
)
1165 if (IsTunnel(tile
)) {
1166 if (flags
& DC_AUTO
) return CommandError(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST
);
1167 return DoClearTunnel(tile
, flags
);
1168 } else { // IsBridge(tile)
1169 if (flags
& DC_AUTO
) return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
1170 return DoClearBridge(tile
, flags
);
1175 * Draw a single pillar sprite.
1176 * @param psid Pillarsprite
1180 * @param w Bounding box size in X direction
1181 * @param h Bounding box size in Y direction
1182 * @param subsprite Optional subsprite for drawing halfpillars
1184 static inline void DrawPillar(const PalSpriteID
*psid
, int x
, int y
, int z
, int w
, int h
, const SubSprite
*subsprite
)
1186 static const int PILLAR_Z_OFFSET
= TILE_HEIGHT
- BRIDGE_Z_START
; ///< Start offset of pillar wrt. bridge (downwards)
1187 AddSortableSpriteToDraw(psid
->sprite
, psid
->pal
, x
, y
, w
, h
, BB_HEIGHT_UNDER_BRIDGE
- PILLAR_Z_OFFSET
, z
, IsTransparencySet(TO_BRIDGES
), 0, 0, -PILLAR_Z_OFFSET
, subsprite
);
1191 * Draw two bridge pillars (north and south).
1192 * @param z_bottom Bottom Z
1193 * @param z_top Top Z
1194 * @param psid Pillarsprite
1197 * @param w Bounding box size in X direction
1198 * @param h Bounding box size in Y direction
1199 * @return Reached Z at the bottom
1201 static int DrawPillarColumn(int z_bottom
, int z_top
, const PalSpriteID
*psid
, int x
, int y
, int w
, int h
)
1204 for (cur_z
= z_top
; cur_z
>= z_bottom
; cur_z
-= TILE_HEIGHT
) {
1205 DrawPillar(psid
, x
, y
, cur_z
, w
, h
, nullptr);
1211 * Draws the pillars under high bridges.
1213 * @param psid Image and palette of a bridge pillar.
1214 * @param ti #TileInfo of current bridge-middle-tile.
1215 * @param axis Orientation of bridge.
1216 * @param drawfarpillar Whether to draw the pillar at the back
1217 * @param x Sprite X position of front pillar.
1218 * @param y Sprite Y position of front pillar.
1219 * @param z_bridge Absolute height of bridge bottom.
1221 static void DrawBridgePillars(const PalSpriteID
*psid
, const TileInfo
*ti
, Axis axis
, bool drawfarpillar
, int x
, int y
, int z_bridge
)
1223 static const int bounding_box_size
[2] = {16, 2}; ///< bounding box size of pillars along bridge direction
1224 static const int back_pillar_offset
[2] = { 0, 9}; ///< sprite position offset of back facing pillar
1226 static const int INF
= 1000; ///< big number compared to sprite size
1227 static const SubSprite half_pillar_sub_sprite
[2][2] = {
1228 { { -14, -INF
, INF
, INF
}, { -INF
, -INF
, -15, INF
} }, // X axis, north and south
1229 { { -INF
, -INF
, 15, INF
}, { 16, -INF
, INF
, INF
} }, // Y axis, north and south
1232 if (psid
->sprite
== 0) return;
1234 /* Determine ground height under pillars */
1235 DiagDirection south_dir
= AxisToDiagDir(axis
);
1236 int z_front_north
= ti
->z
;
1237 int z_back_north
= ti
->z
;
1238 int z_front_south
= ti
->z
;
1239 int z_back_south
= ti
->z
;
1240 GetSlopePixelZOnEdge(ti
->tileh
, south_dir
, &z_front_south
, &z_back_south
);
1241 GetSlopePixelZOnEdge(ti
->tileh
, ReverseDiagDir(south_dir
), &z_front_north
, &z_back_north
);
1243 /* Shared height of pillars */
1244 int z_front
= max(z_front_north
, z_front_south
);
1245 int z_back
= max(z_back_north
, z_back_south
);
1247 /* x and y size of bounding-box of pillars */
1248 int w
= bounding_box_size
[axis
];
1249 int h
= bounding_box_size
[OtherAxis(axis
)];
1250 /* sprite position of back facing pillar */
1251 int x_back
= x
- back_pillar_offset
[axis
];
1252 int y_back
= y
- back_pillar_offset
[OtherAxis(axis
)];
1254 /* Draw front pillars */
1255 int bottom_z
= DrawPillarColumn(z_front
, z_bridge
, psid
, x
, y
, w
, h
);
1256 if (z_front_north
< z_front
) DrawPillar(psid
, x
, y
, bottom_z
, w
, h
, &half_pillar_sub_sprite
[axis
][0]);
1257 if (z_front_south
< z_front
) DrawPillar(psid
, x
, y
, bottom_z
, w
, h
, &half_pillar_sub_sprite
[axis
][1]);
1259 /* Draw back pillars, skip top two parts, which are hidden by the bridge */
1260 int z_bridge_back
= z_bridge
- 2 * (int)TILE_HEIGHT
;
1261 if (drawfarpillar
&& (z_back_north
<= z_bridge_back
|| z_back_south
<= z_bridge_back
)) {
1262 bottom_z
= DrawPillarColumn(z_back
, z_bridge_back
, psid
, x_back
, y_back
, w
, h
);
1263 if (z_back_north
< z_back
) DrawPillar(psid
, x_back
, y_back
, bottom_z
, w
, h
, &half_pillar_sub_sprite
[axis
][0]);
1264 if (z_back_south
< z_back
) DrawPillar(psid
, x_back
, y_back
, bottom_z
, w
, h
, &half_pillar_sub_sprite
[axis
][1]);
1269 * Draws the road and trambits over an already drawn (lower end) of a bridge.
1270 * @param head_tile bridge head tile with roadtype information
1271 * @param x the x of the bridge
1272 * @param y the y of the bridge
1273 * @param z the z of the bridge
1274 * @param offset sprite offset identifying flat to sloped bridge tiles
1275 * @param head are we drawing bridge head?
1277 static void DrawBridgeRoadBits(TileIndex head_tile
, int x
, int y
, int z
, int offset
, bool head
)
1279 RoadTypeIdentifiers rtids
= RoadTypeIdentifiers::FromTile(head_tile
);
1280 const RoadtypeInfo
* road_rti
= rtids
.HasRoad() ? GetRoadTypeInfo(rtids
.road_identifier
) : NULL
;
1281 const RoadtypeInfo
* tram_rti
= rtids
.HasTram() ? GetRoadTypeInfo(rtids
.tram_identifier
) : NULL
;
1283 SpriteID seq_back
[4] = { 0 };
1284 bool trans_back
[4] = { false };
1285 SpriteID seq_front
[4] = { 0 };
1286 bool trans_front
[4] = { false };
1288 static const SpriteID overlay_offsets
[6] = { 0, 1, 11, 12, 13, 14 };
1289 static const SpriteID back_offsets
[6] = { 95, 96, 99, 102, 100, 101 };
1290 static const SpriteID front_offsets
[6] = { 97, 98, 103, 106, 104, 105 };
1292 if (head
|| !IsInvisibilitySet(TO_BRIDGES
)) {
1293 /* Road underlay takes precendence over tram */
1294 trans_back
[0] = !head
&& IsTransparencySet(TO_BRIDGES
);
1295 if (road_rti
!= NULL
) {
1296 if (road_rti
->UsesOverlay()) {
1297 seq_back
[0] = GetCustomRoadSprite(road_rti
, head_tile
, ROTSG_BRIDGE
, head
? TCX_NORMAL
: TCX_ON_BRIDGE
) + offset
;
1299 } else if (tram_rti
!= NULL
) {
1300 if (tram_rti
->UsesOverlay()) {
1301 seq_back
[0] = GetCustomRoadSprite(tram_rti
, head_tile
, ROTSG_BRIDGE
, head
? TCX_NORMAL
: TCX_ON_BRIDGE
) + offset
;
1303 seq_back
[0] = SPR_TRAMWAY_BRIDGE
+ offset
;
1307 /* Draw road overlay */
1308 trans_back
[1] = !head
&& IsTransparencySet(TO_BRIDGES
);
1309 if (road_rti
!= NULL
) {
1310 if (road_rti
->UsesOverlay()) {
1311 seq_back
[1] = GetCustomRoadSprite(road_rti
, head_tile
, ROTSG_OVERLAY
, head
? TCX_NORMAL
: TCX_ON_BRIDGE
);
1312 if (seq_back
[1] != 0) seq_back
[1] += overlay_offsets
[offset
];
1316 /* Draw tram overlay */
1317 trans_back
[2] = !head
&& IsTransparencySet(TO_BRIDGES
);
1318 if (tram_rti
!= NULL
) {
1319 if (tram_rti
->UsesOverlay()) {
1320 seq_back
[2] = GetCustomRoadSprite(tram_rti
, head_tile
, ROTSG_OVERLAY
, head
? TCX_NORMAL
: TCX_ON_BRIDGE
);
1321 if (seq_back
[2] != 0) seq_back
[2] += overlay_offsets
[offset
];
1322 } else if (road_rti
!= NULL
) {
1323 seq_back
[2] = SPR_TRAMWAY_OVERLAY
+ overlay_offsets
[offset
];
1327 /* Road catenary takes precendence over tram */
1328 trans_back
[3] = IsTransparencySet(TO_CATENARY
);
1329 trans_front
[0] = IsTransparencySet(TO_CATENARY
);
1330 if (road_rti
!= NULL
&& HasRoadCatenaryDrawn(rtids
.road_identifier
)) {
1331 seq_back
[3] = GetCustomRoadSprite(road_rti
, head_tile
, ROTSG_CATENARY_BACK
, head
? TCX_NORMAL
: TCX_ON_BRIDGE
);
1332 seq_front
[0] = GetCustomRoadSprite(road_rti
, head_tile
, ROTSG_CATENARY_FRONT
, head
? TCX_NORMAL
: TCX_ON_BRIDGE
);
1333 if (seq_back
[3] == 0 || seq_front
[0] == 0) {
1334 seq_back
[3] = SPR_TRAMWAY_BASE
+ back_offsets
[offset
];
1335 seq_front
[0] = SPR_TRAMWAY_BASE
+ front_offsets
[offset
];
1337 seq_back
[3] += 23 + offset
;
1338 seq_front
[0] += 23 + offset
;
1340 } else if (tram_rti
!= NULL
&& HasRoadCatenaryDrawn(rtids
.tram_identifier
)) {
1341 seq_back
[3] = GetCustomRoadSprite(tram_rti
, head_tile
, ROTSG_CATENARY_BACK
, head
? TCX_NORMAL
: TCX_ON_BRIDGE
);
1342 seq_front
[0] = GetCustomRoadSprite(tram_rti
, head_tile
, ROTSG_CATENARY_FRONT
, head
? TCX_NORMAL
: TCX_ON_BRIDGE
);
1343 if (seq_back
[3] == 0 || seq_front
[0] == 0) {
1344 seq_back
[3] = SPR_TRAMWAY_BASE
+ back_offsets
[offset
];
1345 seq_front
[0] = SPR_TRAMWAY_BASE
+ front_offsets
[offset
];
1347 seq_back
[3] += 23 + offset
;
1348 seq_front
[0] += 23 + offset
;
1353 static const uint size_x
[6] = { 1, 16, 16, 1, 16, 1 };
1354 static const uint size_y
[6] = { 16, 1, 1, 16, 1, 16 };
1355 static const uint front_bb_offset_x
[6] = { 15, 0, 0, 15, 0, 15 };
1356 static const uint front_bb_offset_y
[6] = { 0, 15, 15, 0, 15, 0 };
1358 /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
1359 * The bounding boxes here are the same as for bridge front/roof */
1360 for (uint i
= 0; i
< lengthof(seq_back
); ++i
) {
1361 if (seq_back
[i
] != 0) {
1362 AddSortableSpriteToDraw(seq_back
[i
], PAL_NONE
,
1363 x
, y
, size_x
[offset
], size_y
[offset
], 0x28, z
,
1368 /* Start a new SpriteCombine for the front part */
1370 StartSpriteCombine();
1372 for (uint i
= 0; i
< lengthof(seq_front
); ++i
) {
1373 if (seq_front
[i
] != 0) {
1374 AddSortableSpriteToDraw(seq_front
[i
], PAL_NONE
,
1375 x
, y
, size_x
[offset
] + front_bb_offset_x
[offset
], size_y
[offset
] + front_bb_offset_y
[offset
], 0x28, z
,
1377 front_bb_offset_x
[offset
], front_bb_offset_y
[offset
]);
1382 /* Draws a signal on tunnel / bridge entrance tile. */
1383 static void DrawTunnelBridgeRampSignal(const TileInfo
*ti
)
1385 bool side
= (_settings_game
.vehicle
.road_side
!= 0) &&_settings_game
.construction
.train_signal_side
;
1387 static const Point SignalPositions
[2][4] = {
1388 { /* X X Y Y Signals on the left side */
1389 {13, 3}, { 2, 13}, { 3, 4}, {13, 14}
1390 }, {/* X X Y Y Signals on the right side */
1391 {14, 13}, { 3, 3}, {13, 2}, { 3, 13}
1396 DiagDirection dir
= GetTunnelBridgeDirection(ti
->tile
);
1399 default: NOT_REACHED();
1400 case DIAGDIR_NE
: position
= 0; break;
1401 case DIAGDIR_SE
: position
= 2; break;
1402 case DIAGDIR_SW
: position
= 1; break;
1403 case DIAGDIR_NW
: position
= 3; break;
1406 SignalType type
= SIGTYPE_NORMAL
;
1408 bool is_green
= (GetTunnelBridgeSignalState(ti
->tile
) == SIGNAL_STATE_GREEN
);
1410 if (IsTunnelBridgeSignalSimulationExit(ti
->tile
)) {
1413 if (IsTunnelBridgePBS(ti
->tile
)) type
= SIGTYPE_PBS_ONEWAY
;
1418 uint x
= TileX(ti
->tile
) * TILE_SIZE
+ SignalPositions
[side
!= show_exit
][position
^ (show_exit
? 1 : 0)].x
;
1419 uint y
= TileY(ti
->tile
) * TILE_SIZE
+ SignalPositions
[side
!= show_exit
][position
^ (show_exit
? 1 : 0)].y
;
1422 if (ti
->tileh
== SLOPE_FLAT
&& side
== show_exit
&& dir
== DIAGDIR_SE
) z
+= 2;
1423 if (ti
->tileh
== SLOPE_FLAT
&& side
!= show_exit
&& dir
== DIAGDIR_SW
) z
+= 2;
1425 if (ti
->tileh
!= SLOPE_FLAT
&& IsBridge(ti
->tile
)) z
+= 8; // sloped bridge head
1426 SignalVariant variant
= IsTunnelBridgeSemaphore(ti
->tile
) ? SIG_SEMAPHORE
: SIG_ELECTRIC
;
1427 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
1429 SpriteID sprite
= GetCustomSignalSprite(rti
, ti
->tile
, type
, variant
, is_green
? SIGNAL_STATE_GREEN
: SIGNAL_STATE_RED
);
1430 bool is_custom_sprite
= (sprite
!= 0);
1432 if (is_custom_sprite
) {
1436 if (variant
== SIG_ELECTRIC
&& type
== SIGTYPE_NORMAL
) {
1437 /* Normal electric signals are picked from original sprites. */
1438 sprite
= SPR_ORIGINAL_SIGNALS_BASE
+ ((position
<< 1) + is_green
);
1441 /* All other signals are picked from add on sprites. */
1442 sprite
= SPR_SIGNALS_BASE
+ ((type
- 1) * 16 + variant
* 64 + (position
<< 1) + is_green
) + (type
> SIGTYPE_LAST_NOPBS
? 64 : 0);
1446 AddSortableSpriteToDraw(sprite
, PAL_NONE
, x
, y
, 1, 1, TILE_HEIGHT
, z
, false, 0, 0, BB_Z_SEPARATOR
);
1450 * Draws a tunnel of bridge tile.
1451 * For tunnels, this is rather simple, as you only need to draw the entrance.
1452 * Bridges are a bit more complex. base_offset is where the sprite selection comes into play
1453 * and it works a bit like a bitmask.<p> For bridge heads:
1454 * @param ti TileInfo of the structure to draw
1455 * <ul><li>Bit 0: direction</li>
1456 * <li>Bit 1: northern or southern heads</li>
1457 * <li>Bit 2: Set if the bridge head is sloped</li>
1458 * <li>Bit 3 and more: Railtype Specific subset</li>
1460 * Please note that in this code, "roads" are treated as railtype 1, whilst the real railtypes are 0, 2 and 3
1462 static void DrawTile_TunnelBridge(TileInfo
*ti
)
1464 TransportType transport_type
= GetTunnelBridgeTransportType(ti
->tile
);
1465 DiagDirection tunnelbridge_direction
= GetTunnelBridgeDirection(ti
->tile
);
1467 if (IsTunnel(ti
->tile
)) {
1468 /* Front view of tunnel bounding boxes:
1470 * 122223 <- BB_Z_SEPARATOR
1472 * 1 3 1,3 = empty helper BB
1473 * 1 3 2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
1477 static const int _tunnel_BB
[4][12] = {
1478 /* tunnnel-roof | Z-separator | tram-catenary
1479 * w h bb_x bb_y| x y w h |bb_x bb_y w h */
1480 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // NE
1481 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // SE
1482 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // SW
1483 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // NW
1485 const int *BB_data
= _tunnel_BB
[tunnelbridge_direction
];
1487 bool catenary
= false;
1490 SpriteID railtype_overlay
= 0;
1491 if (transport_type
== TRANSPORT_RAIL
) {
1492 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
1493 image
= rti
->base_sprites
.tunnel
;
1494 if (rti
->UsesOverlay()) {
1495 /* Check if the railtype has custom tunnel portals. */
1496 railtype_overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_TUNNEL_PORTAL
);
1497 if (railtype_overlay
!= 0) image
= SPR_RAILTYPE_TUNNEL_BASE
; // Draw blank grass tunnel base.
1500 image
= SPR_TUNNEL_ENTRY_REAR_ROAD
;
1503 if (HasTunnelBridgeSnowOrDesert(ti
->tile
)) image
+= railtype_overlay
!= 0 ? 8 : 32;
1505 image
+= tunnelbridge_direction
* 2;
1506 DrawGroundSprite(image
, PAL_NONE
);
1508 if (transport_type
== TRANSPORT_ROAD
) {
1509 RoadTypeIdentifiers rtids
= RoadTypeIdentifiers::FromTile(ti
->tile
);
1510 const RoadtypeInfo
* road_rti
= rtids
.HasRoad() ? GetRoadTypeInfo(rtids
.road_identifier
) : NULL
;
1511 const RoadtypeInfo
* tram_rti
= rtids
.HasTram() ? GetRoadTypeInfo(rtids
.tram_identifier
) : NULL
;
1512 uint sprite_offset
= DiagDirToAxis(tunnelbridge_direction
) == AXIS_X
? 1 : 0;
1514 /* Road underlay takes precendence over tram */
1515 if (road_rti
!= NULL
) {
1516 if (road_rti
->UsesOverlay()) {
1517 SpriteID ground
= GetCustomRoadSprite(road_rti
, ti
->tile
, ROTSG_GROUND
);
1518 DrawGroundSprite(ground
+ sprite_offset
, PAL_NONE
);
1520 } else if (tram_rti
!= NULL
) {
1521 if (tram_rti
->UsesOverlay()) {
1522 SpriteID ground
= GetCustomRoadSprite(tram_rti
, ti
->tile
, ROTSG_GROUND
);
1523 DrawGroundSprite(ground
+ sprite_offset
, PAL_NONE
);
1525 DrawGroundSprite(SPR_TRAMWAY_TRAM
+ sprite_offset
, PAL_NONE
);
1529 /* Draw road overlay */
1530 if (road_rti
!= NULL
) {
1531 if (road_rti
->UsesOverlay()) {
1532 SpriteID ground
= GetCustomRoadSprite(road_rti
, ti
->tile
, ROTSG_OVERLAY
);
1533 if (ground
) DrawGroundSprite(ground
+ sprite_offset
, PAL_NONE
);
1537 /* Draw tram overlay */
1538 if (tram_rti
!= NULL
) {
1539 if (tram_rti
->UsesOverlay()) {
1540 SpriteID ground
= GetCustomRoadSprite(tram_rti
, ti
->tile
, ROTSG_OVERLAY
);
1541 if (ground
) DrawGroundSprite(ground
+ sprite_offset
, PAL_NONE
);
1542 } else if (road_rti
!= NULL
) {
1543 DrawGroundSprite(SPR_TRAMWAY_OVERLAY
+ sprite_offset
, PAL_NONE
);
1547 /* Road catenary takes precendence over tram */
1548 SpriteID catenary_sprite_base
= 0;
1549 if (road_rti
!= NULL
&& HasRoadCatenaryDrawn(rtids
.road_identifier
)) {
1550 catenary_sprite_base
= GetCustomRoadSprite(road_rti
, ti
->tile
, ROTSG_CATENARY_FRONT
);
1551 if (catenary_sprite_base
== 0) {
1552 catenary_sprite_base
= SPR_TRAMWAY_TUNNEL_WIRES
;
1554 catenary_sprite_base
+= 19;
1556 } else if (tram_rti
!= NULL
&& HasRoadCatenaryDrawn(rtids
.tram_identifier
)) {
1557 catenary_sprite_base
= GetCustomRoadSprite(tram_rti
, ti
->tile
, ROTSG_CATENARY_FRONT
);
1558 if (catenary_sprite_base
== 0) {
1559 catenary_sprite_base
= SPR_TRAMWAY_TUNNEL_WIRES
;
1561 catenary_sprite_base
+= 19;
1565 if (catenary_sprite_base
!= 0) {
1567 StartSpriteCombine();
1568 AddSortableSpriteToDraw(catenary_sprite_base
+ 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
);
1571 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
1572 if (rti
->UsesOverlay()) {
1573 SpriteID surface
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_TUNNEL
);
1574 if (surface
!= 0) DrawGroundSprite(surface
+ tunnelbridge_direction
, PAL_NONE
);
1577 DrawOverlay(ti
, MP_TUNNELBRIDGE
);
1579 /* PBS debugging, draw reserved tracks darker */
1580 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasTunnelBridgeReservation(ti
->tile
)) {
1581 if (rti
->UsesOverlay()) {
1582 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
1583 DrawGroundSprite(overlay
+ RTO_X
+ DiagDirToAxis(tunnelbridge_direction
), PALETTE_CRASH
);
1585 DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
);
1589 if (HasRailCatenaryDrawn(GetRailType(ti
->tile
))) {
1590 /* Maybe draw pylons on the entry side */
1591 DrawRailCatenary(ti
);
1594 StartSpriteCombine();
1595 /* Draw wire above the ramp */
1596 DrawRailCatenaryOnTunnel(ti
);
1600 if (railtype_overlay
!= 0 && !catenary
) StartSpriteCombine();
1602 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
);
1603 /* Draw railtype tunnel portal overlay if defined. */
1604 if (railtype_overlay
!= 0) AddSortableSpriteToDraw(railtype_overlay
+ tunnelbridge_direction
, 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
);
1606 if (catenary
|| railtype_overlay
!= 0) EndSpriteCombine();
1608 /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
1609 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX
, PAL_NONE
, ti
->x
, ti
->y
, BB_data
[6], BB_data
[7], TILE_HEIGHT
, ti
->z
);
1610 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
);
1612 /* Draw signals for tunnel. */
1613 if (IsTunnelBridgeWithSignalSimulation(ti
->tile
)) DrawTunnelBridgeRampSignal(ti
);
1615 DrawBridgeMiddle(ti
);
1616 } else { // IsBridge(ti->tile)
1617 if (transport_type
== TRANSPORT_ROAD
&& IsRoadCustomBridgeHead(ti
->tile
)) {
1619 DrawBridgeMiddle(ti
);
1623 const PalSpriteID
*psid
;
1625 bool ice
= HasTunnelBridgeSnowOrDesert(ti
->tile
);
1627 if (transport_type
== TRANSPORT_RAIL
) {
1628 base_offset
= GetRailTypeInfo(GetRailType(ti
->tile
))->bridge_offset
;
1629 assert(base_offset
!= 8); // This one is used for roads
1634 /* as the lower 3 bits are used for other stuff, make sure they are clear */
1635 assert( (base_offset
& 0x07) == 0x00);
1637 DrawFoundation(ti
, GetBridgeFoundation(ti
->tileh
, DiagDirToAxis(tunnelbridge_direction
)));
1639 /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
1640 base_offset
+= (6 - tunnelbridge_direction
) % 4;
1642 /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
1643 if (transport_type
!= TRANSPORT_WATER
) {
1644 if (ti
->tileh
== SLOPE_FLAT
) base_offset
+= 4; // sloped bridge head
1645 psid
= &GetBridgeSpriteTable(GetBridgeType(ti
->tile
), BRIDGE_PIECE_HEAD
)[base_offset
];
1647 psid
= _aqueduct_sprites
+ base_offset
;
1651 TileIndex next
= ti
->tile
+ TileOffsByDiagDir(tunnelbridge_direction
);
1652 if (ti
->tileh
!= SLOPE_FLAT
&& ti
->z
== 0 && HasTileWaterClass(next
) && GetWaterClass(next
) == WATER_CLASS_SEA
) {
1653 DrawShoreTile(ti
->tileh
);
1655 DrawClearLandTile(ti
, 3);
1658 DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE
+ SlopeToSpriteOffset(ti
->tileh
), PAL_NONE
);
1663 /* Draw Trambits and PBS Reservation as SpriteCombine */
1664 if (transport_type
== TRANSPORT_ROAD
|| transport_type
== TRANSPORT_RAIL
) StartSpriteCombine();
1666 /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
1667 * it doesn't disappear behind it
1669 /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
1670 AddSortableSpriteToDraw(psid
->sprite
, psid
->pal
, ti
->x
, ti
->y
, 16, 16, ti
->tileh
== SLOPE_FLAT
? 0 : 8, ti
->z
);
1672 if (transport_type
== TRANSPORT_ROAD
) {
1673 uint offset
= tunnelbridge_direction
;
1675 if (ti
->tileh
!= SLOPE_FLAT
) {
1676 offset
= (offset
+ 1) & 1;
1682 /* DrawBridgeRoadBits() calls EndSpriteCombine() and StartSpriteCombine() */
1683 DrawBridgeRoadBits(ti
->tile
, ti
->x
, ti
->y
, z
, offset
, true);
1686 } else if (transport_type
== TRANSPORT_RAIL
) {
1687 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
1688 if (rti
->UsesOverlay()) {
1689 SpriteID surface
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_BRIDGE
);
1691 if (HasBridgeFlatRamp(ti
->tileh
, DiagDirToAxis(tunnelbridge_direction
))) {
1692 AddSortableSpriteToDraw(surface
+ ((DiagDirToAxis(tunnelbridge_direction
) == AXIS_X
) ? RTBO_X
: RTBO_Y
), PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 0, ti
->z
+ 8);
1694 AddSortableSpriteToDraw(surface
+ RTBO_SLOPE
+ tunnelbridge_direction
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 8, ti
->z
);
1697 /* Don't fallback to non-overlay sprite -- the spec states that
1698 * if an overlay is present then the bridge surface must be
1702 /* PBS debugging, draw reserved tracks darker */
1703 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasTunnelBridgeReservation(ti
->tile
)) {
1704 if (rti
->UsesOverlay()) {
1705 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
1706 if (HasBridgeFlatRamp(ti
->tileh
, DiagDirToAxis(tunnelbridge_direction
))) {
1707 AddSortableSpriteToDraw(overlay
+ RTO_X
+ DiagDirToAxis(tunnelbridge_direction
), PALETTE_CRASH
, ti
->x
, ti
->y
, 16, 16, 0, ti
->z
+ 8);
1709 AddSortableSpriteToDraw(overlay
+ RTO_SLOPE_NE
+ tunnelbridge_direction
, PALETTE_CRASH
, ti
->x
, ti
->y
, 16, 16, 8, ti
->z
);
1712 if (HasBridgeFlatRamp(ti
->tileh
, DiagDirToAxis(tunnelbridge_direction
))) {
1713 AddSortableSpriteToDraw(DiagDirToAxis(tunnelbridge_direction
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
, ti
->x
, ti
->y
, 16, 16, 0, ti
->z
+ 8);
1715 AddSortableSpriteToDraw(rti
->base_sprites
.single_sloped
+ tunnelbridge_direction
, PALETTE_CRASH
, ti
->x
, ti
->y
, 16, 16, 8, ti
->z
);
1721 if (HasRailCatenaryDrawn(GetRailType(ti
->tile
))) {
1722 DrawRailCatenary(ti
);
1726 /* Draw signals for bridge. */
1727 if (IsTunnelBridgeWithSignalSimulation(ti
->tile
)) DrawTunnelBridgeRampSignal(ti
);
1729 DrawBridgeMiddle(ti
);
1735 * Compute bridge piece. Computes the bridge piece to display depending on the position inside the bridge.
1736 * bridges pieces sequence (middle parts).
1737 * Note that it is not covering the bridge heads, which are always referenced by the same sprite table.
1738 * bridge len 1: BRIDGE_PIECE_NORTH
1739 * bridge len 2: BRIDGE_PIECE_NORTH BRIDGE_PIECE_SOUTH
1740 * bridge len 3: BRIDGE_PIECE_NORTH BRIDGE_PIECE_MIDDLE_ODD BRIDGE_PIECE_SOUTH
1741 * bridge len 4: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1742 * bridge len 5: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_MIDDLE_EVEN BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1743 * bridge len 6: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1744 * bridge len 7: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_MIDDLE_ODD BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1745 * #0 - always as first, #1 - always as last (if len>1)
1746 * #2,#3 are to pair in order
1747 * for odd bridges: #5 is going in the bridge middle if on even position, #4 on odd (counting from 0)
1748 * @param north Northernmost tile of bridge
1749 * @param south Southernmost tile of bridge
1750 * @return Index of bridge piece
1752 static BridgePieces
CalcBridgePiece(uint north
, uint south
)
1755 return BRIDGE_PIECE_NORTH
;
1756 } else if (south
== 1) {
1757 return BRIDGE_PIECE_SOUTH
;
1758 } else if (north
< south
) {
1759 return north
& 1 ? BRIDGE_PIECE_INNER_SOUTH
: BRIDGE_PIECE_INNER_NORTH
;
1760 } else if (north
> south
) {
1761 return south
& 1 ? BRIDGE_PIECE_INNER_NORTH
: BRIDGE_PIECE_INNER_SOUTH
;
1763 return north
& 1 ? BRIDGE_PIECE_MIDDLE_EVEN
: BRIDGE_PIECE_MIDDLE_ODD
;
1768 * Draw the middle bits of a bridge.
1769 * @param ti Tile information of the tile to draw it on.
1771 void DrawBridgeMiddle(const TileInfo
*ti
)
1773 /* Sectional view of bridge bounding boxes:
1775 * 1 2 1,2 = SpriteCombine of Bridge front/(back&floor) and RoadCatenary
1776 * 1 2 3 = empty helper BB
1777 * 1 7 2 4,5 = pillars under higher bridges
1778 * 1 6 88888 6 2 6 = elrail-pylons
1779 * 1 6 88888 6 2 7 = elrail-wire
1780 * 1 6 88888 6 2 <- TILE_HEIGHT 8 = rail-vehicle on bridge
1781 * 3333333333333 <- BB_Z_SEPARATOR
1783 * 4 5 <- BB_HEIGHT_UNDER_BRIDGE
1789 if (!IsBridgeAbove(ti
->tile
)) return;
1791 TileIndex rampnorth
= GetNorthernBridgeEnd(ti
->tile
);
1792 TileIndex rampsouth
= GetSouthernBridgeEnd(ti
->tile
);
1793 TransportType transport_type
= GetTunnelBridgeTransportType(rampsouth
);
1795 Axis axis
= GetBridgeAxis(ti
->tile
);
1796 BridgePieces piece
= CalcBridgePiece(
1797 GetTunnelBridgeLength(ti
->tile
, rampnorth
) + 1,
1798 GetTunnelBridgeLength(ti
->tile
, rampsouth
) + 1
1801 const PalSpriteID
*psid
;
1803 if (transport_type
!= TRANSPORT_WATER
) {
1804 BridgeType type
= GetBridgeType(rampsouth
);
1805 drawfarpillar
= !HasBit(GetBridgeSpec(type
)->flags
, 0);
1808 if (transport_type
== TRANSPORT_RAIL
) {
1809 base_offset
= GetRailTypeInfo(GetRailType(rampsouth
))->bridge_offset
;
1814 psid
= base_offset
+ GetBridgeSpriteTable(type
, piece
);
1816 drawfarpillar
= true;
1817 psid
= _aqueduct_sprites
;
1820 if (axis
!= AXIS_X
) psid
+= 4;
1824 uint bridge_z
= GetBridgePixelHeight(rampsouth
);
1825 int z
= bridge_z
- BRIDGE_Z_START
;
1827 /* Add a bounding box that separates the bridge from things below it. */
1828 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX
, PAL_NONE
, x
, y
, 16, 16, 1, bridge_z
- TILE_HEIGHT
+ BB_Z_SEPARATOR
);
1830 /* Draw Trambits as SpriteCombine */
1831 if (transport_type
== TRANSPORT_ROAD
|| transport_type
== TRANSPORT_RAIL
) StartSpriteCombine();
1833 /* Draw floor and far part of bridge*/
1834 if (!IsInvisibilitySet(TO_BRIDGES
)) {
1835 if (axis
== AXIS_X
) {
1836 AddSortableSpriteToDraw(psid
->sprite
, psid
->pal
, x
, y
, 16, 1, 0x28, z
, IsTransparencySet(TO_BRIDGES
), 0, 0, BRIDGE_Z_START
);
1838 AddSortableSpriteToDraw(psid
->sprite
, psid
->pal
, x
, y
, 1, 16, 0x28, z
, IsTransparencySet(TO_BRIDGES
), 0, 0, BRIDGE_Z_START
);
1844 if (transport_type
== TRANSPORT_ROAD
) {
1845 /* DrawBridgeRoadBits() calls EndSpriteCombine() and StartSpriteCombine() */
1846 DrawBridgeRoadBits(rampsouth
, x
, y
, bridge_z
, axis
^ 1, false);
1847 } else if (transport_type
== TRANSPORT_RAIL
) {
1848 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(rampsouth
));
1849 if (rti
->UsesOverlay() && !IsInvisibilitySet(TO_BRIDGES
)) {
1850 SpriteID surface
= GetCustomRailSprite(rti
, rampsouth
, RTSG_BRIDGE
, TCX_ON_BRIDGE
);
1852 AddSortableSpriteToDraw(surface
+ axis
, PAL_NONE
, x
, y
, 16, 16, 0, bridge_z
, IsTransparencySet(TO_BRIDGES
));
1856 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& !IsInvisibilitySet(TO_BRIDGES
) && HasTunnelBridgeReservation(rampnorth
)
1857 && !IsTunnelBridgeWithSignalSimulation(rampnorth
)) {
1858 if (rti
->UsesOverlay()) {
1859 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
1860 AddSortableSpriteToDraw(overlay
+ RTO_X
+ axis
, PALETTE_CRASH
, ti
->x
, ti
->y
, 16, 16, 0, bridge_z
, IsTransparencySet(TO_BRIDGES
));
1862 AddSortableSpriteToDraw(axis
== AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
, ti
->x
, ti
->y
, 16, 16, 0, bridge_z
, IsTransparencySet(TO_BRIDGES
));
1868 if (HasRailCatenaryDrawn(GetRailType(rampsouth
))) {
1869 DrawRailCatenaryOnBridge(ti
);
1873 /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
1874 if (!IsInvisibilitySet(TO_BRIDGES
)) {
1875 if (axis
== AXIS_X
) {
1877 if (psid
->sprite
& SPRITE_MASK
) AddSortableSpriteToDraw(psid
->sprite
, psid
->pal
, x
, y
, 16, 4, 0x28, z
, IsTransparencySet(TO_BRIDGES
), 0, 3, BRIDGE_Z_START
);
1880 if (psid
->sprite
& SPRITE_MASK
) AddSortableSpriteToDraw(psid
->sprite
, psid
->pal
, x
, y
, 4, 16, 0x28, z
, IsTransparencySet(TO_BRIDGES
), 3, 0, BRIDGE_Z_START
);
1884 /* Draw TramFront as SpriteCombine */
1885 if (transport_type
== TRANSPORT_ROAD
) EndSpriteCombine();
1887 /* Do not draw anything more if bridges are invisible */
1888 if (IsInvisibilitySet(TO_BRIDGES
)) return;
1891 if (ti
->z
+ 5 == z
) {
1892 /* draw poles below for small bridges */
1893 if (psid
->sprite
!= 0) {
1894 SpriteID image
= psid
->sprite
;
1895 SpriteID pal
= psid
->pal
;
1896 if (IsTransparencySet(TO_BRIDGES
)) {
1897 SetBit(image
, PALETTE_MODIFIER_TRANSPARENT
);
1898 pal
= PALETTE_TO_TRANSPARENT
;
1901 DrawGroundSpriteAt(image
, pal
, x
- ti
->x
, y
- ti
->y
, z
- ti
->z
);
1904 /* draw pillars below for high bridges */
1905 DrawBridgePillars(psid
, ti
, axis
, drawfarpillar
, x
, y
, z
);
1910 static int GetSlopePixelZ_TunnelBridge(TileIndex tile
, uint x
, uint y
)
1913 Slope tileh
= GetTilePixelSlope(tile
, &z
);
1918 if (IsTunnel(tile
)) {
1919 uint pos
= (DiagDirToAxis(GetTunnelBridgeDirection(tile
)) == AXIS_X
? y
: x
);
1921 /* In the tunnel entrance? */
1922 if (5 <= pos
&& pos
<= 10) return z
;
1923 } else { // IsBridge(tile)
1924 if (IsRoadCustomBridgeHeadTile(tile
)) {
1925 return z
+ TILE_HEIGHT
+ (IsSteepSlope(tileh
) ? TILE_HEIGHT
: 0);
1928 DiagDirection dir
= GetTunnelBridgeDirection(tile
);
1929 uint pos
= (DiagDirToAxis(dir
) == AXIS_X
? y
: x
);
1931 z
+= ApplyPixelFoundationToSlope(GetBridgeFoundation(tileh
, DiagDirToAxis(dir
)), &tileh
);
1933 /* On the bridge ramp? */
1934 if (5 <= pos
&& pos
<= 10) {
1937 if (tileh
!= SLOPE_FLAT
) return z
+ TILE_HEIGHT
;
1940 default: NOT_REACHED();
1941 case DIAGDIR_NE
: delta
= (TILE_SIZE
- 1 - x
) / 2; break;
1942 case DIAGDIR_SE
: delta
= y
/ 2; break;
1943 case DIAGDIR_SW
: delta
= x
/ 2; break;
1944 case DIAGDIR_NW
: delta
= (TILE_SIZE
- 1 - y
) / 2; break;
1946 return z
+ 1 + delta
;
1950 return z
+ GetPartialPixelZ(x
, y
, tileh
);
1953 static Foundation
GetFoundation_TunnelBridge(TileIndex tile
, Slope tileh
)
1955 if (IsRoadCustomBridgeHeadTile(tile
)) return FOUNDATION_LEVELED
;
1956 return IsTunnel(tile
) ? FOUNDATION_NONE
: GetBridgeFoundation(tileh
, DiagDirToAxis(GetTunnelBridgeDirection(tile
)));
1959 static void GetTileDesc_TunnelBridge(TileIndex tile
, TileDesc
*td
)
1961 TransportType tt
= GetTunnelBridgeTransportType(tile
);
1963 if (IsTunnel(tile
)) {
1964 if (Tunnel::GetByTile(tile
)->is_chunnel
) {
1965 td
->str
= (tt
== TRANSPORT_RAIL
) ? IsTunnelBridgeWithSignalSimulation(tile
) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_SIGNAL_CHUNNEL
: STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_CHUNNEL
: STR_LAI_TUNNEL_DESCRIPTION_ROAD_CHUNNEL
;
1967 td
->str
= (tt
== TRANSPORT_RAIL
) ? IsTunnelBridgeWithSignalSimulation(tile
) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_SIGNAL
: STR_LAI_TUNNEL_DESCRIPTION_RAILROAD
: STR_LAI_TUNNEL_DESCRIPTION_ROAD
;
1969 } else { // IsBridge(tile)
1970 td
->str
= (tt
== TRANSPORT_WATER
) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT
: IsTunnelBridgeWithSignalSimulation(tile
) ? STR_LAI_BRIDGE_DESCRIPTION_RAILROAD_SIGNAL
: GetBridgeSpec(GetBridgeType(tile
))->transport_name
[tt
];
1972 td
->owner
[0] = GetTileOwner(tile
);
1974 Owner road_owner
= INVALID_OWNER
;
1975 Owner tram_owner
= INVALID_OWNER
;
1976 RoadTypeIdentifiers rtids
= RoadTypeIdentifiers::FromTile(tile
);
1977 if (rtids
.HasRoad()) {
1978 const RoadtypeInfo
*rti
= GetRoadTypeInfo(rtids
.road_identifier
);
1979 td
->roadtype
= rti
->strings
.name
;
1980 td
->road_speed
= rti
->max_speed
/ 2;
1981 road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
1983 if (rtids
.HasTram()) {
1984 const RoadtypeInfo
*rti
= GetRoadTypeInfo(rtids
.tram_identifier
);
1985 td
->tramtype
= rti
->strings
.name
;
1986 td
->tram_speed
= rti
->max_speed
/ 2;
1987 tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
1990 /* Is there a mix of owners? */
1991 if ((tram_owner
!= INVALID_OWNER
&& tram_owner
!= td
->owner
[0]) ||
1992 (road_owner
!= INVALID_OWNER
&& road_owner
!= td
->owner
[0])) {
1994 if (road_owner
!= INVALID_OWNER
) {
1995 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_ROAD_OWNER
;
1996 td
->owner
[i
] = road_owner
;
1999 if (tram_owner
!= INVALID_OWNER
) {
2000 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_TRAM_OWNER
;
2001 td
->owner
[i
] = tram_owner
;
2005 if (tt
== TRANSPORT_RAIL
) {
2006 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
2007 td
->rail_speed
= rti
->max_speed
;
2008 td
->railtype
= rti
->strings
.name
;
2010 if (!IsTunnel(tile
)) {
2011 uint16 spd
= GetBridgeSpec(GetBridgeType(tile
))->speed
;
2012 if (td
->rail_speed
== 0 || spd
< td
->rail_speed
) {
2013 td
->rail_speed
= spd
;
2016 } else if (tt
== TRANSPORT_ROAD
&& !IsTunnel(tile
)) {
2017 uint16 spd
= GetBridgeSpec(GetBridgeType(tile
))->speed
;
2018 if (rtids
.HasRoad() && (td
->road_speed
== 0 || spd
< td
->road_speed
)) td
->road_speed
= spd
;
2019 if (rtids
.HasTram() && (td
->tram_speed
== 0 || spd
< td
->tram_speed
)) td
->tram_speed
= spd
;
2024 static void TileLoop_TunnelBridge(TileIndex tile
)
2026 bool snow_or_desert
= HasTunnelBridgeSnowOrDesert(tile
);
2027 switch (_settings_game
.game_creation
.landscape
) {
2029 /* As long as we do not have a snow density, we want to use the density
2030 * from the entry edge. */
2031 int z
= GetTileMaxZ(tile
);
2032 if (snow_or_desert
!= (z
> GetSnowLine())) {
2033 SetTunnelBridgeSnowOrDesert(tile
, !snow_or_desert
);
2034 MarkTileDirtyByTile(tile
);
2040 if (GetTropicZone(tile
) == TROPICZONE_DESERT
&& !snow_or_desert
) {
2041 SetTunnelBridgeSnowOrDesert(tile
, true);
2042 MarkTileDirtyByTile(tile
);
2051 static bool ClickTile_TunnelBridge(TileIndex tile
)
2053 /* Show vehicles found in tunnel. */
2054 if (IsTunnelTile(tile
)) {
2057 TileIndex tile_end
= GetOtherTunnelBridgeEnd(tile
);
2059 if (!t
->IsFrontEngine()) continue;
2060 if (tile
== t
->tile
|| tile_end
== t
->tile
) {
2061 ShowVehicleViewWindow(t
);
2064 if (count
> 19) break; // no more than 20 windows open
2066 if (count
> 0) return true;
2071 extern const TrackBits _road_trackbits
[16];
2073 static TrackStatus
GetTileTrackStatus_TunnelBridge(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
2075 const TransportType transport_type
= GetTunnelBridgeTransportType(tile
);
2077 if (transport_type
!= mode
|| (transport_type
== TRANSPORT_ROAD
&& !HasTileRoadType(tile
, RoadType(sub_mode
)))) return 0;
2079 const DiagDirection diag_direction
= GetTunnelBridgeDirection(tile
);
2081 if (mode
== TRANSPORT_ROAD
&& IsRoadCustomBridgeHeadTile(tile
)) {
2082 if (side
!= INVALID_DIAGDIR
&& side
== diag_direction
) return 0;
2083 TrackBits bits
= TRACK_BIT_NONE
;
2084 if (sub_mode
& ROADTYPES_TRAM
) bits
|= _road_trackbits
[GetCustomBridgeHeadRoadBits(tile
, ROADTYPE_TRAM
)];
2085 if (sub_mode
& ROADTYPES_ROAD
) bits
|= _road_trackbits
[GetCustomBridgeHeadRoadBits(tile
, ROADTYPE_ROAD
)];
2086 return CombineTrackStatus(TrackBitsToTrackdirBits(bits
), TRACKDIR_BIT_NONE
);
2089 if (side
!= INVALID_DIAGDIR
&& side
!= ReverseDiagDir(diag_direction
)) return 0;
2091 return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(diag_direction
)), TRACKDIR_BIT_NONE
);
2094 static void UpdateRoadTunnelBridgeInfrastructure(TileIndex begin
, TileIndex end
, bool add
) {
2095 /* A full diagonal road has two road bits. */
2096 const uint middle_len
= 2 * GetTunnelBridgeLength(begin
, end
) * TUNNELBRIDGE_TRACKBIT_FACTOR
;
2097 const uint len
= middle_len
+ (4 * TUNNELBRIDGE_TRACKBIT_FACTOR
);
2099 /* Iterate all present road types as each can have a different owner. */
2100 RoadTypeIdentifiers rtids
= RoadTypeIdentifiers::FromTile(begin
);
2101 RoadTypeIdentifier rtid
;
2102 FOR_EACH_SET_ROADTYPEIDENTIFIER(rtid
, rtids
) {
2103 Company
* const c
= Company::GetIfValid(GetRoadOwner(begin
, rtid
.basetype
));
2106 if (IsBridge(begin
)) {
2107 const RoadBits bits
= GetCustomBridgeHeadRoadBits(begin
, rtid
.basetype
);
2108 infra
+= CountBits(bits
) * TUNNELBRIDGE_TRACKBIT_FACTOR
;
2109 if (bits
& DiagDirToRoadBits(GetTunnelBridgeDirection(begin
))) {
2110 infra
+= middle_len
;
2116 c
->infrastructure
.road
[rtid
.basetype
][rtid
.subtype
] += infra
;
2118 c
->infrastructure
.road
[rtid
.basetype
][rtid
.subtype
] -= infra
;
2122 rtids
= RoadTypeIdentifiers::FromTile(end
);
2123 FOR_EACH_SET_ROADTYPEIDENTIFIER(rtid
, rtids
) {
2124 Company
* const c
= Company::GetIfValid(GetRoadOwner(end
, rtid
.basetype
));
2127 if (IsBridge(end
)) {
2128 const RoadBits bits
= GetCustomBridgeHeadRoadBits(end
, rtid
.basetype
);
2129 infra
+= CountBits(bits
) * TUNNELBRIDGE_TRACKBIT_FACTOR
;
2132 c
->infrastructure
.road
[rtid
.basetype
][rtid
.subtype
] += infra
;
2134 c
->infrastructure
.road
[rtid
.basetype
][rtid
.subtype
] -= infra
;
2140 void AddRoadTunnelBridgeInfrastructure(TileIndex begin
, TileIndex end
) {
2141 UpdateRoadTunnelBridgeInfrastructure(begin
, end
, true);
2144 void SubtractRoadTunnelBridgeInfrastructure(TileIndex begin
, TileIndex end
) {
2145 UpdateRoadTunnelBridgeInfrastructure(begin
, end
, false);
2148 static void ChangeTileOwner_TunnelBridge(TileIndex tile
, Owner old_owner
, Owner new_owner
)
2150 const TileIndex other_end
= GetOtherTunnelBridgeEnd(tile
);
2151 /* Set number of pieces to zero if it's the southern tile as we
2152 * don't want to update the infrastructure counts twice. */
2153 const uint num_pieces
= tile
< other_end
? (GetTunnelBridgeLength(tile
, other_end
) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR
: 0;
2154 const TransportType tt
= GetTunnelBridgeTransportType(tile
);
2156 if (tt
== TRANSPORT_ROAD
) SubtractRoadTunnelBridgeInfrastructure(tile
, other_end
);
2158 RoadTypeIdentifiers rtids
= RoadTypeIdentifiers::FromTile(tile
);
2159 for (RoadType rt
= ROADTYPE_ROAD
; rt
< ROADTYPE_END
; rt
++) {
2160 /* Update all roadtypes, no matter if they are present */
2161 if (GetRoadOwner(tile
, rt
) == old_owner
) {
2162 SetRoadOwner(tile
, rt
, new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
);
2166 if (tt
== TRANSPORT_ROAD
) AddRoadTunnelBridgeInfrastructure(tile
, other_end
);
2168 if (!IsTileOwner(tile
, old_owner
)) return;
2170 /* Update company infrastructure counts for rail and water as well.
2171 * No need to dirty windows here, we'll redraw the whole screen anyway. */
2172 Company
*old
= Company::Get(old_owner
);
2173 if (tt
== TRANSPORT_RAIL
) {
2174 old
->infrastructure
.rail
[GetRailType(tile
)] -= num_pieces
;
2175 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.rail
[GetRailType(tile
)] += num_pieces
;
2176 } else if (tt
== TRANSPORT_WATER
) {
2177 old
->infrastructure
.water
-= num_pieces
;
2178 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.water
+= num_pieces
;
2181 if (IsTunnelBridgeWithSignalSimulation(tile
) && IsTunnelBridgeSignalSimulationEntrance(tile
)) {
2182 uint num_sigs
= GetTunnelBridgeSignalSimulationSignalCount(tile
, other_end
);
2183 Company::Get(old_owner
)->infrastructure
.signal
-= num_sigs
;
2184 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.signal
+= num_sigs
;
2187 if (new_owner
!= INVALID_OWNER
) {
2188 SetTileOwner(tile
, new_owner
);
2190 if (tt
== TRANSPORT_RAIL
) {
2191 /* Since all of our vehicles have been removed, it is safe to remove the rail
2192 * bridge / tunnel. */
2193 CommandCost ret
= DoCommand(tile
, 0, 0, DC_EXEC
| DC_BANKRUPT
, CMD_LANDSCAPE_CLEAR
);
2194 assert(ret
.Succeeded());
2196 /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
2197 SetTileOwner(tile
, OWNER_NONE
);
2203 * Frame when the 'enter tunnel' sound should be played. This is the second
2204 * frame on a tile, so the sound is played shortly after entering the tunnel
2205 * tile, while the vehicle is still visible.
2207 static const byte TUNNEL_SOUND_FRAME
= 1;
2210 * Frame when a vehicle should be hidden in a tunnel with a certain direction.
2211 * This differs per direction, because of visibility / bounding box issues.
2212 * Note that direction, in this case, is the direction leading into the tunnel.
2213 * When entering a tunnel, hide the vehicle when it reaches the given frame.
2214 * When leaving a tunnel, show the vehicle when it is one frame further
2215 * to the 'outside', i.e. at (TILE_SIZE-1) - (frame) + 1
2217 extern const byte _tunnel_visibility_frame
[DIAGDIR_END
] = {12, 8, 8, 12};
2219 extern const byte _tunnel_turnaround_pre_visibility_frame
[DIAGDIR_END
] = { 31, 27, 27, 31 };
2221 static VehicleEnterTileStatus
VehicleEnter_TunnelBridge(Vehicle
*v
, TileIndex tile
, int x
, int y
)
2223 int z
= GetSlopePixelZ(x
, y
) - v
->z_pos
;
2225 if (abs(z
) > 2) return VETSB_CANNOT_ENTER
;
2226 /* Direction into the wormhole */
2227 const DiagDirection dir
= GetTunnelBridgeDirection(tile
);
2228 /* Direction of the vehicle */
2229 const DiagDirection vdir
= DirToDiagDir(v
->direction
);
2230 /* New position of the vehicle on the tile */
2231 byte pos
= (DiagDirToAxis(vdir
) == AXIS_X
? x
: y
) & TILE_UNIT_MASK
;
2232 /* Number of units moved by the vehicle since entering the tile */
2233 byte frame
= (vdir
== DIAGDIR_NE
|| vdir
== DIAGDIR_NW
) ? TILE_SIZE
- 1 - pos
: pos
;
2235 if (IsTunnel(tile
)) {
2236 if (v
->type
== VEH_TRAIN
) {
2237 Train
*t
= Train::From(v
);
2239 if (t
->track
!= TRACK_BIT_WORMHOLE
&& dir
== vdir
) {
2240 if (t
->IsFrontEngine() && frame
== TUNNEL_SOUND_FRAME
) {
2241 if (!PlayVehicleSound(t
, VSE_TUNNEL
) && RailVehInfo(t
->engine_type
)->engclass
== 0) {
2242 SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL
, v
);
2244 return VETSB_CONTINUE
;
2246 if (frame
== _tunnel_visibility_frame
[dir
]) {
2248 t
->track
= TRACK_BIT_WORMHOLE
;
2249 if (Tunnel::GetByTile(tile
)->is_chunnel
) SetBit(t
->gv_flags
, GVF_CHUNNEL_BIT
);
2250 t
->vehstatus
|= VS_HIDDEN
;
2251 return VETSB_ENTERED_WORMHOLE
;
2255 if (dir
== ReverseDiagDir(vdir
) && frame
== TILE_SIZE
- _tunnel_visibility_frame
[dir
] && z
== 0) {
2256 /* We're at the tunnel exit ?? */
2257 if (t
->tile
!= tile
&& GetOtherTunnelEnd(t
->tile
) != tile
) return VETSB_CONTINUE
; // In chunnel
2259 t
->track
= DiagDirToDiagTrackBits(vdir
);
2261 t
->vehstatus
&= ~VS_HIDDEN
;
2262 return VETSB_ENTERED_WORMHOLE
;
2264 } else if (v
->type
== VEH_ROAD
) {
2265 RoadVehicle
*rv
= RoadVehicle::From(v
);
2268 if (rv
->state
!= RVSB_WORMHOLE
&& dir
== vdir
) {
2269 if (frame
== _tunnel_visibility_frame
[dir
]) {
2270 /* Frame should be equal to the next frame number in the RV's movement */
2271 assert_msg(frame
== rv
->frame
+ 1 || rv
->frame
== _tunnel_turnaround_pre_visibility_frame
[dir
],
2272 +"frame: %u, rv->frame: %u, dir: %u, _tunnel_turnaround_pre_visibility_frame[dir]: %u", frame
, rv
->frame
, dir
, _tunnel_turnaround_pre_visibility_frame
[dir
]);
2274 rv
->state
= RVSB_WORMHOLE
;
2275 if (Tunnel::GetByTile(tile
)->is_chunnel
) SetBit(rv
->gv_flags
, GVF_CHUNNEL_BIT
);
2276 rv
->vehstatus
|= VS_HIDDEN
;
2277 return VETSB_ENTERED_WORMHOLE
;
2279 return VETSB_CONTINUE
;
2283 /* We're at the tunnel exit ?? */
2284 if (dir
== ReverseDiagDir(vdir
) && frame
== TILE_SIZE
- _tunnel_visibility_frame
[dir
] && z
== 0) {
2285 if (rv
->tile
!= tile
&& GetOtherTunnelEnd(rv
->tile
) != tile
) return VETSB_CONTINUE
; // In chunnel
2287 rv
->state
= DiagDirToDiagTrackdir(vdir
);
2289 rv
->vehstatus
&= ~VS_HIDDEN
;
2290 return VETSB_ENTERED_WORMHOLE
;
2293 } else { // IsBridge(tile)
2294 if (v
->vehstatus
& VS_HIDDEN
) return VETSB_CONTINUE
; // Building bridges between chunnel portals allowed.
2295 if (v
->type
!= VEH_SHIP
) {
2296 /* modify speed of vehicle */
2297 uint16 spd
= GetBridgeSpec(GetBridgeType(tile
))->speed
;
2299 if (v
->type
== VEH_ROAD
) spd
*= 2;
2300 Vehicle
*first
= v
->First();
2301 first
->cur_speed
= min(first
->cur_speed
, spd
);
2305 /* Vehicle enters bridge at the last frame inside this tile. */
2306 if (frame
!= TILE_SIZE
- 1) return VETSB_CONTINUE
;
2309 Train
*t
= Train::From(v
);
2310 t
->track
= TRACK_BIT_WORMHOLE
;
2311 ClrBit(t
->gv_flags
, GVF_GOINGUP_BIT
);
2312 ClrBit(t
->gv_flags
, GVF_GOINGDOWN_BIT
);
2317 RoadVehicle
*rv
= RoadVehicle::From(v
);
2318 if (IsRoadCustomBridgeHeadTile(tile
)) {
2319 RoadBits bits
= ROAD_NONE
;
2320 if (rv
->compatible_subtypes
& ROADTYPES_TRAM
) bits
|= GetCustomBridgeHeadRoadBits(tile
, ROADTYPE_TRAM
);
2321 if (rv
->compatible_subtypes
& ROADTYPES_ROAD
) bits
|= GetCustomBridgeHeadRoadBits(tile
, ROADTYPE_ROAD
);
2322 if (!(bits
& DiagDirToRoadBits(GetTunnelBridgeDirection(tile
)))) return VETSB_CONTINUE
;
2324 rv
->state
= RVSB_WORMHOLE
;
2325 /* There are no slopes inside bridges / tunnels. */
2326 ClrBit(rv
->gv_flags
, GVF_GOINGUP_BIT
);
2327 ClrBit(rv
->gv_flags
, GVF_GOINGDOWN_BIT
);
2332 Ship::From(v
)->state
= TRACK_BIT_WORMHOLE
;
2335 default: NOT_REACHED();
2337 return VETSB_ENTERED_WORMHOLE
;
2338 } else if (vdir
== ReverseDiagDir(dir
)) {
2342 Train
*t
= Train::From(v
);
2343 if (t
->track
== TRACK_BIT_WORMHOLE
) {
2344 t
->track
= DiagDirToDiagTrackBits(vdir
);
2345 return VETSB_ENTERED_WORMHOLE
;
2351 RoadVehicle
*rv
= RoadVehicle::From(v
);
2352 if (rv
->state
== RVSB_WORMHOLE
) {
2353 rv
->state
= DiagDirToDiagTrackdir(vdir
);
2355 return VETSB_ENTERED_WORMHOLE
;
2361 Ship
*ship
= Ship::From(v
);
2362 if (ship
->state
== TRACK_BIT_WORMHOLE
) {
2363 ship
->state
= DiagDirToDiagTrackBits(vdir
);
2364 return VETSB_ENTERED_WORMHOLE
;
2369 default: NOT_REACHED();
2373 return VETSB_CONTINUE
;
2376 static CommandCost
TerraformTile_TunnelBridge(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
2378 if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled() && IsBridge(tile
) && GetTunnelBridgeTransportType(tile
) != TRANSPORT_WATER
) {
2379 DiagDirection direction
= GetTunnelBridgeDirection(tile
);
2380 Axis axis
= DiagDirToAxis(direction
);
2383 Slope tileh_old
= GetTileSlope(tile
, &z_old
);
2385 if (IsRoadCustomBridgeHeadTile(tile
)) {
2386 const RoadBits pieces
= GetCustomBridgeHeadAllRoadBits(tile
);
2387 const RoadBits entrance_piece
= DiagDirToRoadBits(direction
);
2389 /* Steep slopes behave the same as slopes with one corner raised. */
2390 const Slope normalised_tileh_new
= IsSteepSlope(tileh_new
) ? SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh_new
)) : tileh_new
;
2392 if ((_invalid_tileh_slopes_road
[0][normalised_tileh_new
& SLOPE_ELEVATED
] & (pieces
& ~entrance_piece
)) != ROAD_NONE
) {
2393 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2397 /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
2398 if ((direction
== DIAGDIR_NW
) || (direction
== DIAGDIR_NE
)) {
2399 CheckBridgeSlopeSouth(axis
, &tileh_old
, &z_old
);
2400 res
= CheckBridgeSlopeSouth(axis
, &tileh_new
, &z_new
);
2402 CheckBridgeSlopeNorth(axis
, &tileh_old
, &z_old
);
2403 res
= CheckBridgeSlopeNorth(axis
, &tileh_new
, &z_new
);
2406 /* Surface slope is valid and remains unchanged? */
2407 if (res
.Succeeded() && (z_old
== z_new
) && (tileh_old
== tileh_new
)) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
2410 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2413 extern const TileTypeProcs _tile_type_tunnelbridge_procs
= {
2414 DrawTile_TunnelBridge
, // draw_tile_proc
2415 GetSlopePixelZ_TunnelBridge
, // get_slope_z_proc
2416 ClearTile_TunnelBridge
, // clear_tile_proc
2417 nullptr, // add_accepted_cargo_proc
2418 GetTileDesc_TunnelBridge
, // get_tile_desc_proc
2419 GetTileTrackStatus_TunnelBridge
, // get_tile_track_status_proc
2420 ClickTile_TunnelBridge
, // click_tile_proc
2421 nullptr, // animate_tile_proc
2422 TileLoop_TunnelBridge
, // tile_loop_proc
2423 ChangeTileOwner_TunnelBridge
, // change_tile_owner_proc
2424 nullptr, // add_produced_cargo_proc
2425 VehicleEnter_TunnelBridge
, // vehicle_enter_tile_proc
2426 GetFoundation_TunnelBridge
, // get_foundation_proc
2427 TerraformTile_TunnelBridge
, // terraform_tile_proc