Move lighthouse generation to its own function
[openttd/fttd.git] / src / object_cmd.cpp
blobc77e5d88eb128c5de45ee876c4d4d8d4752a7a18
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.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 "map/object.h"
31 #include "map/bridge.h"
32 #include "object_base.h"
33 #include "newgrf_config.h"
34 #include "newgrf_object.h"
35 #include "date_func.h"
36 #include "newgrf_debug.h"
37 #include "vehicle_func.h"
39 #include "table/strings.h"
40 #include "table/object_land.h"
42 ObjectPool _object_pool("Object");
43 INSTANTIATE_POOL_METHODS(Object)
44 uint16 Object::counts[NUM_OBJECTS];
46 /**
47 * Get the object associated with a tile.
48 * @param tile The tile to fetch the object for.
49 * @return The object.
51 /* static */ Object *Object::GetByTile(TileIndex tile)
53 return Object::Get(GetObjectIndex(tile));
56 /**
57 * Gets the ObjectType of the given object tile
58 * @param t the tile to get the type from.
59 * @pre IsObjectTile(t)
60 * @return the type.
62 ObjectType GetObjectType(TileIndex t)
64 assert(IsObjectTile(t));
65 return Object::GetByTile(t)->type;
68 /** Initialize/reset the objects. */
69 void InitializeObjects()
71 Object::ResetTypeCounts();
74 /**
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();
90 o->type = type;
91 o->location = ta;
92 o->town = town == NULL ? CalcClosestTownFromTile(tile) : town;
93 o->build_date = _date;
94 o->view = view;
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) {
99 o->colour = Random();
100 } else {
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 != NULL);
118 TILE_AREA_LOOP(t, ta) {
119 WaterClass wc = (IsPlainWaterTile(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 MakeObject(t, owner, o->index, wc, Random());
126 MarkTileDirtyByTile(t);
129 Object::IncTypeCount(type);
130 if (spec->flags & OBJECT_FLAG_ANIMATION) TriggerObjectAnimation(o, OAT_BUILT, spec);
134 * Increase the animation stage of a whole structure.
135 * @param tile The tile of the structure.
137 static void IncreaseAnimationStage(TileIndex tile)
139 TileArea ta = Object::GetByTile(tile)->location;
140 TILE_AREA_LOOP(t, ta) {
141 SetAnimationFrame(t, GetAnimationFrame(t) + 1);
142 MarkTileDirtyByTile(t);
146 /** We encode the company HQ size in the animation stage. */
147 #define GetCompanyHQSize GetAnimationFrame
148 /** We encode the company HQ size in the animation stage. */
149 #define IncreaseCompanyHQSize IncreaseAnimationStage
152 * Update the CompanyHQ to the state associated with the given score
153 * @param tile The (northern) tile of the company HQ, or INVALID_TILE.
154 * @param score The current (performance) score of the company.
156 void UpdateCompanyHQ(TileIndex tile, uint score)
158 if (tile == INVALID_TILE) return;
160 byte val;
161 (val = 0, score < 170) ||
162 (val++, score < 350) ||
163 (val++, score < 520) ||
164 (val++, score < 720) ||
165 (val++, true);
167 while (GetCompanyHQSize(tile) < val) {
168 IncreaseCompanyHQSize(tile);
173 * Updates the colour of the object whenever a company changes.
174 * @param c The company the company colour changed of.
176 void UpdateObjectColours(const Company *c)
178 Object *obj;
179 FOR_ALL_OBJECTS(obj) {
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
202 * @param text unused
203 * @return the cost of this operation or an error
205 CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
207 CommandCost cost(EXPENSES_PROPERTY);
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 (!spec->IsAvailable()) return CMD_ERROR;
215 if (spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT && (_game_mode != GM_EDITOR || _current_company != OWNER_NONE)) return CMD_ERROR;
216 if (spec->flags & OBJECT_FLAG_ONLY_IN_GAME && (_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);
226 if (type == OBJECT_OWNED_LAND) {
227 /* Owned land is special as it can be placed on any slope. */
228 cost.AddCost(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR));
229 } else {
230 /* Check the surface to build on. At this time we can't actually execute the
231 * the CLEAR_TILE commands since the newgrf callback later on can check
232 * some information about the tiles. */
233 bool allow_water = (spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0;
234 bool allow_ground = (spec->flags & OBJECT_FLAG_NOT_ON_LAND) == 0;
235 TILE_AREA_LOOP(t, ta) {
236 if (HasTileWaterGround(t)) {
237 if (!allow_water) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
238 if (!IsPlainWaterTile(t)) {
239 /* Normal water tiles don't have to be cleared. For all other tile types clear
240 * the tile but leave the water. */
241 cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_NO_WATER & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
242 } else {
243 /* Can't build on water owned by another company. */
244 Owner o = GetTileOwner(t);
245 if (o != OWNER_NONE && o != OWNER_WATER) cost.AddCost(CheckOwnership(o, t));
247 /* However, the tile has to be clear of vehicles. */
248 cost.AddCost(EnsureNoVehicleOnGround(t));
250 } else {
251 if (!allow_ground) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER);
252 /* For non-water tiles, we'll have to clear it before building. */
253 cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
257 /* So, now the surface is checked... check the slope of said surface. */
258 int allowed_z;
259 if (GetTileSlope(tile, &allowed_z) != SLOPE_FLAT) allowed_z++;
261 TILE_AREA_LOOP(t, ta) {
262 uint16 callback = CALLBACK_FAILED;
263 if (HasBit(spec->callback_mask, CBM_OBJ_SLOPE_CHECK)) {
264 TileIndex diff = t - tile;
265 callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t), TileY(diff) << 4 | TileX(diff), spec, NULL, t, view);
268 if (callback == CALLBACK_FAILED) {
269 cost.AddCost(CheckBuildableTile(t, 0, allowed_z, false, false));
270 } else {
271 /* The meaning of bit 10 is inverted for a grf version < 8. */
272 if (spec->grf_prop.grffile->grf_version < 8) ToggleBit(callback, 10);
273 CommandCost ret = GetErrorMessageFromLocationCallbackResult(callback, spec->grf_prop.grffile->grfid, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
274 if (ret.Failed()) return ret;
278 if (flags & DC_EXEC) {
279 /* This is basically a copy of the loop above with the exception that we now
280 * execute the commands and don't check for errors, since that's already done. */
281 TILE_AREA_LOOP(t, ta) {
282 if (HasTileWaterGround(t)) {
283 if (!IsPlainWaterTile(t)) {
284 DoCommand(t, 0, 0, (flags & ~DC_NO_WATER) | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
286 } else {
287 DoCommand(t, 0, 0, flags | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
292 if (cost.Failed()) return cost;
294 /* Finally do a check for bridges. */
295 TILE_AREA_LOOP(t, ta) {
296 if (HasBridgeAbove(t) && (
297 !(spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) ||
298 (GetTileMaxZ(t) + spec->height >= GetBridgeHeight(GetSouthernBridgeEnd(t))))) {
299 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
303 int hq_score = 0;
304 switch (type) {
305 case OBJECT_TRANSMITTER:
306 case OBJECT_LIGHTHOUSE:
307 if (!IsTileFlat(tile)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
308 break;
310 case OBJECT_OWNED_LAND:
311 if (IsObjectTile(tile) &&
312 IsTileOwner(tile, _current_company) &&
313 IsObjectType(tile, OBJECT_OWNED_LAND)) {
314 return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT);
316 break;
318 case OBJECT_HQ: {
319 Company *c = Company::Get(_current_company);
320 if (c->location_of_HQ != INVALID_TILE) {
321 /* We need to persuade a bit harder to remove the old HQ. */
322 _current_company = OWNER_WATER;
323 cost.AddCost(ClearTile_Object(c->location_of_HQ, flags));
324 _current_company = c->index;
327 if (flags & DC_EXEC) {
328 hq_score = UpdateCompanyRatingAndValue(c, false);
329 c->location_of_HQ = tile;
330 SetWindowDirty(WC_COMPANY, c->index);
332 break;
335 case OBJECT_STATUE:
336 /* This may never be constructed using this method. */
337 return CMD_ERROR;
339 default: // i.e. NewGRF provided.
340 break;
343 if (flags & DC_EXEC) {
344 BuildObject(type, tile, _current_company, NULL, view);
346 /* Make sure the HQ starts at the right size. */
347 if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
350 cost.AddCost(ObjectSpec::Get(type)->GetBuildCost() * size_x * size_y);
351 return cost;
355 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh);
357 static void DrawTile_Object(TileInfo *ti)
359 ObjectType type = GetObjectType(ti->tile);
360 const ObjectSpec *spec = ObjectSpec::Get(type);
362 /* Fall back for when the object doesn't exist anymore. */
363 if (!spec->enabled) type = OBJECT_TRANSMITTER;
365 if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
367 if (type < NEW_OBJECT_OFFSET) {
368 const DrawTileSprites *dts = NULL;
369 Owner to = GetTileOwner(ti->tile);
370 PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
372 if (type == OBJECT_HQ) {
373 TileIndex diff = ti->tile - Object::GetByTile(ti->tile)->location.tile;
374 dts = &_object_hq[GetCompanyHQSize(ti->tile) << 2 | TileY(diff) << 1 | TileX(diff)];
375 } else {
376 dts = &_objects[type];
379 if (spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) {
380 /* If an object has no foundation, but tries to draw a (flat) ground
381 * type... we have to be nice and convert that for them. */
382 switch (dts->ground.sprite) {
383 case SPR_FLAT_BARE_LAND: DrawClearLandTile(ti, 0); break;
384 case SPR_FLAT_1_THIRD_GRASS_TILE: DrawClearLandTile(ti, 1); break;
385 case SPR_FLAT_2_THIRD_GRASS_TILE: DrawClearLandTile(ti, 2); break;
386 case SPR_FLAT_GRASS_TILE: DrawClearLandTile(ti, 3); break;
387 default: DrawGroundSprite(dts->ground.sprite, palette); break;
389 } else {
390 DrawGroundSprite(dts->ground.sprite, palette);
393 if (!IsInvisibilitySet(TO_STRUCTURES)) {
394 const DrawTileSeqStruct *dtss;
395 foreach_draw_tile_seq(dtss, dts->seq) {
396 AddSortableSpriteToDraw(
397 dtss->image.sprite, palette,
398 ti->x + dtss->delta_x, ti->y + dtss->delta_y,
399 dtss->size_x, dtss->size_y,
400 dtss->size_z, ti->z + dtss->delta_z,
401 IsTransparencySet(TO_STRUCTURES)
405 } else {
406 DrawNewObjectTile(ti, spec);
409 DrawBridgeMiddle(ti);
412 static int GetSlopePixelZ_Object(TileIndex tile, uint x, uint y)
414 if (IsObjectType(tile, OBJECT_OWNED_LAND)) {
415 int z;
416 Slope tileh = GetTilePixelSlope(tile, &z);
418 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
419 } else {
420 return GetTileMaxPixelZ(tile);
424 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh)
426 return IsObjectType(tile, OBJECT_OWNED_LAND) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
430 * Perform the actual removal of the object from the map.
431 * @param o The object to really clear.
433 static void ReallyClearObjectTile(Object *o)
435 Object::DecTypeCount(o->type);
436 TILE_AREA_LOOP(tile_cur, o->location) {
437 DeleteNewGRFInspectWindow(GSF_OBJECTS, tile_cur);
439 MakeWaterKeepingClass(tile_cur, GetTileOwner(tile_cur));
441 delete o;
444 SmallVector<ClearedObjectArea, 4> _cleared_object_areas;
447 * Find the entry in _cleared_object_areas which occupies a certain tile.
448 * @param tile Tile of interest
449 * @return Occupying entry, or NULL if none
451 ClearedObjectArea *FindClearedObject(TileIndex tile)
453 TileArea ta = TileArea(tile, 1, 1);
455 const ClearedObjectArea *end = _cleared_object_areas.End();
456 for (ClearedObjectArea *coa = _cleared_object_areas.Begin(); coa != end; coa++) {
457 if (coa->area.Intersects(ta)) return coa;
460 return NULL;
463 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
465 /* Get to the northern most tile. */
466 Object *o = Object::GetByTile(tile);
467 TileArea ta = o->location;
469 ObjectType type = o->type;
470 const ObjectSpec *spec = ObjectSpec::Get(type);
472 CommandCost cost(EXPENSES_CONSTRUCTION, spec->GetClearCost() * ta.w * ta.h / 5);
473 if (spec->flags & OBJECT_FLAG_CLEAR_INCOME) cost.MultiplyCost(-1); // They get an income!
475 /* Towns can't remove any objects. */
476 if (_current_company == OWNER_TOWN) return CMD_ERROR;
478 /* Water can remove everything! */
479 if (_current_company != OWNER_WATER) {
480 if ((flags & DC_NO_WATER) && IsTileOnWater(tile)) {
481 /* There is water under the object, treat it as water tile. */
482 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
483 } else if (!(spec->flags & OBJECT_FLAG_AUTOREMOVE) && (flags & DC_AUTO)) {
484 /* No automatic removal by overbuilding stuff. */
485 return_cmd_error(type == OBJECT_HQ ? STR_ERROR_COMPANY_HEADQUARTERS_IN : STR_ERROR_OBJECT_IN_THE_WAY);
486 } else if (_game_mode == GM_EDITOR) {
487 /* No further limitations for the editor. */
488 } else if (GetTileOwner(tile) == OWNER_NONE) {
489 /* Owned by nobody, so we can only remove it with brute force! */
490 if (!_cheats.magic_bulldozer.value) return CMD_ERROR;
491 } else if (CheckTileOwnership(tile).Failed()) {
492 /* We don't own it!. */
493 return_cmd_error(STR_ERROR_OWNED_BY);
494 } else if ((spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0 && (spec->flags & OBJECT_FLAG_AUTOREMOVE) == 0) {
495 /* In the game editor or with cheats we can remove, otherwise we can't. */
496 if (!_cheats.magic_bulldozer.value) return CMD_ERROR;
498 /* Removing with the cheat costs more in TTDPatch / the specs. */
499 cost.MultiplyCost(25);
501 } else if ((spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0) {
502 /* Water can't remove objects that are buildable on water. */
503 return CMD_ERROR;
506 switch (type) {
507 case OBJECT_HQ: {
508 Company *c = Company::Get(GetTileOwner(tile));
509 if (flags & DC_EXEC) {
510 c->location_of_HQ = INVALID_TILE; // reset HQ position
511 SetWindowDirty(WC_COMPANY, c->index);
512 CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS, c->index);
515 /* cost of relocating company is 1% of company value */
516 cost = CommandCost(EXPENSES_PROPERTY, CalculateCompanyValue(c) / 100);
517 break;
520 case OBJECT_STATUE:
521 if (flags & DC_EXEC) {
522 Town *town = o->town;
523 ClrBit(town->statues, GetTileOwner(tile));
524 SetWindowDirty(WC_TOWN_AUTHORITY, town->index);
526 break;
528 default:
529 break;
532 ClearedObjectArea *cleared_area = _cleared_object_areas.Append();
533 cleared_area->first_tile = tile;
534 cleared_area->area = ta;
536 if (flags & DC_EXEC) ReallyClearObjectTile(o);
538 return cost;
541 static void AddAcceptedCargo_Object(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
543 if (!IsObjectType(tile, OBJECT_HQ)) return;
545 /* HQ accepts passenger and mail; but we have to divide the values
546 * between 4 tiles it occupies! */
548 /* HQ level (depends on company performance) in the range 1..5. */
549 uint level = GetCompanyHQSize(tile) + 1;
551 /* Top town building generates 10, so to make HQ interesting, the top
552 * type makes 20. */
553 acceptance[CT_PASSENGERS] += max(1U, level);
554 SetBit(*always_accepted, CT_PASSENGERS);
556 /* Top town building generates 4, HQ can make up to 8. The
557 * proportion passengers:mail is different because such a huge
558 * commercial building generates unusually high amount of mail
559 * correspondence per physical visitor. */
560 acceptance[CT_MAIL] += max(1U, level / 2);
561 SetBit(*always_accepted, CT_MAIL);
565 static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
567 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
568 td->str = spec->name;
569 td->owner[0] = GetTileOwner(tile);
570 td->build_date = Object::GetByTile(tile)->build_date;
572 if (spec->grf_prop.grffile != NULL) {
573 td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
577 static void TileLoop_Object(TileIndex tile)
579 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
580 if (spec->flags & OBJECT_FLAG_ANIMATION) {
581 Object *o = Object::GetByTile(tile);
582 TriggerObjectTileAnimation(o, tile, OAT_TILELOOP, spec);
583 if (o->location.tile == tile) TriggerObjectAnimation(o, OAT_256_TICKS, spec);
586 if (IsTileOnWater(tile)) TileLoop_Water(tile);
588 if (!IsObjectType(tile, OBJECT_HQ)) return;
590 /* HQ accepts passenger and mail; but we have to divide the values
591 * between 4 tiles it occupies! */
593 /* HQ level (depends on company performance) in the range 1..5. */
594 uint level = GetCompanyHQSize(tile) + 1;
595 assert(level < 6);
597 StationFinder stations(TileArea(tile, 2, 2));
599 uint r = Random();
600 /* Top town buildings generate 250, so the top HQ type makes 256. */
601 if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
602 uint amt = GB(r, 0, 8) / 8 / 4 + 1;
603 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
604 MoveGoodsToStation(CT_PASSENGERS, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
607 /* Top town building generates 90, HQ can make up to 196. The
608 * proportion passengers:mail is about the same as in the acceptance
609 * equations. */
610 if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
611 uint amt = GB(r, 8, 8) / 8 / 4 + 1;
612 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
613 MoveGoodsToStation(CT_MAIL, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
618 static bool ClickTile_Object(TileIndex tile)
620 if (!IsObjectType(tile, OBJECT_HQ)) return false;
622 ShowCompany(GetTileOwner(tile));
623 return true;
626 static void AnimateTile_Object(TileIndex tile)
628 AnimateNewObjectTile(tile);
632 * Helper function for \c CircularTileSearch.
633 * @param tile The tile to check.
634 * @param user Ignored.
635 * @return True iff the tile has a radio tower.
637 static bool HasTransmitter(TileIndex tile, void *user)
639 return IsObjectTypeTile(tile, OBJECT_TRANSMITTER);
643 * Try to build a lighthouse.
644 * @return True iff building a lighthouse succeeded.
646 static bool TryBuildLightHouse()
648 uint maxx = MapMaxX();
649 uint maxy = MapMaxY();
650 uint r = Random();
652 /* Scatter the lighthouses more evenly around the perimeter */
653 int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
654 DiagDirection dir;
655 for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
656 perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
659 TileIndex tile;
660 switch (dir) {
661 default:
662 case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
663 case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
664 case DIAGDIR_SW: tile = TileXY(1, r % maxy); break;
665 case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
668 /* Only build lighthouses at tiles where the border is sea. */
669 if (!IsWaterTile(tile)) return false;
671 for (int j = 0; j < 19; j++) {
672 int h;
673 if (IsGroundTile(tile) && IsTileFlat(tile, &h) && h <= 2 && !IsBridgeAbove(tile)) {
674 BuildObject(OBJECT_LIGHTHOUSE, tile);
675 assert(tile < MapSize());
676 return true;
678 tile += TileOffsByDiagDir(dir);
679 if (!IsValidTile(tile)) return false;
681 return false;
685 * Try to build a transmitter.
686 * @return True iff a transmitter was built.
688 static bool TryBuildTransmitter()
690 TileIndex tile = RandomTile();
691 int h;
692 if (IsGroundTile(tile) && IsTileFlat(tile, &h) && h >= 4 && !IsBridgeAbove(tile)) {
693 TileIndex t = tile;
694 if (CircularTileSearch(&t, 9, HasTransmitter, NULL)) return false;
696 BuildObject(OBJECT_TRANSMITTER, tile);
697 return true;
699 return false;
702 void GenerateObjects()
704 if (_settings_game.game_creation.landscape == LT_TOYLAND) return;
706 /* add radio tower */
707 int radiotower_to_build = ScaleByMapSize(15); // maximum number of radio towers on the map
708 int lighthouses_to_build = _settings_game.game_creation.landscape == LT_TROPIC ? 0 : ScaleByMapSize1D((Random() & 3) + 7);
710 /* Scale the amount of lighthouses with the amount of land at the borders. */
711 if (_settings_game.construction.freeform_edges && lighthouses_to_build != 0) {
712 uint num_water_tiles = 0;
713 for (uint x = 0; x < MapMaxX(); x++) {
714 if (IsWaterTile(TileXY(x, 1))) num_water_tiles++;
715 if (IsWaterTile(TileXY(x, MapMaxY() - 1))) num_water_tiles++;
717 for (uint y = 1; y < MapMaxY() - 1; y++) {
718 if (IsWaterTile(TileXY(1, y))) num_water_tiles++;
719 if (IsWaterTile(TileXY(MapMaxX() - 1, y))) num_water_tiles++;
721 /* The -6 is because the top borders are void (-2) and all corners
722 * are counted twice (-4). */
723 lighthouses_to_build = lighthouses_to_build * num_water_tiles / (2 * MapMaxY() + 2 * MapMaxX() - 6);
726 SetGeneratingWorldProgress(GWP_OBJECT, radiotower_to_build + lighthouses_to_build);
728 for (uint i = ScaleByMapSize(1000); i != 0 && Object::CanAllocateItem(); i--) {
729 if (!TryBuildTransmitter()) continue;
730 IncreaseGeneratingWorldProgress(GWP_OBJECT);
731 if (--radiotower_to_build == 0) break;
734 /* add lighthouses */
735 for (int loop_count = 0; loop_count < 1000 && lighthouses_to_build != 0 && Object::CanAllocateItem(); loop_count++) {
736 if (!TryBuildLightHouse()) continue;
737 IncreaseGeneratingWorldProgress(GWP_OBJECT);
738 lighthouses_to_build--;
742 static void ChangeTileOwner_Object(TileIndex tile, Owner old_owner, Owner new_owner)
744 if (!IsTileOwner(tile, old_owner)) return;
746 if (IsObjectType(tile, OBJECT_OWNED_LAND) && new_owner != INVALID_OWNER) {
747 SetTileOwner(tile, new_owner);
748 } else if (IsObjectType(tile, OBJECT_STATUE)) {
749 Town *t = Object::GetByTile(tile)->town;
750 ClrBit(t->statues, old_owner);
751 if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
752 /* Transfer ownership to the new company */
753 SetBit(t->statues, new_owner);
754 SetTileOwner(tile, new_owner);
755 } else {
756 ReallyClearObjectTile(Object::GetByTile(tile));
759 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
760 } else {
761 ReallyClearObjectTile(Object::GetByTile(tile));
765 static CommandCost TerraformTile_Object(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
767 ObjectType type = GetObjectType(tile);
769 if (type == OBJECT_OWNED_LAND) {
770 /* Owned land remains unsold */
771 CommandCost ret = CheckTileOwnership(tile);
772 if (ret.Succeeded()) return CommandCost();
773 } else if (AutoslopeEnabled() && type != OBJECT_TRANSMITTER && type != OBJECT_LIGHTHOUSE) {
774 /* Behaviour:
775 * - Both new and old slope must not be steep.
776 * - TileMaxZ must not be changed.
777 * - Allow autoslope by default.
778 * - Disallow autoslope if callback succeeds and returns non-zero.
780 Slope tileh_old = GetTileSlope(tile);
781 /* TileMaxZ must not be changed. Slopes must not be steep. */
782 if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
783 const ObjectSpec *spec = ObjectSpec::Get(type);
785 /* Call callback 'disable autosloping for objects'. */
786 if (HasBit(spec->callback_mask, CBM_OBJ_AUTOSLOPE)) {
787 /* If the callback fails, allow autoslope. */
788 uint16 res = GetObjectCallback(CBID_OBJECT_AUTOSLOPE, 0, 0, spec, Object::GetByTile(tile), tile);
789 if (res == CALLBACK_FAILED || !ConvertBooleanCallback(spec->grf_prop.grffile, CBID_OBJECT_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
790 } else if (spec->enabled) {
791 /* allow autoslope */
792 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
797 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
800 extern const TileTypeProcs _tile_type_object_procs = {
801 DrawTile_Object, // draw_tile_proc
802 GetSlopePixelZ_Object, // get_slope_z_proc
803 ClearTile_Object, // clear_tile_proc
804 AddAcceptedCargo_Object, // add_accepted_cargo_proc
805 GetTileDesc_Object, // get_tile_desc_proc
806 NULL, // get_tile_railway_status_proc
807 NULL, // get_tile_road_status_proc
808 NULL, // get_tile_waterway_status_proc
809 ClickTile_Object, // click_tile_proc
810 AnimateTile_Object, // animate_tile_proc
811 TileLoop_Object, // tile_loop_proc
812 ChangeTileOwner_Object, // change_tile_owner_proc
813 NULL, // add_produced_cargo_proc
814 GetFoundation_Object, // get_foundation_proc
815 TerraformTile_Object, // terraform_tile_proc