OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

tunnelbridge_cmd.cpp
Go to the documentation of this file.
1 /* $Id: tunnelbridge_cmd.cpp 27209 2015-03-28 14:04:06Z frosch $ */
2
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 */
9
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 "strings_func.h"
30 #include "date_func.h"
31 #include "clear_func.h"
32 #include "vehicle_func.h"
33 #include "sound_func.h"
34 #include "tunnelbridge.h"
35 #include "cheat_type.h"
36 #include "elrail_func.h"
37 #include "pbs.h"
38 #include "company_base.h"
39 #include "newgrf_railtype.h"
40 #include "object_base.h"
41 #include "water.h"
42 #include "company_gui.h"
43
44 #include "table/strings.h"
45 #include "table/bridge_land.h"
46
47 #include "safeguards.h"
48
49 BridgeSpec _bridge[MAX_BRIDGES];
50 TileIndex _build_tunnel_endtile;
51
53 static const int BRIDGE_Z_START = 3;
54
55
64 void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
65 {
66 TileIndexDiff delta = TileOffsByDiagDir(direction);
67 for (TileIndex t = begin; t != end; t += delta) {
68 MarkTileDirtyByTile(t, bridge_height - TileHeight(t));
69 }
70 MarkTileDirtyByTile(end);
71 }
72
77 void MarkBridgeDirty(TileIndex tile)
78 {
79 MarkBridgeDirty(tile, GetOtherTunnelBridgeEnd(tile), GetTunnelBridgeDirection(tile), GetBridgeHeight(tile));
80 }
81
83 void ResetBridges()
84 {
85 /* First, free sprite table data */
86 for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
87 if (_bridge[i].sprite_table != NULL) {
88 for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
89 free(_bridge[i].sprite_table);
90 }
91 }
92
93 /* Then, wipe out current bridges */
94 memset(&_bridge, 0, sizeof(_bridge));
95 /* And finally, reinstall default data */
96 memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
97 }
98
105 int CalcBridgeLenCostFactor(int length)
106 {
107 if (length < 2) return length;
108
109 length -= 2;
110 int sum = 2;
111 for (int delta = 1;; delta++) {
112 for (int count = 0; count < delta; count++) {
113 if (length == 0) return sum;
114 sum += delta;
115 length--;
116 }
117 }
118 }
119
126 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
127 {
128 if (tileh == SLOPE_FLAT ||
129 ((tileh == SLOPE_NE || tileh == SLOPE_SW) && axis == AXIS_X) ||
130 ((tileh == SLOPE_NW || tileh == SLOPE_SE) && axis == AXIS_Y)) return FOUNDATION_NONE;
131
132 return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
133 }
134
142 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
143 {
144 ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
145 /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
146 return (tileh != SLOPE_FLAT);
147 }
148
149 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
150 {
151 const BridgeSpec *bridge = GetBridgeSpec(index);
152 assert(table < BRIDGE_PIECE_INVALID);
153 if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
154 return _bridge_sprite_table[index][table];
155 } else {
156 return bridge->sprite_table[table];
157 }
158 }
159
160
169 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, int *z)
170 {
171 Foundation f = GetBridgeFoundation(*tileh, axis);
172 *z += ApplyFoundationToSlope(f, tileh);
173
174 Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
175 if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
176
177 if (f == FOUNDATION_NONE) return CommandCost();
178
179 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
180 }
181
190 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, int *z)
191 {
192 Foundation f = GetBridgeFoundation(*tileh, axis);
193 *z += ApplyFoundationToSlope(f, tileh);
194
195 Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
196 if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
197
198 if (f == FOUNDATION_NONE) return CommandCost();
199
200 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
201 }
202
209 CommandCost CheckBridgeAvailability(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
210 {
211 if (flags & DC_QUERY_COST) {
212 if (bridge_len <= _settings_game.construction.max_bridge_length) return CommandCost();
213 return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
214 }
215
216 if (bridge_type >= MAX_BRIDGES) return CMD_ERROR;
217
218 const BridgeSpec *b = GetBridgeSpec(bridge_type);
219 if (b->avail_year > _cur_year) return CMD_ERROR;
220
221 uint max = min(b->max_length, _settings_game.construction.max_bridge_length);
222
223 if (b->min_length > bridge_len) return CMD_ERROR;
224 if (bridge_len <= max) return CommandCost();
225 return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
226 }
227
240 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
241 {
242 CompanyID company = _current_company;
243
244 RailType railtype = INVALID_RAILTYPE;
245 RoadTypes roadtypes = ROADTYPES_NONE;
246
247 /* unpack parameters */
248 BridgeType bridge_type = GB(p2, 0, 8);
249
250 if (!IsValidTile(p1)) return_cmd_error(STR_ERROR_BRIDGE_THROUGH_MAP_BORDER);
251
252 TransportType transport_type = Extract<TransportType, 15, 2>(p2);
253
254 /* type of bridge */
255 switch (transport_type) {
256 case TRANSPORT_ROAD:
257 roadtypes = Extract<RoadTypes, 8, 2>(p2);
258 if (!HasExactlyOneBit(roadtypes) || !HasRoadTypesAvail(company, roadtypes)) return CMD_ERROR;
259 break;
260
261 case TRANSPORT_RAIL:
262 railtype = Extract<RailType, 8, 4>(p2);
263 if (!ValParamRailtype(railtype)) return CMD_ERROR;
264 break;
265
266 case TRANSPORT_WATER:
267 break;
268
269 default:
270 /* Airports don't have bridges. */
271 return CMD_ERROR;
272 }
273 TileIndex tile_start = p1;
274 TileIndex tile_end = end_tile;
275
276 if (company == OWNER_DEITY) {
277 if (transport_type != TRANSPORT_ROAD) return CMD_ERROR;
278 const Town *town = CalcClosestTownFromTile(tile_start);
279
280 company = OWNER_TOWN;
281
282 /* If we are not within a town, we are not owned by the town */
283 if (town == NULL || DistanceSquare(tile_start, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
284 company = OWNER_NONE;
285 }
286 }
287
288 if (tile_start == tile_end) {
289 return_cmd_error(STR_ERROR_CAN_T_START_AND_END_ON);
290 }
291
292 Axis direction;
293 if (TileX(tile_start) == TileX(tile_end)) {
294 direction = AXIS_Y;
295 } else if (TileY(tile_start) == TileY(tile_end)) {
296 direction = AXIS_X;
297 } else {
298 return_cmd_error(STR_ERROR_START_AND_END_MUST_BE_IN);
299 }
300
301 if (tile_end < tile_start) Swap(tile_start, tile_end);
302
303 uint bridge_len = GetTunnelBridgeLength(tile_start, tile_end);
304 if (transport_type != TRANSPORT_WATER) {
305 /* set and test bridge length, availability */
306 CommandCost ret = CheckBridgeAvailability(bridge_type, bridge_len, flags);
307 if (ret.Failed()) return ret;
308 } else {
309 if (bridge_len > _settings_game.construction.max_bridge_length) return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
310 }
311
312 int z_start;
313 int z_end;
314 Slope tileh_start = GetTileSlope(tile_start, &z_start);
315 Slope tileh_end = GetTileSlope(tile_end, &z_end);
316 bool pbs_reservation = false;
317
318 CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
319 CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end, &z_end);
320
321 /* Aqueducts can't be built of flat land. */
322 if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
323 if (z_start != z_end) return_cmd_error(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT);
324
325 CommandCost cost(EXPENSES_CONSTRUCTION);
326 Owner owner;
327 bool is_new_owner;
328 if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
329 GetOtherBridgeEnd(tile_start) == tile_end &&
330 GetTunnelBridgeTransportType(tile_start) == transport_type) {
331 /* Replace a current bridge. */
332
333 /* If this is a railway bridge, make sure the railtypes match. */
334 if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
335 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
336 }
337
338 /* Do not replace town bridges with lower speed bridges, unless in scenario editor. */
339 if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
340 GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed &&
341 _game_mode != GM_EDITOR) {
342 Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
343
344 if (t == NULL) {
345 return CMD_ERROR;
346 } else {
347 SetDParam(0, t->index);
348 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
349 }
350 }
351
352 /* Do not replace the bridge with the same bridge type. */
353 if (!(flags & DC_QUERY_COST) && (bridge_type == GetBridgeType(tile_start)) && (transport_type != TRANSPORT_ROAD || (roadtypes & ~GetRoadTypes(tile_start)) == 0)) {
354 return_cmd_error(STR_ERROR_ALREADY_BUILT);
355 }
356
357 /* Do not allow replacing another company's bridges. */
358 if (!IsTileOwner(tile_start, company) && !IsTileOwner(tile_start, OWNER_TOWN) && !IsTileOwner(tile_start, OWNER_NONE)) {
359 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
360 }
361
362 cost.AddCost((bridge_len + 1) * _price[PR_CLEAR_BRIDGE]); // The cost of clearing the current bridge.
363 owner = GetTileOwner(tile_start);
364
365 /* If bridge belonged to bankrupt company, it has a new owner now */
366 is_new_owner = (owner == OWNER_NONE);
367 if (is_new_owner) owner = company;
368
369 switch (transport_type) {
370 case TRANSPORT_RAIL:
371 /* Keep the reservation, the path stays valid. */
372 pbs_reservation = HasTunnelBridgeReservation(tile_start);
373 break;
374
375 case TRANSPORT_ROAD:
376 /* Do not remove road types when upgrading a bridge */
377 roadtypes |= GetRoadTypes(tile_start);
378 break;
379
380 default: break;
381 }
382 } else {
383 /* Build a new bridge. */
384
385 bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
386
387 /* Try and clear the start landscape */
388 CommandCost ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
389 if (ret.Failed()) return ret;
390 cost = ret;
391
392 if (terraform_cost_north.Failed() || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
393 cost.AddCost(terraform_cost_north);
394
395 /* Try and clear the end landscape */
396 ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
397 if (ret.Failed()) return ret;
398 cost.AddCost(ret);
399
400 /* false - end tile slope check */
401 if (terraform_cost_south.Failed() || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
402 cost.AddCost(terraform_cost_south);
403
404 const TileIndex heads[] = {tile_start, tile_end};
405 for (int i = 0; i < 2; i++) {
406 if (IsBridgeAbove(heads[i])) {
407 TileIndex north_head = GetNorthernBridgeEnd(heads[i]);
408
409 if (direction == GetBridgeAxis(heads[i])) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
410
411 if (z_start + 1 == GetBridgeHeight(north_head)) {
412 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
413 }
414 }
415 }
416
417 TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
418 for (TileIndex tile = tile_start + delta; tile != tile_end; tile += delta) {
419 if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN);
420
421 if (z_start >= (GetTileZ(tile) + _settings_game.construction.max_bridge_height)) {
422 /*
423 * Disallow too high bridges.
424 * Properly rendering a map where very high bridges (might) exist is expensive.
425 * See http://www.tt-forums.net/viewtopic.php?f=33&t=40844&start=980#p1131762
426 * for a detailed discussion. z_start here is one heightlevel below the bridge level.
427 */
428 return_cmd_error(STR_ERROR_BRIDGE_TOO_HIGH_FOR_TERRAIN);
429 }
430
431 if (IsBridgeAbove(tile)) {
432 /* Disallow crossing bridges for the time being */
433 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
434 }
435
436 switch (GetTileType(tile)) {
437 case MP_WATER:
438 if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
439 break;
440
441 case MP_RAILWAY:
442 if (!IsPlainRail(tile)) goto not_valid_below;
443 break;
444
445 case MP_ROAD:
446 if (IsRoadDepot(tile)) goto not_valid_below;
447 break;
448
449 case MP_TUNNELBRIDGE:
450 if (IsTunnel(tile)) break;
451 if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
452 if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
453 break;
454
455 case MP_OBJECT: {
456 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
457 if ((spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) == 0) goto not_valid_below;
458 if (GetTileMaxZ(tile) + spec->height > z_start) goto not_valid_below;
459 break;
460 }
461
462 case MP_CLEAR:
463 break;
464
465 default:
466 not_valid_below:;
467 /* try and clear the middle landscape */
468 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
469 if (ret.Failed()) return ret;
470 cost.AddCost(ret);
471 break;
472 }
473
474 if (flags & DC_EXEC) {
475 /* We do this here because when replacing a bridge with another
476 * type calling SetBridgeMiddle isn't needed. After all, the
477 * tile already has the has_bridge_above bits set. */
478 SetBridgeMiddle(tile, direction);
479 }
480 }
481
482 owner = company;
483 is_new_owner = true;
484 }
485
486 /* do the drill? */
487 if (flags & DC_EXEC) {
488 DiagDirection dir = AxisToDiagDir(direction);
489
490 Company *c = Company::GetIfValid(owner);
491 switch (transport_type) {
492 case TRANSPORT_RAIL:
493 /* Add to company infrastructure count if required. */
494 if (is_new_owner && c != NULL) c->infrastructure.rail[railtype] += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
495 MakeRailBridgeRamp(tile_start, owner, bridge_type, dir, railtype);
496 MakeRailBridgeRamp(tile_end, owner, bridge_type, ReverseDiagDir(dir), railtype);
497 SetTunnelBridgeReservation(tile_start, pbs_reservation);
498 SetTunnelBridgeReservation(tile_end, pbs_reservation);
499 break;
500
501 case TRANSPORT_ROAD: {
502 RoadTypes prev_roadtypes = IsBridgeTile(tile_start) ? GetRoadTypes(tile_start) : ROADTYPES_NONE;
503 if (is_new_owner) {
504 /* Also give unowned present roadtypes to new owner */
505 if (HasBit(prev_roadtypes, ROADTYPE_ROAD) && GetRoadOwner(tile_start, ROADTYPE_ROAD) == OWNER_NONE) ClrBit(prev_roadtypes, ROADTYPE_ROAD);
506 if (HasBit(prev_roadtypes, ROADTYPE_TRAM) && GetRoadOwner(tile_start, ROADTYPE_TRAM) == OWNER_NONE) ClrBit(prev_roadtypes, ROADTYPE_TRAM);
507 }
508 if (c != NULL) {
509 /* Add all new road types to the company infrastructure counter. */
510 RoadType new_rt;
511 FOR_EACH_SET_ROADTYPE(new_rt, roadtypes ^ prev_roadtypes) {
512 /* A full diagonal road tile has two road bits. */
513 Company::Get(owner)->infrastructure.road[new_rt] += (bridge_len + 2) * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
514 }
515 }
516 Owner owner_road = owner;
517 Owner owner_tram = owner;
518 if (HasBit(prev_roadtypes, ROADTYPE_ROAD)) owner_road = GetRoadOwner(tile_start, ROADTYPE_ROAD);
519 if (HasBit(prev_roadtypes, ROADTYPE_TRAM)) owner_tram = GetRoadOwner(tile_start, ROADTYPE_TRAM);
520 MakeRoadBridgeRamp(tile_start, owner, owner_road, owner_tram, bridge_type, dir, roadtypes);
521 MakeRoadBridgeRamp(tile_end, owner, owner_road, owner_tram, bridge_type, ReverseDiagDir(dir), roadtypes);
522 break;
523 }
524
525 case TRANSPORT_WATER:
526 if (is_new_owner && c != NULL) c->infrastructure.water += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
527 MakeAqueductBridgeRamp(tile_start, owner, dir);
528 MakeAqueductBridgeRamp(tile_end, owner, ReverseDiagDir(dir));
529 break;
530
531 default:
532 NOT_REACHED();
533 }
534
535 /* Mark all tiles dirty */
536 MarkBridgeDirty(tile_start, tile_end, AxisToDiagDir(direction), z_start);
537 DirtyCompanyInfrastructureWindows(owner);
538 }
539
540 if ((flags & DC_EXEC) && transport_type == TRANSPORT_RAIL) {
541 Track track = AxisToTrack(direction);
542 AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, company);
543 YapfNotifyTrackLayoutChange(tile_start, track);
544 }
545
546 /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
547 * It's unnecessary to execute this command every time for every bridge. So it is done only
548 * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
549 */
550 Company *c = Company::GetIfValid(company);
551 if (!(flags & DC_QUERY_COST) || (c != NULL && c->is_ai)) {
552 bridge_len += 2; // begin and end tiles/ramps
553
554 switch (transport_type) {
555 case TRANSPORT_ROAD: cost.AddCost(bridge_len * _price[PR_BUILD_ROAD] * 2 * CountBits(roadtypes)); break;
556 case TRANSPORT_RAIL: cost.AddCost(bridge_len * RailBuildCost(railtype)); break;
557 default: break;
558 }
559
560 if (c != NULL) bridge_len = CalcBridgeLenCostFactor(bridge_len);
561
562 if (transport_type != TRANSPORT_WATER) {
563 cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
564 } else {
565 /* Aqueducts use a separate base cost. */
566 cost.AddCost((int64)bridge_len * _price[PR_BUILD_AQUEDUCT]);
567 }
568
569 }
570
571 return cost;
572 }
573
574
585 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
586 {
587 CompanyID company = _current_company;
588
589 TransportType transport_type = Extract<TransportType, 8, 2>(p1);
590
591 RailType railtype = INVALID_RAILTYPE;
592 RoadTypes rts = ROADTYPES_NONE;
593 _build_tunnel_endtile = 0;
594 switch (transport_type) {
595 case TRANSPORT_RAIL:
596 railtype = Extract<RailType, 0, 4>(p1);
597 if (!ValParamRailtype(railtype)) return CMD_ERROR;
598 break;
599
600 case TRANSPORT_ROAD:
601 rts = Extract<RoadTypes, 0, 2>(p1);
602 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(company, rts)) return CMD_ERROR;
603 break;
604
605 default: return CMD_ERROR;
606 }
607
608 if (company == OWNER_DEITY) {
609 if (transport_type != TRANSPORT_ROAD) return CMD_ERROR;
610 const Town *town = CalcClosestTownFromTile(start_tile);
611
612 company = OWNER_TOWN;
613
614 /* If we are not within a town, we are not owned by the town */
615 if (town == NULL || DistanceSquare(start_tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
616 company = OWNER_NONE;
617 }
618 }
619
620 int start_z;
621 int end_z;
622 Slope start_tileh = GetTileSlope(start_tile, &start_z);
623 DiagDirection direction = GetInclinedSlopeDirection(start_tileh);
624 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
625
626 if (HasTileWaterGround(start_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
627
628 CommandCost ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
629 if (ret.Failed()) return ret;
630
631 /* XXX - do NOT change 'ret' in the loop, as it is used as the price
632 * for the clearing of the entrance of the tunnel. Assigning it to
633 * cost before the loop will yield different costs depending on start-
634 * position, because of increased-cost-by-length: 'cost += cost >> 3' */
635
636 TileIndexDiff delta = TileOffsByDiagDir(direction);
637 DiagDirection tunnel_in_way_dir;
638 if (DiagDirToAxis(direction) == AXIS_Y) {
639 tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
640 } else {
641 tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
642 }
643
644 TileIndex end_tile = start_tile;
645
646 /* Tile shift coefficient. Will decrease for very long tunnels to avoid exponential growth of price*/
647 int tiles_coef = 3;
648 /* Number of tiles from start of tunnel */
649 int tiles = 0;
650 /* Number of tiles at which the cost increase coefficient per tile is halved */
651 int tiles_bump = 25;
652
653 CommandCost cost(EXPENSES_CONSTRUCTION);
654 Slope end_tileh;
655 for (;;) {
656 end_tile += delta;
657 if (!IsValidTile(end_tile)) return_cmd_error(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
658 end_tileh = GetTileSlope(end_tile, &end_z);
659
660 if (start_z == end_z) break;
661
662 if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
663 return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
664 }
665
666 tiles++;
667 if (tiles == tiles_bump) {
668 tiles_coef++;
669 tiles_bump *= 2;
670 }
671
672 cost.AddCost(_price[PR_BUILD_TUNNEL]);
673 cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
674 }
675
676 /* Add the cost of the entrance */
677 cost.AddCost(_price[PR_BUILD_TUNNEL]);
678 cost.AddCost(ret);
679
680 /* if the command fails from here on we want the end tile to be highlighted */
681 _build_tunnel_endtile = end_tile;
682
683 if (tiles > _settings_game.construction.max_tunnel_length) return_cmd_error(STR_ERROR_TUNNEL_TOO_LONG);
684
685 if (HasTileWaterGround(end_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
686
687 /* Clear the tile in any case */
688 ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
689 if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
690 cost.AddCost(ret);
691
692 /* slope of end tile must be complementary to the slope of the start tile */
693 if (end_tileh != ComplementSlope(start_tileh)) {
694 /* Mark the tile as already cleared for the terraform command.
695 * Do this for all tiles (like trees), not only objects. */
696 ClearedObjectArea *coa = FindClearedObject(end_tile);
697 if (coa == NULL) {
698 coa = _cleared_object_areas.Append();
699 coa->first_tile = end_tile;
700 coa->area = TileArea(end_tile, 1, 1);
701 }
702
703 /* Hide the tile from the terraforming command */
704 TileIndex old_first_tile = coa->first_tile;
705 coa->first_tile = INVALID_TILE;
706 ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
707 coa->first_tile = old_first_tile;
708 if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
709 cost.AddCost(ret);
710 }
711 cost.AddCost(_price[PR_BUILD_TUNNEL]);
712
713 /* Pay for the rail/road in the tunnel including entrances */
714 switch (transport_type) {
715 case TRANSPORT_ROAD: cost.AddCost((tiles + 2) * _price[PR_BUILD_ROAD] * 2); break;
716 case TRANSPORT_RAIL: cost.AddCost((tiles + 2) * RailBuildCost(railtype)); break;
717 default: NOT_REACHED();
718 }
719
720 if (flags & DC_EXEC) {
721 Company *c = Company::GetIfValid(company);
722 uint num_pieces = (tiles + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
723 if (transport_type == TRANSPORT_RAIL) {
724 if (!IsTunnelTile(start_tile) && c != NULL) c->infrastructure.rail[railtype] += num_pieces;
725 MakeRailTunnel(start_tile, company, direction, railtype);
726 MakeRailTunnel(end_tile, company, ReverseDiagDir(direction), railtype);
727 AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, company);
728 YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
729 } else {
730 if (c != NULL) {
731 RoadType rt;
732 FOR_EACH_SET_ROADTYPE(rt, rts ^ (IsTunnelTile(start_tile) ? GetRoadTypes(start_tile) : ROADTYPES_NONE)) {
733 c->infrastructure.road[rt] += num_pieces * 2; // A full diagonal road has two road bits.
734 }
735 }
736 MakeRoadTunnel(start_tile, company, direction, rts);
737 MakeRoadTunnel(end_tile, company, ReverseDiagDir(direction), rts);
738 }
739 DirtyCompanyInfrastructureWindows(company);
740 }
741
742 return cost;
743 }
744
745
751 static inline CommandCost CheckAllowRemoveTunnelBridge(TileIndex tile)
752 {
753 /* Floods can remove anything as well as the scenario editor */
754 if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return CommandCost();
755
756 switch (GetTunnelBridgeTransportType(tile)) {
757 case TRANSPORT_ROAD: {
758 RoadTypes rts = GetRoadTypes(tile);
759 Owner road_owner = _current_company;
760 Owner tram_owner = _current_company;
761
762 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
763 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
764
765 /* We can remove unowned road and if the town allows it */
766 if (road_owner == OWNER_TOWN && _current_company != OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) {
767 /* Town does not allow */
768 return CheckTileOwnership(tile);
769 }
770 if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
771 if (tram_owner == OWNER_NONE) tram_owner = _current_company;
772
773 CommandCost ret = CheckOwnership(road_owner, tile);
774 if (ret.Succeeded()) ret = CheckOwnership(tram_owner, tile);
775 return ret;
776 }
777
778 case TRANSPORT_RAIL:
779 return CheckOwnership(GetTileOwner(tile));
780
781 case TRANSPORT_WATER: {
782 /* Always allow to remove aqueducts without owner. */
783 Owner aqueduct_owner = GetTileOwner(tile);
784 if (aqueduct_owner == OWNER_NONE) aqueduct_owner = _current_company;
785 return CheckOwnership(aqueduct_owner);
786 }
787
788 default: NOT_REACHED();
789 }
790 }
791
798 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
799 {
800 CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
801 if (ret.Failed()) return ret;
802
803 TileIndex endtile = GetOtherTunnelEnd(tile);
804
805 ret = TunnelBridgeIsFree(tile, endtile);
806 if (ret.Failed()) return ret;
807
808 _build_tunnel_endtile = endtile;
809
810 Town *t = NULL;
811 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
812 t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
813
814 /* Check if you are allowed to remove the tunnel owned by a town
815 * Removal depends on difficulty settings */
816 CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
817 if (ret.Failed()) return ret;
818 }
819
820 /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
821 * you have a "Poor" (0) town rating */
822 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
823 ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
824 }
825
826 uint len = GetTunnelBridgeLength(tile, endtile) + 2; // Don't forget the end tiles.
827
828 if (flags & DC_EXEC) {
829 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
830 /* We first need to request values before calling DoClearSquare */
831 DiagDirection dir = GetTunnelBridgeDirection(tile);
832 Track track = DiagDirToDiagTrack(dir);
833 Owner owner = GetTileOwner(tile);
834
835 Train *v = NULL;
836 if (HasTunnelBridgeReservation(tile)) {
837 v = GetTrainForReservation(tile, track);
838 if (v != NULL) FreeTrainTrackReservation(v);
839 }
840
841 if (Company::IsValidID(owner)) {
842 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
843 DirtyCompanyInfrastructureWindows(owner);
844 }
845
846 DoClearSquare(tile);
847 DoClearSquare(endtile);
848
849 /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
850 AddSideToSignalBuffer(tile, ReverseDiagDir(dir), owner);
851 AddSideToSignalBuffer(endtile, dir, owner);
852
853 YapfNotifyTrackLayoutChange(tile, track);
854 YapfNotifyTrackLayoutChange(endtile, track);
855
856 if (v != NULL) TryPathReserve(v);
857 } else {
858 RoadType rt;
859 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
860 /* A full diagonal road tile has two road bits. */
861 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
862 if (c != NULL) {
863 c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
864 DirtyCompanyInfrastructureWindows(c->index);
865 }
866 }
867
868 DoClearSquare(tile);
869 DoClearSquare(endtile);
870 }
871 }
872 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_TUNNEL] * len);
873 }
874
875
882 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
883 {
884 CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
885 if (ret.Failed()) return ret;
886
887 TileIndex endtile = GetOtherBridgeEnd(tile);
888
889 ret = TunnelBridgeIsFree(tile, endtile);
890 if (ret.Failed()) return ret;
891
892 DiagDirection direction = GetTunnelBridgeDirection(tile);
893 TileIndexDiff delta = TileOffsByDiagDir(direction);
894
895 Town *t = NULL;
896 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
897 t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
898
899 /* Check if you are allowed to remove the bridge owned by a town
900 * Removal depends on difficulty settings */
901 CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
902 if (ret.Failed()) return ret;
903 }
904
905 /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
906 * you have a "Poor" (0) town rating */
907 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
908 ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
909 }
910
911 Money base_cost = (GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) ? _price[PR_CLEAR_BRIDGE] : _price[PR_CLEAR_AQUEDUCT];
912 uint len = GetTunnelBridgeLength(tile, endtile) + 2; // Don't forget the end tiles.
913
914 if (flags & DC_EXEC) {
915 /* read this value before actual removal of bridge */
916 bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
917 Owner owner = GetTileOwner(tile);
918 int height = GetBridgeHeight(tile);
919 Train *v = NULL;
920
921 if (rail && HasTunnelBridgeReservation(tile)) {
922 v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
923 if (v != NULL) FreeTrainTrackReservation(v);
924 }
925
926 /* Update company infrastructure counts. */
927 if (rail) {
928 if (Company::IsValidID(owner)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
929 } else if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
930 RoadType rt;
931 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
932 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
933 if (c != NULL) {
934 /* A full diagonal road tile has two road bits. */
935 c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
936 DirtyCompanyInfrastructureWindows(c->index);
937 }
938 }
939 } else { // Aqueduct
940 if (Company::IsValidID(owner)) Company::Get(owner)->infrastructure.water -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
941 }
942 DirtyCompanyInfrastructureWindows(owner);
943
944 DoClearSquare(tile);
945 DoClearSquare(endtile);
946 for (TileIndex c = tile + delta; c != endtile; c += delta) {
947 /* do not let trees appear from 'nowhere' after removing bridge */
948 if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
949 int minz = GetTileMaxZ(c) + 3;
950 if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
951 }
952 ClearBridgeMiddle(c);
953 MarkTileDirtyByTile(c, height - TileHeight(c));
954 }
955
956 if (rail) {
957 /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
958 AddSideToSignalBuffer(tile, ReverseDiagDir(direction), owner);
959 AddSideToSignalBuffer(endtile, direction, owner);
960
961 Track track = DiagDirToDiagTrack(direction);
962 YapfNotifyTrackLayoutChange(tile, track);
963 YapfNotifyTrackLayoutChange(endtile, track);
964
965 if (v != NULL) TryPathReserve(v, true);
966 }
967 }
968
969 return CommandCost(EXPENSES_CONSTRUCTION, len * base_cost);
970 }
971
978 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
979 {
980 if (IsTunnel(tile)) {
981 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
982 return DoClearTunnel(tile, flags);
983 } else { // IsBridge(tile)
984 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
985 return DoClearBridge(tile, flags);
986 }
987 }
988
999 static inline void DrawPillar(const PalSpriteID *psid, int x, int y, int z, int w, int h, const SubSprite *subsprite)
1000 {
1001 static const int PILLAR_Z_OFFSET = TILE_HEIGHT - BRIDGE_Z_START;
1002 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);
1003 }
1004
1016 static int DrawPillarColumn(int z_bottom, int z_top, const PalSpriteID *psid, int x, int y, int w, int h)
1017 {
1018 int cur_z;
1019 for (cur_z = z_top; cur_z >= z_bottom; cur_z -= TILE_HEIGHT) {
1020 DrawPillar(psid, x, y, cur_z, w, h, NULL);
1021 }
1022 return cur_z;
1023 }
1024
1036 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
1037 {
1038 static const int bounding_box_size[2] = {16, 2};
1039 static const int back_pillar_offset[2] = { 0, 9};
1040
1041 static const int INF = 1000;
1042 static const SubSprite half_pillar_sub_sprite[2][2] = {
1043 { { -14, -INF, INF, INF }, { -INF, -INF, -15, INF } }, // X axis, north and south
1044 { { -INF, -INF, 15, INF }, { 16, -INF, INF, INF } }, // Y axis, north and south
1045 };
1046
1047 if (psid->sprite == 0) return;
1048
1049 /* Determine ground height under pillars */
1050 DiagDirection south_dir = AxisToDiagDir(axis);
1051 int z_front_north = ti->z;
1052 int z_back_north = ti->z;
1053 int z_front_south = ti->z;
1054 int z_back_south = ti->z;
1055 GetSlopePixelZOnEdge(ti->tileh, south_dir, &z_front_south, &z_back_south);
1056 GetSlopePixelZOnEdge(ti->tileh, ReverseDiagDir(south_dir), &z_front_north, &z_back_north);
1057
1058 /* Shared height of pillars */
1059 int z_front = max(z_front_north, z_front_south);
1060 int z_back = max(z_back_north, z_back_south);
1061
1062 /* x and y size of bounding-box of pillars */
1063 int w = bounding_box_size[axis];
1064 int h = bounding_box_size[OtherAxis(axis)];
1065 /* sprite position of back facing pillar */
1066 int x_back = x - back_pillar_offset[axis];
1067 int y_back = y - back_pillar_offset[OtherAxis(axis)];
1068
1069 /* Draw front pillars */
1070 int bottom_z = DrawPillarColumn(z_front, z_bridge, psid, x, y, w, h);
1071 if (z_front_north < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
1072 if (z_front_south < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
1073
1074 /* Draw back pillars, skip top two parts, which are hidden by the bridge */
1075 int z_bridge_back = z_bridge - 2 * (int)TILE_HEIGHT;
1076 if (drawfarpillar && (z_back_north <= z_bridge_back || z_back_south <= z_bridge_back)) {
1077 bottom_z = DrawPillarColumn(z_back, z_bridge_back, psid, x_back, y_back, w, h);
1078 if (z_back_north < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
1079 if (z_back_south < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
1080 }
1081 }
1082
1092 static void DrawBridgeTramBits(int x, int y, int z, int offset, bool overlay, bool head)
1093 {
1094 static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
1095 static const SpriteID back_offsets[6] = { 95, 96, 99, 102, 100, 101 };
1096 static const SpriteID front_offsets[6] = { 97, 98, 103, 106, 104, 105 };
1097
1098 static const uint size_x[6] = { 1, 16, 16, 1, 16, 1 };
1099 static const uint size_y[6] = { 16, 1, 1, 16, 1, 16 };
1100 static const uint front_bb_offset_x[6] = { 15, 0, 0, 15, 0, 15 };
1101 static const uint front_bb_offset_y[6] = { 0, 15, 15, 0, 15, 0 };
1102
1103 /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
1104 * The bounding boxes here are the same as for bridge front/roof */
1105 if (head || !IsInvisibilitySet(TO_BRIDGES)) {
1106 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
1107 x, y, size_x[offset], size_y[offset], 0x28, z,
1108 !head && IsTransparencySet(TO_BRIDGES));
1109 }
1110
1111 /* Do not draw catenary if it is set invisible */
1112 if (!IsInvisibilitySet(TO_CATENARY)) {
1113 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
1114 x, y, size_x[offset], size_y[offset], 0x28, z,
1115 IsTransparencySet(TO_CATENARY));
1116 }
1117
1118 /* Start a new SpriteCombine for the front part */
1119 EndSpriteCombine();
1120 StartSpriteCombine();
1121
1122 /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
1123 if (!IsInvisibilitySet(TO_CATENARY)) {
1124 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
1125 x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
1126 IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
1127 }
1128 }
1129
1143 static void DrawTile_TunnelBridge(TileInfo *ti)
1144 {
1145 TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
1146 DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
1147
1148 if (IsTunnel(ti->tile)) {
1149 /* Front view of tunnel bounding boxes:
1150 *
1151 * 122223 <- BB_Z_SEPARATOR
1152 * 1 3
1153 * 1 3 1,3 = empty helper BB
1154 * 1 3 2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
1155 *
1156 */
1157
1158 static const int _tunnel_BB[4][12] = {
1159 /* tunnnel-roof | Z-separator | tram-catenary
1160 * w h bb_x bb_y| x y w h |bb_x bb_y w h */
1161 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // NE
1162 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // SE
1163 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // SW
1164 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // NW
1165 };
1166 const int *BB_data = _tunnel_BB[tunnelbridge_direction];
1167
1168 bool catenary = false;
1169
1170 SpriteID image;
1171 SpriteID railtype_overlay = 0;
1172 if (transport_type == TRANSPORT_RAIL) {
1173 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1174 image = rti->base_sprites.tunnel;
1175 if (rti->UsesOverlay()) {
1176 /* Check if the railtype has custom tunnel portals. */
1177 railtype_overlay = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL_PORTAL);
1178 if (railtype_overlay != 0) image = SPR_RAILTYPE_TUNNEL_BASE; // Draw blank grass tunnel base.
1179 }
1180 } else {
1181 image = SPR_TUNNEL_ENTRY_REAR_ROAD;
1182 }
1183
1184 if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += railtype_overlay != 0 ? 8 : 32;
1185
1186 image += tunnelbridge_direction * 2;
1187 DrawGroundSprite(image, PAL_NONE);
1188
1189 if (transport_type == TRANSPORT_ROAD) {
1190 RoadTypes rts = GetRoadTypes(ti->tile);
1191
1192 if (HasBit(rts, ROADTYPE_TRAM)) {
1193 static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, { 5, 76, 77, 4 } };
1194
1195 DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
1196
1197 /* Do not draw wires if they are invisible */
1198 if (!IsInvisibilitySet(TO_CATENARY)) {
1199 catenary = true;
1200 StartSpriteCombine();
1201 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);
1202 }
1203 }
1204 } else {
1205 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1206 if (rti->UsesOverlay()) {
1207 SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
1208 if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
1209 }
1210
1211 /* PBS debugging, draw reserved tracks darker */
1212 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
1213 if (rti->UsesOverlay()) {
1214 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1215 DrawGroundSprite(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH);
1216 } else {
1217 DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
1218 }
1219 }
1220
1221 if (HasCatenaryDrawn(GetRailType(ti->tile))) {
1222 /* Maybe draw pylons on the entry side */
1223 DrawCatenary(ti);
1224
1225 catenary = true;
1226 StartSpriteCombine();
1227 /* Draw wire above the ramp */
1228 DrawCatenaryOnTunnel(ti);
1229 }
1230 }
1231
1232 if (railtype_overlay != 0 && !catenary) StartSpriteCombine();
1233
1234 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);
1235 /* Draw railtype tunnel portal overlay if defined. */
1236 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);
1237
1238 if (catenary || railtype_overlay != 0) EndSpriteCombine();
1239
1240 /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
1241 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x, ti->y, BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
1242 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);
1243
1244 DrawBridgeMiddle(ti);
1245 } else { // IsBridge(ti->tile)
1246 const PalSpriteID *psid;
1247 int base_offset;
1248 bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
1249
1250 if (transport_type == TRANSPORT_RAIL) {
1251 base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
1252 assert(base_offset != 8); // This one is used for roads
1253 } else {
1254 base_offset = 8;
1255 }
1256
1257 /* as the lower 3 bits are used for other stuff, make sure they are clear */
1258 assert( (base_offset & 0x07) == 0x00);
1259
1260 DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
1261
1262 /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
1263 base_offset += (6 - tunnelbridge_direction) % 4;
1264
1265 /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
1266 if (transport_type != TRANSPORT_WATER) {
1267 if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
1268 psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
1269 } else {
1270 psid = _aqueduct_sprites + base_offset;
1271 }
1272
1273 if (!ice) {
1274 TileIndex next = ti->tile + TileOffsByDiagDir(tunnelbridge_direction);
1275 if (ti->tileh != SLOPE_FLAT && ti->z == 0 && HasTileWaterClass(next) && GetWaterClass(next) == WATER_CLASS_SEA) {
1276 DrawShoreTile(ti->tileh);
1277 } else {
1278 DrawClearLandTile(ti, 3);
1279 }
1280 } else {
1281 DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
1282 }
1283
1284 /* draw ramp */
1285
1286 /* Draw Trambits and PBS Reservation as SpriteCombine */
1287 if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
1288
1289 /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
1290 * it doesn't disappear behind it
1291 */
1292 /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
1293 AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
1294
1295 if (transport_type == TRANSPORT_ROAD) {
1296 RoadTypes rts = GetRoadTypes(ti->tile);
1297
1298 if (HasBit(rts, ROADTYPE_TRAM)) {
1299 uint offset = tunnelbridge_direction;
1300 int z = ti->z;
1301 if (ti->tileh != SLOPE_FLAT) {
1302 offset = (offset + 1) & 1;
1303 z += TILE_HEIGHT;
1304 } else {
1305 offset += 2;
1306 }
1307 /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
1308 DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
1309 }
1310 EndSpriteCombine();
1311 } else if (transport_type == TRANSPORT_RAIL) {
1312 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1313 if (rti->UsesOverlay()) {
1314 SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
1315 if (surface != 0) {
1316 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1317 AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1318 } else {
1319 AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
1320 }
1321 }
1322 /* Don't fallback to non-overlay sprite -- the spec states that
1323 * if an overlay is present then the bridge surface must be
1324 * present. */
1325 }
1326
1327 /* PBS debugging, draw reserved tracks darker */
1328 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
1329 if (rti->UsesOverlay()) {
1330 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1331 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1332 AddSortableSpriteToDraw(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1333 } else {
1334 AddSortableSpriteToDraw(overlay + RTO_SLOPE_NE + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
1335 }
1336 } else {
1337 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1338 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);
1339 } else {
1340 AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
1341 }
1342 }
1343 }
1344
1345 EndSpriteCombine();
1346 if (HasCatenaryDrawn(GetRailType(ti->tile))) {
1347 DrawCatenary(ti);
1348 }
1349 }
1350
1351 DrawBridgeMiddle(ti);
1352 }
1353 }
1354
1355
1374 static BridgePieces CalcBridgePiece(uint north, uint south)
1375 {
1376 if (north == 1) {
1377 return BRIDGE_PIECE_NORTH;
1378 } else if (south == 1) {
1379 return BRIDGE_PIECE_SOUTH;
1380 } else if (north < south) {
1381 return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
1382 } else if (north > south) {
1383 return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
1384 } else {
1385 return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
1386 }
1387 }
1388
1393 void DrawBridgeMiddle(const TileInfo *ti)
1394 {
1395 /* Sectional view of bridge bounding boxes:
1396 *
1397 * 1 2 1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
1398 * 1 2 3 = empty helper BB
1399 * 1 7 2 4,5 = pillars under higher bridges
1400 * 1 6 88888 6 2 6 = elrail-pylons
1401 * 1 6 88888 6 2 7 = elrail-wire
1402 * 1 6 88888 6 2 <- TILE_HEIGHT 8 = rail-vehicle on bridge
1403 * 3333333333333 <- BB_Z_SEPARATOR
1404 * <- unused
1405 * 4 5 <- BB_HEIGHT_UNDER_BRIDGE
1406 * 4 5
1407 * 4 5
1408 *
1409 */
1410
1411 if (!IsBridgeAbove(ti->tile)) return;
1412
1413 TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
1414 TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
1415 TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
1416
1417 Axis axis = GetBridgeAxis(ti->tile);
1418 BridgePieces piece = CalcBridgePiece(
1419 GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
1420 GetTunnelBridgeLength(ti->tile, rampsouth) + 1
1421 );
1422
1423 const PalSpriteID *psid;
1424 bool drawfarpillar;
1425 if (transport_type != TRANSPORT_WATER) {
1426 BridgeType type = GetBridgeType(rampsouth);
1427 drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
1428
1429 uint base_offset;
1430 if (transport_type == TRANSPORT_RAIL) {
1431 base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
1432 } else {
1433 base_offset = 8;
1434 }
1435
1436 psid = base_offset + GetBridgeSpriteTable(type, piece);
1437 } else {
1438 drawfarpillar = true;
1439 psid = _aqueduct_sprites;
1440 }
1441
1442 if (axis != AXIS_X) psid += 4;
1443
1444 int x = ti->x;
1445 int y = ti->y;
1446 uint bridge_z = GetBridgePixelHeight(rampsouth);
1447 int z = bridge_z - BRIDGE_Z_START;
1448
1449 /* Add a bounding box that separates the bridge from things below it. */
1450 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
1451
1452 /* Draw Trambits as SpriteCombine */
1453 if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
1454
1455 /* Draw floor and far part of bridge*/
1456 if (!IsInvisibilitySet(TO_BRIDGES)) {
1457 if (axis == AXIS_X) {
1458 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
1459 } else {
1460 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
1461 }
1462 }
1463
1464 psid++;
1465
1466 if (transport_type == TRANSPORT_ROAD) {
1467 RoadTypes rts = GetRoadTypes(rampsouth);
1468
1469 if (HasBit(rts, ROADTYPE_TRAM)) {
1470 /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
1471 DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
1472 } else {
1473 EndSpriteCombine();
1474 StartSpriteCombine();
1475 }
1476 } else if (transport_type == TRANSPORT_RAIL) {
1477 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
1478 if (rti->UsesOverlay() && !IsInvisibilitySet(TO_BRIDGES)) {
1479 SpriteID surface = GetCustomRailSprite(rti, rampsouth, RTSG_BRIDGE, TCX_ON_BRIDGE);
1480 if (surface != 0) {
1481 AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1482 }
1483 }
1484
1485 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && !IsInvisibilitySet(TO_BRIDGES) && HasTunnelBridgeReservation(rampnorth)) {
1486 if (rti->UsesOverlay()) {
1487 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1488 AddSortableSpriteToDraw(overlay + RTO_X + axis, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1489 } else {
1490 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));
1491 }
1492 }
1493
1494 EndSpriteCombine();
1495
1496 if (HasCatenaryDrawn(GetRailType(rampsouth))) {
1497 DrawCatenaryOnBridge(ti);
1498 }
1499 }
1500
1501 /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
1502 if (!IsInvisibilitySet(TO_BRIDGES)) {
1503 if (axis == AXIS_X) {
1504 y += 12;
1505 if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
1506 } else {
1507 x += 12;
1508 if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
1509 }
1510 }
1511
1512 /* Draw TramFront as SpriteCombine */
1513 if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
1514
1515 /* Do not draw anything more if bridges are invisible */
1516 if (IsInvisibilitySet(TO_BRIDGES)) return;
1517
1518 psid++;
1519 if (ti->z + 5 == z) {
1520 /* draw poles below for small bridges */
1521 if (psid->sprite != 0) {
1522 SpriteID image = psid->sprite;
1523 SpriteID pal = psid->pal;
1524 if (IsTransparencySet(TO_BRIDGES)) {
1525 SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
1526 pal = PALETTE_TO_TRANSPARENT;
1527 }
1528
1529 DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
1530 }
1531 } else {
1532 /* draw pillars below for high bridges */
1533 DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
1534 }
1535 }
1536
1537
1538 static int GetSlopePixelZ_TunnelBridge(TileIndex tile, uint x, uint y)
1539 {
1540 int z;
1541 Slope tileh = GetTilePixelSlope(tile, &z);
1542
1543 x &= 0xF;
1544 y &= 0xF;
1545
1546 if (IsTunnel(tile)) {
1547 uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
1548
1549 /* In the tunnel entrance? */
1550 if (5 <= pos && pos <= 10) return z;
1551 } else { // IsBridge(tile)
1552 DiagDirection dir = GetTunnelBridgeDirection(tile);
1553 uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
1554
1555 z += ApplyPixelFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
1556
1557 /* On the bridge ramp? */
1558 if (5 <= pos && pos <= 10) {
1559 int delta;
1560
1561 if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
1562
1563 switch (dir) {
1564 default: NOT_REACHED();
1565 case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
1566 case DIAGDIR_SE: delta = y / 2; break;
1567 case DIAGDIR_SW: delta = x / 2; break;
1568 case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
1569 }
1570 return z + 1 + delta;
1571 }
1572 }
1573
1574 return z + GetPartialPixelZ(x, y, tileh);
1575 }
1576
1577 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
1578 {
1579 return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
1580 }
1581
1582 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
1583 {
1584 TransportType tt = GetTunnelBridgeTransportType(tile);
1585
1586 if (IsTunnel(tile)) {
1587 td->str = (tt == TRANSPORT_RAIL) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
1588 } else { // IsBridge(tile)
1589 td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
1590 }
1591 td->owner[0] = GetTileOwner(tile);
1592
1593 Owner road_owner = INVALID_OWNER;
1594 Owner tram_owner = INVALID_OWNER;
1595 RoadTypes rts = GetRoadTypes(tile);
1596 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
1597 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
1598
1599 /* Is there a mix of owners? */
1600 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
1601 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
1602 uint i = 1;
1603 if (road_owner != INVALID_OWNER) {
1604 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
1605 td->owner[i] = road_owner;
1606 i++;
1607 }
1608 if (tram_owner != INVALID_OWNER) {
1609 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
1610 td->owner[i] = tram_owner;
1611 }
1612 }
1613
1614 if (tt == TRANSPORT_RAIL) {
1615 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
1616 td->rail_speed = rti->max_speed;
1617
1618 if (!IsTunnel(tile)) {
1619 uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
1620 if (td->rail_speed == 0 || spd < td->rail_speed) {
1621 td->rail_speed = spd;
1622 }
1623 }
1624 } else if (tt == TRANSPORT_ROAD && !IsTunnel(tile)) {
1625 td->road_speed = GetBridgeSpec(GetBridgeType(tile))->speed;
1626 }
1627 }
1628
1629
1630 static void TileLoop_TunnelBridge(TileIndex tile)
1631 {
1632 bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
1633 switch (_settings_game.game_creation.landscape) {
1634 case LT_ARCTIC: {
1635 /* As long as we do not have a snow density, we want to use the density
1636 * from the entry edge. For tunnels this is the lowest point for bridges the highest point.
1637 * (Independent of foundations) */
1638 int z = IsBridge(tile) ? GetTileMaxZ(tile) : GetTileZ(tile);
1639 if (snow_or_desert != (z > GetSnowLine())) {
1640 SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
1641 MarkTileDirtyByTile(tile);
1642 }
1643 break;
1644 }
1645
1646 case LT_TROPIC:
1647 if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
1648 SetTunnelBridgeSnowOrDesert(tile, true);
1649 MarkTileDirtyByTile(tile);
1650 }
1651 break;
1652
1653 default:
1654 break;
1655 }
1656 }
1657
1658 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
1659 {
1660 TransportType transport_type = GetTunnelBridgeTransportType(tile);
1661 if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
1662
1663 DiagDirection dir = GetTunnelBridgeDirection(tile);
1664 if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
1665 return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
1666 }
1667
1668 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
1669 {
1670 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
1671 /* Set number of pieces to zero if it's the southern tile as we
1672 * don't want to update the infrastructure counts twice. */
1673 uint num_pieces = tile < other_end ? (GetTunnelBridgeLength(tile, other_end) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR : 0;
1674
1675 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1676 /* Update all roadtypes, no matter if they are present */
1677 if (GetRoadOwner(tile, rt) == old_owner) {
1678 if (HasBit(GetRoadTypes(tile), rt)) {
1679 /* Update company infrastructure counts. A full diagonal road tile has two road bits.
1680 * No need to dirty windows here, we'll redraw the whole screen anyway. */
1681 Company::Get(old_owner)->infrastructure.road[rt] -= num_pieces * 2;
1682 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += num_pieces * 2;
1683 }
1684
1685 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
1686 }
1687 }
1688
1689 if (!IsTileOwner(tile, old_owner)) return;
1690
1691 /* Update company infrastructure counts for rail and water as well.
1692 * No need to dirty windows here, we'll redraw the whole screen anyway. */
1693 TransportType tt = GetTunnelBridgeTransportType(tile);
1694 Company *old = Company::Get(old_owner);
1695 if (tt == TRANSPORT_RAIL) {
1696 old->infrastructure.rail[GetRailType(tile)] -= num_pieces;
1697 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += num_pieces;
1698 } else if (tt == TRANSPORT_WATER) {
1699 old->infrastructure.water -= num_pieces;
1700 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.water += num_pieces;
1701 }
1702
1703 if (new_owner != INVALID_OWNER) {
1704 SetTileOwner(tile, new_owner);
1705 } else {
1706 if (tt == TRANSPORT_RAIL) {
1707 /* Since all of our vehicles have been removed, it is safe to remove the rail
1708 * bridge / tunnel. */
1709 CommandCost ret = DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
1710 assert(ret.Succeeded());
1711 } else {
1712 /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
1713 SetTileOwner(tile, OWNER_NONE);
1714 }
1715 }
1716 }
1717
1723 static const byte TUNNEL_SOUND_FRAME = 1;
1724
1733 extern const byte _tunnel_visibility_frame[DIAGDIR_END] = {12, 8, 8, 12};
1734
1735 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
1736 {
1737 int z = GetSlopePixelZ(x, y) - v->z_pos;
1738
1739 if (abs(z) > 2) return VETSB_CANNOT_ENTER;
1740 /* Direction into the wormhole */
1741 const DiagDirection dir = GetTunnelBridgeDirection(tile);
1742 /* Direction of the vehicle */
1743 const DiagDirection vdir = DirToDiagDir(v->direction);
1744 /* New position of the vehicle on the tile */
1745 byte pos = (DiagDirToAxis(vdir) == AXIS_X ? x : y) & TILE_UNIT_MASK;
1746 /* Number of units moved by the vehicle since entering the tile */
1747 byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
1748
1749 if (IsTunnel(tile)) {
1750 if (v->type == VEH_TRAIN) {
1751 Train *t = Train::From(v);
1752
1753 if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
1754 if (t->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
1755 if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
1756 SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
1757 }
1758 return VETSB_CONTINUE;
1759 }
1760 if (frame == _tunnel_visibility_frame[dir]) {
1761 t->tile = tile;
1762 t->track = TRACK_BIT_WORMHOLE;
1763 t->vehstatus |= VS_HIDDEN;
1764 return VETSB_ENTERED_WORMHOLE;
1765 }
1766 }
1767
1768 if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
1769 /* We're at the tunnel exit ?? */
1770 t->tile = tile;
1771 t->track = DiagDirToDiagTrackBits(vdir);
1772 assert(t->track);
1773 t->vehstatus &= ~VS_HIDDEN;
1774 return VETSB_ENTERED_WORMHOLE;
1775 }
1776 } else if (v->type == VEH_ROAD) {
1777 RoadVehicle *rv = RoadVehicle::From(v);
1778
1779 /* Enter tunnel? */
1780 if (rv->state != RVSB_WORMHOLE && dir == vdir) {
1781 if (frame == _tunnel_visibility_frame[dir]) {
1782 /* Frame should be equal to the next frame number in the RV's movement */
1783 assert(frame == rv->frame + 1);
1784 rv->tile = tile;
1785 rv->state = RVSB_WORMHOLE;
1786 rv->vehstatus |= VS_HIDDEN;
1787 return VETSB_ENTERED_WORMHOLE;
1788 } else {
1789 return VETSB_CONTINUE;
1790 }
1791 }
1792
1793 /* We're at the tunnel exit ?? */
1794 if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
1795 rv->tile = tile;
1796 rv->state = DiagDirToDiagTrackdir(vdir);
1797 rv->frame = frame;
1798 rv->vehstatus &= ~VS_HIDDEN;
1799 return VETSB_ENTERED_WORMHOLE;
1800 }
1801 }
1802 } else { // IsBridge(tile)
1803 if (v->type != VEH_SHIP) {
1804 /* modify speed of vehicle */
1805 uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
1806
1807 if (v->type == VEH_ROAD) spd *= 2;
1808 Vehicle *first = v->First();
1809 first->cur_speed = min(first->cur_speed, spd);
1810 }
1811
1812 if (vdir == dir) {
1813 /* Vehicle enters bridge at the last frame inside this tile. */
1814 if (frame != TILE_SIZE - 1) return VETSB_CONTINUE;
1815 switch (v->type) {
1816 case VEH_TRAIN: {
1817 Train *t = Train::From(v);
1818 t->track = TRACK_BIT_WORMHOLE;
1819 ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
1820 ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
1821 break;
1822 }
1823
1824 case VEH_ROAD: {
1825 RoadVehicle *rv = RoadVehicle::From(v);
1826 rv->state = RVSB_WORMHOLE;
1827 /* There are no slopes inside bridges / tunnels. */
1828 ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
1829 ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
1830 break;
1831 }
1832
1833 case VEH_SHIP:
1834 Ship::From(v)->state = TRACK_BIT_WORMHOLE;
1835 break;
1836
1837 default: NOT_REACHED();
1838 }
1839 return VETSB_ENTERED_WORMHOLE;
1840 } else if (vdir == ReverseDiagDir(dir)) {
1841 v->tile = tile;
1842 switch (v->type) {
1843 case VEH_TRAIN: {
1844 Train *t = Train::From(v);
1845 if (t->track == TRACK_BIT_WORMHOLE) {
1846 t->track = DiagDirToDiagTrackBits(vdir);
1847 return VETSB_ENTERED_WORMHOLE;
1848 }
1849 break;
1850 }
1851
1852 case VEH_ROAD: {
1853 RoadVehicle *rv = RoadVehicle::From(v);
1854 if (rv->state == RVSB_WORMHOLE) {
1855 rv->state = DiagDirToDiagTrackdir(vdir);
1856 rv->frame = 0;
1857 return VETSB_ENTERED_WORMHOLE;
1858 }
1859 break;
1860 }
1861
1862 case VEH_SHIP: {
1863 Ship *ship = Ship::From(v);
1864 if (ship->state == TRACK_BIT_WORMHOLE) {
1865 ship->state = DiagDirToDiagTrackBits(vdir);
1866 return VETSB_ENTERED_WORMHOLE;
1867 }
1868 break;
1869 }
1870
1871 default: NOT_REACHED();
1872 }
1873 }
1874 }
1875 return VETSB_CONTINUE;
1876 }
1877
1878 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
1879 {
1880 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
1881 DiagDirection direction = GetTunnelBridgeDirection(tile);
1882 Axis axis = DiagDirToAxis(direction);
1883 CommandCost res;
1884 int z_old;
1885 Slope tileh_old = GetTileSlope(tile, &z_old);
1886
1887 /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
1888 if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
1889 CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
1890 res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
1891 } else {
1892 CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
1893 res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
1894 }
1895
1896 /* Surface slope is valid and remains unchanged? */
1897 if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
1898 }
1899
1900 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1901 }
1902
1903 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
1904 DrawTile_TunnelBridge, // draw_tile_proc
1905 GetSlopePixelZ_TunnelBridge, // get_slope_z_proc
1906 ClearTile_TunnelBridge, // clear_tile_proc
1907 NULL, // add_accepted_cargo_proc
1908 GetTileDesc_TunnelBridge, // get_tile_desc_proc
1909 GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
1910 NULL, // click_tile_proc
1911 NULL, // animate_tile_proc
1912 TileLoop_TunnelBridge, // tile_loop_proc
1913 ChangeTileOwner_TunnelBridge, // change_tile_owner_proc
1914 NULL, // add_produced_cargo_proc
1915 VehicleEnter_TunnelBridge, // vehicle_enter_tile_proc
1916 GetFoundation_TunnelBridge, // get_foundation_proc
1917 TerraformTile_TunnelBridge, // terraform_tile_proc
1918 };