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/>.
8 /** @file object_cmd.cpp Handling of object tiles. */
11 #include "landscape.h"
12 #include "command_func.h"
13 #include "viewport_func.h"
14 #include "company_base.h"
16 #include "bridge_map.h"
18 #include "autoslope.h"
19 #include "clear_func.h"
21 #include "window_func.h"
22 #include "company_gui.h"
23 #include "cheat_type.h"
25 #include "cargopacket.h"
26 #include "core/random_func.hpp"
27 #include "core/pool_func.hpp"
28 #include "object_map.h"
29 #include "object_base.h"
30 #include "newgrf_config.h"
31 #include "newgrf_object.h"
32 #include "date_func.h"
33 #include "newgrf_debug.h"
34 #include "vehicle_func.h"
35 #include "station_func.h"
36 #include "object_cmd.h"
37 #include "landscape_cmd.h"
39 #include "table/strings.h"
40 #include "table/object_land.h"
42 #include "safeguards.h"
44 ObjectPool
_object_pool("Object");
45 INSTANTIATE_POOL_METHODS(Object
)
46 uint16
Object::counts
[NUM_OBJECTS
];
49 * Get the object associated with a tile.
50 * @param tile The tile to fetch the object for.
53 /* static */ Object
*Object::GetByTile(TileIndex tile
)
55 return Object::Get(GetObjectIndex(tile
));
59 * Gets the ObjectType of the given object tile
60 * @param t the tile to get the type from.
61 * @pre IsTileType(t, MP_OBJECT)
64 ObjectType
GetObjectType(TileIndex t
)
66 assert(IsTileType(t
, MP_OBJECT
));
67 return Object::GetByTile(t
)->type
;
70 /** Initialize/reset the objects. */
71 void InitializeObjects()
73 Object::ResetTypeCounts();
77 * Actually build the object.
78 * @param type The type of object to build.
79 * @param tile The tile to build the northern tile of the object on.
80 * @param owner The owner of the object.
81 * @param town Town the tile is related with.
82 * @param view The view for the object.
83 * @pre All preconditions for building the object at that location
84 * are met, e.g. slope and clearness of tiles are checked.
86 void BuildObject(ObjectType type
, TileIndex tile
, CompanyID owner
, Town
*town
, uint8 view
)
88 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
90 TileArea
ta(tile
, GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4), GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4));
91 Object
*o
= new Object();
94 o
->town
= town
== nullptr ? CalcClosestTownFromTile(tile
) : town
;
95 o
->build_date
= _date
;
98 /* If nothing owns the object, the colour will be random. Otherwise
99 * get the colour from the company's livery settings. */
100 if (owner
== OWNER_NONE
) {
101 o
->colour
= Random();
103 const Livery
*l
= Company::Get(owner
)->livery
;
104 o
->colour
= l
->colour1
+ l
->colour2
* 16;
107 /* If the object wants only one colour, then give it that colour. */
108 if ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) == 0) o
->colour
&= 0xF;
110 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) {
111 uint16 res
= GetObjectCallback(CBID_OBJECT_COLOUR
, o
->colour
, 0, spec
, o
, tile
);
112 if (res
!= CALLBACK_FAILED
) {
113 if (res
>= 0x100) ErrorUnknownCallbackResult(spec
->grf_prop
.grffile
->grfid
, CBID_OBJECT_COLOUR
, res
);
114 o
->colour
= GB(res
, 0, 8);
118 assert(o
->town
!= nullptr);
120 for (TileIndex t
: ta
) {
121 WaterClass wc
= (IsWaterTile(t
) ? GetWaterClass(t
) : WATER_CLASS_INVALID
);
122 /* Update company infrastructure counts for objects build on canals owned by nobody. */
123 if (wc
== WATER_CLASS_CANAL
&& owner
!= OWNER_NONE
&& (IsTileOwner(tile
, OWNER_NONE
) || IsTileOwner(tile
, OWNER_WATER
))) {
124 Company::Get(owner
)->infrastructure
.water
++;
125 DirtyCompanyInfrastructureWindows(owner
);
127 bool remove
= IsDockingTile(t
);
128 MakeObject(t
, owner
, o
->index
, wc
, Random());
129 if (remove
) RemoveDockingTile(t
);
130 MarkTileDirtyByTile(t
);
133 Object::IncTypeCount(type
);
134 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) TriggerObjectAnimation(o
, OAT_BUILT
, spec
);
138 * Increase the animation stage of a whole structure.
139 * @param tile The tile of the structure.
141 static void IncreaseAnimationStage(TileIndex tile
)
143 TileArea ta
= Object::GetByTile(tile
)->location
;
144 for (TileIndex t
: ta
) {
145 SetAnimationFrame(t
, GetAnimationFrame(t
) + 1);
146 MarkTileDirtyByTile(t
);
150 /** We encode the company HQ size in the animation stage. */
151 #define GetCompanyHQSize GetAnimationFrame
152 /** We encode the company HQ size in the animation stage. */
153 #define IncreaseCompanyHQSize IncreaseAnimationStage
156 * Update the CompanyHQ to the state associated with the given score
157 * @param tile The (northern) tile of the company HQ, or INVALID_TILE.
158 * @param score The current (performance) score of the company.
160 void UpdateCompanyHQ(TileIndex tile
, uint score
)
162 if (tile
== INVALID_TILE
) return;
165 if (score
>= 170) val
++;
166 if (score
>= 350) val
++;
167 if (score
>= 520) val
++;
168 if (score
>= 720) val
++;
170 while (GetCompanyHQSize(tile
) < val
) {
171 IncreaseCompanyHQSize(tile
);
176 * Updates the colour of the object whenever a company changes.
177 * @param c The company the company colour changed of.
179 void UpdateObjectColours(const Company
*c
)
181 for (Object
*obj
: Object::Iterate()) {
182 Owner owner
= GetTileOwner(obj
->location
.tile
);
183 /* Not the current owner, so colour doesn't change. */
184 if (owner
!= c
->index
) continue;
186 const ObjectSpec
*spec
= ObjectSpec::GetByTile(obj
->location
.tile
);
187 /* Using the object colour callback, so not using company colour. */
188 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) continue;
190 const Livery
*l
= c
->livery
;
191 obj
->colour
= ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) ? (l
->colour2
* 16) : 0) + l
->colour1
;
195 extern CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
);
196 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
);
199 * Build an object object
200 * @param flags type of operation
201 * @param tile tile where the object will be located
202 * @param type the object type to build
203 * @param view the view for the object
204 * @return the cost of this operation or an error
206 CommandCost
CmdBuildObject(DoCommandFlag flags
, TileIndex tile
, ObjectType type
, uint8 view
)
208 CommandCost
cost(EXPENSES_CONSTRUCTION
);
210 if (type
>= NUM_OBJECTS
) return CMD_ERROR
;
211 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
212 if (_game_mode
== GM_NORMAL
&& !spec
->IsAvailable() && !_generating_world
) return CMD_ERROR
;
213 if ((_game_mode
== GM_EDITOR
|| _generating_world
) && !spec
->WasEverAvailable()) return CMD_ERROR
;
215 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_SCENEDIT
) != 0 && ((!_generating_world
&& _game_mode
!= GM_EDITOR
) || _current_company
!= OWNER_NONE
)) return CMD_ERROR
;
216 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_GAME
) != 0 && (_generating_world
|| _game_mode
!= GM_NORMAL
|| _current_company
> MAX_COMPANIES
)) return CMD_ERROR
;
217 if (view
>= spec
->views
) return CMD_ERROR
;
219 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS
);
220 if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST
);
222 int size_x
= GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4);
223 int size_y
= GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4);
224 TileArea
ta(tile
, size_x
, size_y
);
225 for (TileIndex t
: ta
) {
226 if (!IsValidTile(t
)) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
); // Might be off the map
229 if (type
== OBJECT_OWNED_LAND
) {
230 /* Owned land is special as it can be placed on any slope. */
231 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
));
233 /* Check the surface to build on. At this time we can't actually execute the
234 * the CLEAR_TILE commands since the newgrf callback later on can check
235 * some information about the tiles. */
236 bool allow_water
= (spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0;
237 bool allow_ground
= (spec
->flags
& OBJECT_FLAG_NOT_ON_LAND
) == 0;
238 for (TileIndex t
: ta
) {
239 if (HasTileWaterGround(t
)) {
240 if (!allow_water
) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
241 if (!IsWaterTile(t
)) {
242 /* Normal water tiles don't have to be cleared. For all other tile types clear
243 * the tile but leave the water. */
244 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
& ~DC_NO_WATER
& ~DC_EXEC
, t
));
246 /* Can't build on water owned by another company. */
247 Owner o
= GetTileOwner(t
);
248 if (o
!= OWNER_NONE
&& o
!= OWNER_WATER
) cost
.AddCost(CheckOwnership(o
, t
));
250 /* However, the tile has to be clear of vehicles. */
251 cost
.AddCost(EnsureNoVehicleOnGround(t
));
254 if (!allow_ground
) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER
);
255 /* For non-water tiles, we'll have to clear it before building. */
257 /* When relocating HQ, allow it to be relocated (partial) on itself. */
258 if (!(type
== OBJECT_HQ
&&
259 IsTileType(t
, MP_OBJECT
) &&
260 IsTileOwner(t
, _current_company
) &&
261 IsObjectType(t
, OBJECT_HQ
))) {
262 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
& ~DC_EXEC
, t
));
267 /* So, now the surface is checked... check the slope of said surface. */
269 if (GetTileSlope(tile
, &allowed_z
) != SLOPE_FLAT
) allowed_z
++;
271 for (TileIndex t
: ta
) {
272 uint16 callback
= CALLBACK_FAILED
;
273 if (HasBit(spec
->callback_mask
, CBM_OBJ_SLOPE_CHECK
)) {
274 TileIndex diff
= t
- tile
;
275 callback
= GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK
, GetTileSlope(t
), TileY(diff
) << 4 | TileX(diff
), spec
, nullptr, t
, view
);
278 if (callback
== CALLBACK_FAILED
) {
279 cost
.AddCost(CheckBuildableTile(t
, 0, allowed_z
, false, false));
281 /* The meaning of bit 10 is inverted for a grf version < 8. */
282 if (spec
->grf_prop
.grffile
->grf_version
< 8) ToggleBit(callback
, 10);
283 CommandCost ret
= GetErrorMessageFromLocationCallbackResult(callback
, spec
->grf_prop
.grffile
, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
284 if (ret
.Failed()) return ret
;
288 if (flags
& DC_EXEC
) {
289 /* This is basically a copy of the loop above with the exception that we now
290 * execute the commands and don't check for errors, since that's already done. */
291 for (TileIndex t
: ta
) {
292 if (HasTileWaterGround(t
)) {
293 if (!IsWaterTile(t
)) {
294 Command
<CMD_LANDSCAPE_CLEAR
>::Do((flags
& ~DC_NO_WATER
) | DC_NO_MODIFY_TOWN_RATING
, t
);
297 Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
| DC_NO_MODIFY_TOWN_RATING
, t
);
302 if (cost
.Failed()) return cost
;
304 /* Finally do a check for bridges. */
305 for (TileIndex t
: ta
) {
306 if (IsBridgeAbove(t
) && (
307 !(spec
->flags
& OBJECT_FLAG_ALLOW_UNDER_BRIDGE
) ||
308 (GetTileMaxZ(t
) + spec
->height
>= GetBridgeHeight(GetSouthernBridgeEnd(t
))))) {
309 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
314 uint build_object_size
= 1;
316 case OBJECT_TRANSMITTER
:
317 case OBJECT_LIGHTHOUSE
:
318 if (!IsTileFlat(tile
)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
321 case OBJECT_OWNED_LAND
:
322 if (IsTileType(tile
, MP_OBJECT
) &&
323 IsTileOwner(tile
, _current_company
) &&
324 IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
325 return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT
);
330 Company
*c
= Company::Get(_current_company
);
331 if (c
->location_of_HQ
!= INVALID_TILE
) {
332 /* Don't relocate HQ on the same location. */
333 if (c
->location_of_HQ
== tile
) return_cmd_error(STR_ERROR_ALREADY_BUILT
);
334 /* We need to persuade a bit harder to remove the old HQ. */
335 _current_company
= OWNER_WATER
;
336 cost
.AddCost(ClearTile_Object(c
->location_of_HQ
, flags
));
337 _current_company
= c
->index
;
340 if (flags
& DC_EXEC
) {
341 hq_score
= UpdateCompanyRatingAndValue(c
, false);
342 c
->location_of_HQ
= tile
;
343 SetWindowDirty(WC_COMPANY
, c
->index
);
349 /* This may never be constructed using this method. */
352 default: // i.e. NewGRF provided.
353 build_object_size
= size_x
* size_y
;
357 /* Don't allow building more objects if the company has reached its limit. */
358 Company
*c
= Company::GetIfValid(_current_company
);
359 if (c
!= nullptr && GB(c
->build_object_limit
, 16, 16) < build_object_size
) {
360 return_cmd_error(STR_ERROR_BUILD_OBJECT_LIMIT_REACHED
);
363 if (flags
& DC_EXEC
) {
364 BuildObject(type
, tile
, _current_company
== OWNER_DEITY
? OWNER_NONE
: _current_company
, nullptr, view
);
366 /* Make sure the HQ starts at the right size. */
367 if (type
== OBJECT_HQ
) UpdateCompanyHQ(tile
, hq_score
);
369 /* Subtract the tile from the build limit. */
370 if (c
!= nullptr) c
->build_object_limit
-= build_object_size
<< 16;
373 cost
.AddCost(spec
->GetBuildCost() * build_object_size
);
378 * Construct multiple objects in an area
379 * @param flags of operation to conduct
380 * @param tile end tile of area dragging
381 * @param start_tile start tile of area dragging
382 * @param type the object type to build
383 * @param view the view for the object
384 * @param diagonal Whether to use the Orthogonal (0) or Diagonal (1) iterator.
385 * @return the cost of this operation or an error
387 CommandCost
CmdBuildObjectArea(DoCommandFlag flags
, TileIndex tile
, TileIndex start_tile
, ObjectType type
, uint8 view
, bool diagonal
)
389 if (start_tile
>= MapSize()) return CMD_ERROR
;
391 if (type
>= NUM_OBJECTS
) return CMD_ERROR
;
392 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
393 if (view
>= spec
->views
) return CMD_ERROR
;
395 if (spec
->size
!= OBJECT_SIZE_1X1
) return CMD_ERROR
;
397 Money money
= GetAvailableMoneyForCommand();
398 CommandCost
cost(EXPENSES_CONSTRUCTION
);
399 CommandCost last_error
= CMD_ERROR
;
400 bool had_success
= false;
402 const Company
*c
= Company::GetIfValid(_current_company
);
403 int limit
= (c
== nullptr ? INT32_MAX
: GB(c
->build_object_limit
, 16, 16));
405 TileIterator
*iter
= diagonal
? (TileIterator
*)new DiagonalTileIterator(tile
, start_tile
) : new OrthogonalTileIterator(tile
, start_tile
);
406 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
408 CommandCost ret
= Command
<CMD_BUILD_OBJECT
>::Do(flags
& ~DC_EXEC
, t
, type
, view
);
410 /* If we've reached the limit, stop building (or testing). */
411 if (c
!= nullptr && limit
-- <= 0) break;
419 if (flags
& DC_EXEC
) {
420 money
-= ret
.GetCost();
422 /* If we run out of money, stop building. */
423 if (ret
.GetCost() > 0 && money
< 0) break;
424 Command
<CMD_BUILD_OBJECT
>::Do(flags
, t
, type
, view
);
430 return had_success
? cost
: last_error
;
433 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
);
435 static void DrawTile_Object(TileInfo
*ti
)
437 ObjectType type
= GetObjectType(ti
->tile
);
438 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
440 /* Fall back for when the object doesn't exist anymore. */
441 if (!spec
->enabled
) type
= OBJECT_TRANSMITTER
;
443 if ((spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) == 0) DrawFoundation(ti
, GetFoundation_Object(ti
->tile
, ti
->tileh
));
445 if (type
< NEW_OBJECT_OFFSET
) {
446 const DrawTileSprites
*dts
= nullptr;
447 Owner to
= GetTileOwner(ti
->tile
);
448 PaletteID palette
= to
== OWNER_NONE
? PAL_NONE
: COMPANY_SPRITE_COLOUR(to
);
450 if (type
== OBJECT_HQ
) {
451 TileIndex diff
= ti
->tile
- Object::GetByTile(ti
->tile
)->location
.tile
;
452 dts
= &_object_hq
[GetCompanyHQSize(ti
->tile
) << 2 | TileY(diff
) << 1 | TileX(diff
)];
454 dts
= &_objects
[type
];
457 if (spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) {
458 /* If an object has no foundation, but tries to draw a (flat) ground
459 * type... we have to be nice and convert that for them. */
460 switch (dts
->ground
.sprite
) {
461 case SPR_FLAT_BARE_LAND
: DrawClearLandTile(ti
, 0); break;
462 case SPR_FLAT_1_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 1); break;
463 case SPR_FLAT_2_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 2); break;
464 case SPR_FLAT_GRASS_TILE
: DrawClearLandTile(ti
, 3); break;
465 default: DrawGroundSprite(dts
->ground
.sprite
, palette
); break;
468 DrawGroundSprite(dts
->ground
.sprite
, palette
);
471 if (!IsInvisibilitySet(TO_STRUCTURES
)) {
472 const DrawTileSeqStruct
*dtss
;
473 foreach_draw_tile_seq(dtss
, dts
->seq
) {
474 AddSortableSpriteToDraw(
475 dtss
->image
.sprite
, palette
,
476 ti
->x
+ dtss
->delta_x
, ti
->y
+ dtss
->delta_y
,
477 dtss
->size_x
, dtss
->size_y
,
478 dtss
->size_z
, ti
->z
+ dtss
->delta_z
,
479 IsTransparencySet(TO_STRUCTURES
)
484 DrawNewObjectTile(ti
, spec
);
487 DrawBridgeMiddle(ti
);
490 static int GetSlopePixelZ_Object(TileIndex tile
, uint x
, uint y
)
492 if (IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
494 Slope tileh
= GetTilePixelSlope(tile
, &z
);
496 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
498 return GetTileMaxPixelZ(tile
);
502 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
)
504 return IsObjectType(tile
, OBJECT_OWNED_LAND
) ? FOUNDATION_NONE
: FlatteningFoundation(tileh
);
508 * Perform the actual removal of the object from the map.
509 * @param o The object to really clear.
511 static void ReallyClearObjectTile(Object
*o
)
513 Object::DecTypeCount(o
->type
);
514 for (TileIndex tile_cur
: o
->location
) {
515 DeleteNewGRFInspectWindow(GSF_OBJECTS
, tile_cur
);
517 MakeWaterKeepingClass(tile_cur
, GetTileOwner(tile_cur
));
522 std::vector
<ClearedObjectArea
> _cleared_object_areas
;
525 * Find the entry in _cleared_object_areas which occupies a certain tile.
526 * @param tile Tile of interest
527 * @return Occupying entry, or nullptr if none
529 ClearedObjectArea
*FindClearedObject(TileIndex tile
)
531 TileArea ta
= TileArea(tile
, 1, 1);
533 for (ClearedObjectArea
&coa
: _cleared_object_areas
) {
534 if (coa
.area
.Intersects(ta
)) return &coa
;
540 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
)
542 /* Get to the northern most tile. */
543 Object
*o
= Object::GetByTile(tile
);
544 TileArea ta
= o
->location
;
546 ObjectType type
= o
->type
;
547 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
549 CommandCost
cost(EXPENSES_CONSTRUCTION
, spec
->GetClearCost() * ta
.w
* ta
.h
/ 5);
550 if (spec
->flags
& OBJECT_FLAG_CLEAR_INCOME
) cost
.MultiplyCost(-1); // They get an income!
552 /* Towns can't remove any objects. */
553 if (_current_company
== OWNER_TOWN
) return CMD_ERROR
;
555 /* Water can remove everything! */
556 if (_current_company
!= OWNER_WATER
) {
557 if ((flags
& DC_NO_WATER
) && IsTileOnWater(tile
)) {
558 /* There is water under the object, treat it as water tile. */
559 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
560 } else if (!(spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) && (flags
& DC_AUTO
)) {
561 /* No automatic removal by overbuilding stuff. */
562 return_cmd_error(type
== OBJECT_HQ
? STR_ERROR_COMPANY_HEADQUARTERS_IN
: STR_ERROR_OBJECT_IN_THE_WAY
);
563 } else if (_game_mode
== GM_EDITOR
) {
564 /* No further limitations for the editor. */
565 } else if (GetTileOwner(tile
) == OWNER_NONE
) {
566 /* Owned by nobody and unremovable, so we can only remove it with brute force! */
567 if (!_cheats
.magic_bulldozer
.value
&& (spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0) return CMD_ERROR
;
568 } else if (CheckTileOwnership(tile
).Failed()) {
569 /* We don't own it!. */
570 return_cmd_error(STR_ERROR_OWNED_BY
);
571 } else if ((spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0 && (spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) == 0) {
572 /* In the game editor or with cheats we can remove, otherwise we can't. */
573 if (!_cheats
.magic_bulldozer
.value
) {
574 if (type
== OBJECT_HQ
) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN
);
578 /* Removing with the cheat costs more in TTDPatch / the specs. */
579 cost
.MultiplyCost(25);
581 } else if ((spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0) {
582 /* Water can't remove objects that are buildable on water. */
588 Company
*c
= Company::Get(GetTileOwner(tile
));
589 if (flags
& DC_EXEC
) {
590 c
->location_of_HQ
= INVALID_TILE
; // reset HQ position
591 SetWindowDirty(WC_COMPANY
, c
->index
);
592 CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS
, c
->index
);
595 /* cost of relocating company is 1% of company value */
596 cost
= CommandCost(EXPENSES_CONSTRUCTION
, CalculateCompanyValue(c
) / 100);
601 if (flags
& DC_EXEC
) {
602 Town
*town
= o
->town
;
603 ClrBit(town
->statues
, GetTileOwner(tile
));
604 SetWindowDirty(WC_TOWN_AUTHORITY
, town
->index
);
612 _cleared_object_areas
.push_back({tile
, ta
});
614 if (flags
& DC_EXEC
) ReallyClearObjectTile(o
);
619 static void AddAcceptedCargo_Object(TileIndex tile
, CargoArray
&acceptance
, CargoTypes
*always_accepted
)
621 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
623 /* HQ accepts passenger and mail; but we have to divide the values
624 * between 4 tiles it occupies! */
626 /* HQ level (depends on company performance) in the range 1..5. */
627 uint level
= GetCompanyHQSize(tile
) + 1;
629 /* Top town building generates 10, so to make HQ interesting, the top
631 acceptance
[CT_PASSENGERS
] += std::max(1U, level
);
632 SetBit(*always_accepted
, CT_PASSENGERS
);
634 /* Top town building generates 4, HQ can make up to 8. The
635 * proportion passengers:mail is different because such a huge
636 * commercial building generates unusually high amount of mail
637 * correspondence per physical visitor. */
638 acceptance
[CT_MAIL
] += std::max(1U, level
/ 2);
639 SetBit(*always_accepted
, CT_MAIL
);
642 static void AddProducedCargo_Object(TileIndex tile
, CargoArray
&produced
)
644 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
646 produced
[CT_PASSENGERS
]++;
651 static void GetTileDesc_Object(TileIndex tile
, TileDesc
*td
)
653 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
654 td
->str
= spec
->name
;
655 td
->owner
[0] = GetTileOwner(tile
);
656 td
->build_date
= Object::GetByTile(tile
)->build_date
;
658 if (spec
->grf_prop
.grffile
!= nullptr) {
659 td
->grf
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
)->GetName();
663 static void TileLoop_Object(TileIndex tile
)
665 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
666 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) {
667 Object
*o
= Object::GetByTile(tile
);
668 TriggerObjectTileAnimation(o
, tile
, OAT_TILELOOP
, spec
);
669 if (o
->location
.tile
== tile
) TriggerObjectAnimation(o
, OAT_256_TICKS
, spec
);
672 if (IsTileOnWater(tile
)) TileLoop_Water(tile
);
674 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
676 /* HQ accepts passenger and mail; but we have to divide the values
677 * between 4 tiles it occupies! */
679 /* HQ level (depends on company performance) in the range 1..5. */
680 uint level
= GetCompanyHQSize(tile
) + 1;
683 StationFinder
stations(TileArea(tile
, 2, 2));
686 /* Top town buildings generate 250, so the top HQ type makes 256. */
687 if (GB(r
, 0, 8) < (256 / 4 / (6 - level
))) {
688 uint amt
= GB(r
, 0, 8) / 8 / 4 + 1;
689 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
690 MoveGoodsToStation(CT_PASSENGERS
, amt
, ST_HEADQUARTERS
, GetTileOwner(tile
), stations
.GetStations());
693 /* Top town building generates 90, HQ can make up to 196. The
694 * proportion passengers:mail is about the same as in the acceptance
696 if (GB(r
, 8, 8) < (196 / 4 / (6 - level
))) {
697 uint amt
= GB(r
, 8, 8) / 8 / 4 + 1;
698 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
699 MoveGoodsToStation(CT_MAIL
, amt
, ST_HEADQUARTERS
, GetTileOwner(tile
), stations
.GetStations());
704 static TrackStatus
GetTileTrackStatus_Object(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
709 static bool ClickTile_Object(TileIndex tile
)
711 if (!IsObjectType(tile
, OBJECT_HQ
)) return false;
713 ShowCompany(GetTileOwner(tile
));
717 static void AnimateTile_Object(TileIndex tile
)
719 AnimateNewObjectTile(tile
);
723 * Helper function for \c CircularTileSearch.
724 * @param tile The tile to check.
725 * @param user Ignored.
726 * @return True iff the tile has a radio tower.
728 static bool HasTransmitter(TileIndex tile
, void *user
)
730 return IsObjectTypeTile(tile
, OBJECT_TRANSMITTER
);
734 * Try to build a lighthouse.
735 * @return True iff building a lighthouse succeeded.
737 static bool TryBuildLightHouse()
739 uint maxx
= MapMaxX();
740 uint maxy
= MapMaxY();
743 /* Scatter the lighthouses more evenly around the perimeter */
744 int perimeter
= (GB(r
, 16, 16) % (2 * (maxx
+ maxy
))) - maxy
;
746 for (dir
= DIAGDIR_NE
; perimeter
> 0; dir
++) {
747 perimeter
-= (DiagDirToAxis(dir
) == AXIS_X
) ? maxx
: maxy
;
753 case DIAGDIR_NE
: tile
= TileXY(maxx
- 1, r
% maxy
); break;
754 case DIAGDIR_SE
: tile
= TileXY(r
% maxx
, 1); break;
755 case DIAGDIR_SW
: tile
= TileXY(1, r
% maxy
); break;
756 case DIAGDIR_NW
: tile
= TileXY(r
% maxx
, maxy
- 1); break;
759 /* Only build lighthouses at tiles where the border is sea. */
760 if (!IsTileType(tile
, MP_WATER
)) return false;
762 for (int j
= 0; j
< 19; j
++) {
764 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
<= 2 && !IsBridgeAbove(tile
)) {
765 BuildObject(OBJECT_LIGHTHOUSE
, tile
);
766 assert(tile
< MapSize());
769 tile
+= TileOffsByDiagDir(dir
);
770 if (!IsValidTile(tile
)) return false;
776 * Try to build a transmitter.
777 * @return True iff a transmitter was built.
779 static bool TryBuildTransmitter()
781 TileIndex tile
= RandomTile();
783 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
>= 4 && !IsBridgeAbove(tile
)) {
785 if (CircularTileSearch(&t
, 9, HasTransmitter
, nullptr)) return false;
787 BuildObject(OBJECT_TRANSMITTER
, tile
);
793 void GenerateObjects()
795 /* Set a guestimate on how much we progress */
796 SetGeneratingWorldProgress(GWP_OBJECT
, NUM_OBJECTS
);
798 /* Determine number of water tiles at map border needed for freeform_edges */
799 uint num_water_tiles
= 0;
800 if (_settings_game
.construction
.freeform_edges
) {
801 for (uint x
= 0; x
< MapMaxX(); x
++) {
802 if (IsTileType(TileXY(x
, 1), MP_WATER
)) num_water_tiles
++;
803 if (IsTileType(TileXY(x
, MapMaxY() - 1), MP_WATER
)) num_water_tiles
++;
805 for (uint y
= 1; y
< MapMaxY() - 1; y
++) {
806 if (IsTileType(TileXY(1, y
), MP_WATER
)) num_water_tiles
++;
807 if (IsTileType(TileXY(MapMaxX() - 1, y
), MP_WATER
)) num_water_tiles
++;
811 /* Iterate over all possible object types */
812 for (uint i
= 0; i
< NUM_OBJECTS
; i
++) {
813 const ObjectSpec
*spec
= ObjectSpec::Get(i
);
815 /* Continue, if the object was never available till now or shall not be placed */
816 if (!spec
->WasEverAvailable() || spec
->generate_amount
== 0) continue;
818 uint16 amount
= spec
->generate_amount
;
820 /* Scale by map size */
821 if ((spec
->flags
& OBJECT_FLAG_SCALE_BY_WATER
) && _settings_game
.construction
.freeform_edges
) {
822 /* Scale the amount of lighthouses with the amount of land at the borders.
823 * The -6 is because the top borders are MP_VOID (-2) and all corners
824 * are counted twice (-4). */
825 amount
= ScaleByMapSize1D(amount
* num_water_tiles
) / (2 * MapMaxY() + 2 * MapMaxX() - 6);
826 } else if (spec
->flags
& OBJECT_FLAG_SCALE_BY_WATER
) {
827 amount
= ScaleByMapSize1D(amount
);
829 amount
= ScaleByMapSize(amount
);
832 /* Now try to place the requested amount of this object */
833 for (uint j
= ScaleByMapSize(1000); j
!= 0 && amount
!= 0 && Object::CanAllocateItem(); j
--) {
835 case OBJECT_TRANSMITTER
:
836 if (TryBuildTransmitter()) amount
--;
839 case OBJECT_LIGHTHOUSE
:
840 if (TryBuildLightHouse()) amount
--;
844 uint8 view
= RandomRange(spec
->views
);
845 if (CmdBuildObject(DC_EXEC
| DC_AUTO
| DC_NO_TEST_TOWN_RATING
| DC_NO_MODIFY_TOWN_RATING
, RandomTile(), i
, view
).Succeeded()) amount
--;
849 IncreaseGeneratingWorldProgress(GWP_OBJECT
);
853 static void ChangeTileOwner_Object(TileIndex tile
, Owner old_owner
, Owner new_owner
)
855 if (!IsTileOwner(tile
, old_owner
)) return;
857 bool do_clear
= false;
859 ObjectType type
= GetObjectType(tile
);
860 if ((type
== OBJECT_OWNED_LAND
|| type
>= NEW_OBJECT_OFFSET
) && new_owner
!= INVALID_OWNER
) {
861 SetTileOwner(tile
, new_owner
);
862 } else if (type
== OBJECT_STATUE
) {
863 Town
*t
= Object::GetByTile(tile
)->town
;
864 ClrBit(t
->statues
, old_owner
);
865 if (new_owner
!= INVALID_OWNER
&& !HasBit(t
->statues
, new_owner
)) {
866 /* Transfer ownership to the new company */
867 SetBit(t
->statues
, new_owner
);
868 SetTileOwner(tile
, new_owner
);
873 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
879 ReallyClearObjectTile(Object::GetByTile(tile
));
880 /* When clearing objects, they may turn into canal, which may require transferring ownership. */
881 ChangeTileOwner(tile
, old_owner
, new_owner
);
885 static CommandCost
TerraformTile_Object(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
887 ObjectType type
= GetObjectType(tile
);
889 if (type
== OBJECT_OWNED_LAND
) {
890 /* Owned land remains unsold */
891 CommandCost ret
= CheckTileOwnership(tile
);
892 if (ret
.Succeeded()) return CommandCost();
893 } else if (AutoslopeEnabled() && type
!= OBJECT_TRANSMITTER
&& type
!= OBJECT_LIGHTHOUSE
) {
895 * - Both new and old slope must not be steep.
896 * - TileMaxZ must not be changed.
897 * - Allow autoslope by default.
898 * - Disallow autoslope if callback succeeds and returns non-zero.
900 Slope tileh_old
= GetTileSlope(tile
);
901 /* TileMaxZ must not be changed. Slopes must not be steep. */
902 if (!IsSteepSlope(tileh_old
) && !IsSteepSlope(tileh_new
) && (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
903 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
905 /* Call callback 'disable autosloping for objects'. */
906 if (HasBit(spec
->callback_mask
, CBM_OBJ_AUTOSLOPE
)) {
907 /* If the callback fails, allow autoslope. */
908 uint16 res
= GetObjectCallback(CBID_OBJECT_AUTOSLOPE
, 0, 0, spec
, Object::GetByTile(tile
), tile
);
909 if (res
== CALLBACK_FAILED
|| !ConvertBooleanCallback(spec
->grf_prop
.grffile
, CBID_OBJECT_AUTOSLOPE
, res
)) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
910 } else if (spec
->enabled
) {
911 /* allow autoslope */
912 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
917 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
920 extern const TileTypeProcs _tile_type_object_procs
= {
921 DrawTile_Object
, // draw_tile_proc
922 GetSlopePixelZ_Object
, // get_slope_z_proc
923 ClearTile_Object
, // clear_tile_proc
924 AddAcceptedCargo_Object
, // add_accepted_cargo_proc
925 GetTileDesc_Object
, // get_tile_desc_proc
926 GetTileTrackStatus_Object
, // get_tile_track_status_proc
927 ClickTile_Object
, // click_tile_proc
928 AnimateTile_Object
, // animate_tile_proc
929 TileLoop_Object
, // tile_loop_proc
930 ChangeTileOwner_Object
, // change_tile_owner_proc
931 AddProducedCargo_Object
, // add_produced_cargo_proc
932 nullptr, // vehicle_enter_tile_proc
933 GetFoundation_Object
, // get_foundation_proc
934 TerraformTile_Object
, // terraform_tile_proc