Fix #10117: Decrement object burst limit after build check
[openttd-github.git] / src / road_cmd.cpp
blob8d2461c48f9ac8e0f92057243721f5f2a7fa94e4
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file road_cmd.cpp Commands related to road tiles. */
10 #include "stdafx.h"
11 #include "road.h"
12 #include "road_internal.h"
13 #include "viewport_func.h"
14 #include "command_func.h"
15 #include "pathfinder/yapf/yapf_cache.h"
16 #include "depot_base.h"
17 #include "newgrf.h"
18 #include "autoslope.h"
19 #include "tunnelbridge_map.h"
20 #include "strings_func.h"
21 #include "vehicle_func.h"
22 #include "sound_func.h"
23 #include "tunnelbridge.h"
24 #include "cheat_type.h"
25 #include "effectvehicle_func.h"
26 #include "effectvehicle_base.h"
27 #include "elrail_func.h"
28 #include "roadveh.h"
29 #include "town.h"
30 #include "company_base.h"
31 #include "core/random_func.hpp"
32 #include "newgrf_debug.h"
33 #include "newgrf_railtype.h"
34 #include "newgrf_roadtype.h"
35 #include "date_func.h"
36 #include "genworld.h"
37 #include "company_gui.h"
38 #include "road_func.h"
39 #include "road_cmd.h"
40 #include "landscape_cmd.h"
41 #include "rail_cmd.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 std::vector<RoadVehicle *> RoadVehicleList;
51 RoadTypeInfo _roadtypes[ROADTYPE_END];
52 std::vector<RoadType> _sorted_roadtypes;
53 RoadTypes _roadtypes_hidden_mask;
55 /**
56 * Bitmap of road/tram types.
57 * Bit if set if a roadtype is tram.
59 RoadTypes _roadtypes_type;
61 /**
62 * Reset all road type information to its default values.
64 void ResetRoadTypes()
66 static_assert(lengthof(_original_roadtypes) <= lengthof(_roadtypes));
68 uint i = 0;
69 for (; i < lengthof(_original_roadtypes); i++) _roadtypes[i] = _original_roadtypes[i];
71 static const RoadTypeInfo empty_roadtype = {
72 { 0, 0, 0, 0, 0, 0 },
73 { 0, 0, 0, 0, 0, 0 },
74 { 0, 0, 0, 0, 0, 0, 0, 0, 0, {}, {}, 0, {}, {} },
75 ROADTYPES_NONE, ROTFB_NONE, 0, 0, 0, 0,
76 RoadTypeLabelList(), 0, 0, ROADTYPES_NONE, ROADTYPES_NONE, 0,
77 {}, {} };
78 for (; i < lengthof(_roadtypes); i++) _roadtypes[i] = empty_roadtype;
80 _roadtypes_hidden_mask = ROADTYPES_NONE;
81 _roadtypes_type = ROADTYPES_TRAM;
84 void ResolveRoadTypeGUISprites(RoadTypeInfo *rti)
86 SpriteID cursors_base = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_CURSORS);
87 if (cursors_base != 0) {
88 rti->gui_sprites.build_y_road = cursors_base + 0;
89 rti->gui_sprites.build_x_road = cursors_base + 1;
90 rti->gui_sprites.auto_road = cursors_base + 2;
91 rti->gui_sprites.build_depot = cursors_base + 3;
92 rti->gui_sprites.build_tunnel = cursors_base + 4;
93 rti->gui_sprites.convert_road = cursors_base + 5;
94 rti->cursor.road_swne = cursors_base + 6;
95 rti->cursor.road_nwse = cursors_base + 7;
96 rti->cursor.autoroad = cursors_base + 8;
97 rti->cursor.depot = cursors_base + 9;
98 rti->cursor.tunnel = cursors_base + 10;
99 rti->cursor.convert_road = cursors_base + 11;
104 * Compare roadtypes based on their sorting order.
105 * @param first The roadtype to compare to.
106 * @param second The roadtype to compare.
107 * @return True iff the first should be sorted before the second.
109 static bool CompareRoadTypes(const RoadType &first, const RoadType &second)
111 if (RoadTypeIsRoad(first) == RoadTypeIsRoad(second)) {
112 return GetRoadTypeInfo(first)->sorting_order < GetRoadTypeInfo(second)->sorting_order;
114 return RoadTypeIsTram(first) < RoadTypeIsTram(second);
118 * Resolve sprites of custom road types
120 void InitRoadTypes()
122 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
123 RoadTypeInfo *rti = &_roadtypes[rt];
124 ResolveRoadTypeGUISprites(rti);
125 if (HasBit(rti->flags, ROTF_HIDDEN)) SetBit(_roadtypes_hidden_mask, rt);
128 _sorted_roadtypes.clear();
129 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
130 if (_roadtypes[rt].label != 0 && !HasBit(_roadtypes_hidden_mask, rt)) {
131 _sorted_roadtypes.push_back(rt);
134 std::sort(_sorted_roadtypes.begin(), _sorted_roadtypes.end(), CompareRoadTypes);
138 * Allocate a new road type label
140 RoadType AllocateRoadType(RoadTypeLabel label, RoadTramType rtt)
142 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
143 RoadTypeInfo *rti = &_roadtypes[rt];
145 if (rti->label == 0) {
146 /* Set up new road type */
147 *rti = _original_roadtypes[(rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD];
148 rti->label = label;
149 rti->alternate_labels.clear();
150 rti->flags = ROTFB_NONE;
151 rti->introduction_date = INVALID_DATE;
153 /* Make us compatible with ourself. */
154 rti->powered_roadtypes = (RoadTypes)(1ULL << rt);
156 /* We also introduce ourself. */
157 rti->introduces_roadtypes = (RoadTypes)(1ULL << rt);
159 /* Default sort order; order of allocation, but with some
160 * offsets so it's easier for NewGRF to pick a spot without
161 * changing the order of other (original) road types.
162 * The << is so you can place other roadtypes in between the
163 * other roadtypes, the 7 is to be able to place something
164 * before the first (default) road type. */
165 rti->sorting_order = rt << 2 | 7;
167 /* Set bitmap of road/tram types */
168 if (rtt == RTT_TRAM) {
169 SetBit(_roadtypes_type, rt);
170 } else {
171 ClrBit(_roadtypes_type, rt);
174 return rt;
178 return INVALID_ROADTYPE;
182 * Verify whether a road vehicle is available.
183 * @return \c true if at least one road vehicle is available, \c false if not
185 bool RoadVehiclesAreBuilt()
187 return !RoadVehicle::Iterate().empty();
191 * Update road infrastructure counts for a company.
192 * @param rt Road type to update count of.
193 * @param o Owner of road piece.
194 * @param count Number of road pieces to adjust.
196 void UpdateCompanyRoadInfrastructure(RoadType rt, Owner o, int count)
198 if (rt == INVALID_ROADTYPE) return;
200 Company *c = Company::GetIfValid(o);
201 if (c == nullptr) return;
203 c->infrastructure.road[rt] += count;
204 DirtyCompanyInfrastructureWindows(c->index);
207 /** Invalid RoadBits on slopes. */
208 static const RoadBits _invalid_tileh_slopes_road[2][15] = {
209 /* The inverse of the mixable RoadBits on a leveled slope */
211 ROAD_NONE, // SLOPE_FLAT
212 ROAD_NE | ROAD_SE, // SLOPE_W
213 ROAD_NE | ROAD_NW, // SLOPE_S
215 ROAD_NE, // SLOPE_SW
216 ROAD_NW | ROAD_SW, // SLOPE_E
217 ROAD_NONE, // SLOPE_EW
219 ROAD_NW, // SLOPE_SE
220 ROAD_NONE, // SLOPE_WSE
221 ROAD_SE | ROAD_SW, // SLOPE_N
223 ROAD_SE, // SLOPE_NW
224 ROAD_NONE, // SLOPE_NS
225 ROAD_NONE, // SLOPE_ENW
227 ROAD_SW, // SLOPE_NE
228 ROAD_NONE, // SLOPE_SEN
229 ROAD_NONE // SLOPE_NWS
231 /* The inverse of the allowed straight roads on a slope
232 * (with and without a foundation). */
234 ROAD_NONE, // SLOPE_FLAT
235 ROAD_NONE, // SLOPE_W Foundation
236 ROAD_NONE, // SLOPE_S Foundation
238 ROAD_Y, // SLOPE_SW
239 ROAD_NONE, // SLOPE_E Foundation
240 ROAD_ALL, // SLOPE_EW
242 ROAD_X, // SLOPE_SE
243 ROAD_ALL, // SLOPE_WSE
244 ROAD_NONE, // SLOPE_N Foundation
246 ROAD_X, // SLOPE_NW
247 ROAD_ALL, // SLOPE_NS
248 ROAD_ALL, // SLOPE_ENW
250 ROAD_Y, // SLOPE_NE
251 ROAD_ALL, // SLOPE_SEN
252 ROAD_ALL // SLOPE_NW
256 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits);
259 * Is it allowed to remove the given road bits from the given tile?
260 * @param tile the tile to remove the road from
261 * @param remove the roadbits that are going to be removed
262 * @param owner the actual owner of the roadbits of the tile
263 * @param rt the road type to remove the bits from
264 * @param flags command flags
265 * @param town_check Shall the town rating checked/affected
266 * @return A succeeded command when it is allowed to remove the road bits, a failed command otherwise.
268 CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadTramType rtt, DoCommandFlag flags, bool town_check)
270 if (_game_mode == GM_EDITOR || remove == ROAD_NONE) return CommandCost();
272 /* Water can always flood and towns can always remove "normal" road pieces.
273 * Towns are not be allowed to remove non "normal" road pieces, like tram
274 * tracks as that would result in trams that cannot turn. */
275 if (_current_company == OWNER_WATER ||
276 (rtt == RTT_ROAD && !Company::IsValidID(_current_company))) return CommandCost();
278 /* Only do the special processing if the road is owned
279 * by a town */
280 if (owner != OWNER_TOWN) {
281 if (owner == OWNER_NONE) return CommandCost();
282 CommandCost ret = CheckOwnership(owner);
283 return ret;
286 if (!town_check) return CommandCost();
288 if (_cheats.magic_bulldozer.value) return CommandCost();
290 Town *t = ClosestTownFromTile(tile, UINT_MAX);
291 if (t == nullptr) return CommandCost();
293 /* check if you're allowed to remove the street owned by a town
294 * removal allowance depends on difficulty setting */
295 CommandCost ret = CheckforTownRating(flags, t, ROAD_REMOVE);
296 if (ret.Failed()) return ret;
298 /* Get a bitmask of which neighbouring roads has a tile */
299 RoadBits n = ROAD_NONE;
300 RoadBits present = GetAnyRoadBits(tile, rtt);
301 if ((present & ROAD_NE) && (GetAnyRoadBits(TILE_ADDXY(tile, -1, 0), rtt) & ROAD_SW)) n |= ROAD_NE;
302 if ((present & ROAD_SE) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, 1), rtt) & ROAD_NW)) n |= ROAD_SE;
303 if ((present & ROAD_SW) && (GetAnyRoadBits(TILE_ADDXY(tile, 1, 0), rtt) & ROAD_NE)) n |= ROAD_SW;
304 if ((present & ROAD_NW) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, -1), rtt) & ROAD_SE)) n |= ROAD_NW;
306 int rating_decrease = RATING_ROAD_DOWN_STEP_EDGE;
307 /* If 0 or 1 bits are set in n, or if no bits that match the bits to remove,
308 * then allow it */
309 if (KillFirstBit(n) != ROAD_NONE && (n & remove) != ROAD_NONE) {
310 /* you can remove all kind of roads with extra dynamite */
311 if (!_settings_game.construction.extra_dynamite) {
312 SetDParam(0, t->index);
313 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
315 rating_decrease = RATING_ROAD_DOWN_STEP_INNER;
317 ChangeTownRating(t, rating_decrease, RATING_ROAD_MINIMUM, flags);
319 return CommandCost();
324 * Delete a piece of road.
325 * @param tile tile where to remove road from
326 * @param flags operation to perform
327 * @param pieces roadbits to remove
328 * @param rt roadtype to remove
329 * @param crossing_check should we check if there is a tram track when we are removing road from crossing?
330 * @param town_check should we check if the town allows removal?
332 static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits pieces, RoadTramType rtt, bool crossing_check, bool town_check = true)
334 assert(pieces != ROAD_NONE);
336 RoadType existing_rt = MayHaveRoad(tile) ? GetRoadType(tile, rtt) : INVALID_ROADTYPE;
337 /* The tile doesn't have the given road type */
338 if (existing_rt == INVALID_ROADTYPE) return_cmd_error((rtt == RTT_TRAM) ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
340 switch (GetTileType(tile)) {
341 case MP_ROAD: {
342 CommandCost ret = EnsureNoVehicleOnGround(tile);
343 if (ret.Failed()) return ret;
344 break;
347 case MP_STATION: {
348 if (!IsDriveThroughStopTile(tile)) return CMD_ERROR;
350 CommandCost ret = EnsureNoVehicleOnGround(tile);
351 if (ret.Failed()) return ret;
352 break;
355 case MP_TUNNELBRIDGE: {
356 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return CMD_ERROR;
357 CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
358 if (ret.Failed()) return ret;
359 break;
362 default:
363 return CMD_ERROR;
366 CommandCost ret = CheckAllowRemoveRoad(tile, pieces, GetRoadOwner(tile, rtt), rtt, flags, town_check);
367 if (ret.Failed()) return ret;
369 if (!IsTileType(tile, MP_ROAD)) {
370 /* If it's the last roadtype, just clear the whole tile */
371 if (GetRoadType(tile, OtherRoadTramType(rtt)) == INVALID_ROADTYPE) return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
373 CommandCost cost(EXPENSES_CONSTRUCTION);
374 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
375 /* Removing any roadbit in the bridge axis removes the roadtype (that's the behaviour remove-long-roads needs) */
376 if ((AxisToRoadBits(DiagDirToAxis(GetTunnelBridgeDirection(tile))) & pieces) == ROAD_NONE) return_cmd_error((rtt == RTT_TRAM) ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
378 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
379 /* Pay for *every* tile of the bridge or tunnel */
380 uint len = GetTunnelBridgeLength(other_end, tile) + 2;
381 cost.AddCost(len * 2 * RoadClearCost(existing_rt));
382 if (flags & DC_EXEC) {
383 /* A full diagonal road tile has two road bits. */
384 UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -(int)(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR));
386 SetRoadType(other_end, rtt, INVALID_ROADTYPE);
387 SetRoadType(tile, rtt, INVALID_ROADTYPE);
389 /* If the owner of the bridge sells all its road, also move the ownership
390 * to the owner of the other roadtype, unless the bridge owner is a town. */
391 Owner other_owner = GetRoadOwner(tile, OtherRoadTramType(rtt));
392 if (!IsTileOwner(tile, other_owner) && !IsTileOwner(tile, OWNER_TOWN)) {
393 SetTileOwner(tile, other_owner);
394 SetTileOwner(other_end, other_owner);
397 /* Mark tiles dirty that have been repaved */
398 if (IsBridge(tile)) {
399 MarkBridgeDirty(tile);
400 } else {
401 MarkTileDirtyByTile(tile);
402 MarkTileDirtyByTile(other_end);
405 } else {
406 assert(IsDriveThroughStopTile(tile));
407 cost.AddCost(RoadClearCost(existing_rt) * 2);
408 if (flags & DC_EXEC) {
409 /* A full diagonal road tile has two road bits. */
410 UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -2);
411 SetRoadType(tile, rtt, INVALID_ROADTYPE);
412 MarkTileDirtyByTile(tile);
415 return cost;
418 switch (GetRoadTileType(tile)) {
419 case ROAD_TILE_NORMAL: {
420 Slope tileh = GetTileSlope(tile);
422 /* Steep slopes behave the same as slopes with one corner raised. */
423 if (IsSteepSlope(tileh)) {
424 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
427 RoadBits present = GetRoadBits(tile, rtt);
428 const RoadBits other = GetRoadBits(tile, OtherRoadTramType(rtt));
429 const Foundation f = GetRoadFoundation(tileh, present);
431 if (HasRoadWorks(tile) && _current_company != OWNER_WATER) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
433 /* Autocomplete to a straight road
434 * @li if the bits of the other roadtypes result in another foundation
435 * @li if build on slopes is disabled */
436 if ((IsStraightRoad(other) && (other & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) != ROAD_NONE) ||
437 (tileh != SLOPE_FLAT && !_settings_game.construction.build_on_slopes)) {
438 pieces |= MirrorRoadBits(pieces);
441 /* limit the bits to delete to the existing bits. */
442 pieces &= present;
443 if (pieces == ROAD_NONE) return_cmd_error((rtt == RTT_TRAM) ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
445 /* Now set present what it will be after the remove */
446 present ^= pieces;
448 /* Check for invalid RoadBit combinations on slopes */
449 if (tileh != SLOPE_FLAT && present != ROAD_NONE &&
450 (present & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) == present) {
451 return CMD_ERROR;
454 if (flags & DC_EXEC) {
455 if (HasRoadWorks(tile)) {
456 /* flooding tile with road works, don't forget to remove the effect vehicle too */
457 assert(_current_company == OWNER_WATER);
458 for (EffectVehicle *v : EffectVehicle::Iterate()) {
459 if (TileVirtXY(v->x_pos, v->y_pos) == tile) {
460 delete v;
465 UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -(int)CountBits(pieces));
467 if (present == ROAD_NONE) {
468 /* No other road type, just clear tile. */
469 if (GetRoadType(tile, OtherRoadTramType(rtt)) == INVALID_ROADTYPE) {
470 /* Includes MarkTileDirtyByTile() */
471 DoClearSquare(tile);
472 } else {
473 if (rtt == RTT_ROAD && IsRoadOwner(tile, rtt, OWNER_TOWN)) {
474 /* Update nearest-town index */
475 const Town *town = CalcClosestTownFromTile(tile);
476 SetTownIndex(tile, town == nullptr ? INVALID_TOWN : town->index);
478 SetRoadBits(tile, ROAD_NONE, rtt);
479 SetRoadType(tile, rtt, INVALID_ROADTYPE);
480 MarkTileDirtyByTile(tile);
482 } else {
483 /* When bits are removed, you *always* end up with something that
484 * is not a complete straight road tile. However, trams do not have
485 * onewayness, so they cannot remove it either. */
486 if (rtt == RTT_ROAD) SetDisallowedRoadDirections(tile, DRD_NONE);
487 SetRoadBits(tile, present, rtt);
488 MarkTileDirtyByTile(tile);
492 CommandCost cost(EXPENSES_CONSTRUCTION, CountBits(pieces) * RoadClearCost(existing_rt));
493 /* If we build a foundation we have to pay for it. */
494 if (f == FOUNDATION_NONE && GetRoadFoundation(tileh, present) != FOUNDATION_NONE) cost.AddCost(_price[PR_BUILD_FOUNDATION]);
496 return cost;
499 case ROAD_TILE_CROSSING: {
500 if (pieces & ComplementRoadBits(GetCrossingRoadBits(tile))) {
501 return CMD_ERROR;
504 if (flags & DC_EXEC) {
505 /* A full diagonal road tile has two road bits. */
506 UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -2);
508 Track railtrack = GetCrossingRailTrack(tile);
509 if (GetRoadType(tile, OtherRoadTramType(rtt)) == INVALID_ROADTYPE) {
510 TrackBits tracks = GetCrossingRailBits(tile);
511 bool reserved = HasCrossingReservation(tile);
512 MakeRailNormal(tile, GetTileOwner(tile), tracks, GetRailType(tile));
513 if (reserved) SetTrackReservation(tile, tracks);
515 /* Update rail count for level crossings. The plain track should still be accounted
516 * for, so only subtract the difference to the level crossing cost. */
517 Company *c = Company::GetIfValid(GetTileOwner(tile));
518 if (c != nullptr) {
519 c->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
520 DirtyCompanyInfrastructureWindows(c->index);
522 } else {
523 SetRoadType(tile, rtt, INVALID_ROADTYPE);
525 MarkTileDirtyByTile(tile);
526 YapfNotifyTrackLayoutChange(tile, railtrack);
528 return CommandCost(EXPENSES_CONSTRUCTION, RoadClearCost(existing_rt) * 2);
531 default:
532 case ROAD_TILE_DEPOT:
533 return CMD_ERROR;
539 * Calculate the costs for roads on slopes
540 * Aside modify the RoadBits to fit on the slopes
542 * @note The RoadBits are modified too!
543 * @param tileh The current slope
544 * @param pieces The RoadBits we want to add
545 * @param existing The existent RoadBits of the current type
546 * @param other The other existent RoadBits
547 * @return The costs for these RoadBits on this slope
549 static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existing, RoadBits other)
551 /* Remove already build pieces */
552 CLRBITS(*pieces, existing);
554 /* If we can't build anything stop here */
555 if (*pieces == ROAD_NONE) return CMD_ERROR;
557 /* All RoadBit combos are valid on flat land */
558 if (tileh == SLOPE_FLAT) return CommandCost();
560 /* Steep slopes behave the same as slopes with one corner raised. */
561 if (IsSteepSlope(tileh)) {
562 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
565 /* Save the merge of all bits of the current type */
566 RoadBits type_bits = existing | *pieces;
568 /* Roads on slopes */
569 if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
571 /* If we add leveling we've got to pay for it */
572 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
574 return CommandCost();
577 /* Autocomplete uphill roads */
578 *pieces |= MirrorRoadBits(*pieces);
579 type_bits = existing | *pieces;
581 /* Uphill roads */
582 if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
583 (_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
585 /* Slopes with foundation ? */
586 if (IsSlopeWithOneCornerRaised(tileh)) {
588 /* Prevent build on slopes if it isn't allowed */
589 if (_settings_game.construction.build_on_slopes) {
591 /* If we add foundation we've got to pay for it */
592 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
594 return CommandCost();
596 } else {
597 if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
598 return CommandCost();
601 return CMD_ERROR;
605 * Build a piece of road.
606 * @param flags operation to perform
607 * @param tile tile where to build road
608 * @param pieces road pieces to build (RoadBits)
609 * @param rt road type
610 * @param toggle_drd disallowed directions to toggle
611 * @param town_id the town that is building the road (0 if not applicable)
612 * @return the cost of this operation or an error
614 CommandCost CmdBuildRoad(DoCommandFlag flags, TileIndex tile, RoadBits pieces, RoadType rt, DisallowedRoadDirections toggle_drd, TownID town_id)
616 CompanyID company = _current_company;
617 CommandCost cost(EXPENSES_CONSTRUCTION);
619 RoadBits existing = ROAD_NONE;
620 RoadBits other_bits = ROAD_NONE;
622 /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
623 * if a non-company is building the road */
624 if ((Company::IsValidID(company) && town_id != 0) || (company == OWNER_TOWN && !Town::IsValidID(town_id)) || (company == OWNER_DEITY && town_id != 0)) return CMD_ERROR;
625 if (company != OWNER_TOWN) {
626 const Town *town = CalcClosestTownFromTile(tile);
627 town_id = (town != nullptr) ? town->index : INVALID_TOWN;
629 if (company == OWNER_DEITY) {
630 company = OWNER_TOWN;
632 /* If we are not within a town, we are not owned by the town */
633 if (town == nullptr || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
634 company = OWNER_NONE;
639 /* do not allow building 'zero' road bits, code wouldn't handle it */
640 if (pieces == ROAD_NONE || !IsValidRoadBits(pieces) || !IsValidDisallowedRoadDirections(toggle_drd)) return CMD_ERROR;
641 if (!ValParamRoadType(rt)) return CMD_ERROR;
643 Slope tileh = GetTileSlope(tile);
644 RoadTramType rtt = GetRoadTramType(rt);
646 bool need_to_clear = false;
647 switch (GetTileType(tile)) {
648 case MP_ROAD:
649 switch (GetRoadTileType(tile)) {
650 case ROAD_TILE_NORMAL: {
651 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
653 other_bits = GetRoadBits(tile, OtherRoadTramType(rtt));
654 if (!HasTileRoadType(tile, rtt)) break;
656 existing = GetRoadBits(tile, rtt);
657 bool crossing = !IsStraightRoad(existing | pieces);
658 if (rtt == RTT_ROAD && (GetDisallowedRoadDirections(tile) != DRD_NONE || toggle_drd != DRD_NONE) && crossing) {
659 /* Junctions cannot be one-way */
660 return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
662 if ((existing & pieces) == pieces) {
663 /* We only want to set the (dis)allowed road directions */
664 if (toggle_drd != DRD_NONE && rtt == RTT_ROAD) {
665 if (crossing) return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
667 Owner owner = GetRoadOwner(tile, rtt);
668 if (owner != OWNER_NONE) {
669 CommandCost ret = CheckOwnership(owner, tile);
670 if (ret.Failed()) return ret;
673 DisallowedRoadDirections dis_existing = GetDisallowedRoadDirections(tile);
674 DisallowedRoadDirections dis_new = dis_existing ^ toggle_drd;
676 /* We allow removing disallowed directions to break up
677 * deadlocks, but adding them can break articulated
678 * vehicles. As such, only when less is disallowed,
679 * i.e. bits are removed, we skip the vehicle check. */
680 if (CountBits(dis_existing) <= CountBits(dis_new)) {
681 CommandCost ret = EnsureNoVehicleOnGround(tile);
682 if (ret.Failed()) return ret;
685 /* Ignore half built tiles */
686 if ((flags & DC_EXEC) && IsStraightRoad(existing)) {
687 SetDisallowedRoadDirections(tile, dis_new);
688 MarkTileDirtyByTile(tile);
690 return CommandCost();
692 return_cmd_error(STR_ERROR_ALREADY_BUILT);
694 /* Disallow breaking end-of-line of someone else
695 * so trams can still reverse on this tile. */
696 if (rtt == RTT_TRAM && HasExactlyOneBit(existing)) {
697 Owner owner = GetRoadOwner(tile, rtt);
698 if (Company::IsValidID(owner)) {
699 CommandCost ret = CheckOwnership(owner);
700 if (ret.Failed()) return ret;
703 break;
706 case ROAD_TILE_CROSSING:
707 if (RoadNoLevelCrossing(rt)) {
708 return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
711 other_bits = GetCrossingRoadBits(tile);
712 if (pieces & ComplementRoadBits(other_bits)) goto do_clear;
713 pieces = other_bits; // we need to pay for both roadbits
715 if (HasTileRoadType(tile, rtt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
716 break;
718 case ROAD_TILE_DEPOT:
719 if ((GetAnyRoadBits(tile, rtt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
720 goto do_clear;
722 default: NOT_REACHED();
724 break;
726 case MP_RAILWAY: {
727 if (IsSteepSlope(tileh)) {
728 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
731 /* Level crossings may only be built on these slopes */
732 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) {
733 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
736 if (GetRailTileType(tile) != RAIL_TILE_NORMAL) goto do_clear;
738 if (RoadNoLevelCrossing(rt)) {
739 return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
742 if (RailNoLevelCrossings(GetRailType(tile))) {
743 return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_RAIL);
746 Axis roaddir;
747 switch (GetTrackBits(tile)) {
748 case TRACK_BIT_X:
749 if (pieces & ROAD_X) goto do_clear;
750 roaddir = AXIS_Y;
751 break;
753 case TRACK_BIT_Y:
754 if (pieces & ROAD_Y) goto do_clear;
755 roaddir = AXIS_X;
756 break;
758 default: goto do_clear;
761 CommandCost ret = EnsureNoVehicleOnGround(tile);
762 if (ret.Failed()) return ret;
764 if (flags & DC_EXEC) {
765 Track railtrack = AxisToTrack(OtherAxis(roaddir));
766 YapfNotifyTrackLayoutChange(tile, railtrack);
767 /* Update company infrastructure counts. A level crossing has two road bits. */
768 UpdateCompanyRoadInfrastructure(rt, company, 2);
770 /* Update rail count for level crossings. The plain track is already
771 * counted, so only add the difference to the level crossing cost. */
772 Company *c = Company::GetIfValid(GetTileOwner(tile));
773 if (c != nullptr) {
774 c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
775 DirtyCompanyInfrastructureWindows(c->index);
778 /* Always add road to the roadtypes (can't draw without it) */
779 bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
780 MakeRoadCrossing(tile, company, company, GetTileOwner(tile), roaddir, GetRailType(tile), rtt == RTT_ROAD ? rt : INVALID_ROADTYPE, (rtt == RTT_TRAM) ? rt : INVALID_ROADTYPE, town_id);
781 SetCrossingReservation(tile, reserved);
782 UpdateLevelCrossing(tile, false);
783 MarkTileDirtyByTile(tile);
785 return CommandCost(EXPENSES_CONSTRUCTION, 2 * RoadBuildCost(rt));
788 case MP_STATION: {
789 if ((GetAnyRoadBits(tile, rtt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
790 if (!IsDriveThroughStopTile(tile)) goto do_clear;
792 RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
793 if (pieces & ~curbits) goto do_clear;
794 pieces = curbits; // we need to pay for both roadbits
796 if (HasTileRoadType(tile, rtt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
797 break;
800 case MP_TUNNELBRIDGE: {
801 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
802 /* Only allow building the outern roadbit, so building long roads stops at existing bridges */
803 if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != pieces) goto do_clear;
804 if (HasTileRoadType(tile, rtt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
805 /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
806 CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
807 if (ret.Failed()) return ret;
808 break;
811 default: {
812 do_clear:;
813 need_to_clear = true;
814 break;
818 if (need_to_clear) {
819 CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
820 if (ret.Failed()) return ret;
821 cost.AddCost(ret);
824 if (other_bits != pieces) {
825 /* Check the foundation/slopes when adding road/tram bits */
826 CommandCost ret = CheckRoadSlope(tileh, &pieces, existing, other_bits);
827 /* Return an error if we need to build a foundation (ret != 0) but the
828 * current setting is turned off */
829 if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
830 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
832 cost.AddCost(ret);
835 if (!need_to_clear) {
836 if (IsTileType(tile, MP_ROAD)) {
837 /* Don't put the pieces that already exist */
838 pieces &= ComplementRoadBits(existing);
840 /* Check if new road bits will have the same foundation as other existing road types */
841 if (IsNormalRoad(tile)) {
842 Slope slope = GetTileSlope(tile);
843 Foundation found_new = GetRoadFoundation(slope, pieces | existing);
845 RoadBits bits = GetRoadBits(tile, OtherRoadTramType(rtt));
846 /* do not check if there are not road bits of given type */
847 if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
848 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
853 CommandCost ret = EnsureNoVehicleOnGround(tile);
854 if (ret.Failed()) return ret;
856 if (IsNormalRoadTile(tile)) {
857 /* If the road types don't match, try to convert only if vehicles of
858 * the new road type are not powered on the present road type and vehicles of
859 * the present road type are powered on the new road type. */
860 RoadType existing_rt = GetRoadType(tile, rtt);
861 if (existing_rt != INVALID_ROADTYPE && existing_rt != rt) {
862 if (HasPowerOnRoad(rt, existing_rt)) {
863 rt = existing_rt;
864 } else if (HasPowerOnRoad(existing_rt, rt)) {
865 CommandCost ret = Command<CMD_CONVERT_ROAD>::Do(flags, tile, tile, rt);
866 if (ret.Failed()) return ret;
867 cost.AddCost(ret);
868 } else {
869 return CMD_ERROR;
875 uint num_pieces = (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) ?
876 /* There are 2 pieces on *every* tile of the bridge or tunnel */
877 2 * (GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2) :
878 /* Count pieces */
879 CountBits(pieces);
881 cost.AddCost(num_pieces * RoadBuildCost(rt));
883 if (flags & DC_EXEC) {
884 switch (GetTileType(tile)) {
885 case MP_ROAD: {
886 RoadTileType rttype = GetRoadTileType(tile);
887 if (existing == ROAD_NONE || rttype == ROAD_TILE_CROSSING) {
888 SetRoadType(tile, rtt, rt);
889 SetRoadOwner(tile, rtt, company);
890 if (rtt == RTT_ROAD) SetTownIndex(tile, town_id);
892 if (rttype != ROAD_TILE_CROSSING) SetRoadBits(tile, existing | pieces, rtt);
893 break;
896 case MP_TUNNELBRIDGE: {
897 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
899 SetRoadType(other_end, rtt, rt);
900 SetRoadType(tile, rtt, rt);
901 SetRoadOwner(other_end, rtt, company);
902 SetRoadOwner(tile, rtt, company);
904 /* Mark tiles dirty that have been repaved */
905 if (IsBridge(tile)) {
906 MarkBridgeDirty(tile);
907 } else {
908 MarkTileDirtyByTile(other_end);
909 MarkTileDirtyByTile(tile);
911 break;
914 case MP_STATION: {
915 assert(IsDriveThroughStopTile(tile));
916 SetRoadType(tile, rtt, rt);
917 SetRoadOwner(tile, rtt, company);
918 break;
921 default:
922 MakeRoadNormal(tile, pieces, (rtt == RTT_ROAD) ? rt : INVALID_ROADTYPE, (rtt == RTT_TRAM) ? rt : INVALID_ROADTYPE, town_id, company, company);
923 break;
926 /* Update company infrastructure count. */
927 if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
928 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), num_pieces);
930 if (rtt == RTT_ROAD && IsNormalRoadTile(tile)) {
931 existing |= pieces;
932 SetDisallowedRoadDirections(tile, IsStraightRoad(existing) ?
933 GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
936 MarkTileDirtyByTile(tile);
938 return cost;
942 * Checks whether a road or tram connection can be found when building a new road or tram.
943 * @param tile Tile at which the road being built will end.
944 * @param rt Roadtype of the road being built.
945 * @param dir Direction that the road is following.
946 * @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.
948 static bool CanConnectToRoad(TileIndex tile, RoadType rt, DiagDirection dir)
950 tile += TileOffsByDiagDir(dir);
951 if (!IsValidTile(tile) || !MayHaveRoad(tile)) return false;
953 RoadTramType rtt = GetRoadTramType(rt);
954 RoadType existing = GetRoadType(tile, rtt);
955 if (existing == INVALID_ROADTYPE) return false;
956 if (!HasPowerOnRoad(existing, rt) && !HasPowerOnRoad(rt, existing)) return false;
958 RoadBits bits = GetAnyRoadBits(tile, rtt, false);
959 return (bits & DiagDirToRoadBits(ReverseDiagDir(dir))) != 0;
963 * Build a long piece of road.
964 * @param flags operation to perform
965 * @param end_tile end tile of drag
966 * @param start_tile start tile of drag
967 * @param rt road type
968 * @param axis direction
969 * @param drd set road direction
970 * @param start_half start tile starts in the 2nd half of tile (p2 & 1). Only used if \c is_ai is set or if we are building a single tile
971 * @param end_half end tile starts in the 2nd half of tile (p2 & 2). Only used if \c is_ai is set or if we are building a single tile
972 * @param is_ai defines two different behaviors for this command:
973 * - false = 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
974 * - true = Fail if an obstacle is found. Always take into account start_half and end_half. This behavior is used for scripts
975 * @return the cost of this operation or an error
977 CommandCost CmdBuildLongRoad(DoCommandFlag flags, TileIndex end_tile, TileIndex start_tile, RoadType rt, Axis axis, DisallowedRoadDirections drd, bool start_half, bool end_half, bool is_ai)
979 if (start_tile >= MapSize()) return CMD_ERROR;
981 if (!ValParamRoadType(rt) || !IsValidAxis(axis) || !IsValidDisallowedRoadDirections(drd)) return CMD_ERROR;
983 /* Only drag in X or Y direction dictated by the direction variable */
984 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
985 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
987 DiagDirection dir = AxisToDiagDir(axis);
989 /* Swap direction, also the half-tile drag vars. */
990 if (start_tile > end_tile || (start_tile == end_tile && start_half)) {
991 dir = ReverseDiagDir(dir);
992 start_half = !start_half;
993 end_half = !end_half;
994 if (drd == DRD_NORTHBOUND || drd == DRD_SOUTHBOUND) drd ^= DRD_BOTH;
997 /* On the X-axis, we have to swap the initial bits, so they
998 * will be interpreted correctly in the GTTS. Furthermore
999 * when you just 'click' on one tile to build them. */
1000 if ((drd == DRD_NORTHBOUND || drd == DRD_SOUTHBOUND) && (axis == AXIS_Y) == (start_tile == end_tile && start_half == end_half)) drd ^= DRD_BOTH;
1002 CommandCost cost(EXPENSES_CONSTRUCTION);
1003 CommandCost last_error = CMD_ERROR;
1004 TileIndex tile = start_tile;
1005 bool had_bridge = false;
1006 bool had_tunnel = false;
1007 bool had_success = false;
1009 /* Start tile is the first tile clicked by the user. */
1010 for (;;) {
1011 RoadBits bits = AxisToRoadBits(axis);
1013 /* Determine which road parts should be built. */
1014 if (!is_ai && start_tile != end_tile) {
1015 /* Only build the first and last roadbit if they can connect to something. */
1016 if (tile == end_tile && !CanConnectToRoad(tile, rt, dir)) {
1017 bits = DiagDirToRoadBits(ReverseDiagDir(dir));
1018 } else if (tile == start_tile && !CanConnectToRoad(tile, rt, ReverseDiagDir(dir))) {
1019 bits = DiagDirToRoadBits(dir);
1021 } else {
1022 /* Road parts only have to be built at the start tile or at the end tile. */
1023 if (tile == end_tile && !end_half) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
1024 if (tile == start_tile && start_half) bits &= DiagDirToRoadBits(dir);
1027 CommandCost ret = Command<CMD_BUILD_ROAD>::Do(flags, tile, bits, rt, drd, 0);
1028 if (ret.Failed()) {
1029 last_error = ret;
1030 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
1031 if (is_ai) return last_error;
1032 break;
1034 } else {
1035 had_success = true;
1036 /* Only pay for the upgrade on one side of the bridges and tunnels */
1037 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1038 if (IsBridge(tile)) {
1039 if (!had_bridge || GetTunnelBridgeDirection(tile) == dir) {
1040 cost.AddCost(ret);
1042 had_bridge = true;
1043 } else { // IsTunnel(tile)
1044 if (!had_tunnel || GetTunnelBridgeDirection(tile) == dir) {
1045 cost.AddCost(ret);
1047 had_tunnel = true;
1049 } else {
1050 cost.AddCost(ret);
1054 if (tile == end_tile) break;
1056 tile += TileOffsByDiagDir(dir);
1059 return had_success ? cost : last_error;
1063 * Remove a long piece of road.
1064 * @param flags operation to perform
1065 * @param end_tile end tile of drag
1066 * @param start_tile start tile of drag
1067 * @param rt road type
1068 * @param axis direction
1069 * @param start_half start tile starts in the 2nd half of tile
1070 * @param end_half end tile starts in the 2nd half of tile (p2 & 2)
1071 * @return the cost of this operation or an error
1073 std::tuple<CommandCost, Money> CmdRemoveLongRoad(DoCommandFlag flags, TileIndex end_tile, TileIndex start_tile, RoadType rt, Axis axis, bool start_half, bool end_half)
1075 CommandCost cost(EXPENSES_CONSTRUCTION);
1077 if (start_tile >= MapSize()) return { CMD_ERROR, 0 };
1078 if (!ValParamRoadType(rt) || !IsValidAxis(axis)) return { CMD_ERROR, 0 };
1080 /* Only drag in X or Y direction dictated by the direction variable */
1081 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return { CMD_ERROR, 0 }; // x-axis
1082 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return { CMD_ERROR, 0 }; // y-axis
1084 /* Swap start and ending tile, also the half-tile drag vars. */
1085 if (start_tile > end_tile || (start_tile == end_tile && start_half)) {
1086 std::swap(start_tile, end_tile);
1087 std::swap(start_half, end_half);
1090 Money money_available = GetAvailableMoneyForCommand();
1091 Money money_spent = 0;
1092 TileIndex tile = start_tile;
1093 CommandCost last_error = CMD_ERROR;
1094 bool had_success = false;
1095 /* Start tile is the small number. */
1096 for (;;) {
1097 RoadBits bits = AxisToRoadBits(axis);
1099 if (tile == end_tile && !end_half) bits &= ROAD_NW | ROAD_NE;
1100 if (tile == start_tile && start_half) bits &= ROAD_SE | ROAD_SW;
1102 /* try to remove the halves. */
1103 if (bits != 0) {
1104 RoadTramType rtt = GetRoadTramType(rt);
1105 CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rtt, true);
1106 if (ret.Succeeded()) {
1107 if (flags & DC_EXEC) {
1108 money_spent += ret.GetCost();
1109 if (money_spent > 0 && money_spent > money_available) {
1110 return { cost, std::get<0>(Command<CMD_REMOVE_LONG_ROAD>::Do(flags & ~DC_EXEC, end_tile, start_tile, rt, axis, start_half, end_half)).GetCost() };
1112 RemoveRoad(tile, flags, bits, rtt, true, false);
1114 cost.AddCost(ret);
1115 had_success = true;
1116 } else {
1117 /* Some errors are more equal than others. */
1118 switch (last_error.GetErrorMessage()) {
1119 case STR_ERROR_OWNED_BY:
1120 case STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS:
1121 break;
1122 default:
1123 last_error = ret;
1128 if (tile == end_tile) break;
1130 tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
1133 return { had_success ? cost : last_error, 0 };
1137 * Build a road depot.
1138 * @param tile tile where to build the depot
1139 * @param flags operation to perform
1140 * @param rt road type
1141 * @param dir entrance direction
1142 * @return the cost of this operation or an error
1144 * @todo When checking for the tile slope,
1145 * distinguish between "Flat land required" and "land sloped in wrong direction"
1147 CommandCost CmdBuildRoadDepot(DoCommandFlag flags, TileIndex tile, RoadType rt, DiagDirection dir)
1149 if (!ValParamRoadType(rt) || !IsValidDiagDirection(dir)) return CMD_ERROR;
1151 CommandCost cost(EXPENSES_CONSTRUCTION);
1153 Slope tileh = GetTileSlope(tile);
1154 if (tileh != SLOPE_FLAT) {
1155 if (!_settings_game.construction.build_on_slopes || !CanBuildDepotByTileh(dir, tileh)) {
1156 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
1158 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
1161 cost.AddCost(Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile));
1162 if (cost.Failed()) return cost;
1164 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1166 if (!Depot::CanAllocateItem()) return CMD_ERROR;
1168 if (flags & DC_EXEC) {
1169 Depot *dep = new Depot(tile);
1170 dep->build_date = _date;
1172 /* A road depot has two road bits. */
1173 UpdateCompanyRoadInfrastructure(rt, _current_company, ROAD_DEPOT_TRACKBIT_FACTOR);
1175 MakeRoadDepot(tile, _current_company, dep->index, dir, rt);
1176 MarkTileDirtyByTile(tile);
1177 MakeDefaultName(dep);
1179 cost.AddCost(_price[PR_BUILD_DEPOT_ROAD]);
1180 return cost;
1183 static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
1185 if (_current_company != OWNER_WATER) {
1186 CommandCost ret = CheckTileOwnership(tile);
1187 if (ret.Failed()) return ret;
1190 CommandCost ret = EnsureNoVehicleOnGround(tile);
1191 if (ret.Failed()) return ret;
1193 if (flags & DC_EXEC) {
1194 Company *c = Company::GetIfValid(GetTileOwner(tile));
1195 if (c != nullptr) {
1196 /* A road depot has two road bits. */
1197 RoadType rt = GetRoadTypeRoad(tile);
1198 if (rt == INVALID_ROADTYPE) rt = GetRoadTypeTram(tile);
1199 c->infrastructure.road[rt] -= ROAD_DEPOT_TRACKBIT_FACTOR;
1200 DirtyCompanyInfrastructureWindows(c->index);
1203 delete Depot::GetByTile(tile);
1204 DoClearSquare(tile);
1207 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_ROAD]);
1210 static CommandCost ClearTile_Road(TileIndex tile, DoCommandFlag flags)
1212 switch (GetRoadTileType(tile)) {
1213 case ROAD_TILE_NORMAL: {
1214 RoadBits b = GetAllRoadBits(tile);
1216 /* Clear the road if only one piece is on the tile OR we are not using the DC_AUTO flag */
1217 if ((HasExactlyOneBit(b) && GetRoadBits(tile, RTT_TRAM) == ROAD_NONE) || !(flags & DC_AUTO)) {
1218 CommandCost ret(EXPENSES_CONSTRUCTION);
1219 for (RoadTramType rtt : _roadtramtypes) {
1220 if (!MayHaveRoad(tile) || GetRoadType(tile, rtt) == INVALID_ROADTYPE) continue;
1222 CommandCost tmp_ret = RemoveRoad(tile, flags, GetRoadBits(tile, rtt), rtt, true);
1223 if (tmp_ret.Failed()) return tmp_ret;
1224 ret.AddCost(tmp_ret);
1226 return ret;
1228 return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1231 case ROAD_TILE_CROSSING: {
1232 CommandCost ret(EXPENSES_CONSTRUCTION);
1234 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1236 /* Must iterate over the roadtypes in a reverse manner because
1237 * tram tracks must be removed before the road bits. */
1238 for (RoadTramType rtt : { RTT_TRAM, RTT_ROAD }) {
1239 if (!MayHaveRoad(tile) || GetRoadType(tile, rtt) == INVALID_ROADTYPE) continue;
1241 CommandCost tmp_ret = RemoveRoad(tile, flags, GetCrossingRoadBits(tile), rtt, false);
1242 if (tmp_ret.Failed()) return tmp_ret;
1243 ret.AddCost(tmp_ret);
1246 if (flags & DC_EXEC) {
1247 Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
1249 return ret;
1252 default:
1253 case ROAD_TILE_DEPOT:
1254 if (flags & DC_AUTO) {
1255 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1257 return RemoveRoadDepot(tile, flags);
1262 struct DrawRoadTileStruct {
1263 uint16 image;
1264 byte subcoord_x;
1265 byte subcoord_y;
1268 #include "table/road_land.h"
1271 * Get the foundationtype of a RoadBits Slope combination
1273 * @param tileh The Slope part
1274 * @param bits The RoadBits part
1275 * @return The resulting Foundation
1277 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
1279 /* Flat land and land without a road doesn't require a foundation */
1280 if (tileh == SLOPE_FLAT || bits == ROAD_NONE) return FOUNDATION_NONE;
1282 /* Steep slopes behave the same as slopes with one corner raised. */
1283 if (IsSteepSlope(tileh)) {
1284 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
1287 /* Leveled RoadBits on a slope */
1288 if ((_invalid_tileh_slopes_road[0][tileh] & bits) == ROAD_NONE) return FOUNDATION_LEVELED;
1290 /* Straight roads without foundation on a slope */
1291 if (!IsSlopeWithOneCornerRaised(tileh) &&
1292 (_invalid_tileh_slopes_road[1][tileh] & bits) == ROAD_NONE)
1293 return FOUNDATION_NONE;
1295 /* Roads on steep Slopes or on Slopes with one corner raised */
1296 return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
1299 const byte _road_sloped_sprites[14] = {
1300 0, 0, 2, 0,
1301 0, 1, 0, 0,
1302 3, 0, 0, 0,
1303 0, 0
1307 * Get the sprite offset within a spritegroup.
1308 * @param slope Slope
1309 * @param bits Roadbits
1310 * @return Offset for the sprite within the spritegroup.
1312 static uint GetRoadSpriteOffset(Slope slope, RoadBits bits)
1314 if (slope != SLOPE_FLAT) {
1315 switch (slope) {
1316 case SLOPE_NE: return 11;
1317 case SLOPE_SE: return 12;
1318 case SLOPE_SW: return 13;
1319 case SLOPE_NW: return 14;
1320 default: NOT_REACHED();
1322 } else {
1323 static const uint offsets[] = {
1324 0, 18, 17, 7,
1325 16, 0, 10, 5,
1326 15, 8, 1, 4,
1327 9, 3, 6, 2
1329 return offsets[bits];
1334 * Should the road be drawn as a unpaved snow/desert road?
1335 * By default, roads are always drawn as unpaved if they are on desert or
1336 * above the snow line, but NewGRFs can override this for desert.
1338 * @param tile The tile the road is on
1339 * @param roadside What sort of road this is
1340 * @return True if snow/desert road sprites should be used.
1342 static bool DrawRoadAsSnowDesert(TileIndex tile, Roadside roadside)
1344 return (IsOnSnow(tile) &&
1345 !(_settings_game.game_creation.landscape == LT_TROPIC && HasGrfMiscBit(GMB_DESERT_PAVED_ROADS) &&
1346 roadside != ROADSIDE_BARREN && roadside != ROADSIDE_GRASS && roadside != ROADSIDE_GRASS_ROAD_WORKS));
1350 * Draws the catenary for the RoadType of the given tile
1351 * @param ti information about the tile (slopes, height etc)
1352 * @param rt road type to draw catenary for
1353 * @param rb the roadbits for the tram
1355 void DrawRoadTypeCatenary(const TileInfo *ti, RoadType rt, RoadBits rb)
1357 /* Don't draw the catenary under a low bridge */
1358 if (IsBridgeAbove(ti->tile) && !IsTransparencySet(TO_CATENARY)) {
1359 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1361 if (height <= GetTileMaxZ(ti->tile) + 1) return;
1364 if (CountBits(rb) > 2) {
1365 /* On junctions we check whether neighbouring tiles also have catenary, and possibly
1366 * do not draw catenary towards those neighbours, which do not have catenary. */
1367 RoadBits rb_new = ROAD_NONE;
1368 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1369 if (rb & DiagDirToRoadBits(dir)) {
1370 TileIndex neighbour = TileAddByDiagDir(ti->tile, dir);
1371 if (MayHaveRoad(neighbour)) {
1372 RoadType rt_road = GetRoadTypeRoad(neighbour);
1373 RoadType rt_tram = GetRoadTypeTram(neighbour);
1375 if ((rt_road != INVALID_ROADTYPE && HasRoadCatenary(rt_road)) ||
1376 (rt_tram != INVALID_ROADTYPE && HasRoadCatenary(rt_tram))) {
1377 rb_new |= DiagDirToRoadBits(dir);
1382 if (CountBits(rb_new) >= 2) rb = rb_new;
1385 const RoadTypeInfo* rti = GetRoadTypeInfo(rt);
1386 SpriteID front = GetCustomRoadSprite(rti, ti->tile, ROTSG_CATENARY_FRONT);
1387 SpriteID back = GetCustomRoadSprite(rti, ti->tile, ROTSG_CATENARY_BACK);
1389 if (front != 0 || back != 0) {
1390 if (front != 0) front += GetRoadSpriteOffset(ti->tileh, rb);
1391 if (back != 0) back += GetRoadSpriteOffset(ti->tileh, rb);
1392 } else if (ti->tileh != SLOPE_FLAT) {
1393 back = SPR_TRAMWAY_BACK_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1394 front = SPR_TRAMWAY_FRONT_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1395 } else {
1396 back = SPR_TRAMWAY_BASE + _road_backpole_sprites_1[rb];
1397 front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[rb];
1400 /* Catenary uses 1st company colour to help identify owner.
1401 * For tiles with OWNER_TOWN or OWNER_NONE, recolour CC to grey as a neutral colour. */
1402 Owner owner = GetRoadOwner(ti->tile, GetRoadTramType(rt));
1403 PaletteID pal = (owner == OWNER_NONE || owner == OWNER_TOWN ? GENERAL_SPRITE_COLOUR(COLOUR_GREY) : COMPANY_SPRITE_COLOUR(owner));
1404 int z_wires = (ti->tileh == SLOPE_FLAT ? 0 : TILE_HEIGHT) + BB_HEIGHT_UNDER_BRIDGE;
1405 if (back != 0) {
1406 /* The "back" sprite contains the west, north and east pillars.
1407 * We cut the sprite at 3/8 of the west/east edges to create 3 sprites.
1408 * 3/8 is chosen so that sprites can somewhat graphically extend into the tile. */
1409 static const int INF = 1000; ///< big number compared to sprite size
1410 static const SubSprite west = { -INF, -INF, -12, INF };
1411 static const SubSprite north = { -12, -INF, 12, INF };
1412 static const SubSprite east = { 12, -INF, INF, INF };
1413 AddSortableSpriteToDraw(back, pal, ti->x, ti->y, 16, 1, z_wires, ti->z, IsTransparencySet(TO_CATENARY), 15, 0, GetSlopePixelZInCorner(ti->tileh, CORNER_W), &west);
1414 AddSortableSpriteToDraw(back, pal, ti->x, ti->y, 1, 1, z_wires, ti->z, IsTransparencySet(TO_CATENARY), 0, 0, GetSlopePixelZInCorner(ti->tileh, CORNER_N), &north);
1415 AddSortableSpriteToDraw(back, pal, ti->x, ti->y, 1, 16, z_wires, ti->z, IsTransparencySet(TO_CATENARY), 0, 15, GetSlopePixelZInCorner(ti->tileh, CORNER_E), &east);
1417 if (front != 0) {
1418 /* Draw the "front" sprite (containing south pillar and wires) at a Z height that is both above the vehicles and above the "back" pillars. */
1419 AddSortableSpriteToDraw(front, pal, ti->x, ti->y, 16, 16, z_wires + 1, ti->z, IsTransparencySet(TO_CATENARY), 0, 0, z_wires);
1424 * Draws the catenary for the given tile
1425 * @param ti information about the tile (slopes, height etc)
1427 void DrawRoadCatenary(const TileInfo *ti)
1429 RoadBits road = ROAD_NONE;
1430 RoadBits tram = ROAD_NONE;
1432 if (IsTileType(ti->tile, MP_ROAD)) {
1433 if (IsNormalRoad(ti->tile)) {
1434 road = GetRoadBits(ti->tile, RTT_ROAD);
1435 tram = GetRoadBits(ti->tile, RTT_TRAM);
1436 } else if (IsLevelCrossing(ti->tile)) {
1437 tram = road = (GetCrossingRailAxis(ti->tile) == AXIS_Y ? ROAD_X : ROAD_Y);
1439 } else if (IsTileType(ti->tile, MP_STATION)) {
1440 if (IsRoadStop(ti->tile)) {
1441 if (IsDriveThroughStopTile(ti->tile)) {
1442 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
1443 tram = road = (axis == AXIS_X ? ROAD_X : ROAD_Y);
1444 } else {
1445 tram = road = DiagDirToRoadBits(GetRoadStopDir(ti->tile));
1448 } else {
1449 // No road here, no catenary to draw
1450 return;
1453 RoadType rt = GetRoadTypeRoad(ti->tile);
1454 if (rt != INVALID_ROADTYPE && HasRoadCatenaryDrawn(rt)) {
1455 DrawRoadTypeCatenary(ti, rt, road);
1458 rt = GetRoadTypeTram(ti->tile);
1459 if (rt != INVALID_ROADTYPE && HasRoadCatenaryDrawn(rt)) {
1460 DrawRoadTypeCatenary(ti, rt, tram);
1465 * Draws details on/around the road
1466 * @param img the sprite to draw
1467 * @param ti the tile to draw on
1468 * @param dx the offset from the top of the BB of the tile
1469 * @param dy the offset from the top of the BB of the tile
1470 * @param h the height of the sprite to draw
1471 * @param transparent whether the sprite should be transparent (used for roadside trees)
1473 static void DrawRoadDetail(SpriteID img, const TileInfo *ti, int dx, int dy, int h, bool transparent)
1475 int x = ti->x | dx;
1476 int y = ti->y | dy;
1477 int z = ti->z;
1478 if (ti->tileh != SLOPE_FLAT) z = GetSlopePixelZ(x, y);
1479 AddSortableSpriteToDraw(img, PAL_NONE, x, y, 2, 2, h, z, transparent);
1483 * Draw road underlay and overlay sprites.
1484 * @param ti TileInfo
1485 * @param road_rti Road road type information
1486 * @param tram_rti Tram road type information
1487 * @param road_offset Road sprite offset (based on road bits)
1488 * @param tram_offset Tram sprite offset (based on road bits)
1490 void DrawRoadOverlays(const TileInfo *ti, PaletteID pal, const RoadTypeInfo *road_rti, const RoadTypeInfo *tram_rti, uint road_offset, uint tram_offset)
1492 /* Road underlay takes precedence over tram */
1493 if (road_rti != nullptr) {
1494 if (road_rti->UsesOverlay()) {
1495 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_GROUND);
1496 DrawGroundSprite(ground + road_offset, pal);
1498 } else {
1499 if (tram_rti->UsesOverlay()) {
1500 SpriteID ground = GetCustomRoadSprite(tram_rti, ti->tile, ROTSG_GROUND);
1501 DrawGroundSprite(ground + tram_offset, pal);
1502 } else {
1503 DrawGroundSprite(SPR_TRAMWAY_TRAM + tram_offset, pal);
1507 /* Draw road overlay */
1508 if (road_rti != nullptr) {
1509 if (road_rti->UsesOverlay()) {
1510 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_OVERLAY);
1511 if (ground != 0) DrawGroundSprite(ground + road_offset, pal);
1515 /* Draw tram overlay */
1516 if (tram_rti != nullptr) {
1517 if (tram_rti->UsesOverlay()) {
1518 SpriteID ground = GetCustomRoadSprite(tram_rti, ti->tile, ROTSG_OVERLAY);
1519 if (ground != 0) DrawGroundSprite(ground + tram_offset, pal);
1520 } else if (road_rti != nullptr) {
1521 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + tram_offset, pal);
1527 * Get ground sprite to draw for a road tile.
1528 * @param ti TileInof
1529 * @param roadside Road side type
1530 * @param rti Road type info
1531 * @param offset Road sprite offset
1532 * @param[out] pal Palette to draw.
1534 static SpriteID GetRoadGroundSprite(const TileInfo *ti, Roadside roadside, const RoadTypeInfo *rti, uint offset, PaletteID *pal)
1536 /* Draw bare ground sprite if no road or road uses overlay system. */
1537 if (rti == nullptr || rti->UsesOverlay()) {
1538 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1539 return SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh);
1542 switch (roadside) {
1543 case ROADSIDE_BARREN: *pal = PALETTE_TO_BARE_LAND;
1544 return SPR_FLAT_GRASS_TILE + SlopeToSpriteOffset(ti->tileh);
1545 case ROADSIDE_GRASS:
1546 case ROADSIDE_GRASS_ROAD_WORKS: return SPR_FLAT_GRASS_TILE + SlopeToSpriteOffset(ti->tileh);
1547 default: break; // Paved
1551 /* Draw original road base sprite */
1552 SpriteID image = SPR_ROAD_Y + offset;
1553 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1554 image += 19;
1555 } else {
1556 switch (roadside) {
1557 case ROADSIDE_BARREN: *pal = PALETTE_TO_BARE_LAND; break;
1558 case ROADSIDE_GRASS: break;
1559 case ROADSIDE_GRASS_ROAD_WORKS: break;
1560 default: image -= 19; break; // Paved
1564 return image;
1568 * Draw ground sprite and road pieces
1569 * @param ti TileInfo
1571 static void DrawRoadBits(TileInfo *ti)
1573 RoadBits road = GetRoadBits(ti->tile, RTT_ROAD);
1574 RoadBits tram = GetRoadBits(ti->tile, RTT_TRAM);
1576 RoadType road_rt = GetRoadTypeRoad(ti->tile);
1577 RoadType tram_rt = GetRoadTypeTram(ti->tile);
1578 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
1579 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
1581 if (ti->tileh != SLOPE_FLAT) {
1582 DrawFoundation(ti, GetRoadFoundation(ti->tileh, road | tram));
1583 /* DrawFoundation() modifies ti. */
1586 /* Determine sprite offsets */
1587 uint road_offset = GetRoadSpriteOffset(ti->tileh, road);
1588 uint tram_offset = GetRoadSpriteOffset(ti->tileh, tram);
1590 /* Draw baseset underlay */
1591 Roadside roadside = GetRoadside(ti->tile);
1593 PaletteID pal = PAL_NONE;
1594 SpriteID image = GetRoadGroundSprite(ti, roadside, road_rti, road == ROAD_NONE ? tram_offset : road_offset, &pal);
1595 DrawGroundSprite(image, pal);
1597 DrawRoadOverlays(ti, pal, road_rti, tram_rti, road_offset, tram_offset);
1599 /* Draw one way */
1600 if (road_rti != nullptr) {
1601 DisallowedRoadDirections drd = GetDisallowedRoadDirections(ti->tile);
1602 if (drd != DRD_NONE) {
1603 DrawGroundSpriteAt(SPR_ONEWAY_BASE + drd - 1 + ((road == ROAD_X) ? 0 : 3), PAL_NONE, 8, 8, GetPartialPixelZ(8, 8, ti->tileh));
1607 if (HasRoadWorks(ti->tile)) {
1608 /* Road works */
1609 DrawGroundSprite((road | tram) & ROAD_X ? SPR_EXCAVATION_X : SPR_EXCAVATION_Y, PAL_NONE);
1610 return;
1613 /* Draw road, tram catenary */
1614 DrawRoadCatenary(ti);
1616 /* Return if full detail is disabled, or we are zoomed fully out. */
1617 if (!HasBit(_display_opt, DO_FULL_DETAIL) || _cur_dpi->zoom > ZOOM_LVL_DETAIL) return;
1619 /* Do not draw details (street lights, trees) under low bridge */
1620 if (IsBridgeAbove(ti->tile) && (roadside == ROADSIDE_TREES || roadside == ROADSIDE_STREET_LIGHTS)) {
1621 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1622 int minz = GetTileMaxZ(ti->tile) + 2;
1624 if (roadside == ROADSIDE_TREES) minz++;
1626 if (height < minz) return;
1629 /* If there are no road bits, return, as there is nothing left to do */
1630 if (HasAtMostOneBit(road)) return;
1632 if (roadside == ROADSIDE_TREES && IsInvisibilitySet(TO_TREES)) return;
1633 bool is_transparent = roadside == ROADSIDE_TREES && IsTransparencySet(TO_TREES);
1635 /* Draw extra details. */
1636 for (const DrawRoadTileStruct *drts = _road_display_table[roadside][road | tram]; drts->image != 0; drts++) {
1637 DrawRoadDetail(drts->image, ti, drts->subcoord_x, drts->subcoord_y, 0x10, is_transparent);
1641 /** Tile callback function for rendering a road tile to the screen */
1642 static void DrawTile_Road(TileInfo *ti)
1644 switch (GetRoadTileType(ti->tile)) {
1645 case ROAD_TILE_NORMAL:
1646 DrawRoadBits(ti);
1647 break;
1649 case ROAD_TILE_CROSSING: {
1650 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1652 Axis axis = GetCrossingRailAxis(ti->tile);
1654 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1656 RoadType road_rt = GetRoadTypeRoad(ti->tile);
1657 RoadType tram_rt = GetRoadTypeTram(ti->tile);
1658 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
1659 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
1661 PaletteID pal = PAL_NONE;
1663 /* Draw base ground */
1664 if (rti->UsesOverlay()) {
1665 SpriteID image = SPR_ROAD_Y + axis;
1667 Roadside roadside = GetRoadside(ti->tile);
1668 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1669 image += 19;
1670 } else {
1671 switch (roadside) {
1672 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1673 case ROADSIDE_GRASS: break;
1674 default: image -= 19; break; // Paved
1678 DrawGroundSprite(image, pal);
1679 } else {
1680 SpriteID image = rti->base_sprites.crossing + axis;
1681 if (IsCrossingBarred(ti->tile)) image += 2;
1683 Roadside roadside = GetRoadside(ti->tile);
1684 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1685 image += 8;
1686 } else {
1687 switch (roadside) {
1688 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1689 case ROADSIDE_GRASS: break;
1690 default: image += 4; break; // Paved
1694 DrawGroundSprite(image, pal);
1697 DrawRoadOverlays(ti, pal, road_rti, tram_rti, axis, axis);
1699 /* Draw rail/PBS overlay */
1700 bool draw_pbs = _game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile);
1701 if (rti->UsesOverlay()) {
1702 PaletteID pal = draw_pbs ? PALETTE_CRASH : PAL_NONE;
1703 SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
1704 DrawGroundSprite(rail, pal);
1706 DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
1707 } else if (draw_pbs || tram_rti != nullptr || road_rti->UsesOverlay()) {
1708 /* Add another rail overlay, unless there is only the base road sprite. */
1709 PaletteID pal = draw_pbs ? PALETTE_CRASH : PAL_NONE;
1710 SpriteID rail = GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y;
1711 DrawGroundSprite(rail, pal);
1714 /* Draw road, tram catenary */
1715 DrawRoadCatenary(ti);
1717 /* Draw rail catenary */
1718 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
1720 break;
1723 default:
1724 case ROAD_TILE_DEPOT: {
1725 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1727 PaletteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
1729 RoadType road_rt = GetRoadTypeRoad(ti->tile);
1730 RoadType tram_rt = GetRoadTypeTram(ti->tile);
1731 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt == INVALID_ROADTYPE ? tram_rt : road_rt);
1733 int relocation = GetCustomRoadSprite(rti, ti->tile, ROTSG_DEPOT);
1734 bool default_gfx = relocation == 0;
1735 if (default_gfx) {
1736 if (HasBit(rti->flags, ROTF_CATENARY)) {
1737 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK && road_rt == INVALID_ROADTYPE && !rti->UsesOverlay()) {
1738 /* Sprites with track only work for default tram */
1739 relocation = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_ROAD_DEPOT;
1740 default_gfx = false;
1741 } else {
1742 /* Sprites without track are always better, if provided */
1743 relocation = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_ROAD_DEPOT;
1746 } else {
1747 relocation -= SPR_ROAD_DEPOT;
1750 DiagDirection dir = GetRoadDepotDirection(ti->tile);
1751 const DrawTileSprites *dts = &_road_depot[dir];
1752 DrawGroundSprite(dts->ground.sprite, PAL_NONE);
1754 if (default_gfx) {
1755 uint offset = GetRoadSpriteOffset(SLOPE_FLAT, DiagDirToRoadBits(dir));
1756 if (rti->UsesOverlay()) {
1757 SpriteID ground = GetCustomRoadSprite(rti, ti->tile, ROTSG_OVERLAY);
1758 if (ground != 0) DrawGroundSprite(ground + offset, PAL_NONE);
1759 } else if (road_rt == INVALID_ROADTYPE) {
1760 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + offset, PAL_NONE);
1764 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, palette);
1765 break;
1768 DrawBridgeMiddle(ti);
1772 * Draw the road depot sprite.
1773 * @param x The x offset to draw at.
1774 * @param y The y offset to draw at.
1775 * @param dir The direction the depot must be facing.
1776 * @param rt The road type of the depot to draw.
1778 void DrawRoadDepotSprite(int x, int y, DiagDirection dir, RoadType rt)
1780 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
1782 const RoadTypeInfo* rti = GetRoadTypeInfo(rt);
1783 int relocation = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_DEPOT);
1784 bool default_gfx = relocation == 0;
1785 if (default_gfx) {
1786 if (HasBit(rti->flags, ROTF_CATENARY)) {
1787 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK && RoadTypeIsTram(rt) && !rti->UsesOverlay()) {
1788 /* Sprites with track only work for default tram */
1789 relocation = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_ROAD_DEPOT;
1790 default_gfx = false;
1791 } else {
1792 /* Sprites without track are always better, if provided */
1793 relocation = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_ROAD_DEPOT;
1796 } else {
1797 relocation -= SPR_ROAD_DEPOT;
1800 const DrawTileSprites *dts = &_road_depot[dir];
1801 DrawSprite(dts->ground.sprite, PAL_NONE, x, y);
1803 if (default_gfx) {
1804 uint offset = GetRoadSpriteOffset(SLOPE_FLAT, DiagDirToRoadBits(dir));
1805 if (rti->UsesOverlay()) {
1806 SpriteID ground = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_OVERLAY);
1807 if (ground != 0) DrawSprite(ground + offset, PAL_NONE, x, y);
1808 } else if (RoadTypeIsTram(rt)) {
1809 DrawSprite(SPR_TRAMWAY_OVERLAY + offset, PAL_NONE, x, y);
1813 DrawRailTileSeqInGUI(x, y, dts, relocation, 0, palette);
1817 * Updates cached nearest town for all road tiles
1818 * @param invalidate are we just invalidating cached data?
1819 * @pre invalidate == true implies _generating_world == true
1821 void UpdateNearestTownForRoadTiles(bool invalidate)
1823 assert(!invalidate || _generating_world);
1825 for (TileIndex t = 0; t < MapSize(); t++) {
1826 if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1827 TownID tid = INVALID_TOWN;
1828 if (!invalidate) {
1829 const Town *town = CalcClosestTownFromTile(t);
1830 if (town != nullptr) tid = town->index;
1832 SetTownIndex(t, tid);
1837 static int GetSlopePixelZ_Road(TileIndex tile, uint x, uint y)
1840 if (IsNormalRoad(tile)) {
1841 int z;
1842 Slope tileh = GetTilePixelSlope(tile, &z);
1843 if (tileh == SLOPE_FLAT) return z;
1845 Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
1846 z += ApplyPixelFoundationToSlope(f, &tileh);
1847 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
1848 } else {
1849 return GetTileMaxPixelZ(tile);
1853 static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
1855 if (IsNormalRoad(tile)) {
1856 return GetRoadFoundation(tileh, GetAllRoadBits(tile));
1857 } else {
1858 return FlatteningFoundation(tileh);
1862 static const Roadside _town_road_types[][2] = {
1863 { ROADSIDE_GRASS, ROADSIDE_GRASS },
1864 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1865 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1866 { ROADSIDE_TREES, ROADSIDE_TREES },
1867 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
1870 static const Roadside _town_road_types_2[][2] = {
1871 { ROADSIDE_GRASS, ROADSIDE_GRASS },
1872 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1873 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
1874 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
1875 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
1879 static void TileLoop_Road(TileIndex tile)
1881 switch (_settings_game.game_creation.landscape) {
1882 case LT_ARCTIC:
1883 if (IsOnSnow(tile) != (GetTileZ(tile) > GetSnowLine())) {
1884 ToggleSnow(tile);
1885 MarkTileDirtyByTile(tile);
1887 break;
1889 case LT_TROPIC:
1890 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsOnDesert(tile)) {
1891 ToggleDesert(tile);
1892 MarkTileDirtyByTile(tile);
1894 break;
1897 if (IsRoadDepot(tile)) return;
1899 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
1900 if (!HasRoadWorks(tile)) {
1901 HouseZonesBits grp = HZB_TOWN_EDGE;
1903 if (t != nullptr) {
1904 grp = GetTownRadiusGroup(t, tile);
1906 /* Show an animation to indicate road work */
1907 if (t->road_build_months != 0 &&
1908 (DistanceManhattan(t->xy, tile) < 8 || grp != HZB_TOWN_EDGE) &&
1909 IsNormalRoad(tile) && !HasAtMostOneBit(GetAllRoadBits(tile))) {
1910 if (GetFoundationSlope(tile) == SLOPE_FLAT && EnsureNoVehicleOnGround(tile).Succeeded() && Chance16(1, 40)) {
1911 StartRoadWorks(tile);
1913 if (_settings_client.sound.ambient) SndPlayTileFx(SND_21_ROAD_WORKS, tile);
1914 CreateEffectVehicleAbove(
1915 TileX(tile) * TILE_SIZE + 7,
1916 TileY(tile) * TILE_SIZE + 7,
1918 EV_BULLDOZER);
1919 MarkTileDirtyByTile(tile);
1920 return;
1926 /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
1927 const Roadside *new_rs = (_settings_game.game_creation.landscape == LT_TOYLAND) ? _town_road_types_2[grp] : _town_road_types[grp];
1928 Roadside cur_rs = GetRoadside(tile);
1930 /* We have our desired type, do nothing */
1931 if (cur_rs == new_rs[0]) return;
1933 /* We have the pre-type of the desired type, switch to the desired type */
1934 if (cur_rs == new_rs[1]) {
1935 cur_rs = new_rs[0];
1936 /* We have barren land, install the pre-type */
1937 } else if (cur_rs == ROADSIDE_BARREN) {
1938 cur_rs = new_rs[1];
1939 /* We're totally off limits, remove any installation and make barren land */
1940 } else {
1941 cur_rs = ROADSIDE_BARREN;
1943 SetRoadside(tile, cur_rs);
1944 MarkTileDirtyByTile(tile);
1946 } else if (IncreaseRoadWorksCounter(tile)) {
1947 TerminateRoadWorks(tile);
1949 if (_settings_game.economy.mod_road_rebuild) {
1950 /* Generate a nicer town surface */
1951 const RoadBits old_rb = GetAnyRoadBits(tile, RTT_ROAD);
1952 const RoadBits new_rb = CleanUpRoadBits(tile, old_rb);
1954 if (old_rb != new_rb) {
1955 RemoveRoad(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, (old_rb ^ new_rb), RTT_ROAD, true);
1957 /* If new_rb is 0, there are now no road pieces left and the tile is no longer a road tile */
1958 if (new_rb == 0) {
1959 MarkTileDirtyByTile(tile);
1960 return;
1965 /* Possibly change road type */
1966 if (GetRoadOwner(tile, RTT_ROAD) == OWNER_TOWN) {
1967 RoadType rt = GetTownRoadType(t);
1968 if (rt != GetRoadTypeRoad(tile)) {
1969 SetRoadType(tile, RTT_ROAD, rt);
1973 MarkTileDirtyByTile(tile);
1977 static bool ClickTile_Road(TileIndex tile)
1979 if (!IsRoadDepot(tile)) return false;
1981 ShowDepotWindow(tile, VEH_ROAD);
1982 return true;
1985 /* Converts RoadBits to TrackBits */
1986 static const TrackBits _road_trackbits[16] = {
1987 TRACK_BIT_NONE, // ROAD_NONE
1988 TRACK_BIT_NONE, // ROAD_NW
1989 TRACK_BIT_NONE, // ROAD_SW
1990 TRACK_BIT_LEFT, // ROAD_W
1991 TRACK_BIT_NONE, // ROAD_SE
1992 TRACK_BIT_Y, // ROAD_Y
1993 TRACK_BIT_LOWER, // ROAD_S
1994 TRACK_BIT_LEFT | TRACK_BIT_LOWER | TRACK_BIT_Y, // ROAD_Y | ROAD_SW
1995 TRACK_BIT_NONE, // ROAD_NE
1996 TRACK_BIT_UPPER, // ROAD_N
1997 TRACK_BIT_X, // ROAD_X
1998 TRACK_BIT_LEFT | TRACK_BIT_UPPER | TRACK_BIT_X, // ROAD_X | ROAD_NW
1999 TRACK_BIT_RIGHT, // ROAD_E
2000 TRACK_BIT_RIGHT | TRACK_BIT_UPPER | TRACK_BIT_Y, // ROAD_Y | ROAD_NE
2001 TRACK_BIT_RIGHT | TRACK_BIT_LOWER | TRACK_BIT_X, // ROAD_X | ROAD_SE
2002 TRACK_BIT_ALL, // ROAD_ALL
2005 static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
2007 TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
2008 TrackdirBits red_signals = TRACKDIR_BIT_NONE; // crossing barred
2009 switch (mode) {
2010 case TRANSPORT_RAIL:
2011 if (IsLevelCrossing(tile)) trackdirbits = TrackBitsToTrackdirBits(GetCrossingRailBits(tile));
2012 break;
2014 case TRANSPORT_ROAD: {
2015 RoadTramType rtt = (RoadTramType)sub_mode;
2016 if (!HasTileRoadType(tile, rtt)) break;
2017 switch (GetRoadTileType(tile)) {
2018 case ROAD_TILE_NORMAL: {
2019 const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
2020 RoadBits bits = GetRoadBits(tile, rtt);
2022 /* no roadbit at this side of tile, return 0 */
2023 if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break;
2025 uint multiplier = drd_to_multiplier[(rtt == RTT_TRAM) ? DRD_NONE : GetDisallowedRoadDirections(tile)];
2026 if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier);
2027 break;
2030 case ROAD_TILE_CROSSING: {
2031 Axis axis = GetCrossingRoadAxis(tile);
2033 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
2035 trackdirbits = TrackBitsToTrackdirBits(AxisToTrackBits(axis));
2036 if (IsCrossingBarred(tile)) red_signals = trackdirbits;
2037 break;
2040 default:
2041 case ROAD_TILE_DEPOT: {
2042 DiagDirection dir = GetRoadDepotDirection(tile);
2044 if (side != INVALID_DIAGDIR && side != dir) break;
2046 trackdirbits = TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir));
2047 break;
2050 break;
2053 default: break;
2055 return CombineTrackStatus(trackdirbits, red_signals);
2058 static const StringID _road_tile_strings[] = {
2059 STR_LAI_ROAD_DESCRIPTION_ROAD,
2060 STR_LAI_ROAD_DESCRIPTION_ROAD,
2061 STR_LAI_ROAD_DESCRIPTION_ROAD,
2062 STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_STREETLIGHTS,
2063 STR_LAI_ROAD_DESCRIPTION_ROAD,
2064 STR_LAI_ROAD_DESCRIPTION_TREE_LINED_ROAD,
2065 STR_LAI_ROAD_DESCRIPTION_ROAD,
2066 STR_LAI_ROAD_DESCRIPTION_ROAD,
2069 static void GetTileDesc_Road(TileIndex tile, TileDesc *td)
2071 Owner rail_owner = INVALID_OWNER;
2072 Owner road_owner = INVALID_OWNER;
2073 Owner tram_owner = INVALID_OWNER;
2075 RoadType road_rt = GetRoadTypeRoad(tile);
2076 RoadType tram_rt = GetRoadTypeTram(tile);
2077 if (road_rt != INVALID_ROADTYPE) {
2078 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
2079 td->roadtype = rti->strings.name;
2080 td->road_speed = rti->max_speed / 2;
2081 road_owner = GetRoadOwner(tile, RTT_ROAD);
2083 if (tram_rt != INVALID_ROADTYPE) {
2084 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
2085 td->tramtype = rti->strings.name;
2086 td->tram_speed = rti->max_speed / 2;
2087 tram_owner = GetRoadOwner(tile, RTT_TRAM);
2090 switch (GetRoadTileType(tile)) {
2091 case ROAD_TILE_CROSSING: {
2092 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_RAIL_LEVEL_CROSSING;
2093 rail_owner = GetTileOwner(tile);
2095 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2096 td->railtype = rti->strings.name;
2097 td->rail_speed = rti->max_speed;
2099 break;
2102 case ROAD_TILE_DEPOT:
2103 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_VEHICLE_DEPOT;
2104 td->build_date = Depot::GetByTile(tile)->build_date;
2105 break;
2107 default: {
2108 td->str = (road_rt != INVALID_ROADTYPE ? _road_tile_strings[GetRoadside(tile)] : STR_LAI_ROAD_DESCRIPTION_TRAMWAY);
2109 break;
2113 /* Now we have to discover, if the tile has only one owner or many:
2114 * - Find a first_owner of the tile. (Currently road or tram must be present, but this will break when the third type becomes available)
2115 * - Compare the found owner with the other owners, and test if they differ.
2116 * Note: If road exists it will be the first_owner.
2118 Owner first_owner = (road_owner == INVALID_OWNER ? tram_owner : road_owner);
2119 bool mixed_owners = (tram_owner != INVALID_OWNER && tram_owner != first_owner) || (rail_owner != INVALID_OWNER && rail_owner != first_owner);
2121 if (mixed_owners) {
2122 /* Multiple owners */
2123 td->owner_type[0] = (rail_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_RAIL_OWNER);
2124 td->owner[0] = rail_owner;
2125 td->owner_type[1] = (road_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_ROAD_OWNER);
2126 td->owner[1] = road_owner;
2127 td->owner_type[2] = (tram_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_TRAM_OWNER);
2128 td->owner[2] = tram_owner;
2129 } else {
2130 /* One to rule them all */
2131 td->owner[0] = first_owner;
2136 * Given the direction the road depot is pointing, this is the direction the
2137 * vehicle should be travelling in in order to enter the depot.
2139 static const byte _roadveh_enter_depot_dir[4] = {
2140 TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
2143 static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
2145 switch (GetRoadTileType(tile)) {
2146 case ROAD_TILE_DEPOT: {
2147 if (v->type != VEH_ROAD) break;
2149 RoadVehicle *rv = RoadVehicle::From(v);
2150 if (rv->frame == RVC_DEPOT_STOP_FRAME &&
2151 _roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
2152 rv->state = RVSB_IN_DEPOT;
2153 rv->vehstatus |= VS_HIDDEN;
2154 rv->direction = ReverseDir(rv->direction);
2155 if (rv->Next() == nullptr) VehicleEnterDepot(rv->First());
2156 rv->tile = tile;
2158 InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
2159 return VETSB_ENTERED_WORMHOLE;
2161 break;
2164 default: break;
2166 return VETSB_CONTINUE;
2170 static void ChangeTileOwner_Road(TileIndex tile, Owner old_owner, Owner new_owner)
2172 if (IsRoadDepot(tile)) {
2173 if (GetTileOwner(tile) == old_owner) {
2174 if (new_owner == INVALID_OWNER) {
2175 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_BANKRUPT, tile);
2176 } else {
2177 /* A road depot has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
2178 RoadType rt = GetRoadTypeRoad(tile);
2179 if (rt == INVALID_ROADTYPE) rt = GetRoadTypeTram(tile);
2180 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
2181 Company::Get(new_owner)->infrastructure.road[rt] += 2;
2183 SetTileOwner(tile, new_owner);
2184 for (RoadTramType rtt : _roadtramtypes) {
2185 if (GetRoadOwner(tile, rtt) == old_owner) {
2186 SetRoadOwner(tile, rtt, new_owner);
2191 return;
2194 for (RoadTramType rtt : _roadtramtypes) {
2195 /* Update all roadtypes, no matter if they are present */
2196 if (GetRoadOwner(tile, rtt) == old_owner) {
2197 RoadType rt = GetRoadType(tile, rtt);
2198 if (rt != INVALID_ROADTYPE) {
2199 /* A level crossing has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
2200 uint num_bits = IsLevelCrossing(tile) ? 2 : CountBits(GetRoadBits(tile, rtt));
2201 Company::Get(old_owner)->infrastructure.road[rt] -= num_bits;
2202 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += num_bits;
2205 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
2209 if (IsLevelCrossing(tile)) {
2210 if (GetTileOwner(tile) == old_owner) {
2211 if (new_owner == INVALID_OWNER) {
2212 Command<CMD_REMOVE_SINGLE_RAIL>::Do(DC_EXEC | DC_BANKRUPT, tile, GetCrossingRailTrack(tile));
2213 } else {
2214 /* Update infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2215 Company::Get(old_owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
2216 Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
2218 SetTileOwner(tile, new_owner);
2224 static CommandCost TerraformTile_Road(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2226 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
2227 switch (GetRoadTileType(tile)) {
2228 case ROAD_TILE_CROSSING:
2229 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]);
2230 break;
2232 case ROAD_TILE_DEPOT:
2233 if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRoadDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2234 break;
2236 case ROAD_TILE_NORMAL: {
2237 RoadBits bits = GetAllRoadBits(tile);
2238 RoadBits bits_copy = bits;
2239 /* Check if the slope-road_bits combination is valid at all, i.e. it is safe to call GetRoadFoundation(). */
2240 if (CheckRoadSlope(tileh_new, &bits_copy, ROAD_NONE, ROAD_NONE).Succeeded()) {
2241 /* CheckRoadSlope() sometimes changes the road_bits, if it does not agree with them. */
2242 if (bits == bits_copy) {
2243 int z_old;
2244 Slope tileh_old = GetTileSlope(tile, &z_old);
2246 /* Get the slope on top of the foundation */
2247 z_old += ApplyFoundationToSlope(GetRoadFoundation(tileh_old, bits), &tileh_old);
2248 z_new += ApplyFoundationToSlope(GetRoadFoundation(tileh_new, bits), &tileh_new);
2250 /* The surface slope must not be changed */
2251 if ((z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2254 break;
2257 default: NOT_REACHED();
2261 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2264 /** Update power of road vehicle under which is the roadtype being converted */
2265 static Vehicle *UpdateRoadVehPowerProc(Vehicle *v, void *data)
2267 if (v->type != VEH_ROAD) return nullptr;
2269 RoadVehicleList *affected_rvs = static_cast<RoadVehicleList*>(data);
2270 include(*affected_rvs, RoadVehicle::From(v)->First());
2272 return nullptr;
2276 * Checks the tile and returns whether the current player is allowed to convert the roadtype to another roadtype without taking ownership
2277 * @param owner the tile owner.
2278 * @param rtt Road/tram type.
2279 * @return whether the road is convertible
2281 static bool CanConvertUnownedRoadType(Owner owner, RoadTramType rtt)
2283 return (owner == OWNER_NONE || (owner == OWNER_TOWN && rtt == RTT_ROAD));
2287 * Convert the ownership of the RoadType of the tile if applicable
2288 * @param tile the tile of which convert ownership
2289 * @param num_pieces the count of the roadbits to assign to the new owner
2290 * @param owner the current owner of the RoadType
2291 * @param from_type the old road type
2292 * @param to_type the new road type
2294 static void ConvertRoadTypeOwner(TileIndex tile, uint num_pieces, Owner owner, RoadType from_type, RoadType to_type)
2296 // Scenario editor, maybe? Don't touch the owners when converting roadtypes...
2297 if (_current_company >= MAX_COMPANIES) return;
2299 // We can't get a company from invalid owners but we can get ownership of roads without an owner
2300 if (owner >= MAX_COMPANIES && owner != OWNER_NONE) return;
2302 Company *c;
2304 switch (owner) {
2305 case OWNER_NONE:
2306 SetRoadOwner(tile, GetRoadTramType(to_type), (Owner)_current_company);
2307 UpdateCompanyRoadInfrastructure(to_type, _current_company, num_pieces);
2308 break;
2310 default:
2311 c = Company::Get(owner);
2312 c->infrastructure.road[from_type] -= num_pieces;
2313 c->infrastructure.road[to_type] += num_pieces;
2314 DirtyCompanyInfrastructureWindows(c->index);
2315 break;
2320 * Convert one road subtype to another.
2321 * Not meant to convert from road to tram.
2323 * @param flags operation to perform
2324 * @param tile end tile of road conversion drag
2325 * @param area_start start tile of drag
2326 * @param to_type new roadtype to convert to.
2327 * @return the cost of this operation or an error
2329 CommandCost CmdConvertRoad(DoCommandFlag flags, TileIndex tile, TileIndex area_start, RoadType to_type)
2331 TileIndex area_end = tile;
2333 if (!ValParamRoadType(to_type)) return CMD_ERROR;
2334 if (area_start >= MapSize()) return CMD_ERROR;
2336 RoadVehicleList affected_rvs;
2337 RoadTramType rtt = GetRoadTramType(to_type);
2339 CommandCost cost(EXPENSES_CONSTRUCTION);
2340 CommandCost error = CommandCost((rtt == RTT_TRAM) ? STR_ERROR_NO_SUITABLE_TRAMWAY : STR_ERROR_NO_SUITABLE_ROAD); // by default, there is no road to convert.
2341 bool found_convertible_road = false; // whether we actually did convert any road/tram (see bug #7633)
2343 TileIterator *iter = new OrthogonalTileIterator(area_start, area_end);
2344 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
2345 /* Is road present on tile? */
2346 if (!MayHaveRoad(tile)) continue;
2348 /* Converting to the same subtype? */
2349 RoadType from_type = GetRoadType(tile, rtt);
2350 if (from_type == INVALID_ROADTYPE || from_type == to_type) continue;
2352 /* Check if there is any infrastructure on tile */
2353 TileType tt = GetTileType(tile);
2354 switch (tt) {
2355 case MP_STATION:
2356 if (!IsRoadStop(tile)) continue;
2357 break;
2358 case MP_ROAD:
2359 if (IsLevelCrossing(tile) && RoadNoLevelCrossing(to_type)) {
2360 error.MakeError(STR_ERROR_CROSSING_DISALLOWED_ROAD);
2361 continue;
2363 break;
2364 case MP_TUNNELBRIDGE:
2365 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) continue;
2366 break;
2367 default: continue;
2370 /* Trying to convert other's road */
2371 Owner owner = GetRoadOwner(tile, rtt);
2372 if (!CanConvertUnownedRoadType(owner, rtt)) {
2373 CommandCost ret = CheckOwnership(owner, tile);
2374 if (ret.Failed()) {
2375 error = ret;
2376 continue;
2380 /* Base the ability to replace town roads and bridges on the town's
2381 * acceptance of destructive actions. */
2382 if (owner == OWNER_TOWN) {
2383 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
2384 CommandCost ret = CheckforTownRating(DC_NONE, t, tt == MP_TUNNELBRIDGE ? TUNNELBRIDGE_REMOVE : ROAD_REMOVE);
2385 if (ret.Failed()) {
2386 error = ret;
2387 continue;
2391 /* Vehicle on the tile when not converting normal <-> powered
2392 * Tunnels and bridges have special check later */
2393 if (tt != MP_TUNNELBRIDGE) {
2394 if (!HasPowerOnRoad(from_type, to_type)) {
2395 CommandCost ret = EnsureNoVehicleOnGround(tile);
2396 if (ret.Failed()) {
2397 error = ret;
2398 continue;
2401 if (rtt == RTT_ROAD && owner == OWNER_TOWN) {
2402 error.MakeError(STR_ERROR_OWNED_BY);
2403 GetNameOfOwner(OWNER_TOWN, tile);
2404 continue;
2408 uint num_pieces = CountBits(GetAnyRoadBits(tile, rtt));
2409 if (tt == MP_STATION && IsStandardRoadStopTile(tile)) {
2410 num_pieces *= ROAD_STOP_TRACKBIT_FACTOR;
2411 } else if (tt == MP_ROAD && IsRoadDepot(tile)) {
2412 num_pieces *= ROAD_DEPOT_TRACKBIT_FACTOR;
2415 found_convertible_road = true;
2416 cost.AddCost(num_pieces * RoadConvertCost(from_type, to_type));
2418 if (flags & DC_EXEC) { // we can safely convert, too
2419 /* Call ConvertRoadTypeOwner() to update the company infrastructure counters. */
2420 if (owner == _current_company) {
2421 ConvertRoadTypeOwner(tile, num_pieces, owner, from_type, to_type);
2424 /* Perform the conversion */
2425 SetRoadType(tile, rtt, to_type);
2426 MarkTileDirtyByTile(tile);
2428 /* update power of train on this tile */
2429 FindVehicleOnPos(tile, &affected_rvs, &UpdateRoadVehPowerProc);
2431 if (IsRoadDepotTile(tile)) {
2432 /* Update build vehicle window related to this depot */
2433 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
2434 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
2437 } else {
2438 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
2440 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
2441 * it would cause assert because of different test and exec runs */
2442 if (endtile < tile) {
2443 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
2446 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
2447 if (!HasPowerOnRoad(from_type, to_type)) {
2448 CommandCost ret = TunnelBridgeIsFree(tile, endtile);
2449 if (ret.Failed()) {
2450 error = ret;
2451 continue;
2454 if (rtt == RTT_ROAD && owner == OWNER_TOWN) {
2455 error.MakeError(STR_ERROR_OWNED_BY);
2456 GetNameOfOwner(OWNER_TOWN, tile);
2457 continue;
2461 /* There are 2 pieces on *every* tile of the bridge or tunnel */
2462 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * 2;
2463 found_convertible_road = true;
2464 cost.AddCost(num_pieces * RoadConvertCost(from_type, to_type));
2466 if (flags & DC_EXEC) {
2467 /* Update the company infrastructure counters. */
2468 if (owner == _current_company) {
2469 /* Each piece should be counted TUNNELBRIDGE_TRACKBIT_FACTOR times
2470 * for the infrastructure counters (cause of #8297). */
2471 ConvertRoadTypeOwner(tile, num_pieces * TUNNELBRIDGE_TRACKBIT_FACTOR, owner, from_type, to_type);
2472 SetTunnelBridgeOwner(tile, endtile, _current_company);
2475 /* Perform the conversion */
2476 SetRoadType(tile, rtt, to_type);
2477 SetRoadType(endtile, rtt, to_type);
2479 FindVehicleOnPos(tile, &affected_rvs, &UpdateRoadVehPowerProc);
2480 FindVehicleOnPos(endtile, &affected_rvs, &UpdateRoadVehPowerProc);
2482 if (IsBridge(tile)) {
2483 MarkBridgeDirty(tile);
2484 } else {
2485 MarkTileDirtyByTile(tile);
2486 MarkTileDirtyByTile(endtile);
2492 if (flags & DC_EXEC) {
2493 /* Roadtype changed, update roadvehicles as when entering different track */
2494 for (RoadVehicle *v : affected_rvs) {
2495 v->CargoChanged();
2499 delete iter;
2500 return found_convertible_road ? cost : error;
2504 /** Tile callback functions for road tiles */
2505 extern const TileTypeProcs _tile_type_road_procs = {
2506 DrawTile_Road, // draw_tile_proc
2507 GetSlopePixelZ_Road, // get_slope_z_proc
2508 ClearTile_Road, // clear_tile_proc
2509 nullptr, // add_accepted_cargo_proc
2510 GetTileDesc_Road, // get_tile_desc_proc
2511 GetTileTrackStatus_Road, // get_tile_track_status_proc
2512 ClickTile_Road, // click_tile_proc
2513 nullptr, // animate_tile_proc
2514 TileLoop_Road, // tile_loop_proc
2515 ChangeTileOwner_Road, // change_tile_owner_proc
2516 nullptr, // add_produced_cargo_proc
2517 VehicleEnter_Road, // vehicle_enter_tile_proc
2518 GetFoundation_Road, // get_foundation_proc
2519 TerraformTile_Road, // terraform_tile_proc