Chunnel: Add setting to enable construction, default on.
[openttd-joker.git] / src / tunnelbridge_cmd.cpp
bloba2bbd56295a0e5b78f1d92a1f0b55eff6e2d23de
1 /* $Id$ */
3 /*
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/>.
8 */
10 /**
11 * @file tunnelbridge_cmd.cpp
12 * This file deals with tunnels and bridges (non-gui stuff)
13 * @todo separate this file into two
16 #include "stdafx.h"
17 #include "newgrf_object.h"
18 #include "viewport_func.h"
19 #include "cmd_helper.h"
20 #include "command_func.h"
21 #include "town.h"
22 #include "train.h"
23 #include "ship.h"
24 #include "roadveh.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"
40 #include "pbs.h"
41 #include "company_base.h"
42 #include "newgrf_railtype.h"
43 #include "object_base.h"
44 #include "water.h"
45 #include "company_gui.h"
46 #include "viewport_func.h"
47 #include "station_map.h"
48 #include "industry_map.h"
50 #include "table/strings.h"
51 #include "table/bridge_land.h"
53 #include "safeguards.h"
55 BridgeSpec _bridge[MAX_BRIDGES]; ///< The specification of all bridges.
56 TileIndex _build_tunnel_endtile; ///< The end of a tunnel; as hidden return from the tunnel build command for GUI purposes.
58 /** Z position of the bridge sprites relative to bridge height (downwards) */
59 static const int BRIDGE_Z_START = 3;
61 extern void DrawRoadBits(TileInfo *ti);
62 extern const RoadBits _invalid_tileh_slopes_road[2][15];
65 /**
66 * Mark bridge tiles dirty.
67 * Note: The bridge does not need to exist, everything is passed via parameters.
68 * @param begin Start tile.
69 * @param end End tile.
70 * @param direction Direction from \a begin to \a end.
71 * @param bridge_height Bridge height level.
73 void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height, const ZoomLevel mark_dirty_if_zoomlevel_is_below)
75 TileIndexDiff delta = TileOffsByDiagDir(direction);
76 for (TileIndex t = begin; t != end; t += delta) {
77 MarkTileDirtyByTile(t, mark_dirty_if_zoomlevel_is_below, bridge_height - TileHeight(t));
79 MarkTileDirtyByTile(end, mark_dirty_if_zoomlevel_is_below);
82 /**
83 * Mark bridge tiles dirty.
84 * @param tile Bridge head.
86 void MarkBridgeDirty(TileIndex tile, const ZoomLevel mark_dirty_if_zoomlevel_is_below)
88 MarkBridgeDirty(tile, GetOtherTunnelBridgeEnd(tile), GetTunnelBridgeDirection(tile), GetBridgeHeight(tile), mark_dirty_if_zoomlevel_is_below);
91 /**
92 * Mark bridge or tunnel tiles dirty.
93 * @param tile Bridge head or tunnel entrance.
95 void MarkBridgeOrTunnelDirty(TileIndex tile, const ZoomLevel mark_dirty_if_zoomlevel_is_below)
97 if (IsBridge(tile)) {
98 MarkBridgeDirty(tile, mark_dirty_if_zoomlevel_is_below);
99 } else {
100 MarkTileDirtyByTile(tile);
101 MarkTileDirtyByTile(GetOtherTunnelBridgeEnd(tile));
106 * Get number of signals on bridge or tunnel with signal simulation.
107 * @param length Length of bridge/tunnel middle
108 * @return Number of signals on signalled bridge/tunnel of this length
110 uint GetTunnelBridgeSignalSimulationSignalCount(uint length)
112 return 2 + (length / _settings_game.construction.simulated_wormhole_signals);
115 /** Reset the data been eventually changed by the grf loaded. */
116 void ResetBridges()
118 /* First, free sprite table data */
119 for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
120 if (_bridge[i].sprite_table != NULL) {
121 for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
122 free(_bridge[i].sprite_table);
126 /* Then, wipe out current bridges */
127 memset(&_bridge, 0, sizeof(_bridge));
128 /* And finally, reinstall default data */
129 memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
133 * Calculate the price factor for building a long bridge.
134 * 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,
135 * @param length Length of the bridge.
136 * @return Price factor for the bridge.
138 int CalcBridgeLenCostFactor(int length)
140 if (length < 2) return length;
142 length -= 2;
143 int sum = 2;
144 for (int delta = 1;; delta++) {
145 for (int count = 0; count < delta; count++) {
146 if (length == 0) return sum;
147 sum += delta;
148 length--;
154 * Get the foundation for a bridge.
155 * @param tileh The slope to build the bridge on.
156 * @param axis The axis of the bridge entrance.
157 * @return The foundation required.
159 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
161 if (tileh == SLOPE_FLAT ||
162 ((tileh == SLOPE_NE || tileh == SLOPE_SW) && axis == AXIS_X) ||
163 ((tileh == SLOPE_NW || tileh == SLOPE_SE) && axis == AXIS_Y)) return FOUNDATION_NONE;
165 return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
169 * Determines if the track on a bridge ramp is flat or goes up/down.
171 * @param tileh Slope of the tile under the bridge head
172 * @param axis Orientation of bridge
173 * @return true iff the track is flat.
175 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
177 ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
178 /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
179 return (tileh != SLOPE_FLAT);
182 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
184 const BridgeSpec *bridge = GetBridgeSpec(index);
185 assert(table < BRIDGE_PIECE_INVALID);
186 if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
187 return _bridge_sprite_table[index][table];
188 } else {
189 return bridge->sprite_table[table];
195 * Determines the foundation for the north bridge head, and tests if the resulting slope is valid.
197 * @param axis Axis of the bridge
198 * @param tileh Slope of the tile under the north bridge head; returns slope on top of foundation
199 * @param z TileZ corresponding to tileh, gets modified as well
200 * @return Error or cost for bridge foundation
202 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, int *z)
204 Foundation f = GetBridgeFoundation(*tileh, axis);
205 *z += ApplyFoundationToSlope(f, tileh);
207 Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
208 if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
210 if (f == FOUNDATION_NONE) return CommandCost();
212 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
216 * Determines the foundation for the south bridge head, and tests if the resulting slope is valid.
218 * @param axis Axis of the bridge
219 * @param tileh Slope of the tile under the south bridge head; returns slope on top of foundation
220 * @param z TileZ corresponding to tileh, gets modified as well
221 * @return Error or cost for bridge foundation
223 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, int *z)
225 Foundation f = GetBridgeFoundation(*tileh, axis);
226 *z += ApplyFoundationToSlope(f, tileh);
228 Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
229 if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
231 if (f == FOUNDATION_NONE) return CommandCost();
233 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
237 * Is a bridge of the specified type and length available?
238 * @param bridge_type Wanted type of bridge.
239 * @param bridge_len Wanted length of the bridge.
240 * @return A succeeded (the requested bridge is available) or failed (it cannot be built) command.
242 CommandCost CheckBridgeAvailability(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
244 if (flags & DC_QUERY_COST) {
245 if (bridge_len <= _settings_game.construction.max_bridge_length) return CommandCost();
246 return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
249 if (bridge_type >= MAX_BRIDGES) return CMD_ERROR;
251 const BridgeSpec *b = GetBridgeSpec(bridge_type);
252 if (b->avail_year > _cur_year) return CMD_ERROR;
254 uint max = min(b->max_length, _settings_game.construction.max_bridge_length);
256 if (b->min_length > bridge_len) return CMD_ERROR;
257 if (bridge_len <= max) return CommandCost();
258 return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
262 * Build a Bridge
263 * @param end_tile end tile
264 * @param flags type of operation
265 * @param p1 packed start tile coords (~ dx)
266 * @param p2 various bitstuffed elements
267 * - p2 = (bit 0- 7) - bridge type (hi bh)
268 * - p2 = (bit 8-12) - rail type or road types.
269 * - p2 = (bit 15-16) - transport type.
270 * @param text unused
271 * @return the cost of this operation or an error
273 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
275 CompanyID company = _current_company;
277 RailType railtype = INVALID_RAILTYPE;
278 RoadTypes roadtypes = ROADTYPES_NONE;
280 /* unpack parameters */
281 BridgeType bridge_type = GB(p2, 0, 8);
283 if (!IsValidTile(p1)) return_cmd_error(STR_ERROR_BRIDGE_THROUGH_MAP_BORDER);
285 TransportType transport_type = Extract<TransportType, 15, 2>(p2);
287 /* type of bridge */
288 switch (transport_type) {
289 case TRANSPORT_ROAD:
290 roadtypes = Extract<RoadTypes, 8, 2>(p2);
291 if (!HasExactlyOneBit(roadtypes) || !HasRoadTypesAvail(company, roadtypes)) return CMD_ERROR;
292 break;
294 case TRANSPORT_RAIL:
295 railtype = Extract<RailType, 8, 5>(p2);
296 if (!ValParamRailtype(railtype)) return CMD_ERROR;
297 break;
299 case TRANSPORT_WATER:
300 break;
302 default:
303 /* Airports don't have bridges. */
304 return CMD_ERROR;
306 TileIndex tile_start = p1;
307 TileIndex tile_end = end_tile;
309 if (company == OWNER_DEITY) {
310 if (transport_type != TRANSPORT_ROAD) return CMD_ERROR;
311 const Town *town = CalcClosestTownFromTile(tile_start);
313 company = OWNER_TOWN;
315 /* If we are not within a town, we are not owned by the town */
316 if (town == NULL || DistanceSquare(tile_start, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
317 company = OWNER_NONE;
321 if (tile_start == tile_end) {
322 return_cmd_error(STR_ERROR_CAN_T_START_AND_END_ON);
325 Axis direction;
326 if (TileX(tile_start) == TileX(tile_end)) {
327 direction = AXIS_Y;
328 } else if (TileY(tile_start) == TileY(tile_end)) {
329 direction = AXIS_X;
330 } else {
331 return_cmd_error(STR_ERROR_START_AND_END_MUST_BE_IN);
334 if (tile_end < tile_start) Swap(tile_start, tile_end);
336 uint bridge_len = GetTunnelBridgeLength(tile_start, tile_end);
337 if (transport_type != TRANSPORT_WATER) {
338 /* set and test bridge length, availability */
339 CommandCost ret = CheckBridgeAvailability(bridge_type, bridge_len, flags);
340 if (ret.Failed()) return ret;
341 } else {
342 if (bridge_len > _settings_game.construction.max_bridge_length) return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
345 int z_start;
346 int z_end;
347 Slope tileh_start = GetTileSlope(tile_start, &z_start);
348 Slope tileh_end = GetTileSlope(tile_end, &z_end);
349 bool pbs_reservation = false;
351 CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
352 CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end, &z_end);
354 /* Aqueducts can't be built of flat land. */
355 if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
356 if (z_start != z_end) return_cmd_error(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT);
358 CommandCost cost(EXPENSES_CONSTRUCTION);
359 Owner owner;
360 bool is_new_owner;
361 if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
362 GetOtherBridgeEnd(tile_start) == tile_end &&
363 GetTunnelBridgeTransportType(tile_start) == transport_type) {
364 /* Replace a current bridge. */
366 /* If this is a railway bridge, make sure the railtypes match. */
367 if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
368 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
371 /* Do not replace town bridges with lower speed bridges, unless in scenario editor. */
372 if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
373 GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed &&
374 _game_mode != GM_EDITOR) {
375 Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
377 if (t == NULL) {
378 return CMD_ERROR;
379 } else {
380 SetDParam(0, t->index);
381 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
385 /* Do not replace the bridge with the same bridge type. */
386 if (!(flags & DC_QUERY_COST) && (bridge_type == GetBridgeType(tile_start)) && (transport_type != TRANSPORT_ROAD || (roadtypes & ~GetRoadTypes(tile_start)) == 0)) {
387 return_cmd_error(STR_ERROR_ALREADY_BUILT);
390 /* Do not allow replacing another company's bridges. */
391 if (!IsTileOwner(tile_start, company) && !IsTileOwner(tile_start, OWNER_TOWN) && !IsTileOwner(tile_start, OWNER_NONE)) {
392 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
395 cost.AddCost((bridge_len + 1) * _price[PR_CLEAR_BRIDGE]); // The cost of clearing the current bridge.
396 owner = GetTileOwner(tile_start);
398 /* If bridge belonged to bankrupt company, it has a new owner now */
399 is_new_owner = (owner == OWNER_NONE);
400 if (is_new_owner) owner = company;
402 switch (transport_type) {
403 case TRANSPORT_RAIL:
404 /* Keep the reservation, the path stays valid. */
405 pbs_reservation = HasTunnelBridgeReservation(tile_start);
406 break;
408 case TRANSPORT_ROAD:
409 /* Do not remove road types when upgrading a bridge */
410 roadtypes |= GetRoadTypes(tile_start);
411 break;
413 default: break;
415 } else {
416 /* Build a new bridge. */
418 bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
420 /* Try and clear the start landscape */
421 CommandCost ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
422 if (ret.Failed()) return ret;
423 cost = ret;
425 if (terraform_cost_north.Failed() || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
426 cost.AddCost(terraform_cost_north);
428 /* Try and clear the end landscape */
429 ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
430 if (ret.Failed()) return ret;
431 cost.AddCost(ret);
433 /* false - end tile slope check */
434 if (terraform_cost_south.Failed() || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
435 cost.AddCost(terraform_cost_south);
437 const TileIndex heads[] = {tile_start, tile_end};
438 for (int i = 0; i < 2; i++) {
439 if (IsBridgeAbove(heads[i])) {
440 TileIndex north_head = GetNorthernBridgeEnd(heads[i]);
442 if (direction == GetBridgeAxis(heads[i])) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
444 if (z_start + 1 == GetBridgeHeight(north_head)) {
445 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
450 TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
451 for (TileIndex tile = tile_start + delta; tile != tile_end; tile += delta) {
452 if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN);
454 if (z_start >= (GetTileZ(tile) + _settings_game.construction.max_bridge_height)) {
456 * Disallow too high bridges.
457 * Properly rendering a map where very high bridges (might) exist is expensive.
458 * See http://www.tt-forums.net/viewtopic.php?f=33&t=40844&start=980#p1131762
459 * for a detailed discussion. z_start here is one heightlevel below the bridge level.
461 return_cmd_error(STR_ERROR_BRIDGE_TOO_HIGH_FOR_TERRAIN);
464 if (IsBridgeAbove(tile)) {
465 /* Disallow crossing bridges for the time being */
466 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
469 switch (GetTileType(tile)) {
470 case MP_WATER:
471 if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
472 break;
474 case MP_RAILWAY:
475 if (!IsPlainRail(tile)) goto not_valid_below;
476 break;
478 case MP_ROAD:
479 if (IsRoadDepot(tile)) goto not_valid_below;
480 break;
482 case MP_TUNNELBRIDGE:
483 if (IsTunnel(tile)) break;
484 if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
485 if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
486 break;
488 case MP_OBJECT: {
489 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
490 if ((spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) == 0) goto not_valid_below;
491 if (GetTileMaxZ(tile) + spec->height > z_start) goto not_valid_below;
492 break;
495 case MP_CLEAR:
496 break;
498 default:
499 not_valid_below:;
500 /* try and clear the middle landscape */
501 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
502 if (ret.Failed()) return ret;
503 cost.AddCost(ret);
504 break;
507 if (flags & DC_EXEC) {
508 /* We do this here because when replacing a bridge with another
509 * type calling SetBridgeMiddle isn't needed. After all, the
510 * tile already has the has_bridge_above bits set. */
511 SetBridgeMiddle(tile, direction);
515 owner = company;
516 is_new_owner = true;
519 /* do the drill? */
520 if (flags & DC_EXEC) {
521 DiagDirection dir = AxisToDiagDir(direction);
523 Company *c = Company::GetIfValid(company);
524 switch (transport_type) {
525 case TRANSPORT_RAIL:
526 /* Add to company infrastructure count if required. */
527 if (is_new_owner && c != NULL) c->infrastructure.rail[railtype] += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
528 MakeRailBridgeRamp(tile_start, owner, bridge_type, dir, railtype);
529 MakeRailBridgeRamp(tile_end, owner, bridge_type, ReverseDiagDir(dir), railtype);
530 SetTunnelBridgeReservation(tile_start, pbs_reservation);
531 SetTunnelBridgeReservation(tile_end, pbs_reservation);
532 break;
534 case TRANSPORT_ROAD: {
535 RoadTypes prev_roadtypes = IsBridgeTile(tile_start) ? GetRoadTypes(tile_start) : ROADTYPES_NONE;
536 if (is_new_owner) {
537 /* Also give unowned present roadtypes to new owner */
538 if (HasBit(prev_roadtypes, ROADTYPE_ROAD) && GetRoadOwner(tile_start, ROADTYPE_ROAD) == OWNER_NONE) ClrBit(prev_roadtypes, ROADTYPE_ROAD);
539 if (HasBit(prev_roadtypes, ROADTYPE_TRAM) && GetRoadOwner(tile_start, ROADTYPE_TRAM) == OWNER_NONE) ClrBit(prev_roadtypes, ROADTYPE_TRAM);
541 if (c != NULL) {
542 /* Add all new road types to the company infrastructure counter. */
543 RoadType new_rt;
544 FOR_EACH_SET_ROADTYPE(new_rt, roadtypes ^ prev_roadtypes) {
545 /* A full diagonal road tile has two road bits. */
546 c->infrastructure.road[new_rt] += (bridge_len + 2) * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
549 Owner owner_road = HasBit(prev_roadtypes, ROADTYPE_ROAD) ? GetRoadOwner(tile_start, ROADTYPE_ROAD) : company;
550 Owner owner_tram = HasBit(prev_roadtypes, ROADTYPE_TRAM) ? GetRoadOwner(tile_start, ROADTYPE_TRAM) : company;
551 MakeRoadBridgeRamp(tile_start, owner, owner_road, owner_tram, bridge_type, dir, roadtypes);
552 MakeRoadBridgeRamp(tile_end, owner, owner_road, owner_tram, bridge_type, ReverseDiagDir(dir), roadtypes);
553 break;
556 case TRANSPORT_WATER:
557 if (is_new_owner && c != NULL) c->infrastructure.water += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
558 MakeAqueductBridgeRamp(tile_start, owner, dir);
559 MakeAqueductBridgeRamp(tile_end, owner, ReverseDiagDir(dir));
560 break;
562 default:
563 NOT_REACHED();
566 /* Mark all tiles dirty */
567 MarkBridgeDirty(tile_start, tile_end, AxisToDiagDir(direction), z_start);
568 DirtyCompanyInfrastructureWindows(company);
571 if ((flags & DC_EXEC) && transport_type == TRANSPORT_RAIL) {
572 Track track = AxisToTrack(direction);
573 AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, company);
574 YapfNotifyTrackLayoutChange(tile_start, track);
577 /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
578 * It's unnecessary to execute this command every time for every bridge. So it is done only
579 * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
581 Company *c = Company::GetIfValid(company);
582 if (!(flags & DC_QUERY_COST) || (c != NULL && c->is_ai)) {
583 bridge_len += 2; // begin and end tiles/ramps
585 switch (transport_type) {
586 case TRANSPORT_ROAD: cost.AddCost(bridge_len * _price[PR_BUILD_ROAD] * 2 * CountBits(roadtypes)); break;
587 case TRANSPORT_RAIL: cost.AddCost(bridge_len * RailBuildCost(railtype)); break;
588 default: break;
591 if (c != NULL) bridge_len = CalcBridgeLenCostFactor(bridge_len);
593 if (transport_type != TRANSPORT_WATER) {
594 cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
595 } else {
596 /* Aqueducts use a separate base cost. */
597 cost.AddCost((int64)bridge_len * _price[PR_BUILD_AQUEDUCT]);
602 return cost;
607 * Build Tunnel.
608 * @param start_tile start tile of tunnel
609 * @param flags type of operation
610 * @param p1 bit 0-4 railtype or roadtypes
611 * bit 8-9 transport type
612 * @param p2 unused
613 * @param text unused
614 * @return the cost of this operation or an error
616 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
618 CompanyID company = _current_company;
620 TransportType transport_type = Extract<TransportType, 8, 2>(p1);
622 RailType railtype = INVALID_RAILTYPE;
623 RoadTypes rts = ROADTYPES_NONE;
624 _build_tunnel_endtile = 0;
625 switch (transport_type) {
626 case TRANSPORT_RAIL:
627 railtype = Extract<RailType, 0, 5>(p1);
628 if (!ValParamRailtype(railtype)) return CMD_ERROR;
629 break;
631 case TRANSPORT_ROAD:
632 rts = Extract<RoadTypes, 0, 2>(p1);
633 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(company, rts)) return CMD_ERROR;
634 break;
636 default: return CMD_ERROR;
639 if (company == OWNER_DEITY) {
640 if (transport_type != TRANSPORT_ROAD) return CMD_ERROR;
641 const Town *town = CalcClosestTownFromTile(start_tile);
643 company = OWNER_TOWN;
645 /* If we are not within a town, we are not owned by the town */
646 if (town == NULL || DistanceSquare(start_tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
647 company = OWNER_NONE;
651 int start_z;
652 int end_z;
653 Slope start_tileh = GetTileSlope(start_tile, &start_z);
654 DiagDirection direction = GetInclinedSlopeDirection(start_tileh);
655 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
657 if (HasTileWaterGround(start_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
659 CommandCost ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
660 if (ret.Failed()) return ret;
662 /* XXX - do NOT change 'ret' in the loop, as it is used as the price
663 * for the clearing of the entrance of the tunnel. Assigning it to
664 * cost before the loop will yield different costs depending on start-
665 * position, because of increased-cost-by-length: 'cost += cost >> 3' */
667 TileIndexDiff delta = TileOffsByDiagDir(direction);
669 TileIndex end_tile = start_tile;
671 /* Tile shift coefficient. Will decrease for very long tunnels to avoid exponential growth of price*/
672 int tiles_coef = 3;
673 /* Number of tiles from start of tunnel */
674 int tiles = 0;
675 /* flag for chunnels. */
676 bool is_chunnel = false;
677 /* Number of chunnel head tiles. */
678 int head_tiles = 0;
679 /* Number of tiles at which the cost increase coefficient per tile is halved */
680 int tiles_bump = 25;
682 TileIndex found_tunnel_tile = INVALID_TILE;
684 CommandCost cost(EXPENSES_CONSTRUCTION);
685 Slope end_tileh;
687 for (;;) {
688 end_tile += delta;
689 if (!IsValidTile(end_tile)) return_cmd_error(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
690 end_tileh = GetTileSlope(end_tile, &end_z);
692 if (start_z == end_z) {
693 _build_tunnel_endtile = found_tunnel_tile != INVALID_TILE ? found_tunnel_tile : end_tile;
695 /* Test if we are on a shore. */
696 if (end_z == 0 && _settings_game.construction.chunnel &&
697 (IsCoastTile(end_tile) ||
698 (IsValidTile(end_tile + delta) && HasTileWaterGround(end_tile + delta)) ||
699 (IsValidTile(end_tile + delta * 2) && HasTileWaterGround(end_tile + delta * 2)))) {
700 if (!is_chunnel) {
701 /*We are about to pass water for the first time so check if not to close to other tunnel */
702 if (tiles + 1 < head_tiles + 4 && found_tunnel_tile != INVALID_TILE) return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY_FOR_CHUNNEL);
703 if (tiles + 1 < 4) return_cmd_error(STR_ERROR_TUNNEL_RAMP_TOO_SHORT);
705 } else {/* We are leaving.*/
706 if (is_chunnel) {
707 /* Check if there is enough ramp space to come up. */
708 if (head_tiles < 4 && found_tunnel_tile != INVALID_TILE) return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY_FOR_CHUNNEL);
709 if (head_tiles < 4) return_cmd_error(STR_ERROR_TUNNEL_RAMP_TOO_SHORT);
710 } else {
711 if (found_tunnel_tile != INVALID_TILE) return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
713 break;
716 /* A shore was found so pass the water and find a proper shore tile that potentially
717 * could have a tunnel portal behind. */
718 for (;;) {
719 if (!IsValidTile(end_tile)) return_cmd_error(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
721 end_tileh = GetTileSlope(end_tile);
722 if (direction == DIAGDIR_NE && (end_tileh & SLOPE_NE) == SLOPE_NE) break;
723 if (direction == DIAGDIR_SE && (end_tileh & SLOPE_SE) == SLOPE_SE) break;
724 if (direction == DIAGDIR_SW && (end_tileh & SLOPE_SW) == SLOPE_SW) break;
725 if (direction == DIAGDIR_NW && (end_tileh & SLOPE_NW) == SLOPE_NW) break;
727 /* No chunnels under oil rigs.*/
728 if ((IsTileType(end_tile, MP_STATION) && IsOilRig(end_tile)) ||
729 (IsTileType(end_tile, MP_INDUSTRY) &&
730 GetIndustryGfx(end_tile) >= GFX_OILRIG_1 &&
731 GetIndustryGfx(end_tile) <= GFX_OILRIG_5)) {
732 _build_tunnel_endtile = end_tile;
733 return_cmd_error(STR_ERROR_NO_DRILLING_ABOVE_CHUNNEL);
736 end_tile += delta;
737 tiles++;
740 /* The water was passed */
741 is_chunnel = true;
742 head_tiles = 0;
743 found_tunnel_tile = INVALID_TILE;
746 head_tiles++;
747 tiles++;
750 /* The cost of the digging. */
751 for (int i = tiles; i > 0; i--) {
752 if (tiles == tiles_bump) {
753 tiles_coef++;
754 tiles_bump *= 2;
757 cost.AddCost(_price[PR_BUILD_TUNNEL]);
758 cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
761 /* Add the cost of the entrance */
762 cost.AddCost(_price[PR_BUILD_TUNNEL]);
763 cost.AddCost(ret);
765 /* if the command fails from here on we want the end tile to be highlighted */
766 _build_tunnel_endtile = end_tile;
768 if (tiles > _settings_game.construction.max_tunnel_length) return_cmd_error(STR_ERROR_TUNNEL_TOO_LONG);
770 if (HasTileWaterGround(end_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
772 /* Clear the tile in any case */
773 ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
774 if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
775 cost.AddCost(ret);
777 /* slope of end tile must be complementary to the slope of the start tile */
778 if (end_tileh != ComplementSlope(start_tileh)) {
779 /* Mark the tile as already cleared for the terraform command.
780 * Do this for all tiles (like trees), not only objects. */
781 ClearedObjectArea *coa = FindClearedObject(end_tile);
782 if (coa == NULL) {
783 coa = _cleared_object_areas.Append();
784 coa->first_tile = end_tile;
785 coa->area = TileArea(end_tile, 1, 1);
788 /* Hide the tile from the terraforming command */
789 TileIndex old_first_tile = coa->first_tile;
790 coa->first_tile = INVALID_TILE;
791 ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
792 coa->first_tile = old_first_tile;
793 if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
794 cost.AddCost(ret);
796 cost.AddCost(_price[PR_BUILD_TUNNEL]);
798 /* Pay for the rail/road in the tunnel including entrances */
799 switch (transport_type) {
800 case TRANSPORT_ROAD: cost.AddCost((tiles + 2) * _price[PR_BUILD_ROAD] * 2); break;
801 case TRANSPORT_RAIL: cost.AddCost((tiles + 2) * RailBuildCost(railtype)); break;
802 default: NOT_REACHED();
805 if (flags & DC_EXEC) {
806 Company *c = Company::GetIfValid(company);
807 uint num_pieces = (tiles + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
809 /* The most northern tile first. */
810 TileIndex tn = start_tile;
811 TileIndex ts = end_tile;
812 if(start_tile > end_tile) Swap(tn, ts);
814 if (!Tunnel::CanAllocateItem()) return_cmd_error(STR_ERROR_TUNNEL_TOO_MANY);
815 const Tunnel *t = new Tunnel(tn, ts, is_chunnel);
817 if (transport_type == TRANSPORT_RAIL) {
818 if (!IsTunnelTile(start_tile) && c != NULL) c->infrastructure.rail[railtype] += num_pieces;
819 MakeRailTunnel(start_tile, company, t->index, direction, railtype);
820 MakeRailTunnel(end_tile, company, t->index, ReverseDiagDir(direction), railtype);
821 AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, company);
822 YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
823 } else {
824 if (c != NULL) {
825 RoadType rt;
826 FOR_EACH_SET_ROADTYPE(rt, rts ^ (IsTunnelTile(start_tile) ? GetRoadTypes(start_tile) : ROADTYPES_NONE)) {
827 c->infrastructure.road[rt] += num_pieces * 2; // A full diagonal road has two road bits.
830 MakeRoadTunnel(start_tile, company, t->index, direction, rts);
831 MakeRoadTunnel(end_tile, company, t->index, ReverseDiagDir(direction), rts);
833 DirtyCompanyInfrastructureWindows(company);
836 return cost;
841 * Are we allowed to remove the tunnel or bridge at \a tile?
842 * @param tile End point of the tunnel or bridge.
843 * @return A succeeded command if the tunnel or bridge may be removed, a failed command otherwise.
845 static inline CommandCost CheckAllowRemoveTunnelBridge(TileIndex tile)
847 /* Floods can remove anything as well as the scenario editor */
848 if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return CommandCost();
850 switch (GetTunnelBridgeTransportType(tile)) {
851 case TRANSPORT_ROAD: {
852 RoadTypes rts = GetRoadTypes(tile);
853 Owner road_owner = _current_company;
854 Owner tram_owner = _current_company;
856 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
857 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
859 /* We can remove unowned road and if the town allows it */
860 if (road_owner == OWNER_TOWN && _current_company != OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) {
861 /* Town does not allow */
862 return CheckTileOwnership(tile);
864 if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
865 if (tram_owner == OWNER_NONE) tram_owner = _current_company;
867 CommandCost ret = CheckOwnership(road_owner, tile);
868 if (ret.Succeeded()) ret = CheckOwnership(tram_owner, tile);
869 return ret;
872 case TRANSPORT_RAIL:
873 return CheckOwnership(GetTileOwner(tile));
875 case TRANSPORT_WATER: {
876 /* Always allow to remove aqueducts without owner. */
877 Owner aqueduct_owner = GetTileOwner(tile);
878 if (aqueduct_owner == OWNER_NONE) aqueduct_owner = _current_company;
879 return CheckOwnership(aqueduct_owner);
882 default: NOT_REACHED();
887 * Remove a tunnel from the game, update town rating, etc.
888 * @param tile Tile containing one of the endpoints of the tunnel.
889 * @param flags Command flags.
890 * @return Succeeded or failed command.
892 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
894 CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
895 if (ret.Failed()) return ret;
897 TileIndex endtile = GetOtherTunnelEnd(tile);
899 ret = TunnelBridgeIsFree(tile, endtile);
900 if (ret.Failed()) return ret;
902 _build_tunnel_endtile = endtile;
904 Town *t = NULL;
905 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
906 t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
908 /* Check if you are allowed to remove the tunnel owned by a town
909 * Removal depends on difficulty settings */
910 CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
911 if (ret.Failed()) return ret;
914 /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
915 * you have a "Poor" (0) town rating */
916 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
917 ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
920 uint len = GetTunnelBridgeLength(tile, endtile) + 2; // Don't forget the end tiles.
922 if (flags & DC_EXEC) {
923 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
924 /* We first need to request values before calling DoClearSquare */
925 DiagDirection dir = GetTunnelBridgeDirection(tile);
926 Track track = DiagDirToDiagTrack(dir);
927 Owner owner = GetTileOwner(tile);
929 Train *v = NULL;
930 if (HasTunnelBridgeReservation(tile)) {
931 v = GetTrainForReservation(tile, track);
932 if (v != NULL) FreeTrainTrackReservation(v);
935 if (Company::IsValidID(owner)) {
936 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
937 if (IsTunnelBridgeWithSignalSimulation(tile)) { // handle tunnel/bridge signals.
938 Company::Get(GetTileOwner(tile))->infrastructure.signal -= GetTunnelBridgeSignalSimulationSignalCount(tile, endtile);
940 DirtyCompanyInfrastructureWindows(owner);
943 delete Tunnel::GetByTile(tile);
945 DoClearSquare(tile);
946 DoClearSquare(endtile);
948 /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
949 AddSideToSignalBuffer(tile, ReverseDiagDir(dir), owner);
950 AddSideToSignalBuffer(endtile, dir, owner);
952 YapfNotifyTrackLayoutChange(tile, track);
953 YapfNotifyTrackLayoutChange(endtile, track);
955 if (v != NULL) TryPathReserve(v);
956 } else {
957 RoadType rt;
958 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
959 /* A full diagonal road tile has two road bits. */
960 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
961 if (c != NULL) {
962 c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
963 DirtyCompanyInfrastructureWindows(c->index);
967 delete Tunnel::GetByTile(tile);
969 DoClearSquare(tile);
970 DoClearSquare(endtile);
972 ViewportMapInvalidateTunnelCacheByTile(tile);
973 ViewportMapInvalidateTunnelCacheByTile(endtile);
975 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_TUNNEL] * len);
980 * Remove a bridge from the game, update town rating, etc.
981 * @param tile Tile containing one of the endpoints of the bridge.
982 * @param flags Command flags.
983 * @return Succeeded or failed command.
985 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
987 CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
988 if (ret.Failed()) return ret;
990 TileIndex endtile = GetOtherBridgeEnd(tile);
992 ret = TunnelBridgeIsFree(tile, endtile);
993 if (ret.Failed()) return ret;
995 DiagDirection direction = GetTunnelBridgeDirection(tile);
996 TileIndexDiff delta = TileOffsByDiagDir(direction);
998 Town *t = NULL;
999 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
1000 t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
1002 /* Check if you are allowed to remove the bridge owned by a town
1003 * Removal depends on difficulty settings */
1004 CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
1005 if (ret.Failed()) return ret;
1008 /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
1009 * you have a "Poor" (0) town rating */
1010 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
1011 ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
1014 Money base_cost = (GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) ? _price[PR_CLEAR_BRIDGE] : _price[PR_CLEAR_AQUEDUCT];
1015 uint len = GetTunnelBridgeLength(tile, endtile) + 2; // Don't forget the end tiles.
1017 if (flags & DC_EXEC) {
1018 /* read this value before actual removal of bridge */
1019 bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
1020 Owner owner = GetTileOwner(tile);
1021 int height = GetBridgeHeight(tile);
1022 Train *v = NULL;
1024 if (rail && HasTunnelBridgeReservation(tile)) {
1025 v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
1026 if (v != NULL) FreeTrainTrackReservation(v);
1029 /* Update company infrastructure counts. */
1030 if (rail) {
1031 if (Company::IsValidID(owner)) {
1032 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
1033 if (IsTunnelBridgeWithSignalSimulation(tile)) { // handle tunnel/bridge signals.
1034 Company::Get(GetTileOwner(tile))->infrastructure.signal -= GetTunnelBridgeSignalSimulationSignalCount(tile, endtile);
1037 } else if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
1038 SubtractRoadTunnelBridgeInfrastructure(tile, endtile);
1039 } else { // Aqueduct
1040 if (Company::IsValidID(owner)) Company::Get(owner)->infrastructure.water -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
1042 DirtyAllCompanyInfrastructureWindows();
1044 if (IsTunnelBridgeSignalSimulationEntrance(tile)) ClearBridgeEntranceSimulatedSignals(tile);
1045 if (IsTunnelBridgeSignalSimulationEntrance(endtile)) ClearBridgeEntranceSimulatedSignals(endtile);
1047 DoClearSquare(tile);
1048 DoClearSquare(endtile);
1049 for (TileIndex c = tile + delta; c != endtile; c += delta) {
1050 /* do not let trees appear from 'nowhere' after removing bridge */
1051 if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
1052 int minz = GetTileMaxZ(c) + 3;
1053 if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
1055 ClearBridgeMiddle(c);
1056 MarkTileDirtyByTile(c, ZOOM_LVL_DRAW_MAP, height - TileHeight(c));
1059 if (rail) {
1060 /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
1061 AddSideToSignalBuffer(tile, ReverseDiagDir(direction), owner);
1062 AddSideToSignalBuffer(endtile, direction, owner);
1064 Track track = DiagDirToDiagTrack(direction);
1065 YapfNotifyTrackLayoutChange(tile, track);
1066 YapfNotifyTrackLayoutChange(endtile, track);
1068 if (v != NULL) TryPathReserve(v, true);
1072 return CommandCost(EXPENSES_CONSTRUCTION, len * base_cost);
1076 * Remove a tunnel or a bridge from the game.
1077 * @param tile Tile containing one of the endpoints.
1078 * @param flags Command flags.
1079 * @return Succeeded or failed command.
1081 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
1083 if (IsTunnel(tile)) {
1084 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
1085 return DoClearTunnel(tile, flags);
1086 } else { // IsBridge(tile)
1087 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1088 return DoClearBridge(tile, flags);
1093 * Draw a single pillar sprite.
1094 * @param psid Pillarsprite
1095 * @param x Pillar X
1096 * @param y Pillar Y
1097 * @param z Pillar Z
1098 * @param w Bounding box size in X direction
1099 * @param h Bounding box size in Y direction
1100 * @param subsprite Optional subsprite for drawing halfpillars
1102 static inline void DrawPillar(const PalSpriteID *psid, int x, int y, int z, int w, int h, const SubSprite *subsprite)
1104 static const int PILLAR_Z_OFFSET = TILE_HEIGHT - BRIDGE_Z_START; ///< Start offset of pillar wrt. bridge (downwards)
1105 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);
1109 * Draw two bridge pillars (north and south).
1110 * @param z_bottom Bottom Z
1111 * @param z_top Top Z
1112 * @param psid Pillarsprite
1113 * @param x Pillar X
1114 * @param y Pillar Y
1115 * @param w Bounding box size in X direction
1116 * @param h Bounding box size in Y direction
1117 * @return Reached Z at the bottom
1119 static int DrawPillarColumn(int z_bottom, int z_top, const PalSpriteID *psid, int x, int y, int w, int h)
1121 int cur_z;
1122 for (cur_z = z_top; cur_z >= z_bottom; cur_z -= TILE_HEIGHT) {
1123 DrawPillar(psid, x, y, cur_z, w, h, NULL);
1125 return cur_z;
1129 * Draws the pillars under high bridges.
1131 * @param psid Image and palette of a bridge pillar.
1132 * @param ti #TileInfo of current bridge-middle-tile.
1133 * @param axis Orientation of bridge.
1134 * @param drawfarpillar Whether to draw the pillar at the back
1135 * @param x Sprite X position of front pillar.
1136 * @param y Sprite Y position of front pillar.
1137 * @param z_bridge Absolute height of bridge bottom.
1139 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
1141 static const int bounding_box_size[2] = {16, 2}; ///< bounding box size of pillars along bridge direction
1142 static const int back_pillar_offset[2] = { 0, 9}; ///< sprite position offset of back facing pillar
1144 static const int INF = 1000; ///< big number compared to sprite size
1145 static const SubSprite half_pillar_sub_sprite[2][2] = {
1146 { { -14, -INF, INF, INF }, { -INF, -INF, -15, INF } }, // X axis, north and south
1147 { { -INF, -INF, 15, INF }, { 16, -INF, INF, INF } }, // Y axis, north and south
1150 if (psid->sprite == 0) return;
1152 /* Determine ground height under pillars */
1153 DiagDirection south_dir = AxisToDiagDir(axis);
1154 int z_front_north = ti->z;
1155 int z_back_north = ti->z;
1156 int z_front_south = ti->z;
1157 int z_back_south = ti->z;
1158 GetSlopePixelZOnEdge(ti->tileh, south_dir, &z_front_south, &z_back_south);
1159 GetSlopePixelZOnEdge(ti->tileh, ReverseDiagDir(south_dir), &z_front_north, &z_back_north);
1161 /* Shared height of pillars */
1162 int z_front = max(z_front_north, z_front_south);
1163 int z_back = max(z_back_north, z_back_south);
1165 /* x and y size of bounding-box of pillars */
1166 int w = bounding_box_size[axis];
1167 int h = bounding_box_size[OtherAxis(axis)];
1168 /* sprite position of back facing pillar */
1169 int x_back = x - back_pillar_offset[axis];
1170 int y_back = y - back_pillar_offset[OtherAxis(axis)];
1172 /* Draw front pillars */
1173 int bottom_z = DrawPillarColumn(z_front, z_bridge, psid, x, y, w, h);
1174 if (z_front_north < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
1175 if (z_front_south < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
1177 /* Draw back pillars, skip top two parts, which are hidden by the bridge */
1178 int z_bridge_back = z_bridge - 2 * (int)TILE_HEIGHT;
1179 if (drawfarpillar && (z_back_north <= z_bridge_back || z_back_south <= z_bridge_back)) {
1180 bottom_z = DrawPillarColumn(z_back, z_bridge_back, psid, x_back, y_back, w, h);
1181 if (z_back_north < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
1182 if (z_back_south < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
1187 * Draws the trambits over an already drawn (lower end) of a bridge.
1188 * @param x the x of the bridge
1189 * @param y the y of the bridge
1190 * @param z the z of the bridge
1191 * @param offset number representing whether to level or sloped and the direction
1192 * @param overlay do we want to still see the road?
1193 * @param head are we drawing bridge head?
1195 static void DrawBridgeTramBits(int x, int y, int z, int offset, bool overlay, bool head)
1197 static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
1198 static const SpriteID back_offsets[6] = { 95, 96, 99, 102, 100, 101 };
1199 static const SpriteID front_offsets[6] = { 97, 98, 103, 106, 104, 105 };
1201 static const uint size_x[6] = { 1, 16, 16, 1, 16, 1 };
1202 static const uint size_y[6] = { 16, 1, 1, 16, 1, 16 };
1203 static const uint front_bb_offset_x[6] = { 15, 0, 0, 15, 0, 15 };
1204 static const uint front_bb_offset_y[6] = { 0, 15, 15, 0, 15, 0 };
1206 /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
1207 * The bounding boxes here are the same as for bridge front/roof */
1208 if (head || !IsInvisibilitySet(TO_BRIDGES)) {
1209 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
1210 x, y, size_x[offset], size_y[offset], 0x28, z,
1211 !head && IsTransparencySet(TO_BRIDGES));
1214 /* Do not draw catenary if it is set invisible */
1215 if (!IsInvisibilitySet(TO_CATENARY)) {
1216 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
1217 x, y, size_x[offset], size_y[offset], 0x28, z,
1218 IsTransparencySet(TO_CATENARY));
1221 /* Start a new SpriteCombine for the front part */
1222 EndSpriteCombine();
1223 StartSpriteCombine();
1225 /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
1226 if (!IsInvisibilitySet(TO_CATENARY)) {
1227 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
1228 x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
1229 IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
1233 /* Draws a signal on tunnel / bridge entrance tile. */
1234 static void DrawTunnelBridgeRampSignal(const TileInfo *ti)
1236 bool side = (_settings_game.vehicle.road_side != 0) &&_settings_game.construction.train_signal_side;
1238 static const Point SignalPositions[2][4] = {
1239 { /* X X Y Y Signals on the left side */
1240 {13, 3}, { 2, 13}, { 3, 4}, {13, 14}
1241 }, {/* X X Y Y Signals on the right side */
1242 {14, 13}, { 3, 3}, {13, 2}, { 3, 13}
1246 uint position;
1247 DiagDirection dir = GetTunnelBridgeDirection(ti->tile);
1249 switch (dir) {
1250 default: NOT_REACHED();
1251 case DIAGDIR_NE: position = 0; break;
1252 case DIAGDIR_SE: position = 2; break;
1253 case DIAGDIR_SW: position = 1; break;
1254 case DIAGDIR_NW: position = 3; break;
1257 SignalType type = SIGTYPE_NORMAL;
1259 bool is_green = (GetTunnelBridgeSignalState(ti->tile) == SIGNAL_STATE_GREEN);
1260 bool show_exit;
1261 if (IsTunnelBridgeSignalSimulationExit(ti->tile)) {
1262 show_exit = true;
1263 position ^= 1;
1264 if (IsTunnelBridgePBS(ti->tile)) type = SIGTYPE_PBS_ONEWAY;
1265 } else {
1266 show_exit = false;
1269 uint x = TileX(ti->tile) * TILE_SIZE + SignalPositions[side != show_exit][position ^ (show_exit ? 1 : 0)].x;
1270 uint y = TileY(ti->tile) * TILE_SIZE + SignalPositions[side != show_exit][position ^ (show_exit ? 1 : 0)].y;
1271 uint z = ti->z;
1273 if (ti->tileh == SLOPE_FLAT && side == show_exit && dir == DIAGDIR_SE) z += 2;
1274 if (ti->tileh == SLOPE_FLAT && side != show_exit && dir == DIAGDIR_SW) z += 2;
1276 if (ti->tileh != SLOPE_FLAT && IsBridge(ti->tile)) z += 8; // sloped bridge head
1277 SignalVariant variant = IsTunnelBridgeSemaphore(ti->tile) ? SIG_SEMAPHORE : SIG_ELECTRIC;
1278 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1280 SpriteID sprite = GetCustomSignalSprite(rti, ti->tile, type, variant, is_green ? SIGNAL_STATE_GREEN : SIGNAL_STATE_RED);
1281 bool is_custom_sprite = (sprite != 0);
1283 if (is_custom_sprite) {
1284 sprite += position;
1286 else {
1287 if (variant == SIG_ELECTRIC && type == SIGTYPE_NORMAL) {
1288 /* Normal electric signals are picked from original sprites. */
1289 sprite = SPR_ORIGINAL_SIGNALS_BASE + ((position << 1) + is_green);
1291 else {
1292 /* All other signals are picked from add on sprites. */
1293 sprite = SPR_SIGNALS_BASE + ((type - 1) * 16 + variant * 64 + (position << 1) + is_green) + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
1297 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, TILE_HEIGHT, z, false, 0, 0, BB_Z_SEPARATOR);
1300 /* Draws a signal on tunnel / bridge entrance tile. */
1301 static void DrawBrigeSignalOnMiddlePart(const TileInfo *ti, TileIndex bridge_start_tile, uint z)
1304 uint bridge_signal_position = 0;
1305 int m2_position = 0;
1307 uint bridge_section = GetTunnelBridgeLength(ti->tile, bridge_start_tile) + 1;
1309 while (bridge_signal_position <= bridge_section) {
1310 bridge_signal_position += _settings_game.construction.simulated_wormhole_signals;
1311 if (bridge_signal_position == bridge_section) {
1312 bool side = (_settings_game.vehicle.road_side != 0) && _settings_game.construction.train_signal_side;
1314 static const Point SignalPositions[2][4] = {
1315 { /* X X Y Y Signals on the left side */
1316 {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1317 }, {/* X X Y Y Signals on the right side */
1318 {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1322 uint position;
1324 switch (GetTunnelBridgeDirection(bridge_start_tile)) {
1325 default: NOT_REACHED();
1326 case DIAGDIR_NE: position = 0; break;
1327 case DIAGDIR_SE: position = 2; break;
1328 case DIAGDIR_SW: position = 1; break;
1329 case DIAGDIR_NW: position = 3; break;
1332 uint x = TileX(ti->tile) * TILE_SIZE + SignalPositions[side][position].x;
1333 uint y = TileY(ti->tile) * TILE_SIZE + SignalPositions[side][position].y;
1334 z += 5;
1336 SignalVariant variant = IsTunnelBridgeSemaphore(bridge_start_tile) ? SIG_SEMAPHORE : SIG_ELECTRIC;
1338 SpriteID sprite = (GetBridgeEntranceSimulatedSignalState(bridge_start_tile, m2_position) == SIGNAL_STATE_GREEN);
1340 if (variant == SIG_ELECTRIC) {
1341 /* Normal electric signals are picked from original sprites. */
1342 sprite += SPR_ORIGINAL_SIGNALS_BASE + (position << 1);
1343 } else {
1344 /* All other signals are picked from add on sprites. */
1345 sprite += SPR_SIGNALS_BASE + (SIGTYPE_NORMAL - 1) * 16 + variant * 64 + (position << 1);
1348 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, TILE_HEIGHT, z, false, 0, 0, BB_Z_SEPARATOR);
1350 m2_position++;
1355 * Draws a tunnel of bridge tile.
1356 * For tunnels, this is rather simple, as you only need to draw the entrance.
1357 * Bridges are a bit more complex. base_offset is where the sprite selection comes into play
1358 * and it works a bit like a bitmask.<p> For bridge heads:
1359 * @param ti TileInfo of the structure to draw
1360 * <ul><li>Bit 0: direction</li>
1361 * <li>Bit 1: northern or southern heads</li>
1362 * <li>Bit 2: Set if the bridge head is sloped</li>
1363 * <li>Bit 3 and more: Railtype Specific subset</li>
1364 * </ul>
1365 * Please note that in this code, "roads" are treated as railtype 1, whilst the real railtypes are 0, 2 and 3
1367 static void DrawTile_TunnelBridge(TileInfo *ti)
1369 TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
1370 DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
1372 if (IsTunnel(ti->tile)) {
1373 /* Front view of tunnel bounding boxes:
1375 * 122223 <- BB_Z_SEPARATOR
1376 * 1 3
1377 * 1 3 1,3 = empty helper BB
1378 * 1 3 2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
1382 static const int _tunnel_BB[4][12] = {
1383 /* tunnnel-roof | Z-separator | tram-catenary
1384 * w h bb_x bb_y| x y w h |bb_x bb_y w h */
1385 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // NE
1386 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // SE
1387 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // SW
1388 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // NW
1390 const int *BB_data = _tunnel_BB[tunnelbridge_direction];
1392 bool catenary = false;
1394 SpriteID image;
1395 SpriteID railtype_overlay = 0;
1396 if (transport_type == TRANSPORT_RAIL) {
1397 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1398 image = rti->base_sprites.tunnel;
1399 if (rti->UsesOverlay()) {
1400 /* Check if the railtype has custom tunnel portals. */
1401 railtype_overlay = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL_PORTAL);
1402 if (railtype_overlay != 0) image = SPR_RAILTYPE_TUNNEL_BASE; // Draw blank grass tunnel base.
1404 } else {
1405 image = SPR_TUNNEL_ENTRY_REAR_ROAD;
1408 if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += railtype_overlay != 0 ? 8 : 32;
1410 image += tunnelbridge_direction * 2;
1411 DrawGroundSprite(image, PAL_NONE);
1413 if (transport_type == TRANSPORT_ROAD) {
1414 RoadTypes rts = GetRoadTypes(ti->tile);
1416 if (HasBit(rts, ROADTYPE_TRAM)) {
1417 static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, { 5, 76, 77, 4 } };
1419 DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
1421 /* Do not draw wires if they are invisible */
1422 if (!IsInvisibilitySet(TO_CATENARY)) {
1423 catenary = true;
1424 StartSpriteCombine();
1425 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);
1428 } else {
1429 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1430 if (rti->UsesOverlay()) {
1431 SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
1432 if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
1435 DrawOverlay(ti, MP_TUNNELBRIDGE);
1437 /* PBS debugging, draw reserved tracks darker */
1438 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
1439 if (rti->UsesOverlay()) {
1440 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1441 DrawGroundSprite(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH);
1442 } else {
1443 DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
1447 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) {
1448 /* Maybe draw pylons on the entry side */
1449 DrawRailCatenary(ti);
1451 catenary = true;
1452 StartSpriteCombine();
1453 /* Draw wire above the ramp */
1454 DrawRailCatenaryOnTunnel(ti);
1458 if (railtype_overlay != 0 && !catenary) StartSpriteCombine();
1460 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);
1461 /* Draw railtype tunnel portal overlay if defined. */
1462 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);
1464 if (catenary || railtype_overlay != 0) EndSpriteCombine();
1466 /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
1467 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x, ti->y, BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
1468 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);
1470 /* Draw signals for tunnel. */
1471 if (IsTunnelBridgeWithSignalSimulation(ti->tile)) DrawTunnelBridgeRampSignal(ti);
1473 DrawBridgeMiddle(ti);
1474 } else { // IsBridge(ti->tile)
1475 if (transport_type == TRANSPORT_ROAD && IsRoadCustomBridgeHead(ti->tile)) {
1476 DrawRoadBits(ti);
1477 DrawBridgeMiddle(ti);
1478 return;
1481 const PalSpriteID *psid;
1482 int base_offset;
1483 bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
1485 if (transport_type == TRANSPORT_RAIL) {
1486 base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
1487 assert(base_offset != 8); // This one is used for roads
1488 } else {
1489 base_offset = 8;
1492 /* as the lower 3 bits are used for other stuff, make sure they are clear */
1493 assert( (base_offset & 0x07) == 0x00);
1495 DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
1497 /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
1498 base_offset += (6 - tunnelbridge_direction) % 4;
1500 /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
1501 if (transport_type != TRANSPORT_WATER) {
1502 if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
1503 psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
1504 } else {
1505 psid = _aqueduct_sprites + base_offset;
1508 if (!ice) {
1509 TileIndex next = ti->tile + TileOffsByDiagDir(tunnelbridge_direction);
1510 if (ti->tileh != SLOPE_FLAT && ti->z == 0 && HasTileWaterClass(next) && GetWaterClass(next) == WATER_CLASS_SEA) {
1511 DrawShoreTile(ti->tileh);
1512 } else {
1513 DrawClearLandTile(ti, 3);
1515 } else {
1516 DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
1519 /* draw ramp */
1521 /* Draw Trambits and PBS Reservation as SpriteCombine */
1522 if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
1524 /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
1525 * it doesn't disappear behind it
1527 /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
1528 AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
1530 if (transport_type == TRANSPORT_ROAD) {
1531 RoadTypes rts = GetRoadTypes(ti->tile);
1533 if (HasBit(rts, ROADTYPE_TRAM)) {
1534 uint offset = tunnelbridge_direction;
1535 int z = ti->z;
1536 if (ti->tileh != SLOPE_FLAT) {
1537 offset = (offset + 1) & 1;
1538 z += TILE_HEIGHT;
1539 } else {
1540 offset += 2;
1542 /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
1543 DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
1545 EndSpriteCombine();
1546 } else if (transport_type == TRANSPORT_RAIL) {
1547 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1548 if (rti->UsesOverlay()) {
1549 SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
1550 if (surface != 0) {
1551 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1552 AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1553 } else {
1554 AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
1557 /* Don't fallback to non-overlay sprite -- the spec states that
1558 * if an overlay is present then the bridge surface must be
1559 * present. */
1562 /* PBS debugging, draw reserved tracks darker */
1563 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
1564 if (rti->UsesOverlay()) {
1565 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1566 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1567 AddSortableSpriteToDraw(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1568 } else {
1569 AddSortableSpriteToDraw(overlay + RTO_SLOPE_NE + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
1571 } else {
1572 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1573 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);
1574 } else {
1575 AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
1580 EndSpriteCombine();
1581 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) {
1582 DrawRailCatenary(ti);
1586 /* Draw signals for bridge. */
1587 if (IsTunnelBridgeWithSignalSimulation(ti->tile)) DrawTunnelBridgeRampSignal(ti);
1589 DrawBridgeMiddle(ti);
1595 * Compute bridge piece. Computes the bridge piece to display depending on the position inside the bridge.
1596 * bridges pieces sequence (middle parts).
1597 * Note that it is not covering the bridge heads, which are always referenced by the same sprite table.
1598 * bridge len 1: BRIDGE_PIECE_NORTH
1599 * bridge len 2: BRIDGE_PIECE_NORTH BRIDGE_PIECE_SOUTH
1600 * bridge len 3: BRIDGE_PIECE_NORTH BRIDGE_PIECE_MIDDLE_ODD BRIDGE_PIECE_SOUTH
1601 * bridge len 4: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1602 * bridge len 5: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_MIDDLE_EVEN BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1603 * 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
1604 * 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
1605 * #0 - always as first, #1 - always as last (if len>1)
1606 * #2,#3 are to pair in order
1607 * for odd bridges: #5 is going in the bridge middle if on even position, #4 on odd (counting from 0)
1608 * @param north Northernmost tile of bridge
1609 * @param south Southernmost tile of bridge
1610 * @return Index of bridge piece
1612 static BridgePieces CalcBridgePiece(uint north, uint south)
1614 if (north == 1) {
1615 return BRIDGE_PIECE_NORTH;
1616 } else if (south == 1) {
1617 return BRIDGE_PIECE_SOUTH;
1618 } else if (north < south) {
1619 return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
1620 } else if (north > south) {
1621 return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
1622 } else {
1623 return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
1628 * Draw the middle bits of a bridge.
1629 * @param ti Tile information of the tile to draw it on.
1631 void DrawBridgeMiddle(const TileInfo *ti)
1633 /* Sectional view of bridge bounding boxes:
1635 * 1 2 1,2 = SpriteCombine of Bridge front/(back&floor) and RoadCatenary
1636 * 1 2 3 = empty helper BB
1637 * 1 7 2 4,5 = pillars under higher bridges
1638 * 1 6 88888 6 2 6 = elrail-pylons
1639 * 1 6 88888 6 2 7 = elrail-wire
1640 * 1 6 88888 6 2 <- TILE_HEIGHT 8 = rail-vehicle on bridge
1641 * 3333333333333 <- BB_Z_SEPARATOR
1642 * <- unused
1643 * 4 5 <- BB_HEIGHT_UNDER_BRIDGE
1644 * 4 5
1645 * 4 5
1649 if (!IsBridgeAbove(ti->tile)) return;
1651 TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
1652 TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
1653 TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
1655 Axis axis = GetBridgeAxis(ti->tile);
1656 BridgePieces piece = CalcBridgePiece(
1657 GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
1658 GetTunnelBridgeLength(ti->tile, rampsouth) + 1
1661 const PalSpriteID *psid;
1662 bool drawfarpillar;
1663 if (transport_type != TRANSPORT_WATER) {
1664 BridgeType type = GetBridgeType(rampsouth);
1665 drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
1667 uint base_offset;
1668 if (transport_type == TRANSPORT_RAIL) {
1669 base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
1670 } else {
1671 base_offset = 8;
1674 psid = base_offset + GetBridgeSpriteTable(type, piece);
1675 } else {
1676 drawfarpillar = true;
1677 psid = _aqueduct_sprites;
1680 if (axis != AXIS_X) psid += 4;
1682 int x = ti->x;
1683 int y = ti->y;
1684 uint bridge_z = GetBridgePixelHeight(rampsouth);
1685 int z = bridge_z - BRIDGE_Z_START;
1687 /* Add a bounding box that separates the bridge from things below it. */
1688 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
1690 /* Draw Trambits as SpriteCombine */
1691 if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
1693 /* Draw floor and far part of bridge*/
1694 if (!IsInvisibilitySet(TO_BRIDGES)) {
1695 if (axis == AXIS_X) {
1696 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
1697 } else {
1698 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
1702 psid++;
1704 if (transport_type == TRANSPORT_ROAD) {
1705 const RoadTypes rts = GetRoadTypes(rampsouth);
1707 bool has_tram = HasBit(rts, ROADTYPE_TRAM);
1708 bool has_road = HasBit(rts, ROADTYPE_ROAD);
1709 if (IsRoadCustomBridgeHeadTile(rampsouth)) {
1710 RoadBits entrance_bit = DiagDirToRoadBits(GetTunnelBridgeDirection(rampsouth));
1711 has_tram = has_tram && (GetCustomBridgeHeadRoadBits(rampsouth, ROADTYPE_TRAM) & entrance_bit);
1712 has_road = has_road && (GetCustomBridgeHeadRoadBits(rampsouth, ROADTYPE_ROAD) & entrance_bit);
1715 if (has_tram) {
1716 /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
1717 DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, has_road, false);
1718 } else {
1719 EndSpriteCombine();
1720 StartSpriteCombine();
1722 } else if (transport_type == TRANSPORT_RAIL) {
1723 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
1724 if (rti->UsesOverlay() && !IsInvisibilitySet(TO_BRIDGES)) {
1725 SpriteID surface = GetCustomRailSprite(rti, rampsouth, RTSG_BRIDGE, TCX_ON_BRIDGE);
1726 if (surface != 0) {
1727 AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1731 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && !IsInvisibilitySet(TO_BRIDGES) && HasTunnelBridgeReservation(rampnorth)
1732 && !IsTunnelBridgeWithSignalSimulation(rampnorth)) {
1733 if (rti->UsesOverlay()) {
1734 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1735 AddSortableSpriteToDraw(overlay + RTO_X + axis, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1736 } else {
1737 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));
1741 EndSpriteCombine();
1743 if (HasRailCatenaryDrawn(GetRailType(rampsouth))) {
1744 DrawRailCatenaryOnBridge(ti);
1748 /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
1749 if (!IsInvisibilitySet(TO_BRIDGES)) {
1750 if (axis == AXIS_X) {
1751 y += 12;
1752 if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
1753 } else {
1754 x += 12;
1755 if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
1759 /* Draw TramFront as SpriteCombine */
1760 if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
1762 /* Do not draw anything more if bridges are invisible */
1763 if (IsInvisibilitySet(TO_BRIDGES)) return;
1765 psid++;
1766 if (ti->z + 5 == z) {
1767 /* draw poles below for small bridges */
1768 if (psid->sprite != 0) {
1769 SpriteID image = psid->sprite;
1770 SpriteID pal = psid->pal;
1771 if (IsTransparencySet(TO_BRIDGES)) {
1772 SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
1773 pal = PALETTE_TO_TRANSPARENT;
1776 DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
1778 } else {
1779 /* draw pillars below for high bridges */
1780 DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
1785 static int GetSlopePixelZ_TunnelBridge(TileIndex tile, uint x, uint y)
1787 int z;
1788 Slope tileh = GetTilePixelSlope(tile, &z);
1790 x &= 0xF;
1791 y &= 0xF;
1793 if (IsTunnel(tile)) {
1794 uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
1796 /* In the tunnel entrance? */
1797 if (5 <= pos && pos <= 10) return z;
1798 } else { // IsBridge(tile)
1799 if (IsRoadCustomBridgeHeadTile(tile)) {
1800 return z + TILE_HEIGHT;
1803 DiagDirection dir = GetTunnelBridgeDirection(tile);
1804 uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
1806 z += ApplyPixelFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
1808 /* On the bridge ramp? */
1809 if (5 <= pos && pos <= 10) {
1810 int delta;
1812 if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
1814 switch (dir) {
1815 default: NOT_REACHED();
1816 case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
1817 case DIAGDIR_SE: delta = y / 2; break;
1818 case DIAGDIR_SW: delta = x / 2; break;
1819 case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
1821 return z + 1 + delta;
1825 return z + GetPartialPixelZ(x, y, tileh);
1828 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
1830 if (IsRoadCustomBridgeHeadTile(tile)) return FOUNDATION_LEVELED;
1831 return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
1834 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
1836 TransportType tt = GetTunnelBridgeTransportType(tile);
1838 if (IsTunnel(tile)) {
1839 if (Tunnel::GetByTile(tile)->is_chunnel) {
1840 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;
1841 } else {
1842 td->str = (tt == TRANSPORT_RAIL) ? IsTunnelBridgeWithSignalSimulation(tile) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_SIGNAL : STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
1844 } else { // IsBridge(tile)
1845 td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : IsTunnelBridgeWithSignalSimulation(tile) ? STR_LAI_BRIDGE_DESCRIPTION_RAILROAD_SIGNAL : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
1847 td->owner[0] = GetTileOwner(tile);
1849 Owner road_owner = INVALID_OWNER;
1850 Owner tram_owner = INVALID_OWNER;
1851 RoadTypes rts = GetRoadTypes(tile);
1852 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
1853 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
1855 /* Is there a mix of owners? */
1856 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
1857 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
1858 uint i = 1;
1859 if (road_owner != INVALID_OWNER) {
1860 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
1861 td->owner[i] = road_owner;
1862 i++;
1864 if (tram_owner != INVALID_OWNER) {
1865 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
1866 td->owner[i] = tram_owner;
1870 if (tt == TRANSPORT_RAIL) {
1871 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
1872 td->rail_speed = rti->max_speed;
1873 td->railtype = rti->strings.name;
1875 if (!IsTunnel(tile)) {
1876 uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
1877 if (td->rail_speed == 0 || spd < td->rail_speed) {
1878 td->rail_speed = spd;
1881 } else if (tt == TRANSPORT_ROAD && !IsTunnel(tile)) {
1882 td->road_speed = GetBridgeSpec(GetBridgeType(tile))->speed;
1887 static void TileLoop_TunnelBridge(TileIndex tile)
1889 bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
1890 switch (_settings_game.game_creation.landscape) {
1891 case LT_ARCTIC: {
1892 /* As long as we do not have a snow density, we want to use the density
1893 * from the entry edge. */
1894 int z = GetTileMaxZ(tile);
1895 if (snow_or_desert != (z > GetSnowLine())) {
1896 SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
1897 MarkTileDirtyByTile(tile);
1899 break;
1902 case LT_TROPIC:
1903 if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
1904 SetTunnelBridgeSnowOrDesert(tile, true);
1905 MarkTileDirtyByTile(tile);
1907 break;
1909 default:
1910 break;
1914 static bool ClickTile_TunnelBridge(TileIndex tile)
1916 /* Show vehicles found in tunnel. */
1917 if (IsTunnelTile(tile)) {
1918 int count = 0;
1919 const Train *t;
1920 TileIndex tile_end = GetOtherTunnelBridgeEnd(tile);
1921 FOR_ALL_TRAINS(t) {
1922 if (!t->IsFrontEngine()) continue;
1923 if (tile == t->tile || tile_end == t->tile) {
1924 ShowVehicleViewWindow(t);
1925 count++;
1927 if (count > 19) break; // no more than 20 windows open
1929 if (count > 0) return true;
1931 return false;
1934 extern const TrackBits _road_trackbits[16];
1936 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
1938 TransportType transport_type = GetTunnelBridgeTransportType(tile);
1940 if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
1942 DiagDirection dir = GetTunnelBridgeDirection(tile);
1944 if (mode == TRANSPORT_ROAD && IsRoadCustomBridgeHeadTile(tile)) {
1945 if (side != INVALID_DIAGDIR && side == dir) return 0;
1946 TrackBits bits = TRACK_BIT_NONE;
1947 if (sub_mode & ROADTYPES_TRAM) bits |= _road_trackbits[GetCustomBridgeHeadRoadBits(tile, ROADTYPE_TRAM)];
1948 if (sub_mode & ROADTYPES_ROAD) bits |= _road_trackbits[GetCustomBridgeHeadRoadBits(tile, ROADTYPE_ROAD)];
1949 return CombineTrackStatus(TrackBitsToTrackdirBits(bits), TRACKDIR_BIT_NONE);
1952 if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
1954 return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
1957 static void UpdateRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end, bool add) {
1958 /* A full diagonal road has two road bits. */
1959 const uint middle_len = 2 * GetTunnelBridgeLength(begin, end) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1960 const uint len = middle_len + (4 * TUNNELBRIDGE_TRACKBIT_FACTOR);
1962 /* Iterate all present road types as each can have a different owner. */
1963 RoadType rt;
1964 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(begin)) {
1965 Company * const c = Company::GetIfValid(GetRoadOwner(begin, rt));
1966 if (c != NULL) {
1967 uint infra = 0;
1968 if (IsBridge(begin)) {
1969 const RoadBits bits = GetCustomBridgeHeadRoadBits(begin, rt);
1970 infra += CountBits(bits) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1971 if (bits & DiagDirToRoadBits(GetTunnelBridgeDirection(begin))) {
1972 infra += middle_len;
1974 } else {
1975 infra += len;
1977 if (add) {
1978 c->infrastructure.road[rt] += infra;
1979 } else {
1980 c->infrastructure.road[rt] -= infra;
1984 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(end)) {
1985 Company * const c = Company::GetIfValid(GetRoadOwner(end, rt));
1986 if (c != NULL) {
1987 uint infra = 0;
1988 if (IsBridge(end)) {
1989 const RoadBits bits = GetCustomBridgeHeadRoadBits(end, rt);
1990 infra += CountBits(bits) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1992 if (add) {
1993 c->infrastructure.road[rt] += infra;
1994 } else {
1995 c->infrastructure.road[rt] -= infra;
2001 void AddRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end) {
2002 UpdateRoadTunnelBridgeInfrastructure(begin, end, true);
2005 void SubtractRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end) {
2006 UpdateRoadTunnelBridgeInfrastructure(begin, end, false);
2009 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
2011 const TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
2012 /* Set number of pieces to zero if it's the southern tile as we
2013 * don't want to update the infrastructure counts twice. */
2014 const uint num_pieces = tile < other_end ? (GetTunnelBridgeLength(tile, other_end) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR : 0;
2015 const TransportType tt = GetTunnelBridgeTransportType(tile);
2017 if (tt == TRANSPORT_ROAD) SubtractRoadTunnelBridgeInfrastructure(tile, other_end);
2019 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
2020 /* Update all roadtypes, no matter if they are present */
2021 if (GetRoadOwner(tile, rt) == old_owner) {
2022 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
2026 if (tt == TRANSPORT_ROAD) AddRoadTunnelBridgeInfrastructure(tile, other_end);
2028 if (!IsTileOwner(tile, old_owner)) return;
2030 /* Update company infrastructure counts for rail and water as well.
2031 * No need to dirty windows here, we'll redraw the whole screen anyway. */
2032 Company *old = Company::Get(old_owner);
2033 if (tt == TRANSPORT_RAIL) {
2034 old->infrastructure.rail[GetRailType(tile)] -= num_pieces;
2035 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += num_pieces;
2036 } else if (tt == TRANSPORT_WATER) {
2037 old->infrastructure.water -= num_pieces;
2038 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.water += num_pieces;
2041 if (IsTunnelBridgeWithSignalSimulation(tile) && IsTunnelBridgeSignalSimulationEntrance(tile)) {
2042 uint num_sigs = GetTunnelBridgeSignalSimulationSignalCount(tile, other_end);
2043 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
2044 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.signal += num_sigs;
2047 if (new_owner != INVALID_OWNER) {
2048 SetTileOwner(tile, new_owner);
2049 } else {
2050 if (tt == TRANSPORT_RAIL) {
2051 /* Since all of our vehicles have been removed, it is safe to remove the rail
2052 * bridge / tunnel. */
2053 CommandCost ret = DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
2054 assert(ret.Succeeded());
2055 } else {
2056 /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
2057 SetTileOwner(tile, OWNER_NONE);
2063 * Frame when the 'enter tunnel' sound should be played. This is the second
2064 * frame on a tile, so the sound is played shortly after entering the tunnel
2065 * tile, while the vehicle is still visible.
2067 static const byte TUNNEL_SOUND_FRAME = 1;
2070 * Frame when a vehicle should be hidden in a tunnel with a certain direction.
2071 * This differs per direction, because of visibility / bounding box issues.
2072 * Note that direction, in this case, is the direction leading into the tunnel.
2073 * When entering a tunnel, hide the vehicle when it reaches the given frame.
2074 * When leaving a tunnel, show the vehicle when it is one frame further
2075 * to the 'outside', i.e. at (TILE_SIZE-1) - (frame) + 1
2077 extern const byte _tunnel_visibility_frame[DIAGDIR_END] = {12, 8, 8, 12};
2079 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
2081 int z = GetSlopePixelZ(x, y) - v->z_pos;
2083 if (abs(z) > 2) return VETSB_CANNOT_ENTER;
2084 /* Direction into the wormhole */
2085 const DiagDirection dir = GetTunnelBridgeDirection(tile);
2086 /* Direction of the vehicle */
2087 const DiagDirection vdir = DirToDiagDir(v->direction);
2088 /* New position of the vehicle on the tile */
2089 byte pos = (DiagDirToAxis(vdir) == AXIS_X ? x : y) & TILE_UNIT_MASK;
2090 /* Number of units moved by the vehicle since entering the tile */
2091 byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2093 if (IsTunnel(tile)) {
2094 if (v->type == VEH_TRAIN) {
2095 Train *t = Train::From(v);
2097 if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
2098 if (t->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
2099 if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
2100 SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
2102 return VETSB_CONTINUE;
2104 if (frame == _tunnel_visibility_frame[dir]) {
2105 t->tile = tile;
2106 t->track = TRACK_BIT_WORMHOLE;
2107 t->vehstatus |= VS_HIDDEN;
2108 return VETSB_ENTERED_WORMHOLE;
2112 if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
2113 /* We're at the tunnel exit ?? */
2114 if (t->tile != tile && GetOtherTunnelEnd(t->tile) != tile) return VETSB_CONTINUE; // In chunnel
2115 t->tile = tile;
2116 t->track = DiagDirToDiagTrackBits(vdir);
2117 assert(t->track);
2118 t->vehstatus &= ~VS_HIDDEN;
2119 return VETSB_ENTERED_WORMHOLE;
2121 } else if (v->type == VEH_ROAD) {
2122 RoadVehicle *rv = RoadVehicle::From(v);
2124 /* Enter tunnel? */
2125 if (rv->state != RVSB_WORMHOLE && dir == vdir) {
2126 if (frame == _tunnel_visibility_frame[dir]) {
2127 /* Frame should be equal to the next frame number in the RV's movement */
2128 assert(frame == rv->frame + 1);
2129 rv->tile = tile;
2130 rv->state = RVSB_WORMHOLE;
2131 rv->vehstatus |= VS_HIDDEN;
2132 return VETSB_ENTERED_WORMHOLE;
2133 } else {
2134 return VETSB_CONTINUE;
2138 /* We're at the tunnel exit ?? */
2139 if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
2140 if (rv->tile != tile && GetOtherTunnelEnd(rv->tile) != tile) return VETSB_CONTINUE; // In chunnel
2141 rv->tile = tile;
2142 rv->state = DiagDirToDiagTrackdir(vdir);
2143 rv->frame = frame;
2144 rv->vehstatus &= ~VS_HIDDEN;
2145 return VETSB_ENTERED_WORMHOLE;
2148 } else { // IsBridge(tile)
2149 if (v->vehstatus & VS_HIDDEN) return VETSB_CONTINUE; // Building bridges between chunnel portals allowed.
2150 if (v->type != VEH_SHIP) {
2151 /* modify speed of vehicle */
2152 uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
2154 if (v->type == VEH_ROAD) spd *= 2;
2155 Vehicle *first = v->First();
2156 first->cur_speed = min(first->cur_speed, spd);
2159 if (vdir == dir) {
2160 /* Vehicle enters bridge at the last frame inside this tile. */
2161 if (frame != TILE_SIZE - 1) return VETSB_CONTINUE;
2162 switch (v->type) {
2163 case VEH_TRAIN: {
2164 Train *t = Train::From(v);
2165 t->track = TRACK_BIT_WORMHOLE;
2166 ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
2167 ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
2168 break;
2171 case VEH_ROAD: {
2172 RoadVehicle *rv = RoadVehicle::From(v);
2173 rv->state = RVSB_WORMHOLE;
2174 /* There are no slopes inside bridges / tunnels. */
2175 ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
2176 ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
2177 break;
2180 case VEH_SHIP:
2181 Ship::From(v)->state = TRACK_BIT_WORMHOLE;
2182 break;
2184 default: NOT_REACHED();
2186 return VETSB_ENTERED_WORMHOLE;
2187 } else if (vdir == ReverseDiagDir(dir)) {
2188 v->tile = tile;
2189 switch (v->type) {
2190 case VEH_TRAIN: {
2191 Train *t = Train::From(v);
2192 if (t->track == TRACK_BIT_WORMHOLE) {
2193 t->track = DiagDirToDiagTrackBits(vdir);
2194 return VETSB_ENTERED_WORMHOLE;
2196 break;
2199 case VEH_ROAD: {
2200 RoadVehicle *rv = RoadVehicle::From(v);
2201 if (rv->state == RVSB_WORMHOLE) {
2202 rv->state = DiagDirToDiagTrackdir(vdir);
2203 rv->frame = 0;
2204 return VETSB_ENTERED_WORMHOLE;
2206 break;
2209 case VEH_SHIP: {
2210 Ship *ship = Ship::From(v);
2211 if (ship->state == TRACK_BIT_WORMHOLE) {
2212 ship->state = DiagDirToDiagTrackBits(vdir);
2213 return VETSB_ENTERED_WORMHOLE;
2215 break;
2218 default: NOT_REACHED();
2222 return VETSB_CONTINUE;
2225 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2227 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
2228 DiagDirection direction = GetTunnelBridgeDirection(tile);
2229 Axis axis = DiagDirToAxis(direction);
2230 CommandCost res;
2231 int z_old;
2232 Slope tileh_old = GetTileSlope(tile, &z_old);
2234 if (IsRoadCustomBridgeHeadTile(tile)) {
2235 const RoadBits pieces = GetCustomBridgeHeadAllRoadBits(tile);
2236 const RoadBits entrance_piece = DiagDirToRoadBits(direction);
2237 if ((_invalid_tileh_slopes_road[0][tileh_new] & (pieces & ~entrance_piece)) != ROAD_NONE) {
2238 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2242 /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
2243 if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
2244 CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
2245 res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
2246 } else {
2247 CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
2248 res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
2251 /* Surface slope is valid and remains unchanged? */
2252 if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2255 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2258 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
2259 DrawTile_TunnelBridge, // draw_tile_proc
2260 GetSlopePixelZ_TunnelBridge, // get_slope_z_proc
2261 ClearTile_TunnelBridge, // clear_tile_proc
2262 NULL, // add_accepted_cargo_proc
2263 GetTileDesc_TunnelBridge, // get_tile_desc_proc
2264 GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
2265 ClickTile_TunnelBridge, // click_tile_proc
2266 NULL, // animate_tile_proc
2267 TileLoop_TunnelBridge, // tile_loop_proc
2268 ChangeTileOwner_TunnelBridge, // change_tile_owner_proc
2269 NULL, // add_produced_cargo_proc
2270 VehicleEnter_TunnelBridge, // vehicle_enter_tile_proc
2271 GetFoundation_TunnelBridge, // get_foundation_proc
2272 TerraformTile_TunnelBridge, // terraform_tile_proc