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