Codechange: Move flags in CommandProc in front of the command arguments.
[openttd-github.git] / src / object_cmd.cpp
blobb5271727ce1594fa15fab6f96c34bebf904f39eb
1 /*
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/>.
6 */
8 /** @file object_cmd.cpp Handling of object tiles. */
10 #include "stdafx.h"
11 #include "landscape.h"
12 #include "command_func.h"
13 #include "viewport_func.h"
14 #include "company_base.h"
15 #include "town.h"
16 #include "bridge_map.h"
17 #include "genworld.h"
18 #include "autoslope.h"
19 #include "clear_func.h"
20 #include "water.h"
21 #include "window_func.h"
22 #include "company_gui.h"
23 #include "cheat_type.h"
24 #include "object.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"
38 #include "table/strings.h"
39 #include "table/object_land.h"
41 #include "safeguards.h"
43 ObjectPool _object_pool("Object");
44 INSTANTIATE_POOL_METHODS(Object)
45 uint16 Object::counts[NUM_OBJECTS];
47 /**
48 * Get the object associated with a tile.
49 * @param tile The tile to fetch the object for.
50 * @return The object.
52 /* static */ Object *Object::GetByTile(TileIndex tile)
54 return Object::Get(GetObjectIndex(tile));
57 /**
58 * Gets the ObjectType of the given object tile
59 * @param t the tile to get the type from.
60 * @pre IsTileType(t, MP_OBJECT)
61 * @return the type.
63 ObjectType GetObjectType(TileIndex t)
65 assert(IsTileType(t, MP_OBJECT));
66 return Object::GetByTile(t)->type;
69 /** Initialize/reset the objects. */
70 void InitializeObjects()
72 Object::ResetTypeCounts();
75 /**
76 * Actually build the object.
77 * @param type The type of object to build.
78 * @param tile The tile to build the northern tile of the object on.
79 * @param owner The owner of the object.
80 * @param town Town the tile is related with.
81 * @param view The view for the object.
82 * @pre All preconditions for building the object at that location
83 * are met, e.g. slope and clearness of tiles are checked.
85 void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, uint8 view)
87 const ObjectSpec *spec = ObjectSpec::Get(type);
89 TileArea ta(tile, GB(spec->size, HasBit(view, 0) ? 4 : 0, 4), GB(spec->size, HasBit(view, 0) ? 0 : 4, 4));
90 Object *o = new Object();
91 o->type = type;
92 o->location = ta;
93 o->town = town == nullptr ? CalcClosestTownFromTile(tile) : town;
94 o->build_date = _date;
95 o->view = view;
97 /* If nothing owns the object, the colour will be random. Otherwise
98 * get the colour from the company's livery settings. */
99 if (owner == OWNER_NONE) {
100 o->colour = Random();
101 } else {
102 const Livery *l = Company::Get(owner)->livery;
103 o->colour = l->colour1 + l->colour2 * 16;
106 /* If the object wants only one colour, then give it that colour. */
107 if ((spec->flags & OBJECT_FLAG_2CC_COLOUR) == 0) o->colour &= 0xF;
109 if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) {
110 uint16 res = GetObjectCallback(CBID_OBJECT_COLOUR, o->colour, 0, spec, o, tile);
111 if (res != CALLBACK_FAILED) {
112 if (res >= 0x100) ErrorUnknownCallbackResult(spec->grf_prop.grffile->grfid, CBID_OBJECT_COLOUR, res);
113 o->colour = GB(res, 0, 8);
117 assert(o->town != nullptr);
119 for (TileIndex t : ta) {
120 WaterClass wc = (IsWaterTile(t) ? GetWaterClass(t) : WATER_CLASS_INVALID);
121 /* Update company infrastructure counts for objects build on canals owned by nobody. */
122 if (wc == WATER_CLASS_CANAL && owner != OWNER_NONE && (IsTileOwner(tile, OWNER_NONE) || IsTileOwner(tile, OWNER_WATER))) {
123 Company::Get(owner)->infrastructure.water++;
124 DirtyCompanyInfrastructureWindows(owner);
126 bool remove = IsDockingTile(t);
127 MakeObject(t, owner, o->index, wc, Random());
128 if (remove) RemoveDockingTile(t);
129 MarkTileDirtyByTile(t);
132 Object::IncTypeCount(type);
133 if (spec->flags & OBJECT_FLAG_ANIMATION) TriggerObjectAnimation(o, OAT_BUILT, spec);
137 * Increase the animation stage of a whole structure.
138 * @param tile The tile of the structure.
140 static void IncreaseAnimationStage(TileIndex tile)
142 TileArea ta = Object::GetByTile(tile)->location;
143 for (TileIndex t : ta) {
144 SetAnimationFrame(t, GetAnimationFrame(t) + 1);
145 MarkTileDirtyByTile(t);
149 /** We encode the company HQ size in the animation stage. */
150 #define GetCompanyHQSize GetAnimationFrame
151 /** We encode the company HQ size in the animation stage. */
152 #define IncreaseCompanyHQSize IncreaseAnimationStage
155 * Update the CompanyHQ to the state associated with the given score
156 * @param tile The (northern) tile of the company HQ, or INVALID_TILE.
157 * @param score The current (performance) score of the company.
159 void UpdateCompanyHQ(TileIndex tile, uint score)
161 if (tile == INVALID_TILE) return;
163 byte val = 0;
164 if (score >= 170) val++;
165 if (score >= 350) val++;
166 if (score >= 520) val++;
167 if (score >= 720) val++;
169 while (GetCompanyHQSize(tile) < val) {
170 IncreaseCompanyHQSize(tile);
175 * Updates the colour of the object whenever a company changes.
176 * @param c The company the company colour changed of.
178 void UpdateObjectColours(const Company *c)
180 for (Object *obj : Object::Iterate()) {
181 Owner owner = GetTileOwner(obj->location.tile);
182 /* Not the current owner, so colour doesn't change. */
183 if (owner != c->index) continue;
185 const ObjectSpec *spec = ObjectSpec::GetByTile(obj->location.tile);
186 /* Using the object colour callback, so not using company colour. */
187 if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) continue;
189 const Livery *l = c->livery;
190 obj->colour = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? (l->colour2 * 16) : 0) + l->colour1;
194 extern CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge);
195 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags);
198 * Build an object object
199 * @param flags type of operation
200 * @param tile tile where the object will be located
201 * @param p1 the object type to build
202 * @param p2 the view for the object
203 * @param text unused
204 * @return the cost of this operation or an error
206 CommandCost CmdBuildObject(DoCommandFlag flags, TileIndex tile, uint32 p1, uint32 p2, const std::string &text)
208 CommandCost cost(EXPENSES_CONSTRUCTION);
210 ObjectType type = (ObjectType)GB(p1, 0, 16);
211 if (type >= NUM_OBJECTS) return CMD_ERROR;
212 uint8 view = GB(p2, 0, 2);
213 const ObjectSpec *spec = ObjectSpec::Get(type);
214 if (_game_mode == GM_NORMAL && !spec->IsAvailable() && !_generating_world) return CMD_ERROR;
215 if ((_game_mode == GM_EDITOR || _generating_world) && !spec->WasEverAvailable()) return CMD_ERROR;
217 if ((spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT) != 0 && ((!_generating_world && _game_mode != GM_EDITOR) || _current_company != OWNER_NONE)) return CMD_ERROR;
218 if ((spec->flags & OBJECT_FLAG_ONLY_IN_GAME) != 0 && (_generating_world || _game_mode != GM_NORMAL || _current_company > MAX_COMPANIES)) return CMD_ERROR;
219 if (view >= spec->views) return CMD_ERROR;
221 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
222 if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST);
224 int size_x = GB(spec->size, HasBit(view, 0) ? 4 : 0, 4);
225 int size_y = GB(spec->size, HasBit(view, 0) ? 0 : 4, 4);
226 TileArea ta(tile, size_x, size_y);
227 for (TileIndex t : ta) {
228 if (!IsValidTile(t)) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB); // Might be off the map
231 if (type == OBJECT_OWNED_LAND) {
232 /* Owned land is special as it can be placed on any slope. */
233 cost.AddCost(DoCommand(flags, CMD_LANDSCAPE_CLEAR, tile, 0, 0));
234 } else {
235 /* Check the surface to build on. At this time we can't actually execute the
236 * the CLEAR_TILE commands since the newgrf callback later on can check
237 * some information about the tiles. */
238 bool allow_water = (spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0;
239 bool allow_ground = (spec->flags & OBJECT_FLAG_NOT_ON_LAND) == 0;
240 for (TileIndex t : ta) {
241 if (HasTileWaterGround(t)) {
242 if (!allow_water) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
243 if (!IsWaterTile(t)) {
244 /* Normal water tiles don't have to be cleared. For all other tile types clear
245 * the tile but leave the water. */
246 cost.AddCost(DoCommand(flags & ~DC_NO_WATER & ~DC_EXEC, CMD_LANDSCAPE_CLEAR, t, 0, 0));
247 } else {
248 /* Can't build on water owned by another company. */
249 Owner o = GetTileOwner(t);
250 if (o != OWNER_NONE && o != OWNER_WATER) cost.AddCost(CheckOwnership(o, t));
252 /* However, the tile has to be clear of vehicles. */
253 cost.AddCost(EnsureNoVehicleOnGround(t));
255 } else {
256 if (!allow_ground) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER);
257 /* For non-water tiles, we'll have to clear it before building. */
259 /* When relocating HQ, allow it to be relocated (partial) on itself. */
260 if (!(type == OBJECT_HQ &&
261 IsTileType(t, MP_OBJECT) &&
262 IsTileOwner(t, _current_company) &&
263 IsObjectType(t, OBJECT_HQ))) {
264 cost.AddCost(DoCommand(flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR, t, 0, 0));
269 /* So, now the surface is checked... check the slope of said surface. */
270 int allowed_z;
271 if (GetTileSlope(tile, &allowed_z) != SLOPE_FLAT) allowed_z++;
273 for (TileIndex t : ta) {
274 uint16 callback = CALLBACK_FAILED;
275 if (HasBit(spec->callback_mask, CBM_OBJ_SLOPE_CHECK)) {
276 TileIndex diff = t - tile;
277 callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t), TileY(diff) << 4 | TileX(diff), spec, nullptr, t, view);
280 if (callback == CALLBACK_FAILED) {
281 cost.AddCost(CheckBuildableTile(t, 0, allowed_z, false, false));
282 } else {
283 /* The meaning of bit 10 is inverted for a grf version < 8. */
284 if (spec->grf_prop.grffile->grf_version < 8) ToggleBit(callback, 10);
285 CommandCost ret = GetErrorMessageFromLocationCallbackResult(callback, spec->grf_prop.grffile, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
286 if (ret.Failed()) return ret;
290 if (flags & DC_EXEC) {
291 /* This is basically a copy of the loop above with the exception that we now
292 * execute the commands and don't check for errors, since that's already done. */
293 for (TileIndex t : ta) {
294 if (HasTileWaterGround(t)) {
295 if (!IsWaterTile(t)) {
296 DoCommand((flags & ~DC_NO_WATER) | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR, t, 0, 0);
298 } else {
299 DoCommand(flags | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR, t, 0, 0);
304 if (cost.Failed()) return cost;
306 /* Finally do a check for bridges. */
307 for (TileIndex t : ta) {
308 if (IsBridgeAbove(t) && (
309 !(spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) ||
310 (GetTileMaxZ(t) + spec->height >= GetBridgeHeight(GetSouthernBridgeEnd(t))))) {
311 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
315 int hq_score = 0;
316 switch (type) {
317 case OBJECT_TRANSMITTER:
318 case OBJECT_LIGHTHOUSE:
319 if (!IsTileFlat(tile)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
320 break;
322 case OBJECT_OWNED_LAND:
323 if (IsTileType(tile, MP_OBJECT) &&
324 IsTileOwner(tile, _current_company) &&
325 IsObjectType(tile, OBJECT_OWNED_LAND)) {
326 return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT);
328 break;
330 case OBJECT_HQ: {
331 Company *c = Company::Get(_current_company);
332 if (c->location_of_HQ != INVALID_TILE) {
333 /* We need to persuade a bit harder to remove the old HQ. */
334 _current_company = OWNER_WATER;
335 cost.AddCost(ClearTile_Object(c->location_of_HQ, flags));
336 _current_company = c->index;
339 if (flags & DC_EXEC) {
340 hq_score = UpdateCompanyRatingAndValue(c, false);
341 c->location_of_HQ = tile;
342 SetWindowDirty(WC_COMPANY, c->index);
344 break;
347 case OBJECT_STATUE:
348 /* This may never be constructed using this method. */
349 return CMD_ERROR;
351 default: // i.e. NewGRF provided.
352 break;
355 if (flags & DC_EXEC) {
356 BuildObject(type, tile, _current_company == OWNER_DEITY ? OWNER_NONE : _current_company, nullptr, view);
358 /* Make sure the HQ starts at the right size. */
359 if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
362 cost.AddCost(ObjectSpec::Get(type)->GetBuildCost() * size_x * size_y);
363 return cost;
367 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh);
369 static void DrawTile_Object(TileInfo *ti)
371 ObjectType type = GetObjectType(ti->tile);
372 const ObjectSpec *spec = ObjectSpec::Get(type);
374 /* Fall back for when the object doesn't exist anymore. */
375 if (!spec->enabled) type = OBJECT_TRANSMITTER;
377 if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
379 if (type < NEW_OBJECT_OFFSET) {
380 const DrawTileSprites *dts = nullptr;
381 Owner to = GetTileOwner(ti->tile);
382 PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
384 if (type == OBJECT_HQ) {
385 TileIndex diff = ti->tile - Object::GetByTile(ti->tile)->location.tile;
386 dts = &_object_hq[GetCompanyHQSize(ti->tile) << 2 | TileY(diff) << 1 | TileX(diff)];
387 } else {
388 dts = &_objects[type];
391 if (spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) {
392 /* If an object has no foundation, but tries to draw a (flat) ground
393 * type... we have to be nice and convert that for them. */
394 switch (dts->ground.sprite) {
395 case SPR_FLAT_BARE_LAND: DrawClearLandTile(ti, 0); break;
396 case SPR_FLAT_1_THIRD_GRASS_TILE: DrawClearLandTile(ti, 1); break;
397 case SPR_FLAT_2_THIRD_GRASS_TILE: DrawClearLandTile(ti, 2); break;
398 case SPR_FLAT_GRASS_TILE: DrawClearLandTile(ti, 3); break;
399 default: DrawGroundSprite(dts->ground.sprite, palette); break;
401 } else {
402 DrawGroundSprite(dts->ground.sprite, palette);
405 if (!IsInvisibilitySet(TO_STRUCTURES)) {
406 const DrawTileSeqStruct *dtss;
407 foreach_draw_tile_seq(dtss, dts->seq) {
408 AddSortableSpriteToDraw(
409 dtss->image.sprite, palette,
410 ti->x + dtss->delta_x, ti->y + dtss->delta_y,
411 dtss->size_x, dtss->size_y,
412 dtss->size_z, ti->z + dtss->delta_z,
413 IsTransparencySet(TO_STRUCTURES)
417 } else {
418 DrawNewObjectTile(ti, spec);
421 DrawBridgeMiddle(ti);
424 static int GetSlopePixelZ_Object(TileIndex tile, uint x, uint y)
426 if (IsObjectType(tile, OBJECT_OWNED_LAND)) {
427 int z;
428 Slope tileh = GetTilePixelSlope(tile, &z);
430 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
431 } else {
432 return GetTileMaxPixelZ(tile);
436 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh)
438 return IsObjectType(tile, OBJECT_OWNED_LAND) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
442 * Perform the actual removal of the object from the map.
443 * @param o The object to really clear.
445 static void ReallyClearObjectTile(Object *o)
447 Object::DecTypeCount(o->type);
448 for (TileIndex tile_cur : o->location) {
449 DeleteNewGRFInspectWindow(GSF_OBJECTS, tile_cur);
451 MakeWaterKeepingClass(tile_cur, GetTileOwner(tile_cur));
453 delete o;
456 std::vector<ClearedObjectArea> _cleared_object_areas;
459 * Find the entry in _cleared_object_areas which occupies a certain tile.
460 * @param tile Tile of interest
461 * @return Occupying entry, or nullptr if none
463 ClearedObjectArea *FindClearedObject(TileIndex tile)
465 TileArea ta = TileArea(tile, 1, 1);
467 for (ClearedObjectArea &coa : _cleared_object_areas) {
468 if (coa.area.Intersects(ta)) return &coa;
471 return nullptr;
474 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
476 /* Get to the northern most tile. */
477 Object *o = Object::GetByTile(tile);
478 TileArea ta = o->location;
480 ObjectType type = o->type;
481 const ObjectSpec *spec = ObjectSpec::Get(type);
483 CommandCost cost(EXPENSES_CONSTRUCTION, spec->GetClearCost() * ta.w * ta.h / 5);
484 if (spec->flags & OBJECT_FLAG_CLEAR_INCOME) cost.MultiplyCost(-1); // They get an income!
486 /* Towns can't remove any objects. */
487 if (_current_company == OWNER_TOWN) return CMD_ERROR;
489 /* Water can remove everything! */
490 if (_current_company != OWNER_WATER) {
491 if ((flags & DC_NO_WATER) && IsTileOnWater(tile)) {
492 /* There is water under the object, treat it as water tile. */
493 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
494 } else if (!(spec->flags & OBJECT_FLAG_AUTOREMOVE) && (flags & DC_AUTO)) {
495 /* No automatic removal by overbuilding stuff. */
496 return_cmd_error(type == OBJECT_HQ ? STR_ERROR_COMPANY_HEADQUARTERS_IN : STR_ERROR_OBJECT_IN_THE_WAY);
497 } else if (_game_mode == GM_EDITOR) {
498 /* No further limitations for the editor. */
499 } else if (GetTileOwner(tile) == OWNER_NONE) {
500 /* Owned by nobody and unremovable, so we can only remove it with brute force! */
501 if (!_cheats.magic_bulldozer.value && (spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0) return CMD_ERROR;
502 } else if (CheckTileOwnership(tile).Failed()) {
503 /* We don't own it!. */
504 return_cmd_error(STR_ERROR_OWNED_BY);
505 } else if ((spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0 && (spec->flags & OBJECT_FLAG_AUTOREMOVE) == 0) {
506 /* In the game editor or with cheats we can remove, otherwise we can't. */
507 if (!_cheats.magic_bulldozer.value) {
508 if (type == OBJECT_HQ) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN);
509 return CMD_ERROR;
512 /* Removing with the cheat costs more in TTDPatch / the specs. */
513 cost.MultiplyCost(25);
515 } else if ((spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0) {
516 /* Water can't remove objects that are buildable on water. */
517 return CMD_ERROR;
520 switch (type) {
521 case OBJECT_HQ: {
522 Company *c = Company::Get(GetTileOwner(tile));
523 if (flags & DC_EXEC) {
524 c->location_of_HQ = INVALID_TILE; // reset HQ position
525 SetWindowDirty(WC_COMPANY, c->index);
526 CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS, c->index);
529 /* cost of relocating company is 1% of company value */
530 cost = CommandCost(EXPENSES_CONSTRUCTION, CalculateCompanyValue(c) / 100);
531 break;
534 case OBJECT_STATUE:
535 if (flags & DC_EXEC) {
536 Town *town = o->town;
537 ClrBit(town->statues, GetTileOwner(tile));
538 SetWindowDirty(WC_TOWN_AUTHORITY, town->index);
540 break;
542 default:
543 break;
546 _cleared_object_areas.push_back({tile, ta});
548 if (flags & DC_EXEC) ReallyClearObjectTile(o);
550 return cost;
553 static void AddAcceptedCargo_Object(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
555 if (!IsObjectType(tile, OBJECT_HQ)) return;
557 /* HQ accepts passenger and mail; but we have to divide the values
558 * between 4 tiles it occupies! */
560 /* HQ level (depends on company performance) in the range 1..5. */
561 uint level = GetCompanyHQSize(tile) + 1;
563 /* Top town building generates 10, so to make HQ interesting, the top
564 * type makes 20. */
565 acceptance[CT_PASSENGERS] += std::max(1U, level);
566 SetBit(*always_accepted, CT_PASSENGERS);
568 /* Top town building generates 4, HQ can make up to 8. The
569 * proportion passengers:mail is different because such a huge
570 * commercial building generates unusually high amount of mail
571 * correspondence per physical visitor. */
572 acceptance[CT_MAIL] += std::max(1U, level / 2);
573 SetBit(*always_accepted, CT_MAIL);
576 static void AddProducedCargo_Object(TileIndex tile, CargoArray &produced)
578 if (!IsObjectType(tile, OBJECT_HQ)) return;
580 produced[CT_PASSENGERS]++;
581 produced[CT_MAIL]++;
585 static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
587 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
588 td->str = spec->name;
589 td->owner[0] = GetTileOwner(tile);
590 td->build_date = Object::GetByTile(tile)->build_date;
592 if (spec->grf_prop.grffile != nullptr) {
593 td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
597 static void TileLoop_Object(TileIndex tile)
599 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
600 if (spec->flags & OBJECT_FLAG_ANIMATION) {
601 Object *o = Object::GetByTile(tile);
602 TriggerObjectTileAnimation(o, tile, OAT_TILELOOP, spec);
603 if (o->location.tile == tile) TriggerObjectAnimation(o, OAT_256_TICKS, spec);
606 if (IsTileOnWater(tile)) TileLoop_Water(tile);
608 if (!IsObjectType(tile, OBJECT_HQ)) return;
610 /* HQ accepts passenger and mail; but we have to divide the values
611 * between 4 tiles it occupies! */
613 /* HQ level (depends on company performance) in the range 1..5. */
614 uint level = GetCompanyHQSize(tile) + 1;
615 assert(level < 6);
617 StationFinder stations(TileArea(tile, 2, 2));
619 uint r = Random();
620 /* Top town buildings generate 250, so the top HQ type makes 256. */
621 if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
622 uint amt = GB(r, 0, 8) / 8 / 4 + 1;
623 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
624 MoveGoodsToStation(CT_PASSENGERS, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
627 /* Top town building generates 90, HQ can make up to 196. The
628 * proportion passengers:mail is about the same as in the acceptance
629 * equations. */
630 if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
631 uint amt = GB(r, 8, 8) / 8 / 4 + 1;
632 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
633 MoveGoodsToStation(CT_MAIL, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
638 static TrackStatus GetTileTrackStatus_Object(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
640 return 0;
643 static bool ClickTile_Object(TileIndex tile)
645 if (!IsObjectType(tile, OBJECT_HQ)) return false;
647 ShowCompany(GetTileOwner(tile));
648 return true;
651 static void AnimateTile_Object(TileIndex tile)
653 AnimateNewObjectTile(tile);
657 * Helper function for \c CircularTileSearch.
658 * @param tile The tile to check.
659 * @param user Ignored.
660 * @return True iff the tile has a radio tower.
662 static bool HasTransmitter(TileIndex tile, void *user)
664 return IsObjectTypeTile(tile, OBJECT_TRANSMITTER);
668 * Try to build a lighthouse.
669 * @return True iff building a lighthouse succeeded.
671 static bool TryBuildLightHouse()
673 uint maxx = MapMaxX();
674 uint maxy = MapMaxY();
675 uint r = Random();
677 /* Scatter the lighthouses more evenly around the perimeter */
678 int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
679 DiagDirection dir;
680 for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
681 perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
684 TileIndex tile;
685 switch (dir) {
686 default:
687 case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
688 case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
689 case DIAGDIR_SW: tile = TileXY(1, r % maxy); break;
690 case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
693 /* Only build lighthouses at tiles where the border is sea. */
694 if (!IsTileType(tile, MP_WATER)) return false;
696 for (int j = 0; j < 19; j++) {
697 int h;
698 if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h <= 2 && !IsBridgeAbove(tile)) {
699 BuildObject(OBJECT_LIGHTHOUSE, tile);
700 assert(tile < MapSize());
701 return true;
703 tile += TileOffsByDiagDir(dir);
704 if (!IsValidTile(tile)) return false;
706 return false;
710 * Try to build a transmitter.
711 * @return True iff a transmitter was built.
713 static bool TryBuildTransmitter()
715 TileIndex tile = RandomTile();
716 int h;
717 if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h >= 4 && !IsBridgeAbove(tile)) {
718 TileIndex t = tile;
719 if (CircularTileSearch(&t, 9, HasTransmitter, nullptr)) return false;
721 BuildObject(OBJECT_TRANSMITTER, tile);
722 return true;
724 return false;
727 void GenerateObjects()
729 /* Set a guestimate on how much we progress */
730 SetGeneratingWorldProgress(GWP_OBJECT, NUM_OBJECTS);
732 /* Determine number of water tiles at map border needed for freeform_edges */
733 uint num_water_tiles = 0;
734 if (_settings_game.construction.freeform_edges) {
735 for (uint x = 0; x < MapMaxX(); x++) {
736 if (IsTileType(TileXY(x, 1), MP_WATER)) num_water_tiles++;
737 if (IsTileType(TileXY(x, MapMaxY() - 1), MP_WATER)) num_water_tiles++;
739 for (uint y = 1; y < MapMaxY() - 1; y++) {
740 if (IsTileType(TileXY(1, y), MP_WATER)) num_water_tiles++;
741 if (IsTileType(TileXY(MapMaxX() - 1, y), MP_WATER)) num_water_tiles++;
745 /* Iterate over all possible object types */
746 for (uint i = 0; i < NUM_OBJECTS; i++) {
747 const ObjectSpec *spec = ObjectSpec::Get(i);
749 /* Continue, if the object was never available till now or shall not be placed */
750 if (!spec->WasEverAvailable() || spec->generate_amount == 0) continue;
752 uint16 amount = spec->generate_amount;
754 /* Scale by map size */
755 if ((spec->flags & OBJECT_FLAG_SCALE_BY_WATER) && _settings_game.construction.freeform_edges) {
756 /* Scale the amount of lighthouses with the amount of land at the borders.
757 * The -6 is because the top borders are MP_VOID (-2) and all corners
758 * are counted twice (-4). */
759 amount = ScaleByMapSize1D(amount * num_water_tiles) / (2 * MapMaxY() + 2 * MapMaxX() - 6);
760 } else if (spec->flags & OBJECT_FLAG_SCALE_BY_WATER) {
761 amount = ScaleByMapSize1D(amount);
762 } else {
763 amount = ScaleByMapSize(amount);
766 /* Now try to place the requested amount of this object */
767 for (uint j = ScaleByMapSize(1000); j != 0 && amount != 0 && Object::CanAllocateItem(); j--) {
768 switch (i) {
769 case OBJECT_TRANSMITTER:
770 if (TryBuildTransmitter()) amount--;
771 break;
773 case OBJECT_LIGHTHOUSE:
774 if (TryBuildLightHouse()) amount--;
775 break;
777 default:
778 uint8 view = RandomRange(spec->views);
779 if (CmdBuildObject(DC_EXEC | DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, RandomTile(), i, view, {}).Succeeded()) amount--;
780 break;
783 IncreaseGeneratingWorldProgress(GWP_OBJECT);
787 static void ChangeTileOwner_Object(TileIndex tile, Owner old_owner, Owner new_owner)
789 if (!IsTileOwner(tile, old_owner)) return;
791 bool do_clear = false;
793 ObjectType type = GetObjectType(tile);
794 if ((type == OBJECT_OWNED_LAND || type >= NEW_OBJECT_OFFSET) && new_owner != INVALID_OWNER) {
795 SetTileOwner(tile, new_owner);
796 } else if (type == OBJECT_STATUE) {
797 Town *t = Object::GetByTile(tile)->town;
798 ClrBit(t->statues, old_owner);
799 if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
800 /* Transfer ownership to the new company */
801 SetBit(t->statues, new_owner);
802 SetTileOwner(tile, new_owner);
803 } else {
804 do_clear = true;
807 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
808 } else {
809 do_clear = true;
812 if (do_clear) {
813 ReallyClearObjectTile(Object::GetByTile(tile));
814 /* When clearing objects, they may turn into canal, which may require transferring ownership. */
815 ChangeTileOwner(tile, old_owner, new_owner);
819 static CommandCost TerraformTile_Object(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
821 ObjectType type = GetObjectType(tile);
823 if (type == OBJECT_OWNED_LAND) {
824 /* Owned land remains unsold */
825 CommandCost ret = CheckTileOwnership(tile);
826 if (ret.Succeeded()) return CommandCost();
827 } else if (AutoslopeEnabled() && type != OBJECT_TRANSMITTER && type != OBJECT_LIGHTHOUSE) {
828 /* Behaviour:
829 * - Both new and old slope must not be steep.
830 * - TileMaxZ must not be changed.
831 * - Allow autoslope by default.
832 * - Disallow autoslope if callback succeeds and returns non-zero.
834 Slope tileh_old = GetTileSlope(tile);
835 /* TileMaxZ must not be changed. Slopes must not be steep. */
836 if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
837 const ObjectSpec *spec = ObjectSpec::Get(type);
839 /* Call callback 'disable autosloping for objects'. */
840 if (HasBit(spec->callback_mask, CBM_OBJ_AUTOSLOPE)) {
841 /* If the callback fails, allow autoslope. */
842 uint16 res = GetObjectCallback(CBID_OBJECT_AUTOSLOPE, 0, 0, spec, Object::GetByTile(tile), tile);
843 if (res == CALLBACK_FAILED || !ConvertBooleanCallback(spec->grf_prop.grffile, CBID_OBJECT_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
844 } else if (spec->enabled) {
845 /* allow autoslope */
846 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
851 return DoCommand(flags, CMD_LANDSCAPE_CLEAR, tile, 0, 0);
854 extern const TileTypeProcs _tile_type_object_procs = {
855 DrawTile_Object, // draw_tile_proc
856 GetSlopePixelZ_Object, // get_slope_z_proc
857 ClearTile_Object, // clear_tile_proc
858 AddAcceptedCargo_Object, // add_accepted_cargo_proc
859 GetTileDesc_Object, // get_tile_desc_proc
860 GetTileTrackStatus_Object, // get_tile_track_status_proc
861 ClickTile_Object, // click_tile_proc
862 AnimateTile_Object, // animate_tile_proc
863 TileLoop_Object, // tile_loop_proc
864 ChangeTileOwner_Object, // change_tile_owner_proc
865 AddProducedCargo_Object, // add_produced_cargo_proc
866 nullptr, // vehicle_enter_tile_proc
867 GetFoundation_Object, // get_foundation_proc
868 TerraformTile_Object, // terraform_tile_proc