Update readme and changelog for v1.27.0
[openttd-joker.git] / src / road_cmd.cpp
blob4024cc557f020b90d6b592f33d42a8e30948ced8
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file road_cmd.cpp Commands related to road tiles. */
12 #include "stdafx.h"
13 #include "cmd_helper.h"
14 #include "road_internal.h"
15 #include "viewport_func.h"
16 #include "command_func.h"
17 #include "pathfinder/yapf/yapf_cache.h"
18 #include "depot_base.h"
19 #include "newgrf.h"
20 #include "autoslope.h"
21 #include "tunnelbridge_map.h"
22 #include "strings_func.h"
23 #include "vehicle_func.h"
24 #include "sound_func.h"
25 #include "tunnelbridge.h"
26 #include "cheat_type.h"
27 #include "effectvehicle_func.h"
28 #include "effectvehicle_base.h"
29 #include "elrail_func.h"
30 #include "roadveh.h"
31 #include "town.h"
32 #include "company_base.h"
33 #include "core/random_func.hpp"
34 #include "newgrf_debug.h"
35 #include "newgrf_railtype.h"
36 #include "newgrf_roadtype.h"
37 #include "date_func.h"
38 #include "genworld.h"
39 #include "company_gui.h"
40 #include "road.h"
41 #include "road_func.h"
43 #include "table/strings.h"
44 #include "table/roadtypes.h"
46 #include "safeguards.h"
48 /** Helper type for lists/vectors of road vehicles */
49 typedef SmallVector<RoadVehicle *, 16> RoadVehicleList;
51 RoadtypeInfo _roadtypes[ROADTYPE_END][ROADSUBTYPE_END];
52 RoadTypeIdentifier _sorted_roadtypes[ROADTYPE_END][ROADSUBTYPE_END];
53 uint8 _sorted_roadtypes_size[ROADTYPE_END];
55 /**
56 * Reset all road type information to its default values.
58 void ResetRoadTypes()
60 static const RoadtypeInfo empty_roadtype = {
61 {0,0,0,0,0,0},
62 {0,0,0,0,0,0},
63 {0,0,0,0,0,0,0,0,0,{},{},0,{},{}},
64 ROADSUBTYPES_NONE, ROTFB_NONE, 0, 0, 0, 0,
65 RoadTypeLabelList(), 0, 0, ROADSUBTYPES_NONE, ROADSUBTYPES_NONE, 0,
66 {}, {} };
68 /* Road type */
69 assert_compile(lengthof(_original_roadtypes) <= lengthof(_roadtypes[ROADTYPE_ROAD]));
70 uint i = 0;
71 for (; i < lengthof(_original_roadtypes); i++) _roadtypes[ROADTYPE_ROAD][i] = _original_roadtypes[i];
72 for (; i < lengthof(_roadtypes[ROADTYPE_ROAD]); i++) _roadtypes[ROADTYPE_ROAD][i] = empty_roadtype;
74 /* Tram type */
75 assert_compile(lengthof(_original_tramtypes) <= lengthof(_roadtypes[ROADTYPE_TRAM]));
76 i = 0;
77 for (; i < lengthof(_original_tramtypes); i++) _roadtypes[ROADTYPE_TRAM][i] = _original_tramtypes[i];
78 for (; i < lengthof(_roadtypes[ROADTYPE_TRAM]); i++) _roadtypes[ROADTYPE_TRAM][i] = empty_roadtype;
81 void ResolveRoadTypeGUISprites(RoadtypeInfo *rti)
83 SpriteID cursors_base = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_CURSORS);
84 if (cursors_base != 0) {
85 rti->gui_sprites.build_x_road = cursors_base + 0;
86 rti->gui_sprites.build_y_road = cursors_base + 1;
87 rti->gui_sprites.auto_road = cursors_base + 2;
88 rti->gui_sprites.build_depot = cursors_base + 3;
89 rti->gui_sprites.build_tunnel = cursors_base + 4;
90 rti->gui_sprites.convert_road = cursors_base + 5;
91 rti->cursor.road_swne = cursors_base + 6;
92 rti->cursor.road_nwse = cursors_base + 7;
93 rti->cursor.autoroad = cursors_base + 8;
94 rti->cursor.depot = cursors_base + 9;
95 rti->cursor.tunnel = cursors_base + 10;
96 rti->cursor.convert_road = cursors_base + 11;
101 * Compare roadtypes based on their sorting order.
102 * @param first The roadtype to compare to.
103 * @param second The roadtype to compare.
104 * @return True iff the first should be sorted before the second.
106 static int CDECL CompareRoadTypes(const RoadTypeIdentifier *first, const RoadTypeIdentifier *second)
108 return GetRoadTypeInfo(*first)->sorting_order - GetRoadTypeInfo(*second)->sorting_order;
112 * Resolve sprites of custom road types
114 void InitRoadTypes()
116 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
117 for (RoadSubType rst = ROADSUBTYPE_BEGIN; rst != ROADSUBTYPE_END; rst++) {
118 RoadtypeInfo *rti = &_roadtypes[rt][rst];
119 ResolveRoadTypeGUISprites(rti);
122 _sorted_roadtypes_size[rt] = 0;
123 for (RoadSubType rst = ROADSUBTYPE_BEGIN; rst != ROADSUBTYPE_END; rst++) {
124 if (_roadtypes[rt][rst].label != 0) {
125 _sorted_roadtypes[rt][_sorted_roadtypes_size[rt]++] = RoadTypeIdentifier(rt, rst);
128 QSortT(_sorted_roadtypes[rt], _sorted_roadtypes_size[rt], CompareRoadTypes);
133 * Allocate a new road type label
135 RoadTypeIdentifier AllocateRoadType(RoadTypeLabel label, RoadType basetype)
137 RoadTypeIdentifier rtid;
139 rtid.basetype = INVALID_ROADTYPE;
140 rtid.subtype = INVALID_ROADSUBTYPE;
142 for (RoadSubType rt = ROADSUBTYPE_BEGIN; rt != ROADSUBTYPE_END; rt++) {
143 RoadtypeInfo *rti = &_roadtypes[basetype][rt];
145 if (rti->label == 0) {
146 /* Set up new road type */
147 *rti = (basetype == ROADTYPE_ROAD ? _original_roadtypes[ROADSUBTYPE_NORMAL] : _original_tramtypes[ROADSUBTYPE_NORMAL]);
148 rti->label = label;
149 rti->alternate_labels.Clear();
151 /* Make us compatible with ourself. */
152 rti->powered_roadtypes = (RoadSubTypes)(1 << rt);
154 /* We also introduce ourself. */
155 rti->introduces_roadtypes = (RoadSubTypes)(1 << rt);
157 /* Default sort order; order of allocation, but with some
158 * offsets so it's easier for NewGRF to pick a spot without
159 * changing the order of other (original) road types.
160 * The << is so you can place other roadtypes in between the
161 * other roadtypes, the 7 is to be able to place something
162 * before the first (default) road type. */
163 rti->sorting_order = rt << 4 | 7;
165 rtid.basetype = basetype;
166 rtid.subtype = rt;
168 return rtid;
172 return rtid;
176 * Verify whether a road vehicle is available.
177 * @return \c true if at least one road vehicle is available, \c false if not
179 bool RoadVehiclesAreBuilt()
181 const RoadVehicle *rv;
182 FOR_ALL_ROADVEHICLES(rv) return true;
184 return false;
187 /** Invalid RoadBits on slopes. */
188 extern const RoadBits _invalid_tileh_slopes_road[2][15] = {
189 /* The inverse of the mixable RoadBits on a leveled slope */
191 ROAD_NONE, // SLOPE_FLAT
192 ROAD_NE | ROAD_SE, // SLOPE_W
193 ROAD_NE | ROAD_NW, // SLOPE_S
195 ROAD_NE, // SLOPE_SW
196 ROAD_NW | ROAD_SW, // SLOPE_E
197 ROAD_NONE, // SLOPE_EW
199 ROAD_NW, // SLOPE_SE
200 ROAD_NONE, // SLOPE_WSE
201 ROAD_SE | ROAD_SW, // SLOPE_N
203 ROAD_SE, // SLOPE_NW
204 ROAD_NONE, // SLOPE_NS
205 ROAD_NONE, // SLOPE_ENW
207 ROAD_SW, // SLOPE_NE
208 ROAD_NONE, // SLOPE_SEN
209 ROAD_NONE // SLOPE_NWS
211 /* The inverse of the allowed straight roads on a slope
212 * (with and without a foundation). */
214 ROAD_NONE, // SLOPE_FLAT
215 ROAD_NONE, // SLOPE_W Foundation
216 ROAD_NONE, // SLOPE_S Foundation
218 ROAD_Y, // SLOPE_SW
219 ROAD_NONE, // SLOPE_E Foundation
220 ROAD_ALL, // SLOPE_EW
222 ROAD_X, // SLOPE_SE
223 ROAD_ALL, // SLOPE_WSE
224 ROAD_NONE, // SLOPE_N Foundation
226 ROAD_X, // SLOPE_NW
227 ROAD_ALL, // SLOPE_NS
228 ROAD_ALL, // SLOPE_ENW
230 ROAD_Y, // SLOPE_NE
231 ROAD_ALL, // SLOPE_SEN
232 ROAD_ALL // SLOPE_NW
236 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits);
239 * Is it allowed to remove the given road bits from the given tile?
240 * @param tile the tile to remove the road from
241 * @param remove the roadbits that are going to be removed
242 * @param owner the actual owner of the roadbits of the tile
243 * @param rt the road type to remove the bits from
244 * @param flags command flags
245 * @param town_check Shall the town rating checked/affected
246 * @return A succeeded command when it is allowed to remove the road bits, a failed command otherwise.
248 CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadType rt, DoCommandFlag flags, bool town_check)
250 if (_game_mode == GM_EDITOR || remove == ROAD_NONE) return CommandCost();
252 /* Water can always flood and towns can always remove "normal" road pieces.
253 * Towns are not be allowed to remove non "normal" road pieces, like tram
254 * tracks as that would result in trams that cannot turn. */
255 if (_current_company == OWNER_WATER ||
256 (rt == ROADTYPE_ROAD && !Company::IsValidID(_current_company))) return CommandCost();
258 /* Only do the special processing if the road is owned
259 * by a town */
260 if (owner != OWNER_TOWN) {
261 if (owner == OWNER_NONE) return CommandCost();
262 CommandCost ret = CheckOwnership(owner);
263 return ret;
266 if (!town_check) return CommandCost();
268 if (_cheats.magic_bulldozer.value) return CommandCost();
270 Town *t = ClosestTownFromTile(tile, UINT_MAX);
271 if (t == nullptr) return CommandCost();
273 /* check if you're allowed to remove the street owned by a town
274 * removal allowance depends on difficulty setting */
275 CommandCost ret = CheckforTownRating(flags, t, ROAD_REMOVE);
276 if (ret.Failed()) return ret;
278 /* Get a bitmask of which neighbouring roads has a tile */
279 RoadBits n = ROAD_NONE;
280 RoadBits present = GetAnyRoadBits(tile, rt);
281 if ((present & ROAD_NE) && (GetAnyRoadBits(TILE_ADDXY(tile, -1, 0), rt) & ROAD_SW)) n |= ROAD_NE;
282 if ((present & ROAD_SE) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, 1), rt) & ROAD_NW)) n |= ROAD_SE;
283 if ((present & ROAD_SW) && (GetAnyRoadBits(TILE_ADDXY(tile, 1, 0), rt) & ROAD_NE)) n |= ROAD_SW;
284 if ((present & ROAD_NW) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, -1), rt) & ROAD_SE)) n |= ROAD_NW;
286 int rating_decrease = RATING_ROAD_DOWN_STEP_EDGE;
287 /* If 0 or 1 bits are set in n, or if no bits that match the bits to remove,
288 * then allow it */
289 if (KillFirstBit(n) != ROAD_NONE && (n & remove) != ROAD_NONE) {
290 /* you can remove all kind of roads with extra dynamite */
291 if (!_settings_game.construction.extra_dynamite) {
292 SetDParam(0, t->index);
293 return CommandError(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
295 rating_decrease = RATING_ROAD_DOWN_STEP_INNER;
297 ChangeTownRating(t, rating_decrease, RATING_ROAD_MINIMUM, flags);
299 return CommandCost();
304 * Delete a piece of road.
305 * @param tile tile where to remove road from
306 * @param flags operation to perform
307 * @param pieces roadbits to remove
308 * @param rtid identifyer describing the roadtype to remove
309 * @param town_check should we check if the town allows removal?
311 static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits pieces, RoadTypeIdentifier rtid, bool town_check = true)
313 const RoadType rt = rtid.basetype;
314 const RoadTypes rts = GetRoadTypes(tile);
316 // The tile doesn't have the given road type.
317 if (!HasBit(rts, rtid.basetype)) return CommandError(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
319 switch (GetTileType(tile)) {
320 case MP_ROAD: {
321 CommandCost ret = EnsureNoVehicleOnGround(tile);
322 if (ret.Failed()) return ret;
323 break;
326 case MP_STATION: {
327 if (!IsDriveThroughStopTile(tile)) return CommandError();
329 CommandCost ret = EnsureNoVehicleOnGround(tile);
330 if (ret.Failed()) return ret;
331 break;
334 case MP_TUNNELBRIDGE: {
335 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return CommandError();
336 CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
337 if (ret.Failed()) return ret;
338 break;
341 default:
342 return CommandError();
345 CommandCost ret = CheckAllowRemoveRoad(tile, pieces, GetRoadOwner(tile, rt), rt, flags, town_check);
346 if (ret.Failed()) return ret;
348 if (!IsTileType(tile, MP_ROAD)) {
349 const bool custom_bridge_head = IsBridgeTile(tile) &&
350 HasBridgeFlatRamp(GetTileSlope(tile), DiagDirToAxis(GetTunnelBridgeDirection(tile))) &&
351 (_settings_game.construction.road_custom_bridge_heads || IsRoadCustomBridgeHead(tile));
353 // If it's the last roadtype, just clear the whole tile.
354 if (!custom_bridge_head && rts == RoadTypeToRoadTypes(rt)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
356 CommandCost cost(EXPENSES_CONSTRUCTION);
357 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
358 const RoadBits entrance_piece = DiagDirToRoadBits(GetTunnelBridgeDirection(tile));
359 const RoadBits axial_pieces = AxisToRoadBits(DiagDirToAxis(GetTunnelBridgeDirection(tile)));
360 const RoadBits existing = IsBridge(tile) ? GetCustomBridgeHeadRoadBits(tile, rt) : axial_pieces;
361 const RoadType other_rt = (rt == ROADTYPE_ROAD) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
363 // Handle case where we would otherwise leave a single bridge entrance piece.
364 if ((existing & ~pieces) == entrance_piece) {
365 pieces |= entrance_piece;
368 /* Removing any roadbit in the bridge axis removes the roadtype (that's the behaviour remove-long-roads needs) */
369 if ((existing & pieces) == ROAD_NONE) return CommandError(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
371 if (!custom_bridge_head) pieces |= axial_pieces;
373 const TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
374 const uint middle_len = GetTunnelBridgeLength(other_end, tile);
375 uint pieces_count = 0;
377 const RoadBits other_end_existing = IsBridge(other_end) ? GetCustomBridgeHeadRoadBits(other_end, rt) : axial_pieces;
378 RoadBits other_end_pieces = ROAD_NONE;
379 if (pieces & entrance_piece) {
380 other_end_pieces |= MirrorRoadBits(entrance_piece);
381 // If removing the other end entrance would only leave one piece, remove that too.
382 if (CountBits(other_end_existing & ~other_end_pieces) == 1) {
383 other_end_pieces |= other_end_existing;
385 pieces_count += middle_len * 2;
386 if (custom_bridge_head && ((GetCustomBridgeHeadRoadBits(tile, other_rt) & entrance_piece) == ROAD_NONE)) {
387 // Can't leave no entrance pieces for any road type.
388 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
391 pieces_count += CountBits(pieces & existing);
392 pieces_count += CountBits(other_end_pieces & other_end_existing);
393 cost.AddCost(pieces_count * _price[PR_CLEAR_ROAD]);
395 if (flags & DC_EXEC) {
396 SubtractRoadTunnelBridgeInfrastructure(tile, other_end);
398 const RoadBits bits = existing & ~pieces;
399 const RoadBits other_bits = other_end_existing & ~other_end_pieces;
401 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
402 RoadTypeIdentifiers other_rtids = RoadTypeIdentifiers::FromTile(other_end);
403 rtids.ClearRoadType(rt);
404 other_rtids.ClearRoadType(rt);
405 if (bits == ROAD_NONE) SetRoadTypes(tile, rtids);
406 if (other_bits == ROAD_NONE) SetRoadTypes(other_end, other_rtids);
408 if (IsBridge(tile)) {
409 SetCustomBridgeHeadRoadBits(tile, rt, bits);
410 SetCustomBridgeHeadRoadBits(other_end, rt, other_bits);
413 if (bits == ROAD_NONE && other_bits == ROAD_NONE) {
414 /* If the owner of the bridge sells all its road, also move the ownership
415 * to the owner of the other roadtype, unless the bridge owner is a town. */
416 Owner other_owner = GetRoadOwner(tile, other_rt);
417 if (!IsTileOwner(tile, other_owner) && !IsTileOwner(tile, OWNER_TOWN)) {
418 SetTileOwner(tile, other_owner);
419 SetTileOwner(other_end, other_owner);
423 /* Mark tiles dirty that have been repaved */
424 if (IsBridge(tile)) {
425 MarkBridgeDirty(tile);
426 } else {
427 MarkTileDirtyByTile(tile);
428 MarkTileDirtyByTile(other_end);
431 AddRoadTunnelBridgeInfrastructure(tile, other_end);
432 DirtyAllCompanyInfrastructureWindows();
434 } else {
435 assert(IsDriveThroughStopTile(tile));
436 cost.AddCost(_price[PR_CLEAR_ROAD] * 2);
438 if (flags & DC_EXEC) {
439 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
440 if (c != nullptr) {
441 /* A full diagonal road tile has two road bits. */
442 c->infrastructure.road[rtid.basetype][rtid.subtype] -= 2;
443 DirtyCompanyInfrastructureWindows(c->index);
445 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
446 rtids.ClearRoadType(rt);
447 SetRoadTypes(tile, rtids);
448 MarkTileDirtyByTile(tile);
451 return cost;
454 switch (GetRoadTileType(tile)) {
455 case ROAD_TILE_NORMAL: {
456 Slope tileh = GetTileSlope(tile);
458 /* Steep slopes behave the same as slopes with one corner raised. */
459 if (IsSteepSlope(tileh)) {
460 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
463 RoadBits present = GetRoadBits(tile, rt);
464 const RoadBits other = GetOtherRoadBits(tile, rt);
465 const Foundation f = GetRoadFoundation(tileh, present);
467 if (HasRoadWorks(tile) && _current_company != OWNER_WATER) return CommandError(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
469 /* Autocomplete to a straight road
470 * @li if the bits of the other roadtypes result in another foundation
471 * @li if build on slopes is disabled */
472 if ((IsStraightRoad(other) && (other & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) != ROAD_NONE) ||
473 (tileh != SLOPE_FLAT && !_settings_game.construction.build_on_slopes)) {
474 pieces |= MirrorRoadBits(pieces);
477 /* limit the bits to delete to the existing bits. */
478 pieces &= present;
479 if (pieces == ROAD_NONE) return CommandError(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
481 /* Now set present what it will be after the remove */
482 present ^= pieces;
484 /* Check for invalid RoadBit combinations on slopes */
485 if (tileh != SLOPE_FLAT && present != ROAD_NONE &&
486 (present & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) == present) {
487 return CommandError();
490 if (flags & DC_EXEC) {
491 if (HasRoadWorks(tile)) {
492 /* flooding tile with road works, don't forget to remove the effect vehicle too */
493 assert(_current_company == OWNER_WATER);
494 EffectVehicle *v;
495 FOR_ALL_EFFECTVEHICLES(v) {
496 if (TileVirtXY(v->x_pos, v->y_pos) == tile) {
497 delete v;
502 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
503 if (c != nullptr) {
504 c->infrastructure.road[rtid.basetype][rtid.subtype] -= CountBits(pieces);
505 DirtyCompanyInfrastructureWindows(c->index);
508 if (present == ROAD_NONE) {
509 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
510 rtids.ClearRoadType(rt);
511 if (rtids.PresentRoadTypes() == ROADTYPES_NONE) {
512 /* Includes MarkTileDirtyByTile() */
513 DoClearSquare(tile);
514 } else {
515 if (rt == ROADTYPE_ROAD && IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN)) {
516 /* Update nearest-town index */
517 const Town *town = CalcClosestTownFromTile(tile);
518 SetTownIndex(tile, town == nullptr ? (TownID)INVALID_TOWN : town->index);
520 SetRoadBits(tile, ROAD_NONE, rt);
521 SetRoadTypes(tile, rtids);
522 MarkTileDirtyByTile(tile);
524 } else {
525 /* When bits are removed, you *always* end up with something that
526 * is not a complete straight road tile. However, trams do not have
527 * onewayness, so they cannot remove it either. */
528 if (rt != ROADTYPE_TRAM) SetDisallowedRoadDirections(tile, DRD_NONE);
529 SetRoadBits(tile, present, rt);
530 MarkTileDirtyByTile(tile);
534 CommandCost cost(EXPENSES_CONSTRUCTION, CountBits(pieces) * _price[PR_CLEAR_ROAD]);
535 /* If we build a foundation we have to pay for it. */
536 if (f == FOUNDATION_NONE && GetRoadFoundation(tileh, present) != FOUNDATION_NONE) cost.AddCost(_price[PR_BUILD_FOUNDATION]);
538 return cost;
541 case ROAD_TILE_CROSSING: {
542 if (pieces & ComplementRoadBits(GetCrossingRoadBits(tile))) {
543 return CommandError();
546 if (flags & DC_EXEC) {
547 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
548 if (c != nullptr) {
549 /* A full diagonal road tile has two road bits. */
550 c->infrastructure.road[rtid.basetype][rtid.subtype] -= 2;
551 DirtyCompanyInfrastructureWindows(c->index);
554 Track railtrack = GetCrossingRailTrack(tile);
555 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
556 rtids.ClearRoadType(rt);
557 if (rtids.PresentRoadTypes() == ROADTYPES_NONE) {
558 TrackBits tracks = GetCrossingRailBits(tile);
559 bool reserved = HasCrossingReservation(tile);
560 MakeRailNormal(tile, GetTileOwner(tile), tracks, GetRailType(tile));
561 if (reserved) SetTrackReservation(tile, tracks);
563 /* Update rail count for level crossings. The plain track should still be accounted
564 * for, so only subtract the difference to the level crossing cost. */
565 c = Company::GetIfValid(GetTileOwner(tile));
566 if (c != nullptr) {
567 c->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
568 DirtyCompanyInfrastructureWindows(c->index);
570 } else {
571 SetRoadTypes(tile, rtids);
573 MarkTileDirtyByTile(tile);
574 YapfNotifyTrackLayoutChange(tile, railtrack);
576 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_ROAD] * 2);
579 default:
580 case ROAD_TILE_DEPOT:
581 return CommandError();
587 * Calculate the costs for roads on slopes
588 * Aside modify the RoadBits to fit on the slopes
590 * @note The RoadBits are modified too!
591 * @param tileh The current slope
592 * @param pieces The RoadBits we want to add
593 * @param existing The existent RoadBits of the current type
594 * @param other The other existent RoadBits
595 * @return The costs for these RoadBits on this slope
597 static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existing, RoadBits other)
599 /* Remove already build pieces */
600 CLRBITS(*pieces, existing);
602 /* If we can't build anything stop here */
603 if (*pieces == ROAD_NONE) return CommandError();
605 /* All RoadBit combos are valid on flat land */
606 if (tileh == SLOPE_FLAT) return CommandCost();
608 /* Steep slopes behave the same as slopes with one corner raised. */
609 if (IsSteepSlope(tileh)) {
610 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
613 /* Save the merge of all bits of the current type */
614 RoadBits type_bits = existing | *pieces;
616 /* Roads on slopes */
617 if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
619 /* If we add leveling we've got to pay for it */
620 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
622 return CommandCost();
625 /* Autocomplete uphill roads */
626 *pieces |= MirrorRoadBits(*pieces);
627 type_bits = existing | *pieces;
629 /* Uphill roads */
630 if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
631 (_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
633 /* Slopes with foundation ? */
634 if (IsSlopeWithOneCornerRaised(tileh)) {
636 /* Prevent build on slopes if it isn't allowed */
637 if (_settings_game.construction.build_on_slopes) {
639 /* If we add foundation we've got to pay for it */
640 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
642 return CommandCost();
644 } else {
645 if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
646 return CommandCost();
649 return CommandError();
653 * Build a piece of road.
654 * @param tile tile where to build road
655 * @param flags operation to perform
656 * @param p1 bit 0.. 3 road pieces to build (RoadBits)
657 * bit 4.. 9 road type
658 * bit 10..11 disallowed directions to toggle
659 * bit 12 disable custom bridge heads
660 * @param p2 the town that is building the road (0 if not applicable)
661 * @param text unused
662 * @return the cost of this operation or an error
664 CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char* text)
666 CompanyID company = _current_company;
667 CommandCost cost(EXPENSES_CONSTRUCTION);
669 RoadBits existing_bits = ROAD_NONE;
670 RoadBits other_bits = ROAD_NONE;
672 // Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
673 // if a non-company is building the road.
674 if ((Company::IsValidID(company) && p2 != 0) || (company == OWNER_TOWN && !Town::IsValidID(p2)) || (company == OWNER_DEITY && p2 != 0)) return CommandError();
675 if (company != OWNER_TOWN) {
676 const Town* town = CalcClosestTownFromTile(tile);
677 p2 = (town != nullptr) ? town->index : static_cast<TownID>(INVALID_TOWN);
679 if (company == OWNER_DEITY) {
680 company = OWNER_TOWN;
682 // If we are not within a town, we are not owned by the town.
683 if (town == nullptr || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
684 company = OWNER_NONE;
689 auto bits_to_build = Extract<RoadBits, 0, 4>(p1);
691 // Do not allow building 'zero' road bits, code wouldn't handle it.
692 if (bits_to_build == ROAD_NONE) return CommandError();
694 RoadTypeIdentifier rtid;
695 if (!rtid.UnpackIfValid(GB(p1, 4, 6))) return CommandError();
696 if (!ValParamRoadType(rtid)) return CommandError();
698 const auto disallowed_road_directions = Extract<DisallowedRoadDirections, 10, 2>(p1);
699 const bool disable_custom_bridge_heads = HasBit(p1, 12);
701 const Slope slope = GetTileSlope(tile);
703 bool need_to_clear = false;
704 switch (GetTileType(tile)) {
705 case MP_ROAD:
706 switch (GetRoadTileType(tile)) {
707 case ROAD_TILE_NORMAL: {
708 if (HasRoadWorks(tile)) return CommandError(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
710 other_bits = GetOtherRoadBits(tile, rtid.basetype);
712 if (!HasTileRoadType(tile, rtid.basetype)) break;
714 existing_bits = GetRoadBits(tile, rtid.basetype);
715 const bool crossing = !IsStraightRoad(existing_bits | bits_to_build);
717 if (rtid.IsRoad() && (GetDisallowedRoadDirections(tile) != DRD_NONE || disallowed_road_directions != DRD_NONE) && crossing) {
718 // Junctions cannot be one-way.
719 return CommandError(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
722 if ((existing_bits & bits_to_build) == bits_to_build) {
723 // We only want to set the (dis)allowed road directions.
724 if (disallowed_road_directions != DRD_NONE && rtid.IsRoad()) {
725 if (crossing) return CommandError(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
727 const Owner owner = GetRoadOwner(tile, ROADTYPE_ROAD);
729 if (owner != OWNER_NONE) {
730 CommandCost ret = CheckOwnership(owner, tile);
731 if (ret.Failed()) return ret;
734 const DisallowedRoadDirections dis_existing = GetDisallowedRoadDirections(tile);
735 const DisallowedRoadDirections dis_new = dis_existing ^ disallowed_road_directions;
737 // We allow removing disallowed directions to break up
738 // deadlocks, but adding them can break articulated
739 // vehicles. As such, only when less is disallowed,
740 // i.e. bits are removed, we skip the vehicle check.
741 if (CountBits(dis_existing) <= CountBits(dis_new)) {
742 CommandCost ret = EnsureNoVehicleOnGround(tile);
743 if (ret.Failed()) return ret;
746 // Ignore half built tiles.
747 if ((flags & DC_EXEC) && rtid.IsRoad() && IsStraightRoad(existing_bits)) {
748 SetDisallowedRoadDirections(tile, dis_new);
749 MarkTileDirtyByTile(tile);
752 return CommandCost();
755 return CommandError(STR_ERROR_ALREADY_BUILT);
758 // Disallow breaking end-of-line of someone else
759 // so trams can still reverse on this tile.
760 if (rtid.IsTram() && HasExactlyOneBit(existing_bits)) {
761 const Owner owner = GetRoadOwner(tile, rtid.basetype);
763 if (Company::IsValidID(owner)) {
764 CommandCost ret = CheckOwnership(owner);
765 if (ret.Failed()) return ret;
768 break;
771 case ROAD_TILE_CROSSING:
772 if (RoadNoLevelCrossing(rtid)) {
773 return CommandError(STR_ERROR_CROSSING_DISALLOWED_ROAD);
776 other_bits = GetCrossingRoadBits(tile);
777 if (bits_to_build & ComplementRoadBits(other_bits)) goto do_clear;
779 // We need to pay for both roadbits.
780 bits_to_build = other_bits;
782 if (HasTileRoadType(tile, rtid.basetype)) return CommandError(STR_ERROR_ALREADY_BUILT);
783 break;
785 case ROAD_TILE_DEPOT:
786 if ((GetAnyRoadBits(tile, rtid.basetype) & bits_to_build) == bits_to_build) return CommandError(STR_ERROR_ALREADY_BUILT);
787 goto do_clear;
789 default: NOT_REACHED();
791 break;
793 case MP_RAILWAY: {
794 if (IsSteepSlope(slope)) {
795 return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
798 /* Level crossings may only be built on these slopes */
799 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, slope)) {
800 return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
803 if (GetRailTileType(tile) != RAIL_TILE_NORMAL) goto do_clear;
805 if (RoadNoLevelCrossing(rtid)) {
806 return CommandError(STR_ERROR_CROSSING_DISALLOWED_ROAD);
809 if (RailNoLevelCrossings(GetRailType(tile))) {
810 return CommandError(STR_ERROR_CROSSING_DISALLOWED_RAIL);
813 Axis roaddir;
814 switch (GetTrackBits(tile)) {
815 case TRACK_BIT_X:
816 if (bits_to_build & ROAD_X) goto do_clear;
817 roaddir = AXIS_Y;
818 break;
820 case TRACK_BIT_Y:
821 if (bits_to_build & ROAD_Y) goto do_clear;
822 roaddir = AXIS_X;
823 break;
825 default: goto do_clear;
828 CommandCost ret = EnsureNoVehicleOnGround(tile);
829 if (ret.Failed()) return ret;
831 if (flags & DC_EXEC) {
832 Track railtrack = AxisToTrack(OtherAxis(roaddir));
833 YapfNotifyTrackLayoutChange(tile, railtrack);
834 /* Update company infrastructure counts. A level crossing has two road bits. */
835 Company *c = Company::GetIfValid(company);
836 if (c != nullptr) {
837 c->infrastructure.road[rtid.basetype][rtid.subtype] += 2;
838 DirtyCompanyInfrastructureWindows(company);
840 /* Update rail count for level crossings. The plain track is already
841 * counted, so only add the difference to the level crossing cost. */
842 c = Company::GetIfValid(GetTileOwner(tile));
843 if (c != nullptr) {
844 c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
845 DirtyCompanyInfrastructureWindows(c->index);
848 /* Always add road to the roadtypes (can't draw without it) */
849 bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
850 MakeRoadCrossing(tile, company, company, GetTileOwner(tile), roaddir, GetRailType(tile), RoadTypeIdentifiers::FromRoadTypeIdentifier(rtid), p2);
851 SetCrossingReservation(tile, reserved);
852 UpdateLevelCrossing(tile, false);
853 MarkTileDirtyByTile(tile);
855 return CommandCost(EXPENSES_CONSTRUCTION, 2 * RoadBuildCost(rtid));
858 case MP_STATION: {
859 if ((GetAnyRoadBits(tile, rtid.basetype) & bits_to_build) == bits_to_build) return CommandError(STR_ERROR_ALREADY_BUILT);
860 if (!IsDriveThroughStopTile(tile)) goto do_clear;
862 RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
863 if (bits_to_build & ~curbits) goto do_clear;
864 bits_to_build = curbits; // we need to pay for both roadbits
866 if (HasTileRoadType(tile, rtid.basetype)) return CommandError(STR_ERROR_ALREADY_BUILT);
867 break;
870 case MP_TUNNELBRIDGE: {
871 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
873 const TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
875 if (IsBridge(tile)) {
876 const DiagDirection entrance_dir = GetTunnelBridgeDirection(tile);
877 const RoadBits entrance_piece = DiagDirToRoadBits(entrance_dir);
878 const RoadBits axial_pieces = AxisToRoadBits(DiagDirToAxis(entrance_dir));
879 existing_bits = GetCustomBridgeHeadRoadBits(tile, rtid.basetype);
881 if (!(_settings_game.construction.road_custom_bridge_heads && HasBridgeFlatRamp(slope, DiagDirToAxis(entrance_dir))) || disable_custom_bridge_heads) {
882 // Ordinary bridge heads only
883 // Only allow building the outer roadbit, so building long roads stops at existing bridges.
884 if (MirrorRoadBits(entrance_piece) != bits_to_build) goto do_clear;
885 bits_to_build = axial_pieces;
888 if ((existing_bits & bits_to_build) == bits_to_build) return CommandError(STR_ERROR_ALREADY_BUILT);
890 if ((bits_to_build & ~axial_pieces) && !_settings_game.construction.build_on_slopes) {
891 return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
894 // Steep slopes behave the same as slopes with one corner raised.
895 const Slope normalised_tileh = IsSteepSlope(slope) ? SlopeWithOneCornerRaised(GetHighestSlopeCorner(slope)) : slope;
897 if ((_invalid_tileh_slopes_road[0][normalised_tileh & SLOPE_ELEVATED] & (bits_to_build & ~entrance_piece)) != ROAD_NONE) {
898 return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
901 // Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it.
902 CommandCost ret = TunnelBridgeIsFree(tile, other_end);
903 if (ret.Failed()) return ret;
905 if ((existing_bits | bits_to_build) == entrance_piece) {
906 // Don't allow the custom bridge head bits to be only the entrance piece
907 // as this makes road vehicles go haywire
908 bits_to_build = axial_pieces;
911 const RoadBits added_pieces = (existing_bits | bits_to_build) & ~existing_bits;
912 uint added_pieces_count = CountBits(added_pieces);
913 RoadBits other_end_added_pieces = ROAD_NONE;
914 RoadBits other_end_existing = ROAD_NONE;
916 if (added_pieces & entrance_piece) {
917 // adding road to whole bridge.
919 other_end_added_pieces = MirrorRoadBits(entrance_piece);
920 added_pieces_count += 1 + (GetTunnelBridgeLength(tile, other_end) * 2);
922 other_end_existing = GetCustomBridgeHeadRoadBits(other_end, rtid.basetype);
923 assert((other_end_added_pieces & other_end_existing) == ROAD_NONE);
925 if (other_end_existing == ROAD_NONE) {
926 // Don't allow the other end custom bridge head bits to be only the entrance piece
927 // as this makes road vehicles go haywire
928 other_end_added_pieces = axial_pieces;
929 added_pieces_count++;
933 cost.AddCost(added_pieces_count * _price[PR_BUILD_ROAD]);
935 if (flags & DC_EXEC) {
936 SubtractRoadTunnelBridgeInfrastructure(tile, other_end);
938 auto tile_rtids = RoadTypeIdentifiers::FromTile(tile);
939 tile_rtids.MergeRoadType(rtid);
940 SetRoadTypes(tile, tile_rtids);
942 if (!existing_bits) {
943 SetRoadOwner(tile, rtid.basetype, company);
946 SetCustomBridgeHeadRoadBits(tile, rtid.basetype, existing_bits | bits_to_build);
948 if (other_end_added_pieces) {
950 auto other_rtids = RoadTypeIdentifiers::FromTile(other_end);
951 other_rtids.MergeRoadType(rtid);
952 SetRoadTypes(other_end, other_rtids);
954 if (!other_end_existing) {
955 SetRoadOwner(other_end, rtid.basetype, company);
958 SetCustomBridgeHeadRoadBits(other_end, rtid.basetype, other_end_existing | other_end_added_pieces);
961 MarkBridgeDirty(tile);
963 AddRoadTunnelBridgeInfrastructure(tile, other_end);
964 DirtyAllCompanyInfrastructureWindows();
967 return cost;
968 } else { // IsTunnel(tile)
969 /* Only allow building the outer roadbit, so building long roads stops at existing bridges */
970 if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != bits_to_build) goto do_clear;
971 if (HasTileRoadType(tile, rtid.basetype)) return CommandError(STR_ERROR_ALREADY_BUILT);
972 /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
973 CommandCost ret = TunnelBridgeIsFree(tile, other_end);
974 if (ret.Failed()) return ret;
976 break;
979 default: {
980 do_clear:;
981 need_to_clear = true;
982 break;
986 if (need_to_clear) {
987 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
988 if (ret.Failed()) return ret;
989 cost.AddCost(ret);
992 if (other_bits != bits_to_build) {
993 /* Check the foundation/slopes when adding road/tram bits */
994 CommandCost ret = CheckRoadSlope(slope, &bits_to_build, existing_bits, other_bits);
995 /* Return an error if we need to build a foundation (ret != 0) but the
996 * current setting is turned off */
997 if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
998 return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
1000 cost.AddCost(ret);
1003 if (!need_to_clear) {
1004 if (IsTileType(tile, MP_ROAD)) {
1005 /* Don't put the pieces that already exist */
1006 bits_to_build &= ComplementRoadBits(existing_bits);
1008 /* Check if new road bits will have the same foundation as other existing road types */
1009 if (IsNormalRoad(tile)) {
1010 Slope slope = GetTileSlope(tile);
1011 Foundation found_new = GetRoadFoundation(slope, bits_to_build | existing_bits);
1013 /* Test if all other roadtypes can be built at that foundation */
1014 for (RoadType rtest = ROADTYPE_ROAD; rtest < ROADTYPE_END; rtest++) {
1015 if (rtest != rtid.basetype) { // check only other road types
1016 RoadBits bits = GetRoadBits(tile, rtest);
1017 /* do not check if there are not road bits of given type */
1018 if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
1019 return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
1026 CommandCost ret = EnsureNoVehicleOnGround(tile);
1027 if (ret.Failed()) return ret;
1029 if (IsNormalRoadTile(tile)) {
1030 /* If the road types don't match, try to convert only if vehicles of
1031 * the new road type are not powered on the present road type and vehicles of
1032 * the present road type are powered on the new road type. */
1033 RoadTypeIdentifier existing_rtid = GetRoadType(tile, rtid.basetype);
1034 if (existing_rtid.IsValid() && existing_rtid != rtid) {
1035 if (HasPowerOnRoad(rtid, existing_rtid)) {
1036 rtid = existing_rtid;
1037 } else if (HasPowerOnRoad(existing_rtid, rtid)) {
1038 CommandCost ret = DoCommand(tile, tile, rtid.Pack(), flags, CMD_CONVERT_ROAD);
1039 if (ret.Failed()) return ret;
1040 cost.AddCost(ret);
1041 } else {
1042 return CommandError();
1048 uint num_pieces = (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) ?
1049 /* There are 2 pieces on *every* tile of the bridge or tunnel */
1050 2 * (GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2) :
1051 /* Count pieces */
1052 CountBits(bits_to_build);
1054 cost.AddCost(num_pieces * RoadBuildCost(rtid));
1056 if (flags & DC_EXEC) {
1057 switch (GetTileType(tile)) {
1058 case MP_ROAD: {
1059 RoadTileType rtt = GetRoadTileType(tile);
1060 if (existing_bits == ROAD_NONE || rtt == ROAD_TILE_CROSSING) {
1061 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
1062 rtids.MergeRoadType(rtid);
1063 SetRoadTypes(tile, rtids);
1065 SetRoadOwner(tile, rtid.basetype, company);
1066 if (rtid.IsRoad()) SetTownIndex(tile, p2);
1068 if (rtt != ROAD_TILE_CROSSING) SetRoadBits(tile, existing_bits | bits_to_build, rtid.basetype);
1069 break;
1072 case MP_TUNNELBRIDGE: {
1073 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
1075 RoadTypeIdentifiers other_rtids = RoadTypeIdentifiers::FromTile(other_end);
1076 other_rtids.MergeRoadType(rtid);
1077 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
1078 rtids.MergeRoadType(rtid);
1079 SetRoadTypes(other_end, other_rtids);
1080 SetRoadTypes(tile, rtids);
1081 SetRoadOwner(other_end, rtid.basetype, company);
1082 SetRoadOwner(tile, rtid.basetype, company);
1084 /* Mark tiles dirty that have been repaved */
1085 if (IsBridge(tile)) {
1086 NOT_REACHED();
1087 } else {
1088 MarkTileDirtyByTile(other_end);
1089 MarkTileDirtyByTile(tile);
1091 break;
1094 case MP_STATION: {
1095 assert(IsDriveThroughStopTile(tile));
1096 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
1097 rtids.MergeRoadType(rtid);
1098 SetRoadTypes(tile, rtids);
1099 SetRoadOwner(tile, rtid.basetype, company);
1100 break;
1103 default:
1104 MakeRoadNormal(tile, bits_to_build, RoadTypeIdentifiers::FromRoadTypeIdentifier(rtid), p2, company, company);
1105 break;
1108 /* Update company infrastructure count. */
1109 Company *c = Company::GetIfValid(GetRoadOwner(tile, rtid.basetype));
1110 if (c != nullptr) {
1111 if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
1112 c->infrastructure.road[rtid.basetype][rtid.subtype] += num_pieces;
1113 DirtyCompanyInfrastructureWindows(c->index);
1116 if (rtid.IsRoad() && IsNormalRoadTile(tile)) {
1117 existing_bits |= bits_to_build;
1118 SetDisallowedRoadDirections(tile, IsStraightRoad(existing_bits) ?
1119 GetDisallowedRoadDirections(tile) ^ disallowed_road_directions : DRD_NONE);
1122 MarkTileDirtyByTile(tile);
1124 return cost;
1128 * Checks whether a road or tram connection can be found when building a new road or tram.
1129 * @param tile Tile at which the road being built will end.
1130 * @param rt Roadtype of the road being built.
1131 * @param dir Direction that the road is following.
1132 * @return True if the next tile at dir direction is suitable for being connected directly by a second roadbit at the end of the road being built.
1134 static bool CanConnectToRoad(TileIndex tile, RoadType rt, DiagDirection dir)
1136 RoadBits bits = GetAnyRoadBits(tile + TileOffsByDiagDir(dir), rt, false);
1137 return (bits & DiagDirToRoadBits(ReverseDiagDir(dir))) != 0;
1141 * Build a long piece of road.
1142 * @param start_tile start tile of drag (the building cost will appear over this tile)
1143 * @param flags operation to perform
1144 * @param p1 end tile of drag
1145 * @param p2 various bitstuffed elements
1146 * - p2 = (bit 0) - start tile starts in the 2nd half of tile (p2 & 1). Only used if bit 6 is set or if we are building a single tile
1147 * - p2 = (bit 1) - end tile starts in the 2nd half of tile (p2 & 2). Only used if bit 6 is set or if we are building a single tile
1148 * - p2 = (bit 2) - direction: 0 = along x-axis, 1 = along y-axis (p2 & 4)
1149 * - p2 = (bit 3..8) - road type identifier
1150 * - p2 = (bit 9) - set road direction
1151 * - p2 = (bit 10) - defines two different behaviors for this command:
1152 * - 0 = Build up to an obstacle. Do not build the first and last roadbits unless they can be connected to something, or if we are building a single tile
1153 * - 1 = Fail if an obstacle is found. Always take into account bit 0 and 1. Disable custom bridge heads. This behavior is used for scripts
1154 * @param text unused
1155 * @return the cost of this operation or an error
1157 CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1159 DisallowedRoadDirections drd = DRD_NORTHBOUND;
1161 if (p1 >= MapSize()) return CommandError();
1163 TileIndex end_tile = p1;
1164 RoadTypeIdentifier rtid;
1165 if (!rtid.UnpackIfValid(GB(p2, 3, 6))) return CommandError();
1166 if (!ValParamRoadType(rtid)) return CommandError();
1168 Axis axis = Extract<Axis, 2, 1>(p2);
1169 /* Only drag in X or Y direction dictated by the direction variable */
1170 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CommandError(); // x-axis
1171 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CommandError(); // y-axis
1173 DiagDirection dir = AxisToDiagDir(axis);
1175 /* Swap direction, also the half-tile drag var (bit 0 and 1) */
1176 if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
1177 dir = ReverseDiagDir(dir);
1178 p2 ^= 3;
1179 drd = DRD_SOUTHBOUND;
1182 /* On the X-axis, we have to swap the initial bits, so they
1183 * will be interpreted correctly in the GTTS. Furthermore
1184 * when you just 'click' on one tile to build them. */
1185 if ((axis == AXIS_Y) == (start_tile == end_tile && HasBit(p2, 0) == HasBit(p2, 1))) drd ^= DRD_BOTH;
1186 /* No disallowed direction bits have to be toggled */
1187 if (!HasBit(p2, 9)) drd = DRD_NONE;
1189 CommandCost cost(EXPENSES_CONSTRUCTION);
1190 CommandCost last_error = CommandError();
1191 TileIndex tile = start_tile;
1192 bool had_success = false;
1193 bool is_ai = HasBit(p2, 10);
1195 /* Start tile is the first tile clicked by the user. */
1196 for (;;) {
1197 RoadBits bits = AxisToRoadBits(axis);
1199 /* Determine which road parts should be built. */
1200 if (!is_ai && start_tile != end_tile) {
1201 /* Only build the first and last roadbit if they can connect to something. */
1202 if (tile == end_tile && !CanConnectToRoad(tile, rtid.basetype, dir)) { // TODO
1203 bits = DiagDirToRoadBits(ReverseDiagDir(dir));
1204 } else if (tile == start_tile && !CanConnectToRoad(tile, rtid.basetype, ReverseDiagDir(dir))) { // TODO
1205 bits = DiagDirToRoadBits(dir);
1207 } else {
1208 /* Road parts only have to be built at the start tile or at the end tile. */
1209 if (tile == end_tile && !HasBit(p2, 1)) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
1210 if (tile == start_tile && HasBit(p2, 0)) bits &= DiagDirToRoadBits(dir);
1213 CommandCost ret = DoCommand(tile, (is_ai ? 1 << 12 : 0) | drd << 10 | rtid.Pack() << 4 | bits, 0, flags, CMD_BUILD_ROAD);
1214 if (ret.Failed()) {
1215 last_error = ret;
1216 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
1217 if (is_ai) return last_error;
1218 break;
1220 } else {
1221 had_success = true;
1222 cost.AddCost(ret);
1225 /* Do not run into or across bridges/tunnels */
1226 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1227 if (GetTunnelBridgeDirection(tile) == dir) break;
1230 if (tile == end_tile) break;
1232 tile += TileOffsByDiagDir(dir);
1234 /* Do not run onto a bridge/tunnel tile from below/above */
1235 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1236 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) break;
1240 return had_success ? cost : last_error;
1244 * Remove a long piece of road.
1245 * RoadSubType is ignored, each roadtype can remove all its subtypes
1246 * @param start_tile start tile of drag
1247 * @param flags operation to perform
1248 * @param p1 end tile of drag
1249 * @param p2 various bitstuffed elements
1250 * - p2 = (bit 0) - start tile starts in the 2nd half of tile (p2 & 1)
1251 * - p2 = (bit 1) - end tile starts in the 2nd half of tile (p2 & 2)
1252 * - p2 = (bit 2) - direction: 0 = along x-axis, 1 = along y-axis (p2 & 4)
1253 * - p2 = (bit 3 - 8) - road type
1254 * @param text unused
1255 * @return the cost of this operation or an error
1257 CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1259 CommandCost cost(EXPENSES_CONSTRUCTION);
1261 if (p1 >= MapSize()) return CommandError();
1263 TileIndex end_tile = p1;
1264 RoadTypeIdentifier rtid;
1265 if (!rtid.UnpackIfValid(GB(p2, 3, 6))) return CommandError();
1267 Axis axis = Extract<Axis, 2, 1>(p2);
1268 /* Only drag in X or Y direction dictated by the direction variable */
1269 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CommandError(); // x-axis
1270 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CommandError(); // y-axis
1272 /* Swap start and ending tile, also the half-tile drag var (bit 0 and 1) */
1273 if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
1274 TileIndex t = start_tile;
1275 start_tile = end_tile;
1276 end_tile = t;
1277 p2 ^= IsInsideMM(p2 & 3, 1, 3) ? 3 : 0;
1280 Money money = GetAvailableMoneyForCommand();
1281 TileIndex tile = start_tile;
1282 CommandCost last_error = CommandError();
1283 bool had_success = false;
1284 /* Start tile is the small number. */
1285 for (;;) {
1286 RoadBits bits = AxisToRoadBits(axis);
1288 if (tile == end_tile && !HasBit(p2, 1)) bits &= ROAD_NW | ROAD_NE;
1289 if (tile == start_tile && HasBit(p2, 0)) bits &= ROAD_SE | ROAD_SW;
1291 /* try to remove the halves. */
1292 if (bits != 0) {
1293 CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rtid);
1294 if (ret.Succeeded()) {
1295 if (flags & DC_EXEC) {
1296 money -= ret.GetCost();
1297 if (money < 0) {
1298 _additional_cash_required = DoCommand(start_tile, end_tile, p2, flags & ~DC_EXEC, CMD_REMOVE_LONG_ROAD).GetCost();
1299 return cost;
1301 RemoveRoad(tile, flags, bits, rtid, false);
1303 cost.AddCost(ret);
1304 had_success = true;
1305 } else {
1306 /* Ownership errors are more important. */
1307 if (last_error.GetErrorMessage() != STR_ERROR_OWNED_BY) last_error = ret;
1311 if (tile == end_tile) break;
1313 tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
1316 return had_success ? cost : last_error;
1320 * Build a road depot.
1321 * @param tile tile where to build the depot
1322 * @param flags operation to perform
1323 * @param p1 bit 0..1 entrance direction (DiagDirection)
1324 * bit 2..7 road type identifier
1325 * @param p2 unused
1326 * @param text unused
1327 * @return the cost of this operation or an error
1329 * @todo When checking for the tile slope,
1330 * distinguish between "Flat land required" and "land sloped in wrong direction"
1332 CommandCost CmdBuildRoadDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1334 DiagDirection dir = Extract<DiagDirection, 0, 2>(p1);
1336 RoadTypeIdentifier rtid;
1337 if (!rtid.UnpackIfValid(GB(p1, 2, 6))) return CommandError();
1338 if (!ValParamRoadType(rtid)) return CommandError();
1340 Slope tileh = GetTileSlope(tile);
1341 if (tileh != SLOPE_FLAT && (
1342 !_settings_game.construction.build_on_slopes ||
1343 !CanBuildDepotByTileh(dir, tileh)
1344 )) {
1345 return CommandError(STR_ERROR_FLAT_LAND_REQUIRED);
1348 CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1349 if (cost.Failed()) return cost;
1351 if (IsBridgeAbove(tile)) return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1353 if (!Depot::CanAllocateItem()) return CommandError();
1355 if (flags & DC_EXEC) {
1356 Depot *dep = new Depot(tile);
1357 dep->build_date = _date;
1359 /* A road depot has two road bits. */
1360 Company::Get(_current_company)->infrastructure.road[rtid.basetype][rtid.subtype] += 2;
1361 DirtyCompanyInfrastructureWindows(_current_company);
1363 MakeRoadDepot(tile, _current_company, dep->index, dir, rtid);
1364 MarkTileDirtyByTile(tile);
1365 MakeDefaultName(dep);
1367 cost.AddCost(_price[PR_BUILD_DEPOT_ROAD]);
1368 return cost;
1371 static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
1373 if (_current_company != OWNER_WATER) {
1374 CommandCost ret = CheckTileOwnership(tile);
1375 if (ret.Failed()) return ret;
1378 CommandCost ret = EnsureNoVehicleOnGround(tile);
1379 if (ret.Failed()) return ret;
1381 if (flags & DC_EXEC) {
1382 Company *c = Company::GetIfValid(GetTileOwner(tile));
1383 if (c != nullptr) {
1384 /* A road depot has two road bits. */
1385 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
1386 RoadTypeIdentifier rtid = rtids.HasRoad() ? rtids.road_identifier : rtids.tram_identifier;
1387 c->infrastructure.road[rtid.basetype][rtid.subtype] -= 2;
1388 DirtyCompanyInfrastructureWindows(c->index);
1391 delete Depot::GetByTile(tile);
1392 DoClearSquare(tile);
1395 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_ROAD]);
1398 static CommandCost ClearTile_Road(TileIndex tile, DoCommandFlag flags)
1400 switch (GetRoadTileType(tile)) {
1401 case ROAD_TILE_NORMAL: {
1402 RoadBits b = GetAllRoadBits(tile);
1404 /* Clear the road if only one piece is on the tile OR we are not using the DC_AUTO flag */
1405 if ((HasExactlyOneBit(b) && GetRoadBits(tile, ROADTYPE_TRAM) == ROAD_NONE) || !(flags & DC_AUTO)) {
1406 CommandCost ret(EXPENSES_CONSTRUCTION);
1407 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
1408 RoadTypeIdentifier rtid;
1409 FOR_EACH_SET_ROADTYPEIDENTIFIER(rtid, rtids) {
1410 CommandCost tmp_ret = RemoveRoad(tile, flags, GetRoadBits(tile, rtid.basetype), rtid);
1411 if (tmp_ret.Failed()) return tmp_ret;
1412 ret.AddCost(tmp_ret);
1414 return ret;
1416 return CommandError(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1419 case ROAD_TILE_CROSSING: {
1420 RoadTypes rts = GetRoadTypes(tile);
1421 CommandCost ret(EXPENSES_CONSTRUCTION);
1423 if (flags & DC_AUTO) return CommandError(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1425 /* Must iterate over the roadtypes in a reverse manner because
1426 * tram tracks must be removed before the road bits. */
1427 RoadType rt = ROADTYPE_TRAM;
1428 RoadTypeIdentifier rtid;
1429 do {
1430 if (HasBit(rts, rt)) {
1431 rtid.basetype = rt;
1432 CommandCost tmp_ret = RemoveRoad(tile, flags, GetCrossingRoadBits(tile), rtid);
1433 if (tmp_ret.Failed()) return tmp_ret;
1434 ret.AddCost(tmp_ret);
1436 } while (rt-- != ROADTYPE_ROAD);
1438 if (flags & DC_EXEC) {
1439 DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1441 return ret;
1444 default:
1445 case ROAD_TILE_DEPOT:
1446 if (flags & DC_AUTO) {
1447 return CommandError(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1449 return RemoveRoadDepot(tile, flags);
1454 struct DrawRoadTileStruct {
1455 uint16 image;
1456 byte subcoord_x;
1457 byte subcoord_y;
1460 #include "table/road_land.h"
1463 * Get the foundationtype of a RoadBits Slope combination
1465 * @param tileh The Slope part
1466 * @param bits The RoadBits part
1467 * @return The resulting Foundation
1469 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
1471 /* Flat land and land without a road doesn't require a foundation */
1472 if (tileh == SLOPE_FLAT || bits == ROAD_NONE) return FOUNDATION_NONE;
1474 /* Steep slopes behave the same as slopes with one corner raised. */
1475 if (IsSteepSlope(tileh)) {
1476 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
1479 /* Leveled RoadBits on a slope */
1480 if ((_invalid_tileh_slopes_road[0][tileh] & bits) == ROAD_NONE) return FOUNDATION_LEVELED;
1482 /* Straight roads without foundation on a slope */
1483 if (!IsSlopeWithOneCornerRaised(tileh) &&
1484 (_invalid_tileh_slopes_road[1][tileh] & bits) == ROAD_NONE)
1485 return FOUNDATION_NONE;
1487 /* Roads on steep Slopes or on Slopes with one corner raised */
1488 return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
1491 const byte _road_sloped_sprites[14] = {
1492 0, 0, 2, 0,
1493 0, 1, 0, 0,
1494 3, 0, 0, 0,
1495 0, 0
1499 * Get the sprite offset within a spritegroup.
1500 * @param slope Slope
1501 * @param bits Roadbits
1502 * @return Offset for the sprite within the spritegroup.
1504 static uint GetRoadSpriteOffset(Slope slope, RoadBits bits)
1506 if (slope != SLOPE_FLAT) {
1507 switch (slope) {
1508 case SLOPE_NE: return 11;
1509 case SLOPE_SE: return 12;
1510 case SLOPE_SW: return 13;
1511 case SLOPE_NW: return 14;
1512 default: NOT_REACHED();
1514 } else {
1515 static const uint offsets[] = {
1516 0, 18, 17, 7,
1517 16, 0, 10, 5,
1518 15, 8, 1, 4,
1519 9, 3, 6, 2
1521 return offsets[bits];
1526 * Should the road be drawn as a unpaved snow/desert road?
1527 * By default, roads are always drawn as unpaved if they are on desert or
1528 * above the snow line, but NewGRFs can override this for desert.
1530 * @param tile The tile the road is on
1531 * @param roadside What sort of road this is
1532 * @return True if snow/desert road sprites should be used.
1534 static bool DrawRoadAsSnowDesert(TileIndex tile, Roadside roadside)
1536 return (IsOnSnow(tile) &&
1537 !(_settings_game.game_creation.landscape == LT_TROPIC && HasGrfMiscBit(GMB_DESERT_PAVED_ROADS) &&
1538 roadside != ROADSIDE_BARREN && roadside != ROADSIDE_GRASS && roadside != ROADSIDE_GRASS_ROAD_WORKS));
1542 * Draws the catenary for the RoadType of the given tile
1543 * @param ti information about the tile (slopes, height etc)
1544 * @param rtid road type to draw catenary for
1545 * @param rb the roadbits for the tram
1547 void DrawRoadTypeCatenary(const TileInfo *ti, RoadTypeIdentifier rtid, RoadBits rb)
1549 /* Don't draw the catenary under a low bridge */
1550 if (IsBridgeAbove(ti->tile) && !IsTransparencySet(TO_CATENARY)) {
1551 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1553 if (height <= GetTileMaxZ(ti->tile) + 1) return;
1556 if (CountBits(rb) > 2) {
1557 /* On junctions we check whether neighbouring tiles also have catenary, and possibly
1558 * do not draw catenary towards those neighbours, which do not have catenary. */
1559 RoadBits rb_new = ROAD_NONE;
1560 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1561 if (rb & DiagDirToRoadBits(dir)) {
1562 TileIndex neighbour = TileAddByDiagDir(ti->tile, dir);
1563 if (MayHaveRoad(neighbour)) {
1564 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(neighbour);
1565 if ((rtids.HasRoad() && HasRoadCatenary(rtids.road_identifier)) ||
1566 (rtids.HasTram() && HasRoadCatenary(rtids.tram_identifier))) {
1567 rb_new |= DiagDirToRoadBits(dir);
1572 if (CountBits(rb_new) >= 2) rb = rb_new;
1575 const RoadtypeInfo* rti = GetRoadTypeInfo(rtid);
1576 SpriteID front = GetCustomRoadSprite(rti, ti->tile, ROTSG_CATENARY_FRONT);
1577 SpriteID back = GetCustomRoadSprite(rti, ti->tile, ROTSG_CATENARY_BACK);
1579 if (front != 0 || back != 0) {
1580 if (front != 0) front += GetRoadSpriteOffset(ti->tileh, rb);
1581 if (back != 0) back += GetRoadSpriteOffset(ti->tileh, rb);
1582 } else if (ti->tileh != SLOPE_FLAT) {
1583 back = SPR_TRAMWAY_BACK_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1584 front = SPR_TRAMWAY_FRONT_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1585 } else {
1586 back = SPR_TRAMWAY_BASE + _road_backpole_sprites_1[rb];
1587 front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[rb];
1590 /* Catenary uses 1st company colour to help identify owner.
1591 * For tiles with OWNER_TOWN or OWNER_NONE, recolour CC to grey as a neutral colour. */
1592 Owner owner = GetRoadOwner(ti->tile, rtid.basetype);
1593 PaletteID pal = (owner == OWNER_NONE || owner == OWNER_TOWN ? GENERAL_SPRITE_COLOUR(COLOUR_GREY) : COMPANY_SPRITE_COLOUR(owner));
1594 if (back != 0) AddSortableSpriteToDraw(back, pal, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
1595 if (front != 0) AddSortableSpriteToDraw(front, pal, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
1599 * Draws the catenary for the given tile
1600 * @param ti information about the tile (slopes, height etc)
1602 void DrawRoadCatenary(const TileInfo *ti)
1604 RoadBits road;
1605 RoadBits tram;
1607 if (IsTileType(ti->tile, MP_ROAD)) {
1608 if (IsNormalRoad(ti->tile)) {
1609 road = GetRoadBits(ti->tile, ROADTYPE_ROAD);
1610 tram = GetRoadBits(ti->tile, ROADTYPE_TRAM);
1612 else if (IsLevelCrossing(ti->tile)) {
1613 tram = road = (GetCrossingRailAxis(ti->tile) == AXIS_Y ? ROAD_X : ROAD_Y);
1616 else if (IsTileType(ti->tile, MP_STATION)) {
1617 if (IsRoadStop(ti->tile)) {
1618 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
1619 tram = road = (axis == AXIS_X ? ROAD_X : ROAD_Y);
1622 else {
1623 // No road here, no catenary to draw
1624 return;
1627 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(ti->tile);
1628 const RoadtypeInfo* road_rti = rtids.HasRoad() ? GetRoadTypeInfo(rtids.road_identifier) : NULL;
1629 const RoadtypeInfo* tram_rti = rtids.HasTram() ? GetRoadTypeInfo(rtids.tram_identifier) : NULL;
1631 if (road_rti != NULL && HasRoadCatenaryDrawn(rtids.road_identifier)) {
1632 DrawRoadTypeCatenary(ti, rtids.road_identifier, road);
1635 if (tram_rti != NULL && HasRoadCatenaryDrawn(rtids.tram_identifier)) {
1636 DrawRoadTypeCatenary(ti, rtids.tram_identifier, tram);
1641 * Draws details on/around the road
1642 * @param img the sprite to draw
1643 * @param ti the tile to draw on
1644 * @param dx the offset from the top of the BB of the tile
1645 * @param dy the offset from the top of the BB of the tile
1646 * @param h the height of the sprite to draw
1648 static void DrawRoadDetail(SpriteID img, const TileInfo *ti, int dx, int dy, int h)
1650 int x = ti->x | dx;
1651 int y = ti->y | dy;
1652 int z = ti->z;
1653 if (ti->tileh != SLOPE_FLAT) z = GetSlopePixelZ(x, y);
1654 AddSortableSpriteToDraw(img, PAL_NONE, x, y, 2, 2, h, z);
1658 * Draw ground sprite and road pieces
1659 * @param ti TileInfo
1661 void DrawRoadBits(TileInfo *ti)
1663 const bool is_bridge = IsTileType(ti->tile, MP_TUNNELBRIDGE);
1664 RoadBits road = is_bridge ? GetCustomBridgeHeadRoadBits(ti->tile, ROADTYPE_ROAD) : GetRoadBits(ti->tile, ROADTYPE_ROAD);
1665 RoadBits tram = is_bridge ? GetCustomBridgeHeadRoadBits(ti->tile, ROADTYPE_TRAM) : GetRoadBits(ti->tile, ROADTYPE_TRAM);
1667 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(ti->tile);
1668 const RoadtypeInfo* road_rti = rtids.HasRoad() ? GetRoadTypeInfo(rtids.road_identifier) : NULL;
1669 const RoadtypeInfo* tram_rti = rtids.HasTram() ? GetRoadTypeInfo(rtids.tram_identifier) : NULL;
1671 if (ti->tileh != SLOPE_FLAT) {
1672 DrawFoundation(ti, is_bridge ? FOUNDATION_LEVELED : GetRoadFoundation(ti->tileh, road | tram));
1673 /* DrawFoundation() modifies ti. */
1676 /* Determine sprite offsets */
1677 uint road_offset = GetRoadSpriteOffset(ti->tileh, road);
1678 uint tram_offset = GetRoadSpriteOffset(ti->tileh, tram);
1680 /* Draw baseset underlay */
1681 SpriteID image = SPR_ROAD_Y + (road_rti != NULL ? road_offset : tram_offset);
1682 PaletteID pal = PAL_NONE;
1684 Roadside roadside = is_bridge ? ROADSIDE_PAVED : GetRoadside(ti->tile);
1686 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1687 image += 19;
1688 } else {
1689 switch (roadside) {
1690 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1691 case ROADSIDE_GRASS: break;
1692 case ROADSIDE_GRASS_ROAD_WORKS: break;
1693 default: image -= 19; break; // Paved
1697 DrawGroundSprite(image, pal);
1699 /* Road underlay takes precendence over tram */
1700 if (road_rti != NULL) {
1701 if (road_rti->UsesOverlay()) {
1702 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_GROUND);
1703 DrawGroundSprite(ground + road_offset, PAL_NONE);
1705 } else {
1706 if (tram_rti->UsesOverlay()) {
1707 SpriteID ground = GetCustomRoadSprite(tram_rti, ti->tile, ROTSG_GROUND);
1708 DrawGroundSprite(ground + tram_offset, PAL_NONE);
1709 } else {
1710 DrawGroundSprite(SPR_TRAMWAY_TRAM + tram_offset, PAL_NONE);
1714 /* Draw road overlay */
1715 if (road_rti != nullptr) {
1716 if (road_rti->UsesOverlay()) {
1717 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_OVERLAY);
1718 if (ground != 0) DrawGroundSprite(ground + road_offset, PAL_NONE);
1722 /* Draw tram overlay */
1723 if (tram_rti != nullptr) {
1724 if (tram_rti->UsesOverlay()) {
1725 SpriteID ground = GetCustomRoadSprite(tram_rti, ti->tile, ROTSG_OVERLAY);
1726 if (ground != 0) DrawGroundSprite(ground + tram_offset, PAL_NONE);
1727 } else if (road_rti != nullptr) {
1728 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + tram_offset, PAL_NONE);
1732 /* Draw one way */
1733 if (!is_bridge && road_rti != nullptr) {
1734 DisallowedRoadDirections drd = GetDisallowedRoadDirections(ti->tile);
1735 if (drd != DRD_NONE) {
1736 DrawGroundSpriteAt(SPR_ONEWAY_BASE + drd - 1 + ((road == ROAD_X) ? 0 : 3), PAL_NONE, 8, 8, GetPartialPixelZ(8, 8, ti->tileh));
1740 if (!is_bridge && HasRoadWorks(ti->tile)) {
1741 /* Road works */
1742 DrawGroundSprite((road | tram) & ROAD_X ? SPR_EXCAVATION_X : SPR_EXCAVATION_Y, PAL_NONE);
1743 return;
1746 /* Draw road, tram catenary */
1747 DrawRoadCatenary(ti);
1749 /* Return if full detail is disabled, or we are zoomed fully out. */
1750 if (!HasBit(_display_opt, DO_FULL_DETAIL) || _cur_dpi->zoom > ZOOM_LVL_DETAIL) return;
1752 /* Do not draw details (street lights, trees) under low bridge */
1753 if (IsBridgeAbove(ti->tile) && (roadside == ROADSIDE_TREES || roadside == ROADSIDE_STREET_LIGHTS)) {
1754 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1755 int minz = GetTileMaxZ(ti->tile) + 2;
1757 if (roadside == ROADSIDE_TREES) minz++;
1759 if (height < minz) return;
1762 /* If there are no road bits, return, as there is nothing left to do */
1763 if (HasAtMostOneBit(road)) return;
1765 /* Draw extra details. */
1766 for (const DrawRoadTileStruct *drts = _road_display_table[roadside][road | tram]; drts->image != 0; drts++) {
1767 DrawRoadDetail(drts->image, ti, drts->subcoord_x, drts->subcoord_y, 0x10);
1771 /** Tile callback function for rendering a road tile to the screen */
1772 static void DrawTile_Road(TileInfo *ti)
1774 switch (GetRoadTileType(ti->tile)) {
1775 case ROAD_TILE_NORMAL:
1776 DrawRoadBits(ti);
1777 DrawOverlay(ti, MP_ROAD);
1778 break;
1780 case ROAD_TILE_CROSSING: {
1781 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1783 Axis axis = GetCrossingRailAxis(ti->tile);
1785 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1787 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(ti->tile);
1788 const RoadtypeInfo* road_rti = rtids.HasRoad() ? GetRoadTypeInfo(rtids.road_identifier) : NULL;
1789 const RoadtypeInfo* tram_rti = rtids.HasTram() ? GetRoadTypeInfo(rtids.tram_identifier) : NULL;
1791 /* Draw base ground */
1792 if (rti->UsesOverlay()) {
1793 PaletteID pal = PAL_NONE;
1794 SpriteID image = SPR_ROAD_Y + axis;
1796 Roadside roadside = GetRoadside(ti->tile);
1797 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1798 image += 19;
1799 } else {
1800 switch (roadside) {
1801 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1802 case ROADSIDE_GRASS: break;
1803 default: image -= 19; break; // Paved
1807 DrawGroundSprite(image, pal);
1808 } else {
1809 PaletteID pal = PAL_NONE;
1810 SpriteID image = rti->base_sprites.crossing + axis;
1811 if (IsCrossingBarred(ti->tile)) image += 2;
1813 Roadside roadside = GetRoadside(ti->tile);
1814 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1815 image += 8;
1816 } else {
1817 switch (roadside) {
1818 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1819 case ROADSIDE_GRASS: break;
1820 default: image += 4; break; // Paved
1824 DrawGroundSprite(image, pal);
1827 /* Draw road/tram underlay; road underlay takes precendence over tram */
1828 if (road_rti != NULL) {
1829 if (road_rti->UsesOverlay()) {
1830 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_GROUND);
1831 DrawGroundSprite(ground + axis, PAL_NONE);
1833 } else {
1834 if (tram_rti->UsesOverlay()) {
1835 SpriteID ground = GetCustomRoadSprite(tram_rti, ti->tile, ROTSG_GROUND);
1836 DrawGroundSprite(ground + axis, PAL_NONE);
1837 } else {
1838 DrawGroundSprite(SPR_TRAMWAY_TRAM + axis, PAL_NONE);
1842 /* Draw road overlay */
1843 if (road_rti != NULL) {
1844 if (road_rti->UsesOverlay()) {
1845 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_OVERLAY);
1846 if (ground != 0) DrawGroundSprite(ground + axis, PAL_NONE);
1850 /* Draw tram overlay */
1851 if (tram_rti != NULL) {
1852 if (tram_rti->UsesOverlay()) {
1853 SpriteID ground = GetCustomRoadSprite(tram_rti, ti->tile, ROTSG_OVERLAY);
1854 if (ground != 0) DrawGroundSprite(ground + axis, PAL_NONE);
1855 } else if (road_rti != NULL) {
1856 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + axis, PAL_NONE);
1860 /* Draw rail/PBS overlay */
1861 bool draw_pbs = _game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile);
1862 if (rti->UsesOverlay()) {
1863 PaletteID pal = draw_pbs ? PALETTE_CRASH : PAL_NONE;
1864 SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
1865 DrawGroundSprite(rail, pal);
1867 DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
1868 } else if (draw_pbs || tram_rti != NULL || road_rti->UsesOverlay()) {
1869 /* Add another rail overlay, unless there is only the base road sprite. */
1870 PaletteID pal = draw_pbs ? PALETTE_CRASH : PAL_NONE;
1871 SpriteID rail = GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y;
1872 DrawGroundSprite(rail, pal);
1875 /* Draw road, tram catenary */
1876 DrawRoadCatenary(ti);
1878 /* Draw rail catenary */
1879 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
1881 break;
1884 default:
1885 case ROAD_TILE_DEPOT: {
1886 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1888 PaletteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
1889 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(ti->tile);
1890 const RoadtypeInfo* rti = GetRoadTypeInfo(rtids.HasRoad() ? rtids.road_identifier : rtids.tram_identifier);
1892 int relocation = GetCustomRoadSprite(rti, ti->tile, ROTSG_DEPOT);
1893 bool default_gfx = relocation == 0;
1894 if (default_gfx) {
1895 if (HasBit(rti->flags, ROTF_CATENARY)) {
1896 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK && rtids.HasTram() && !rti->UsesOverlay()) {
1897 /* Sprites with track only work for default tram */
1898 relocation = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_ROAD_DEPOT;
1899 default_gfx = false;
1900 } else {
1901 /* Sprites without track are always better, if provided */
1902 relocation = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_ROAD_DEPOT;
1905 } else {
1906 relocation -= SPR_ROAD_DEPOT;
1909 DiagDirection dir = GetRoadDepotDirection(ti->tile);
1910 const DrawTileSprites *dts = &_road_depot[dir];
1911 DrawGroundSprite(dts->ground.sprite, PAL_NONE);
1913 if (default_gfx) {
1914 uint offset = GetRoadSpriteOffset(SLOPE_FLAT, DiagDirToRoadBits(dir));
1915 if (rti->UsesOverlay()) {
1916 SpriteID ground = GetCustomRoadSprite(rti, ti->tile, ROTSG_OVERLAY);
1917 if (ground != 0) DrawGroundSprite(ground + offset, PAL_NONE);
1918 } else if (rtids.HasTram()) {
1919 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + offset, PAL_NONE);
1923 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, palette);
1924 break;
1927 DrawBridgeMiddle(ti);
1931 * Draw the road depot sprite.
1932 * @param x The x offset to draw at.
1933 * @param y The y offset to draw at.
1934 * @param dir The direction the depot must be facing.
1935 * @param rtid The road type of the depot to draw.
1937 void DrawRoadDepotSprite(int x, int y, DiagDirection dir, RoadTypeIdentifier rtid)
1939 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
1941 const RoadtypeInfo* rti = GetRoadTypeInfo(rtid);
1942 int relocation = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_DEPOT);
1943 bool default_gfx = relocation == 0;
1944 if (default_gfx) {
1945 if (HasBit(rti->flags, ROTF_CATENARY)) {
1946 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK && rtid.IsTram() && !rti->UsesOverlay()) {
1947 /* Sprites with track only work for default tram */
1948 relocation = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_ROAD_DEPOT;
1949 default_gfx = false;
1950 } else {
1951 /* Sprites without track are always better, if provided */
1952 relocation = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_ROAD_DEPOT;
1955 } else {
1956 relocation -= SPR_ROAD_DEPOT;
1959 const DrawTileSprites *dts = &_road_depot[dir];
1960 DrawSprite(dts->ground.sprite, PAL_NONE, x, y);
1962 if (default_gfx) {
1963 uint offset = GetRoadSpriteOffset(SLOPE_FLAT, DiagDirToRoadBits(dir));
1964 if (rti->UsesOverlay()) {
1965 SpriteID ground = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_OVERLAY);
1966 if (ground != 0) DrawSprite(ground + offset, PAL_NONE, x, y);
1967 } else if (rtid.IsTram()) {
1968 DrawSprite(SPR_TRAMWAY_OVERLAY + offset, PAL_NONE, x, y);
1972 DrawRailTileSeqInGUI(x, y, dts, relocation, 0, palette);
1976 * Updates cached nearest town for all road tiles
1977 * @param invalidate are we just invalidating cached data?
1978 * @pre invalidate == true implies _generating_world == true
1980 void UpdateNearestTownForRoadTiles(bool invalidate)
1982 assert(!invalidate || _generating_world);
1984 for (TileIndex t = 0; t < MapSize(); t++) {
1985 if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1986 TownID tid = (TownID)INVALID_TOWN;
1987 if (!invalidate) {
1988 const Town *town = CalcClosestTownFromTile(t);
1989 if (town != nullptr) tid = town->index;
1991 SetTownIndex(t, tid);
1996 static int GetSlopePixelZ_Road(TileIndex tile, uint x, uint y)
1999 if (IsNormalRoad(tile)) {
2000 int z;
2001 Slope tileh = GetTilePixelSlope(tile, &z);
2002 if (tileh == SLOPE_FLAT) return z;
2004 Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
2005 z += ApplyPixelFoundationToSlope(f, &tileh);
2006 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
2007 } else {
2008 return GetTileMaxPixelZ(tile);
2012 static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
2014 if (IsNormalRoad(tile)) {
2015 return GetRoadFoundation(tileh, GetAllRoadBits(tile));
2016 } else {
2017 return FlatteningFoundation(tileh);
2021 static const Roadside _town_road_types[][2] = {
2022 { ROADSIDE_GRASS, ROADSIDE_GRASS },
2023 { ROADSIDE_PAVED, ROADSIDE_PAVED },
2024 { ROADSIDE_PAVED, ROADSIDE_PAVED },
2025 { ROADSIDE_TREES, ROADSIDE_TREES },
2026 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
2029 static const Roadside _town_road_types_2[][2] = {
2030 { ROADSIDE_GRASS, ROADSIDE_GRASS },
2031 { ROADSIDE_PAVED, ROADSIDE_PAVED },
2032 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
2033 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
2034 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
2038 static void TileLoop_Road(TileIndex tile)
2040 switch (_settings_game.game_creation.landscape) {
2041 case LT_ARCTIC:
2042 if (IsOnSnow(tile) != (GetTileMaxZ(tile) > GetSnowLine())) {
2043 ToggleSnow(tile);
2044 MarkTileDirtyByTile(tile);
2046 break;
2048 case LT_TROPIC:
2049 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsOnDesert(tile)) {
2050 ToggleDesert(tile);
2051 MarkTileDirtyByTile(tile);
2053 break;
2056 if (IsRoadDepot(tile)) return;
2058 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
2059 if (!HasRoadWorks(tile)) {
2060 HouseZonesBits grp = HZB_TOWN_EDGE;
2062 if (t != nullptr) {
2063 grp = GetTownRadiusGroup(t, tile);
2065 /* Show an animation to indicate road work */
2066 if (t->road_build_months != 0 &&
2067 (DistanceManhattan(t->xy, tile) < 8 || grp != HZB_TOWN_EDGE) &&
2068 IsNormalRoad(tile) && !HasAtMostOneBit(GetAllRoadBits(tile))) {
2069 if (GetFoundationSlope(tile) == SLOPE_FLAT && EnsureNoVehicleOnGround(tile).Succeeded() && Chance16(1, 40)) {
2070 StartRoadWorks(tile);
2072 if (_settings_client.sound.ambient) SndPlayTileFx(SND_21_JACKHAMMER, tile);
2073 CreateEffectVehicleAbove(
2074 TileX(tile) * TILE_SIZE + 7,
2075 TileY(tile) * TILE_SIZE + 7,
2077 EV_BULLDOZER);
2078 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2079 return;
2085 /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
2086 const Roadside *new_rs = (_settings_game.game_creation.landscape == LT_TOYLAND) ? _town_road_types_2[grp] : _town_road_types[grp];
2087 Roadside cur_rs = GetRoadside(tile);
2089 /* We have our desired type, do nothing */
2090 if (cur_rs == new_rs[0]) return;
2092 /* We have the pre-type of the desired type, switch to the desired type */
2093 if (cur_rs == new_rs[1]) {
2094 cur_rs = new_rs[0];
2095 /* We have barren land, install the pre-type */
2096 } else if (cur_rs == ROADSIDE_BARREN) {
2097 cur_rs = new_rs[1];
2098 /* We're totally off limits, remove any installation and make barren land */
2099 } else {
2100 cur_rs = ROADSIDE_BARREN;
2102 SetRoadside(tile, cur_rs);
2103 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2105 } else if (IncreaseRoadWorksCounter(tile)) {
2106 TerminateRoadWorks(tile);
2108 if (_settings_game.economy.mod_road_rebuild) {
2109 /* Generate a nicer town surface */
2110 const RoadBits old_rb = GetAnyRoadBits(tile, ROADTYPE_ROAD);
2111 const RoadBits new_rb = CleanUpRoadBits(tile, old_rb);
2113 if (old_rb != new_rb) {
2114 RemoveRoad(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, (old_rb ^ new_rb), RoadTypeIdentifier(ROADTYPE_ROAD, ROADSUBTYPE_NORMAL));
2118 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2122 static bool ClickTile_Road(TileIndex tile)
2124 if (!IsRoadDepot(tile)) return false;
2126 ShowDepotWindow(tile, VEH_ROAD);
2127 return true;
2130 /* Converts RoadBits to TrackBits */
2131 extern const TrackBits _road_trackbits[16] = {
2132 TRACK_BIT_NONE, // ROAD_NONE
2133 TRACK_BIT_NONE, // ROAD_NW
2134 TRACK_BIT_NONE, // ROAD_SW
2135 TRACK_BIT_LEFT, // ROAD_W
2136 TRACK_BIT_NONE, // ROAD_SE
2137 TRACK_BIT_Y, // ROAD_Y
2138 TRACK_BIT_LOWER, // ROAD_S
2139 TRACK_BIT_LEFT | TRACK_BIT_LOWER | TRACK_BIT_Y, // ROAD_Y | ROAD_SW
2140 TRACK_BIT_NONE, // ROAD_NE
2141 TRACK_BIT_UPPER, // ROAD_N
2142 TRACK_BIT_X, // ROAD_X
2143 TRACK_BIT_LEFT | TRACK_BIT_UPPER | TRACK_BIT_X, // ROAD_X | ROAD_NW
2144 TRACK_BIT_RIGHT, // ROAD_E
2145 TRACK_BIT_RIGHT | TRACK_BIT_UPPER | TRACK_BIT_Y, // ROAD_Y | ROAD_NE
2146 TRACK_BIT_RIGHT | TRACK_BIT_LOWER | TRACK_BIT_X, // ROAD_X | ROAD_SE
2147 TRACK_BIT_ALL, // ROAD_ALL
2150 static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
2152 TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
2153 TrackdirBits red_signals = TRACKDIR_BIT_NONE; // crossing barred
2154 switch (mode) {
2155 case TRANSPORT_RAIL:
2156 if (IsLevelCrossing(tile)) trackdirbits = TrackBitsToTrackdirBits(GetCrossingRailBits(tile));
2157 break;
2159 case TRANSPORT_ROAD: {
2160 RoadType rt = (RoadType)sub_mode;
2161 if (!HasTileRoadType(tile, rt)) break;
2162 switch (GetRoadTileType(tile)) {
2163 case ROAD_TILE_NORMAL: {
2164 const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
2165 RoadBits bits = GetRoadBits(tile, rt);
2167 /* no roadbit at this side of tile, return 0 */
2168 if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break;
2170 uint multiplier = drd_to_multiplier[rt == ROADTYPE_TRAM ? DRD_NONE : GetDisallowedRoadDirections(tile)];
2171 if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier);
2172 break;
2175 case ROAD_TILE_CROSSING: {
2176 Axis axis = GetCrossingRoadAxis(tile);
2178 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
2180 trackdirbits = TrackBitsToTrackdirBits(AxisToTrackBits(axis));
2181 if (IsCrossingBarred(tile)) red_signals = trackdirbits;
2182 if (IsLevelCrossingTile(TileAddByDiagDir(tile, AxisToDiagDir(axis))) &&
2183 IsCrossingBarred(TileAddByDiagDir(tile, AxisToDiagDir(axis)))) {
2184 red_signals &= (TrackdirBits)0x0102; // magic value. I think TRACKBIT_X_SW and TRACKBIT_X_NE should be swapped
2186 if (IsLevelCrossingTile(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis)))) &&
2187 IsCrossingBarred(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis))))) {
2188 red_signals &= (TrackdirBits)0x0201; // inverse of above magic value
2190 break;
2193 default:
2194 case ROAD_TILE_DEPOT: {
2195 DiagDirection dir = GetRoadDepotDirection(tile);
2197 if (side != INVALID_DIAGDIR && side != dir) break;
2199 trackdirbits = TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir));
2200 break;
2203 break;
2206 default: break;
2208 return CombineTrackStatus(trackdirbits, red_signals);
2211 static const StringID _road_tile_strings[] = {
2212 STR_LAI_ROAD_DESCRIPTION_ROAD,
2213 STR_LAI_ROAD_DESCRIPTION_ROAD,
2214 STR_LAI_ROAD_DESCRIPTION_ROAD,
2215 STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_STREETLIGHTS,
2216 STR_LAI_ROAD_DESCRIPTION_ROAD,
2217 STR_LAI_ROAD_DESCRIPTION_TREE_LINED_ROAD,
2218 STR_LAI_ROAD_DESCRIPTION_ROAD,
2219 STR_LAI_ROAD_DESCRIPTION_ROAD,
2222 static void GetTileDesc_Road(TileIndex tile, TileDesc *td)
2224 Owner rail_owner = INVALID_OWNER;
2225 Owner road_owner = INVALID_OWNER;
2226 Owner tram_owner = INVALID_OWNER;
2228 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
2229 if (rtids.HasRoad()) {
2230 const RoadtypeInfo *rti = GetRoadTypeInfo(rtids.road_identifier);
2231 td->roadtype = rti->strings.name;
2232 td->road_speed = rti->max_speed / 2;
2233 road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
2235 if (rtids.HasTram()) {
2236 const RoadtypeInfo *rti = GetRoadTypeInfo(rtids.tram_identifier);
2237 td->tramtype = rti->strings.name;
2238 td->tram_speed = rti->max_speed / 2;
2239 tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
2242 switch (GetRoadTileType(tile)) {
2243 case ROAD_TILE_CROSSING: {
2244 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_RAIL_LEVEL_CROSSING;
2245 rail_owner = GetTileOwner(tile);
2247 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2248 td->railtype = rti->strings.name;
2249 td->rail_speed = rti->max_speed;
2251 break;
2254 case ROAD_TILE_DEPOT:
2255 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_VEHICLE_DEPOT;
2256 td->build_date = Depot::GetByTile(tile)->build_date;
2257 break;
2259 default: {
2260 td->str = (rtids.HasRoad() ? _road_tile_strings[GetRoadside(tile)] : STR_LAI_ROAD_DESCRIPTION_TRAMWAY);
2261 break;
2265 /* Now we have to discover, if the tile has only one owner or many:
2266 * - Find a first_owner of the tile. (Currently road or tram must be present, but this will break when the third type becomes available)
2267 * - Compare the found owner with the other owners, and test if they differ.
2268 * Note: If road exists it will be the first_owner.
2270 Owner first_owner = (road_owner == INVALID_OWNER ? tram_owner : road_owner);
2271 bool mixed_owners = (tram_owner != INVALID_OWNER && tram_owner != first_owner) || (rail_owner != INVALID_OWNER && rail_owner != first_owner);
2273 if (mixed_owners) {
2274 /* Multiple owners */
2275 td->owner_type[0] = (rail_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_RAIL_OWNER);
2276 td->owner[0] = rail_owner;
2277 td->owner_type[1] = (road_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_ROAD_OWNER);
2278 td->owner[1] = road_owner;
2279 td->owner_type[2] = (tram_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_TRAM_OWNER);
2280 td->owner[2] = tram_owner;
2281 } else {
2282 /* One to rule them all */
2283 td->owner[0] = first_owner;
2288 * Given the direction the road depot is pointing, this is the direction the
2289 * vehicle should be travelling in in order to enter the depot.
2291 static const byte _roadveh_enter_depot_dir[4] = {
2292 TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
2295 static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
2297 switch (GetRoadTileType(tile)) {
2298 case ROAD_TILE_DEPOT: {
2299 if (v->type != VEH_ROAD) break;
2301 RoadVehicle *rv = RoadVehicle::From(v);
2302 if (rv->frame == RVC_DEPOT_STOP_FRAME &&
2303 _roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
2304 rv->state = RVSB_IN_DEPOT;
2305 rv->vehstatus |= VS_HIDDEN;
2306 rv->direction = ReverseDir(rv->direction);
2307 if (rv->Next() == nullptr) VehicleEnterDepot(rv->First());
2308 rv->tile = tile;
2310 InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
2311 return VETSB_ENTERED_WORMHOLE;
2313 break;
2316 default: break;
2318 return VETSB_CONTINUE;
2322 static void ChangeTileOwner_Road(TileIndex tile, Owner old_owner, Owner new_owner)
2324 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
2325 if (IsRoadDepot(tile)) {
2326 if (GetTileOwner(tile) == old_owner) {
2327 if (new_owner == INVALID_OWNER) {
2328 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
2329 } else {
2330 /* A road depot has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
2331 RoadTypeIdentifier rtid = rtids.HasRoad() ? rtids.road_identifier : rtids.tram_identifier;
2332 Company::Get(old_owner)->infrastructure.road[rtid.basetype][rtid.subtype] -= 2;
2333 Company::Get(new_owner)->infrastructure.road[rtid.basetype][rtid.subtype] += 2;
2335 SetTileOwner(tile, new_owner);
2336 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
2337 if (GetRoadOwner(tile, rt) == old_owner) {
2338 SetRoadOwner(tile, rt, new_owner);
2343 return;
2346 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
2347 /* Update all roadtypes, no matter if they are present */
2348 if (GetRoadOwner(tile, rt) == old_owner) {
2349 RoadTypeIdentifier rtid = rt == ROADTYPE_ROAD ? rtids.road_identifier : rtids.tram_identifier;
2350 if (rtid.IsValid()) {
2351 /* A level crossing has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
2352 uint num_bits = IsLevelCrossing(tile) ? 2 : CountBits(GetRoadBits(tile, rt));
2353 Company::Get(old_owner)->infrastructure.road[rtid.basetype][rtid.subtype] -= num_bits;
2354 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rtid.basetype][rtid.subtype] += num_bits;
2357 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
2361 if (IsLevelCrossing(tile)) {
2362 if (GetTileOwner(tile) == old_owner) {
2363 if (new_owner == INVALID_OWNER) {
2364 DoCommand(tile, 0, GetCrossingRailTrack(tile), DC_EXEC | DC_BANKRUPT, CMD_REMOVE_SINGLE_RAIL);
2365 } else {
2366 /* Update infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2367 Company::Get(old_owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
2368 Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
2370 SetTileOwner(tile, new_owner);
2376 static CommandCost TerraformTile_Road(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2378 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
2379 switch (GetRoadTileType(tile)) {
2380 case ROAD_TILE_CROSSING:
2381 if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) && HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2382 break;
2384 case ROAD_TILE_DEPOT:
2385 if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRoadDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2386 break;
2388 case ROAD_TILE_NORMAL: {
2389 RoadBits bits = GetAllRoadBits(tile);
2390 RoadBits bits_copy = bits;
2391 /* Check if the slope-road_bits combination is valid at all, i.e. it is safe to call GetRoadFoundation(). */
2392 if (CheckRoadSlope(tileh_new, &bits_copy, ROAD_NONE, ROAD_NONE).Succeeded()) {
2393 /* CheckRoadSlope() sometimes changes the road_bits, if it does not agree with them. */
2394 if (bits == bits_copy) {
2395 int z_old;
2396 Slope tileh_old = GetTileSlope(tile, &z_old);
2398 /* Get the slope on top of the foundation */
2399 z_old += ApplyFoundationToSlope(GetRoadFoundation(tileh_old, bits), &tileh_old);
2400 z_new += ApplyFoundationToSlope(GetRoadFoundation(tileh_new, bits), &tileh_new);
2402 /* The surface slope must not be changed */
2403 if ((z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2406 break;
2409 default: NOT_REACHED();
2413 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2416 /** Update power of train under which is the railtype being converted */
2417 static Vehicle *UpdateRoadVehPowerProc(Vehicle *v, void *data)
2419 if (v->type != VEH_ROAD) return NULL;
2421 RoadVehicleList *affected_trains = static_cast<RoadVehicleList*>(data);
2422 affected_trains->Include(RoadVehicle::From(v)->First());
2424 return NULL;
2428 * Checks the tile and returns whether the current player is allowed to convert the roadtype to another roadtype
2429 * @param tile the tile to convert
2430 * @param to_type the RoadTypeIdentifier to be converted
2431 * @return whether the road is convertible
2433 static bool CanConvertRoadType(Owner owner, RoadType basetype)
2435 return (owner == OWNER_NONE || (owner == OWNER_TOWN && basetype == ROADTYPE_ROAD));
2439 * Convert the ownership of the RoadType of the tile if applyable
2440 * @param tile the tile of which convert ownership
2441 * @param num_pieces the count of the roadbits to assign to the new owner
2442 * @param owner the current owner of the RoadType
2443 * @param from_type the old RoadTypeIdentifier
2444 * @param to_type the new RoadTypeIdentifier
2446 static void ConvertRoadTypeOwner(TileIndex tile, uint num_pieces, Owner owner, RoadTypeIdentifier from_type, RoadTypeIdentifier to_type)
2448 // Scenario editor, maybe? Don't touch the owners when converting roadtypes...
2449 if (_current_company >= MAX_COMPANIES) return;
2451 // We can't get a company from invalid owners but we can get ownership of roads without an owner
2452 if (owner >= MAX_COMPANIES && owner != OWNER_NONE) return;
2454 Company *c;
2456 switch (owner) {
2457 case OWNER_NONE:
2458 SetRoadOwner(tile, to_type.basetype, (Owner)_current_company);
2459 c = Company::Get(_current_company);
2460 c->infrastructure.road[to_type.basetype][to_type.subtype] += num_pieces;
2461 DirtyCompanyInfrastructureWindows(c->index);
2462 break;
2464 default:
2465 c = Company::Get(owner);
2466 c->infrastructure.road[from_type.basetype][from_type.subtype] -= num_pieces;
2467 c->infrastructure.road[to_type.basetype][to_type.subtype] += num_pieces;
2468 DirtyCompanyInfrastructureWindows(c->index);
2469 break;
2474 * Convert one road subtype to another.
2475 * Not meant to convert from road to tram.
2477 * @param tile end tile of road conversion drag
2478 * @param flags operation to perform
2479 * @param p1 start tile of drag
2480 * @param p2 various bitstuffed elements:
2481 * - p2 = (bit 0..5) new roadtype to convert to.
2482 * @param text unused
2483 * @return the cost of this operation or an error
2485 CommandCost CmdConvertRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2487 RoadTypeIdentifier to_type;
2488 if (!to_type.UnpackIfValid(GB(p2, 0, 6))) return CommandError();
2490 TileIndex area_start = p1;
2491 TileIndex area_end = tile;
2493 if (!ValParamRoadType(to_type)) return CommandError();
2494 if (area_start >= MapSize()) return CommandError();
2496 RoadVehicleList affected_rvs;
2498 CommandCost cost(EXPENSES_CONSTRUCTION);
2499 CommandCost error = CommandCost(to_type.IsRoad() ? STR_ERROR_NO_SUITABLE_ROAD : STR_ERROR_NO_SUITABLE_TRAMWAY); // by default, there is no road to convert.
2501 TileIterator *iter = new OrthogonalTileIterator(area_start, area_end);
2502 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
2503 /* Is road present on tile? */
2504 if (!MayHaveRoad(tile)) continue;
2505 RoadTypeIdentifiers rtids = RoadTypeIdentifiers::FromTile(tile);
2506 if (!rtids.HasType(to_type.basetype)) continue;
2508 /* Converting to the same subtype? */
2509 RoadTypeIdentifier from_type = rtids.GetType(to_type.basetype);
2510 if (from_type.subtype == to_type.subtype) continue;
2512 /* Check if there is any infrastructure on tile */
2513 TileType tt = GetTileType(tile);
2514 switch (tt) {
2515 case MP_STATION:
2516 if (!IsRoadStop(tile)) continue;
2517 break;
2518 case MP_ROAD:
2519 if (IsLevelCrossing(tile) && RoadNoLevelCrossing(to_type)) {
2520 error.MakeError(STR_ERROR_CROSSING_DISALLOWED_ROAD);
2521 continue;
2523 break;
2524 case MP_TUNNELBRIDGE:
2525 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) continue;
2526 break;
2527 default: continue;
2530 /* Trying to convert other's road */ // TODO allow upgrade?
2531 Owner owner = GetRoadOwner(tile, to_type.basetype);
2532 if (!CanConvertRoadType(owner, to_type.basetype)) {
2533 CommandCost ret = CheckOwnership(owner, tile);
2534 if (ret.Failed()) {
2535 error = ret;
2536 continue;
2540 /* Vehicle on the tile when not converting normal <-> powered
2541 * Tunnels and bridges have special check later */
2542 if (tt != MP_TUNNELBRIDGE) {
2543 if (!HasPowerOnRoad(from_type, to_type)) {
2544 CommandCost ret = EnsureNoVehicleOnGround(tile);
2545 if (ret.Failed()) {
2546 error = ret;
2547 continue;
2550 if (to_type.basetype == ROADTYPE_ROAD && owner == OWNER_TOWN) {
2551 error.MakeError(STR_ERROR_INCOMPATIBLE_ROAD);
2552 continue;
2556 uint num_pieces = CountBits(GetAnyRoadBits(tile, from_type.basetype));;
2557 cost.AddCost(num_pieces * RoadConvertCost(from_type, to_type));
2559 if (flags & DC_EXEC) { // we can safely convert, too
2560 /* Update the company infrastructure counters. */
2561 if (!IsRoadStopTile(tile) && CanConvertRoadType(owner, to_type.basetype) && owner != OWNER_TOWN) {
2562 ConvertRoadTypeOwner(tile, num_pieces, owner, from_type, to_type);
2565 /* Perform the conversion */
2566 rtids.MergeRoadType(to_type);
2567 SetRoadTypes(tile, rtids);
2568 MarkTileDirtyByTile(tile);
2570 /* update power of train on this tile */
2571 FindVehicleOnPos(tile, &affected_rvs, &UpdateRoadVehPowerProc);
2573 if (IsRoadDepotTile(tile)) {
2574 /* Update build vehicle window related to this depot */
2575 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
2576 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
2579 } else {
2580 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
2582 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
2583 * it would cause assert because of different test and exec runs */
2584 if (endtile < tile) {
2585 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
2588 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
2589 if (!HasPowerOnRoad(from_type, to_type)) {
2590 CommandCost ret = TunnelBridgeIsFree(tile, endtile);
2591 if (ret.Failed()) {
2592 error = ret;
2593 continue;
2596 if (to_type.basetype == ROADTYPE_ROAD && owner == OWNER_TOWN) {
2597 error.MakeError(STR_ERROR_INCOMPATIBLE_ROAD);
2598 continue;
2602 /* There are 2 pieces on *every* tile of the bridge or tunnel */
2603 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * 2;
2604 cost.AddCost(num_pieces * RoadConvertCost(from_type, to_type));
2606 if (flags & DC_EXEC) {
2607 /* Update the company infrastructure counters. */
2608 if (CanConvertRoadType(owner, to_type.basetype) && owner != OWNER_TOWN) {
2609 ConvertRoadTypeOwner(tile, num_pieces, owner, from_type, to_type);
2610 ConvertRoadTypeOwner(endtile, num_pieces, owner, from_type, to_type);
2611 SetTunnelBridgeOwner(tile, endtile, _current_company);
2614 /* Perform the conversion */
2615 rtids.MergeRoadType(to_type);
2616 SetRoadTypes(tile, rtids);
2617 SetRoadTypes(endtile, rtids);
2619 FindVehicleOnPos(tile, &affected_rvs, &UpdateRoadVehPowerProc);
2620 FindVehicleOnPos(endtile, &affected_rvs, &UpdateRoadVehPowerProc);
2622 if (IsBridge(tile)) {
2623 MarkBridgeDirty(tile);
2624 } else {
2625 MarkTileDirtyByTile(tile);
2626 MarkTileDirtyByTile(endtile);
2632 if (flags & DC_EXEC) {
2633 /* Roadtype changed, update roadvehicles as when entering different track */
2634 for (RoadVehicle **v = affected_rvs.Begin(); v != affected_rvs.End(); v++) {
2635 (*v)->CargoChanged();
2639 delete iter;
2640 return (cost.GetCost() == 0) ? error : cost;
2644 /** Tile callback functions for road tiles */
2645 extern const TileTypeProcs _tile_type_road_procs = {
2646 DrawTile_Road, // draw_tile_proc
2647 GetSlopePixelZ_Road, // get_slope_z_proc
2648 ClearTile_Road, // clear_tile_proc
2649 nullptr, // add_accepted_cargo_proc
2650 GetTileDesc_Road, // get_tile_desc_proc
2651 GetTileTrackStatus_Road, // get_tile_track_status_proc
2652 ClickTile_Road, // click_tile_proc
2653 nullptr, // animate_tile_proc
2654 TileLoop_Road, // tile_loop_proc
2655 ChangeTileOwner_Road, // change_tile_owner_proc
2656 nullptr, // add_produced_cargo_proc
2657 VehicleEnter_Road, // vehicle_enter_tile_proc
2658 GetFoundation_Road, // get_foundation_proc
2659 TerraformTile_Road, // terraform_tile_proc