(svn r28004) -Update from Eints:
[openttd.git] / src / road_cmd.cpp
blob5e432a2e6bc5024c1c30d74badd74c3629d08c94
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_railtype.h"
35 #include "date_func.h"
36 #include "genworld.h"
37 #include "company_gui.h"
39 #include "table/strings.h"
41 #include "safeguards.h"
43 /**
44 * Verify whether a road vehicle is available.
45 * @return \c true if at least one road vehicle is available, \c false if not
47 bool RoadVehiclesAreBuilt()
49 const RoadVehicle *rv;
50 FOR_ALL_ROADVEHICLES(rv) return true;
52 return false;
55 /** Invalid RoadBits on slopes. */
56 static const RoadBits _invalid_tileh_slopes_road[2][15] = {
57 /* The inverse of the mixable RoadBits on a leveled slope */
59 ROAD_NONE, // SLOPE_FLAT
60 ROAD_NE | ROAD_SE, // SLOPE_W
61 ROAD_NE | ROAD_NW, // SLOPE_S
63 ROAD_NE, // SLOPE_SW
64 ROAD_NW | ROAD_SW, // SLOPE_E
65 ROAD_NONE, // SLOPE_EW
67 ROAD_NW, // SLOPE_SE
68 ROAD_NONE, // SLOPE_WSE
69 ROAD_SE | ROAD_SW, // SLOPE_N
71 ROAD_SE, // SLOPE_NW
72 ROAD_NONE, // SLOPE_NS
73 ROAD_NONE, // SLOPE_ENW
75 ROAD_SW, // SLOPE_NE
76 ROAD_NONE, // SLOPE_SEN
77 ROAD_NONE // SLOPE_NWS
79 /* The inverse of the allowed straight roads on a slope
80 * (with and without a foundation). */
82 ROAD_NONE, // SLOPE_FLAT
83 ROAD_NONE, // SLOPE_W Foundation
84 ROAD_NONE, // SLOPE_S Foundation
86 ROAD_Y, // SLOPE_SW
87 ROAD_NONE, // SLOPE_E Foundation
88 ROAD_ALL, // SLOPE_EW
90 ROAD_X, // SLOPE_SE
91 ROAD_ALL, // SLOPE_WSE
92 ROAD_NONE, // SLOPE_N Foundation
94 ROAD_X, // SLOPE_NW
95 ROAD_ALL, // SLOPE_NS
96 ROAD_ALL, // SLOPE_ENW
98 ROAD_Y, // SLOPE_NE
99 ROAD_ALL, // SLOPE_SEN
100 ROAD_ALL // SLOPE_NW
104 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits);
107 * Is it allowed to remove the given road bits from the given tile?
108 * @param tile the tile to remove the road from
109 * @param remove the roadbits that are going to be removed
110 * @param owner the actual owner of the roadbits of the tile
111 * @param rt the road type to remove the bits from
112 * @param flags command flags
113 * @param town_check Shall the town rating checked/affected
114 * @return A succeeded command when it is allowed to remove the road bits, a failed command otherwise.
116 CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadType rt, DoCommandFlag flags, bool town_check)
118 if (_game_mode == GM_EDITOR || remove == ROAD_NONE) return CommandCost();
120 /* Water can always flood and towns can always remove "normal" road pieces.
121 * Towns are not be allowed to remove non "normal" road pieces, like tram
122 * tracks as that would result in trams that cannot turn. */
123 if (_current_company == OWNER_WATER ||
124 (rt == ROADTYPE_ROAD && !Company::IsValidID(_current_company))) return CommandCost();
126 /* Only do the special processing if the road is owned
127 * by a town */
128 if (owner != OWNER_TOWN) {
129 if (owner == OWNER_NONE) return CommandCost();
130 CommandCost ret = CheckOwnership(owner);
131 return ret;
134 if (!town_check) return CommandCost();
136 if (_cheats.magic_bulldozer.value) return CommandCost();
138 Town *t = ClosestTownFromTile(tile, UINT_MAX);
139 if (t == NULL) return CommandCost();
141 /* check if you're allowed to remove the street owned by a town
142 * removal allowance depends on difficulty setting */
143 CommandCost ret = CheckforTownRating(flags, t, ROAD_REMOVE);
144 if (ret.Failed()) return ret;
146 /* Get a bitmask of which neighbouring roads has a tile */
147 RoadBits n = ROAD_NONE;
148 RoadBits present = GetAnyRoadBits(tile, rt);
149 if ((present & ROAD_NE) && (GetAnyRoadBits(TILE_ADDXY(tile, -1, 0), rt) & ROAD_SW)) n |= ROAD_NE;
150 if ((present & ROAD_SE) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, 1), rt) & ROAD_NW)) n |= ROAD_SE;
151 if ((present & ROAD_SW) && (GetAnyRoadBits(TILE_ADDXY(tile, 1, 0), rt) & ROAD_NE)) n |= ROAD_SW;
152 if ((present & ROAD_NW) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, -1), rt) & ROAD_SE)) n |= ROAD_NW;
154 int rating_decrease = RATING_ROAD_DOWN_STEP_EDGE;
155 /* If 0 or 1 bits are set in n, or if no bits that match the bits to remove,
156 * then allow it */
157 if (KillFirstBit(n) != ROAD_NONE && (n & remove) != ROAD_NONE) {
158 /* you can remove all kind of roads with extra dynamite */
159 if (!_settings_game.construction.extra_dynamite) {
160 SetDParam(0, t->index);
161 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
163 rating_decrease = RATING_ROAD_DOWN_STEP_INNER;
165 ChangeTownRating(t, rating_decrease, RATING_ROAD_MINIMUM, flags);
167 return CommandCost();
172 * Delete a piece of road.
173 * @param tile tile where to remove road from
174 * @param flags operation to perform
175 * @param pieces roadbits to remove
176 * @param rt roadtype to remove
177 * @param crossing_check should we check if there is a tram track when we are removing road from crossing?
178 * @param town_check should we check if the town allows removal?
180 static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits pieces, RoadType rt, bool crossing_check, bool town_check = true)
182 RoadTypes rts = GetRoadTypes(tile);
183 /* The tile doesn't have the given road type */
184 if (!HasBit(rts, rt)) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
186 switch (GetTileType(tile)) {
187 case MP_ROAD: {
188 CommandCost ret = EnsureNoVehicleOnGround(tile);
189 if (ret.Failed()) return ret;
190 break;
193 case MP_STATION: {
194 if (!IsDriveThroughStopTile(tile)) return CMD_ERROR;
196 CommandCost ret = EnsureNoVehicleOnGround(tile);
197 if (ret.Failed()) return ret;
198 break;
201 case MP_TUNNELBRIDGE: {
202 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return CMD_ERROR;
203 CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
204 if (ret.Failed()) return ret;
205 break;
208 default:
209 return CMD_ERROR;
212 CommandCost ret = CheckAllowRemoveRoad(tile, pieces, GetRoadOwner(tile, rt), rt, flags, town_check);
213 if (ret.Failed()) return ret;
215 if (!IsTileType(tile, MP_ROAD)) {
216 /* If it's the last roadtype, just clear the whole tile */
217 if (rts == RoadTypeToRoadTypes(rt)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
219 CommandCost cost(EXPENSES_CONSTRUCTION);
220 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
221 /* Removing any roadbit in the bridge axis removes the roadtype (that's the behaviour remove-long-roads needs) */
222 if ((AxisToRoadBits(DiagDirToAxis(GetTunnelBridgeDirection(tile))) & pieces) == ROAD_NONE) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
224 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
225 /* Pay for *every* tile of the bridge or tunnel */
226 uint len = GetTunnelBridgeLength(other_end, tile) + 2;
227 cost.AddCost(len * 2 * _price[PR_CLEAR_ROAD]);
228 if (flags & DC_EXEC) {
229 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
230 if (c != NULL) {
231 /* A full diagonal road tile has two road bits. */
232 c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
233 DirtyCompanyInfrastructureWindows(c->index);
236 SetRoadTypes(other_end, GetRoadTypes(other_end) & ~RoadTypeToRoadTypes(rt));
237 SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
239 /* If the owner of the bridge sells all its road, also move the ownership
240 * to the owner of the other roadtype, unless the bridge owner is a town. */
241 RoadType other_rt = (rt == ROADTYPE_ROAD) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
242 Owner other_owner = GetRoadOwner(tile, other_rt);
243 if (!IsTileOwner(tile, other_owner) && !IsTileOwner(tile, OWNER_TOWN)) {
244 SetTileOwner(tile, other_owner);
245 SetTileOwner(other_end, other_owner);
248 /* Mark tiles dirty that have been repaved */
249 if (IsBridge(tile)) {
250 MarkBridgeDirty(tile);
251 } else {
252 MarkTileDirtyByTile(tile);
253 MarkTileDirtyByTile(other_end);
256 } else {
257 assert(IsDriveThroughStopTile(tile));
258 cost.AddCost(_price[PR_CLEAR_ROAD] * 2);
259 if (flags & DC_EXEC) {
260 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
261 if (c != NULL) {
262 /* A full diagonal road tile has two road bits. */
263 c->infrastructure.road[rt] -= 2;
264 DirtyCompanyInfrastructureWindows(c->index);
266 SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
267 MarkTileDirtyByTile(tile);
270 return cost;
273 switch (GetRoadTileType(tile)) {
274 case ROAD_TILE_NORMAL: {
275 Slope tileh = GetTileSlope(tile);
277 /* Steep slopes behave the same as slopes with one corner raised. */
278 if (IsSteepSlope(tileh)) {
279 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
282 RoadBits present = GetRoadBits(tile, rt);
283 const RoadBits other = GetOtherRoadBits(tile, rt);
284 const Foundation f = GetRoadFoundation(tileh, present);
286 if (HasRoadWorks(tile) && _current_company != OWNER_WATER) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
288 /* Autocomplete to a straight road
289 * @li if the bits of the other roadtypes result in another foundation
290 * @li if build on slopes is disabled */
291 if ((IsStraightRoad(other) && (other & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) != ROAD_NONE) ||
292 (tileh != SLOPE_FLAT && !_settings_game.construction.build_on_slopes)) {
293 pieces |= MirrorRoadBits(pieces);
296 /* limit the bits to delete to the existing bits. */
297 pieces &= present;
298 if (pieces == ROAD_NONE) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
300 /* Now set present what it will be after the remove */
301 present ^= pieces;
303 /* Check for invalid RoadBit combinations on slopes */
304 if (tileh != SLOPE_FLAT && present != ROAD_NONE &&
305 (present & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) == present) {
306 return CMD_ERROR;
309 if (flags & DC_EXEC) {
310 if (HasRoadWorks(tile)) {
311 /* flooding tile with road works, don't forget to remove the effect vehicle too */
312 assert(_current_company == OWNER_WATER);
313 EffectVehicle *v;
314 FOR_ALL_EFFECTVEHICLES(v) {
315 if (TileVirtXY(v->x_pos, v->y_pos) == tile) {
316 delete v;
321 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
322 if (c != NULL) {
323 c->infrastructure.road[rt] -= CountBits(pieces);
324 DirtyCompanyInfrastructureWindows(c->index);
327 if (present == ROAD_NONE) {
328 RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
329 if (rts == ROADTYPES_NONE) {
330 /* Includes MarkTileDirtyByTile() */
331 DoClearSquare(tile);
332 } else {
333 if (rt == ROADTYPE_ROAD && IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN)) {
334 /* Update nearest-town index */
335 const Town *town = CalcClosestTownFromTile(tile);
336 SetTownIndex(tile, town == NULL ? (TownID)INVALID_TOWN : town->index);
338 SetRoadBits(tile, ROAD_NONE, rt);
339 SetRoadTypes(tile, rts);
340 MarkTileDirtyByTile(tile);
342 } else {
343 /* When bits are removed, you *always* end up with something that
344 * is not a complete straight road tile. However, trams do not have
345 * onewayness, so they cannot remove it either. */
346 if (rt != ROADTYPE_TRAM) SetDisallowedRoadDirections(tile, DRD_NONE);
347 SetRoadBits(tile, present, rt);
348 MarkTileDirtyByTile(tile);
352 CommandCost cost(EXPENSES_CONSTRUCTION, CountBits(pieces) * _price[PR_CLEAR_ROAD]);
353 /* If we build a foundation we have to pay for it. */
354 if (f == FOUNDATION_NONE && GetRoadFoundation(tileh, present) != FOUNDATION_NONE) cost.AddCost(_price[PR_BUILD_FOUNDATION]);
356 return cost;
359 case ROAD_TILE_CROSSING: {
360 if (pieces & ComplementRoadBits(GetCrossingRoadBits(tile))) {
361 return CMD_ERROR;
364 /* Don't allow road to be removed from the crossing when there is tram;
365 * we can't draw the crossing without roadbits ;) */
366 if (rt == ROADTYPE_ROAD && HasTileRoadType(tile, ROADTYPE_TRAM) && (flags & DC_EXEC || crossing_check)) return CMD_ERROR;
368 if (flags & DC_EXEC) {
369 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
370 if (c != NULL) {
371 /* A full diagonal road tile has two road bits. */
372 c->infrastructure.road[rt] -= 2;
373 DirtyCompanyInfrastructureWindows(c->index);
376 Track railtrack = GetCrossingRailTrack(tile);
377 RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
378 if (rts == ROADTYPES_NONE) {
379 TrackBits tracks = GetCrossingRailBits(tile);
380 bool reserved = HasCrossingReservation(tile);
381 MakeRailNormal(tile, GetTileOwner(tile), tracks, GetRailType(tile));
382 if (reserved) SetTrackReservation(tile, tracks);
384 /* Update rail count for level crossings. The plain track should still be accounted
385 * for, so only subtract the difference to the level crossing cost. */
386 c = Company::GetIfValid(GetTileOwner(tile));
387 if (c != NULL) {
388 c->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
389 DirtyCompanyInfrastructureWindows(c->index);
391 } else {
392 SetRoadTypes(tile, rts);
394 MarkTileDirtyByTile(tile);
395 YapfNotifyTrackLayoutChange(tile, railtrack);
397 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_ROAD] * 2);
400 default:
401 case ROAD_TILE_DEPOT:
402 return CMD_ERROR;
408 * Calculate the costs for roads on slopes
409 * Aside modify the RoadBits to fit on the slopes
411 * @note The RoadBits are modified too!
412 * @param tileh The current slope
413 * @param pieces The RoadBits we want to add
414 * @param existing The existent RoadBits of the current type
415 * @param other The other existent RoadBits
416 * @return The costs for these RoadBits on this slope
418 static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existing, RoadBits other)
420 /* Remove already build pieces */
421 CLRBITS(*pieces, existing);
423 /* If we can't build anything stop here */
424 if (*pieces == ROAD_NONE) return CMD_ERROR;
426 /* All RoadBit combos are valid on flat land */
427 if (tileh == SLOPE_FLAT) return CommandCost();
429 /* Steep slopes behave the same as slopes with one corner raised. */
430 if (IsSteepSlope(tileh)) {
431 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
434 /* Save the merge of all bits of the current type */
435 RoadBits type_bits = existing | *pieces;
437 /* Roads on slopes */
438 if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
440 /* If we add leveling we've got to pay for it */
441 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
443 return CommandCost();
446 /* Autocomplete uphill roads */
447 *pieces |= MirrorRoadBits(*pieces);
448 type_bits = existing | *pieces;
450 /* Uphill roads */
451 if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
452 (_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
454 /* Slopes with foundation ? */
455 if (IsSlopeWithOneCornerRaised(tileh)) {
457 /* Prevent build on slopes if it isn't allowed */
458 if (_settings_game.construction.build_on_slopes) {
460 /* If we add foundation we've got to pay for it */
461 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
463 return CommandCost();
465 } else {
466 if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
467 return CommandCost();
470 return CMD_ERROR;
474 * Build a piece of road.
475 * @param tile tile where to build road
476 * @param flags operation to perform
477 * @param p1 bit 0..3 road pieces to build (RoadBits)
478 * bit 4..5 road type
479 * bit 6..7 disallowed directions to toggle
480 * @param p2 the town that is building the road (0 if not applicable)
481 * @param text unused
482 * @return the cost of this operation or an error
484 CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
486 CompanyID company = _current_company;
487 CommandCost cost(EXPENSES_CONSTRUCTION);
489 RoadBits existing = ROAD_NONE;
490 RoadBits other_bits = ROAD_NONE;
492 /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
493 * if a non-company is building the road */
494 if ((Company::IsValidID(company) && p2 != 0) || (company == OWNER_TOWN && !Town::IsValidID(p2)) || (company == OWNER_DEITY && p2 != 0)) return CMD_ERROR;
495 if (company != OWNER_TOWN) {
496 const Town *town = CalcClosestTownFromTile(tile);
497 p2 = (town != NULL) ? town->index : (TownID)INVALID_TOWN;
499 if (company == OWNER_DEITY) {
500 company = OWNER_TOWN;
502 /* If we are not within a town, we are not owned by the town */
503 if (town == NULL || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
504 company = OWNER_NONE;
509 RoadBits pieces = Extract<RoadBits, 0, 4>(p1);
511 /* do not allow building 'zero' road bits, code wouldn't handle it */
512 if (pieces == ROAD_NONE) return CMD_ERROR;
514 RoadType rt = Extract<RoadType, 4, 2>(p1);
515 if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
517 DisallowedRoadDirections toggle_drd = Extract<DisallowedRoadDirections, 6, 2>(p1);
519 Slope tileh = GetTileSlope(tile);
521 bool need_to_clear = false;
522 switch (GetTileType(tile)) {
523 case MP_ROAD:
524 switch (GetRoadTileType(tile)) {
525 case ROAD_TILE_NORMAL: {
526 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
528 other_bits = GetOtherRoadBits(tile, rt);
529 if (!HasTileRoadType(tile, rt)) break;
531 existing = GetRoadBits(tile, rt);
532 bool crossing = !IsStraightRoad(existing | pieces);
533 if (rt != ROADTYPE_TRAM && (GetDisallowedRoadDirections(tile) != DRD_NONE || toggle_drd != DRD_NONE) && crossing) {
534 /* Junctions cannot be one-way */
535 return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
537 if ((existing & pieces) == pieces) {
538 /* We only want to set the (dis)allowed road directions */
539 if (toggle_drd != DRD_NONE && rt != ROADTYPE_TRAM) {
540 if (crossing) return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
542 Owner owner = GetRoadOwner(tile, ROADTYPE_ROAD);
543 if (owner != OWNER_NONE) {
544 CommandCost ret = CheckOwnership(owner, tile);
545 if (ret.Failed()) return ret;
548 DisallowedRoadDirections dis_existing = GetDisallowedRoadDirections(tile);
549 DisallowedRoadDirections dis_new = dis_existing ^ toggle_drd;
551 /* We allow removing disallowed directions to break up
552 * deadlocks, but adding them can break articulated
553 * vehicles. As such, only when less is disallowed,
554 * i.e. bits are removed, we skip the vehicle check. */
555 if (CountBits(dis_existing) <= CountBits(dis_new)) {
556 CommandCost ret = EnsureNoVehicleOnGround(tile);
557 if (ret.Failed()) return ret;
560 /* Ignore half built tiles */
561 if ((flags & DC_EXEC) && rt != ROADTYPE_TRAM && IsStraightRoad(existing)) {
562 SetDisallowedRoadDirections(tile, dis_new);
563 MarkTileDirtyByTile(tile);
565 return CommandCost();
567 return_cmd_error(STR_ERROR_ALREADY_BUILT);
569 /* Disallow breaking end-of-line of someone else
570 * so trams can still reverse on this tile. */
571 if (rt == ROADTYPE_TRAM && HasExactlyOneBit(existing)) {
572 Owner owner = GetRoadOwner(tile, rt);
573 if (Company::IsValidID(owner)) {
574 CommandCost ret = CheckOwnership(owner);
575 if (ret.Failed()) return ret;
578 break;
581 case ROAD_TILE_CROSSING:
582 other_bits = GetCrossingRoadBits(tile);
583 if (pieces & ComplementRoadBits(other_bits)) goto do_clear;
584 pieces = other_bits; // we need to pay for both roadbits
586 if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
587 break;
589 case ROAD_TILE_DEPOT:
590 if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
591 goto do_clear;
593 default: NOT_REACHED();
595 break;
597 case MP_RAILWAY: {
598 if (IsSteepSlope(tileh)) {
599 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
602 /* Level crossings may only be built on these slopes */
603 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) {
604 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
607 if (GetRailTileType(tile) != RAIL_TILE_NORMAL) goto do_clear;
609 if (RailNoLevelCrossings(GetRailType(tile))) {
610 return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
613 Axis roaddir;
614 switch (GetTrackBits(tile)) {
615 case TRACK_BIT_X:
616 if (pieces & ROAD_X) goto do_clear;
617 roaddir = AXIS_Y;
618 break;
620 case TRACK_BIT_Y:
621 if (pieces & ROAD_Y) goto do_clear;
622 roaddir = AXIS_X;
623 break;
625 default: goto do_clear;
628 CommandCost ret = EnsureNoVehicleOnGround(tile);
629 if (ret.Failed()) return ret;
631 if (flags & DC_EXEC) {
632 Track railtrack = AxisToTrack(OtherAxis(roaddir));
633 YapfNotifyTrackLayoutChange(tile, railtrack);
634 /* Update company infrastructure counts. A level crossing has two road bits. */
635 Company *c = Company::GetIfValid(company);
636 if (c != NULL) {
637 c->infrastructure.road[rt] += 2;
638 if (rt != ROADTYPE_ROAD) c->infrastructure.road[ROADTYPE_ROAD] += 2;
639 DirtyCompanyInfrastructureWindows(company);
641 /* Update rail count for level crossings. The plain track is already
642 * counted, so only add the difference to the level crossing cost. */
643 c = Company::GetIfValid(GetTileOwner(tile));
644 if (c != NULL) {
645 c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
646 DirtyCompanyInfrastructureWindows(c->index);
649 /* Always add road to the roadtypes (can't draw without it) */
650 bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
651 MakeRoadCrossing(tile, company, company, GetTileOwner(tile), roaddir, GetRailType(tile), RoadTypeToRoadTypes(rt) | ROADTYPES_ROAD, p2);
652 SetCrossingReservation(tile, reserved);
653 UpdateLevelCrossing(tile, false);
654 MarkTileDirtyByTile(tile);
656 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_ROAD] * (rt == ROADTYPE_ROAD ? 2 : 4));
659 case MP_STATION: {
660 if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
661 if (!IsDriveThroughStopTile(tile)) goto do_clear;
663 RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
664 if (pieces & ~curbits) goto do_clear;
665 pieces = curbits; // we need to pay for both roadbits
667 if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
668 break;
671 case MP_TUNNELBRIDGE: {
672 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
673 /* Only allow building the outern roadbit, so building long roads stops at existing bridges */
674 if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != pieces) goto do_clear;
675 if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
676 /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
677 CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
678 if (ret.Failed()) return ret;
679 break;
682 default: {
683 do_clear:;
684 need_to_clear = true;
685 break;
689 if (need_to_clear) {
690 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
691 if (ret.Failed()) return ret;
692 cost.AddCost(ret);
695 if (other_bits != pieces) {
696 /* Check the foundation/slopes when adding road/tram bits */
697 CommandCost ret = CheckRoadSlope(tileh, &pieces, existing, other_bits);
698 /* Return an error if we need to build a foundation (ret != 0) but the
699 * current setting is turned off */
700 if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
701 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
703 cost.AddCost(ret);
706 if (!need_to_clear) {
707 if (IsTileType(tile, MP_ROAD)) {
708 /* Don't put the pieces that already exist */
709 pieces &= ComplementRoadBits(existing);
711 /* Check if new road bits will have the same foundation as other existing road types */
712 if (IsNormalRoad(tile)) {
713 Slope slope = GetTileSlope(tile);
714 Foundation found_new = GetRoadFoundation(slope, pieces | existing);
716 /* Test if all other roadtypes can be built at that foundation */
717 for (RoadType rtest = ROADTYPE_ROAD; rtest < ROADTYPE_END; rtest++) {
718 if (rtest != rt) { // check only other road types
719 RoadBits bits = GetRoadBits(tile, rtest);
720 /* do not check if there are not road bits of given type */
721 if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
722 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
729 CommandCost ret = EnsureNoVehicleOnGround(tile);
730 if (ret.Failed()) return ret;
734 uint num_pieces = (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) ?
735 /* There are 2 pieces on *every* tile of the bridge or tunnel */
736 2 * (GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2) :
737 /* Count pieces */
738 CountBits(pieces);
740 cost.AddCost(num_pieces * _price[PR_BUILD_ROAD]);
742 if (flags & DC_EXEC) {
743 switch (GetTileType(tile)) {
744 case MP_ROAD: {
745 RoadTileType rtt = GetRoadTileType(tile);
746 if (existing == ROAD_NONE || rtt == ROAD_TILE_CROSSING) {
747 SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
748 SetRoadOwner(tile, rt, company);
749 if (rt == ROADTYPE_ROAD) SetTownIndex(tile, p2);
751 if (rtt != ROAD_TILE_CROSSING) SetRoadBits(tile, existing | pieces, rt);
752 break;
755 case MP_TUNNELBRIDGE: {
756 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
758 SetRoadTypes(other_end, GetRoadTypes(other_end) | RoadTypeToRoadTypes(rt));
759 SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
760 SetRoadOwner(other_end, rt, company);
761 SetRoadOwner(tile, rt, company);
763 /* Mark tiles dirty that have been repaved */
764 if (IsBridge(tile)) {
765 MarkBridgeDirty(tile);
766 } else {
767 MarkTileDirtyByTile(other_end);
768 MarkTileDirtyByTile(tile);
770 break;
773 case MP_STATION:
774 assert(IsDriveThroughStopTile(tile));
775 SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
776 SetRoadOwner(tile, rt, company);
777 break;
779 default:
780 MakeRoadNormal(tile, pieces, RoadTypeToRoadTypes(rt), p2, company, company);
781 break;
784 /* Update company infrastructure count. */
785 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
786 if (c != NULL) {
787 if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
788 c->infrastructure.road[rt] += num_pieces;
789 DirtyCompanyInfrastructureWindows(c->index);
792 if (rt != ROADTYPE_TRAM && IsNormalRoadTile(tile)) {
793 existing |= pieces;
794 SetDisallowedRoadDirections(tile, IsStraightRoad(existing) ?
795 GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
798 MarkTileDirtyByTile(tile);
800 return cost;
804 * Checks whether a road or tram connection can be found when building a new road or tram.
805 * @param tile Tile at which the road being built will end.
806 * @param rt Roadtype of the road being built.
807 * @param dir Direction that the road is following.
808 * @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.
810 static bool CanConnectToRoad(TileIndex tile, RoadType rt, DiagDirection dir)
812 RoadBits bits = GetAnyRoadBits(tile + TileOffsByDiagDir(dir), rt, false);
813 return (bits & DiagDirToRoadBits(ReverseDiagDir(dir))) != 0;
817 * Build a long piece of road.
818 * @param start_tile start tile of drag (the building cost will appear over this tile)
819 * @param flags operation to perform
820 * @param p1 end tile of drag
821 * @param p2 various bitstuffed elements
822 * - 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
823 * - 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
824 * - p2 = (bit 2) - direction: 0 = along x-axis, 1 = along y-axis (p2 & 4)
825 * - p2 = (bit 3 + 4) - road type
826 * - p2 = (bit 5) - set road direction
827 * - p2 = (bit 6) - defines two different behaviors for this command:
828 * - 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
829 * - 1 = Fail if an obstacle is found. Always take into account bit 0 and 1. This behavior is used for scripts
830 * @param text unused
831 * @return the cost of this operation or an error
833 CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
835 DisallowedRoadDirections drd = DRD_NORTHBOUND;
837 if (p1 >= MapSize()) return CMD_ERROR;
839 TileIndex end_tile = p1;
840 RoadType rt = Extract<RoadType, 3, 2>(p2);
841 if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
843 Axis axis = Extract<Axis, 2, 1>(p2);
844 /* Only drag in X or Y direction dictated by the direction variable */
845 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
846 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
848 DiagDirection dir = AxisToDiagDir(axis);
850 /* Swap direction, also the half-tile drag var (bit 0 and 1) */
851 if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
852 dir = ReverseDiagDir(dir);
853 p2 ^= 3;
854 drd = DRD_SOUTHBOUND;
857 /* On the X-axis, we have to swap the initial bits, so they
858 * will be interpreted correctly in the GTTS. Furthermore
859 * when you just 'click' on one tile to build them. */
860 if ((axis == AXIS_Y) == (start_tile == end_tile && HasBit(p2, 0) == HasBit(p2, 1))) drd ^= DRD_BOTH;
861 /* No disallowed direction bits have to be toggled */
862 if (!HasBit(p2, 5)) drd = DRD_NONE;
864 CommandCost cost(EXPENSES_CONSTRUCTION);
865 CommandCost last_error = CMD_ERROR;
866 TileIndex tile = start_tile;
867 bool had_bridge = false;
868 bool had_tunnel = false;
869 bool had_success = false;
870 bool is_ai = HasBit(p2, 6);
872 /* Start tile is the first tile clicked by the user. */
873 for (;;) {
874 RoadBits bits = AxisToRoadBits(axis);
876 /* Determine which road parts should be built. */
877 if (!is_ai && start_tile != end_tile) {
878 /* Only build the first and last roadbit if they can connect to something. */
879 if (tile == end_tile && !CanConnectToRoad(tile, rt, dir)) {
880 bits = DiagDirToRoadBits(ReverseDiagDir(dir));
881 } else if (tile == start_tile && !CanConnectToRoad(tile, rt, ReverseDiagDir(dir))) {
882 bits = DiagDirToRoadBits(dir);
884 } else {
885 /* Road parts only have to be built at the start tile or at the end tile. */
886 if (tile == end_tile && !HasBit(p2, 1)) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
887 if (tile == start_tile && HasBit(p2, 0)) bits &= DiagDirToRoadBits(dir);
890 CommandCost ret = DoCommand(tile, drd << 6 | rt << 4 | bits, 0, flags, CMD_BUILD_ROAD);
891 if (ret.Failed()) {
892 last_error = ret;
893 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
894 if (is_ai) return last_error;
895 break;
897 } else {
898 had_success = true;
899 /* Only pay for the upgrade on one side of the bridges and tunnels */
900 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
901 if (IsBridge(tile)) {
902 if (!had_bridge || GetTunnelBridgeDirection(tile) == dir) {
903 cost.AddCost(ret);
905 had_bridge = true;
906 } else { // IsTunnel(tile)
907 if (!had_tunnel || GetTunnelBridgeDirection(tile) == dir) {
908 cost.AddCost(ret);
910 had_tunnel = true;
912 } else {
913 cost.AddCost(ret);
917 if (tile == end_tile) break;
919 tile += TileOffsByDiagDir(dir);
922 return had_success ? cost : last_error;
926 * Remove a long piece of road.
927 * @param start_tile start tile of drag
928 * @param flags operation to perform
929 * @param p1 end tile of drag
930 * @param p2 various bitstuffed elements
931 * - p2 = (bit 0) - start tile starts in the 2nd half of tile (p2 & 1)
932 * - p2 = (bit 1) - end tile starts in the 2nd half of tile (p2 & 2)
933 * - p2 = (bit 2) - direction: 0 = along x-axis, 1 = along y-axis (p2 & 4)
934 * - p2 = (bit 3 + 4) - road type
935 * @param text unused
936 * @return the cost of this operation or an error
938 CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
940 CommandCost cost(EXPENSES_CONSTRUCTION);
942 if (p1 >= MapSize()) return CMD_ERROR;
944 TileIndex end_tile = p1;
945 RoadType rt = Extract<RoadType, 3, 2>(p2);
946 if (!IsValidRoadType(rt)) return CMD_ERROR;
948 Axis axis = Extract<Axis, 2, 1>(p2);
949 /* Only drag in X or Y direction dictated by the direction variable */
950 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
951 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
953 /* Swap start and ending tile, also the half-tile drag var (bit 0 and 1) */
954 if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
955 TileIndex t = start_tile;
956 start_tile = end_tile;
957 end_tile = t;
958 p2 ^= IsInsideMM(p2 & 3, 1, 3) ? 3 : 0;
961 Money money = GetAvailableMoneyForCommand();
962 TileIndex tile = start_tile;
963 CommandCost last_error = CMD_ERROR;
964 bool had_success = false;
965 /* Start tile is the small number. */
966 for (;;) {
967 RoadBits bits = AxisToRoadBits(axis);
969 if (tile == end_tile && !HasBit(p2, 1)) bits &= ROAD_NW | ROAD_NE;
970 if (tile == start_tile && HasBit(p2, 0)) bits &= ROAD_SE | ROAD_SW;
972 /* try to remove the halves. */
973 if (bits != 0) {
974 CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rt, true);
975 if (ret.Succeeded()) {
976 if (flags & DC_EXEC) {
977 money -= ret.GetCost();
978 if (money < 0) {
979 _additional_cash_required = DoCommand(start_tile, end_tile, p2, flags & ~DC_EXEC, CMD_REMOVE_LONG_ROAD).GetCost();
980 return cost;
982 RemoveRoad(tile, flags, bits, rt, true, false);
984 cost.AddCost(ret);
985 had_success = true;
986 } else {
987 /* Ownership errors are more important. */
988 if (last_error.GetErrorMessage() != STR_ERROR_OWNED_BY) last_error = ret;
992 if (tile == end_tile) break;
994 tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
997 return had_success ? cost : last_error;
1001 * Build a road depot.
1002 * @param tile tile where to build the depot
1003 * @param flags operation to perform
1004 * @param p1 bit 0..1 entrance direction (DiagDirection)
1005 * bit 2..3 road type
1006 * @param p2 unused
1007 * @param text unused
1008 * @return the cost of this operation or an error
1010 * @todo When checking for the tile slope,
1011 * distinguish between "Flat land required" and "land sloped in wrong direction"
1013 CommandCost CmdBuildRoadDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1015 DiagDirection dir = Extract<DiagDirection, 0, 2>(p1);
1016 RoadType rt = Extract<RoadType, 2, 2>(p1);
1018 if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
1020 Slope tileh = GetTileSlope(tile);
1021 if (tileh != SLOPE_FLAT && (
1022 !_settings_game.construction.build_on_slopes ||
1023 !CanBuildDepotByTileh(dir, tileh)
1024 )) {
1025 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
1028 CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1029 if (cost.Failed()) return cost;
1031 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1033 if (!Depot::CanAllocateItem()) return CMD_ERROR;
1035 if (flags & DC_EXEC) {
1036 Depot *dep = new Depot(tile);
1037 dep->build_date = _date;
1039 /* A road depot has two road bits. */
1040 Company::Get(_current_company)->infrastructure.road[rt] += 2;
1041 DirtyCompanyInfrastructureWindows(_current_company);
1043 MakeRoadDepot(tile, _current_company, dep->index, dir, rt);
1044 MarkTileDirtyByTile(tile);
1045 MakeDefaultName(dep);
1047 cost.AddCost(_price[PR_BUILD_DEPOT_ROAD]);
1048 return cost;
1051 static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
1053 if (_current_company != OWNER_WATER) {
1054 CommandCost ret = CheckTileOwnership(tile);
1055 if (ret.Failed()) return ret;
1058 CommandCost ret = EnsureNoVehicleOnGround(tile);
1059 if (ret.Failed()) return ret;
1061 if (flags & DC_EXEC) {
1062 Company *c = Company::GetIfValid(GetTileOwner(tile));
1063 if (c != NULL) {
1064 /* A road depot has two road bits. */
1065 c->infrastructure.road[FIND_FIRST_BIT(GetRoadTypes(tile))] -= 2;
1066 DirtyCompanyInfrastructureWindows(c->index);
1069 delete Depot::GetByTile(tile);
1070 DoClearSquare(tile);
1073 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_ROAD]);
1076 static CommandCost ClearTile_Road(TileIndex tile, DoCommandFlag flags)
1078 switch (GetRoadTileType(tile)) {
1079 case ROAD_TILE_NORMAL: {
1080 RoadBits b = GetAllRoadBits(tile);
1082 /* Clear the road if only one piece is on the tile OR we are not using the DC_AUTO flag */
1083 if ((HasExactlyOneBit(b) && GetRoadBits(tile, ROADTYPE_TRAM) == ROAD_NONE) || !(flags & DC_AUTO)) {
1084 CommandCost ret(EXPENSES_CONSTRUCTION);
1085 RoadType rt;
1086 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1087 CommandCost tmp_ret = RemoveRoad(tile, flags, GetRoadBits(tile, rt), rt, true);
1088 if (tmp_ret.Failed()) return tmp_ret;
1089 ret.AddCost(tmp_ret);
1091 return ret;
1093 return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1096 case ROAD_TILE_CROSSING: {
1097 RoadTypes rts = GetRoadTypes(tile);
1098 CommandCost ret(EXPENSES_CONSTRUCTION);
1100 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1102 /* Must iterate over the roadtypes in a reverse manner because
1103 * tram tracks must be removed before the road bits. */
1104 RoadType rt = ROADTYPE_TRAM;
1105 do {
1106 if (HasBit(rts, rt)) {
1107 CommandCost tmp_ret = RemoveRoad(tile, flags, GetCrossingRoadBits(tile), rt, false);
1108 if (tmp_ret.Failed()) return tmp_ret;
1109 ret.AddCost(tmp_ret);
1111 } while (rt-- != ROADTYPE_ROAD);
1113 if (flags & DC_EXEC) {
1114 DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1116 return ret;
1119 default:
1120 case ROAD_TILE_DEPOT:
1121 if (flags & DC_AUTO) {
1122 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1124 return RemoveRoadDepot(tile, flags);
1129 struct DrawRoadTileStruct {
1130 uint16 image;
1131 byte subcoord_x;
1132 byte subcoord_y;
1135 #include "table/road_land.h"
1138 * Get the foundationtype of a RoadBits Slope combination
1140 * @param tileh The Slope part
1141 * @param bits The RoadBits part
1142 * @return The resulting Foundation
1144 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
1146 /* Flat land and land without a road doesn't require a foundation */
1147 if (tileh == SLOPE_FLAT || bits == ROAD_NONE) return FOUNDATION_NONE;
1149 /* Steep slopes behave the same as slopes with one corner raised. */
1150 if (IsSteepSlope(tileh)) {
1151 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
1154 /* Leveled RoadBits on a slope */
1155 if ((_invalid_tileh_slopes_road[0][tileh] & bits) == ROAD_NONE) return FOUNDATION_LEVELED;
1157 /* Straight roads without foundation on a slope */
1158 if (!IsSlopeWithOneCornerRaised(tileh) &&
1159 (_invalid_tileh_slopes_road[1][tileh] & bits) == ROAD_NONE)
1160 return FOUNDATION_NONE;
1162 /* Roads on steep Slopes or on Slopes with one corner raised */
1163 return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
1166 const byte _road_sloped_sprites[14] = {
1167 0, 0, 2, 0,
1168 0, 1, 0, 0,
1169 3, 0, 0, 0,
1170 0, 0
1174 * Should the road be drawn as a unpaved snow/desert road?
1175 * By default, roads are always drawn as unpaved if they are on desert or
1176 * above the snow line, but NewGRFs can override this for desert.
1178 * @param tile The tile the road is on
1179 * @param roadside What sort of road this is
1180 * @return True if snow/desert road sprites should be used.
1182 static bool DrawRoadAsSnowDesert(TileIndex tile, Roadside roadside)
1184 return (IsOnSnow(tile) &&
1185 !(_settings_game.game_creation.landscape == LT_TROPIC && HasGrfMiscBit(GMB_DESERT_PAVED_ROADS) &&
1186 roadside != ROADSIDE_BARREN && roadside != ROADSIDE_GRASS && roadside != ROADSIDE_GRASS_ROAD_WORKS));
1190 * Draws the catenary for the given tile
1191 * @param ti information about the tile (slopes, height etc)
1192 * @param tram the roadbits for the tram
1194 void DrawRoadCatenary(const TileInfo *ti, RoadBits tram)
1196 /* Do not draw catenary if it is invisible */
1197 if (IsInvisibilitySet(TO_CATENARY)) return;
1199 /* Don't draw the catenary under a low bridge */
1200 if (IsBridgeAbove(ti->tile) && !IsTransparencySet(TO_CATENARY)) {
1201 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1203 if (height <= GetTileMaxZ(ti->tile) + 1) return;
1206 SpriteID front;
1207 SpriteID back;
1209 if (ti->tileh != SLOPE_FLAT) {
1210 back = SPR_TRAMWAY_BACK_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1211 front = SPR_TRAMWAY_FRONT_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1212 } else {
1213 back = SPR_TRAMWAY_BASE + _road_backpole_sprites_1[tram];
1214 front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[tram];
1217 AddSortableSpriteToDraw(back, PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
1218 AddSortableSpriteToDraw(front, PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
1222 * Draws details on/around the road
1223 * @param img the sprite to draw
1224 * @param ti the tile to draw on
1225 * @param dx the offset from the top of the BB of the tile
1226 * @param dy the offset from the top of the BB of the tile
1227 * @param h the height of the sprite to draw
1229 static void DrawRoadDetail(SpriteID img, const TileInfo *ti, int dx, int dy, int h)
1231 int x = ti->x | dx;
1232 int y = ti->y | dy;
1233 int z = ti->z;
1234 if (ti->tileh != SLOPE_FLAT) z = GetSlopePixelZ(x, y);
1235 AddSortableSpriteToDraw(img, PAL_NONE, x, y, 2, 2, h, z);
1239 * Draw ground sprite and road pieces
1240 * @param ti TileInfo
1242 static void DrawRoadBits(TileInfo *ti)
1244 RoadBits road = GetRoadBits(ti->tile, ROADTYPE_ROAD);
1245 RoadBits tram = GetRoadBits(ti->tile, ROADTYPE_TRAM);
1247 SpriteID image = 0;
1248 PaletteID pal = PAL_NONE;
1250 if (ti->tileh != SLOPE_FLAT) {
1251 DrawFoundation(ti, GetRoadFoundation(ti->tileh, road | tram));
1253 /* DrawFoundation() modifies ti.
1254 * Default sloped sprites.. */
1255 if (ti->tileh != SLOPE_FLAT) image = _road_sloped_sprites[ti->tileh - 1] + SPR_ROAD_SLOPE_START;
1258 if (image == 0) image = _road_tile_sprites_1[road != ROAD_NONE ? road : tram];
1260 Roadside roadside = GetRoadside(ti->tile);
1262 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1263 image += 19;
1264 } else {
1265 switch (roadside) {
1266 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1267 case ROADSIDE_GRASS: break;
1268 case ROADSIDE_GRASS_ROAD_WORKS: break;
1269 default: image -= 19; break; // Paved
1273 DrawGroundSprite(image, pal);
1275 /* For tram we overlay the road graphics with either tram tracks only
1276 * (when there is actual road beneath the trams) or with tram tracks
1277 * and some dirts which hides the road graphics */
1278 if (tram != ROAD_NONE) {
1279 if (ti->tileh != SLOPE_FLAT) {
1280 image = _road_sloped_sprites[ti->tileh - 1] + SPR_TRAMWAY_SLOPED_OFFSET;
1281 } else {
1282 image = _road_tile_sprites_1[tram] - SPR_ROAD_Y;
1284 image += (road == ROAD_NONE) ? SPR_TRAMWAY_TRAM : SPR_TRAMWAY_OVERLAY;
1285 DrawGroundSprite(image, pal);
1288 if (road != ROAD_NONE) {
1289 DisallowedRoadDirections drd = GetDisallowedRoadDirections(ti->tile);
1290 if (drd != DRD_NONE) {
1291 DrawGroundSpriteAt(SPR_ONEWAY_BASE + drd - 1 + ((road == ROAD_X) ? 0 : 3), PAL_NONE, 8, 8, GetPartialPixelZ(8, 8, ti->tileh));
1295 if (HasRoadWorks(ti->tile)) {
1296 /* Road works */
1297 DrawGroundSprite((road | tram) & ROAD_X ? SPR_EXCAVATION_X : SPR_EXCAVATION_Y, PAL_NONE);
1298 return;
1301 if (tram != ROAD_NONE) DrawRoadCatenary(ti, tram);
1303 /* Return if full detail is disabled, or we are zoomed fully out. */
1304 if (!HasBit(_display_opt, DO_FULL_DETAIL) || _cur_dpi->zoom > ZOOM_LVL_DETAIL) return;
1306 /* Do not draw details (street lights, trees) under low bridge */
1307 if (IsBridgeAbove(ti->tile) && (roadside == ROADSIDE_TREES || roadside == ROADSIDE_STREET_LIGHTS)) {
1308 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1309 int minz = GetTileMaxZ(ti->tile) + 2;
1311 if (roadside == ROADSIDE_TREES) minz++;
1313 if (height < minz) return;
1316 /* If there are no road bits, return, as there is nothing left to do */
1317 if (HasAtMostOneBit(road)) return;
1319 /* Draw extra details. */
1320 for (const DrawRoadTileStruct *drts = _road_display_table[roadside][road | tram]; drts->image != 0; drts++) {
1321 DrawRoadDetail(drts->image, ti, drts->subcoord_x, drts->subcoord_y, 0x10);
1325 /** Tile callback function for rendering a road tile to the screen */
1326 static void DrawTile_Road(TileInfo *ti)
1328 switch (GetRoadTileType(ti->tile)) {
1329 case ROAD_TILE_NORMAL:
1330 DrawRoadBits(ti);
1331 break;
1333 case ROAD_TILE_CROSSING: {
1334 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1336 PaletteID pal = PAL_NONE;
1337 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1339 if (rti->UsesOverlay()) {
1340 Axis axis = GetCrossingRailAxis(ti->tile);
1341 SpriteID road = SPR_ROAD_Y + axis;
1343 Roadside roadside = GetRoadside(ti->tile);
1345 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1346 road += 19;
1347 } else {
1348 switch (roadside) {
1349 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1350 case ROADSIDE_GRASS: break;
1351 default: road -= 19; break; // Paved
1355 DrawGroundSprite(road, pal);
1357 SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
1358 /* Draw tracks, but draw PBS reserved tracks darker. */
1359 pal = (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) ? PALETTE_CRASH : PAL_NONE;
1360 DrawGroundSprite(rail, pal);
1362 DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
1363 } else {
1364 SpriteID image = rti->base_sprites.crossing;
1366 if (GetCrossingRoadAxis(ti->tile) == AXIS_X) image++;
1367 if (IsCrossingBarred(ti->tile)) image += 2;
1369 Roadside roadside = GetRoadside(ti->tile);
1371 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1372 image += 8;
1373 } else {
1374 switch (roadside) {
1375 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1376 case ROADSIDE_GRASS: break;
1377 default: image += 4; break; // Paved
1381 DrawGroundSprite(image, pal);
1383 /* PBS debugging, draw reserved tracks darker */
1384 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) {
1385 DrawGroundSprite(GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y, PALETTE_CRASH);
1389 if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
1390 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + (GetCrossingRoadAxis(ti->tile) ^ 1), pal);
1391 DrawRoadCatenary(ti, GetCrossingRoadBits(ti->tile));
1393 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
1394 break;
1397 default:
1398 case ROAD_TILE_DEPOT: {
1399 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1401 PaletteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
1403 const DrawTileSprites *dts;
1404 if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
1405 dts = &_tram_depot[GetRoadDepotDirection(ti->tile)];
1406 } else {
1407 dts = &_road_depot[GetRoadDepotDirection(ti->tile)];
1410 DrawGroundSprite(dts->ground.sprite, PAL_NONE);
1411 DrawOrigTileSeq(ti, dts, TO_BUILDINGS, palette);
1412 break;
1415 DrawBridgeMiddle(ti);
1419 * Draw the road depot sprite.
1420 * @param x The x offset to draw at.
1421 * @param y The y offset to draw at.
1422 * @param dir The direction the depot must be facing.
1423 * @param rt The road type of the depot to draw.
1425 void DrawRoadDepotSprite(int x, int y, DiagDirection dir, RoadType rt)
1427 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
1428 const DrawTileSprites *dts = (rt == ROADTYPE_TRAM) ? &_tram_depot[dir] : &_road_depot[dir];
1430 DrawSprite(dts->ground.sprite, PAL_NONE, x, y);
1431 DrawOrigTileSeqInGUI(x, y, dts, palette);
1435 * Updates cached nearest town for all road tiles
1436 * @param invalidate are we just invalidating cached data?
1437 * @pre invalidate == true implies _generating_world == true
1439 void UpdateNearestTownForRoadTiles(bool invalidate)
1441 assert(!invalidate || _generating_world);
1443 for (TileIndex t = 0; t < MapSize(); t++) {
1444 if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1445 TownID tid = (TownID)INVALID_TOWN;
1446 if (!invalidate) {
1447 const Town *town = CalcClosestTownFromTile(t);
1448 if (town != NULL) tid = town->index;
1450 SetTownIndex(t, tid);
1455 static int GetSlopePixelZ_Road(TileIndex tile, uint x, uint y)
1458 if (IsNormalRoad(tile)) {
1459 int z;
1460 Slope tileh = GetTilePixelSlope(tile, &z);
1461 if (tileh == SLOPE_FLAT) return z;
1463 Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
1464 z += ApplyPixelFoundationToSlope(f, &tileh);
1465 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
1466 } else {
1467 return GetTileMaxPixelZ(tile);
1471 static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
1473 if (IsNormalRoad(tile)) {
1474 return GetRoadFoundation(tileh, GetAllRoadBits(tile));
1475 } else {
1476 return FlatteningFoundation(tileh);
1480 static const Roadside _town_road_types[][2] = {
1481 { ROADSIDE_GRASS, ROADSIDE_GRASS },
1482 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1483 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1484 { ROADSIDE_TREES, ROADSIDE_TREES },
1485 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
1488 static const Roadside _town_road_types_2[][2] = {
1489 { ROADSIDE_GRASS, ROADSIDE_GRASS },
1490 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1491 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
1492 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
1493 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
1497 static void TileLoop_Road(TileIndex tile)
1499 switch (_settings_game.game_creation.landscape) {
1500 case LT_ARCTIC:
1501 if (IsOnSnow(tile) != (GetTileZ(tile) > GetSnowLine())) {
1502 ToggleSnow(tile);
1503 MarkTileDirtyByTile(tile);
1505 break;
1507 case LT_TROPIC:
1508 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsOnDesert(tile)) {
1509 ToggleDesert(tile);
1510 MarkTileDirtyByTile(tile);
1512 break;
1515 if (IsRoadDepot(tile)) return;
1517 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
1518 if (!HasRoadWorks(tile)) {
1519 HouseZonesBits grp = HZB_TOWN_EDGE;
1521 if (t != NULL) {
1522 grp = GetTownRadiusGroup(t, tile);
1524 /* Show an animation to indicate road work */
1525 if (t->road_build_months != 0 &&
1526 (DistanceManhattan(t->xy, tile) < 8 || grp != HZB_TOWN_EDGE) &&
1527 IsNormalRoad(tile) && !HasAtMostOneBit(GetAllRoadBits(tile))) {
1528 if (GetFoundationSlope(tile) == SLOPE_FLAT && EnsureNoVehicleOnGround(tile).Succeeded() && Chance16(1, 40)) {
1529 StartRoadWorks(tile);
1531 if (_settings_client.sound.ambient) SndPlayTileFx(SND_21_JACKHAMMER, tile);
1532 CreateEffectVehicleAbove(
1533 TileX(tile) * TILE_SIZE + 7,
1534 TileY(tile) * TILE_SIZE + 7,
1536 EV_BULLDOZER);
1537 MarkTileDirtyByTile(tile);
1538 return;
1544 /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
1545 const Roadside *new_rs = (_settings_game.game_creation.landscape == LT_TOYLAND) ? _town_road_types_2[grp] : _town_road_types[grp];
1546 Roadside cur_rs = GetRoadside(tile);
1548 /* We have our desired type, do nothing */
1549 if (cur_rs == new_rs[0]) return;
1551 /* We have the pre-type of the desired type, switch to the desired type */
1552 if (cur_rs == new_rs[1]) {
1553 cur_rs = new_rs[0];
1554 /* We have barren land, install the pre-type */
1555 } else if (cur_rs == ROADSIDE_BARREN) {
1556 cur_rs = new_rs[1];
1557 /* We're totally off limits, remove any installation and make barren land */
1558 } else {
1559 cur_rs = ROADSIDE_BARREN;
1561 SetRoadside(tile, cur_rs);
1562 MarkTileDirtyByTile(tile);
1564 } else if (IncreaseRoadWorksCounter(tile)) {
1565 TerminateRoadWorks(tile);
1567 if (_settings_game.economy.mod_road_rebuild) {
1568 /* Generate a nicer town surface */
1569 const RoadBits old_rb = GetAnyRoadBits(tile, ROADTYPE_ROAD);
1570 const RoadBits new_rb = CleanUpRoadBits(tile, old_rb);
1572 if (old_rb != new_rb) {
1573 RemoveRoad(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, (old_rb ^ new_rb), ROADTYPE_ROAD, true);
1577 MarkTileDirtyByTile(tile);
1581 static bool ClickTile_Road(TileIndex tile)
1583 if (!IsRoadDepot(tile)) return false;
1585 ShowDepotWindow(tile, VEH_ROAD);
1586 return true;
1589 /* Converts RoadBits to TrackBits */
1590 static const TrackBits _road_trackbits[16] = {
1591 TRACK_BIT_NONE, // ROAD_NONE
1592 TRACK_BIT_NONE, // ROAD_NW
1593 TRACK_BIT_NONE, // ROAD_SW
1594 TRACK_BIT_LEFT, // ROAD_W
1595 TRACK_BIT_NONE, // ROAD_SE
1596 TRACK_BIT_Y, // ROAD_Y
1597 TRACK_BIT_LOWER, // ROAD_S
1598 TRACK_BIT_LEFT | TRACK_BIT_LOWER | TRACK_BIT_Y, // ROAD_Y | ROAD_SW
1599 TRACK_BIT_NONE, // ROAD_NE
1600 TRACK_BIT_UPPER, // ROAD_N
1601 TRACK_BIT_X, // ROAD_X
1602 TRACK_BIT_LEFT | TRACK_BIT_UPPER | TRACK_BIT_X, // ROAD_X | ROAD_NW
1603 TRACK_BIT_RIGHT, // ROAD_E
1604 TRACK_BIT_RIGHT | TRACK_BIT_UPPER | TRACK_BIT_Y, // ROAD_Y | ROAD_NE
1605 TRACK_BIT_RIGHT | TRACK_BIT_LOWER | TRACK_BIT_X, // ROAD_X | ROAD_SE
1606 TRACK_BIT_ALL, // ROAD_ALL
1609 static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
1611 TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
1612 TrackdirBits red_signals = TRACKDIR_BIT_NONE; // crossing barred
1613 switch (mode) {
1614 case TRANSPORT_RAIL:
1615 if (IsLevelCrossing(tile)) trackdirbits = TrackBitsToTrackdirBits(GetCrossingRailBits(tile));
1616 break;
1618 case TRANSPORT_ROAD:
1619 if ((GetRoadTypes(tile) & sub_mode) == 0) break;
1620 switch (GetRoadTileType(tile)) {
1621 case ROAD_TILE_NORMAL: {
1622 const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
1623 RoadType rt = (RoadType)FindFirstBit(sub_mode);
1624 RoadBits bits = GetRoadBits(tile, rt);
1626 /* no roadbit at this side of tile, return 0 */
1627 if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break;
1629 uint multiplier = drd_to_multiplier[rt == ROADTYPE_TRAM ? DRD_NONE : GetDisallowedRoadDirections(tile)];
1630 if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier);
1631 break;
1634 case ROAD_TILE_CROSSING: {
1635 Axis axis = GetCrossingRoadAxis(tile);
1637 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
1639 trackdirbits = TrackBitsToTrackdirBits(AxisToTrackBits(axis));
1640 if (IsCrossingBarred(tile)) red_signals = trackdirbits;
1641 break;
1644 default:
1645 case ROAD_TILE_DEPOT: {
1646 DiagDirection dir = GetRoadDepotDirection(tile);
1648 if (side != INVALID_DIAGDIR && side != dir) break;
1650 trackdirbits = TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir));
1651 break;
1654 break;
1656 default: break;
1658 return CombineTrackStatus(trackdirbits, red_signals);
1661 static const StringID _road_tile_strings[] = {
1662 STR_LAI_ROAD_DESCRIPTION_ROAD,
1663 STR_LAI_ROAD_DESCRIPTION_ROAD,
1664 STR_LAI_ROAD_DESCRIPTION_ROAD,
1665 STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_STREETLIGHTS,
1666 STR_LAI_ROAD_DESCRIPTION_ROAD,
1667 STR_LAI_ROAD_DESCRIPTION_TREE_LINED_ROAD,
1668 STR_LAI_ROAD_DESCRIPTION_ROAD,
1669 STR_LAI_ROAD_DESCRIPTION_ROAD,
1672 static void GetTileDesc_Road(TileIndex tile, TileDesc *td)
1674 Owner rail_owner = INVALID_OWNER;
1675 Owner road_owner = INVALID_OWNER;
1676 Owner tram_owner = INVALID_OWNER;
1678 switch (GetRoadTileType(tile)) {
1679 case ROAD_TILE_CROSSING: {
1680 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_RAIL_LEVEL_CROSSING;
1681 RoadTypes rts = GetRoadTypes(tile);
1682 rail_owner = GetTileOwner(tile);
1683 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
1684 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
1686 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
1687 td->railtype = rti->strings.name;
1688 td->rail_speed = rti->max_speed;
1690 break;
1693 case ROAD_TILE_DEPOT:
1694 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_VEHICLE_DEPOT;
1695 road_owner = GetTileOwner(tile); // Tile has only one owner, roadtype does not matter
1696 td->build_date = Depot::GetByTile(tile)->build_date;
1697 break;
1699 default: {
1700 RoadTypes rts = GetRoadTypes(tile);
1701 td->str = (HasBit(rts, ROADTYPE_ROAD) ? _road_tile_strings[GetRoadside(tile)] : STR_LAI_ROAD_DESCRIPTION_TRAMWAY);
1702 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
1703 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
1704 break;
1708 /* Now we have to discover, if the tile has only one owner or many:
1709 * - Find a first_owner of the tile. (Currently road or tram must be present, but this will break when the third type becomes available)
1710 * - Compare the found owner with the other owners, and test if they differ.
1711 * Note: If road exists it will be the first_owner.
1713 Owner first_owner = (road_owner == INVALID_OWNER ? tram_owner : road_owner);
1714 bool mixed_owners = (tram_owner != INVALID_OWNER && tram_owner != first_owner) || (rail_owner != INVALID_OWNER && rail_owner != first_owner);
1716 if (mixed_owners) {
1717 /* Multiple owners */
1718 td->owner_type[0] = (rail_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_RAIL_OWNER);
1719 td->owner[0] = rail_owner;
1720 td->owner_type[1] = (road_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_ROAD_OWNER);
1721 td->owner[1] = road_owner;
1722 td->owner_type[2] = (tram_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_TRAM_OWNER);
1723 td->owner[2] = tram_owner;
1724 } else {
1725 /* One to rule them all */
1726 td->owner[0] = first_owner;
1731 * Given the direction the road depot is pointing, this is the direction the
1732 * vehicle should be travelling in in order to enter the depot.
1734 static const byte _roadveh_enter_depot_dir[4] = {
1735 TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
1738 static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
1740 switch (GetRoadTileType(tile)) {
1741 case ROAD_TILE_DEPOT: {
1742 if (v->type != VEH_ROAD) break;
1744 RoadVehicle *rv = RoadVehicle::From(v);
1745 if (rv->frame == RVC_DEPOT_STOP_FRAME &&
1746 _roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
1747 rv->state = RVSB_IN_DEPOT;
1748 rv->vehstatus |= VS_HIDDEN;
1749 rv->direction = ReverseDir(rv->direction);
1750 if (rv->Next() == NULL) VehicleEnterDepot(rv->First());
1751 rv->tile = tile;
1753 InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
1754 return VETSB_ENTERED_WORMHOLE;
1756 break;
1759 default: break;
1761 return VETSB_CONTINUE;
1765 static void ChangeTileOwner_Road(TileIndex tile, Owner old_owner, Owner new_owner)
1767 if (IsRoadDepot(tile)) {
1768 if (GetTileOwner(tile) == old_owner) {
1769 if (new_owner == INVALID_OWNER) {
1770 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
1771 } else {
1772 /* A road depot has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
1773 RoadType rt = (RoadType)FIND_FIRST_BIT(GetRoadTypes(tile));
1774 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
1775 Company::Get(new_owner)->infrastructure.road[rt] += 2;
1777 SetTileOwner(tile, new_owner);
1778 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1779 if (GetRoadOwner(tile, rt) == old_owner) {
1780 SetRoadOwner(tile, rt, new_owner);
1785 return;
1788 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1789 /* Update all roadtypes, no matter if they are present */
1790 if (GetRoadOwner(tile, rt) == old_owner) {
1791 if (HasTileRoadType(tile, rt)) {
1792 /* A level crossing has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
1793 uint num_bits = IsLevelCrossing(tile) ? 2 : CountBits(GetRoadBits(tile, rt));
1794 Company::Get(old_owner)->infrastructure.road[rt] -= num_bits;
1795 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += num_bits;
1798 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
1802 if (IsLevelCrossing(tile)) {
1803 if (GetTileOwner(tile) == old_owner) {
1804 if (new_owner == INVALID_OWNER) {
1805 DoCommand(tile, 0, GetCrossingRailTrack(tile), DC_EXEC | DC_BANKRUPT, CMD_REMOVE_SINGLE_RAIL);
1806 } else {
1807 /* Update infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
1808 Company::Get(old_owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
1809 Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
1811 SetTileOwner(tile, new_owner);
1817 static CommandCost TerraformTile_Road(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
1819 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
1820 switch (GetRoadTileType(tile)) {
1821 case ROAD_TILE_CROSSING:
1822 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]);
1823 break;
1825 case ROAD_TILE_DEPOT:
1826 if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRoadDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
1827 break;
1829 case ROAD_TILE_NORMAL: {
1830 RoadBits bits = GetAllRoadBits(tile);
1831 RoadBits bits_copy = bits;
1832 /* Check if the slope-road_bits combination is valid at all, i.e. it is safe to call GetRoadFoundation(). */
1833 if (CheckRoadSlope(tileh_new, &bits_copy, ROAD_NONE, ROAD_NONE).Succeeded()) {
1834 /* CheckRoadSlope() sometimes changes the road_bits, if it does not agree with them. */
1835 if (bits == bits_copy) {
1836 int z_old;
1837 Slope tileh_old = GetTileSlope(tile, &z_old);
1839 /* Get the slope on top of the foundation */
1840 z_old += ApplyFoundationToSlope(GetRoadFoundation(tileh_old, bits), &tileh_old);
1841 z_new += ApplyFoundationToSlope(GetRoadFoundation(tileh_new, bits), &tileh_new);
1843 /* The surface slope must not be changed */
1844 if ((z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
1847 break;
1850 default: NOT_REACHED();
1854 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1857 /** Tile callback functions for road tiles */
1858 extern const TileTypeProcs _tile_type_road_procs = {
1859 DrawTile_Road, // draw_tile_proc
1860 GetSlopePixelZ_Road, // get_slope_z_proc
1861 ClearTile_Road, // clear_tile_proc
1862 NULL, // add_accepted_cargo_proc
1863 GetTileDesc_Road, // get_tile_desc_proc
1864 GetTileTrackStatus_Road, // get_tile_track_status_proc
1865 ClickTile_Road, // click_tile_proc
1866 NULL, // animate_tile_proc
1867 TileLoop_Road, // tile_loop_proc
1868 ChangeTileOwner_Road, // change_tile_owner_proc
1869 NULL, // add_produced_cargo_proc
1870 VehicleEnter_Road, // vehicle_enter_tile_proc
1871 GetFoundation_Road, // get_foundation_proc
1872 TerraformTile_Road, // terraform_tile_proc