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"
36 #include "table/strings.h"
37 #include "table/object_land.h"
39 #include "safeguards.h"
41 ObjectPool
_object_pool("Object");
42 INSTANTIATE_POOL_METHODS(Object
)
43 uint16
Object::counts
[NUM_OBJECTS
];
46 * Get the object associated with a tile.
47 * @param tile The tile to fetch the object for.
50 /* static */ Object
*Object::GetByTile(TileIndex tile
)
52 return Object::Get(GetObjectIndex(tile
));
56 * Gets the ObjectType of the given object tile
57 * @param t the tile to get the type from.
58 * @pre IsTileType(t, MP_OBJECT)
61 ObjectType
GetObjectType(TileIndex t
)
63 assert(IsTileType(t
, MP_OBJECT
));
64 return Object::GetByTile(t
)->type
;
67 /** Initialize/reset the objects. */
68 void InitializeObjects()
70 Object::ResetTypeCounts();
74 * Actually build the object.
75 * @param type The type of object to build.
76 * @param tile The tile to build the northern tile of the object on.
77 * @param owner The owner of the object.
78 * @param town Town the tile is related with.
79 * @param view The view for the object.
80 * @pre All preconditions for building the object at that location
81 * are met, e.g. slope and clearness of tiles are checked.
83 void BuildObject(ObjectType type
, TileIndex tile
, CompanyID owner
, Town
*town
, uint8 view
)
85 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
87 TileArea
ta(tile
, GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4), GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4));
88 Object
*o
= new Object();
91 o
->town
= town
== nullptr ? CalcClosestTownFromTile(tile
) : town
;
92 o
->build_date
= _date
;
95 /* If nothing owns the object, the colour will be random. Otherwise
96 * get the colour from the company's livery settings. */
97 if (owner
== OWNER_NONE
) {
100 const Livery
*l
= Company::Get(owner
)->livery
;
101 o
->colour
= l
->colour1
+ l
->colour2
* 16;
104 /* If the object wants only one colour, then give it that colour. */
105 if ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) == 0) o
->colour
&= 0xF;
107 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) {
108 uint16 res
= GetObjectCallback(CBID_OBJECT_COLOUR
, o
->colour
, 0, spec
, o
, tile
);
109 if (res
!= CALLBACK_FAILED
) {
110 if (res
>= 0x100) ErrorUnknownCallbackResult(spec
->grf_prop
.grffile
->grfid
, CBID_OBJECT_COLOUR
, res
);
111 o
->colour
= GB(res
, 0, 8);
115 assert(o
->town
!= nullptr);
117 for (TileIndex t
: ta
) {
118 WaterClass wc
= (IsWaterTile(t
) ? GetWaterClass(t
) : WATER_CLASS_INVALID
);
119 /* Update company infrastructure counts for objects build on canals owned by nobody. */
120 if (wc
== WATER_CLASS_CANAL
&& owner
!= OWNER_NONE
&& (IsTileOwner(tile
, OWNER_NONE
) || IsTileOwner(tile
, OWNER_WATER
))) {
121 Company::Get(owner
)->infrastructure
.water
++;
122 DirtyCompanyInfrastructureWindows(owner
);
124 MakeObject(t
, owner
, o
->index
, wc
, Random());
125 MarkTileDirtyByTile(t
);
128 Object::IncTypeCount(type
);
129 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) TriggerObjectAnimation(o
, OAT_BUILT
, spec
);
133 * Increase the animation stage of a whole structure.
134 * @param tile The tile of the structure.
136 static void IncreaseAnimationStage(TileIndex tile
)
138 TileArea ta
= Object::GetByTile(tile
)->location
;
139 for (TileIndex t
: ta
) {
140 SetAnimationFrame(t
, GetAnimationFrame(t
) + 1);
141 MarkTileDirtyByTile(t
);
145 /** We encode the company HQ size in the animation stage. */
146 #define GetCompanyHQSize GetAnimationFrame
147 /** We encode the company HQ size in the animation stage. */
148 #define IncreaseCompanyHQSize IncreaseAnimationStage
151 * Update the CompanyHQ to the state associated with the given score
152 * @param tile The (northern) tile of the company HQ, or INVALID_TILE.
153 * @param score The current (performance) score of the company.
155 void UpdateCompanyHQ(TileIndex tile
, uint score
)
157 if (tile
== INVALID_TILE
) return;
160 if (score
>= 170) val
++;
161 if (score
>= 350) val
++;
162 if (score
>= 520) val
++;
163 if (score
>= 720) val
++;
165 while (GetCompanyHQSize(tile
) < val
) {
166 IncreaseCompanyHQSize(tile
);
171 * Updates the colour of the object whenever a company changes.
172 * @param c The company the company colour changed of.
174 void UpdateObjectColours(const Company
*c
)
176 for (Object
*obj
: Object::Iterate()) {
177 Owner owner
= GetTileOwner(obj
->location
.tile
);
178 /* Not the current owner, so colour doesn't change. */
179 if (owner
!= c
->index
) continue;
181 const ObjectSpec
*spec
= ObjectSpec::GetByTile(obj
->location
.tile
);
182 /* Using the object colour callback, so not using company colour. */
183 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) continue;
185 const Livery
*l
= c
->livery
;
186 obj
->colour
= ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) ? (l
->colour2
* 16) : 0) + l
->colour1
;
190 extern CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
);
191 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
);
194 * Build an object object
195 * @param tile tile where the object will be located
196 * @param flags type of operation
197 * @param p1 the object type to build
198 * @param p2 the view for the object
200 * @return the cost of this operation or an error
202 CommandCost
CmdBuildObject(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
204 CommandCost
cost(EXPENSES_PROPERTY
);
206 ObjectType type
= (ObjectType
)GB(p1
, 0, 16);
207 if (type
>= NUM_OBJECTS
) return CMD_ERROR
;
208 uint8 view
= GB(p2
, 0, 2);
209 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
210 if (_game_mode
== GM_NORMAL
&& !spec
->IsAvailable() && !_generating_world
) return CMD_ERROR
;
211 if ((_game_mode
== GM_EDITOR
|| _generating_world
) && !spec
->WasEverAvailable()) return CMD_ERROR
;
213 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_SCENEDIT
) != 0 && ((!_generating_world
&& _game_mode
!= GM_EDITOR
) || _current_company
!= OWNER_NONE
)) return CMD_ERROR
;
214 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_GAME
) != 0 && (_generating_world
|| _game_mode
!= GM_NORMAL
|| _current_company
> MAX_COMPANIES
)) return CMD_ERROR
;
215 if (view
>= spec
->views
) return CMD_ERROR
;
217 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS
);
218 if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST
);
220 int size_x
= GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4);
221 int size_y
= GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4);
222 TileArea
ta(tile
, size_x
, size_y
);
223 for (TileIndex t
: ta
) {
224 if (!IsValidTile(t
)) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
); // Might be off the map
227 if (type
== OBJECT_OWNED_LAND
) {
228 /* Owned land is special as it can be placed on any slope. */
229 cost
.AddCost(DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
));
231 /* Check the surface to build on. At this time we can't actually execute the
232 * the CLEAR_TILE commands since the newgrf callback later on can check
233 * some information about the tiles. */
234 bool allow_water
= (spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0;
235 bool allow_ground
= (spec
->flags
& OBJECT_FLAG_NOT_ON_LAND
) == 0;
236 for (TileIndex t
: ta
) {
237 if (HasTileWaterGround(t
)) {
238 if (!allow_water
) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
239 if (!IsWaterTile(t
)) {
240 /* Normal water tiles don't have to be cleared. For all other tile types clear
241 * the tile but leave the water. */
242 cost
.AddCost(DoCommand(t
, 0, 0, flags
& ~DC_NO_WATER
& ~DC_EXEC
, CMD_LANDSCAPE_CLEAR
));
244 /* Can't build on water owned by another company. */
245 Owner o
= GetTileOwner(t
);
246 if (o
!= OWNER_NONE
&& o
!= OWNER_WATER
) cost
.AddCost(CheckOwnership(o
, t
));
248 /* However, the tile has to be clear of vehicles. */
249 cost
.AddCost(EnsureNoVehicleOnGround(t
));
252 if (!allow_ground
) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER
);
253 /* For non-water tiles, we'll have to clear it before building. */
255 /* When relocating HQ, allow it to be relocated (partial) on itself. */
256 if (!(type
== OBJECT_HQ
&&
257 IsTileType(t
, MP_OBJECT
) &&
258 IsTileOwner(t
, _current_company
) &&
259 IsObjectType(t
, OBJECT_HQ
))) {
260 cost
.AddCost(DoCommand(t
, 0, 0, flags
& ~DC_EXEC
, CMD_LANDSCAPE_CLEAR
));
265 /* So, now the surface is checked... check the slope of said surface. */
267 if (GetTileSlope(tile
, &allowed_z
) != SLOPE_FLAT
) allowed_z
++;
269 for (TileIndex t
: ta
) {
270 uint16 callback
= CALLBACK_FAILED
;
271 if (HasBit(spec
->callback_mask
, CBM_OBJ_SLOPE_CHECK
)) {
272 TileIndex diff
= t
- tile
;
273 callback
= GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK
, GetTileSlope(t
), TileY(diff
) << 4 | TileX(diff
), spec
, nullptr, t
, view
);
276 if (callback
== CALLBACK_FAILED
) {
277 cost
.AddCost(CheckBuildableTile(t
, 0, allowed_z
, false, false));
279 /* The meaning of bit 10 is inverted for a grf version < 8. */
280 if (spec
->grf_prop
.grffile
->grf_version
< 8) ToggleBit(callback
, 10);
281 CommandCost ret
= GetErrorMessageFromLocationCallbackResult(callback
, spec
->grf_prop
.grffile
, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
282 if (ret
.Failed()) return ret
;
286 if (flags
& DC_EXEC
) {
287 /* This is basically a copy of the loop above with the exception that we now
288 * execute the commands and don't check for errors, since that's already done. */
289 for (TileIndex t
: ta
) {
290 if (HasTileWaterGround(t
)) {
291 if (!IsWaterTile(t
)) {
292 DoCommand(t
, 0, 0, (flags
& ~DC_NO_WATER
) | DC_NO_MODIFY_TOWN_RATING
, CMD_LANDSCAPE_CLEAR
);
295 DoCommand(t
, 0, 0, flags
| DC_NO_MODIFY_TOWN_RATING
, CMD_LANDSCAPE_CLEAR
);
300 if (cost
.Failed()) return cost
;
302 /* Finally do a check for bridges. */
303 for (TileIndex t
: ta
) {
304 if (IsBridgeAbove(t
) && (
305 !(spec
->flags
& OBJECT_FLAG_ALLOW_UNDER_BRIDGE
) ||
306 (GetTileMaxZ(t
) + spec
->height
>= GetBridgeHeight(GetSouthernBridgeEnd(t
))))) {
307 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
313 case OBJECT_TRANSMITTER
:
314 case OBJECT_LIGHTHOUSE
:
315 if (!IsTileFlat(tile
)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
318 case OBJECT_OWNED_LAND
:
319 if (IsTileType(tile
, MP_OBJECT
) &&
320 IsTileOwner(tile
, _current_company
) &&
321 IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
322 return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT
);
327 Company
*c
= Company::Get(_current_company
);
328 if (c
->location_of_HQ
!= INVALID_TILE
) {
329 /* We need to persuade a bit harder to remove the old HQ. */
330 _current_company
= OWNER_WATER
;
331 cost
.AddCost(ClearTile_Object(c
->location_of_HQ
, flags
));
332 _current_company
= c
->index
;
335 if (flags
& DC_EXEC
) {
336 hq_score
= UpdateCompanyRatingAndValue(c
, false);
337 c
->location_of_HQ
= tile
;
338 SetWindowDirty(WC_COMPANY
, c
->index
);
344 /* This may never be constructed using this method. */
347 default: // i.e. NewGRF provided.
351 if (flags
& DC_EXEC
) {
352 BuildObject(type
, tile
, _current_company
, nullptr, view
);
354 /* Make sure the HQ starts at the right size. */
355 if (type
== OBJECT_HQ
) UpdateCompanyHQ(tile
, hq_score
);
358 cost
.AddCost(ObjectSpec::Get(type
)->GetBuildCost() * size_x
* size_y
);
363 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
);
365 static void DrawTile_Object(TileInfo
*ti
)
367 ObjectType type
= GetObjectType(ti
->tile
);
368 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
370 /* Fall back for when the object doesn't exist anymore. */
371 if (!spec
->enabled
) type
= OBJECT_TRANSMITTER
;
373 if ((spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) == 0) DrawFoundation(ti
, GetFoundation_Object(ti
->tile
, ti
->tileh
));
375 if (type
< NEW_OBJECT_OFFSET
) {
376 const DrawTileSprites
*dts
= nullptr;
377 Owner to
= GetTileOwner(ti
->tile
);
378 PaletteID palette
= to
== OWNER_NONE
? PAL_NONE
: COMPANY_SPRITE_COLOUR(to
);
380 if (type
== OBJECT_HQ
) {
381 TileIndex diff
= ti
->tile
- Object::GetByTile(ti
->tile
)->location
.tile
;
382 dts
= &_object_hq
[GetCompanyHQSize(ti
->tile
) << 2 | TileY(diff
) << 1 | TileX(diff
)];
384 dts
= &_objects
[type
];
387 if (spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) {
388 /* If an object has no foundation, but tries to draw a (flat) ground
389 * type... we have to be nice and convert that for them. */
390 switch (dts
->ground
.sprite
) {
391 case SPR_FLAT_BARE_LAND
: DrawClearLandTile(ti
, 0); break;
392 case SPR_FLAT_1_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 1); break;
393 case SPR_FLAT_2_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 2); break;
394 case SPR_FLAT_GRASS_TILE
: DrawClearLandTile(ti
, 3); break;
395 default: DrawGroundSprite(dts
->ground
.sprite
, palette
); break;
398 DrawGroundSprite(dts
->ground
.sprite
, palette
);
401 if (!IsInvisibilitySet(TO_STRUCTURES
)) {
402 const DrawTileSeqStruct
*dtss
;
403 foreach_draw_tile_seq(dtss
, dts
->seq
) {
404 AddSortableSpriteToDraw(
405 dtss
->image
.sprite
, palette
,
406 ti
->x
+ dtss
->delta_x
, ti
->y
+ dtss
->delta_y
,
407 dtss
->size_x
, dtss
->size_y
,
408 dtss
->size_z
, ti
->z
+ dtss
->delta_z
,
409 IsTransparencySet(TO_STRUCTURES
)
414 DrawNewObjectTile(ti
, spec
);
417 DrawBridgeMiddle(ti
);
420 static int GetSlopePixelZ_Object(TileIndex tile
, uint x
, uint y
)
422 if (IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
424 Slope tileh
= GetTilePixelSlope(tile
, &z
);
426 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
428 return GetTileMaxPixelZ(tile
);
432 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
)
434 return IsObjectType(tile
, OBJECT_OWNED_LAND
) ? FOUNDATION_NONE
: FlatteningFoundation(tileh
);
438 * Perform the actual removal of the object from the map.
439 * @param o The object to really clear.
441 static void ReallyClearObjectTile(Object
*o
)
443 Object::DecTypeCount(o
->type
);
444 for (TileIndex tile_cur
: o
->location
) {
445 DeleteNewGRFInspectWindow(GSF_OBJECTS
, tile_cur
);
447 MakeWaterKeepingClass(tile_cur
, GetTileOwner(tile_cur
));
452 std::vector
<ClearedObjectArea
> _cleared_object_areas
;
455 * Find the entry in _cleared_object_areas which occupies a certain tile.
456 * @param tile Tile of interest
457 * @return Occupying entry, or nullptr if none
459 ClearedObjectArea
*FindClearedObject(TileIndex tile
)
461 TileArea ta
= TileArea(tile
, 1, 1);
463 for (ClearedObjectArea
&coa
: _cleared_object_areas
) {
464 if (coa
.area
.Intersects(ta
)) return &coa
;
470 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
)
472 /* Get to the northern most tile. */
473 Object
*o
= Object::GetByTile(tile
);
474 TileArea ta
= o
->location
;
476 ObjectType type
= o
->type
;
477 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
479 CommandCost
cost(EXPENSES_CONSTRUCTION
, spec
->GetClearCost() * ta
.w
* ta
.h
/ 5);
480 if (spec
->flags
& OBJECT_FLAG_CLEAR_INCOME
) cost
.MultiplyCost(-1); // They get an income!
482 /* Towns can't remove any objects. */
483 if (_current_company
== OWNER_TOWN
) return CMD_ERROR
;
485 /* Water can remove everything! */
486 if (_current_company
!= OWNER_WATER
) {
487 if ((flags
& DC_NO_WATER
) && IsTileOnWater(tile
)) {
488 /* There is water under the object, treat it as water tile. */
489 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
490 } else if (!(spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) && (flags
& DC_AUTO
)) {
491 /* No automatic removal by overbuilding stuff. */
492 return_cmd_error(type
== OBJECT_HQ
? STR_ERROR_COMPANY_HEADQUARTERS_IN
: STR_ERROR_OBJECT_IN_THE_WAY
);
493 } else if (_game_mode
== GM_EDITOR
) {
494 /* No further limitations for the editor. */
495 } else if (GetTileOwner(tile
) == OWNER_NONE
) {
496 /* Owned by nobody and unremovable, so we can only remove it with brute force! */
497 if (!_cheats
.magic_bulldozer
.value
&& (spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0) return CMD_ERROR
;
498 } else if (CheckTileOwnership(tile
).Failed()) {
499 /* We don't own it!. */
500 return_cmd_error(STR_ERROR_OWNED_BY
);
501 } else if ((spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0 && (spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) == 0) {
502 /* In the game editor or with cheats we can remove, otherwise we can't. */
503 if (!_cheats
.magic_bulldozer
.value
) {
504 if (type
== OBJECT_HQ
) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN
);
508 /* Removing with the cheat costs more in TTDPatch / the specs. */
509 cost
.MultiplyCost(25);
511 } else if ((spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0) {
512 /* Water can't remove objects that are buildable on water. */
518 Company
*c
= Company::Get(GetTileOwner(tile
));
519 if (flags
& DC_EXEC
) {
520 c
->location_of_HQ
= INVALID_TILE
; // reset HQ position
521 SetWindowDirty(WC_COMPANY
, c
->index
);
522 CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS
, c
->index
);
525 /* cost of relocating company is 1% of company value */
526 cost
= CommandCost(EXPENSES_PROPERTY
, CalculateCompanyValue(c
) / 100);
531 if (flags
& DC_EXEC
) {
532 Town
*town
= o
->town
;
533 ClrBit(town
->statues
, GetTileOwner(tile
));
534 SetWindowDirty(WC_TOWN_AUTHORITY
, town
->index
);
542 _cleared_object_areas
.push_back({tile
, ta
});
544 if (flags
& DC_EXEC
) ReallyClearObjectTile(o
);
549 static void AddAcceptedCargo_Object(TileIndex tile
, CargoArray
&acceptance
, CargoTypes
*always_accepted
)
551 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
553 /* HQ accepts passenger and mail; but we have to divide the values
554 * between 4 tiles it occupies! */
556 /* HQ level (depends on company performance) in the range 1..5. */
557 uint level
= GetCompanyHQSize(tile
) + 1;
559 /* Top town building generates 10, so to make HQ interesting, the top
561 acceptance
[CT_PASSENGERS
] += std::max(1U, level
);
562 SetBit(*always_accepted
, CT_PASSENGERS
);
564 /* Top town building generates 4, HQ can make up to 8. The
565 * proportion passengers:mail is different because such a huge
566 * commercial building generates unusually high amount of mail
567 * correspondence per physical visitor. */
568 acceptance
[CT_MAIL
] += std::max(1U, level
/ 2);
569 SetBit(*always_accepted
, CT_MAIL
);
572 static void AddProducedCargo_Object(TileIndex tile
, CargoArray
&produced
)
574 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
576 produced
[CT_PASSENGERS
]++;
581 static void GetTileDesc_Object(TileIndex tile
, TileDesc
*td
)
583 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
584 td
->str
= spec
->name
;
585 td
->owner
[0] = GetTileOwner(tile
);
586 td
->build_date
= Object::GetByTile(tile
)->build_date
;
588 if (spec
->grf_prop
.grffile
!= nullptr) {
589 td
->grf
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
)->GetName();
593 static void TileLoop_Object(TileIndex tile
)
595 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
596 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) {
597 Object
*o
= Object::GetByTile(tile
);
598 TriggerObjectTileAnimation(o
, tile
, OAT_TILELOOP
, spec
);
599 if (o
->location
.tile
== tile
) TriggerObjectAnimation(o
, OAT_256_TICKS
, spec
);
602 if (IsTileOnWater(tile
)) TileLoop_Water(tile
);
604 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
606 /* HQ accepts passenger and mail; but we have to divide the values
607 * between 4 tiles it occupies! */
609 /* HQ level (depends on company performance) in the range 1..5. */
610 uint level
= GetCompanyHQSize(tile
) + 1;
613 StationFinder
stations(TileArea(tile
, 2, 2));
616 /* Top town buildings generate 250, so the top HQ type makes 256. */
617 if (GB(r
, 0, 8) < (256 / 4 / (6 - level
))) {
618 uint amt
= GB(r
, 0, 8) / 8 / 4 + 1;
619 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
620 MoveGoodsToStation(CT_PASSENGERS
, amt
, ST_HEADQUARTERS
, GetTileOwner(tile
), stations
.GetStations());
623 /* Top town building generates 90, HQ can make up to 196. The
624 * proportion passengers:mail is about the same as in the acceptance
626 if (GB(r
, 8, 8) < (196 / 4 / (6 - level
))) {
627 uint amt
= GB(r
, 8, 8) / 8 / 4 + 1;
628 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
629 MoveGoodsToStation(CT_MAIL
, amt
, ST_HEADQUARTERS
, GetTileOwner(tile
), stations
.GetStations());
634 static TrackStatus
GetTileTrackStatus_Object(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
639 static bool ClickTile_Object(TileIndex tile
)
641 if (!IsObjectType(tile
, OBJECT_HQ
)) return false;
643 ShowCompany(GetTileOwner(tile
));
647 static void AnimateTile_Object(TileIndex tile
)
649 AnimateNewObjectTile(tile
);
653 * Helper function for \c CircularTileSearch.
654 * @param tile The tile to check.
655 * @param user Ignored.
656 * @return True iff the tile has a radio tower.
658 static bool HasTransmitter(TileIndex tile
, void *user
)
660 return IsObjectTypeTile(tile
, OBJECT_TRANSMITTER
);
664 * Try to build a lighthouse.
665 * @return True iff building a lighthouse succeeded.
667 static bool TryBuildLightHouse()
669 uint maxx
= MapMaxX();
670 uint maxy
= MapMaxY();
673 /* Scatter the lighthouses more evenly around the perimeter */
674 int perimeter
= (GB(r
, 16, 16) % (2 * (maxx
+ maxy
))) - maxy
;
676 for (dir
= DIAGDIR_NE
; perimeter
> 0; dir
++) {
677 perimeter
-= (DiagDirToAxis(dir
) == AXIS_X
) ? maxx
: maxy
;
683 case DIAGDIR_NE
: tile
= TileXY(maxx
- 1, r
% maxy
); break;
684 case DIAGDIR_SE
: tile
= TileXY(r
% maxx
, 1); break;
685 case DIAGDIR_SW
: tile
= TileXY(1, r
% maxy
); break;
686 case DIAGDIR_NW
: tile
= TileXY(r
% maxx
, maxy
- 1); break;
689 /* Only build lighthouses at tiles where the border is sea. */
690 if (!IsTileType(tile
, MP_WATER
)) return false;
692 for (int j
= 0; j
< 19; j
++) {
694 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
<= 2 && !IsBridgeAbove(tile
)) {
695 BuildObject(OBJECT_LIGHTHOUSE
, tile
);
696 assert(tile
< MapSize());
699 tile
+= TileOffsByDiagDir(dir
);
700 if (!IsValidTile(tile
)) return false;
706 * Try to build a transmitter.
707 * @return True iff a transmitter was built.
709 static bool TryBuildTransmitter()
711 TileIndex tile
= RandomTile();
713 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
>= 4 && !IsBridgeAbove(tile
)) {
715 if (CircularTileSearch(&t
, 9, HasTransmitter
, nullptr)) return false;
717 BuildObject(OBJECT_TRANSMITTER
, tile
);
723 void GenerateObjects()
725 /* Set a guestimate on how much we progress */
726 SetGeneratingWorldProgress(GWP_OBJECT
, NUM_OBJECTS
);
728 /* Determine number of water tiles at map border needed for freeform_edges */
729 uint num_water_tiles
= 0;
730 if (_settings_game
.construction
.freeform_edges
) {
731 for (uint x
= 0; x
< MapMaxX(); x
++) {
732 if (IsTileType(TileXY(x
, 1), MP_WATER
)) num_water_tiles
++;
733 if (IsTileType(TileXY(x
, MapMaxY() - 1), MP_WATER
)) num_water_tiles
++;
735 for (uint y
= 1; y
< MapMaxY() - 1; y
++) {
736 if (IsTileType(TileXY(1, y
), MP_WATER
)) num_water_tiles
++;
737 if (IsTileType(TileXY(MapMaxX() - 1, y
), MP_WATER
)) num_water_tiles
++;
741 /* Iterate over all possible object types */
742 for (uint i
= 0; i
< NUM_OBJECTS
; i
++) {
743 const ObjectSpec
*spec
= ObjectSpec::Get(i
);
745 /* Continue, if the object was never available till now or shall not be placed */
746 if (!spec
->WasEverAvailable() || spec
->generate_amount
== 0) continue;
748 uint16 amount
= spec
->generate_amount
;
750 /* Scale by map size */
751 if ((spec
->flags
& OBJECT_FLAG_SCALE_BY_WATER
) && _settings_game
.construction
.freeform_edges
) {
752 /* Scale the amount of lighthouses with the amount of land at the borders.
753 * The -6 is because the top borders are MP_VOID (-2) and all corners
754 * are counted twice (-4). */
755 amount
= ScaleByMapSize1D(amount
* num_water_tiles
) / (2 * MapMaxY() + 2 * MapMaxX() - 6);
756 } else if (spec
->flags
& OBJECT_FLAG_SCALE_BY_WATER
) {
757 amount
= ScaleByMapSize1D(amount
);
759 amount
= ScaleByMapSize(amount
);
762 /* Now try to place the requested amount of this object */
763 for (uint j
= ScaleByMapSize(1000); j
!= 0 && amount
!= 0 && Object::CanAllocateItem(); j
--) {
765 case OBJECT_TRANSMITTER
:
766 if (TryBuildTransmitter()) amount
--;
769 case OBJECT_LIGHTHOUSE
:
770 if (TryBuildLightHouse()) amount
--;
774 uint8 view
= RandomRange(spec
->views
);
775 if (CmdBuildObject(RandomTile(), DC_EXEC
| DC_AUTO
| DC_NO_TEST_TOWN_RATING
| DC_NO_MODIFY_TOWN_RATING
, i
, view
, {}).Succeeded()) amount
--;
779 IncreaseGeneratingWorldProgress(GWP_OBJECT
);
783 static void ChangeTileOwner_Object(TileIndex tile
, Owner old_owner
, Owner new_owner
)
785 if (!IsTileOwner(tile
, old_owner
)) return;
787 bool do_clear
= false;
789 ObjectType type
= GetObjectType(tile
);
790 if ((type
== OBJECT_OWNED_LAND
|| type
>= NEW_OBJECT_OFFSET
) && new_owner
!= INVALID_OWNER
) {
791 SetTileOwner(tile
, new_owner
);
792 } else if (type
== OBJECT_STATUE
) {
793 Town
*t
= Object::GetByTile(tile
)->town
;
794 ClrBit(t
->statues
, old_owner
);
795 if (new_owner
!= INVALID_OWNER
&& !HasBit(t
->statues
, new_owner
)) {
796 /* Transfer ownership to the new company */
797 SetBit(t
->statues
, new_owner
);
798 SetTileOwner(tile
, new_owner
);
803 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
809 ReallyClearObjectTile(Object::GetByTile(tile
));
810 /* When clearing objects, they may turn into canal, which may require transferring ownership. */
811 ChangeTileOwner(tile
, old_owner
, new_owner
);
815 static CommandCost
TerraformTile_Object(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
817 ObjectType type
= GetObjectType(tile
);
819 if (type
== OBJECT_OWNED_LAND
) {
820 /* Owned land remains unsold */
821 CommandCost ret
= CheckTileOwnership(tile
);
822 if (ret
.Succeeded()) return CommandCost();
823 } else if (AutoslopeEnabled() && type
!= OBJECT_TRANSMITTER
&& type
!= OBJECT_LIGHTHOUSE
) {
825 * - Both new and old slope must not be steep.
826 * - TileMaxZ must not be changed.
827 * - Allow autoslope by default.
828 * - Disallow autoslope if callback succeeds and returns non-zero.
830 Slope tileh_old
= GetTileSlope(tile
);
831 /* TileMaxZ must not be changed. Slopes must not be steep. */
832 if (!IsSteepSlope(tileh_old
) && !IsSteepSlope(tileh_new
) && (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
833 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
835 /* Call callback 'disable autosloping for objects'. */
836 if (HasBit(spec
->callback_mask
, CBM_OBJ_AUTOSLOPE
)) {
837 /* If the callback fails, allow autoslope. */
838 uint16 res
= GetObjectCallback(CBID_OBJECT_AUTOSLOPE
, 0, 0, spec
, Object::GetByTile(tile
), tile
);
839 if (res
== CALLBACK_FAILED
|| !ConvertBooleanCallback(spec
->grf_prop
.grffile
, CBID_OBJECT_AUTOSLOPE
, res
)) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
840 } else if (spec
->enabled
) {
841 /* allow autoslope */
842 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
847 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
850 extern const TileTypeProcs _tile_type_object_procs
= {
851 DrawTile_Object
, // draw_tile_proc
852 GetSlopePixelZ_Object
, // get_slope_z_proc
853 ClearTile_Object
, // clear_tile_proc
854 AddAcceptedCargo_Object
, // add_accepted_cargo_proc
855 GetTileDesc_Object
, // get_tile_desc_proc
856 GetTileTrackStatus_Object
, // get_tile_track_status_proc
857 ClickTile_Object
, // click_tile_proc
858 AnimateTile_Object
, // animate_tile_proc
859 TileLoop_Object
, // tile_loop_proc
860 ChangeTileOwner_Object
, // change_tile_owner_proc
861 AddProducedCargo_Object
, // add_produced_cargo_proc
862 nullptr, // vehicle_enter_tile_proc
863 GetFoundation_Object
, // get_foundation_proc
864 TerraformTile_Object
, // terraform_tile_proc