Fix #9867: Industry::stations_near not filled at industry creation
[openttd-github.git] / src / industry_cmd.cpp
blob385a952b607742d21af5e3a30e1a3f29225dae1b
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 industry_cmd.cpp Handling of industry tiles. */
10 #include "stdafx.h"
11 #include "clear_map.h"
12 #include "industry.h"
13 #include "station_base.h"
14 #include "landscape.h"
15 #include "viewport_func.h"
16 #include "command_func.h"
17 #include "town.h"
18 #include "news_func.h"
19 #include "cheat_type.h"
20 #include "company_base.h"
21 #include "genworld.h"
22 #include "tree_map.h"
23 #include "newgrf_cargo.h"
24 #include "newgrf_debug.h"
25 #include "newgrf_industrytiles.h"
26 #include "autoslope.h"
27 #include "water.h"
28 #include "strings_func.h"
29 #include "window_func.h"
30 #include "date_func.h"
31 #include "vehicle_func.h"
32 #include "sound_func.h"
33 #include "animated_tile_func.h"
34 #include "effectvehicle_func.h"
35 #include "effectvehicle_base.h"
36 #include "ai/ai.hpp"
37 #include "core/pool_func.hpp"
38 #include "subsidy_func.h"
39 #include "core/backup_type.hpp"
40 #include "object_base.h"
41 #include "game/game.hpp"
42 #include "error.h"
43 #include "string_func.h"
44 #include "industry_cmd.h"
45 #include "landscape_cmd.h"
46 #include "terraform_cmd.h"
48 #include "table/strings.h"
49 #include "table/industry_land.h"
50 #include "table/build_industry.h"
52 #include "safeguards.h"
54 IndustryPool _industry_pool("Industry");
55 INSTANTIATE_POOL_METHODS(Industry)
57 void ShowIndustryViewWindow(int industry);
58 void BuildOilRig(TileIndex tile);
60 static byte _industry_sound_ctr;
61 static TileIndex _industry_sound_tile;
63 uint16 Industry::counts[NUM_INDUSTRYTYPES];
65 IndustrySpec _industry_specs[NUM_INDUSTRYTYPES];
66 IndustryTileSpec _industry_tile_specs[NUM_INDUSTRYTILES];
67 IndustryBuildData _industry_builder; ///< In-game manager of industries.
69 /**
70 * This function initialize the spec arrays of both
71 * industry and industry tiles.
72 * It adjusts the enabling of the industry too, based on climate availability.
73 * This will allow for clearer testings
75 void ResetIndustries()
77 for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
78 /* Reset the spec to default */
79 if (i < lengthof(_origin_industry_specs)) {
80 _industry_specs[i] = _origin_industry_specs[i];
81 } else {
82 _industry_specs[i] = IndustrySpec{};
85 /* Enable only the current climate industries */
86 _industry_specs[i].enabled = i < NEW_INDUSTRYOFFSET &&
87 HasBit(_origin_industry_specs[i].climate_availability, _settings_game.game_creation.landscape);
90 memset(&_industry_tile_specs, 0, sizeof(_industry_tile_specs));
91 memcpy(&_industry_tile_specs, &_origin_industry_tile_specs, sizeof(_origin_industry_tile_specs));
93 /* Reset any overrides that have been set. */
94 _industile_mngr.ResetOverride();
95 _industry_mngr.ResetOverride();
98 /**
99 * Retrieve the type for this industry. Although it is accessed by a tile,
100 * it will return the general type of industry, and not the sprite index
101 * as would do GetIndustryGfx.
102 * @param tile that is queried
103 * @pre IsTileType(tile, MP_INDUSTRY)
104 * @return general type for this industry, as defined in industry.h
106 IndustryType GetIndustryType(TileIndex tile)
108 assert(IsTileType(tile, MP_INDUSTRY));
110 const Industry *ind = Industry::GetByTile(tile);
111 assert(ind != nullptr);
112 return ind->type;
116 * Accessor for array _industry_specs.
117 * This will ensure at once : proper access and
118 * not allowing modifications of it.
119 * @param thistype of industry (which is the index in _industry_specs)
120 * @pre thistype < NUM_INDUSTRYTYPES
121 * @return a pointer to the corresponding industry spec
123 const IndustrySpec *GetIndustrySpec(IndustryType thistype)
125 assert(thistype < NUM_INDUSTRYTYPES);
126 return &_industry_specs[thistype];
130 * Accessor for array _industry_tile_specs.
131 * This will ensure at once : proper access and
132 * not allowing modifications of it.
133 * @param gfx of industrytile (which is the index in _industry_tile_specs)
134 * @pre gfx < INVALID_INDUSTRYTILE
135 * @return a pointer to the corresponding industrytile spec
137 const IndustryTileSpec *GetIndustryTileSpec(IndustryGfx gfx)
139 assert(gfx < INVALID_INDUSTRYTILE);
140 return &_industry_tile_specs[gfx];
143 Industry::~Industry()
145 if (CleaningPool()) return;
147 /* Industry can also be destroyed when not fully initialized.
148 * This means that we do not have to clear tiles either.
149 * Also we must not decrement industry counts in that case. */
150 if (this->location.w == 0) return;
152 const bool has_neutral_station = this->neutral_station != nullptr;
154 for (TileIndex tile_cur : this->location) {
155 if (IsTileType(tile_cur, MP_INDUSTRY)) {
156 if (GetIndustryIndex(tile_cur) == this->index) {
157 DeleteNewGRFInspectWindow(GSF_INDUSTRYTILES, tile_cur);
159 /* MakeWaterKeepingClass() can also handle 'land' */
160 MakeWaterKeepingClass(tile_cur, OWNER_NONE);
162 } else if (IsTileType(tile_cur, MP_STATION) && IsOilRig(tile_cur)) {
163 DeleteOilRig(tile_cur);
167 if (has_neutral_station) {
168 /* Remove possible docking tiles */
169 for (TileIndex tile_cur : this->location) {
170 ClearDockingTilesCheckingNeighbours(tile_cur);
174 if (GetIndustrySpec(this->type)->behaviour & INDUSTRYBEH_PLANT_FIELDS) {
175 TileArea ta = TileArea(this->location.tile, 0, 0).Expand(21);
177 /* Remove the farmland and convert it to regular tiles over time. */
178 for (TileIndex tile_cur : ta) {
179 if (IsTileType(tile_cur, MP_CLEAR) && IsClearGround(tile_cur, CLEAR_FIELDS) &&
180 GetIndustryIndexOfField(tile_cur) == this->index) {
181 SetIndustryIndexOfField(tile_cur, INVALID_INDUSTRY);
186 /* don't let any disaster vehicle target invalid industry */
187 ReleaseDisastersTargetingIndustry(this->index);
189 /* Clear the persistent storage. */
190 delete this->psa;
192 DecIndustryTypeCount(this->type);
194 DeleteIndustryNews(this->index);
195 CloseWindowById(WC_INDUSTRY_VIEW, this->index);
196 DeleteNewGRFInspectWindow(GSF_INDUSTRIES, this->index);
198 DeleteSubsidyWith(ST_INDUSTRY, this->index);
199 CargoPacket::InvalidateAllFrom(ST_INDUSTRY, this->index);
201 for (Station *st : this->stations_near) {
202 st->RemoveIndustryToDeliver(this);
207 * Invalidating some stuff after removing item from the pool.
208 * @param index index of deleted item
210 void Industry::PostDestructor(size_t index)
212 InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, IDIWD_FORCE_REBUILD);
217 * Return a random valid industry.
218 * @return random industry, nullptr if there are no industries
220 /* static */ Industry *Industry::GetRandom()
222 if (Industry::GetNumItems() == 0) return nullptr;
223 int num = RandomRange((uint16)Industry::GetNumItems());
224 size_t index = MAX_UVALUE(size_t);
226 while (num >= 0) {
227 num--;
228 index++;
230 /* Make sure we have a valid industry */
231 while (!Industry::IsValidID(index)) {
232 index++;
233 assert(index < Industry::GetPoolSize());
237 return Industry::Get(index);
241 static void IndustryDrawSugarMine(const TileInfo *ti)
243 if (!IsIndustryCompleted(ti->tile)) return;
245 const DrawIndustryAnimationStruct *d = &_draw_industry_spec1[GetAnimationFrame(ti->tile)];
247 AddChildSpriteScreen(SPR_IT_SUGAR_MINE_SIEVE + d->image_1, PAL_NONE, d->x, 0);
249 if (d->image_2 != 0) {
250 AddChildSpriteScreen(SPR_IT_SUGAR_MINE_CLOUDS + d->image_2 - 1, PAL_NONE, 8, 41);
253 if (d->image_3 != 0) {
254 AddChildSpriteScreen(SPR_IT_SUGAR_MINE_PILE + d->image_3 - 1, PAL_NONE,
255 _drawtile_proc1[d->image_3 - 1].x, _drawtile_proc1[d->image_3 - 1].y);
259 static void IndustryDrawToffeeQuarry(const TileInfo *ti)
261 uint8 x = 0;
263 if (IsIndustryCompleted(ti->tile)) {
264 x = _industry_anim_offs_toffee[GetAnimationFrame(ti->tile)];
265 if (x == 0xFF) {
266 x = 0;
270 AddChildSpriteScreen(SPR_IT_TOFFEE_QUARRY_SHOVEL, PAL_NONE, 22 - x, 24 + x);
271 AddChildSpriteScreen(SPR_IT_TOFFEE_QUARRY_TOFFEE, PAL_NONE, 6, 14);
274 static void IndustryDrawBubbleGenerator( const TileInfo *ti)
276 if (IsIndustryCompleted(ti->tile)) {
277 AddChildSpriteScreen(SPR_IT_BUBBLE_GENERATOR_BUBBLE, PAL_NONE, 5, _industry_anim_offs_bubbles[GetAnimationFrame(ti->tile)]);
279 AddChildSpriteScreen(SPR_IT_BUBBLE_GENERATOR_SPRING, PAL_NONE, 3, 67);
282 static void IndustryDrawToyFactory(const TileInfo *ti)
284 const DrawIndustryAnimationStruct *d = &_industry_anim_offs_toys[GetAnimationFrame(ti->tile)];
286 if (d->image_1 != 0xFF) {
287 AddChildSpriteScreen(SPR_IT_TOY_FACTORY_CLAY, PAL_NONE, d->x, 96 + d->image_1);
290 if (d->image_2 != 0xFF) {
291 AddChildSpriteScreen(SPR_IT_TOY_FACTORY_ROBOT, PAL_NONE, 16 - d->image_2 * 2, 100 + d->image_2);
294 AddChildSpriteScreen(SPR_IT_TOY_FACTORY_STAMP, PAL_NONE, 7, d->image_3);
295 AddChildSpriteScreen(SPR_IT_TOY_FACTORY_STAMP_HOLDER, PAL_NONE, 0, 42);
298 static void IndustryDrawCoalPlantSparks(const TileInfo *ti)
300 if (IsIndustryCompleted(ti->tile)) {
301 uint8 image = GetAnimationFrame(ti->tile);
303 if (image != 0 && image < 7) {
304 AddChildSpriteScreen(image + SPR_IT_POWER_PLANT_TRANSFORMERS,
305 PAL_NONE,
306 _coal_plant_sparks[image - 1].x,
307 _coal_plant_sparks[image - 1].y
313 typedef void IndustryDrawTileProc(const TileInfo *ti);
314 static IndustryDrawTileProc * const _industry_draw_tile_procs[5] = {
315 IndustryDrawSugarMine,
316 IndustryDrawToffeeQuarry,
317 IndustryDrawBubbleGenerator,
318 IndustryDrawToyFactory,
319 IndustryDrawCoalPlantSparks,
322 static void DrawTile_Industry(TileInfo *ti)
324 IndustryGfx gfx = GetIndustryGfx(ti->tile);
325 Industry *ind = Industry::GetByTile(ti->tile);
326 const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
328 /* Retrieve pointer to the draw industry tile struct */
329 if (gfx >= NEW_INDUSTRYTILEOFFSET) {
330 /* Draw the tile using the specialized method of newgrf industrytile.
331 * DrawNewIndustry will return false if ever the resolver could not
332 * find any sprite to display. So in this case, we will jump on the
333 * substitute gfx instead. */
334 if (indts->grf_prop.spritegroup[0] != nullptr && DrawNewIndustryTile(ti, ind, gfx, indts)) {
335 return;
336 } else {
337 /* No sprite group (or no valid one) found, meaning no graphics associated.
338 * Use the substitute one instead */
339 if (indts->grf_prop.subst_id != INVALID_INDUSTRYTILE) {
340 gfx = indts->grf_prop.subst_id;
341 /* And point the industrytile spec accordingly */
342 indts = GetIndustryTileSpec(gfx);
347 const DrawBuildingsTileStruct *dits = &_industry_draw_tile_data[gfx << 2 | (indts->anim_state ?
348 GetAnimationFrame(ti->tile) & INDUSTRY_COMPLETED :
349 GetIndustryConstructionStage(ti->tile))];
351 SpriteID image = dits->ground.sprite;
353 /* DrawFoundation() modifies ti->z and ti->tileh */
354 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
356 /* If the ground sprite is the default flat water sprite, draw also canal/river borders.
357 * Do not do this if the tile's WaterClass is 'land'. */
358 if (image == SPR_FLAT_WATER_TILE && IsTileOnWater(ti->tile)) {
359 DrawWaterClassGround(ti);
360 } else {
361 DrawGroundSprite(image, GroundSpritePaletteTransform(image, dits->ground.pal, GENERAL_SPRITE_COLOUR(ind->random_colour)));
364 /* If industries are transparent and invisible, do not draw the upper part */
365 if (IsInvisibilitySet(TO_INDUSTRIES)) return;
367 /* Add industry on top of the ground? */
368 image = dits->building.sprite;
369 if (image != 0) {
370 AddSortableSpriteToDraw(image, SpriteLayoutPaletteTransform(image, dits->building.pal, GENERAL_SPRITE_COLOUR(ind->random_colour)),
371 ti->x + dits->subtile_x,
372 ti->y + dits->subtile_y,
373 dits->width,
374 dits->height,
375 dits->dz,
376 ti->z,
377 IsTransparencySet(TO_INDUSTRIES));
379 if (IsTransparencySet(TO_INDUSTRIES)) return;
383 int proc = dits->draw_proc - 1;
384 if (proc >= 0) _industry_draw_tile_procs[proc](ti);
388 static int GetSlopePixelZ_Industry(TileIndex tile, uint x, uint y)
390 return GetTileMaxPixelZ(tile);
393 static Foundation GetFoundation_Industry(TileIndex tile, Slope tileh)
395 IndustryGfx gfx = GetIndustryGfx(tile);
397 /* For NewGRF industry tiles we might not be drawing a foundation. We need to
398 * account for this, as other structures should
399 * draw the wall of the foundation in this case.
401 if (gfx >= NEW_INDUSTRYTILEOFFSET) {
402 const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
403 if (indts->grf_prop.spritegroup[0] != nullptr && HasBit(indts->callback_mask, CBM_INDT_DRAW_FOUNDATIONS)) {
404 uint32 callback_res = GetIndustryTileCallback(CBID_INDTILE_DRAW_FOUNDATIONS, 0, 0, gfx, Industry::GetByTile(tile), tile);
405 if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(indts->grf_prop.grffile, CBID_INDTILE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
408 return FlatteningFoundation(tileh);
411 static void AddAcceptedCargo_Industry(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
413 IndustryGfx gfx = GetIndustryGfx(tile);
414 const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
415 const Industry *ind = Industry::GetByTile(tile);
417 /* Starting point for acceptance */
418 CargoID accepts_cargo[lengthof(itspec->accepts_cargo)];
419 int8 cargo_acceptance[lengthof(itspec->acceptance)];
420 MemCpyT(accepts_cargo, itspec->accepts_cargo, lengthof(accepts_cargo));
421 MemCpyT(cargo_acceptance, itspec->acceptance, lengthof(cargo_acceptance));
423 if (itspec->special_flags & INDTILE_SPECIAL_ACCEPTS_ALL_CARGO) {
424 /* Copy all accepted cargoes from industry itself */
425 for (uint i = 0; i < lengthof(ind->accepts_cargo); i++) {
426 CargoID *pos = std::find(accepts_cargo, endof(accepts_cargo), ind->accepts_cargo[i]);
427 if (pos == endof(accepts_cargo)) {
428 /* Not found, insert */
429 pos = std::find(accepts_cargo, endof(accepts_cargo), CT_INVALID);
430 if (pos == endof(accepts_cargo)) continue; // nowhere to place, give up on this one
431 *pos = ind->accepts_cargo[i];
433 cargo_acceptance[pos - accepts_cargo] += 8;
437 if (HasBit(itspec->callback_mask, CBM_INDT_ACCEPT_CARGO)) {
438 /* Try callback for accepts list, if success override all existing accepts */
439 uint16 res = GetIndustryTileCallback(CBID_INDTILE_ACCEPT_CARGO, 0, 0, gfx, Industry::GetByTile(tile), tile);
440 if (res != CALLBACK_FAILED) {
441 MemSetT(accepts_cargo, CT_INVALID, lengthof(accepts_cargo));
442 for (uint i = 0; i < 3; i++) accepts_cargo[i] = GetCargoTranslation(GB(res, i * 5, 5), itspec->grf_prop.grffile);
446 if (HasBit(itspec->callback_mask, CBM_INDT_CARGO_ACCEPTANCE)) {
447 /* Try callback for acceptance list, if success override all existing acceptance */
448 uint16 res = GetIndustryTileCallback(CBID_INDTILE_CARGO_ACCEPTANCE, 0, 0, gfx, Industry::GetByTile(tile), tile);
449 if (res != CALLBACK_FAILED) {
450 MemSetT(cargo_acceptance, 0, lengthof(cargo_acceptance));
451 for (uint i = 0; i < 3; i++) cargo_acceptance[i] = GB(res, i * 4, 4);
455 for (byte i = 0; i < lengthof(itspec->accepts_cargo); i++) {
456 CargoID a = accepts_cargo[i];
457 if (a == CT_INVALID || cargo_acceptance[i] <= 0) continue; // work only with valid cargoes
459 /* Add accepted cargo */
460 acceptance[a] += cargo_acceptance[i];
462 /* Maybe set 'always accepted' bit (if it's not set already) */
463 if (HasBit(*always_accepted, a)) continue;
465 bool accepts = false;
466 for (uint cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
467 /* Test whether the industry itself accepts the cargo type */
468 if (ind->accepts_cargo[cargo_index] == a) {
469 accepts = true;
470 break;
474 if (accepts) continue;
476 /* If the industry itself doesn't accept this cargo, set 'always accepted' bit */
477 SetBit(*always_accepted, a);
481 static void GetTileDesc_Industry(TileIndex tile, TileDesc *td)
483 const Industry *i = Industry::GetByTile(tile);
484 const IndustrySpec *is = GetIndustrySpec(i->type);
486 td->owner[0] = i->owner;
487 td->str = is->name;
488 if (!IsIndustryCompleted(tile)) {
489 SetDParamX(td->dparam, 0, td->str);
490 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
493 if (is->grf_prop.grffile != nullptr) {
494 td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
498 static CommandCost ClearTile_Industry(TileIndex tile, DoCommandFlag flags)
500 Industry *i = Industry::GetByTile(tile);
501 const IndustrySpec *indspec = GetIndustrySpec(i->type);
503 /* water can destroy industries
504 * in editor you can bulldoze industries
505 * with magic_bulldozer cheat you can destroy industries
506 * (area around OILRIG is water, so water shouldn't flood it
508 if ((_current_company != OWNER_WATER && _game_mode != GM_EDITOR &&
509 !_cheats.magic_bulldozer.value) ||
510 ((flags & DC_AUTO) != 0) ||
511 (_current_company == OWNER_WATER &&
512 ((indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) ||
513 HasBit(GetIndustryTileSpec(GetIndustryGfx(tile))->slopes_refused, 5)))) {
514 SetDParam(1, indspec->name);
515 return_cmd_error(flags & DC_AUTO ? STR_ERROR_GENERIC_OBJECT_IN_THE_WAY : INVALID_STRING_ID);
518 if (flags & DC_EXEC) {
519 AI::BroadcastNewEvent(new ScriptEventIndustryClose(i->index));
520 Game::NewEvent(new ScriptEventIndustryClose(i->index));
521 delete i;
523 return CommandCost(EXPENSES_CONSTRUCTION, indspec->GetRemovalCost());
527 * Move produced cargo from industry to nearby stations.
528 * @param tile Industry tile
529 * @return true if any cargo was moved.
531 static bool TransportIndustryGoods(TileIndex tile)
533 Industry *i = Industry::GetByTile(tile);
534 const IndustrySpec *indspec = GetIndustrySpec(i->type);
535 bool moved_cargo = false;
537 for (uint j = 0; j < lengthof(i->produced_cargo_waiting); j++) {
538 uint cw = std::min<uint>(i->produced_cargo_waiting[j], 255u);
539 if (cw > indspec->minimal_cargo && i->produced_cargo[j] != CT_INVALID) {
540 i->produced_cargo_waiting[j] -= cw;
542 /* fluctuating economy? */
543 if (EconomyIsInRecession()) cw = (cw + 1) / 2;
545 i->this_month_production[j] += cw;
547 uint am = MoveGoodsToStation(i->produced_cargo[j], cw, ST_INDUSTRY, i->index, &i->stations_near, i->exclusive_consumer);
548 i->this_month_transported[j] += am;
550 moved_cargo |= (am != 0);
554 return moved_cargo;
558 static void AnimateTile_Industry(TileIndex tile)
560 IndustryGfx gfx = GetIndustryGfx(tile);
562 if (GetIndustryTileSpec(gfx)->animation.status != ANIM_STATUS_NO_ANIMATION) {
563 AnimateNewIndustryTile(tile);
564 return;
567 switch (gfx) {
568 case GFX_SUGAR_MINE_SIEVE:
569 if ((_tick_counter & 1) == 0) {
570 byte m = GetAnimationFrame(tile) + 1;
572 if (_settings_client.sound.ambient) {
573 switch (m & 7) {
574 case 2: SndPlayTileFx(SND_2D_SUGAR_MINE_1, tile); break;
575 case 6: SndPlayTileFx(SND_29_SUGAR_MINE_2, tile); break;
579 if (m >= 96) {
580 m = 0;
581 DeleteAnimatedTile(tile);
583 SetAnimationFrame(tile, m);
585 MarkTileDirtyByTile(tile);
587 break;
589 case GFX_TOFFEE_QUARY:
590 if ((_tick_counter & 3) == 0) {
591 byte m = GetAnimationFrame(tile);
593 if (_industry_anim_offs_toffee[m] == 0xFF && _settings_client.sound.ambient) {
594 SndPlayTileFx(SND_30_TOFFEE_QUARRY, tile);
597 if (++m >= 70) {
598 m = 0;
599 DeleteAnimatedTile(tile);
601 SetAnimationFrame(tile, m);
603 MarkTileDirtyByTile(tile);
605 break;
607 case GFX_BUBBLE_CATCHER:
608 if ((_tick_counter & 1) == 0) {
609 byte m = GetAnimationFrame(tile);
611 if (++m >= 40) {
612 m = 0;
613 DeleteAnimatedTile(tile);
615 SetAnimationFrame(tile, m);
617 MarkTileDirtyByTile(tile);
619 break;
621 /* Sparks on a coal plant */
622 case GFX_POWERPLANT_SPARKS:
623 if ((_tick_counter & 3) == 0) {
624 byte m = GetAnimationFrame(tile);
625 if (m == 6) {
626 SetAnimationFrame(tile, 0);
627 DeleteAnimatedTile(tile);
628 } else {
629 SetAnimationFrame(tile, m + 1);
630 MarkTileDirtyByTile(tile);
633 break;
635 case GFX_TOY_FACTORY:
636 if ((_tick_counter & 1) == 0) {
637 byte m = GetAnimationFrame(tile) + 1;
639 switch (m) {
640 case 1: if (_settings_client.sound.ambient) SndPlayTileFx(SND_2C_TOY_FACTORY_1, tile); break;
641 case 23: if (_settings_client.sound.ambient) SndPlayTileFx(SND_2B_TOY_FACTORY_2, tile); break;
642 case 28: if (_settings_client.sound.ambient) SndPlayTileFx(SND_2A_TOY_FACTORY_3, tile); break;
643 default:
644 if (m >= 50) {
645 int n = GetIndustryAnimationLoop(tile) + 1;
646 m = 0;
647 if (n >= 8) {
648 n = 0;
649 DeleteAnimatedTile(tile);
651 SetIndustryAnimationLoop(tile, n);
655 SetAnimationFrame(tile, m);
656 MarkTileDirtyByTile(tile);
658 break;
660 case GFX_PLASTIC_FOUNTAIN_ANIMATED_1: case GFX_PLASTIC_FOUNTAIN_ANIMATED_2:
661 case GFX_PLASTIC_FOUNTAIN_ANIMATED_3: case GFX_PLASTIC_FOUNTAIN_ANIMATED_4:
662 case GFX_PLASTIC_FOUNTAIN_ANIMATED_5: case GFX_PLASTIC_FOUNTAIN_ANIMATED_6:
663 case GFX_PLASTIC_FOUNTAIN_ANIMATED_7: case GFX_PLASTIC_FOUNTAIN_ANIMATED_8:
664 if ((_tick_counter & 3) == 0) {
665 IndustryGfx gfx = GetIndustryGfx(tile);
667 gfx = (gfx < 155) ? gfx + 1 : 148;
668 SetIndustryGfx(tile, gfx);
669 MarkTileDirtyByTile(tile);
671 break;
673 case GFX_OILWELL_ANIMATED_1:
674 case GFX_OILWELL_ANIMATED_2:
675 case GFX_OILWELL_ANIMATED_3:
676 if ((_tick_counter & 7) == 0) {
677 bool b = Chance16(1, 7);
678 IndustryGfx gfx = GetIndustryGfx(tile);
680 byte m = GetAnimationFrame(tile) + 1;
681 if (m == 4 && (m = 0, ++gfx) == GFX_OILWELL_ANIMATED_3 + 1 && (gfx = GFX_OILWELL_ANIMATED_1, b)) {
682 SetIndustryGfx(tile, GFX_OILWELL_NOT_ANIMATED);
683 SetIndustryConstructionStage(tile, 3);
684 DeleteAnimatedTile(tile);
685 } else {
686 SetAnimationFrame(tile, m);
687 SetIndustryGfx(tile, gfx);
688 MarkTileDirtyByTile(tile);
691 break;
693 case GFX_COAL_MINE_TOWER_ANIMATED:
694 case GFX_COPPER_MINE_TOWER_ANIMATED:
695 case GFX_GOLD_MINE_TOWER_ANIMATED: {
696 int state = _tick_counter & 0x7FF;
698 if ((state -= 0x400) < 0) return;
700 if (state < 0x1A0) {
701 if (state < 0x20 || state >= 0x180) {
702 byte m = GetAnimationFrame(tile);
703 if (!(m & 0x40)) {
704 SetAnimationFrame(tile, m | 0x40);
705 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0B_MINE, tile);
707 if (state & 7) return;
708 } else {
709 if (state & 3) return;
711 byte m = (GetAnimationFrame(tile) + 1) | 0x40;
712 if (m > 0xC2) m = 0xC0;
713 SetAnimationFrame(tile, m);
714 MarkTileDirtyByTile(tile);
715 } else if (state >= 0x200 && state < 0x3A0) {
716 int i = (state < 0x220 || state >= 0x380) ? 7 : 3;
717 if (state & i) return;
719 byte m = (GetAnimationFrame(tile) & 0xBF) - 1;
720 if (m < 0x80) m = 0x82;
721 SetAnimationFrame(tile, m);
722 MarkTileDirtyByTile(tile);
724 break;
729 static void CreateChimneySmoke(TileIndex tile)
731 uint x = TileX(tile) * TILE_SIZE;
732 uint y = TileY(tile) * TILE_SIZE;
733 int z = GetTileMaxPixelZ(tile);
735 CreateEffectVehicle(x + 15, y + 14, z + 59, EV_CHIMNEY_SMOKE);
738 static void MakeIndustryTileBigger(TileIndex tile)
740 byte cnt = GetIndustryConstructionCounter(tile) + 1;
741 if (cnt != 4) {
742 SetIndustryConstructionCounter(tile, cnt);
743 return;
746 byte stage = GetIndustryConstructionStage(tile) + 1;
747 SetIndustryConstructionCounter(tile, 0);
748 SetIndustryConstructionStage(tile, stage);
749 StartStopIndustryTileAnimation(tile, IAT_CONSTRUCTION_STATE_CHANGE);
750 if (stage == INDUSTRY_COMPLETED) SetIndustryCompleted(tile);
752 MarkTileDirtyByTile(tile);
754 if (!IsIndustryCompleted(tile)) return;
756 IndustryGfx gfx = GetIndustryGfx(tile);
757 if (gfx >= NEW_INDUSTRYTILEOFFSET) {
758 /* New industries are already animated on construction. */
759 return;
762 switch (gfx) {
763 case GFX_POWERPLANT_CHIMNEY:
764 CreateChimneySmoke(tile);
765 break;
767 case GFX_OILRIG_1: {
768 /* Do not require an industry tile to be after the first two GFX_OILRIG_1
769 * tiles (like the default oil rig). Do a proper check to ensure the
770 * tiles belong to the same industry and based on that build the oil rig's
771 * station. */
772 TileIndex other = tile + TileDiffXY(0, 1);
774 if (IsTileType(other, MP_INDUSTRY) &&
775 GetIndustryGfx(other) == GFX_OILRIG_1 &&
776 GetIndustryIndex(tile) == GetIndustryIndex(other)) {
777 BuildOilRig(tile);
779 break;
782 case GFX_TOY_FACTORY:
783 case GFX_BUBBLE_CATCHER:
784 case GFX_TOFFEE_QUARY:
785 SetAnimationFrame(tile, 0);
786 SetIndustryAnimationLoop(tile, 0);
787 break;
789 case GFX_PLASTIC_FOUNTAIN_ANIMATED_1: case GFX_PLASTIC_FOUNTAIN_ANIMATED_2:
790 case GFX_PLASTIC_FOUNTAIN_ANIMATED_3: case GFX_PLASTIC_FOUNTAIN_ANIMATED_4:
791 case GFX_PLASTIC_FOUNTAIN_ANIMATED_5: case GFX_PLASTIC_FOUNTAIN_ANIMATED_6:
792 case GFX_PLASTIC_FOUNTAIN_ANIMATED_7: case GFX_PLASTIC_FOUNTAIN_ANIMATED_8:
793 AddAnimatedTile(tile);
794 break;
798 static void TileLoopIndustry_BubbleGenerator(TileIndex tile)
800 static const int8 _bubble_spawn_location[3][4] = {
801 { 11, 0, -4, -14 },
802 { -4, -10, -4, 1 },
803 { 49, 59, 60, 65 },
806 if (_settings_client.sound.ambient) SndPlayTileFx(SND_2E_BUBBLE_GENERATOR, tile);
808 int dir = Random() & 3;
810 EffectVehicle *v = CreateEffectVehicleAbove(
811 TileX(tile) * TILE_SIZE + _bubble_spawn_location[0][dir],
812 TileY(tile) * TILE_SIZE + _bubble_spawn_location[1][dir],
813 _bubble_spawn_location[2][dir],
814 EV_BUBBLE
817 if (v != nullptr) v->animation_substate = dir;
820 static void TileLoop_Industry(TileIndex tile)
822 if (IsTileOnWater(tile)) TileLoop_Water(tile);
824 /* Normally this doesn't happen, but if an industry NewGRF is removed
825 * an industry that was previously build on water can now be flooded.
826 * If this happens the tile is no longer an industry tile after
827 * returning from TileLoop_Water. */
828 if (!IsTileType(tile, MP_INDUSTRY)) return;
830 TriggerIndustryTile(tile, INDTILE_TRIGGER_TILE_LOOP);
832 if (!IsIndustryCompleted(tile)) {
833 MakeIndustryTileBigger(tile);
834 return;
837 if (_game_mode == GM_EDITOR) return;
839 if (TransportIndustryGoods(tile) && !StartStopIndustryTileAnimation(Industry::GetByTile(tile), IAT_INDUSTRY_DISTRIBUTES_CARGO)) {
840 uint newgfx = GetIndustryTileSpec(GetIndustryGfx(tile))->anim_production;
842 if (newgfx != INDUSTRYTILE_NOANIM) {
843 ResetIndustryConstructionStage(tile);
844 SetIndustryCompleted(tile);
845 SetIndustryGfx(tile, newgfx);
846 MarkTileDirtyByTile(tile);
847 return;
851 if (StartStopIndustryTileAnimation(tile, IAT_TILELOOP)) return;
853 IndustryGfx newgfx = GetIndustryTileSpec(GetIndustryGfx(tile))->anim_next;
854 if (newgfx != INDUSTRYTILE_NOANIM) {
855 ResetIndustryConstructionStage(tile);
856 SetIndustryGfx(tile, newgfx);
857 MarkTileDirtyByTile(tile);
858 return;
861 IndustryGfx gfx = GetIndustryGfx(tile);
862 switch (gfx) {
863 case GFX_COAL_MINE_TOWER_NOT_ANIMATED:
864 case GFX_COPPER_MINE_TOWER_NOT_ANIMATED:
865 case GFX_GOLD_MINE_TOWER_NOT_ANIMATED:
866 if (!(_tick_counter & 0x400) && Chance16(1, 2)) {
867 switch (gfx) {
868 case GFX_COAL_MINE_TOWER_NOT_ANIMATED: gfx = GFX_COAL_MINE_TOWER_ANIMATED; break;
869 case GFX_COPPER_MINE_TOWER_NOT_ANIMATED: gfx = GFX_COPPER_MINE_TOWER_ANIMATED; break;
870 case GFX_GOLD_MINE_TOWER_NOT_ANIMATED: gfx = GFX_GOLD_MINE_TOWER_ANIMATED; break;
872 SetIndustryGfx(tile, gfx);
873 SetAnimationFrame(tile, 0x80);
874 AddAnimatedTile(tile);
876 break;
878 case GFX_OILWELL_NOT_ANIMATED:
879 if (Chance16(1, 6)) {
880 SetIndustryGfx(tile, GFX_OILWELL_ANIMATED_1);
881 SetAnimationFrame(tile, 0);
882 AddAnimatedTile(tile);
884 break;
886 case GFX_COAL_MINE_TOWER_ANIMATED:
887 case GFX_COPPER_MINE_TOWER_ANIMATED:
888 case GFX_GOLD_MINE_TOWER_ANIMATED:
889 if (!(_tick_counter & 0x400)) {
890 switch (gfx) {
891 case GFX_COAL_MINE_TOWER_ANIMATED: gfx = GFX_COAL_MINE_TOWER_NOT_ANIMATED; break;
892 case GFX_COPPER_MINE_TOWER_ANIMATED: gfx = GFX_COPPER_MINE_TOWER_NOT_ANIMATED; break;
893 case GFX_GOLD_MINE_TOWER_ANIMATED: gfx = GFX_GOLD_MINE_TOWER_NOT_ANIMATED; break;
895 SetIndustryGfx(tile, gfx);
896 SetIndustryCompleted(tile);
897 SetIndustryConstructionStage(tile, 3);
898 DeleteAnimatedTile(tile);
900 break;
902 case GFX_POWERPLANT_SPARKS:
903 if (Chance16(1, 3)) {
904 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0C_POWER_STATION, tile);
905 AddAnimatedTile(tile);
907 break;
909 case GFX_COPPER_MINE_CHIMNEY:
910 CreateEffectVehicleAbove(TileX(tile) * TILE_SIZE + 6, TileY(tile) * TILE_SIZE + 6, 43, EV_COPPER_MINE_SMOKE);
911 break;
914 case GFX_TOY_FACTORY: {
915 Industry *i = Industry::GetByTile(tile);
916 if (i->was_cargo_delivered) {
917 i->was_cargo_delivered = false;
918 SetIndustryAnimationLoop(tile, 0);
919 AddAnimatedTile(tile);
922 break;
924 case GFX_BUBBLE_GENERATOR:
925 TileLoopIndustry_BubbleGenerator(tile);
926 break;
928 case GFX_TOFFEE_QUARY:
929 AddAnimatedTile(tile);
930 break;
932 case GFX_SUGAR_MINE_SIEVE:
933 if (Chance16(1, 3)) AddAnimatedTile(tile);
934 break;
938 static bool ClickTile_Industry(TileIndex tile)
940 ShowIndustryViewWindow(GetIndustryIndex(tile));
941 return true;
944 static TrackStatus GetTileTrackStatus_Industry(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
946 return 0;
949 static void ChangeTileOwner_Industry(TileIndex tile, Owner old_owner, Owner new_owner)
951 /* If the founder merges, the industry was created by the merged company */
952 Industry *i = Industry::GetByTile(tile);
953 if (i->founder == old_owner) i->founder = (new_owner == INVALID_OWNER) ? OWNER_NONE : new_owner;
955 if (i->exclusive_supplier == old_owner) i->exclusive_supplier = new_owner;
956 if (i->exclusive_consumer == old_owner) i->exclusive_consumer = new_owner;
960 * Check whether the tile is a forest.
961 * @param tile the tile to investigate.
962 * @return true if and only if the tile is a forest
964 bool IsTileForestIndustry(TileIndex tile)
966 /* Check for industry tile */
967 if (!IsTileType(tile, MP_INDUSTRY)) return false;
969 const Industry *ind = Industry::GetByTile(tile);
971 /* Check for organic industry (i.e. not processing or extractive) */
972 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
974 /* Check for wood production */
975 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
976 /* The industry produces wood. */
977 if (ind->produced_cargo[i] != CT_INVALID && CargoSpec::Get(ind->produced_cargo[i])->label == 'WOOD') return true;
980 return false;
983 static const byte _plantfarmfield_type[] = {1, 1, 1, 1, 1, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6};
986 * Check whether the tile can be replaced by a farm field.
987 * @param tile the tile to investigate.
988 * @param allow_fields if true, the method will return true even if
989 * the tile is a farm tile, otherwise the tile may not be a farm tile
990 * @return true if the tile can become a farm field
992 static bool IsSuitableForFarmField(TileIndex tile, bool allow_fields)
994 switch (GetTileType(tile)) {
995 case MP_CLEAR: return !IsClearGround(tile, CLEAR_SNOW) && !IsClearGround(tile, CLEAR_DESERT) && (allow_fields || !IsClearGround(tile, CLEAR_FIELDS));
996 case MP_TREES: return GetTreeGround(tile) != TREE_GROUND_SHORE;
997 default: return false;
1002 * Build farm field fence
1003 * @param tile the tile to position the fence on
1004 * @param size the size of the field being planted in tiles
1005 * @param type type of fence to set
1006 * @param side the side of the tile to attempt placement
1008 static void SetupFarmFieldFence(TileIndex tile, int size, byte type, DiagDirection side)
1010 TileIndexDiff diff = (DiagDirToAxis(side) == AXIS_Y ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1012 do {
1013 tile = TILE_MASK(tile);
1015 if (IsTileType(tile, MP_CLEAR) && IsClearGround(tile, CLEAR_FIELDS)) {
1016 byte or_ = type;
1018 if (or_ == 1 && Chance16(1, 7)) or_ = 2;
1020 SetFence(tile, side, or_);
1023 tile += diff;
1024 } while (--size);
1027 static void PlantFarmField(TileIndex tile, IndustryID industry)
1029 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
1030 if (GetTileZ(tile) + 2 >= GetSnowLine()) return;
1033 /* determine field size */
1034 uint32 r = (Random() & 0x303) + 0x404;
1035 if (_settings_game.game_creation.landscape == LT_ARCTIC) r += 0x404;
1036 uint size_x = GB(r, 0, 8);
1037 uint size_y = GB(r, 8, 8);
1039 TileArea ta(tile - TileDiffXY(std::min(TileX(tile), size_x / 2), std::min(TileY(tile), size_y / 2)), size_x, size_y);
1040 ta.ClampToMap();
1042 if (ta.w == 0 || ta.h == 0) return;
1044 /* check the amount of bad tiles */
1045 int count = 0;
1046 for (TileIndex cur_tile : ta) {
1047 assert(cur_tile < MapSize());
1048 count += IsSuitableForFarmField(cur_tile, false);
1050 if (count * 2 < ta.w * ta.h) return;
1052 /* determine type of field */
1053 r = Random();
1054 uint counter = GB(r, 5, 3);
1055 uint field_type = GB(r, 8, 8) * 9 >> 8;
1057 /* make field */
1058 for (TileIndex cur_tile : ta) {
1059 assert(cur_tile < MapSize());
1060 if (IsSuitableForFarmField(cur_tile, true)) {
1061 MakeField(cur_tile, field_type, industry);
1062 SetClearCounter(cur_tile, counter);
1063 MarkTileDirtyByTile(cur_tile);
1067 int type = 3;
1068 if (_settings_game.game_creation.landscape != LT_ARCTIC && _settings_game.game_creation.landscape != LT_TROPIC) {
1069 type = _plantfarmfield_type[Random() & 0xF];
1072 SetupFarmFieldFence(ta.tile, ta.h, type, DIAGDIR_NE);
1073 SetupFarmFieldFence(ta.tile, ta.w, type, DIAGDIR_NW);
1074 SetupFarmFieldFence(ta.tile + TileDiffXY(ta.w - 1, 0), ta.h, type, DIAGDIR_SW);
1075 SetupFarmFieldFence(ta.tile + TileDiffXY(0, ta.h - 1), ta.w, type, DIAGDIR_SE);
1078 void PlantRandomFarmField(const Industry *i)
1080 int x = i->location.w / 2 + Random() % 31 - 16;
1081 int y = i->location.h / 2 + Random() % 31 - 16;
1083 TileIndex tile = TileAddWrap(i->location.tile, x, y);
1085 if (tile != INVALID_TILE) PlantFarmField(tile, i->index);
1089 * Search callback function for ChopLumberMillTrees
1090 * @param tile to test
1091 * @param user_data that is passed by the caller. In this case, nothing
1092 * @return the result of the test
1094 static bool SearchLumberMillTrees(TileIndex tile, void *user_data)
1096 if (IsTileType(tile, MP_TREES) && GetTreeGrowth(tile) > 2) { ///< 3 and up means all fully grown trees
1097 /* found a tree */
1099 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1101 _industry_sound_ctr = 1;
1102 _industry_sound_tile = tile;
1103 if (_settings_client.sound.ambient) SndPlayTileFx(SND_38_LUMBER_MILL_1, tile);
1105 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC, tile);
1107 cur_company.Restore();
1108 return true;
1110 return false;
1114 * Perform a circular search around the Lumber Mill in order to find trees to cut
1115 * @param i industry
1117 static void ChopLumberMillTrees(Industry *i)
1119 /* We only want to cut trees if all tiles are completed. */
1120 for (TileIndex tile_cur : i->location) {
1121 if (i->TileBelongsToIndustry(tile_cur)) {
1122 if (!IsIndustryCompleted(tile_cur)) return;
1126 TileIndex tile = i->location.tile;
1127 if (CircularTileSearch(&tile, 40, SearchLumberMillTrees, nullptr)) { // 40x40 tiles to search.
1128 i->produced_cargo_waiting[0] = std::min(0xffff, i->produced_cargo_waiting[0] + 45); // Found a tree, add according value to waiting cargo.
1132 static void ProduceIndustryGoods(Industry *i)
1134 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1136 /* play a sound? */
1137 if ((i->counter & 0x3F) == 0) {
1138 uint32 r;
1139 if (Chance16R(1, 14, r) && indsp->number_of_sounds != 0 && _settings_client.sound.ambient) {
1140 for (size_t j = 0; j < lengthof(i->last_month_production); j++) {
1141 if (i->last_month_production[j] > 0) {
1142 /* Play sound since last month had production */
1143 SndPlayTileFx(
1144 (SoundFx)(indsp->random_sounds[((r >> 16) * indsp->number_of_sounds) >> 16]),
1145 i->location.tile);
1146 break;
1152 i->counter--;
1154 /* produce some cargo */
1155 if ((i->counter % INDUSTRY_PRODUCE_TICKS) == 0) {
1156 if (HasBit(indsp->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) IndustryProductionCallback(i, 1);
1158 IndustryBehaviour indbehav = indsp->behaviour;
1159 for (size_t j = 0; j < lengthof(i->produced_cargo_waiting); j++) {
1160 i->produced_cargo_waiting[j] = std::min(0xffff, i->produced_cargo_waiting[j] + i->production_rate[j]);
1163 if ((indbehav & INDUSTRYBEH_PLANT_FIELDS) != 0) {
1164 uint16 cb_res = CALLBACK_FAILED;
1165 if (HasBit(indsp->callback_mask, CBM_IND_SPECIAL_EFFECT)) {
1166 cb_res = GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, Random(), 0, i, i->type, i->location.tile);
1169 bool plant;
1170 if (cb_res != CALLBACK_FAILED) {
1171 plant = ConvertBooleanCallback(indsp->grf_prop.grffile, CBID_INDUSTRY_SPECIAL_EFFECT, cb_res);
1172 } else {
1173 plant = Chance16(1, 8);
1176 if (plant) PlantRandomFarmField(i);
1178 if ((indbehav & INDUSTRYBEH_CUT_TREES) != 0) {
1179 uint16 cb_res = CALLBACK_FAILED;
1180 if (HasBit(indsp->callback_mask, CBM_IND_SPECIAL_EFFECT)) {
1181 cb_res = GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, Random(), 1, i, i->type, i->location.tile);
1184 bool cut;
1185 if (cb_res != CALLBACK_FAILED) {
1186 cut = ConvertBooleanCallback(indsp->grf_prop.grffile, CBID_INDUSTRY_SPECIAL_EFFECT, cb_res);
1187 } else {
1188 cut = ((i->counter % INDUSTRY_CUT_TREE_TICKS) == 0);
1191 if (cut) ChopLumberMillTrees(i);
1194 TriggerIndustry(i, INDUSTRY_TRIGGER_INDUSTRY_TICK);
1195 StartStopIndustryTileAnimation(i, IAT_INDUSTRY_TICK);
1199 void OnTick_Industry()
1201 if (_industry_sound_ctr != 0) {
1202 _industry_sound_ctr++;
1204 if (_industry_sound_ctr == 75) {
1205 if (_settings_client.sound.ambient) SndPlayTileFx(SND_37_LUMBER_MILL_2, _industry_sound_tile);
1206 } else if (_industry_sound_ctr == 160) {
1207 _industry_sound_ctr = 0;
1208 if (_settings_client.sound.ambient) SndPlayTileFx(SND_36_LUMBER_MILL_3, _industry_sound_tile);
1212 if (_game_mode == GM_EDITOR) return;
1214 for (Industry *i : Industry::Iterate()) {
1215 ProduceIndustryGoods(i);
1220 * Check the conditions of #CHECK_NOTHING (Always succeeds).
1221 * @param tile %Tile to perform the checking.
1222 * @return Succeeded or failed command.
1224 static CommandCost CheckNewIndustry_NULL(TileIndex tile)
1226 return CommandCost();
1230 * Check the conditions of #CHECK_FOREST (Industry should be build above snow-line in arctic climate).
1231 * @param tile %Tile to perform the checking.
1232 * @return Succeeded or failed command.
1234 static CommandCost CheckNewIndustry_Forest(TileIndex tile)
1236 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
1237 if (GetTileZ(tile) < HighestSnowLine() + 2) {
1238 return_cmd_error(STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED);
1241 return CommandCost();
1245 * Check if a tile is within a distance from map edges, scaled by map dimensions independently.
1246 * Each dimension is checked independently, and dimensions smaller than 256 are not scaled.
1247 * @param tile Which tile to check distance of.
1248 * @param maxdist Normal distance on a 256x256 map.
1249 * @return True if the tile is near the map edge.
1251 static bool CheckScaledDistanceFromEdge(TileIndex tile, uint maxdist)
1253 uint maxdist_x = maxdist;
1254 uint maxdist_y = maxdist;
1256 if (MapSizeX() > 256) maxdist_x *= MapSizeX() / 256;
1257 if (MapSizeY() > 256) maxdist_y *= MapSizeY() / 256;
1259 if (DistanceFromEdgeDir(tile, DIAGDIR_NE) < maxdist_x) return true;
1260 if (DistanceFromEdgeDir(tile, DIAGDIR_NW) < maxdist_y) return true;
1261 if (DistanceFromEdgeDir(tile, DIAGDIR_SW) < maxdist_x) return true;
1262 if (DistanceFromEdgeDir(tile, DIAGDIR_SE) < maxdist_y) return true;
1264 return false;
1268 * Check the conditions of #CHECK_REFINERY (Industry should be positioned near edge of the map).
1269 * @param tile %Tile to perform the checking.
1270 * @return Succeeded or failed command.
1272 static CommandCost CheckNewIndustry_OilRefinery(TileIndex tile)
1274 if (_game_mode == GM_EDITOR) return CommandCost();
1276 if (CheckScaledDistanceFromEdge(TILE_ADDXY(tile, 1, 1), _settings_game.game_creation.oil_refinery_limit)) return CommandCost();
1278 return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
1281 extern bool _ignore_restrictions;
1284 * Check the conditions of #CHECK_OIL_RIG (Industries at sea should be positioned near edge of the map).
1285 * @param tile %Tile to perform the checking.
1286 * @return Succeeded or failed command.
1288 static CommandCost CheckNewIndustry_OilRig(TileIndex tile)
1290 if (_game_mode == GM_EDITOR && _ignore_restrictions) return CommandCost();
1292 if (TileHeight(tile) == 0 &&
1293 CheckScaledDistanceFromEdge(TILE_ADDXY(tile, 1, 1), _settings_game.game_creation.oil_refinery_limit)) return CommandCost();
1295 return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
1299 * Check the conditions of #CHECK_FARM (Industry should be below snow-line in arctic).
1300 * @param tile %Tile to perform the checking.
1301 * @return Succeeded or failed command.
1303 static CommandCost CheckNewIndustry_Farm(TileIndex tile)
1305 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
1306 if (GetTileZ(tile) + 2 >= HighestSnowLine()) {
1307 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1310 return CommandCost();
1314 * Check the conditions of #CHECK_PLANTATION (Industry should NOT be in the desert).
1315 * @param tile %Tile to perform the checking.
1316 * @return Succeeded or failed command.
1318 static CommandCost CheckNewIndustry_Plantation(TileIndex tile)
1320 if (GetTropicZone(tile) == TROPICZONE_DESERT) {
1321 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1323 return CommandCost();
1327 * Check the conditions of #CHECK_WATER (Industry should be in the desert).
1328 * @param tile %Tile to perform the checking.
1329 * @return Succeeded or failed command.
1331 static CommandCost CheckNewIndustry_Water(TileIndex tile)
1333 if (GetTropicZone(tile) != TROPICZONE_DESERT) {
1334 return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT);
1336 return CommandCost();
1340 * Check the conditions of #CHECK_LUMBERMILL (Industry should be in the rain forest).
1341 * @param tile %Tile to perform the checking.
1342 * @return Succeeded or failed command.
1344 static CommandCost CheckNewIndustry_Lumbermill(TileIndex tile)
1346 if (GetTropicZone(tile) != TROPICZONE_RAINFOREST) {
1347 return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST);
1349 return CommandCost();
1353 * Check the conditions of #CHECK_BUBBLEGEN (Industry should be in low land).
1354 * @param tile %Tile to perform the checking.
1355 * @return Succeeded or failed command.
1357 static CommandCost CheckNewIndustry_BubbleGen(TileIndex tile)
1359 if (GetTileZ(tile) > 4) {
1360 return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_LOW_AREAS);
1362 return CommandCost();
1366 * Industrytype check function signature.
1367 * @param tile %Tile to check.
1368 * @return Succeeded or failed command.
1370 typedef CommandCost CheckNewIndustryProc(TileIndex tile);
1372 /** Check functions for different types of industry. */
1373 static CheckNewIndustryProc * const _check_new_industry_procs[CHECK_END] = {
1374 CheckNewIndustry_NULL, ///< CHECK_NOTHING
1375 CheckNewIndustry_Forest, ///< CHECK_FOREST
1376 CheckNewIndustry_OilRefinery, ///< CHECK_REFINERY
1377 CheckNewIndustry_Farm, ///< CHECK_FARM
1378 CheckNewIndustry_Plantation, ///< CHECK_PLANTATION
1379 CheckNewIndustry_Water, ///< CHECK_WATER
1380 CheckNewIndustry_Lumbermill, ///< CHECK_LUMBERMILL
1381 CheckNewIndustry_BubbleGen, ///< CHECK_BUBBLEGEN
1382 CheckNewIndustry_OilRig, ///< CHECK_OIL_RIG
1386 * Find a town for the industry, while checking for multiple industries in the same town.
1387 * @param tile Position of the industry to build.
1388 * @param type Industry type.
1389 * @param[out] t Pointer to return town for the new industry, \c nullptr is written if no good town can be found.
1390 * @return Succeeded or failed command.
1392 * @pre \c *t != nullptr
1393 * @post \c *t points to a town on success, and \c nullptr on failure.
1395 static CommandCost FindTownForIndustry(TileIndex tile, int type, Town **t)
1397 *t = ClosestTownFromTile(tile, UINT_MAX);
1399 if (_settings_game.economy.multiple_industry_per_town) return CommandCost();
1401 for (const Industry *i : Industry::Iterate()) {
1402 if (i->type == (byte)type && i->town == *t) {
1403 *t = nullptr;
1404 return_cmd_error(STR_ERROR_ONLY_ONE_ALLOWED_PER_TOWN);
1408 return CommandCost();
1411 bool IsSlopeRefused(Slope current, Slope refused)
1413 if (IsSteepSlope(current)) return true;
1414 if (current != SLOPE_FLAT) {
1415 if (IsSteepSlope(refused)) return true;
1417 Slope t = ComplementSlope(current);
1419 if ((refused & SLOPE_W) && (t & SLOPE_NW)) return true;
1420 if ((refused & SLOPE_S) && (t & SLOPE_NE)) return true;
1421 if ((refused & SLOPE_E) && (t & SLOPE_SW)) return true;
1422 if ((refused & SLOPE_N) && (t & SLOPE_SE)) return true;
1425 return false;
1429 * Are the tiles of the industry free?
1430 * @param tile Position to check.
1431 * @param layout Industry tiles table.
1432 * @param layout_index The index of the layout to build/fund
1433 * @param type Type of the industry.
1434 * @param initial_random_bits The random bits the industry is going to have after construction.
1435 * @param founder Industry founder
1436 * @param creation_type The circumstances the industry is created under.
1437 * @param[out] custom_shape_check Perform custom check for the site.
1438 * @return Failed or succeeded command.
1440 static CommandCost CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileLayout &layout, size_t layout_index, int type, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type, bool *custom_shape_check = nullptr)
1442 bool refused_slope = false;
1443 bool custom_shape = false;
1445 for (const IndustryTileLayoutTile &it : layout) {
1446 IndustryGfx gfx = GetTranslatedIndustryTileID(it.gfx);
1447 TileIndex cur_tile = TileAddWrap(tile, it.ti.x, it.ti.y);
1449 if (!IsValidTile(cur_tile)) {
1450 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1453 if (gfx == GFX_WATERTILE_SPECIALCHECK) {
1454 if (!IsWaterTile(cur_tile) ||
1455 !IsTileFlat(cur_tile)) {
1456 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1458 } else {
1459 CommandCost ret = EnsureNoVehicleOnGround(cur_tile);
1460 if (ret.Failed()) return ret;
1461 if (IsBridgeAbove(cur_tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1463 const IndustryTileSpec *its = GetIndustryTileSpec(gfx);
1465 IndustryBehaviour ind_behav = GetIndustrySpec(type)->behaviour;
1467 /* Perform land/water check if not disabled */
1468 if (!HasBit(its->slopes_refused, 5) && ((HasTileWaterClass(cur_tile) && IsTileOnWater(cur_tile)) == !(ind_behav & INDUSTRYBEH_BUILT_ONWATER))) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1470 if (HasBit(its->callback_mask, CBM_INDT_SHAPE_CHECK)) {
1471 custom_shape = true;
1472 CommandCost ret = PerformIndustryTileSlopeCheck(tile, cur_tile, its, type, gfx, layout_index, initial_random_bits, founder, creation_type);
1473 if (ret.Failed()) return ret;
1474 } else {
1475 Slope tileh = GetTileSlope(cur_tile);
1476 refused_slope |= IsSlopeRefused(tileh, its->slopes_refused);
1479 if ((ind_behav & (INDUSTRYBEH_ONLY_INTOWN | INDUSTRYBEH_TOWN1200_MORE)) || // Tile must be a house
1480 ((ind_behav & INDUSTRYBEH_ONLY_NEARTOWN) && IsTileType(cur_tile, MP_HOUSE))) { // Tile is allowed to be a house (and it is a house)
1481 if (!IsTileType(cur_tile, MP_HOUSE)) {
1482 return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_TOWNS);
1485 /* Clear the tiles as OWNER_TOWN to not affect town rating, and to not clear protected buildings */
1486 Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1487 CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(DC_NONE, cur_tile);
1488 cur_company.Restore();
1490 if (ret.Failed()) return ret;
1491 } else {
1492 /* Clear the tiles, but do not affect town ratings */
1493 CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, cur_tile);
1495 if (ret.Failed()) return ret;
1500 if (custom_shape_check != nullptr) *custom_shape_check = custom_shape;
1502 /* It is almost impossible to have a fully flat land in TG, so what we
1503 * do is that we check if we can make the land flat later on. See
1504 * CheckIfCanLevelIndustryPlatform(). */
1505 if (!refused_slope || (_settings_game.game_creation.land_generator == LG_TERRAGENESIS && _generating_world && !custom_shape && !_ignore_restrictions)) {
1506 return CommandCost();
1508 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1512 * Is the industry allowed to be built at this place for the town?
1513 * @param tile Tile to construct the industry.
1514 * @param type Type of the industry.
1515 * @param t Town authority that the industry belongs to.
1516 * @return Succeeded or failed command.
1518 static CommandCost CheckIfIndustryIsAllowed(TileIndex tile, int type, const Town *t)
1520 if ((GetIndustrySpec(type)->behaviour & INDUSTRYBEH_TOWN1200_MORE) && t->cache.population < 1200) {
1521 return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_TOWNS_WITH_POPULATION_OF_1200);
1524 if ((GetIndustrySpec(type)->behaviour & INDUSTRYBEH_ONLY_NEARTOWN) && DistanceMax(t->xy, tile) > 9) {
1525 return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_NEAR_TOWN_CENTER);
1528 return CommandCost();
1531 static bool CheckCanTerraformSurroundingTiles(TileIndex tile, uint height, int internal)
1533 /* Check if we don't leave the map */
1534 if (TileX(tile) == 0 || TileY(tile) == 0 || GetTileType(tile) == MP_VOID) return false;
1536 TileArea ta(tile - TileDiffXY(1, 1), 2, 2);
1537 for (TileIndex tile_walk : ta) {
1538 uint curh = TileHeight(tile_walk);
1539 /* Is the tile clear? */
1540 if ((GetTileType(tile_walk) != MP_CLEAR) && (GetTileType(tile_walk) != MP_TREES)) return false;
1542 /* Don't allow too big of a change if this is the sub-tile check */
1543 if (internal != 0 && Delta(curh, height) > 1) return false;
1545 /* Different height, so the surrounding tiles of this tile
1546 * has to be correct too (in level, or almost in level)
1547 * else you get a chain-reaction of terraforming. */
1548 if (internal == 0 && curh != height) {
1549 if (TileX(tile_walk) == 0 || TileY(tile_walk) == 0 || !CheckCanTerraformSurroundingTiles(tile_walk + TileDiffXY(-1, -1), height, internal + 1)) {
1550 return false;
1555 return true;
1559 * This function tries to flatten out the land below an industry, without
1560 * damaging the surroundings too much.
1562 static bool CheckIfCanLevelIndustryPlatform(TileIndex tile, DoCommandFlag flags, const IndustryTileLayout &layout, int type)
1564 int max_x = 0;
1565 int max_y = 0;
1567 /* Finds dimensions of largest variant of this industry */
1568 for (const IndustryTileLayoutTile &it : layout) {
1569 if (it.gfx == GFX_WATERTILE_SPECIALCHECK) continue; // watercheck tiles don't count for footprint size
1570 if (it.ti.x > max_x) max_x = it.ti.x;
1571 if (it.ti.y > max_y) max_y = it.ti.y;
1574 /* Remember level height */
1575 uint h = TileHeight(tile);
1577 if (TileX(tile) <= _settings_game.construction.industry_platform + 1U || TileY(tile) <= _settings_game.construction.industry_platform + 1U) return false;
1578 /* Check that all tiles in area and surrounding are clear
1579 * this determines that there are no obstructing items */
1581 /* TileArea::Expand is not used here as we need to abort
1582 * instead of clamping if the bounds cannot expanded. */
1583 TileArea ta(tile + TileDiffXY(-_settings_game.construction.industry_platform, -_settings_game.construction.industry_platform),
1584 max_x + 2 + 2 * _settings_game.construction.industry_platform, max_y + 2 + 2 * _settings_game.construction.industry_platform);
1586 if (TileX(ta.tile) + ta.w >= MapMaxX() || TileY(ta.tile) + ta.h >= MapMaxY()) return false;
1588 /* _current_company is OWNER_NONE for randomly generated industries and in editor, or the company who funded or prospected the industry.
1589 * Perform terraforming as OWNER_TOWN to disable autoslope and town ratings. */
1590 Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1592 for (TileIndex tile_walk : ta) {
1593 uint curh = TileHeight(tile_walk);
1594 if (curh != h) {
1595 /* This tile needs terraforming. Check if we can do that without
1596 * damaging the surroundings too much. */
1597 if (!CheckCanTerraformSurroundingTiles(tile_walk, h, 0)) {
1598 cur_company.Restore();
1599 return false;
1601 /* This is not 100% correct check, but the best we can do without modifying the map.
1602 * What is missing, is if the difference in height is more than 1.. */
1603 if (std::get<0>(Command<CMD_TERRAFORM_LAND>::Do(flags & ~DC_EXEC, tile_walk, SLOPE_N, curh <= h)).Failed()) {
1604 cur_company.Restore();
1605 return false;
1610 if (flags & DC_EXEC) {
1611 /* Terraform the land under the industry */
1612 for (TileIndex tile_walk : ta) {
1613 uint curh = TileHeight(tile_walk);
1614 while (curh != h) {
1615 /* We give the terraforming for free here, because we can't calculate
1616 * exact cost in the test-round, and as we all know, that will cause
1617 * a nice assert if they don't match ;) */
1618 Command<CMD_TERRAFORM_LAND>::Do(flags, tile_walk, SLOPE_N, curh <= h);
1619 curh += (curh > h) ? -1 : 1;
1624 cur_company.Restore();
1625 return true;
1630 * Check that the new industry is far enough from conflicting industries.
1631 * @param tile Tile to construct the industry.
1632 * @param type Type of the new industry.
1633 * @return Succeeded or failed command.
1635 static CommandCost CheckIfFarEnoughFromConflictingIndustry(TileIndex tile, int type)
1637 const IndustrySpec *indspec = GetIndustrySpec(type);
1639 /* On a large map with many industries, it may be faster to check an area. */
1640 static const int dmax = 14;
1641 if (Industry::GetNumItems() > (size_t) (dmax * dmax * 2)) {
1642 const Industry* i = nullptr;
1643 TileArea tile_area = TileArea(tile, 1, 1).Expand(dmax);
1644 for (TileIndex atile : tile_area) {
1645 if (GetTileType(atile) == MP_INDUSTRY) {
1646 const Industry *i2 = Industry::GetByTile(atile);
1647 if (i == i2) continue;
1648 i = i2;
1649 if (DistanceMax(tile, i->location.tile) > (uint)dmax) continue;
1650 if (i->type == indspec->conflicting[0] ||
1651 i->type == indspec->conflicting[1] ||
1652 i->type == indspec->conflicting[2]) {
1653 return_cmd_error(STR_ERROR_INDUSTRY_TOO_CLOSE);
1657 return CommandCost();
1660 for (const Industry *i : Industry::Iterate()) {
1661 /* Within 14 tiles from another industry is considered close */
1662 if (DistanceMax(tile, i->location.tile) > 14) continue;
1664 /* check if there are any conflicting industry types around */
1665 if (i->type == indspec->conflicting[0] ||
1666 i->type == indspec->conflicting[1] ||
1667 i->type == indspec->conflicting[2]) {
1668 return_cmd_error(STR_ERROR_INDUSTRY_TOO_CLOSE);
1671 return CommandCost();
1675 * Advertise about a new industry opening.
1676 * @param ind Industry being opened.
1678 static void AdvertiseIndustryOpening(const Industry *ind)
1680 const IndustrySpec *ind_spc = GetIndustrySpec(ind->type);
1681 SetDParam(0, ind_spc->name);
1682 if (ind_spc->new_industry_text > STR_LAST_STRINGID) {
1683 SetDParam(1, STR_TOWN_NAME);
1684 SetDParam(2, ind->town->index);
1685 } else {
1686 SetDParam(1, ind->town->index);
1688 AddIndustryNewsItem(ind_spc->new_industry_text, NT_INDUSTRY_OPEN, ind->index);
1689 AI::BroadcastNewEvent(new ScriptEventIndustryOpen(ind->index));
1690 Game::NewEvent(new ScriptEventIndustryOpen(ind->index));
1694 * Populate an industry's list of nearby stations, and if it accepts any cargo, also
1695 * add the industry to each station's nearby industry list.
1696 * @param ind Industry
1698 static void PopulateStationsNearby(Industry *ind)
1700 if (ind->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) {
1701 /* Industry has a neutral station. Use it and ignore any other nearby stations. */
1702 ind->stations_near.insert(ind->neutral_station);
1703 ind->neutral_station->industries_near.clear();
1704 ind->neutral_station->industries_near.insert(IndustryListEntry{0, ind});
1705 return;
1708 ForAllStationsAroundTiles(ind->location, [ind](Station *st, TileIndex tile) {
1709 if (!IsTileType(tile, MP_INDUSTRY) || GetIndustryIndex(tile) != ind->index) return false;
1710 ind->stations_near.insert(st);
1711 st->AddIndustryToDeliver(ind, tile);
1712 return false;
1717 * Put an industry on the map.
1718 * @param i Just allocated poolitem, mostly empty.
1719 * @param tile North tile of the industry.
1720 * @param type Type of the industry.
1721 * @param layout Industrylayout to build.
1722 * @param layout_index Number of the industry layout.
1723 * @param t Nearest town.
1724 * @param founder Founder of the industry; OWNER_NONE in case of random construction.
1725 * @param initial_random_bits Random bits for the industry.
1727 static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type, const IndustryTileLayout &layout, size_t layout_index, Town *t, Owner founder, uint16 initial_random_bits)
1729 const IndustrySpec *indspec = GetIndustrySpec(type);
1731 i->location = TileArea(tile, 1, 1);
1732 i->type = type;
1733 Industry::IncIndustryTypeCount(type);
1735 MemCpyT(i->produced_cargo, indspec->produced_cargo, lengthof(i->produced_cargo));
1736 MemCpyT(i->production_rate, indspec->production_rate, lengthof(i->production_rate));
1737 MemCpyT(i->accepts_cargo, indspec->accepts_cargo, lengthof(i->accepts_cargo));
1739 MemSetT(i->produced_cargo_waiting, 0, lengthof(i->produced_cargo_waiting));
1740 MemSetT(i->this_month_production, 0, lengthof(i->this_month_production));
1741 MemSetT(i->this_month_transported, 0, lengthof(i->this_month_transported));
1742 MemSetT(i->last_month_pct_transported, 0, lengthof(i->last_month_pct_transported));
1743 MemSetT(i->last_month_transported, 0, lengthof(i->last_month_transported));
1744 MemSetT(i->incoming_cargo_waiting, 0, lengthof(i->incoming_cargo_waiting));
1745 MemSetT(i->last_cargo_accepted_at, 0, lengthof(i->last_cargo_accepted_at));
1747 /* Randomize inital production if non-original economy is used and there are no production related callbacks. */
1748 if (!indspec->UsesOriginalEconomy()) {
1749 for (size_t ci = 0; ci < lengthof(i->production_rate); ci++) {
1750 i->production_rate[ci] = std::min((RandomRange(256) + 128) * i->production_rate[ci] >> 8, 255u);
1754 i->town = t;
1755 i->owner = OWNER_NONE;
1757 uint16 r = Random();
1758 i->random_colour = GB(r, 0, 4);
1759 i->counter = GB(r, 4, 12);
1760 i->random = initial_random_bits;
1761 i->was_cargo_delivered = false;
1762 i->last_prod_year = _cur_year;
1763 i->founder = founder;
1764 i->ctlflags = INDCTL_NONE;
1766 i->construction_date = _date;
1767 i->construction_type = (_game_mode == GM_EDITOR) ? ICT_SCENARIO_EDITOR :
1768 (_generating_world ? ICT_MAP_GENERATION : ICT_NORMAL_GAMEPLAY);
1770 /* Adding 1 here makes it conform to specs of var44 of varaction2 for industries
1771 * 0 = created prior of newindustries
1772 * else, chosen layout + 1 */
1773 i->selected_layout = (byte)(layout_index + 1);
1775 i->exclusive_supplier = INVALID_OWNER;
1776 i->exclusive_consumer = INVALID_OWNER;
1778 i->prod_level = PRODLEVEL_DEFAULT;
1780 /* Call callbacks after the regular fields got initialised. */
1782 if (HasBit(indspec->callback_mask, CBM_IND_PROD_CHANGE_BUILD)) {
1783 uint16 res = GetIndustryCallback(CBID_INDUSTRY_PROD_CHANGE_BUILD, 0, Random(), i, type, INVALID_TILE);
1784 if (res != CALLBACK_FAILED) {
1785 if (res < PRODLEVEL_MINIMUM || res > PRODLEVEL_MAXIMUM) {
1786 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_PROD_CHANGE_BUILD, res);
1787 } else {
1788 i->prod_level = res;
1789 i->RecomputeProductionMultipliers();
1794 if (_generating_world) {
1795 if (HasBit(indspec->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) {
1796 IndustryProductionCallback(i, 1);
1797 for (size_t ci = 0; ci < lengthof(i->last_month_production); ci++) {
1798 i->last_month_production[ci] = i->produced_cargo_waiting[ci] * 8;
1799 i->produced_cargo_waiting[ci] = 0;
1803 for (size_t ci = 0; ci < lengthof(i->last_month_production); ci++) {
1804 i->last_month_production[ci] += i->production_rate[ci] * 8;
1808 if (HasBit(indspec->callback_mask, CBM_IND_DECIDE_COLOUR)) {
1809 uint16 res = GetIndustryCallback(CBID_INDUSTRY_DECIDE_COLOUR, 0, 0, i, type, INVALID_TILE);
1810 if (res != CALLBACK_FAILED) {
1811 if (GB(res, 4, 11) != 0) ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_DECIDE_COLOUR, res);
1812 i->random_colour = GB(res, 0, 4);
1816 if (HasBit(indspec->callback_mask, CBM_IND_INPUT_CARGO_TYPES)) {
1817 /* Clear all input cargo types */
1818 for (uint j = 0; j < lengthof(i->accepts_cargo); j++) i->accepts_cargo[j] = CT_INVALID;
1819 /* Query actual types */
1820 uint maxcargoes = (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) ? lengthof(i->accepts_cargo) : 3;
1821 for (uint j = 0; j < maxcargoes; j++) {
1822 uint16 res = GetIndustryCallback(CBID_INDUSTRY_INPUT_CARGO_TYPES, j, 0, i, type, INVALID_TILE);
1823 if (res == CALLBACK_FAILED || GB(res, 0, 8) == CT_INVALID) break;
1824 if (indspec->grf_prop.grffile->grf_version >= 8 && res >= 0x100) {
1825 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_INPUT_CARGO_TYPES, res);
1826 break;
1828 CargoID cargo = GetCargoTranslation(GB(res, 0, 8), indspec->grf_prop.grffile);
1829 /* Industries without "unlimited" cargo types support depend on the specific order/slots of cargo types.
1830 * They need to be able to blank out specific slots without aborting the callback sequence,
1831 * and solve this by returning undefined cargo indexes. Skip these. */
1832 if (cargo == CT_INVALID && !(indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED)) continue;
1833 /* Verify valid cargo */
1834 if (std::find(indspec->accepts_cargo, endof(indspec->accepts_cargo), cargo) == endof(indspec->accepts_cargo)) {
1835 /* Cargo not in spec, error in NewGRF */
1836 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_INPUT_CARGO_TYPES, res);
1837 break;
1839 if (std::find(i->accepts_cargo, i->accepts_cargo + j, cargo) != i->accepts_cargo + j) {
1840 /* Duplicate cargo */
1841 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_INPUT_CARGO_TYPES, res);
1842 break;
1844 i->accepts_cargo[j] = cargo;
1848 if (HasBit(indspec->callback_mask, CBM_IND_OUTPUT_CARGO_TYPES)) {
1849 /* Clear all output cargo types */
1850 for (uint j = 0; j < lengthof(i->produced_cargo); j++) i->produced_cargo[j] = CT_INVALID;
1851 /* Query actual types */
1852 uint maxcargoes = (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) ? lengthof(i->produced_cargo) : 2;
1853 for (uint j = 0; j < maxcargoes; j++) {
1854 uint16 res = GetIndustryCallback(CBID_INDUSTRY_OUTPUT_CARGO_TYPES, j, 0, i, type, INVALID_TILE);
1855 if (res == CALLBACK_FAILED || GB(res, 0, 8) == CT_INVALID) break;
1856 if (indspec->grf_prop.grffile->grf_version >= 8 && res >= 0x100) {
1857 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_OUTPUT_CARGO_TYPES, res);
1858 break;
1860 CargoID cargo = GetCargoTranslation(GB(res, 0, 8), indspec->grf_prop.grffile);
1861 /* Allow older GRFs to skip slots. */
1862 if (cargo == CT_INVALID && !(indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED)) continue;
1863 /* Verify valid cargo */
1864 if (std::find(indspec->produced_cargo, endof(indspec->produced_cargo), cargo) == endof(indspec->produced_cargo)) {
1865 /* Cargo not in spec, error in NewGRF */
1866 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_OUTPUT_CARGO_TYPES, res);
1867 break;
1869 if (std::find(i->produced_cargo, i->produced_cargo + j, cargo) != i->produced_cargo + j) {
1870 /* Duplicate cargo */
1871 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_OUTPUT_CARGO_TYPES, res);
1872 break;
1874 i->produced_cargo[j] = cargo;
1878 /* Plant the tiles */
1880 for (const IndustryTileLayoutTile &it : layout) {
1881 TileIndex cur_tile = tile + ToTileIndexDiff(it.ti);
1883 if (it.gfx != GFX_WATERTILE_SPECIALCHECK) {
1884 i->location.Add(cur_tile);
1886 WaterClass wc = (IsWaterTile(cur_tile) ? GetWaterClass(cur_tile) : WATER_CLASS_INVALID);
1888 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, cur_tile);
1890 MakeIndustry(cur_tile, i->index, it.gfx, Random(), wc);
1892 if (_generating_world) {
1893 SetIndustryConstructionCounter(cur_tile, 3);
1894 SetIndustryConstructionStage(cur_tile, 2);
1897 /* it->gfx is stored in the map. But the translated ID cur_gfx is the interesting one */
1898 IndustryGfx cur_gfx = GetTranslatedIndustryTileID(it.gfx);
1899 const IndustryTileSpec *its = GetIndustryTileSpec(cur_gfx);
1900 if (its->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(cur_tile);
1904 if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
1905 for (uint j = 0; j != 50; j++) PlantRandomFarmField(i);
1907 InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, IDIWD_FORCE_REBUILD);
1909 if (!_generating_world) PopulateStationsNearby(i);
1913 * Helper function for Build/Fund an industry
1914 * @param tile tile where industry is built
1915 * @param type of industry to build
1916 * @param flags of operations to conduct
1917 * @param indspec pointer to industry specifications
1918 * @param layout_index the index of the itsepc to build/fund
1919 * @param random_var8f random seed (possibly) used by industries
1920 * @param random_initial_bits The random bits the industry is going to have after construction.
1921 * @param founder Founder of the industry
1922 * @param creation_type The circumstances the industry is created under.
1923 * @param[out] ip Pointer to store newly created industry.
1924 * @return Succeeded or failed command.
1926 * @post \c *ip contains the newly created industry if all checks are successful and the \a flags request actual creation, else it contains \c nullptr afterwards.
1928 static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, DoCommandFlag flags, const IndustrySpec *indspec, size_t layout_index, uint32 random_var8f, uint16 random_initial_bits, Owner founder, IndustryAvailabilityCallType creation_type, Industry **ip)
1930 assert(layout_index < indspec->layouts.size());
1931 const IndustryTileLayout &layout = indspec->layouts[layout_index];
1932 bool custom_shape_check = false;
1934 *ip = nullptr;
1936 std::vector<ClearedObjectArea> object_areas(_cleared_object_areas);
1937 CommandCost ret = CheckIfIndustryTilesAreFree(tile, layout, layout_index, type, random_initial_bits, founder, creation_type, &custom_shape_check);
1938 _cleared_object_areas = object_areas;
1939 if (ret.Failed()) return ret;
1941 if (HasBit(GetIndustrySpec(type)->callback_mask, CBM_IND_LOCATION)) {
1942 ret = CheckIfCallBackAllowsCreation(tile, type, layout_index, random_var8f, random_initial_bits, founder, creation_type);
1943 } else {
1944 ret = _check_new_industry_procs[indspec->check_proc](tile);
1946 if (ret.Failed()) return ret;
1948 if (!custom_shape_check && _settings_game.game_creation.land_generator == LG_TERRAGENESIS && _generating_world &&
1949 !_ignore_restrictions && !CheckIfCanLevelIndustryPlatform(tile, DC_NO_WATER, layout, type)) {
1950 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1953 ret = CheckIfFarEnoughFromConflictingIndustry(tile, type);
1954 if (ret.Failed()) return ret;
1956 Town *t = nullptr;
1957 ret = FindTownForIndustry(tile, type, &t);
1958 if (ret.Failed()) return ret;
1959 assert(t != nullptr);
1961 ret = CheckIfIndustryIsAllowed(tile, type, t);
1962 if (ret.Failed()) return ret;
1964 if (!Industry::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_INDUSTRIES);
1966 if (flags & DC_EXEC) {
1967 *ip = new Industry(tile);
1968 if (!custom_shape_check) CheckIfCanLevelIndustryPlatform(tile, DC_NO_WATER | DC_EXEC, layout, type);
1969 DoCreateNewIndustry(*ip, tile, type, layout, layout_index, t, founder, random_initial_bits);
1972 return CommandCost();
1976 * Build/Fund an industry
1977 * @param flags of operations to conduct
1978 * @param tile tile where industry is built
1979 * @param it industry type see build_industry.h and see industry.h
1980 * @param first_layout first layout to try
1981 * @param fund false = prospect, true = fund (only valid if current company is DEITY)
1982 * @param seed seed to use for desyncfree randomisations
1983 * @return the cost of this operation or an error
1985 CommandCost CmdBuildIndustry(DoCommandFlag flags, TileIndex tile, IndustryType it, uint32 first_layout, bool fund, uint32 seed)
1987 if (it >= NUM_INDUSTRYTYPES) return CMD_ERROR;
1989 const IndustrySpec *indspec = GetIndustrySpec(it);
1991 /* Check if the to-be built/founded industry is available for this climate. */
1992 if (!indspec->enabled || indspec->layouts.empty()) return CMD_ERROR;
1994 /* If the setting for raw-material industries is not on, you cannot build raw-material industries.
1995 * Raw material industries are industries that do not accept cargo (at least for now) */
1996 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 0 && indspec->IsRawIndustry()) {
1997 return CMD_ERROR;
2000 if (_game_mode != GM_EDITOR && GetIndustryProbabilityCallback(it, _current_company == OWNER_DEITY ? IACT_RANDOMCREATION : IACT_USERCREATION, 1) == 0) {
2001 return CMD_ERROR;
2004 Randomizer randomizer;
2005 randomizer.SetSeed(seed);
2006 uint16 random_initial_bits = GB(seed, 0, 16);
2007 uint32 random_var8f = randomizer.Next();
2008 size_t num_layouts = indspec->layouts.size();
2009 CommandCost ret = CommandCost(STR_ERROR_SITE_UNSUITABLE);
2010 const bool deity_prospect = _current_company == OWNER_DEITY && !fund;
2012 Industry *ind = nullptr;
2013 if (deity_prospect || (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 2 && indspec->IsRawIndustry())) {
2014 if (flags & DC_EXEC) {
2015 /* Prospected industries are build as OWNER_TOWN to not e.g. be build on owned land of the founder */
2016 Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
2017 /* Prospecting has a chance to fail, however we cannot guarantee that something can
2018 * be built on the map, so the chance gets lower when the map is fuller, but there
2019 * is nothing we can really do about that. */
2020 if (deity_prospect || Random() <= indspec->prospecting_chance) {
2021 for (int i = 0; i < 5000; i++) {
2022 /* We should not have more than one Random() in a function call
2023 * because parameter evaluation order is not guaranteed in the c++ standard
2025 tile = RandomTile();
2026 /* Start with a random layout */
2027 size_t layout = RandomRange((uint32)num_layouts);
2028 /* Check now each layout, starting with the random one */
2029 for (size_t j = 0; j < num_layouts; j++) {
2030 layout = (layout + 1) % num_layouts;
2031 ret = CreateNewIndustryHelper(tile, it, flags, indspec, layout, random_var8f, random_initial_bits, cur_company.GetOriginalValue(), _current_company == OWNER_DEITY ? IACT_RANDOMCREATION : IACT_PROSPECTCREATION, &ind);
2032 if (ret.Succeeded()) break;
2034 if (ret.Succeeded()) break;
2037 cur_company.Restore();
2039 } else {
2040 size_t layout = first_layout;
2041 if (layout >= num_layouts) return CMD_ERROR;
2043 /* Check subsequently each layout, starting with the given layout in p1 */
2044 for (size_t i = 0; i < num_layouts; i++) {
2045 layout = (layout + 1) % num_layouts;
2046 ret = CreateNewIndustryHelper(tile, it, flags, indspec, layout, random_var8f, random_initial_bits, _current_company, _current_company == OWNER_DEITY ? IACT_RANDOMCREATION : IACT_USERCREATION, &ind);
2047 if (ret.Succeeded()) break;
2050 /* If it still failed, there's no suitable layout to build here, return the error */
2051 if (ret.Failed()) return ret;
2054 if ((flags & DC_EXEC) && ind != nullptr && _game_mode != GM_EDITOR) {
2055 AdvertiseIndustryOpening(ind);
2058 return CommandCost(EXPENSES_OTHER, indspec->GetConstructionCost());
2062 * Change industry properties
2063 * @param flags Type of operation.
2064 * @param ind_id IndustryID
2065 * @param action IndustryAction to perform
2066 * @param ctlflags IndustryControlFlags (only used with set control flags)
2067 * @param company_id CompanyID to set or INVALID_OWNER (available to everyone) or
2068 * OWNER_NONE (neutral stations only) or OWNER_DEITY (no one)
2069 * (only used with set exclusive supplier / consumer)
2070 * @param text - Additional industry text (only used with set text action)
2071 * @return Empty cost or an error.
2073 CommandCost CmdIndustryCtrl(DoCommandFlag flags, IndustryID ind_id, IndustryAction action, IndustryControlFlags ctlflags, Owner company_id, const std::string &text)
2075 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2077 Industry *ind = Industry::GetIfValid(ind_id);
2078 if (ind == nullptr) return CMD_ERROR;
2080 switch (action) {
2081 case IndustryAction::SetControlFlags: {
2082 if (flags & DC_EXEC) ind->ctlflags = ctlflags & INDCTL_MASK;
2084 break;
2087 case IndustryAction::SetExclusiveSupplier:
2088 case IndustryAction::SetExclusiveConsumer: {
2089 if (company_id != OWNER_NONE && company_id != INVALID_OWNER && company_id != OWNER_DEITY
2090 && !Company::IsValidID(company_id)) return CMD_ERROR;
2092 if (flags & DC_EXEC) {
2093 if (action == IndustryAction::SetExclusiveSupplier) {
2094 ind->exclusive_supplier = company_id;
2095 } else {
2096 ind->exclusive_consumer = company_id;
2100 break;
2103 case IndustryAction::SetText: {
2104 ind->text.clear();
2105 if (!text.empty()) ind->text = text;
2106 InvalidateWindowData(WC_INDUSTRY_VIEW, ind->index);
2107 break;
2110 default:
2111 return CMD_ERROR;
2114 return CommandCost();
2118 * Create a new industry of random layout.
2119 * @param tile The location to build the industry.
2120 * @param type The industry type to build.
2121 * @param creation_type The circumstances the industry is created under.
2122 * @return the created industry or nullptr if it failed.
2124 static Industry *CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAvailabilityCallType creation_type)
2126 const IndustrySpec *indspec = GetIndustrySpec(type);
2128 uint32 seed = Random();
2129 uint32 seed2 = Random();
2130 Industry *i = nullptr;
2131 size_t layout_index = RandomRange((uint32)indspec->layouts.size());
2132 [[maybe_unused]] CommandCost ret = CreateNewIndustryHelper(tile, type, DC_EXEC, indspec, layout_index, seed, GB(seed2, 0, 16), OWNER_NONE, creation_type, &i);
2133 assert(i != nullptr || ret.Failed());
2134 return i;
2138 * Compute the appearance probability for an industry during map creation.
2139 * @param it Industry type to compute.
2140 * @param[out] force_at_least_one Returns whether at least one instance should be forced on map creation.
2141 * @return Relative probability for the industry to appear.
2143 static uint32 GetScaledIndustryGenerationProbability(IndustryType it, bool *force_at_least_one)
2145 const IndustrySpec *ind_spc = GetIndustrySpec(it);
2146 uint32 chance = ind_spc->appear_creation[_settings_game.game_creation.landscape];
2147 if (!ind_spc->enabled || ind_spc->layouts.empty() ||
2148 (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) ||
2149 (chance = GetIndustryProbabilityCallback(it, IACT_MAPGENERATION, chance)) == 0) {
2150 *force_at_least_one = false;
2151 return 0;
2152 } else {
2153 chance *= 16; // to increase precision
2154 /* We want industries appearing at coast to appear less often on bigger maps, as length of coast increases slower than map area.
2155 * For simplicity we scale in both cases, though scaling the probabilities of all industries has no effect. */
2156 chance = (ind_spc->check_proc == CHECK_REFINERY || ind_spc->check_proc == CHECK_OIL_RIG) ? ScaleByMapSize1D(chance) : ScaleByMapSize(chance);
2158 *force_at_least_one = (chance > 0) && !(ind_spc->behaviour & INDUSTRYBEH_NOBUILT_MAPCREATION) && (_game_mode != GM_EDITOR);
2159 return chance;
2164 * Compute the probability for constructing a new industry during game play.
2165 * @param it Industry type to compute.
2166 * @param[out] min_number Minimal number of industries that should exist at the map.
2167 * @return Relative probability for the industry to appear.
2169 static uint16 GetIndustryGamePlayProbability(IndustryType it, byte *min_number)
2171 if (_settings_game.difficulty.industry_density == ID_FUND_ONLY) {
2172 *min_number = 0;
2173 return 0;
2176 const IndustrySpec *ind_spc = GetIndustrySpec(it);
2177 byte chance = ind_spc->appear_ingame[_settings_game.game_creation.landscape];
2178 if (!ind_spc->enabled || ind_spc->layouts.empty() ||
2179 ((ind_spc->behaviour & INDUSTRYBEH_BEFORE_1950) && _cur_year > 1950) ||
2180 ((ind_spc->behaviour & INDUSTRYBEH_AFTER_1960) && _cur_year < 1960) ||
2181 (chance = GetIndustryProbabilityCallback(it, IACT_RANDOMCREATION, chance)) == 0) {
2182 *min_number = 0;
2183 return 0;
2185 *min_number = (ind_spc->behaviour & INDUSTRYBEH_CANCLOSE_LASTINSTANCE) ? 1 : 0;
2186 return chance;
2190 * Get wanted number of industries on the map.
2191 * @return Wanted number of industries at the map.
2193 static uint GetNumberOfIndustries()
2195 /* Number of industries on a 256x256 map. */
2196 static const uint16 numof_industry_table[] = {
2197 0, // none
2198 0, // minimal
2199 10, // very low
2200 25, // low
2201 55, // normal
2202 80, // high
2205 assert(lengthof(numof_industry_table) == ID_END);
2206 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
2207 return std::min<uint>(IndustryPool::MAX_SIZE, ScaleByMapSize(numof_industry_table[difficulty]));
2211 * Try to place the industry in the game.
2212 * Since there is no feedback why placement fails, there is no other option
2213 * than to try a few times before concluding it does not work.
2214 * @param type Industry type of the desired industry.
2215 * @param try_hard Try very hard to find a place. (Used to place at least one industry per type.)
2216 * @return Pointer to created industry, or \c nullptr if creation failed.
2218 static Industry *PlaceIndustry(IndustryType type, IndustryAvailabilityCallType creation_type, bool try_hard)
2220 uint tries = try_hard ? 10000u : 2000u;
2221 for (; tries > 0; tries--) {
2222 Industry *ind = CreateNewIndustry(RandomTile(), type, creation_type);
2223 if (ind != nullptr) return ind;
2225 return nullptr;
2229 * Try to build a industry on the map.
2230 * @param type IndustryType of the desired industry
2231 * @param try_hard Try very hard to find a place. (Used to place at least one industry per type)
2233 static void PlaceInitialIndustry(IndustryType type, bool try_hard)
2235 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2237 IncreaseGeneratingWorldProgress(GWP_INDUSTRY);
2238 PlaceIndustry(type, IACT_MAPGENERATION, try_hard);
2240 cur_company.Restore();
2244 * Get total number of industries existing in the game.
2245 * @return Number of industries currently in the game.
2247 static uint GetCurrentTotalNumberOfIndustries()
2249 int total = 0;
2250 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) total += Industry::GetIndustryTypeCount(it);
2251 return total;
2255 /** Reset the entry. */
2256 void IndustryTypeBuildData::Reset()
2258 this->probability = 0;
2259 this->min_number = 0;
2260 this->target_count = 0;
2261 this->max_wait = 1;
2262 this->wait_count = 0;
2265 /** Completely reset the industry build data. */
2266 void IndustryBuildData::Reset()
2268 this->wanted_inds = GetCurrentTotalNumberOfIndustries() << 16;
2270 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2271 this->builddata[it].Reset();
2275 /** Monthly update of industry build data. */
2276 void IndustryBuildData::MonthlyLoop()
2278 static const int NEWINDS_PER_MONTH = 0x38000 / (10 * 12); // lower 16 bits is a float fraction, 3.5 industries per decade, divided by 10 * 12 months.
2279 if (_settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // 'no industries' setting.
2281 /* To prevent running out of unused industries for the player to connect,
2282 * add a fraction of new industries each month, but only if the manager can keep up. */
2283 uint max_behind = 1 + std::min(99u, ScaleByMapSize(3)); // At most 2 industries for small maps, and 100 at the biggest map (about 6 months industry build attempts).
2284 if (GetCurrentTotalNumberOfIndustries() + max_behind >= (this->wanted_inds >> 16)) {
2285 this->wanted_inds += ScaleByMapSize(NEWINDS_PER_MONTH);
2290 * This function will create random industries during game creation.
2291 * It will scale the amount of industries by mapsize and difficulty level.
2293 void GenerateIndustries()
2295 if (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // No industries in the game.
2297 uint32 industry_probs[NUM_INDUSTRYTYPES];
2298 bool force_at_least_one[NUM_INDUSTRYTYPES];
2299 uint32 total_prob = 0;
2300 uint num_forced = 0;
2302 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2303 industry_probs[it] = GetScaledIndustryGenerationProbability(it, force_at_least_one + it);
2304 total_prob += industry_probs[it];
2305 if (force_at_least_one[it]) num_forced++;
2308 uint total_amount = GetNumberOfIndustries();
2309 if (total_prob == 0 || total_amount < num_forced) {
2310 /* Only place the forced ones */
2311 total_amount = num_forced;
2314 SetGeneratingWorldProgress(GWP_INDUSTRY, total_amount);
2316 /* Try to build one industry per type independent of any probabilities */
2317 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2318 if (force_at_least_one[it]) {
2319 assert(total_amount > 0);
2320 total_amount--;
2321 PlaceInitialIndustry(it, true);
2325 /* Add the remaining industries according to their probabilities */
2326 for (uint i = 0; i < total_amount; i++) {
2327 uint32 r = RandomRange(total_prob);
2328 IndustryType it = 0;
2329 while (r >= industry_probs[it]) {
2330 r -= industry_probs[it];
2331 it++;
2332 assert(it < NUM_INDUSTRYTYPES);
2334 assert(industry_probs[it] > 0);
2335 PlaceInitialIndustry(it, false);
2337 _industry_builder.Reset();
2341 * Monthly update of industry statistics.
2342 * @param i Industry to update.
2344 static void UpdateIndustryStatistics(Industry *i)
2346 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
2347 if (i->produced_cargo[j] != CT_INVALID) {
2348 byte pct = 0;
2349 if (i->this_month_production[j] != 0) {
2350 i->last_prod_year = _cur_year;
2351 pct = std::min(i->this_month_transported[j] * 256 / i->this_month_production[j], 255);
2353 i->last_month_pct_transported[j] = pct;
2355 i->last_month_production[j] = i->this_month_production[j];
2356 i->this_month_production[j] = 0;
2358 i->last_month_transported[j] = i->this_month_transported[j];
2359 i->this_month_transported[j] = 0;
2365 * Recompute #production_rate for current #prod_level.
2366 * This function is only valid when not using smooth economy.
2368 void Industry::RecomputeProductionMultipliers()
2370 const IndustrySpec *indspec = GetIndustrySpec(this->type);
2371 assert(indspec->UsesOriginalEconomy());
2373 /* Rates are rounded up, so e.g. oilrig always produces some passengers */
2374 for (size_t i = 0; i < lengthof(this->production_rate); i++) {
2375 this->production_rate[i] = std::min(CeilDiv(indspec->production_rate[i] * this->prod_level, PRODLEVEL_DEFAULT), 0xFFu);
2379 void Industry::FillCachedName() const
2381 char buf[256];
2382 int64 args_array[] = { this->index };
2383 StringParameters tmp_params(args_array);
2384 char *end = GetStringWithArgs(buf, STR_INDUSTRY_NAME, &tmp_params, lastof(buf));
2385 this->cached_name.assign(buf, end);
2388 void ClearAllIndustryCachedNames()
2390 for (Industry *ind : Industry::Iterate()) {
2391 ind->cached_name.clear();
2396 * Set the #probability and #min_number fields for the industry type \a it for a running game.
2397 * @param it Industry type.
2398 * @return At least one of the fields has changed value.
2400 bool IndustryTypeBuildData::GetIndustryTypeData(IndustryType it)
2402 byte min_number;
2403 uint32 probability = GetIndustryGamePlayProbability(it, &min_number);
2404 bool changed = min_number != this->min_number || probability != this->probability;
2405 this->min_number = min_number;
2406 this->probability = probability;
2407 return changed;
2410 /** Decide how many industries of each type are needed. */
2411 void IndustryBuildData::SetupTargetCount()
2413 bool changed = false;
2414 uint num_planned = 0; // Number of industries planned in the industry build data.
2415 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2416 changed |= this->builddata[it].GetIndustryTypeData(it);
2417 num_planned += this->builddata[it].target_count;
2419 uint total_amount = this->wanted_inds >> 16; // Desired total number of industries.
2420 changed |= num_planned != total_amount;
2421 if (!changed) return; // All industries are still the same, no need to re-randomize.
2423 /* Initialize the target counts. */
2424 uint force_build = 0; // Number of industries that should always be available.
2425 uint32 total_prob = 0; // Sum of probabilities.
2426 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2427 IndustryTypeBuildData *ibd = this->builddata + it;
2428 force_build += ibd->min_number;
2429 ibd->target_count = ibd->min_number;
2430 total_prob += ibd->probability;
2433 if (total_prob == 0) return; // No buildable industries.
2435 /* Subtract forced industries from the number of industries available for construction. */
2436 total_amount = (total_amount <= force_build) ? 0 : total_amount - force_build;
2438 /* Assign number of industries that should be aimed for, by using the probability as a weight. */
2439 while (total_amount > 0) {
2440 uint32 r = RandomRange(total_prob);
2441 IndustryType it = 0;
2442 while (r >= this->builddata[it].probability) {
2443 r -= this->builddata[it].probability;
2444 it++;
2445 assert(it < NUM_INDUSTRYTYPES);
2447 assert(this->builddata[it].probability > 0);
2448 this->builddata[it].target_count++;
2449 total_amount--;
2454 * Try to create a random industry, during gameplay
2456 void IndustryBuildData::TryBuildNewIndustry()
2458 this->SetupTargetCount();
2460 int missing = 0; // Number of industries that need to be build.
2461 uint count = 0; // Number of industry types eligible for build.
2462 uint32 total_prob = 0; // Sum of probabilities.
2463 IndustryType forced_build = NUM_INDUSTRYTYPES; // Industry type that should be forcibly build.
2464 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2465 int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it);
2466 missing += difference;
2467 if (this->builddata[it].wait_count > 0) continue; // This type may not be built now.
2468 if (difference > 0) {
2469 if (Industry::GetIndustryTypeCount(it) == 0 && this->builddata[it].min_number > 0) {
2470 /* An industry that should exist at least once, is not available. Force it, trying the most needed one first. */
2471 if (forced_build == NUM_INDUSTRYTYPES ||
2472 difference > this->builddata[forced_build].target_count - Industry::GetIndustryTypeCount(forced_build)) {
2473 forced_build = it;
2476 total_prob += difference;
2477 count++;
2481 if (EconomyIsInRecession() || (forced_build == NUM_INDUSTRYTYPES && (missing <= 0 || total_prob == 0))) count = 0; // Skip creation of an industry.
2483 if (count >= 1) {
2484 /* If not forced, pick a weighted random industry to build.
2485 * For the case that count == 1, there is no need to draw a random number. */
2486 IndustryType it;
2487 if (forced_build != NUM_INDUSTRYTYPES) {
2488 it = forced_build;
2489 } else {
2490 /* Non-forced, select an industry type to build (weighted random). */
2491 uint32 r = 0; // Initialized to silence the compiler.
2492 if (count > 1) r = RandomRange(total_prob);
2493 for (it = 0; it < NUM_INDUSTRYTYPES; it++) {
2494 if (this->builddata[it].wait_count > 0) continue; // Type may not be built now.
2495 int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it);
2496 if (difference <= 0) continue; // Too many of this kind.
2497 if (count == 1) break;
2498 if (r < (uint)difference) break;
2499 r -= difference;
2501 assert(it < NUM_INDUSTRYTYPES && this->builddata[it].target_count > Industry::GetIndustryTypeCount(it));
2504 /* Try to create the industry. */
2505 const Industry *ind = PlaceIndustry(it, IACT_RANDOMCREATION, false);
2506 if (ind == nullptr) {
2507 this->builddata[it].wait_count = this->builddata[it].max_wait + 1; // Compensate for decrementing below.
2508 this->builddata[it].max_wait = std::min(1000, this->builddata[it].max_wait + 2);
2509 } else {
2510 AdvertiseIndustryOpening(ind);
2511 this->builddata[it].max_wait = std::max(this->builddata[it].max_wait / 2, 1); // Reduce waiting time of the industry type.
2515 /* Decrement wait counters. */
2516 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2517 if (this->builddata[it].wait_count > 0) this->builddata[it].wait_count--;
2522 * Protects an industry from closure if the appropriate flags and conditions are met
2523 * INDUSTRYBEH_CANCLOSE_LASTINSTANCE must be set (which, by default, it is not) and the
2524 * count of industries of this type must one (or lower) in order to be protected
2525 * against closure.
2526 * @param type IndustryType been queried
2527 * @result true if protection is on, false otherwise (except for oil wells)
2529 static bool CheckIndustryCloseDownProtection(IndustryType type)
2531 const IndustrySpec *indspec = GetIndustrySpec(type);
2533 /* oil wells (or the industries with that flag set) are always allowed to closedown */
2534 if ((indspec->behaviour & INDUSTRYBEH_DONT_INCR_PROD) && _settings_game.game_creation.landscape == LT_TEMPERATE) return false;
2535 return (indspec->behaviour & INDUSTRYBEH_CANCLOSE_LASTINSTANCE) == 0 && Industry::GetIndustryTypeCount(type) <= 1;
2539 * Can given cargo type be accepted or produced by the industry?
2540 * @param cargo: Cargo type
2541 * @param ind: Industry
2542 * @param *c_accepts: Pointer to boolean for acceptance of cargo
2543 * @param *c_produces: Pointer to boolean for production of cargo
2544 * @return: \c *c_accepts is set when industry accepts the cargo type,
2545 * \c *c_produces is set when the industry produces the cargo type
2547 static void CanCargoServiceIndustry(CargoID cargo, Industry *ind, bool *c_accepts, bool *c_produces)
2549 if (cargo == CT_INVALID) return;
2551 /* Check for acceptance of cargo */
2552 for (byte j = 0; j < lengthof(ind->accepts_cargo); j++) {
2553 if (cargo == ind->accepts_cargo[j] && !IndustryTemporarilyRefusesCargo(ind, cargo)) {
2554 *c_accepts = true;
2555 break;
2559 /* Check for produced cargo */
2560 for (byte j = 0; j < lengthof(ind->produced_cargo); j++) {
2561 if (cargo == ind->produced_cargo[j]) {
2562 *c_produces = true;
2563 break;
2569 * Compute who can service the industry.
2571 * Here, 'can service' means that they have trains and stations close enough
2572 * to the industry with the right cargo type and the right orders (ie has the
2573 * technical means).
2575 * @param ind: Industry being investigated.
2577 * @return: 0 if nobody can service the industry, 2 if the local company can
2578 * service the industry, and 1 otherwise (only competitors can service the
2579 * industry)
2581 static int WhoCanServiceIndustry(Industry *ind)
2583 if (ind->stations_near.size() == 0) return 0; // No stations found at all => nobody services
2585 int result = 0;
2586 for (const Vehicle *v : Vehicle::Iterate()) {
2587 /* Is it worthwhile to try this vehicle? */
2588 if (v->owner != _local_company && result != 0) continue;
2590 /* Check whether it accepts the right kind of cargo */
2591 bool c_accepts = false;
2592 bool c_produces = false;
2593 if (v->type == VEH_TRAIN && v->IsFrontEngine()) {
2594 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
2595 CanCargoServiceIndustry(u->cargo_type, ind, &c_accepts, &c_produces);
2597 } else if (v->type == VEH_ROAD || v->type == VEH_SHIP || v->type == VEH_AIRCRAFT) {
2598 CanCargoServiceIndustry(v->cargo_type, ind, &c_accepts, &c_produces);
2599 } else {
2600 continue;
2602 if (!c_accepts && !c_produces) continue; // Wrong cargo
2604 /* Check orders of the vehicle.
2605 * We cannot check the first of shared orders only, since the first vehicle in such a chain
2606 * may have a different cargo type.
2608 for (const Order *o : v->Orders()) {
2609 if (o->IsType(OT_GOTO_STATION) && !(o->GetUnloadType() & OUFB_TRANSFER)) {
2610 /* Vehicle visits a station to load or unload */
2611 Station *st = Station::Get(o->GetDestination());
2612 assert(st != nullptr);
2614 /* Same cargo produced by industry is dropped here => not serviced by vehicle v */
2615 if ((o->GetUnloadType() & OUFB_UNLOAD) && !c_accepts) break;
2617 if (ind->stations_near.find(st) != ind->stations_near.end()) {
2618 if (v->owner == _local_company) return 2; // Company services industry
2619 result = 1; // Competitor services industry
2624 return result;
2628 * Report news that industry production has changed significantly
2630 * @param ind: Industry with changed production
2631 * @param type: Cargo type that has changed
2632 * @param percent: Percentage of change (>0 means increase, <0 means decrease)
2634 static void ReportNewsProductionChangeIndustry(Industry *ind, CargoID type, int percent)
2636 NewsType nt;
2638 switch (WhoCanServiceIndustry(ind)) {
2639 case 0: nt = NT_INDUSTRY_NOBODY; break;
2640 case 1: nt = NT_INDUSTRY_OTHER; break;
2641 case 2: nt = NT_INDUSTRY_COMPANY; break;
2642 default: NOT_REACHED();
2644 SetDParam(2, abs(percent));
2645 SetDParam(0, CargoSpec::Get(type)->name);
2646 SetDParam(1, ind->index);
2647 AddIndustryNewsItem(
2648 percent >= 0 ? STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_SMOOTH : STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_SMOOTH,
2650 ind->index
2654 static const uint PERCENT_TRANSPORTED_60 = 153;
2655 static const uint PERCENT_TRANSPORTED_80 = 204;
2658 * Change industry production or do closure
2659 * @param i Industry for which changes are performed
2660 * @param monthly true if it's the monthly call, false if it's the random call
2662 static void ChangeIndustryProduction(Industry *i, bool monthly)
2664 StringID str = STR_NULL;
2665 bool closeit = false;
2666 const IndustrySpec *indspec = GetIndustrySpec(i->type);
2667 bool standard = false;
2668 bool suppress_message = false;
2669 bool recalculate_multipliers = false; ///< reinitialize production_rate to match prod_level
2670 /* use original economy for industries using production related callbacks */
2671 bool original_economy = indspec->UsesOriginalEconomy();
2672 byte div = 0;
2673 byte mul = 0;
2674 int8 increment = 0;
2676 bool callback_enabled = HasBit(indspec->callback_mask, monthly ? CBM_IND_MONTHLYPROD_CHANGE : CBM_IND_PRODUCTION_CHANGE);
2677 if (callback_enabled) {
2678 uint16 res = GetIndustryCallback(monthly ? CBID_INDUSTRY_MONTHLYPROD_CHANGE : CBID_INDUSTRY_PRODUCTION_CHANGE, 0, Random(), i, i->type, i->location.tile);
2679 if (res != CALLBACK_FAILED) { // failed callback means "do nothing"
2680 suppress_message = HasBit(res, 7);
2681 /* Get the custom message if any */
2682 if (HasBit(res, 8)) str = MapGRFStringID(indspec->grf_prop.grffile->grfid, GB(GetRegister(0x100), 0, 16));
2683 res = GB(res, 0, 4);
2684 switch (res) {
2685 default: NOT_REACHED();
2686 case 0x0: break; // Do nothing, but show the custom message if any
2687 case 0x1: div = 1; break; // Halve industry production. If production reaches the quarter of the default, the industry is closed instead.
2688 case 0x2: mul = 1; break; // Double industry production if it hasn't reached eight times of the original yet.
2689 case 0x3: closeit = true; break; // The industry announces imminent closure, and is physically removed from the map next month.
2690 case 0x4: standard = true; break; // Do the standard random production change as if this industry was a primary one.
2691 case 0x5: case 0x6: case 0x7: // Divide production by 4, 8, 16
2692 case 0x8: div = res - 0x3; break; // Divide production by 32
2693 case 0x9: case 0xA: case 0xB: // Multiply production by 4, 8, 16
2694 case 0xC: mul = res - 0x7; break; // Multiply production by 32
2695 case 0xD: // decrement production
2696 case 0xE: // increment production
2697 increment = res == 0x0D ? -1 : 1;
2698 break;
2699 case 0xF: // Set production to third byte of register 0x100
2700 i->prod_level = Clamp(GB(GetRegister(0x100), 16, 8), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
2701 recalculate_multipliers = true;
2702 break;
2705 } else {
2706 if (monthly == original_economy) return;
2707 if (!original_economy && _settings_game.economy.type == ET_FROZEN) return;
2708 if (indspec->life_type == INDUSTRYLIFE_BLACK_HOLE) return;
2711 if (standard || (!callback_enabled && (indspec->life_type & (INDUSTRYLIFE_ORGANIC | INDUSTRYLIFE_EXTRACTIVE)) != 0)) {
2712 /* decrease or increase */
2713 bool only_decrease = (indspec->behaviour & INDUSTRYBEH_DONT_INCR_PROD) && _settings_game.game_creation.landscape == LT_TEMPERATE;
2715 if (original_economy) {
2716 if (only_decrease || Chance16(1, 3)) {
2717 /* If more than 60% transported, 66% chance of increase, else 33% chance of increase */
2718 if (!only_decrease && (i->last_month_pct_transported[0] > PERCENT_TRANSPORTED_60) != Chance16(1, 3)) {
2719 mul = 1; // Increase production
2720 } else {
2721 div = 1; // Decrease production
2724 } else if (_settings_game.economy.type == ET_SMOOTH) {
2725 closeit = !(i->ctlflags & (INDCTL_NO_CLOSURE | INDCTL_NO_PRODUCTION_DECREASE));
2726 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
2727 if (i->produced_cargo[j] == CT_INVALID) continue;
2728 uint32 r = Random();
2729 int old_prod, new_prod, percent;
2730 /* If over 60% is transported, mult is 1, else mult is -1. */
2731 int mult = (i->last_month_pct_transported[j] > PERCENT_TRANSPORTED_60) ? 1 : -1;
2733 new_prod = old_prod = i->production_rate[j];
2735 /* For industries with only_decrease flags (temperate terrain Oil Wells),
2736 * the multiplier will always be -1 so they will only decrease. */
2737 if (only_decrease) {
2738 mult = -1;
2739 /* For normal industries, if over 60% is transported, 33% chance for decrease.
2740 * Bonus for very high station ratings (over 80%): 16% chance for decrease. */
2741 } else if (Chance16I(1, ((i->last_month_pct_transported[j] > PERCENT_TRANSPORTED_80) ? 6 : 3), r)) {
2742 mult *= -1;
2745 /* 4.5% chance for 3-23% (or 1 unit for very low productions) production change,
2746 * determined by mult value. If mult = 1 prod. increases, else (-1) it decreases. */
2747 if (Chance16I(1, 22, r >> 16)) {
2748 new_prod += mult * (std::max(((RandomRange(50) + 10) * old_prod) >> 8, 1U));
2751 /* Prevent production to overflow or Oil Rig passengers to be over-"produced" */
2752 new_prod = Clamp(new_prod, 1, 255);
2753 if (i->produced_cargo[j] == CT_PASSENGERS && !(indspec->behaviour & INDUSTRYBEH_NO_PAX_PROD_CLAMP)) {
2754 new_prod = Clamp(new_prod, 0, 16);
2757 /* If override flags are set, prevent actually changing production if any was decided on */
2758 if ((i->ctlflags & INDCTL_NO_PRODUCTION_DECREASE) && new_prod < old_prod) continue;
2759 if ((i->ctlflags & INDCTL_NO_PRODUCTION_INCREASE) && new_prod > old_prod) continue;
2761 /* Do not stop closing the industry when it has the lowest possible production rate */
2762 if (new_prod == old_prod && old_prod > 1) {
2763 closeit = false;
2764 continue;
2767 percent = (old_prod == 0) ? 100 : (new_prod * 100 / old_prod - 100);
2768 i->production_rate[j] = new_prod;
2770 /* Close the industry when it has the lowest possible production rate */
2771 if (new_prod > 1) closeit = false;
2773 if (abs(percent) >= 10) {
2774 ReportNewsProductionChangeIndustry(i, i->produced_cargo[j], percent);
2780 /* If override flags are set, prevent actually changing production if any was decided on */
2781 if ((i->ctlflags & INDCTL_NO_PRODUCTION_DECREASE) && (div > 0 || increment < 0)) return;
2782 if ((i->ctlflags & INDCTL_NO_PRODUCTION_INCREASE) && (mul > 0 || increment > 0)) return;
2784 if (!callback_enabled && (indspec->life_type & INDUSTRYLIFE_PROCESSING)) {
2785 if ( (byte)(_cur_year - i->last_prod_year) >= 5 && Chance16(1, original_economy ? 2 : 180)) {
2786 closeit = true;
2790 /* Increase if needed */
2791 while (mul-- != 0 && i->prod_level < PRODLEVEL_MAXIMUM) {
2792 i->prod_level = std::min<int>(i->prod_level * 2, PRODLEVEL_MAXIMUM);
2793 recalculate_multipliers = true;
2794 if (str == STR_NULL) str = indspec->production_up_text;
2797 /* Decrease if needed */
2798 while (div-- != 0 && !closeit) {
2799 if (i->prod_level == PRODLEVEL_MINIMUM) {
2800 closeit = true;
2801 break;
2802 } else {
2803 i->prod_level = std::max<int>(i->prod_level / 2, PRODLEVEL_MINIMUM);
2804 recalculate_multipliers = true;
2805 if (str == STR_NULL) str = indspec->production_down_text;
2809 /* Increase or Decreasing the production level if needed */
2810 if (increment != 0) {
2811 if (increment < 0 && i->prod_level == PRODLEVEL_MINIMUM) {
2812 closeit = true;
2813 } else {
2814 i->prod_level = ClampU(i->prod_level + increment, PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
2815 recalculate_multipliers = true;
2819 /* Recalculate production_rate
2820 * For non-smooth economy these should always be synchronized with prod_level */
2821 if (recalculate_multipliers) i->RecomputeProductionMultipliers();
2823 /* Close if needed and allowed */
2824 if (closeit && !CheckIndustryCloseDownProtection(i->type) && !(i->ctlflags & INDCTL_NO_CLOSURE)) {
2825 i->prod_level = PRODLEVEL_CLOSURE;
2826 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
2827 str = indspec->closure_text;
2830 if (!suppress_message && str != STR_NULL) {
2831 NewsType nt;
2832 /* Compute news category */
2833 if (closeit) {
2834 nt = NT_INDUSTRY_CLOSE;
2835 AI::BroadcastNewEvent(new ScriptEventIndustryClose(i->index));
2836 Game::NewEvent(new ScriptEventIndustryClose(i->index));
2837 } else {
2838 switch (WhoCanServiceIndustry(i)) {
2839 case 0: nt = NT_INDUSTRY_NOBODY; break;
2840 case 1: nt = NT_INDUSTRY_OTHER; break;
2841 case 2: nt = NT_INDUSTRY_COMPANY; break;
2842 default: NOT_REACHED();
2845 /* Set parameters of news string */
2846 if (str > STR_LAST_STRINGID) {
2847 SetDParam(0, STR_TOWN_NAME);
2848 SetDParam(1, i->town->index);
2849 SetDParam(2, indspec->name);
2850 } else if (closeit) {
2851 SetDParam(0, STR_FORMAT_INDUSTRY_NAME);
2852 SetDParam(1, i->town->index);
2853 SetDParam(2, indspec->name);
2854 } else {
2855 SetDParam(0, i->index);
2857 /* and report the news to the user */
2858 if (closeit) {
2859 AddTileNewsItem(str, nt, i->location.tile + TileDiffXY(1, 1));
2860 } else {
2861 AddIndustryNewsItem(str, nt, i->index);
2867 * Daily handler for the industry changes
2868 * Taking the original map size of 256*256, the number of random changes was always of just one unit.
2869 * But it cannot be the same on smaller or bigger maps. That number has to be scaled up or down.
2870 * For small maps, it implies that less than one change per month is required, while on bigger maps,
2871 * it would be way more. The daily loop handles those changes.
2873 void IndustryDailyLoop()
2875 _economy.industry_daily_change_counter += _economy.industry_daily_increment;
2877 /* Bits 16-31 of industry_construction_counter contain the number of industries to change/create today,
2878 * the lower 16 bit are a fractional part that might accumulate over several days until it
2879 * is sufficient for an industry. */
2880 uint16 change_loop = _economy.industry_daily_change_counter >> 16;
2882 /* Reset the active part of the counter, just keeping the "fractional part" */
2883 _economy.industry_daily_change_counter &= 0xFFFF;
2885 if (change_loop == 0) {
2886 return; // Nothing to do? get out
2889 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2891 /* perform the required industry changes for the day */
2893 uint perc = 3; // Between 3% and 9% chance of creating a new industry.
2894 if ((_industry_builder.wanted_inds >> 16) > GetCurrentTotalNumberOfIndustries()) {
2895 perc = std::min(9u, perc + (_industry_builder.wanted_inds >> 16) - GetCurrentTotalNumberOfIndustries());
2897 for (uint16 j = 0; j < change_loop; j++) {
2898 if (Chance16(perc, 100)) {
2899 _industry_builder.TryBuildNewIndustry();
2900 } else {
2901 Industry *i = Industry::GetRandom();
2902 if (i != nullptr) {
2903 ChangeIndustryProduction(i, false);
2904 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
2909 cur_company.Restore();
2911 /* production-change */
2912 InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, IDIWD_PRODUCTION_CHANGE);
2915 void IndustryMonthlyLoop()
2917 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2919 _industry_builder.MonthlyLoop();
2921 for (Industry *i : Industry::Iterate()) {
2922 UpdateIndustryStatistics(i);
2923 if (i->prod_level == PRODLEVEL_CLOSURE) {
2924 delete i;
2925 } else {
2926 ChangeIndustryProduction(i, true);
2927 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
2931 cur_company.Restore();
2933 /* production-change */
2934 InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, IDIWD_PRODUCTION_CHANGE);
2938 void InitializeIndustries()
2940 Industry::ResetIndustryCounts();
2941 _industry_sound_tile = 0;
2943 _industry_builder.Reset();
2946 /** Verify whether the generated industries are complete, and warn the user if not. */
2947 void CheckIndustries()
2949 int count = 0;
2950 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2951 if (Industry::GetIndustryTypeCount(it) > 0) continue; // Types of existing industries can be skipped.
2953 bool force_at_least_one;
2954 uint32 chance = GetScaledIndustryGenerationProbability(it, &force_at_least_one);
2955 if (chance == 0 || !force_at_least_one) continue; // Types that are not available can be skipped.
2957 const IndustrySpec *is = GetIndustrySpec(it);
2958 SetDParam(0, is->name);
2959 ShowErrorMessage(STR_ERROR_NO_SUITABLE_PLACES_FOR_INDUSTRIES, STR_ERROR_NO_SUITABLE_PLACES_FOR_INDUSTRIES_EXPLANATION, WL_WARNING);
2961 count++;
2962 if (count >= 3) break; // Don't swamp the user with errors.
2967 * Is an industry with the spec a raw industry?
2968 * @return true if it should be handled as a raw industry
2970 bool IndustrySpec::IsRawIndustry() const
2972 return (this->life_type & (INDUSTRYLIFE_EXTRACTIVE | INDUSTRYLIFE_ORGANIC)) != 0;
2976 * Is an industry with the spec a processing industry?
2977 * @return true if it should be handled as a processing industry
2979 bool IndustrySpec::IsProcessingIndustry() const
2981 /* Lumber mills are neither raw nor processing */
2982 return (this->life_type & INDUSTRYLIFE_PROCESSING) != 0 &&
2983 (this->behaviour & INDUSTRYBEH_CUT_TREES) == 0;
2987 * Get the cost for constructing this industry
2988 * @return the cost (inflation corrected etc)
2990 Money IndustrySpec::GetConstructionCost() const
2992 /* Building raw industries like secondary uses different price base */
2993 return (_price[(_settings_game.construction.raw_industry_construction == 1 && this->IsRawIndustry()) ?
2994 PR_BUILD_INDUSTRY_RAW : PR_BUILD_INDUSTRY] * this->cost_multiplier) >> 8;
2998 * Get the cost for removing this industry
2999 * Take note that the cost will always be zero for non-grf industries.
3000 * Only if the grf author did specified a cost will it be applicable.
3001 * @return the cost (inflation corrected etc)
3003 Money IndustrySpec::GetRemovalCost() const
3005 return (_price[PR_CLEAR_INDUSTRY] * this->removal_cost_multiplier) >> 8;
3009 * Determines whether this industrytype uses standard/newgrf production changes.
3010 * @return true if original economy is used.
3012 bool IndustrySpec::UsesOriginalEconomy() const
3014 return _settings_game.economy.type == ET_ORIGINAL ||
3015 HasBit(this->callback_mask, CBM_IND_PRODUCTION_256_TICKS) || HasBit(this->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || // production callbacks
3016 HasBit(this->callback_mask, CBM_IND_MONTHLYPROD_CHANGE) || HasBit(this->callback_mask, CBM_IND_PRODUCTION_CHANGE) || HasBit(this->callback_mask, CBM_IND_PROD_CHANGE_BUILD); // production change callbacks
3019 IndustrySpec::~IndustrySpec()
3021 if (HasBit(this->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3022 free(this->random_sounds);
3026 static CommandCost TerraformTile_Industry(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3028 if (AutoslopeEnabled()) {
3029 /* We imitate here TTDP's behaviour:
3030 * - Both new and old slope must not be steep.
3031 * - TileMaxZ must not be changed.
3032 * - Allow autoslope by default.
3033 * - Disallow autoslope if callback succeeds and returns non-zero.
3035 Slope tileh_old = GetTileSlope(tile);
3036 /* TileMaxZ must not be changed. Slopes must not be steep. */
3037 if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3038 const IndustryGfx gfx = GetIndustryGfx(tile);
3039 const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
3041 /* Call callback 3C 'disable autosloping for industry tiles'. */
3042 if (HasBit(itspec->callback_mask, CBM_INDT_AUTOSLOPE)) {
3043 /* If the callback fails, allow autoslope. */
3044 uint16 res = GetIndustryTileCallback(CBID_INDTILE_AUTOSLOPE, 0, 0, gfx, Industry::GetByTile(tile), tile);
3045 if (res == CALLBACK_FAILED || !ConvertBooleanCallback(itspec->grf_prop.grffile, CBID_INDTILE_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3046 } else {
3047 /* allow autoslope */
3048 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3052 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
3055 extern const TileTypeProcs _tile_type_industry_procs = {
3056 DrawTile_Industry, // draw_tile_proc
3057 GetSlopePixelZ_Industry, // get_slope_z_proc
3058 ClearTile_Industry, // clear_tile_proc
3059 AddAcceptedCargo_Industry, // add_accepted_cargo_proc
3060 GetTileDesc_Industry, // get_tile_desc_proc
3061 GetTileTrackStatus_Industry, // get_tile_track_status_proc
3062 ClickTile_Industry, // click_tile_proc
3063 AnimateTile_Industry, // animate_tile_proc
3064 TileLoop_Industry, // tile_loop_proc
3065 ChangeTileOwner_Industry, // change_tile_owner_proc
3066 nullptr, // add_produced_cargo_proc
3067 nullptr, // vehicle_enter_tile_proc
3068 GetFoundation_Industry, // get_foundation_proc
3069 TerraformTile_Industry, // terraform_tile_proc
3072 bool IndustryCompare::operator() (const IndustryListEntry &lhs, const IndustryListEntry &rhs) const
3074 /* Compare by distance first and use index as a tiebreaker. */
3075 return std::tie(lhs.distance, lhs.industry->index) < std::tie(rhs.distance, rhs.industry->index);