Fix crash when setting separation mode for vehicles with no orders list.
[openttd-joker.git] / src / object_cmd.cpp
blob2d882db1d7a2c4a540f554d2a7c4b9e91c4f9fd1
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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 */
10 /** @file object_cmd.cpp Handling of object tiles. */
12 #include "stdafx.h"
13 #include "landscape.h"
14 #include "command_func.h"
15 #include "viewport_func.h"
16 #include "company_base.h"
17 #include "town.h"
18 #include "bridge_map.h"
19 #include "genworld.h"
20 #include "autoslope.h"
21 #include "clear_func.h"
22 #include "water.h"
23 #include "window_func.h"
24 #include "company_gui.h"
25 #include "cheat_type.h"
26 #include "object.h"
27 #include "cargopacket.h"
28 #include "core/random_func.hpp"
29 #include "core/pool_func.hpp"
30 #include "object_map.h"
31 #include "object_base.h"
32 #include "newgrf_config.h"
33 #include "newgrf_object.h"
34 #include "date_func.h"
35 #include "newgrf_debug.h"
36 #include "vehicle_func.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));
91 Object *o = new Object();
92 o->type = type;
93 o->location = ta;
94 o->town = town == nullptr ? CalcClosestTownFromTile(tile) : town;
95 o->build_date = _date;
96 o->view = view;
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();
102 } else {
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 TILE_AREA_LOOP(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 MakeObject(t, owner, o->index, wc, Random());
128 MarkTileDirtyByTile(t, ZOOM_LVL_DRAW_MAP);
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 TILE_AREA_LOOP(t, ta) {
143 SetAnimationFrame(t, GetAnimationFrame(t) + 1);
144 MarkTileDirtyByTile(t, ZOOM_LVL_DRAW_MAP);
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;
162 byte val;
163 (val = 0, score < 170) ||
164 (val++, score < 350) ||
165 (val++, score < 520) ||
166 (val++, score < 720) ||
167 (val++, true);
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 Object *obj;
181 FOR_ALL_OBJECTS(obj) {
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 tile tile where the object will be located
201 * @param flags type of operation
202 * @param p1 the object type to build
203 * @param p2 the view for the object
204 * @param text unused
205 * @return the cost of this operation or an error
207 CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
209 CommandCost cost(EXPENSES_PROPERTY);
211 ObjectType type = (ObjectType)GB(p1, 0, 16);
212 if (type >= NUM_OBJECTS) return CommandError();
213 uint8 view = GB(p2, 0, 2);
214 TileIndex start_tile = GB(p2, 2, 30);
216 if (start_tile >= MapSize()) return CommandError();
218 const ObjectSpec *spec = ObjectSpec::Get(type);
219 if (_game_mode == GM_NORMAL && !spec->IsAvailable() && !_generating_world) return CommandError();
220 if ((_game_mode == GM_EDITOR || _generating_world) && !spec->WasEverAvailable()) return CommandError();
222 if ((spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT) != 0 && ((!_generating_world && _game_mode != GM_EDITOR) || _current_company != OWNER_NONE)) return CommandError();
223 if ((spec->flags & OBJECT_FLAG_ONLY_IN_GAME) != 0 && (_generating_world || _game_mode != GM_NORMAL || _current_company > MAX_COMPANIES)) return CommandError();
224 if (view >= spec->views) return CommandError();
226 if (!Object::CanAllocateItem()) return CommandError(STR_ERROR_TOO_MANY_OBJECTS);
227 if (Town::GetNumItems() == 0) return CommandError(STR_ERROR_MUST_FOUND_TOWN_FIRST);
229 int size_x = GB(spec->size, HasBit(view, 0) ? 4 : 0, 4);
230 int size_y = GB(spec->size, HasBit(view, 0) ? 0 : 4, 4);
231 bool is_draggable = (type == OBJECT_OWNED_LAND || (size_x == 1 && size_y == 1 && type >= NEW_OBJECT_OFFSET));
232 TileArea drag_ta;
234 if (is_draggable) {
235 drag_ta = TileArea(tile, start_tile);
237 else {
238 drag_ta = TileArea(tile, 1, 1);
241 TILE_AREA_LOOP(tile, drag_ta) {
242 TileArea ta(tile, size_x, size_y);
243 if (type == OBJECT_OWNED_LAND) {
244 /* Owned land is special as it can be placed on any slope. */
245 cost.AddCost(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR));
247 else {
248 /* Check the surface to build on. At this time we can't actually execute the
249 * the CLEAR_TILE commands since the newgrf callback later on can check
250 * some information about the tiles. */
251 bool allow_water = (spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0;
252 bool allow_ground = (spec->flags & OBJECT_FLAG_NOT_ON_LAND) == 0;
253 TILE_AREA_LOOP(t, ta) {
254 if (HasTileWaterGround(t)) {
255 if (!allow_water) return CommandError(STR_ERROR_CAN_T_BUILD_ON_WATER);
256 if (!IsWaterTile(t)) {
257 /* Normal water tiles don't have to be cleared. For all other tile types clear
258 * the tile but leave the water. */
259 cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_NO_WATER & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
261 else {
262 /* Can't build on water owned by another company. */
263 Owner o = GetTileOwner(t);
264 if (o != OWNER_NONE && o != OWNER_WATER) cost.AddCost(CheckOwnership(o, t));
266 /* However, the tile has to be clear of vehicles. */
267 cost.AddCost(EnsureNoVehicleOnGround(t));
270 else {
271 if (!allow_ground) return CommandError(STR_ERROR_MUST_BE_BUILT_ON_WATER);
272 /* For non-water tiles, we'll have to clear it before building. */
273 cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
277 /* So, now the surface is checked... check the slope of said surface. */
278 int allowed_z;
279 if (GetTileSlope(tile, &allowed_z) != SLOPE_FLAT) allowed_z++;
281 TILE_AREA_LOOP(t, ta) {
282 uint16 callback = CALLBACK_FAILED;
283 if (HasBit(spec->callback_mask, CBM_OBJ_SLOPE_CHECK)) {
284 TileIndex diff = t - tile;
285 callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t), TileY(diff) << 4 | TileX(diff), spec, nullptr, t, view);
288 if (callback == CALLBACK_FAILED) {
289 cost.AddCost(CheckBuildableTile(t, 0, allowed_z, false, false));
291 else {
292 /* The meaning of bit 10 is inverted for a grf version < 8. */
293 if (spec->grf_prop.grffile->grf_version < 8) ToggleBit(callback, 10);
294 CommandCost ret = GetErrorMessageFromLocationCallbackResult(callback, spec->grf_prop.grffile, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
295 if (ret.Failed()) return ret;
299 if (flags & DC_EXEC) {
300 /* This is basically a copy of the loop above with the exception that we now
301 * execute the commands and don't check for errors, since that's already done. */
302 TILE_AREA_LOOP(t, ta) {
303 if (HasTileWaterGround(t)) {
304 if (!IsWaterTile(t)) {
305 DoCommand(t, 0, 0, (flags & ~DC_NO_WATER) | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
308 else {
309 DoCommand(t, 0, 0, flags | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
314 if (cost.Failed()) return cost;
316 /* Finally do a check for bridges. */
317 TILE_AREA_LOOP(t, ta) {
318 if (IsBridgeAbove(t) && (
319 !(spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) ||
320 (GetTileMaxZ(t) + spec->height >= GetBridgeHeight(GetSouthernBridgeEnd(t))))) {
321 return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
325 int hq_score = 0;
326 switch (type) {
327 case OBJECT_TRANSMITTER:
328 case OBJECT_LIGHTHOUSE:
329 if (!IsTileFlat(tile)) return CommandError(STR_ERROR_FLAT_LAND_REQUIRED);
330 break;
332 case OBJECT_OWNED_LAND:
333 if (IsTileType(tile, MP_OBJECT) &&
334 IsTileOwner(tile, _current_company) &&
335 IsObjectType(tile, OBJECT_OWNED_LAND)) {
336 return CommandError(STR_ERROR_YOU_ALREADY_OWN_IT);
338 break;
340 case OBJECT_HQ: {
341 Company *c = Company::Get(_current_company);
342 if (c->location_of_HQ != INVALID_TILE) {
343 /* We need to persuade a bit harder to remove the old HQ. */
344 _current_company = OWNER_WATER;
345 cost.AddCost(ClearTile_Object(c->location_of_HQ, flags));
346 _current_company = c->index;
349 if (flags & DC_EXEC) {
350 hq_score = UpdateCompanyRatingAndValue(c, false);
351 c->location_of_HQ = tile;
352 SetWindowDirty(WC_COMPANY, c->index);
354 break;
357 case OBJECT_STATUE:
358 /* This may never be constructed using this method. */
359 return CommandError();
361 default: // i.e. NewGRF provided.
362 break;
365 if (flags & DC_EXEC) {
366 if (!Object::CanAllocateItem()) return CommandError(STR_ERROR_TOO_MANY_OBJECTS);
368 BuildObject(type, tile, _current_company, nullptr, view);
370 /* Make sure the HQ starts at the right size. */
371 if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
374 cost.AddCost(ObjectSpec::Get(type)->GetBuildCost() * size_x * size_y);
377 return cost;
381 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh);
383 static void DrawTile_Object(TileInfo *ti)
385 ObjectType type = GetObjectType(ti->tile);
386 const ObjectSpec *spec = ObjectSpec::Get(type);
388 /* Fall back for when the object doesn't exist anymore. */
389 if (!spec->enabled) type = OBJECT_TRANSMITTER;
391 if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
393 if (type < NEW_OBJECT_OFFSET) {
394 const DrawTileSprites *dts = nullptr;
395 Owner to = GetTileOwner(ti->tile);
396 PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
398 if (type == OBJECT_HQ) {
399 TileIndex diff = ti->tile - Object::GetByTile(ti->tile)->location.tile;
400 dts = &_object_hq[GetCompanyHQSize(ti->tile) << 2 | TileY(diff) << 1 | TileX(diff)];
401 } else {
402 dts = &_objects[type];
405 if (spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) {
406 /* If an object has no foundation, but tries to draw a (flat) ground
407 * type... we have to be nice and convert that for them. */
408 switch (dts->ground.sprite) {
409 case SPR_FLAT_BARE_LAND: DrawClearLandTile(ti, 0); break;
410 case SPR_FLAT_1_THIRD_GRASS_TILE: DrawClearLandTile(ti, 1); break;
411 case SPR_FLAT_2_THIRD_GRASS_TILE: DrawClearLandTile(ti, 2); break;
412 case SPR_FLAT_GRASS_TILE: DrawClearLandTile(ti, 3); break;
413 default: DrawGroundSprite(dts->ground.sprite, palette); break;
415 } else {
416 DrawGroundSprite(dts->ground.sprite, palette);
419 if (!IsInvisibilitySet(TO_STRUCTURES)) {
420 const DrawTileSeqStruct *dtss;
421 foreach_draw_tile_seq(dtss, dts->seq) {
422 AddSortableSpriteToDraw(
423 dtss->image.sprite, palette,
424 ti->x + dtss->delta_x, ti->y + dtss->delta_y,
425 dtss->size_x, dtss->size_y,
426 dtss->size_z, ti->z + dtss->delta_z,
427 IsTransparencySet(TO_STRUCTURES)
431 } else {
432 DrawNewObjectTile(ti, spec);
435 DrawBridgeMiddle(ti);
438 static int GetSlopePixelZ_Object(TileIndex tile, uint x, uint y)
440 if (IsObjectType(tile, OBJECT_OWNED_LAND)) {
441 int z;
442 Slope tileh = GetTilePixelSlope(tile, &z);
444 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
445 } else {
446 return GetTileMaxPixelZ(tile);
450 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh)
452 return IsObjectType(tile, OBJECT_OWNED_LAND) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
456 * Perform the actual removal of the object from the map.
457 * @param o The object to really clear.
459 static void ReallyClearObjectTile(Object *o)
461 Object::DecTypeCount(o->type);
462 TILE_AREA_LOOP(tile_cur, o->location) {
463 DeleteNewGRFInspectWindow(GSF_OBJECTS, tile_cur);
465 MakeWaterKeepingClass(tile_cur, GetTileOwner(tile_cur));
467 delete o;
470 SmallVector<ClearedObjectArea, 4> _cleared_object_areas;
473 * Find the entry in _cleared_object_areas which occupies a certain tile.
474 * @param tile Tile of interest
475 * @return Occupying entry, or nullptr if none
477 ClearedObjectArea *FindClearedObject(TileIndex tile)
479 TileArea ta = TileArea(tile, 1, 1);
481 const ClearedObjectArea *end = _cleared_object_areas.End();
482 for (ClearedObjectArea *coa = _cleared_object_areas.Begin(); coa != end; coa++) {
483 if (coa->area.Intersects(ta)) return coa;
486 return nullptr;
489 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
491 /* Get to the northern most tile. */
492 Object *o = Object::GetByTile(tile);
493 TileArea ta = o->location;
495 ObjectType type = o->type;
496 const ObjectSpec *spec = ObjectSpec::Get(type);
498 CommandCost cost(EXPENSES_CONSTRUCTION, spec->GetClearCost() * ta.w * ta.h / 5);
499 if (spec->flags & OBJECT_FLAG_CLEAR_INCOME) cost.MultiplyCost(-1); // They get an income!
501 /* Towns can't remove any objects. */
502 if (_current_company == OWNER_TOWN) return CommandError();
504 /* Water can remove everything! */
505 if (_current_company != OWNER_WATER) {
506 if ((flags & DC_NO_WATER) && IsTileOnWater(tile)) {
507 /* There is water under the object, treat it as water tile. */
508 return CommandError(STR_ERROR_CAN_T_BUILD_ON_WATER);
509 } else if (!(spec->flags & OBJECT_FLAG_AUTOREMOVE) && (flags & DC_AUTO)) {
510 /* No automatic removal by overbuilding stuff. */
511 return CommandError(type == OBJECT_HQ ? STR_ERROR_COMPANY_HEADQUARTERS_IN : STR_ERROR_OBJECT_IN_THE_WAY);
512 } else if (_game_mode == GM_EDITOR) {
513 /* No further limitations for the editor. */
514 } else if (GetTileOwner(tile) == OWNER_NONE) {
515 /* Owned by nobody and unremovable, so we can only remove it with brute force! */
516 if (!_cheats.magic_bulldozer.value && (spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0) return CommandError();
517 } else if (CheckTileOwnership(tile).Failed()) {
518 /* We don't own it!. */
519 return CommandError(STR_ERROR_OWNED_BY);
520 } else if ((spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0 && (spec->flags & OBJECT_FLAG_AUTOREMOVE) == 0) {
521 /* In the game editor or with cheats we can remove, otherwise we can't. */
522 if (!_cheats.magic_bulldozer.value) return CommandError();
524 /* Removing with the cheat costs more in TTDPatch / the specs. */
525 cost.MultiplyCost(25);
527 } else if ((spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0) {
528 /* Water can't remove objects that are buildable on water. */
529 return CommandError();
532 switch (type) {
533 case OBJECT_HQ: {
534 Company *c = Company::Get(GetTileOwner(tile));
535 if (flags & DC_EXEC) {
536 c->location_of_HQ = INVALID_TILE; // reset HQ position
537 SetWindowDirty(WC_COMPANY, c->index);
538 CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS, c->index);
541 /* cost of relocating company is 1% of company value */
542 cost = CommandCost(EXPENSES_PROPERTY, CalculateCompanyValue(c) / 100);
543 break;
546 case OBJECT_STATUE:
547 if (flags & DC_EXEC) {
548 Town *town = o->town;
549 ClrBit(town->statues, GetTileOwner(tile));
550 SetWindowDirty(WC_TOWN_AUTHORITY, town->index);
552 break;
554 default:
555 break;
558 ClearedObjectArea *cleared_area = _cleared_object_areas.Append();
559 cleared_area->first_tile = tile;
560 cleared_area->area = ta;
562 if (flags & DC_EXEC) ReallyClearObjectTile(o);
564 return cost;
567 static void AddAcceptedCargo_Object(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
569 if (!IsObjectType(tile, OBJECT_HQ)) return;
571 /* HQ accepts passenger and mail; but we have to divide the values
572 * between 4 tiles it occupies! */
574 /* HQ level (depends on company performance) in the range 1..5. */
575 uint level = GetCompanyHQSize(tile) + 1;
577 /* Top town building generates 10, so to make HQ interesting, the top
578 * type makes 20. */
579 acceptance[CT_PASSENGERS] += max(1U, level);
580 SetBit(*always_accepted, CT_PASSENGERS);
582 /* Top town building generates 4, HQ can make up to 8. The
583 * proportion passengers:mail is different because such a huge
584 * commercial building generates unusually high amount of mail
585 * correspondence per physical visitor. */
586 acceptance[CT_MAIL] += max(1U, level / 2);
587 SetBit(*always_accepted, CT_MAIL);
591 static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
593 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
594 td->str = spec->name;
595 td->owner[0] = GetTileOwner(tile);
596 td->build_date = Object::GetByTile(tile)->build_date;
598 if (spec->grf_prop.grffile != nullptr) {
599 td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
603 static void TileLoop_Object(TileIndex tile)
605 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
606 if (spec->flags & OBJECT_FLAG_ANIMATION) {
607 Object *o = Object::GetByTile(tile);
608 TriggerObjectTileAnimation(o, tile, OAT_TILELOOP, spec);
609 if (o->location.tile == tile) TriggerObjectAnimation(o, OAT_256_TICKS, spec);
612 if (IsTileOnWater(tile)) TileLoop_Water(tile);
614 if (!IsObjectType(tile, OBJECT_HQ)) return;
616 /* HQ accepts passenger and mail; but we have to divide the values
617 * between 4 tiles it occupies! */
619 /* HQ level (depends on company performance) in the range 1..5. */
620 uint level = GetCompanyHQSize(tile) + 1;
621 assert(level < 6);
623 StationFinder stations(TileArea(tile, 2, 2));
625 uint r = Random();
626 /* Top town buildings generate 250, so the top HQ type makes 256. */
627 if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
628 uint amt = GB(r, 0, 8) / 8 / 4 + 1;
629 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
630 MoveGoodsToStation(CT_PASSENGERS, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
633 /* Top town building generates 90, HQ can make up to 196. The
634 * proportion passengers:mail is about the same as in the acceptance
635 * equations. */
636 if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
637 uint amt = GB(r, 8, 8) / 8 / 4 + 1;
638 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
639 MoveGoodsToStation(CT_MAIL, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
644 static TrackStatus GetTileTrackStatus_Object(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
646 return 0;
649 static bool ClickTile_Object(TileIndex tile)
651 if (!IsObjectType(tile, OBJECT_HQ)) return false;
653 ShowCompany(GetTileOwner(tile));
654 return true;
657 static void AnimateTile_Object(TileIndex tile)
659 AnimateNewObjectTile(tile);
663 * Helper function for \c CircularTileSearch.
664 * @param tile The tile to check.
665 * @param user Ignored.
666 * @return True iff the tile has a radio tower.
668 static bool HasTransmitter(TileIndex tile, void *user)
670 return IsObjectTypeTile(tile, OBJECT_TRANSMITTER);
674 * Try to build a lighthouse.
675 * @return True iff building a lighthouse succeeded.
677 static bool TryBuildLightHouse()
679 uint maxx = MapMaxX();
680 uint maxy = MapMaxY();
681 uint r = Random();
683 /* Scatter the lighthouses more evenly around the perimeter */
684 int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
685 DiagDirection dir;
686 for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
687 perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
690 TileIndex tile;
691 switch (dir) {
692 default:
693 case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
694 case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
695 case DIAGDIR_SW: tile = TileXY(1, r % maxy); break;
696 case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
699 /* Only build lighthouses at tiles where the border is sea. */
700 if (!IsTileType(tile, MP_WATER)) return false;
702 for (int j = 0; j < 19; j++) {
703 int h;
704 if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h <= 2 && !IsBridgeAbove(tile)) {
705 BuildObject(OBJECT_LIGHTHOUSE, tile);
706 assert(tile < MapSize());
707 return true;
709 tile += TileOffsByDiagDir(dir);
710 if (!IsValidTile(tile)) return false;
712 return false;
716 * Try to build a transmitter.
717 * @return True iff a transmitter was built.
719 static bool TryBuildTransmitter()
721 TileIndex tile = RandomTile();
722 int h;
723 if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h >= 4 && !IsBridgeAbove(tile)) {
724 TileIndex t = tile;
725 if (CircularTileSearch(&t, 9, HasTransmitter, nullptr)) return false;
727 BuildObject(OBJECT_TRANSMITTER, tile);
728 return true;
730 return false;
733 void GenerateObjects()
735 /* Set a guestimate on how much we progress */
736 SetGeneratingWorldProgress(GWP_OBJECT, NUM_OBJECTS);
738 /* Determine number of water tiles at map border needed for freeform_edges */
739 uint num_water_tiles = 0;
740 if (_settings_game.construction.freeform_edges) {
741 for (uint x = 0; x < MapMaxX(); x++) {
742 if (IsTileType(TileXY(x, 1), MP_WATER)) num_water_tiles++;
743 if (IsTileType(TileXY(x, MapMaxY() - 1), MP_WATER)) num_water_tiles++;
745 for (uint y = 1; y < MapMaxY() - 1; y++) {
746 if (IsTileType(TileXY(1, y), MP_WATER)) num_water_tiles++;
747 if (IsTileType(TileXY(MapMaxX() - 1, y), MP_WATER)) num_water_tiles++;
751 /* Iterate over all possible object types */
752 for (uint i = 0; i < NUM_OBJECTS; i++) {
753 const ObjectSpec *spec = ObjectSpec::Get(i);
755 /* Continue, if the object was never available till now or shall not be placed */
756 if (!spec->WasEverAvailable() || spec->generate_amount == 0) continue;
758 uint16 amount = spec->generate_amount;
760 /* Scale by map size */
761 if ((spec->flags & OBJECT_FLAG_SCALE_BY_WATER) && _settings_game.construction.freeform_edges) {
762 /* Scale the amount of lighthouses with the amount of land at the borders.
763 * The -6 is because the top borders are MP_VOID (-2) and all corners
764 * are counted twice (-4). */
765 amount = ScaleByMapSize1D(amount * num_water_tiles) / (2 * MapMaxY() + 2 * MapMaxX() - 6);
766 } else if (spec->flags & OBJECT_FLAG_SCALE_BY_WATER) {
767 amount = ScaleByMapSize1D(amount);
768 } else {
769 amount = ScaleByMapSize(amount);
772 if ((i == OBJECT_TRANSMITTER) || (i == OBJECT_LIGHTHOUSE)) {
773 amount /= 10;
776 /* Now try to place the requested amount of this object */
777 for (uint j = ScaleByMapSize(1000); j != 0 && amount != 0 && Object::CanAllocateItem(); j--) {
778 switch (i) {
779 case OBJECT_TRANSMITTER:
780 if (TryBuildTransmitter()) amount--;
781 break;
783 case OBJECT_LIGHTHOUSE:
784 if (TryBuildLightHouse()) amount--;
785 break;
787 default:
788 uint8 view = RandomRange(spec->views);
789 if (CmdBuildObject(RandomTile(), DC_EXEC | DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, i, view, nullptr).Succeeded()) amount--;
790 break;
793 IncreaseGeneratingWorldProgress(GWP_OBJECT);
797 static void ChangeTileOwner_Object(TileIndex tile, Owner old_owner, Owner new_owner)
799 if (!IsTileOwner(tile, old_owner)) return;
801 bool do_clear = false;
803 if (IsObjectType(tile, OBJECT_OWNED_LAND) && new_owner != INVALID_OWNER) {
804 SetTileOwner(tile, new_owner);
805 } else if (IsObjectType(tile, OBJECT_STATUE)) {
806 Town *t = Object::GetByTile(tile)->town;
807 ClrBit(t->statues, old_owner);
808 if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
809 /* Transfer ownership to the new company */
810 SetBit(t->statues, new_owner);
811 SetTileOwner(tile, new_owner);
812 } else {
813 do_clear = true;
816 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
817 } else {
818 do_clear = true;
821 if (do_clear) {
822 ReallyClearObjectTile(Object::GetByTile(tile));
823 /* When clearing objects, they may turn into canal, which may require transfering ownership. */
824 ChangeTileOwner(tile, old_owner, new_owner);
828 static CommandCost TerraformTile_Object(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
830 ObjectType type = GetObjectType(tile);
832 if (type == OBJECT_OWNED_LAND) {
833 /* Owned land remains unsold */
834 CommandCost ret = CheckTileOwnership(tile);
835 if (ret.Succeeded()) return CommandCost();
836 } else if (AutoslopeEnabled() && type != OBJECT_TRANSMITTER && type != OBJECT_LIGHTHOUSE) {
837 /* Behaviour:
838 * - Both new and old slope must not be steep.
839 * - TileMaxZ must not be changed.
840 * - Allow autoslope by default.
841 * - Disallow autoslope if callback succeeds and returns non-zero.
843 Slope tileh_old = GetTileSlope(tile);
844 /* TileMaxZ must not be changed. Slopes must not be steep. */
845 if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
846 const ObjectSpec *spec = ObjectSpec::Get(type);
848 /* Call callback 'disable autosloping for objects'. */
849 if (HasBit(spec->callback_mask, CBM_OBJ_AUTOSLOPE)) {
850 /* If the callback fails, allow autoslope. */
851 uint16 res = GetObjectCallback(CBID_OBJECT_AUTOSLOPE, 0, 0, spec, Object::GetByTile(tile), tile);
852 if (res == CALLBACK_FAILED || !ConvertBooleanCallback(spec->grf_prop.grffile, CBID_OBJECT_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
853 } else if (spec->enabled) {
854 /* allow autoslope */
855 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
860 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
863 extern const TileTypeProcs _tile_type_object_procs = {
864 DrawTile_Object, // draw_tile_proc
865 GetSlopePixelZ_Object, // get_slope_z_proc
866 ClearTile_Object, // clear_tile_proc
867 AddAcceptedCargo_Object, // add_accepted_cargo_proc
868 GetTileDesc_Object, // get_tile_desc_proc
869 GetTileTrackStatus_Object, // get_tile_track_status_proc
870 ClickTile_Object, // click_tile_proc
871 AnimateTile_Object, // animate_tile_proc
872 TileLoop_Object, // tile_loop_proc
873 ChangeTileOwner_Object, // change_tile_owner_proc
874 nullptr, // add_produced_cargo_proc
875 nullptr, // vehicle_enter_tile_proc
876 GetFoundation_Object, // get_foundation_proc
877 TerraformTile_Object, // terraform_tile_proc