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
);
315 case OBJECT_TRANSMITTER
:
316 case OBJECT_LIGHTHOUSE
:
317 if (!IsTileFlat(tile
)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
320 case OBJECT_OWNED_LAND
:
321 if (IsTileType(tile
, MP_OBJECT
) &&
322 IsTileOwner(tile
, _current_company
) &&
323 IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
324 return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT
);
329 Company
*c
= Company::Get(_current_company
);
330 if (c
->location_of_HQ
!= INVALID_TILE
) {
331 /* We need to persuade a bit harder to remove the old HQ. */
332 _current_company
= OWNER_WATER
;
333 cost
.AddCost(ClearTile_Object(c
->location_of_HQ
, flags
));
334 _current_company
= c
->index
;
337 if (flags
& DC_EXEC
) {
338 hq_score
= UpdateCompanyRatingAndValue(c
, false);
339 c
->location_of_HQ
= tile
;
340 SetWindowDirty(WC_COMPANY
, c
->index
);
346 /* This may never be constructed using this method. */
349 default: // i.e. NewGRF provided.
353 if (flags
& DC_EXEC
) {
354 BuildObject(type
, tile
, _current_company
== OWNER_DEITY
? OWNER_NONE
: _current_company
, nullptr, view
);
356 /* Make sure the HQ starts at the right size. */
357 if (type
== OBJECT_HQ
) UpdateCompanyHQ(tile
, hq_score
);
360 cost
.AddCost(ObjectSpec::Get(type
)->GetBuildCost() * size_x
* size_y
);
365 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
);
367 static void DrawTile_Object(TileInfo
*ti
)
369 ObjectType type
= GetObjectType(ti
->tile
);
370 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
372 /* Fall back for when the object doesn't exist anymore. */
373 if (!spec
->enabled
) type
= OBJECT_TRANSMITTER
;
375 if ((spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) == 0) DrawFoundation(ti
, GetFoundation_Object(ti
->tile
, ti
->tileh
));
377 if (type
< NEW_OBJECT_OFFSET
) {
378 const DrawTileSprites
*dts
= nullptr;
379 Owner to
= GetTileOwner(ti
->tile
);
380 PaletteID palette
= to
== OWNER_NONE
? PAL_NONE
: COMPANY_SPRITE_COLOUR(to
);
382 if (type
== OBJECT_HQ
) {
383 TileIndex diff
= ti
->tile
- Object::GetByTile(ti
->tile
)->location
.tile
;
384 dts
= &_object_hq
[GetCompanyHQSize(ti
->tile
) << 2 | TileY(diff
) << 1 | TileX(diff
)];
386 dts
= &_objects
[type
];
389 if (spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) {
390 /* If an object has no foundation, but tries to draw a (flat) ground
391 * type... we have to be nice and convert that for them. */
392 switch (dts
->ground
.sprite
) {
393 case SPR_FLAT_BARE_LAND
: DrawClearLandTile(ti
, 0); break;
394 case SPR_FLAT_1_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 1); break;
395 case SPR_FLAT_2_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 2); break;
396 case SPR_FLAT_GRASS_TILE
: DrawClearLandTile(ti
, 3); break;
397 default: DrawGroundSprite(dts
->ground
.sprite
, palette
); break;
400 DrawGroundSprite(dts
->ground
.sprite
, palette
);
403 if (!IsInvisibilitySet(TO_STRUCTURES
)) {
404 const DrawTileSeqStruct
*dtss
;
405 foreach_draw_tile_seq(dtss
, dts
->seq
) {
406 AddSortableSpriteToDraw(
407 dtss
->image
.sprite
, palette
,
408 ti
->x
+ dtss
->delta_x
, ti
->y
+ dtss
->delta_y
,
409 dtss
->size_x
, dtss
->size_y
,
410 dtss
->size_z
, ti
->z
+ dtss
->delta_z
,
411 IsTransparencySet(TO_STRUCTURES
)
416 DrawNewObjectTile(ti
, spec
);
419 DrawBridgeMiddle(ti
);
422 static int GetSlopePixelZ_Object(TileIndex tile
, uint x
, uint y
)
424 if (IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
426 Slope tileh
= GetTilePixelSlope(tile
, &z
);
428 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
430 return GetTileMaxPixelZ(tile
);
434 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
)
436 return IsObjectType(tile
, OBJECT_OWNED_LAND
) ? FOUNDATION_NONE
: FlatteningFoundation(tileh
);
440 * Perform the actual removal of the object from the map.
441 * @param o The object to really clear.
443 static void ReallyClearObjectTile(Object
*o
)
445 Object::DecTypeCount(o
->type
);
446 for (TileIndex tile_cur
: o
->location
) {
447 DeleteNewGRFInspectWindow(GSF_OBJECTS
, tile_cur
);
449 MakeWaterKeepingClass(tile_cur
, GetTileOwner(tile_cur
));
454 std::vector
<ClearedObjectArea
> _cleared_object_areas
;
457 * Find the entry in _cleared_object_areas which occupies a certain tile.
458 * @param tile Tile of interest
459 * @return Occupying entry, or nullptr if none
461 ClearedObjectArea
*FindClearedObject(TileIndex tile
)
463 TileArea ta
= TileArea(tile
, 1, 1);
465 for (ClearedObjectArea
&coa
: _cleared_object_areas
) {
466 if (coa
.area
.Intersects(ta
)) return &coa
;
472 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
)
474 /* Get to the northern most tile. */
475 Object
*o
= Object::GetByTile(tile
);
476 TileArea ta
= o
->location
;
478 ObjectType type
= o
->type
;
479 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
481 CommandCost
cost(EXPENSES_CONSTRUCTION
, spec
->GetClearCost() * ta
.w
* ta
.h
/ 5);
482 if (spec
->flags
& OBJECT_FLAG_CLEAR_INCOME
) cost
.MultiplyCost(-1); // They get an income!
484 /* Towns can't remove any objects. */
485 if (_current_company
== OWNER_TOWN
) return CMD_ERROR
;
487 /* Water can remove everything! */
488 if (_current_company
!= OWNER_WATER
) {
489 if ((flags
& DC_NO_WATER
) && IsTileOnWater(tile
)) {
490 /* There is water under the object, treat it as water tile. */
491 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
492 } else if (!(spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) && (flags
& DC_AUTO
)) {
493 /* No automatic removal by overbuilding stuff. */
494 return_cmd_error(type
== OBJECT_HQ
? STR_ERROR_COMPANY_HEADQUARTERS_IN
: STR_ERROR_OBJECT_IN_THE_WAY
);
495 } else if (_game_mode
== GM_EDITOR
) {
496 /* No further limitations for the editor. */
497 } else if (GetTileOwner(tile
) == OWNER_NONE
) {
498 /* Owned by nobody and unremovable, so we can only remove it with brute force! */
499 if (!_cheats
.magic_bulldozer
.value
&& (spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0) return CMD_ERROR
;
500 } else if (CheckTileOwnership(tile
).Failed()) {
501 /* We don't own it!. */
502 return_cmd_error(STR_ERROR_OWNED_BY
);
503 } else if ((spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0 && (spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) == 0) {
504 /* In the game editor or with cheats we can remove, otherwise we can't. */
505 if (!_cheats
.magic_bulldozer
.value
) {
506 if (type
== OBJECT_HQ
) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN
);
510 /* Removing with the cheat costs more in TTDPatch / the specs. */
511 cost
.MultiplyCost(25);
513 } else if ((spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0) {
514 /* Water can't remove objects that are buildable on water. */
520 Company
*c
= Company::Get(GetTileOwner(tile
));
521 if (flags
& DC_EXEC
) {
522 c
->location_of_HQ
= INVALID_TILE
; // reset HQ position
523 SetWindowDirty(WC_COMPANY
, c
->index
);
524 CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS
, c
->index
);
527 /* cost of relocating company is 1% of company value */
528 cost
= CommandCost(EXPENSES_CONSTRUCTION
, CalculateCompanyValue(c
) / 100);
533 if (flags
& DC_EXEC
) {
534 Town
*town
= o
->town
;
535 ClrBit(town
->statues
, GetTileOwner(tile
));
536 SetWindowDirty(WC_TOWN_AUTHORITY
, town
->index
);
544 _cleared_object_areas
.push_back({tile
, ta
});
546 if (flags
& DC_EXEC
) ReallyClearObjectTile(o
);
551 static void AddAcceptedCargo_Object(TileIndex tile
, CargoArray
&acceptance
, CargoTypes
*always_accepted
)
553 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
555 /* HQ accepts passenger and mail; but we have to divide the values
556 * between 4 tiles it occupies! */
558 /* HQ level (depends on company performance) in the range 1..5. */
559 uint level
= GetCompanyHQSize(tile
) + 1;
561 /* Top town building generates 10, so to make HQ interesting, the top
563 acceptance
[CT_PASSENGERS
] += std::max(1U, level
);
564 SetBit(*always_accepted
, CT_PASSENGERS
);
566 /* Top town building generates 4, HQ can make up to 8. The
567 * proportion passengers:mail is different because such a huge
568 * commercial building generates unusually high amount of mail
569 * correspondence per physical visitor. */
570 acceptance
[CT_MAIL
] += std::max(1U, level
/ 2);
571 SetBit(*always_accepted
, CT_MAIL
);
574 static void AddProducedCargo_Object(TileIndex tile
, CargoArray
&produced
)
576 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
578 produced
[CT_PASSENGERS
]++;
583 static void GetTileDesc_Object(TileIndex tile
, TileDesc
*td
)
585 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
586 td
->str
= spec
->name
;
587 td
->owner
[0] = GetTileOwner(tile
);
588 td
->build_date
= Object::GetByTile(tile
)->build_date
;
590 if (spec
->grf_prop
.grffile
!= nullptr) {
591 td
->grf
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
)->GetName();
595 static void TileLoop_Object(TileIndex tile
)
597 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
598 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) {
599 Object
*o
= Object::GetByTile(tile
);
600 TriggerObjectTileAnimation(o
, tile
, OAT_TILELOOP
, spec
);
601 if (o
->location
.tile
== tile
) TriggerObjectAnimation(o
, OAT_256_TICKS
, spec
);
604 if (IsTileOnWater(tile
)) TileLoop_Water(tile
);
606 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
608 /* HQ accepts passenger and mail; but we have to divide the values
609 * between 4 tiles it occupies! */
611 /* HQ level (depends on company performance) in the range 1..5. */
612 uint level
= GetCompanyHQSize(tile
) + 1;
615 StationFinder
stations(TileArea(tile
, 2, 2));
618 /* Top town buildings generate 250, so the top HQ type makes 256. */
619 if (GB(r
, 0, 8) < (256 / 4 / (6 - level
))) {
620 uint amt
= GB(r
, 0, 8) / 8 / 4 + 1;
621 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
622 MoveGoodsToStation(CT_PASSENGERS
, amt
, ST_HEADQUARTERS
, GetTileOwner(tile
), stations
.GetStations());
625 /* Top town building generates 90, HQ can make up to 196. The
626 * proportion passengers:mail is about the same as in the acceptance
628 if (GB(r
, 8, 8) < (196 / 4 / (6 - level
))) {
629 uint amt
= GB(r
, 8, 8) / 8 / 4 + 1;
630 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
631 MoveGoodsToStation(CT_MAIL
, amt
, ST_HEADQUARTERS
, GetTileOwner(tile
), stations
.GetStations());
636 static TrackStatus
GetTileTrackStatus_Object(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
641 static bool ClickTile_Object(TileIndex tile
)
643 if (!IsObjectType(tile
, OBJECT_HQ
)) return false;
645 ShowCompany(GetTileOwner(tile
));
649 static void AnimateTile_Object(TileIndex tile
)
651 AnimateNewObjectTile(tile
);
655 * Helper function for \c CircularTileSearch.
656 * @param tile The tile to check.
657 * @param user Ignored.
658 * @return True iff the tile has a radio tower.
660 static bool HasTransmitter(TileIndex tile
, void *user
)
662 return IsObjectTypeTile(tile
, OBJECT_TRANSMITTER
);
666 * Try to build a lighthouse.
667 * @return True iff building a lighthouse succeeded.
669 static bool TryBuildLightHouse()
671 uint maxx
= MapMaxX();
672 uint maxy
= MapMaxY();
675 /* Scatter the lighthouses more evenly around the perimeter */
676 int perimeter
= (GB(r
, 16, 16) % (2 * (maxx
+ maxy
))) - maxy
;
678 for (dir
= DIAGDIR_NE
; perimeter
> 0; dir
++) {
679 perimeter
-= (DiagDirToAxis(dir
) == AXIS_X
) ? maxx
: maxy
;
685 case DIAGDIR_NE
: tile
= TileXY(maxx
- 1, r
% maxy
); break;
686 case DIAGDIR_SE
: tile
= TileXY(r
% maxx
, 1); break;
687 case DIAGDIR_SW
: tile
= TileXY(1, r
% maxy
); break;
688 case DIAGDIR_NW
: tile
= TileXY(r
% maxx
, maxy
- 1); break;
691 /* Only build lighthouses at tiles where the border is sea. */
692 if (!IsTileType(tile
, MP_WATER
)) return false;
694 for (int j
= 0; j
< 19; j
++) {
696 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
<= 2 && !IsBridgeAbove(tile
)) {
697 BuildObject(OBJECT_LIGHTHOUSE
, tile
);
698 assert(tile
< MapSize());
701 tile
+= TileOffsByDiagDir(dir
);
702 if (!IsValidTile(tile
)) return false;
708 * Try to build a transmitter.
709 * @return True iff a transmitter was built.
711 static bool TryBuildTransmitter()
713 TileIndex tile
= RandomTile();
715 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
>= 4 && !IsBridgeAbove(tile
)) {
717 if (CircularTileSearch(&t
, 9, HasTransmitter
, nullptr)) return false;
719 BuildObject(OBJECT_TRANSMITTER
, tile
);
725 void GenerateObjects()
727 /* Set a guestimate on how much we progress */
728 SetGeneratingWorldProgress(GWP_OBJECT
, NUM_OBJECTS
);
730 /* Determine number of water tiles at map border needed for freeform_edges */
731 uint num_water_tiles
= 0;
732 if (_settings_game
.construction
.freeform_edges
) {
733 for (uint x
= 0; x
< MapMaxX(); x
++) {
734 if (IsTileType(TileXY(x
, 1), MP_WATER
)) num_water_tiles
++;
735 if (IsTileType(TileXY(x
, MapMaxY() - 1), MP_WATER
)) num_water_tiles
++;
737 for (uint y
= 1; y
< MapMaxY() - 1; y
++) {
738 if (IsTileType(TileXY(1, y
), MP_WATER
)) num_water_tiles
++;
739 if (IsTileType(TileXY(MapMaxX() - 1, y
), MP_WATER
)) num_water_tiles
++;
743 /* Iterate over all possible object types */
744 for (uint i
= 0; i
< NUM_OBJECTS
; i
++) {
745 const ObjectSpec
*spec
= ObjectSpec::Get(i
);
747 /* Continue, if the object was never available till now or shall not be placed */
748 if (!spec
->WasEverAvailable() || spec
->generate_amount
== 0) continue;
750 uint16 amount
= spec
->generate_amount
;
752 /* Scale by map size */
753 if ((spec
->flags
& OBJECT_FLAG_SCALE_BY_WATER
) && _settings_game
.construction
.freeform_edges
) {
754 /* Scale the amount of lighthouses with the amount of land at the borders.
755 * The -6 is because the top borders are MP_VOID (-2) and all corners
756 * are counted twice (-4). */
757 amount
= ScaleByMapSize1D(amount
* num_water_tiles
) / (2 * MapMaxY() + 2 * MapMaxX() - 6);
758 } else if (spec
->flags
& OBJECT_FLAG_SCALE_BY_WATER
) {
759 amount
= ScaleByMapSize1D(amount
);
761 amount
= ScaleByMapSize(amount
);
764 /* Now try to place the requested amount of this object */
765 for (uint j
= ScaleByMapSize(1000); j
!= 0 && amount
!= 0 && Object::CanAllocateItem(); j
--) {
767 case OBJECT_TRANSMITTER
:
768 if (TryBuildTransmitter()) amount
--;
771 case OBJECT_LIGHTHOUSE
:
772 if (TryBuildLightHouse()) amount
--;
776 uint8 view
= RandomRange(spec
->views
);
777 if (CmdBuildObject(DC_EXEC
| DC_AUTO
| DC_NO_TEST_TOWN_RATING
| DC_NO_MODIFY_TOWN_RATING
, RandomTile(), i
, view
).Succeeded()) amount
--;
781 IncreaseGeneratingWorldProgress(GWP_OBJECT
);
785 static void ChangeTileOwner_Object(TileIndex tile
, Owner old_owner
, Owner new_owner
)
787 if (!IsTileOwner(tile
, old_owner
)) return;
789 bool do_clear
= false;
791 ObjectType type
= GetObjectType(tile
);
792 if ((type
== OBJECT_OWNED_LAND
|| type
>= NEW_OBJECT_OFFSET
) && new_owner
!= INVALID_OWNER
) {
793 SetTileOwner(tile
, new_owner
);
794 } else if (type
== OBJECT_STATUE
) {
795 Town
*t
= Object::GetByTile(tile
)->town
;
796 ClrBit(t
->statues
, old_owner
);
797 if (new_owner
!= INVALID_OWNER
&& !HasBit(t
->statues
, new_owner
)) {
798 /* Transfer ownership to the new company */
799 SetBit(t
->statues
, new_owner
);
800 SetTileOwner(tile
, new_owner
);
805 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
811 ReallyClearObjectTile(Object::GetByTile(tile
));
812 /* When clearing objects, they may turn into canal, which may require transferring ownership. */
813 ChangeTileOwner(tile
, old_owner
, new_owner
);
817 static CommandCost
TerraformTile_Object(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
819 ObjectType type
= GetObjectType(tile
);
821 if (type
== OBJECT_OWNED_LAND
) {
822 /* Owned land remains unsold */
823 CommandCost ret
= CheckTileOwnership(tile
);
824 if (ret
.Succeeded()) return CommandCost();
825 } else if (AutoslopeEnabled() && type
!= OBJECT_TRANSMITTER
&& type
!= OBJECT_LIGHTHOUSE
) {
827 * - Both new and old slope must not be steep.
828 * - TileMaxZ must not be changed.
829 * - Allow autoslope by default.
830 * - Disallow autoslope if callback succeeds and returns non-zero.
832 Slope tileh_old
= GetTileSlope(tile
);
833 /* TileMaxZ must not be changed. Slopes must not be steep. */
834 if (!IsSteepSlope(tileh_old
) && !IsSteepSlope(tileh_new
) && (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
835 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
837 /* Call callback 'disable autosloping for objects'. */
838 if (HasBit(spec
->callback_mask
, CBM_OBJ_AUTOSLOPE
)) {
839 /* If the callback fails, allow autoslope. */
840 uint16 res
= GetObjectCallback(CBID_OBJECT_AUTOSLOPE
, 0, 0, spec
, Object::GetByTile(tile
), tile
);
841 if (res
== CALLBACK_FAILED
|| !ConvertBooleanCallback(spec
->grf_prop
.grffile
, CBID_OBJECT_AUTOSLOPE
, res
)) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
842 } else if (spec
->enabled
) {
843 /* allow autoslope */
844 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
849 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
852 extern const TileTypeProcs _tile_type_object_procs
= {
853 DrawTile_Object
, // draw_tile_proc
854 GetSlopePixelZ_Object
, // get_slope_z_proc
855 ClearTile_Object
, // clear_tile_proc
856 AddAcceptedCargo_Object
, // add_accepted_cargo_proc
857 GetTileDesc_Object
, // get_tile_desc_proc
858 GetTileTrackStatus_Object
, // get_tile_track_status_proc
859 ClickTile_Object
, // click_tile_proc
860 AnimateTile_Object
, // animate_tile_proc
861 TileLoop_Object
, // tile_loop_proc
862 ChangeTileOwner_Object
, // change_tile_owner_proc
863 AddProducedCargo_Object
, // add_produced_cargo_proc
864 nullptr, // vehicle_enter_tile_proc
865 GetFoundation_Object
, // get_foundation_proc
866 TerraformTile_Object
, // terraform_tile_proc