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"
37 #include "table/strings.h"
38 #include "table/object_land.h"
40 #include "safeguards.h"
42 ObjectPool
_object_pool("Object");
43 INSTANTIATE_POOL_METHODS(Object
)
44 uint16
Object::counts
[NUM_OBJECTS
];
47 * Get the object associated with a tile.
48 * @param tile The tile to fetch the object for.
51 /* static */ Object
*Object::GetByTile(TileIndex tile
)
53 return Object::Get(GetObjectIndex(tile
));
57 * Gets the ObjectType of the given object tile
58 * @param t the tile to get the type from.
59 * @pre IsTileType(t, MP_OBJECT)
62 ObjectType
GetObjectType(TileIndex t
)
64 assert(IsTileType(t
, MP_OBJECT
));
65 return Object::GetByTile(t
)->type
;
68 /** Initialize/reset the objects. */
69 void InitializeObjects()
71 Object::ResetTypeCounts();
75 * Actually build the object.
76 * @param type The type of object to build.
77 * @param tile The tile to build the northern tile of the object on.
78 * @param owner The owner of the object.
79 * @param town Town the tile is related with.
80 * @param view The view for the object.
81 * @pre All preconditions for building the object at that location
82 * are met, e.g. slope and clearness of tiles are checked.
84 void BuildObject(ObjectType type
, TileIndex tile
, CompanyID owner
, Town
*town
, uint8 view
)
86 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
88 TileArea
ta(tile
, GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4), GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4));
89 Object
*o
= new Object();
92 o
->town
= town
== nullptr ? CalcClosestTownFromTile(tile
) : town
;
93 o
->build_date
= _date
;
96 /* If nothing owns the object, the colour will be random. Otherwise
97 * get the colour from the company's livery settings. */
98 if (owner
== OWNER_NONE
) {
101 const Livery
*l
= Company::Get(owner
)->livery
;
102 o
->colour
= l
->colour1
+ l
->colour2
* 16;
105 /* If the object wants only one colour, then give it that colour. */
106 if ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) == 0) o
->colour
&= 0xF;
108 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) {
109 uint16 res
= GetObjectCallback(CBID_OBJECT_COLOUR
, o
->colour
, 0, spec
, o
, tile
);
110 if (res
!= CALLBACK_FAILED
) {
111 if (res
>= 0x100) ErrorUnknownCallbackResult(spec
->grf_prop
.grffile
->grfid
, CBID_OBJECT_COLOUR
, res
);
112 o
->colour
= GB(res
, 0, 8);
116 assert(o
->town
!= nullptr);
118 for (TileIndex t
: ta
) {
119 WaterClass wc
= (IsWaterTile(t
) ? GetWaterClass(t
) : WATER_CLASS_INVALID
);
120 /* Update company infrastructure counts for objects build on canals owned by nobody. */
121 if (wc
== WATER_CLASS_CANAL
&& owner
!= OWNER_NONE
&& (IsTileOwner(tile
, OWNER_NONE
) || IsTileOwner(tile
, OWNER_WATER
))) {
122 Company::Get(owner
)->infrastructure
.water
++;
123 DirtyCompanyInfrastructureWindows(owner
);
125 bool remove
= IsDockingTile(t
);
126 MakeObject(t
, owner
, o
->index
, wc
, Random());
127 if (remove
) RemoveDockingTile(t
);
128 MarkTileDirtyByTile(t
);
131 Object::IncTypeCount(type
);
132 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) TriggerObjectAnimation(o
, OAT_BUILT
, spec
);
136 * Increase the animation stage of a whole structure.
137 * @param tile The tile of the structure.
139 static void IncreaseAnimationStage(TileIndex tile
)
141 TileArea ta
= Object::GetByTile(tile
)->location
;
142 for (TileIndex t
: ta
) {
143 SetAnimationFrame(t
, GetAnimationFrame(t
) + 1);
144 MarkTileDirtyByTile(t
);
148 /** We encode the company HQ size in the animation stage. */
149 #define GetCompanyHQSize GetAnimationFrame
150 /** We encode the company HQ size in the animation stage. */
151 #define IncreaseCompanyHQSize IncreaseAnimationStage
154 * Update the CompanyHQ to the state associated with the given score
155 * @param tile The (northern) tile of the company HQ, or INVALID_TILE.
156 * @param score The current (performance) score of the company.
158 void UpdateCompanyHQ(TileIndex tile
, uint score
)
160 if (tile
== INVALID_TILE
) return;
163 if (score
>= 170) val
++;
164 if (score
>= 350) val
++;
165 if (score
>= 520) val
++;
166 if (score
>= 720) val
++;
168 while (GetCompanyHQSize(tile
) < val
) {
169 IncreaseCompanyHQSize(tile
);
174 * Updates the colour of the object whenever a company changes.
175 * @param c The company the company colour changed of.
177 void UpdateObjectColours(const Company
*c
)
179 for (Object
*obj
: Object::Iterate()) {
180 Owner owner
= GetTileOwner(obj
->location
.tile
);
181 /* Not the current owner, so colour doesn't change. */
182 if (owner
!= c
->index
) continue;
184 const ObjectSpec
*spec
= ObjectSpec::GetByTile(obj
->location
.tile
);
185 /* Using the object colour callback, so not using company colour. */
186 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) continue;
188 const Livery
*l
= c
->livery
;
189 obj
->colour
= ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) ? (l
->colour2
* 16) : 0) + l
->colour1
;
193 extern CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
);
194 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
);
197 * Build an object object
198 * @param tile tile where the object will be located
199 * @param flags type of operation
200 * @param p1 the object type to build
201 * @param p2 the view for the object
203 * @return the cost of this operation or an error
205 CommandCost
CmdBuildObject(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
207 CommandCost
cost(EXPENSES_CONSTRUCTION
);
209 ObjectType type
= (ObjectType
)GB(p1
, 0, 16);
210 if (type
>= NUM_OBJECTS
) return CMD_ERROR
;
211 uint8 view
= GB(p2
, 0, 2);
212 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
213 if (_game_mode
== GM_NORMAL
&& !spec
->IsAvailable() && !_generating_world
) return CMD_ERROR
;
214 if ((_game_mode
== GM_EDITOR
|| _generating_world
) && !spec
->WasEverAvailable()) return CMD_ERROR
;
216 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_SCENEDIT
) != 0 && ((!_generating_world
&& _game_mode
!= GM_EDITOR
) || _current_company
!= OWNER_NONE
)) return CMD_ERROR
;
217 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_GAME
) != 0 && (_generating_world
|| _game_mode
!= GM_NORMAL
|| _current_company
> MAX_COMPANIES
)) return CMD_ERROR
;
218 if (view
>= spec
->views
) return CMD_ERROR
;
220 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS
);
221 if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST
);
223 int size_x
= GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4);
224 int size_y
= GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4);
225 TileArea
ta(tile
, size_x
, size_y
);
226 for (TileIndex t
: ta
) {
227 if (!IsValidTile(t
)) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
); // Might be off the map
230 if (type
== OBJECT_OWNED_LAND
) {
231 /* Owned land is special as it can be placed on any slope. */
232 cost
.AddCost(DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
));
234 /* Check the surface to build on. At this time we can't actually execute the
235 * the CLEAR_TILE commands since the newgrf callback later on can check
236 * some information about the tiles. */
237 bool allow_water
= (spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0;
238 bool allow_ground
= (spec
->flags
& OBJECT_FLAG_NOT_ON_LAND
) == 0;
239 for (TileIndex t
: ta
) {
240 if (HasTileWaterGround(t
)) {
241 if (!allow_water
) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
242 if (!IsWaterTile(t
)) {
243 /* Normal water tiles don't have to be cleared. For all other tile types clear
244 * the tile but leave the water. */
245 cost
.AddCost(DoCommand(t
, 0, 0, flags
& ~DC_NO_WATER
& ~DC_EXEC
, CMD_LANDSCAPE_CLEAR
));
247 /* Can't build on water owned by another company. */
248 Owner o
= GetTileOwner(t
);
249 if (o
!= OWNER_NONE
&& o
!= OWNER_WATER
) cost
.AddCost(CheckOwnership(o
, t
));
251 /* However, the tile has to be clear of vehicles. */
252 cost
.AddCost(EnsureNoVehicleOnGround(t
));
255 if (!allow_ground
) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER
);
256 /* For non-water tiles, we'll have to clear it before building. */
258 /* When relocating HQ, allow it to be relocated (partial) on itself. */
259 if (!(type
== OBJECT_HQ
&&
260 IsTileType(t
, MP_OBJECT
) &&
261 IsTileOwner(t
, _current_company
) &&
262 IsObjectType(t
, OBJECT_HQ
))) {
263 cost
.AddCost(DoCommand(t
, 0, 0, flags
& ~DC_EXEC
, CMD_LANDSCAPE_CLEAR
));
268 /* So, now the surface is checked... check the slope of said surface. */
270 if (GetTileSlope(tile
, &allowed_z
) != SLOPE_FLAT
) allowed_z
++;
272 for (TileIndex t
: ta
) {
273 uint16 callback
= CALLBACK_FAILED
;
274 if (HasBit(spec
->callback_mask
, CBM_OBJ_SLOPE_CHECK
)) {
275 TileIndex diff
= t
- tile
;
276 callback
= GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK
, GetTileSlope(t
), TileY(diff
) << 4 | TileX(diff
), spec
, nullptr, t
, view
);
279 if (callback
== CALLBACK_FAILED
) {
280 cost
.AddCost(CheckBuildableTile(t
, 0, allowed_z
, false, false));
282 /* The meaning of bit 10 is inverted for a grf version < 8. */
283 if (spec
->grf_prop
.grffile
->grf_version
< 8) ToggleBit(callback
, 10);
284 CommandCost ret
= GetErrorMessageFromLocationCallbackResult(callback
, spec
->grf_prop
.grffile
, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
285 if (ret
.Failed()) return ret
;
289 if (flags
& DC_EXEC
) {
290 /* This is basically a copy of the loop above with the exception that we now
291 * execute the commands and don't check for errors, since that's already done. */
292 for (TileIndex t
: ta
) {
293 if (HasTileWaterGround(t
)) {
294 if (!IsWaterTile(t
)) {
295 DoCommand(t
, 0, 0, (flags
& ~DC_NO_WATER
) | DC_NO_MODIFY_TOWN_RATING
, CMD_LANDSCAPE_CLEAR
);
298 DoCommand(t
, 0, 0, flags
| DC_NO_MODIFY_TOWN_RATING
, CMD_LANDSCAPE_CLEAR
);
303 if (cost
.Failed()) return cost
;
305 /* Finally do a check for bridges. */
306 for (TileIndex t
: ta
) {
307 if (IsBridgeAbove(t
) && (
308 !(spec
->flags
& OBJECT_FLAG_ALLOW_UNDER_BRIDGE
) ||
309 (GetTileMaxZ(t
) + spec
->height
>= GetBridgeHeight(GetSouthernBridgeEnd(t
))))) {
310 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
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 /* We need to persuade a bit harder to remove the old HQ. */
333 _current_company
= OWNER_WATER
;
334 cost
.AddCost(ClearTile_Object(c
->location_of_HQ
, flags
));
335 _current_company
= c
->index
;
338 if (flags
& DC_EXEC
) {
339 hq_score
= UpdateCompanyRatingAndValue(c
, false);
340 c
->location_of_HQ
= tile
;
341 SetWindowDirty(WC_COMPANY
, c
->index
);
347 /* This may never be constructed using this method. */
350 default: // i.e. NewGRF provided.
354 if (flags
& DC_EXEC
) {
355 BuildObject(type
, tile
, _current_company
== OWNER_DEITY
? OWNER_NONE
: _current_company
, nullptr, view
);
357 /* Make sure the HQ starts at the right size. */
358 if (type
== OBJECT_HQ
) UpdateCompanyHQ(tile
, hq_score
);
361 cost
.AddCost(ObjectSpec::Get(type
)->GetBuildCost() * size_x
* size_y
);
366 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
);
368 static void DrawTile_Object(TileInfo
*ti
)
370 ObjectType type
= GetObjectType(ti
->tile
);
371 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
373 /* Fall back for when the object doesn't exist anymore. */
374 if (!spec
->enabled
) type
= OBJECT_TRANSMITTER
;
376 if ((spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) == 0) DrawFoundation(ti
, GetFoundation_Object(ti
->tile
, ti
->tileh
));
378 if (type
< NEW_OBJECT_OFFSET
) {
379 const DrawTileSprites
*dts
= nullptr;
380 Owner to
= GetTileOwner(ti
->tile
);
381 PaletteID palette
= to
== OWNER_NONE
? PAL_NONE
: COMPANY_SPRITE_COLOUR(to
);
383 if (type
== OBJECT_HQ
) {
384 TileIndex diff
= ti
->tile
- Object::GetByTile(ti
->tile
)->location
.tile
;
385 dts
= &_object_hq
[GetCompanyHQSize(ti
->tile
) << 2 | TileY(diff
) << 1 | TileX(diff
)];
387 dts
= &_objects
[type
];
390 if (spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) {
391 /* If an object has no foundation, but tries to draw a (flat) ground
392 * type... we have to be nice and convert that for them. */
393 switch (dts
->ground
.sprite
) {
394 case SPR_FLAT_BARE_LAND
: DrawClearLandTile(ti
, 0); break;
395 case SPR_FLAT_1_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 1); break;
396 case SPR_FLAT_2_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 2); break;
397 case SPR_FLAT_GRASS_TILE
: DrawClearLandTile(ti
, 3); break;
398 default: DrawGroundSprite(dts
->ground
.sprite
, palette
); break;
401 DrawGroundSprite(dts
->ground
.sprite
, palette
);
404 if (!IsInvisibilitySet(TO_STRUCTURES
)) {
405 const DrawTileSeqStruct
*dtss
;
406 foreach_draw_tile_seq(dtss
, dts
->seq
) {
407 AddSortableSpriteToDraw(
408 dtss
->image
.sprite
, palette
,
409 ti
->x
+ dtss
->delta_x
, ti
->y
+ dtss
->delta_y
,
410 dtss
->size_x
, dtss
->size_y
,
411 dtss
->size_z
, ti
->z
+ dtss
->delta_z
,
412 IsTransparencySet(TO_STRUCTURES
)
417 DrawNewObjectTile(ti
, spec
);
420 DrawBridgeMiddle(ti
);
423 static int GetSlopePixelZ_Object(TileIndex tile
, uint x
, uint y
)
425 if (IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
427 Slope tileh
= GetTilePixelSlope(tile
, &z
);
429 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
431 return GetTileMaxPixelZ(tile
);
435 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
)
437 return IsObjectType(tile
, OBJECT_OWNED_LAND
) ? FOUNDATION_NONE
: FlatteningFoundation(tileh
);
441 * Perform the actual removal of the object from the map.
442 * @param o The object to really clear.
444 static void ReallyClearObjectTile(Object
*o
)
446 Object::DecTypeCount(o
->type
);
447 for (TileIndex tile_cur
: o
->location
) {
448 DeleteNewGRFInspectWindow(GSF_OBJECTS
, tile_cur
);
450 MakeWaterKeepingClass(tile_cur
, GetTileOwner(tile_cur
));
455 std::vector
<ClearedObjectArea
> _cleared_object_areas
;
458 * Find the entry in _cleared_object_areas which occupies a certain tile.
459 * @param tile Tile of interest
460 * @return Occupying entry, or nullptr if none
462 ClearedObjectArea
*FindClearedObject(TileIndex tile
)
464 TileArea ta
= TileArea(tile
, 1, 1);
466 for (ClearedObjectArea
&coa
: _cleared_object_areas
) {
467 if (coa
.area
.Intersects(ta
)) return &coa
;
473 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
)
475 /* Get to the northern most tile. */
476 Object
*o
= Object::GetByTile(tile
);
477 TileArea ta
= o
->location
;
479 ObjectType type
= o
->type
;
480 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
482 CommandCost
cost(EXPENSES_CONSTRUCTION
, spec
->GetClearCost() * ta
.w
* ta
.h
/ 5);
483 if (spec
->flags
& OBJECT_FLAG_CLEAR_INCOME
) cost
.MultiplyCost(-1); // They get an income!
485 /* Towns can't remove any objects. */
486 if (_current_company
== OWNER_TOWN
) return CMD_ERROR
;
488 /* Water can remove everything! */
489 if (_current_company
!= OWNER_WATER
) {
490 if ((flags
& DC_NO_WATER
) && IsTileOnWater(tile
)) {
491 /* There is water under the object, treat it as water tile. */
492 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
493 } else if (!(spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) && (flags
& DC_AUTO
)) {
494 /* No automatic removal by overbuilding stuff. */
495 return_cmd_error(type
== OBJECT_HQ
? STR_ERROR_COMPANY_HEADQUARTERS_IN
: STR_ERROR_OBJECT_IN_THE_WAY
);
496 } else if (_game_mode
== GM_EDITOR
) {
497 /* No further limitations for the editor. */
498 } else if (GetTileOwner(tile
) == OWNER_NONE
) {
499 /* Owned by nobody and unremovable, so we can only remove it with brute force! */
500 if (!_cheats
.magic_bulldozer
.value
&& (spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0) return CMD_ERROR
;
501 } else if (CheckTileOwnership(tile
).Failed()) {
502 /* We don't own it!. */
503 return_cmd_error(STR_ERROR_OWNED_BY
);
504 } else if ((spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0 && (spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) == 0) {
505 /* In the game editor or with cheats we can remove, otherwise we can't. */
506 if (!_cheats
.magic_bulldozer
.value
) {
507 if (type
== OBJECT_HQ
) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN
);
511 /* Removing with the cheat costs more in TTDPatch / the specs. */
512 cost
.MultiplyCost(25);
514 } else if ((spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0) {
515 /* Water can't remove objects that are buildable on water. */
521 Company
*c
= Company::Get(GetTileOwner(tile
));
522 if (flags
& DC_EXEC
) {
523 c
->location_of_HQ
= INVALID_TILE
; // reset HQ position
524 SetWindowDirty(WC_COMPANY
, c
->index
);
525 CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS
, c
->index
);
528 /* cost of relocating company is 1% of company value */
529 cost
= CommandCost(EXPENSES_CONSTRUCTION
, CalculateCompanyValue(c
) / 100);
534 if (flags
& DC_EXEC
) {
535 Town
*town
= o
->town
;
536 ClrBit(town
->statues
, GetTileOwner(tile
));
537 SetWindowDirty(WC_TOWN_AUTHORITY
, town
->index
);
545 _cleared_object_areas
.push_back({tile
, ta
});
547 if (flags
& DC_EXEC
) ReallyClearObjectTile(o
);
552 static void AddAcceptedCargo_Object(TileIndex tile
, CargoArray
&acceptance
, CargoTypes
*always_accepted
)
554 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
556 /* HQ accepts passenger and mail; but we have to divide the values
557 * between 4 tiles it occupies! */
559 /* HQ level (depends on company performance) in the range 1..5. */
560 uint level
= GetCompanyHQSize(tile
) + 1;
562 /* Top town building generates 10, so to make HQ interesting, the top
564 acceptance
[CT_PASSENGERS
] += std::max(1U, level
);
565 SetBit(*always_accepted
, CT_PASSENGERS
);
567 /* Top town building generates 4, HQ can make up to 8. The
568 * proportion passengers:mail is different because such a huge
569 * commercial building generates unusually high amount of mail
570 * correspondence per physical visitor. */
571 acceptance
[CT_MAIL
] += std::max(1U, level
/ 2);
572 SetBit(*always_accepted
, CT_MAIL
);
575 static void AddProducedCargo_Object(TileIndex tile
, CargoArray
&produced
)
577 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
579 produced
[CT_PASSENGERS
]++;
584 static void GetTileDesc_Object(TileIndex tile
, TileDesc
*td
)
586 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
587 td
->str
= spec
->name
;
588 td
->owner
[0] = GetTileOwner(tile
);
589 td
->build_date
= Object::GetByTile(tile
)->build_date
;
591 if (spec
->grf_prop
.grffile
!= nullptr) {
592 td
->grf
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
)->GetName();
596 static void TileLoop_Object(TileIndex tile
)
598 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
599 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) {
600 Object
*o
= Object::GetByTile(tile
);
601 TriggerObjectTileAnimation(o
, tile
, OAT_TILELOOP
, spec
);
602 if (o
->location
.tile
== tile
) TriggerObjectAnimation(o
, OAT_256_TICKS
, spec
);
605 if (IsTileOnWater(tile
)) TileLoop_Water(tile
);
607 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
609 /* HQ accepts passenger and mail; but we have to divide the values
610 * between 4 tiles it occupies! */
612 /* HQ level (depends on company performance) in the range 1..5. */
613 uint level
= GetCompanyHQSize(tile
) + 1;
616 StationFinder
stations(TileArea(tile
, 2, 2));
619 /* Top town buildings generate 250, so the top HQ type makes 256. */
620 if (GB(r
, 0, 8) < (256 / 4 / (6 - level
))) {
621 uint amt
= GB(r
, 0, 8) / 8 / 4 + 1;
622 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
623 MoveGoodsToStation(CT_PASSENGERS
, amt
, ST_HEADQUARTERS
, GetTileOwner(tile
), stations
.GetStations());
626 /* Top town building generates 90, HQ can make up to 196. The
627 * proportion passengers:mail is about the same as in the acceptance
629 if (GB(r
, 8, 8) < (196 / 4 / (6 - level
))) {
630 uint amt
= GB(r
, 8, 8) / 8 / 4 + 1;
631 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
632 MoveGoodsToStation(CT_MAIL
, amt
, ST_HEADQUARTERS
, GetTileOwner(tile
), stations
.GetStations());
637 static TrackStatus
GetTileTrackStatus_Object(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
642 static bool ClickTile_Object(TileIndex tile
)
644 if (!IsObjectType(tile
, OBJECT_HQ
)) return false;
646 ShowCompany(GetTileOwner(tile
));
650 static void AnimateTile_Object(TileIndex tile
)
652 AnimateNewObjectTile(tile
);
656 * Helper function for \c CircularTileSearch.
657 * @param tile The tile to check.
658 * @param user Ignored.
659 * @return True iff the tile has a radio tower.
661 static bool HasTransmitter(TileIndex tile
, void *user
)
663 return IsObjectTypeTile(tile
, OBJECT_TRANSMITTER
);
667 * Try to build a lighthouse.
668 * @return True iff building a lighthouse succeeded.
670 static bool TryBuildLightHouse()
672 uint maxx
= MapMaxX();
673 uint maxy
= MapMaxY();
676 /* Scatter the lighthouses more evenly around the perimeter */
677 int perimeter
= (GB(r
, 16, 16) % (2 * (maxx
+ maxy
))) - maxy
;
679 for (dir
= DIAGDIR_NE
; perimeter
> 0; dir
++) {
680 perimeter
-= (DiagDirToAxis(dir
) == AXIS_X
) ? maxx
: maxy
;
686 case DIAGDIR_NE
: tile
= TileXY(maxx
- 1, r
% maxy
); break;
687 case DIAGDIR_SE
: tile
= TileXY(r
% maxx
, 1); break;
688 case DIAGDIR_SW
: tile
= TileXY(1, r
% maxy
); break;
689 case DIAGDIR_NW
: tile
= TileXY(r
% maxx
, maxy
- 1); break;
692 /* Only build lighthouses at tiles where the border is sea. */
693 if (!IsTileType(tile
, MP_WATER
)) return false;
695 for (int j
= 0; j
< 19; j
++) {
697 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
<= 2 && !IsBridgeAbove(tile
)) {
698 BuildObject(OBJECT_LIGHTHOUSE
, tile
);
699 assert(tile
< MapSize());
702 tile
+= TileOffsByDiagDir(dir
);
703 if (!IsValidTile(tile
)) return false;
709 * Try to build a transmitter.
710 * @return True iff a transmitter was built.
712 static bool TryBuildTransmitter()
714 TileIndex tile
= RandomTile();
716 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
>= 4 && !IsBridgeAbove(tile
)) {
718 if (CircularTileSearch(&t
, 9, HasTransmitter
, nullptr)) return false;
720 BuildObject(OBJECT_TRANSMITTER
, tile
);
726 void GenerateObjects()
728 /* Set a guestimate on how much we progress */
729 SetGeneratingWorldProgress(GWP_OBJECT
, NUM_OBJECTS
);
731 /* Determine number of water tiles at map border needed for freeform_edges */
732 uint num_water_tiles
= 0;
733 if (_settings_game
.construction
.freeform_edges
) {
734 for (uint x
= 0; x
< MapMaxX(); x
++) {
735 if (IsTileType(TileXY(x
, 1), MP_WATER
)) num_water_tiles
++;
736 if (IsTileType(TileXY(x
, MapMaxY() - 1), MP_WATER
)) num_water_tiles
++;
738 for (uint y
= 1; y
< MapMaxY() - 1; y
++) {
739 if (IsTileType(TileXY(1, y
), MP_WATER
)) num_water_tiles
++;
740 if (IsTileType(TileXY(MapMaxX() - 1, y
), MP_WATER
)) num_water_tiles
++;
744 /* Iterate over all possible object types */
745 for (uint i
= 0; i
< NUM_OBJECTS
; i
++) {
746 const ObjectSpec
*spec
= ObjectSpec::Get(i
);
748 /* Continue, if the object was never available till now or shall not be placed */
749 if (!spec
->WasEverAvailable() || spec
->generate_amount
== 0) continue;
751 uint16 amount
= spec
->generate_amount
;
753 /* Scale by map size */
754 if ((spec
->flags
& OBJECT_FLAG_SCALE_BY_WATER
) && _settings_game
.construction
.freeform_edges
) {
755 /* Scale the amount of lighthouses with the amount of land at the borders.
756 * The -6 is because the top borders are MP_VOID (-2) and all corners
757 * are counted twice (-4). */
758 amount
= ScaleByMapSize1D(amount
* num_water_tiles
) / (2 * MapMaxY() + 2 * MapMaxX() - 6);
759 } else if (spec
->flags
& OBJECT_FLAG_SCALE_BY_WATER
) {
760 amount
= ScaleByMapSize1D(amount
);
762 amount
= ScaleByMapSize(amount
);
765 /* Now try to place the requested amount of this object */
766 for (uint j
= ScaleByMapSize(1000); j
!= 0 && amount
!= 0 && Object::CanAllocateItem(); j
--) {
768 case OBJECT_TRANSMITTER
:
769 if (TryBuildTransmitter()) amount
--;
772 case OBJECT_LIGHTHOUSE
:
773 if (TryBuildLightHouse()) amount
--;
777 uint8 view
= RandomRange(spec
->views
);
778 if (CmdBuildObject(RandomTile(), DC_EXEC
| DC_AUTO
| DC_NO_TEST_TOWN_RATING
| DC_NO_MODIFY_TOWN_RATING
, i
, view
, {}).Succeeded()) amount
--;
782 IncreaseGeneratingWorldProgress(GWP_OBJECT
);
786 static void ChangeTileOwner_Object(TileIndex tile
, Owner old_owner
, Owner new_owner
)
788 if (!IsTileOwner(tile
, old_owner
)) return;
790 bool do_clear
= false;
792 ObjectType type
= GetObjectType(tile
);
793 if ((type
== OBJECT_OWNED_LAND
|| type
>= NEW_OBJECT_OFFSET
) && new_owner
!= INVALID_OWNER
) {
794 SetTileOwner(tile
, new_owner
);
795 } else if (type
== OBJECT_STATUE
) {
796 Town
*t
= Object::GetByTile(tile
)->town
;
797 ClrBit(t
->statues
, old_owner
);
798 if (new_owner
!= INVALID_OWNER
&& !HasBit(t
->statues
, new_owner
)) {
799 /* Transfer ownership to the new company */
800 SetBit(t
->statues
, new_owner
);
801 SetTileOwner(tile
, new_owner
);
806 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
812 ReallyClearObjectTile(Object::GetByTile(tile
));
813 /* When clearing objects, they may turn into canal, which may require transferring ownership. */
814 ChangeTileOwner(tile
, old_owner
, new_owner
);
818 static CommandCost
TerraformTile_Object(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
820 ObjectType type
= GetObjectType(tile
);
822 if (type
== OBJECT_OWNED_LAND
) {
823 /* Owned land remains unsold */
824 CommandCost ret
= CheckTileOwnership(tile
);
825 if (ret
.Succeeded()) return CommandCost();
826 } else if (AutoslopeEnabled() && type
!= OBJECT_TRANSMITTER
&& type
!= OBJECT_LIGHTHOUSE
) {
828 * - Both new and old slope must not be steep.
829 * - TileMaxZ must not be changed.
830 * - Allow autoslope by default.
831 * - Disallow autoslope if callback succeeds and returns non-zero.
833 Slope tileh_old
= GetTileSlope(tile
);
834 /* TileMaxZ must not be changed. Slopes must not be steep. */
835 if (!IsSteepSlope(tileh_old
) && !IsSteepSlope(tileh_new
) && (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
836 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
838 /* Call callback 'disable autosloping for objects'. */
839 if (HasBit(spec
->callback_mask
, CBM_OBJ_AUTOSLOPE
)) {
840 /* If the callback fails, allow autoslope. */
841 uint16 res
= GetObjectCallback(CBID_OBJECT_AUTOSLOPE
, 0, 0, spec
, Object::GetByTile(tile
), tile
);
842 if (res
== CALLBACK_FAILED
|| !ConvertBooleanCallback(spec
->grf_prop
.grffile
, CBID_OBJECT_AUTOSLOPE
, res
)) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
843 } else if (spec
->enabled
) {
844 /* allow autoslope */
845 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
850 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
853 extern const TileTypeProcs _tile_type_object_procs
= {
854 DrawTile_Object
, // draw_tile_proc
855 GetSlopePixelZ_Object
, // get_slope_z_proc
856 ClearTile_Object
, // clear_tile_proc
857 AddAcceptedCargo_Object
, // add_accepted_cargo_proc
858 GetTileDesc_Object
, // get_tile_desc_proc
859 GetTileTrackStatus_Object
, // get_tile_track_status_proc
860 ClickTile_Object
, // click_tile_proc
861 AnimateTile_Object
, // animate_tile_proc
862 TileLoop_Object
, // tile_loop_proc
863 ChangeTileOwner_Object
, // change_tile_owner_proc
864 AddProducedCargo_Object
, // add_produced_cargo_proc
865 nullptr, // vehicle_enter_tile_proc
866 GetFoundation_Object
, // get_foundation_proc
867 TerraformTile_Object
, // terraform_tile_proc