OpenTTD Source  13.2.1
industry_cmd.cpp
Go to the documentation of this file.
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  */
7 
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"
47 
48 #include "table/strings.h"
49 #include "table/industry_land.h"
50 #include "table/build_industry.h"
51 
52 #include "safeguards.h"
53 
54 IndustryPool _industry_pool("Industry");
56 
57 void ShowIndustryViewWindow(int industry);
58 void BuildOilRig(TileIndex tile);
59 
60 static byte _industry_sound_ctr;
61 static TileIndex _industry_sound_tile;
62 
64 
65 IndustrySpec _industry_specs[NUM_INDUSTRYTYPES];
66 IndustryTileSpec _industry_tile_specs[NUM_INDUSTRYTILES];
68 
76 {
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{};
83  }
84 
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);
88  }
89 
90  memset(&_industry_tile_specs, 0, sizeof(_industry_tile_specs));
91  memcpy(&_industry_tile_specs, &_origin_industry_tile_specs, sizeof(_origin_industry_tile_specs));
92 
93  /* Reset any overrides that have been set. */
94  _industile_mngr.ResetOverride();
95  _industry_mngr.ResetOverride();
96 }
97 
106 IndustryType GetIndustryType(TileIndex tile)
107 {
108  assert(IsTileType(tile, MP_INDUSTRY));
109 
110  const Industry *ind = Industry::GetByTile(tile);
111  assert(ind != nullptr);
112  return ind->type;
113 }
114 
123 const IndustrySpec *GetIndustrySpec(IndustryType thistype)
124 {
125  assert(thistype < NUM_INDUSTRYTYPES);
126  return &_industry_specs[thistype];
127 }
128 
137 const IndustryTileSpec *GetIndustryTileSpec(IndustryGfx gfx)
138 {
139  assert(gfx < INVALID_INDUSTRYTILE);
140  return &_industry_tile_specs[gfx];
141 }
142 
143 Industry::~Industry()
144 {
145  if (CleaningPool()) return;
146 
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;
151 
152  const bool has_neutral_station = this->neutral_station != nullptr;
153 
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);
158 
159  /* MakeWaterKeepingClass() can also handle 'land' */
160  MakeWaterKeepingClass(tile_cur, OWNER_NONE);
161  }
162  } else if (IsTileType(tile_cur, MP_STATION) && IsOilRig(tile_cur)) {
163  DeleteOilRig(tile_cur);
164  }
165  }
166 
167  if (has_neutral_station) {
168  /* Remove possible docking tiles */
169  for (TileIndex tile_cur : this->location) {
171  }
172  }
173 
174  if (GetIndustrySpec(this->type)->behaviour & INDUSTRYBEH_PLANT_FIELDS) {
175  TileArea ta = TileArea(this->location.tile, 0, 0).Expand(21);
176 
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);
182  }
183  }
184  }
185 
186  /* don't let any disaster vehicle target invalid industry */
188 
189  /* Clear the persistent storage. */
190  delete this->psa;
191 
192  DecIndustryTypeCount(this->type);
193 
194  DeleteIndustryNews(this->index);
196  DeleteNewGRFInspectWindow(GSF_INDUSTRIES, this->index);
197 
200 
201  for (Station *st : this->stations_near) {
202  st->RemoveIndustryToDeliver(this);
203  }
204 }
205 
210 void Industry::PostDestructor(size_t index)
211 {
212  InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, IDIWD_FORCE_REBUILD);
213 }
214 
215 
221 {
222  if (Industry::GetNumItems() == 0) return nullptr;
223  int num = RandomRange((uint16)Industry::GetNumItems());
224  size_t index = MAX_UVALUE(size_t);
225 
226  while (num >= 0) {
227  num--;
228  index++;
229 
230  /* Make sure we have a valid industry */
231  while (!Industry::IsValidID(index)) {
232  index++;
233  assert(index < Industry::GetPoolSize());
234  }
235  }
236 
237  return Industry::Get(index);
238 }
239 
240 
241 static void IndustryDrawSugarMine(const TileInfo *ti)
242 {
243  if (!IsIndustryCompleted(ti->tile)) return;
244 
245  const DrawIndustryAnimationStruct *d = &_draw_industry_spec1[GetAnimationFrame(ti->tile)];
246 
247  AddChildSpriteScreen(SPR_IT_SUGAR_MINE_SIEVE + d->image_1, PAL_NONE, d->x, 0);
248 
249  if (d->image_2 != 0) {
250  AddChildSpriteScreen(SPR_IT_SUGAR_MINE_CLOUDS + d->image_2 - 1, PAL_NONE, 8, 41);
251  }
252 
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);
256  }
257 }
258 
259 static void IndustryDrawToffeeQuarry(const TileInfo *ti)
260 {
261  uint8 x = 0;
262 
263  if (IsIndustryCompleted(ti->tile)) {
264  x = _industry_anim_offs_toffee[GetAnimationFrame(ti->tile)];
265  if (x == 0xFF) {
266  x = 0;
267  }
268  }
269 
270  AddChildSpriteScreen(SPR_IT_TOFFEE_QUARRY_SHOVEL, PAL_NONE, 22 - x, 24 + x);
271  AddChildSpriteScreen(SPR_IT_TOFFEE_QUARRY_TOFFEE, PAL_NONE, 6, 14);
272 }
273 
274 static void IndustryDrawBubbleGenerator( const TileInfo *ti)
275 {
276  if (IsIndustryCompleted(ti->tile)) {
277  AddChildSpriteScreen(SPR_IT_BUBBLE_GENERATOR_BUBBLE, PAL_NONE, 5, _industry_anim_offs_bubbles[GetAnimationFrame(ti->tile)]);
278  }
279  AddChildSpriteScreen(SPR_IT_BUBBLE_GENERATOR_SPRING, PAL_NONE, 3, 67);
280 }
281 
282 static void IndustryDrawToyFactory(const TileInfo *ti)
283 {
284  const DrawIndustryAnimationStruct *d = &_industry_anim_offs_toys[GetAnimationFrame(ti->tile)];
285 
286  if (d->image_1 != 0xFF) {
287  AddChildSpriteScreen(SPR_IT_TOY_FACTORY_CLAY, PAL_NONE, d->x, 96 + d->image_1);
288  }
289 
290  if (d->image_2 != 0xFF) {
291  AddChildSpriteScreen(SPR_IT_TOY_FACTORY_ROBOT, PAL_NONE, 16 - d->image_2 * 2, 100 + d->image_2);
292  }
293 
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);
296 }
297 
298 static void IndustryDrawCoalPlantSparks(const TileInfo *ti)
299 {
300  if (IsIndustryCompleted(ti->tile)) {
301  uint8 image = GetAnimationFrame(ti->tile);
302 
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
308  );
309  }
310  }
311 }
312 
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,
320 };
321 
322 static void DrawTile_Industry(TileInfo *ti)
323 {
324  IndustryGfx gfx = GetIndustryGfx(ti->tile);
325  Industry *ind = Industry::GetByTile(ti->tile);
326  const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
327 
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);
343  }
344  }
345  }
346 
347  const DrawBuildingsTileStruct *dits = &_industry_draw_tile_data[gfx << 2 | (indts->anim_state ?
350 
351  SpriteID image = dits->ground.sprite;
352 
353  /* DrawFoundation() modifies ti->z and ti->tileh */
355 
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)));
362  }
363 
364  /* If industries are transparent and invisible, do not draw the upper part */
365  if (IsInvisibilitySet(TO_INDUSTRIES)) return;
366 
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,
378 
379  if (IsTransparencySet(TO_INDUSTRIES)) return;
380  }
381 
382  {
383  int proc = dits->draw_proc - 1;
384  if (proc >= 0) _industry_draw_tile_procs[proc](ti);
385  }
386 }
387 
388 static int GetSlopePixelZ_Industry(TileIndex tile, uint x, uint y)
389 {
390  return GetTileMaxPixelZ(tile);
391 }
392 
393 static Foundation GetFoundation_Industry(TileIndex tile, Slope tileh)
394 {
395  IndustryGfx gfx = GetIndustryGfx(tile);
396 
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.
400  */
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;
406  }
407  }
408  return FlatteningFoundation(tileh);
409 }
410 
411 static void AddAcceptedCargo_Industry(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
412 {
413  IndustryGfx gfx = GetIndustryGfx(tile);
414  const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
415  const Industry *ind = Industry::GetByTile(tile);
416 
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));
422 
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];
432  }
433  cargo_acceptance[pos - accepts_cargo] += 8;
434  }
435  }
436 
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);
443  }
444  }
445 
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);
452  }
453  }
454 
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
458 
459  /* Add accepted cargo */
460  acceptance[a] += cargo_acceptance[i];
461 
462  /* Maybe set 'always accepted' bit (if it's not set already) */
463  if (HasBit(*always_accepted, a)) continue;
464 
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;
471  }
472  }
473 
474  if (accepts) continue;
475 
476  /* If the industry itself doesn't accept this cargo, set 'always accepted' bit */
477  SetBit(*always_accepted, a);
478  }
479 }
480 
481 static void GetTileDesc_Industry(TileIndex tile, TileDesc *td)
482 {
483  const Industry *i = Industry::GetByTile(tile);
484  const IndustrySpec *is = GetIndustrySpec(i->type);
485 
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;
491  }
492 
493  if (is->grf_prop.grffile != nullptr) {
494  td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
495  }
496 }
497 
498 static CommandCost ClearTile_Industry(TileIndex tile, DoCommandFlag flags)
499 {
500  Industry *i = Industry::GetByTile(tile);
501  const IndustrySpec *indspec = GetIndustrySpec(i->type);
502 
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
507  */
508  if ((_current_company != OWNER_WATER && _game_mode != GM_EDITOR &&
510  ((flags & DC_AUTO) != 0) ||
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);
516  }
517 
518  if (flags & DC_EXEC) {
519  AI::BroadcastNewEvent(new ScriptEventIndustryClose(i->index));
520  Game::NewEvent(new ScriptEventIndustryClose(i->index));
521  delete i;
522  }
524 }
525 
532 {
533  Industry *i = Industry::GetByTile(tile);
534  const IndustrySpec *indspec = GetIndustrySpec(i->type);
535  bool moved_cargo = false;
536 
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;
541 
542  /* fluctuating economy? */
543  if (EconomyIsInRecession()) cw = (cw + 1) / 2;
544 
545  i->this_month_production[j] += cw;
546 
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;
549 
550  moved_cargo |= (am != 0);
551  }
552  }
553 
554  return moved_cargo;
555 }
556 
557 
558 static void AnimateTile_Industry(TileIndex tile)
559 {
560  IndustryGfx gfx = GetIndustryGfx(tile);
561 
562  if (GetIndustryTileSpec(gfx)->animation.status != ANIM_STATUS_NO_ANIMATION) {
563  AnimateNewIndustryTile(tile);
564  return;
565  }
566 
567  switch (gfx) {
568  case GFX_SUGAR_MINE_SIEVE:
569  if ((_tick_counter & 1) == 0) {
570  byte m = GetAnimationFrame(tile) + 1;
571 
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;
576  }
577  }
578 
579  if (m >= 96) {
580  m = 0;
581  DeleteAnimatedTile(tile);
582  }
583  SetAnimationFrame(tile, m);
584 
585  MarkTileDirtyByTile(tile);
586  }
587  break;
588 
589  case GFX_TOFFEE_QUARY:
590  if ((_tick_counter & 3) == 0) {
591  byte m = GetAnimationFrame(tile);
592 
593  if (_industry_anim_offs_toffee[m] == 0xFF && _settings_client.sound.ambient) {
594  SndPlayTileFx(SND_30_TOFFEE_QUARRY, tile);
595  }
596 
597  if (++m >= 70) {
598  m = 0;
599  DeleteAnimatedTile(tile);
600  }
601  SetAnimationFrame(tile, m);
602 
603  MarkTileDirtyByTile(tile);
604  }
605  break;
606 
607  case GFX_BUBBLE_CATCHER:
608  if ((_tick_counter & 1) == 0) {
609  byte m = GetAnimationFrame(tile);
610 
611  if (++m >= 40) {
612  m = 0;
613  DeleteAnimatedTile(tile);
614  }
615  SetAnimationFrame(tile, m);
616 
617  MarkTileDirtyByTile(tile);
618  }
619  break;
620 
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);
631  }
632  }
633  break;
634 
635  case GFX_TOY_FACTORY:
636  if ((_tick_counter & 1) == 0) {
637  byte m = GetAnimationFrame(tile) + 1;
638 
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);
650  }
651  SetIndustryAnimationLoop(tile, n);
652  }
653  }
654 
655  SetAnimationFrame(tile, m);
656  MarkTileDirtyByTile(tile);
657  }
658  break;
659 
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);
666 
667  gfx = (gfx < 155) ? gfx + 1 : 148;
668  SetIndustryGfx(tile, gfx);
669  MarkTileDirtyByTile(tile);
670  }
671  break;
672 
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);
679 
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);
684  DeleteAnimatedTile(tile);
685  } else {
686  SetAnimationFrame(tile, m);
687  SetIndustryGfx(tile, gfx);
688  MarkTileDirtyByTile(tile);
689  }
690  }
691  break;
692 
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;
697 
698  if ((state -= 0x400) < 0) return;
699 
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);
706  }
707  if (state & 7) return;
708  } else {
709  if (state & 3) return;
710  }
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;
718 
719  byte m = (GetAnimationFrame(tile) & 0xBF) - 1;
720  if (m < 0x80) m = 0x82;
721  SetAnimationFrame(tile, m);
722  MarkTileDirtyByTile(tile);
723  }
724  break;
725  }
726  }
727 }
728 
729 static void CreateChimneySmoke(TileIndex tile)
730 {
731  uint x = TileX(tile) * TILE_SIZE;
732  uint y = TileY(tile) * TILE_SIZE;
733  int z = GetTileMaxPixelZ(tile);
734 
735  CreateEffectVehicle(x + 15, y + 14, z + 59, EV_CHIMNEY_SMOKE);
736 }
737 
738 static void MakeIndustryTileBigger(TileIndex tile)
739 {
740  byte cnt = GetIndustryConstructionCounter(tile) + 1;
741  if (cnt != 4) {
743  return;
744  }
745 
746  byte stage = GetIndustryConstructionStage(tile) + 1;
748  SetIndustryConstructionStage(tile, stage);
749  StartStopIndustryTileAnimation(tile, IAT_CONSTRUCTION_STATE_CHANGE);
750  if (stage == INDUSTRY_COMPLETED) SetIndustryCompleted(tile);
751 
752  MarkTileDirtyByTile(tile);
753 
754  if (!IsIndustryCompleted(tile)) return;
755 
756  IndustryGfx gfx = GetIndustryGfx(tile);
757  if (gfx >= NEW_INDUSTRYTILEOFFSET) {
758  /* New industries are already animated on construction. */
759  return;
760  }
761 
762  switch (gfx) {
763  case GFX_POWERPLANT_CHIMNEY:
764  CreateChimneySmoke(tile);
765  break;
766 
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);
773 
774  if (IsTileType(other, MP_INDUSTRY) &&
775  GetIndustryGfx(other) == GFX_OILRIG_1 &&
776  GetIndustryIndex(tile) == GetIndustryIndex(other)) {
777  BuildOilRig(tile);
778  }
779  break;
780  }
781 
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;
788 
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;
795  }
796 }
797 
798 static void TileLoopIndustry_BubbleGenerator(TileIndex tile)
799 {
800  static const int8 _bubble_spawn_location[3][4] = {
801  { 11, 0, -4, -14 },
802  { -4, -10, -4, 1 },
803  { 49, 59, 60, 65 },
804  };
805 
806  if (_settings_client.sound.ambient) SndPlayTileFx(SND_2E_BUBBLE_GENERATOR, tile);
807 
808  int dir = Random() & 3;
809 
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
815  );
816 
817  if (v != nullptr) v->animation_substate = dir;
818 }
819 
820 static void TileLoop_Industry(TileIndex tile)
821 {
822  if (IsTileOnWater(tile)) TileLoop_Water(tile);
823 
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;
829 
831 
832  if (!IsIndustryCompleted(tile)) {
833  MakeIndustryTileBigger(tile);
834  return;
835  }
836 
837  if (_game_mode == GM_EDITOR) return;
838 
839  if (TransportIndustryGoods(tile) && !StartStopIndustryTileAnimation(Industry::GetByTile(tile), IAT_INDUSTRY_DISTRIBUTES_CARGO)) {
840  uint newgfx = GetIndustryTileSpec(GetIndustryGfx(tile))->anim_production;
841 
842  if (newgfx != INDUSTRYTILE_NOANIM) {
844  SetIndustryCompleted(tile);
845  SetIndustryGfx(tile, newgfx);
846  MarkTileDirtyByTile(tile);
847  return;
848  }
849  }
850 
851  if (StartStopIndustryTileAnimation(tile, IAT_TILELOOP)) return;
852 
853  IndustryGfx newgfx = GetIndustryTileSpec(GetIndustryGfx(tile))->anim_next;
854  if (newgfx != INDUSTRYTILE_NOANIM) {
856  SetIndustryGfx(tile, newgfx);
857  MarkTileDirtyByTile(tile);
858  return;
859  }
860 
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;
871  }
872  SetIndustryGfx(tile, gfx);
873  SetAnimationFrame(tile, 0x80);
874  AddAnimatedTile(tile);
875  }
876  break;
877 
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);
883  }
884  break;
885 
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;
894  }
895  SetIndustryGfx(tile, gfx);
896  SetIndustryCompleted(tile);
898  DeleteAnimatedTile(tile);
899  }
900  break;
901 
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);
906  }
907  break;
908 
909  case GFX_COPPER_MINE_CHIMNEY:
911  break;
912 
913 
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);
920  }
921  }
922  break;
923 
924  case GFX_BUBBLE_GENERATOR:
925  TileLoopIndustry_BubbleGenerator(tile);
926  break;
927 
928  case GFX_TOFFEE_QUARY:
929  AddAnimatedTile(tile);
930  break;
931 
932  case GFX_SUGAR_MINE_SIEVE:
933  if (Chance16(1, 3)) AddAnimatedTile(tile);
934  break;
935  }
936 }
937 
938 static bool ClickTile_Industry(TileIndex tile)
939 {
940  ShowIndustryViewWindow(GetIndustryIndex(tile));
941  return true;
942 }
943 
944 static TrackStatus GetTileTrackStatus_Industry(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
945 {
946  return 0;
947 }
948 
949 static void ChangeTileOwner_Industry(TileIndex tile, Owner old_owner, Owner new_owner)
950 {
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;
954 
955  if (i->exclusive_supplier == old_owner) i->exclusive_supplier = new_owner;
956  if (i->exclusive_consumer == old_owner) i->exclusive_consumer = new_owner;
957 }
958 
965 {
966  /* Check for industry tile */
967  if (!IsTileType(tile, MP_INDUSTRY)) return false;
968 
969  const Industry *ind = Industry::GetByTile(tile);
970 
971  /* Check for organic industry (i.e. not processing or extractive) */
972  if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
973 
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;
978  }
979 
980  return false;
981 }
982 
983 static const byte _plantfarmfield_type[] = {1, 1, 1, 1, 1, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6};
984 
992 static bool IsSuitableForFarmField(TileIndex tile, bool allow_fields)
993 {
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;
998  }
999 }
1000 
1008 static void SetupFarmFieldFence(TileIndex tile, int size, byte type, DiagDirection side)
1009 {
1010  TileIndexDiff diff = (DiagDirToAxis(side) == AXIS_Y ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1011 
1012  do {
1013  tile = TILE_MASK(tile);
1014 
1015  if (IsTileType(tile, MP_CLEAR) && IsClearGround(tile, CLEAR_FIELDS)) {
1016  byte or_ = type;
1017 
1018  if (or_ == 1 && Chance16(1, 7)) or_ = 2;
1019 
1020  SetFence(tile, side, or_);
1021  }
1022 
1023  tile += diff;
1024  } while (--size);
1025 }
1026 
1027 static void PlantFarmField(TileIndex tile, IndustryID industry)
1028 {
1029  if (_settings_game.game_creation.landscape == LT_ARCTIC) {
1030  if (GetTileZ(tile) + 2 >= GetSnowLine()) return;
1031  }
1032 
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);
1038 
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();
1041 
1042  if (ta.w == 0 || ta.h == 0) return;
1043 
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);
1049  }
1050  if (count * 2 < ta.w * ta.h) return;
1051 
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;
1056 
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);
1064  }
1065  }
1066 
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];
1070  }
1071 
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);
1076 }
1077 
1078 void PlantRandomFarmField(const Industry *i)
1079 {
1080  int x = i->location.w / 2 + Random() % 31 - 16;
1081  int y = i->location.h / 2 + Random() % 31 - 16;
1082 
1083  TileIndex tile = TileAddWrap(i->location.tile, x, y);
1084 
1085  if (tile != INVALID_TILE) PlantFarmField(tile, i->index);
1086 }
1087 
1094 static bool SearchLumberMillTrees(TileIndex tile, void *user_data)
1095 {
1096  if (IsTileType(tile, MP_TREES) && GetTreeGrowth(tile) > 2) {
1097  /* found a tree */
1098 
1099  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1100 
1101  _industry_sound_ctr = 1;
1102  _industry_sound_tile = tile;
1103  if (_settings_client.sound.ambient) SndPlayTileFx(SND_38_LUMBER_MILL_1, tile);
1104 
1106 
1107  cur_company.Restore();
1108  return true;
1109  }
1110  return false;
1111 }
1112 
1118 {
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;
1123  }
1124  }
1125 
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.
1129  }
1130 }
1131 
1132 static void ProduceIndustryGoods(Industry *i)
1133 {
1134  const IndustrySpec *indsp = GetIndustrySpec(i->type);
1135 
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;
1147  }
1148  }
1149  }
1150  }
1151 
1152  i->counter--;
1153 
1154  /* produce some cargo */
1155  if ((i->counter % INDUSTRY_PRODUCE_TICKS) == 0) {
1157 
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]);
1161  }
1162 
1163  if ((indbehav & INDUSTRYBEH_PLANT_FIELDS) != 0) {
1164  uint16 cb_res = CALLBACK_FAILED;
1166  cb_res = GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, Random(), 0, i, i->type, i->location.tile);
1167  }
1168 
1169  bool plant;
1170  if (cb_res != CALLBACK_FAILED) {
1172  } else {
1173  plant = Chance16(1, 8);
1174  }
1175 
1176  if (plant) PlantRandomFarmField(i);
1177  }
1178  if ((indbehav & INDUSTRYBEH_CUT_TREES) != 0) {
1179  uint16 cb_res = CALLBACK_FAILED;
1181  cb_res = GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, Random(), 1, i, i->type, i->location.tile);
1182  }
1183 
1184  bool cut;
1185  if (cb_res != CALLBACK_FAILED) {
1187  } else {
1188  cut = ((i->counter % INDUSTRY_CUT_TREE_TICKS) == 0);
1189  }
1190 
1191  if (cut) ChopLumberMillTrees(i);
1192  }
1193 
1195  StartStopIndustryTileAnimation(i, IAT_INDUSTRY_TICK);
1196  }
1197 }
1198 
1199 void OnTick_Industry()
1200 {
1201  if (_industry_sound_ctr != 0) {
1202  _industry_sound_ctr++;
1203 
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);
1209  }
1210  }
1211 
1212  if (_game_mode == GM_EDITOR) return;
1213 
1214  for (Industry *i : Industry::Iterate()) {
1215  ProduceIndustryGoods(i);
1216  }
1217 }
1218 
1225 {
1226  return CommandCost();
1227 }
1228 
1235 {
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);
1239  }
1240  }
1241  return CommandCost();
1242 }
1243 
1251 static bool CheckScaledDistanceFromEdge(TileIndex tile, uint maxdist)
1252 {
1253  uint maxdist_x = maxdist;
1254  uint maxdist_y = maxdist;
1255 
1256  if (MapSizeX() > 256) maxdist_x *= MapSizeX() / 256;
1257  if (MapSizeY() > 256) maxdist_y *= MapSizeY() / 256;
1258 
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;
1263 
1264  return false;
1265 }
1266 
1273 {
1274  if (_game_mode == GM_EDITOR) return CommandCost();
1275 
1277 
1278  return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
1279 }
1280 
1281 extern bool _ignore_restrictions;
1282 
1289 {
1290  if (_game_mode == GM_EDITOR && _ignore_restrictions) return CommandCost();
1291 
1292  if (TileHeight(tile) == 0 &&
1294 
1295  return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
1296 }
1297 
1304 {
1305  if (_settings_game.game_creation.landscape == LT_ARCTIC) {
1306  if (GetTileZ(tile) + 2 >= HighestSnowLine()) {
1307  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1308  }
1309  }
1310  return CommandCost();
1311 }
1312 
1319 {
1320  if (GetTropicZone(tile) == TROPICZONE_DESERT) {
1321  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1322  }
1323  return CommandCost();
1324 }
1325 
1332 {
1333  if (GetTropicZone(tile) != TROPICZONE_DESERT) {
1334  return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT);
1335  }
1336  return CommandCost();
1337 }
1338 
1345 {
1346  if (GetTropicZone(tile) != TROPICZONE_RAINFOREST) {
1347  return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST);
1348  }
1349  return CommandCost();
1350 }
1351 
1358 {
1359  if (GetTileZ(tile) > 4) {
1360  return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_LOW_AREAS);
1361  }
1362  return CommandCost();
1363 }
1364 
1371 
1383 };
1384 
1395 static CommandCost FindTownForIndustry(TileIndex tile, int type, Town **t)
1396 {
1397  *t = ClosestTownFromTile(tile, UINT_MAX);
1398 
1400 
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);
1405  }
1406  }
1407 
1408  return CommandCost();
1409 }
1410 
1411 bool IsSlopeRefused(Slope current, Slope refused)
1412 {
1413  if (IsSteepSlope(current)) return true;
1414  if (current != SLOPE_FLAT) {
1415  if (IsSteepSlope(refused)) return true;
1416 
1417  Slope t = ComplementSlope(current);
1418 
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;
1423  }
1424 
1425  return false;
1426 }
1427 
1435 static CommandCost CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileLayout &layout, IndustryType type)
1436 {
1437  IndustryBehaviour ind_behav = GetIndustrySpec(type)->behaviour;
1438 
1439  for (const IndustryTileLayoutTile &it : layout) {
1440  IndustryGfx gfx = GetTranslatedIndustryTileID(it.gfx);
1441  TileIndex cur_tile = TileAddWrap(tile, it.ti.x, it.ti.y);
1442 
1443  if (!IsValidTile(cur_tile)) {
1444  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1445  }
1446 
1447  if (gfx == GFX_WATERTILE_SPECIALCHECK) {
1448  if (!IsWaterTile(cur_tile) ||
1449  !IsTileFlat(cur_tile)) {
1450  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1451  }
1452  } else {
1453  CommandCost ret = EnsureNoVehicleOnGround(cur_tile);
1454  if (ret.Failed()) return ret;
1455  if (IsBridgeAbove(cur_tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1456 
1457  const IndustryTileSpec *its = GetIndustryTileSpec(gfx);
1458 
1459  /* Perform land/water check if not disabled */
1460  if (!HasBit(its->slopes_refused, 5) && ((HasTileWaterClass(cur_tile) && IsTileOnWater(cur_tile)) == !(ind_behav & INDUSTRYBEH_BUILT_ONWATER))) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1461 
1462  if ((ind_behav & (INDUSTRYBEH_ONLY_INTOWN | INDUSTRYBEH_TOWN1200_MORE)) || // Tile must be a house
1463  ((ind_behav & INDUSTRYBEH_ONLY_NEARTOWN) && IsTileType(cur_tile, MP_HOUSE))) { // Tile is allowed to be a house (and it is a house)
1464  if (!IsTileType(cur_tile, MP_HOUSE)) {
1465  return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_TOWNS);
1466  }
1467 
1468  /* Clear the tiles as OWNER_TOWN to not affect town rating, and to not clear protected buildings */
1469  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1471  cur_company.Restore();
1472 
1473  if (ret.Failed()) return ret;
1474  } else {
1475  /* Clear the tiles, but do not affect town ratings */
1477  if (ret.Failed()) return ret;
1478  }
1479  }
1480  }
1481 
1482  return CommandCost();
1483 }
1484 
1497 static CommandCost CheckIfIndustryTileSlopes(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)
1498 {
1499  bool refused_slope = false;
1500  bool custom_shape = false;
1501 
1502  for (const IndustryTileLayoutTile &it : layout) {
1503  IndustryGfx gfx = GetTranslatedIndustryTileID(it.gfx);
1504  TileIndex cur_tile = TileAddWrap(tile, it.ti.x, it.ti.y);
1505  assert(IsValidTile(cur_tile)); // checked before in CheckIfIndustryTilesAreFree
1506 
1507  if (gfx != GFX_WATERTILE_SPECIALCHECK) {
1508  const IndustryTileSpec *its = GetIndustryTileSpec(gfx);
1509 
1511  custom_shape = true;
1512  CommandCost ret = PerformIndustryTileSlopeCheck(tile, cur_tile, its, type, gfx, layout_index, initial_random_bits, founder, creation_type);
1513  if (ret.Failed()) return ret;
1514  } else {
1515  Slope tileh = GetTileSlope(cur_tile);
1516  refused_slope |= IsSlopeRefused(tileh, its->slopes_refused);
1517  }
1518  }
1519  }
1520 
1521  if (custom_shape_check != nullptr) *custom_shape_check = custom_shape;
1522 
1523  /* It is almost impossible to have a fully flat land in TG, so what we
1524  * do is that we check if we can make the land flat later on. See
1525  * CheckIfCanLevelIndustryPlatform(). */
1526  if (!refused_slope || (_settings_game.game_creation.land_generator == LG_TERRAGENESIS && _generating_world && !custom_shape && !_ignore_restrictions)) {
1527  return CommandCost();
1528  }
1529  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1530 }
1531 
1539 static CommandCost CheckIfIndustryIsAllowed(TileIndex tile, int type, const Town *t)
1540 {
1541  if ((GetIndustrySpec(type)->behaviour & INDUSTRYBEH_TOWN1200_MORE) && t->cache.population < 1200) {
1542  return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_TOWNS_WITH_POPULATION_OF_1200);
1543  }
1544 
1545  if ((GetIndustrySpec(type)->behaviour & INDUSTRYBEH_ONLY_NEARTOWN) && DistanceMax(t->xy, tile) > 9) {
1546  return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_NEAR_TOWN_CENTER);
1547  }
1548 
1549  return CommandCost();
1550 }
1551 
1552 static bool CheckCanTerraformSurroundingTiles(TileIndex tile, uint height, int internal)
1553 {
1554  /* Check if we don't leave the map */
1555  if (TileX(tile) == 0 || TileY(tile) == 0 || GetTileType(tile) == MP_VOID) return false;
1556 
1557  TileArea ta(tile - TileDiffXY(1, 1), 2, 2);
1558  for (TileIndex tile_walk : ta) {
1559  uint curh = TileHeight(tile_walk);
1560  /* Is the tile clear? */
1561  if ((GetTileType(tile_walk) != MP_CLEAR) && (GetTileType(tile_walk) != MP_TREES)) return false;
1562 
1563  /* Don't allow too big of a change if this is the sub-tile check */
1564  if (internal != 0 && Delta(curh, height) > 1) return false;
1565 
1566  /* Different height, so the surrounding tiles of this tile
1567  * has to be correct too (in level, or almost in level)
1568  * else you get a chain-reaction of terraforming. */
1569  if (internal == 0 && curh != height) {
1570  if (TileX(tile_walk) == 0 || TileY(tile_walk) == 0 || !CheckCanTerraformSurroundingTiles(tile_walk + TileDiffXY(-1, -1), height, internal + 1)) {
1571  return false;
1572  }
1573  }
1574  }
1575 
1576  return true;
1577 }
1578 
1583 static bool CheckIfCanLevelIndustryPlatform(TileIndex tile, DoCommandFlag flags, const IndustryTileLayout &layout, int type)
1584 {
1585  int max_x = 0;
1586  int max_y = 0;
1587 
1588  /* Finds dimensions of largest variant of this industry */
1589  for (const IndustryTileLayoutTile &it : layout) {
1590  if (it.gfx == GFX_WATERTILE_SPECIALCHECK) continue; // watercheck tiles don't count for footprint size
1591  if (it.ti.x > max_x) max_x = it.ti.x;
1592  if (it.ti.y > max_y) max_y = it.ti.y;
1593  }
1594 
1595  /* Remember level height */
1596  uint h = TileHeight(tile);
1597 
1598  if (TileX(tile) <= _settings_game.construction.industry_platform + 1U || TileY(tile) <= _settings_game.construction.industry_platform + 1U) return false;
1599  /* Check that all tiles in area and surrounding are clear
1600  * this determines that there are no obstructing items */
1601 
1602  /* TileArea::Expand is not used here as we need to abort
1603  * instead of clamping if the bounds cannot expanded. */
1606 
1607  if (TileX(ta.tile) + ta.w >= MapMaxX() || TileY(ta.tile) + ta.h >= MapMaxY()) return false;
1608 
1609  /* _current_company is OWNER_NONE for randomly generated industries and in editor, or the company who funded or prospected the industry.
1610  * Perform terraforming as OWNER_TOWN to disable autoslope and town ratings. */
1611  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1612 
1613  for (TileIndex tile_walk : ta) {
1614  uint curh = TileHeight(tile_walk);
1615  if (curh != h) {
1616  /* This tile needs terraforming. Check if we can do that without
1617  * damaging the surroundings too much. */
1618  if (!CheckCanTerraformSurroundingTiles(tile_walk, h, 0)) {
1619  cur_company.Restore();
1620  return false;
1621  }
1622  /* This is not 100% correct check, but the best we can do without modifying the map.
1623  * What is missing, is if the difference in height is more than 1.. */
1624  if (std::get<0>(Command<CMD_TERRAFORM_LAND>::Do(flags & ~DC_EXEC, tile_walk, SLOPE_N, curh <= h)).Failed()) {
1625  cur_company.Restore();
1626  return false;
1627  }
1628  }
1629  }
1630 
1631  if (flags & DC_EXEC) {
1632  /* Terraform the land under the industry */
1633  for (TileIndex tile_walk : ta) {
1634  uint curh = TileHeight(tile_walk);
1635  while (curh != h) {
1636  /* We give the terraforming for free here, because we can't calculate
1637  * exact cost in the test-round, and as we all know, that will cause
1638  * a nice assert if they don't match ;) */
1639  Command<CMD_TERRAFORM_LAND>::Do(flags, tile_walk, SLOPE_N, curh <= h);
1640  curh += (curh > h) ? -1 : 1;
1641  }
1642  }
1643  }
1644 
1645  cur_company.Restore();
1646  return true;
1647 }
1648 
1649 
1657 {
1658  const IndustrySpec *indspec = GetIndustrySpec(type);
1659 
1660  /* On a large map with many industries, it may be faster to check an area. */
1661  static const int dmax = 14;
1662  if (Industry::GetNumItems() > (size_t) (dmax * dmax * 2)) {
1663  const Industry* i = nullptr;
1664  TileArea tile_area = TileArea(tile, 1, 1).Expand(dmax);
1665  for (TileIndex atile : tile_area) {
1666  if (GetTileType(atile) == MP_INDUSTRY) {
1667  const Industry *i2 = Industry::GetByTile(atile);
1668  if (i == i2) continue;
1669  i = i2;
1670  if (DistanceMax(tile, i->location.tile) > (uint)dmax) continue;
1671  if (i->type == indspec->conflicting[0] ||
1672  i->type == indspec->conflicting[1] ||
1673  i->type == indspec->conflicting[2]) {
1674  return_cmd_error(STR_ERROR_INDUSTRY_TOO_CLOSE);
1675  }
1676  }
1677  }
1678  return CommandCost();
1679  }
1680 
1681  for (const Industry *i : Industry::Iterate()) {
1682  /* Within 14 tiles from another industry is considered close */
1683  if (DistanceMax(tile, i->location.tile) > 14) continue;
1684 
1685  /* check if there are any conflicting industry types around */
1686  if (i->type == indspec->conflicting[0] ||
1687  i->type == indspec->conflicting[1] ||
1688  i->type == indspec->conflicting[2]) {
1689  return_cmd_error(STR_ERROR_INDUSTRY_TOO_CLOSE);
1690  }
1691  }
1692  return CommandCost();
1693 }
1694 
1699 static void AdvertiseIndustryOpening(const Industry *ind)
1700 {
1701  const IndustrySpec *ind_spc = GetIndustrySpec(ind->type);
1702  SetDParam(0, ind_spc->name);
1703  if (ind_spc->new_industry_text > STR_LAST_STRINGID) {
1704  SetDParam(1, STR_TOWN_NAME);
1705  SetDParam(2, ind->town->index);
1706  } else {
1707  SetDParam(1, ind->town->index);
1708  }
1709  AddIndustryNewsItem(ind_spc->new_industry_text, NT_INDUSTRY_OPEN, ind->index);
1710  AI::BroadcastNewEvent(new ScriptEventIndustryOpen(ind->index));
1711  Game::NewEvent(new ScriptEventIndustryOpen(ind->index));
1712 }
1713 
1720 {
1722  /* Industry has a neutral station. Use it and ignore any other nearby stations. */
1723  ind->stations_near.insert(ind->neutral_station);
1724  ind->neutral_station->industries_near.clear();
1725  ind->neutral_station->industries_near.insert(IndustryListEntry{0, ind});
1726  return;
1727  }
1728 
1729  ForAllStationsAroundTiles(ind->location, [ind](Station *st, TileIndex tile) {
1730  if (!IsTileType(tile, MP_INDUSTRY) || GetIndustryIndex(tile) != ind->index) return false;
1731  ind->stations_near.insert(st);
1732  st->AddIndustryToDeliver(ind, tile);
1733  return false;
1734  });
1735 }
1736 
1748 static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type, const IndustryTileLayout &layout, size_t layout_index, Town *t, Owner founder, uint16 initial_random_bits)
1749 {
1750  const IndustrySpec *indspec = GetIndustrySpec(type);
1751 
1752  i->location = TileArea(tile, 1, 1);
1753  i->type = type;
1755 
1756  MemCpyT(i->produced_cargo, indspec->produced_cargo, lengthof(i->produced_cargo));
1757  MemCpyT(i->production_rate, indspec->production_rate, lengthof(i->production_rate));
1759 
1767 
1768  /* Randomize inital production if non-original economy is used and there are no production related callbacks. */
1769  if (!indspec->UsesOriginalEconomy()) {
1770  for (size_t ci = 0; ci < lengthof(i->production_rate); ci++) {
1771  i->production_rate[ci] = std::min((RandomRange(256) + 128) * i->production_rate[ci] >> 8, 255u);
1772  }
1773  }
1774 
1775  i->town = t;
1776  i->owner = OWNER_NONE;
1777 
1778  uint16 r = Random();
1779  i->random_colour = GB(r, 0, 4);
1780  i->counter = GB(r, 4, 12);
1781  i->random = initial_random_bits;
1782  i->was_cargo_delivered = false;
1784  i->founder = founder;
1785  i->ctlflags = INDCTL_NONE;
1786 
1787  i->construction_date = _date;
1788  i->construction_type = (_game_mode == GM_EDITOR) ? ICT_SCENARIO_EDITOR :
1790 
1791  /* Adding 1 here makes it conform to specs of var44 of varaction2 for industries
1792  * 0 = created prior of newindustries
1793  * else, chosen layout + 1 */
1794  i->selected_layout = (byte)(layout_index + 1);
1795 
1798 
1800 
1801  /* Call callbacks after the regular fields got initialised. */
1802 
1804  uint16 res = GetIndustryCallback(CBID_INDUSTRY_PROD_CHANGE_BUILD, 0, Random(), i, type, INVALID_TILE);
1805  if (res != CALLBACK_FAILED) {
1806  if (res < PRODLEVEL_MINIMUM || res > PRODLEVEL_MAXIMUM) {
1808  } else {
1809  i->prod_level = res;
1811  }
1812  }
1813  }
1814 
1815  if (_generating_world) {
1818  for (size_t ci = 0; ci < lengthof(i->last_month_production); ci++) {
1819  i->last_month_production[ci] = i->produced_cargo_waiting[ci] * 8;
1820  i->produced_cargo_waiting[ci] = 0;
1821  }
1822  }
1823 
1824  for (size_t ci = 0; ci < lengthof(i->last_month_production); ci++) {
1825  i->last_month_production[ci] += i->production_rate[ci] * 8;
1826  }
1827  }
1828 
1829  if (HasBit(indspec->callback_mask, CBM_IND_DECIDE_COLOUR)) {
1830  uint16 res = GetIndustryCallback(CBID_INDUSTRY_DECIDE_COLOUR, 0, 0, i, type, INVALID_TILE);
1831  if (res != CALLBACK_FAILED) {
1832  if (GB(res, 4, 11) != 0) ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_DECIDE_COLOUR, res);
1833  i->random_colour = GB(res, 0, 4);
1834  }
1835  }
1836 
1838  /* Clear all input cargo types */
1839  for (uint j = 0; j < lengthof(i->accepts_cargo); j++) i->accepts_cargo[j] = CT_INVALID;
1840  /* Query actual types */
1841  uint maxcargoes = (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) ? lengthof(i->accepts_cargo) : 3;
1842  for (uint j = 0; j < maxcargoes; j++) {
1844  if (res == CALLBACK_FAILED || GB(res, 0, 8) == CT_INVALID) break;
1845  if (indspec->grf_prop.grffile->grf_version >= 8 && res >= 0x100) {
1847  break;
1848  }
1849  CargoID cargo = GetCargoTranslation(GB(res, 0, 8), indspec->grf_prop.grffile);
1850  /* Industries without "unlimited" cargo types support depend on the specific order/slots of cargo types.
1851  * They need to be able to blank out specific slots without aborting the callback sequence,
1852  * and solve this by returning undefined cargo indexes. Skip these. */
1853  if (cargo == CT_INVALID && !(indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED)) continue;
1854  /* Verify valid cargo */
1855  if (std::find(indspec->accepts_cargo, endof(indspec->accepts_cargo), cargo) == endof(indspec->accepts_cargo)) {
1856  /* Cargo not in spec, error in NewGRF */
1858  break;
1859  }
1860  if (std::find(i->accepts_cargo, i->accepts_cargo + j, cargo) != i->accepts_cargo + j) {
1861  /* Duplicate cargo */
1863  break;
1864  }
1865  i->accepts_cargo[j] = cargo;
1866  }
1867  }
1868 
1870  /* Clear all output cargo types */
1871  for (uint j = 0; j < lengthof(i->produced_cargo); j++) i->produced_cargo[j] = CT_INVALID;
1872  /* Query actual types */
1873  uint maxcargoes = (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) ? lengthof(i->produced_cargo) : 2;
1874  for (uint j = 0; j < maxcargoes; j++) {
1876  if (res == CALLBACK_FAILED || GB(res, 0, 8) == CT_INVALID) break;
1877  if (indspec->grf_prop.grffile->grf_version >= 8 && res >= 0x100) {
1879  break;
1880  }
1881  CargoID cargo = GetCargoTranslation(GB(res, 0, 8), indspec->grf_prop.grffile);
1882  /* Allow older GRFs to skip slots. */
1883  if (cargo == CT_INVALID && !(indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED)) continue;
1884  /* Verify valid cargo */
1885  if (std::find(indspec->produced_cargo, endof(indspec->produced_cargo), cargo) == endof(indspec->produced_cargo)) {
1886  /* Cargo not in spec, error in NewGRF */
1888  break;
1889  }
1890  if (std::find(i->produced_cargo, i->produced_cargo + j, cargo) != i->produced_cargo + j) {
1891  /* Duplicate cargo */
1893  break;
1894  }
1895  i->produced_cargo[j] = cargo;
1896  }
1897  }
1898 
1899  /* Plant the tiles */
1900 
1901  for (const IndustryTileLayoutTile &it : layout) {
1902  TileIndex cur_tile = tile + ToTileIndexDiff(it.ti);
1903 
1904  if (it.gfx != GFX_WATERTILE_SPECIALCHECK) {
1905  i->location.Add(cur_tile);
1906 
1907  WaterClass wc = (IsWaterTile(cur_tile) ? GetWaterClass(cur_tile) : WATER_CLASS_INVALID);
1908 
1910 
1911  MakeIndustry(cur_tile, i->index, it.gfx, Random(), wc);
1912 
1913  if (_generating_world) {
1914  SetIndustryConstructionCounter(cur_tile, 3);
1915  SetIndustryConstructionStage(cur_tile, 2);
1916  }
1917 
1918  /* it->gfx is stored in the map. But the translated ID cur_gfx is the interesting one */
1919  IndustryGfx cur_gfx = GetTranslatedIndustryTileID(it.gfx);
1920  const IndustryTileSpec *its = GetIndustryTileSpec(cur_gfx);
1922  }
1923  }
1924 
1926  for (uint j = 0; j != 50; j++) PlantRandomFarmField(i);
1927  }
1928  InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, IDIWD_FORCE_REBUILD);
1929 
1931 }
1932 
1949 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)
1950 {
1951  assert(layout_index < indspec->layouts.size());
1952  const IndustryTileLayout &layout = indspec->layouts[layout_index];
1953 
1954  *ip = nullptr;
1955 
1956  /* 1. Cheap: Built-in checks on industry level. */
1958  if (ret.Failed()) return ret;
1959 
1960  Town *t = nullptr;
1961  ret = FindTownForIndustry(tile, type, &t);
1962  if (ret.Failed()) return ret;
1963  assert(t != nullptr);
1964 
1965  ret = CheckIfIndustryIsAllowed(tile, type, t);
1966  if (ret.Failed()) return ret;
1967 
1968  /* 2. Built-in checks on industry tiles. */
1969  std::vector<ClearedObjectArea> object_areas(_cleared_object_areas);
1970  ret = CheckIfIndustryTilesAreFree(tile, layout, type);
1971  _cleared_object_areas = object_areas;
1972  if (ret.Failed()) return ret;
1973 
1974  /* 3. NewGRF-defined checks on industry level. */
1975  if (HasBit(GetIndustrySpec(type)->callback_mask, CBM_IND_LOCATION)) {
1976  ret = CheckIfCallBackAllowsCreation(tile, type, layout_index, random_var8f, random_initial_bits, founder, creation_type);
1977  } else {
1978  ret = _check_new_industry_procs[indspec->check_proc](tile);
1979  }
1980  if (ret.Failed()) return ret;
1981 
1982  /* 4. Expensive: NewGRF-defined checks on industry tiles. */
1983  bool custom_shape_check = false;
1984  ret = CheckIfIndustryTileSlopes(tile, layout, layout_index, type, random_initial_bits, founder, creation_type, &custom_shape_check);
1985  if (ret.Failed()) return ret;
1986 
1988  !_ignore_restrictions && !CheckIfCanLevelIndustryPlatform(tile, DC_NO_WATER, layout, type)) {
1989  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1990  }
1991 
1992  if (!Industry::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_INDUSTRIES);
1993 
1994  if (flags & DC_EXEC) {
1995  *ip = new Industry(tile);
1996  if (!custom_shape_check) CheckIfCanLevelIndustryPlatform(tile, DC_NO_WATER | DC_EXEC, layout, type);
1997  DoCreateNewIndustry(*ip, tile, type, layout, layout_index, t, founder, random_initial_bits);
1998  }
1999 
2000  return CommandCost();
2001 }
2002 
2013 CommandCost CmdBuildIndustry(DoCommandFlag flags, TileIndex tile, IndustryType it, uint32 first_layout, bool fund, uint32 seed)
2014 {
2015  if (it >= NUM_INDUSTRYTYPES) return CMD_ERROR;
2016 
2017  const IndustrySpec *indspec = GetIndustrySpec(it);
2018 
2019  /* Check if the to-be built/founded industry is available for this climate. */
2020  if (!indspec->enabled || indspec->layouts.empty()) return CMD_ERROR;
2021 
2022  /* If the setting for raw-material industries is not on, you cannot build raw-material industries.
2023  * Raw material industries are industries that do not accept cargo (at least for now) */
2024  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 0 && indspec->IsRawIndustry()) {
2025  return CMD_ERROR;
2026  }
2027 
2028  if (_game_mode != GM_EDITOR && GetIndustryProbabilityCallback(it, _current_company == OWNER_DEITY ? IACT_RANDOMCREATION : IACT_USERCREATION, 1) == 0) {
2029  return CMD_ERROR;
2030  }
2031 
2032  Randomizer randomizer;
2033  randomizer.SetSeed(seed);
2034  uint16 random_initial_bits = GB(seed, 0, 16);
2035  uint32 random_var8f = randomizer.Next();
2036  size_t num_layouts = indspec->layouts.size();
2037  CommandCost ret = CommandCost(STR_ERROR_SITE_UNSUITABLE);
2038  const bool deity_prospect = _current_company == OWNER_DEITY && !fund;
2039 
2040  Industry *ind = nullptr;
2041  if (deity_prospect || (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 2 && indspec->IsRawIndustry())) {
2042  if (flags & DC_EXEC) {
2043  /* Prospecting has a chance to fail, however we cannot guarantee that something can
2044  * be built on the map, so the chance gets lower when the map is fuller, but there
2045  * is nothing we can really do about that. */
2046  bool prospect_success = deity_prospect || Random() <= indspec->prospecting_chance;
2047  if (prospect_success) {
2048  /* Prospected industries are build as OWNER_TOWN to not e.g. be build on owned land of the founder */
2050  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
2051  for (int i = 0; i < 5000; i++) {
2052  /* We should not have more than one Random() in a function call
2053  * because parameter evaluation order is not guaranteed in the c++ standard
2054  */
2055  tile = RandomTile();
2056  /* Start with a random layout */
2057  size_t layout = RandomRange((uint32)num_layouts);
2058  /* Check now each layout, starting with the random one */
2059  for (size_t j = 0; j < num_layouts; j++) {
2060  layout = (layout + 1) % num_layouts;
2061  ret = CreateNewIndustryHelper(tile, it, flags, indspec, layout, random_var8f, random_initial_bits, cur_company.GetOriginalValue(), calltype, &ind);
2062  if (ret.Succeeded()) break;
2063  }
2064  if (ret.Succeeded()) break;
2065  }
2066  cur_company.Restore();
2067  }
2068  if (ret.Failed() && IsLocalCompany()) {
2069  if (prospect_success) {
2070  ShowErrorMessage(STR_ERROR_CAN_T_PROSPECT_INDUSTRY, STR_ERROR_NO_SUITABLE_PLACES_FOR_PROSPECTING, WL_INFO);
2071  } else {
2072  ShowErrorMessage(STR_ERROR_CAN_T_PROSPECT_INDUSTRY, STR_ERROR_PROSPECTING_WAS_UNLUCKY, WL_INFO);
2073  }
2074  }
2075  }
2076  } else {
2077  size_t layout = first_layout;
2078  if (layout >= num_layouts) return CMD_ERROR;
2079 
2080  /* Check subsequently each layout, starting with the given layout in p1 */
2081  for (size_t i = 0; i < num_layouts; i++) {
2082  layout = (layout + 1) % num_layouts;
2083  ret = CreateNewIndustryHelper(tile, it, flags, indspec, layout, random_var8f, random_initial_bits, _current_company, _current_company == OWNER_DEITY ? IACT_RANDOMCREATION : IACT_USERCREATION, &ind);
2084  if (ret.Succeeded()) break;
2085  }
2086 
2087  /* If it still failed, there's no suitable layout to build here, return the error */
2088  if (ret.Failed()) return ret;
2089  }
2090 
2091  if ((flags & DC_EXEC) && ind != nullptr && _game_mode != GM_EDITOR) {
2093  }
2094 
2095  return CommandCost(EXPENSES_OTHER, indspec->GetConstructionCost());
2096 }
2097 
2110 CommandCost CmdIndustryCtrl(DoCommandFlag flags, IndustryID ind_id, IndustryAction action, IndustryControlFlags ctlflags, Owner company_id, const std::string &text)
2111 {
2112  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2113 
2114  Industry *ind = Industry::GetIfValid(ind_id);
2115  if (ind == nullptr) return CMD_ERROR;
2116 
2117  switch (action) {
2119  if (flags & DC_EXEC) ind->ctlflags = ctlflags & INDCTL_MASK;
2120 
2121  break;
2122  }
2123 
2126  if (company_id != OWNER_NONE && company_id != INVALID_OWNER && company_id != OWNER_DEITY
2127  && !Company::IsValidID(company_id)) return CMD_ERROR;
2128 
2129  if (flags & DC_EXEC) {
2130  if (action == IndustryAction::SetExclusiveSupplier) {
2131  ind->exclusive_supplier = company_id;
2132  } else {
2133  ind->exclusive_consumer = company_id;
2134  }
2135  }
2136 
2137  break;
2138  }
2139 
2140  case IndustryAction::SetText: {
2141  ind->text.clear();
2142  if (!text.empty()) ind->text = text;
2144  break;
2145  }
2146 
2147  default:
2148  return CMD_ERROR;
2149  }
2150 
2151  return CommandCost();
2152 }
2153 
2161 static Industry *CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAvailabilityCallType creation_type)
2162 {
2163  const IndustrySpec *indspec = GetIndustrySpec(type);
2164 
2165  uint32 seed = Random();
2166  uint32 seed2 = Random();
2167  Industry *i = nullptr;
2168  size_t layout_index = RandomRange((uint32)indspec->layouts.size());
2169  [[maybe_unused]] CommandCost ret = CreateNewIndustryHelper(tile, type, DC_EXEC, indspec, layout_index, seed, GB(seed2, 0, 16), OWNER_NONE, creation_type, &i);
2170  assert(i != nullptr || ret.Failed());
2171  return i;
2172 }
2173 
2180 static uint32 GetScaledIndustryGenerationProbability(IndustryType it, bool *force_at_least_one)
2181 {
2182  const IndustrySpec *ind_spc = GetIndustrySpec(it);
2183  uint32 chance = ind_spc->appear_creation[_settings_game.game_creation.landscape];
2184  if (!ind_spc->enabled || ind_spc->layouts.empty() ||
2185  (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) ||
2186  (chance = GetIndustryProbabilityCallback(it, IACT_MAPGENERATION, chance)) == 0) {
2187  *force_at_least_one = false;
2188  return 0;
2189  } else {
2190  chance *= 16; // to increase precision
2191  /* We want industries appearing at coast to appear less often on bigger maps, as length of coast increases slower than map area.
2192  * For simplicity we scale in both cases, though scaling the probabilities of all industries has no effect. */
2193  chance = (ind_spc->check_proc == CHECK_REFINERY || ind_spc->check_proc == CHECK_OIL_RIG) ? ScaleByMapSize1D(chance) : ScaleByMapSize(chance);
2194 
2195  *force_at_least_one = (chance > 0) && !(ind_spc->behaviour & INDUSTRYBEH_NOBUILT_MAPCREATION) && (_game_mode != GM_EDITOR);
2196  return chance;
2197  }
2198 }
2199 
2206 static uint16 GetIndustryGamePlayProbability(IndustryType it, byte *min_number)
2207 {
2209  *min_number = 0;
2210  return 0;
2211  }
2212 
2213  const IndustrySpec *ind_spc = GetIndustrySpec(it);
2214  byte chance = ind_spc->appear_ingame[_settings_game.game_creation.landscape];
2215  if (!ind_spc->enabled || ind_spc->layouts.empty() ||
2216  ((ind_spc->behaviour & INDUSTRYBEH_BEFORE_1950) && _cur_year > 1950) ||
2217  ((ind_spc->behaviour & INDUSTRYBEH_AFTER_1960) && _cur_year < 1960) ||
2218  (chance = GetIndustryProbabilityCallback(it, IACT_RANDOMCREATION, chance)) == 0) {
2219  *min_number = 0;
2220  return 0;
2221  }
2222  *min_number = (ind_spc->behaviour & INDUSTRYBEH_CANCLOSE_LASTINSTANCE) ? 1 : 0;
2223  return chance;
2224 }
2225 
2231 {
2232  /* Number of industries on a 256x256 map. */
2233  static const uint16 numof_industry_table[] = {
2234  0, // none
2235  0, // minimal
2236  10, // very low
2237  25, // low
2238  55, // normal
2239  80, // high
2240  0, // custom
2241  };
2242 
2243  assert(lengthof(numof_industry_table) == ID_END);
2244  uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
2245 
2246  if (difficulty == ID_CUSTOM) return std::min<uint>(IndustryPool::MAX_SIZE, _settings_game.game_creation.custom_industry_number);
2247 
2248  return std::min<uint>(IndustryPool::MAX_SIZE, ScaleByMapSize(numof_industry_table[difficulty]));
2249 }
2250 
2259 static Industry *PlaceIndustry(IndustryType type, IndustryAvailabilityCallType creation_type, bool try_hard)
2260 {
2261  uint tries = try_hard ? 10000u : 2000u;
2262  for (; tries > 0; tries--) {
2263  Industry *ind = CreateNewIndustry(RandomTile(), type, creation_type);
2264  if (ind != nullptr) return ind;
2265  }
2266  return nullptr;
2267 }
2268 
2274 static void PlaceInitialIndustry(IndustryType type, bool try_hard)
2275 {
2276  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2277 
2279  PlaceIndustry(type, IACT_MAPGENERATION, try_hard);
2280 
2281  cur_company.Restore();
2282 }
2283 
2289 {
2290  int total = 0;
2291  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) total += Industry::GetIndustryTypeCount(it);
2292  return total;
2293 }
2294 
2295 
2298 {
2299  this->probability = 0;
2300  this->min_number = 0;
2301  this->target_count = 0;
2302  this->max_wait = 1;
2303  this->wait_count = 0;
2304 }
2305 
2308 {
2310 
2311  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2312  this->builddata[it].Reset();
2313  }
2314 }
2315 
2318 {
2319  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.
2320  if (_settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // 'no industries' setting.
2321 
2322  /* To prevent running out of unused industries for the player to connect,
2323  * add a fraction of new industries each month, but only if the manager can keep up. */
2324  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).
2325  if (GetCurrentTotalNumberOfIndustries() + max_behind >= (this->wanted_inds >> 16)) {
2326  this->wanted_inds += ScaleByMapSize(NEWINDS_PER_MONTH);
2327  }
2328 }
2329 
2335 {
2336  if (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // No industries in the game.
2337 
2338  uint32 industry_probs[NUM_INDUSTRYTYPES];
2339  bool force_at_least_one[NUM_INDUSTRYTYPES];
2340  uint32 total_prob = 0;
2341  uint num_forced = 0;
2342 
2343  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2344  industry_probs[it] = GetScaledIndustryGenerationProbability(it, force_at_least_one + it);
2345  total_prob += industry_probs[it];
2346  if (force_at_least_one[it]) num_forced++;
2347  }
2348 
2349  uint total_amount = GetNumberOfIndustries();
2350  if (total_prob == 0 || total_amount < num_forced) {
2351  /* Only place the forced ones */
2352  total_amount = num_forced;
2353  }
2354 
2356 
2357  /* Try to build one industry per type independent of any probabilities */
2358  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2359  if (force_at_least_one[it]) {
2360  assert(total_amount > 0);
2361  total_amount--;
2362  PlaceInitialIndustry(it, true);
2363  }
2364  }
2365 
2366  /* Add the remaining industries according to their probabilities */
2367  for (uint i = 0; i < total_amount; i++) {
2368  uint32 r = RandomRange(total_prob);
2369  IndustryType it = 0;
2370  while (r >= industry_probs[it]) {
2371  r -= industry_probs[it];
2372  it++;
2373  assert(it < NUM_INDUSTRYTYPES);
2374  }
2375  assert(industry_probs[it] > 0);
2376  PlaceInitialIndustry(it, false);
2377  }
2379 }
2380 
2386 {
2387  for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
2388  if (i->produced_cargo[j] != CT_INVALID) {
2389  byte pct = 0;
2390  if (i->this_month_production[j] != 0) {
2392  pct = std::min(i->this_month_transported[j] * 256 / i->this_month_production[j], 255);
2393  }
2394  i->last_month_pct_transported[j] = pct;
2395 
2397  i->this_month_production[j] = 0;
2398 
2400  i->this_month_transported[j] = 0;
2401  }
2402  }
2403 }
2404 
2410 {
2411  const IndustrySpec *indspec = GetIndustrySpec(this->type);
2412  assert(indspec->UsesOriginalEconomy());
2413 
2414  /* Rates are rounded up, so e.g. oilrig always produces some passengers */
2415  for (size_t i = 0; i < lengthof(this->production_rate); i++) {
2416  this->production_rate[i] = std::min(CeilDiv(indspec->production_rate[i] * this->prod_level, PRODLEVEL_DEFAULT), 0xFFu);
2417  }
2418 }
2419 
2420 void Industry::FillCachedName() const
2421 {
2422  char buf[256];
2423  int64 args_array[] = { this->index };
2424  StringParameters tmp_params(args_array);
2425  char *end = GetStringWithArgs(buf, STR_INDUSTRY_NAME, &tmp_params, lastof(buf));
2426  this->cached_name.assign(buf, end);
2427 }
2428 
2429 void ClearAllIndustryCachedNames()
2430 {
2431  for (Industry *ind : Industry::Iterate()) {
2432  ind->cached_name.clear();
2433  }
2434 }
2435 
2442 {
2443  byte min_number;
2445  bool changed = min_number != this->min_number || probability != this->probability;
2446  this->min_number = min_number;
2447  this->probability = probability;
2448  return changed;
2449 }
2450 
2453 {
2454  bool changed = false;
2455  uint num_planned = 0; // Number of industries planned in the industry build data.
2456  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2457  changed |= this->builddata[it].GetIndustryTypeData(it);
2458  num_planned += this->builddata[it].target_count;
2459  }
2460  uint total_amount = this->wanted_inds >> 16; // Desired total number of industries.
2461  changed |= num_planned != total_amount;
2462  if (!changed) return; // All industries are still the same, no need to re-randomize.
2463 
2464  /* Initialize the target counts. */
2465  uint force_build = 0; // Number of industries that should always be available.
2466  uint32 total_prob = 0; // Sum of probabilities.
2467  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2468  IndustryTypeBuildData *ibd = this->builddata + it;
2469  force_build += ibd->min_number;
2470  ibd->target_count = ibd->min_number;
2471  total_prob += ibd->probability;
2472  }
2473 
2474  if (total_prob == 0) return; // No buildable industries.
2475 
2476  /* Subtract forced industries from the number of industries available for construction. */
2477  total_amount = (total_amount <= force_build) ? 0 : total_amount - force_build;
2478 
2479  /* Assign number of industries that should be aimed for, by using the probability as a weight. */
2480  while (total_amount > 0) {
2481  uint32 r = RandomRange(total_prob);
2482  IndustryType it = 0;
2483  while (r >= this->builddata[it].probability) {
2484  r -= this->builddata[it].probability;
2485  it++;
2486  assert(it < NUM_INDUSTRYTYPES);
2487  }
2488  assert(this->builddata[it].probability > 0);
2489  this->builddata[it].target_count++;
2490  total_amount--;
2491  }
2492 }
2493 
2498 {
2499  this->SetupTargetCount();
2500 
2501  int missing = 0; // Number of industries that need to be build.
2502  uint count = 0; // Number of industry types eligible for build.
2503  uint32 total_prob = 0; // Sum of probabilities.
2504  IndustryType forced_build = NUM_INDUSTRYTYPES; // Industry type that should be forcibly build.
2505  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2506  int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it);
2507  missing += difference;
2508  if (this->builddata[it].wait_count > 0) continue; // This type may not be built now.
2509  if (difference > 0) {
2510  if (Industry::GetIndustryTypeCount(it) == 0 && this->builddata[it].min_number > 0) {
2511  /* An industry that should exist at least once, is not available. Force it, trying the most needed one first. */
2512  if (forced_build == NUM_INDUSTRYTYPES ||
2513  difference > this->builddata[forced_build].target_count - Industry::GetIndustryTypeCount(forced_build)) {
2514  forced_build = it;
2515  }
2516  }
2517  total_prob += difference;
2518  count++;
2519  }
2520  }
2521 
2522  if (EconomyIsInRecession() || (forced_build == NUM_INDUSTRYTYPES && (missing <= 0 || total_prob == 0))) count = 0; // Skip creation of an industry.
2523 
2524  if (count >= 1) {
2525  /* If not forced, pick a weighted random industry to build.
2526  * For the case that count == 1, there is no need to draw a random number. */
2527  IndustryType it;
2528  if (forced_build != NUM_INDUSTRYTYPES) {
2529  it = forced_build;
2530  } else {
2531  /* Non-forced, select an industry type to build (weighted random). */
2532  uint32 r = 0; // Initialized to silence the compiler.
2533  if (count > 1) r = RandomRange(total_prob);
2534  for (it = 0; it < NUM_INDUSTRYTYPES; it++) {
2535  if (this->builddata[it].wait_count > 0) continue; // Type may not be built now.
2536  int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it);
2537  if (difference <= 0) continue; // Too many of this kind.
2538  if (count == 1) break;
2539  if (r < (uint)difference) break;
2540  r -= difference;
2541  }
2542  assert(it < NUM_INDUSTRYTYPES && this->builddata[it].target_count > Industry::GetIndustryTypeCount(it));
2543  }
2544 
2545  /* Try to create the industry. */
2546  const Industry *ind = PlaceIndustry(it, IACT_RANDOMCREATION, false);
2547  if (ind == nullptr) {
2548  this->builddata[it].wait_count = this->builddata[it].max_wait + 1; // Compensate for decrementing below.
2549  this->builddata[it].max_wait = std::min(1000, this->builddata[it].max_wait + 2);
2550  } else {
2552  this->builddata[it].max_wait = std::max(this->builddata[it].max_wait / 2, 1); // Reduce waiting time of the industry type.
2553  }
2554  }
2555 
2556  /* Decrement wait counters. */
2557  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2558  if (this->builddata[it].wait_count > 0) this->builddata[it].wait_count--;
2559  }
2560 }
2561 
2570 static bool CheckIndustryCloseDownProtection(IndustryType type)
2571 {
2572  const IndustrySpec *indspec = GetIndustrySpec(type);
2573 
2574  /* oil wells (or the industries with that flag set) are always allowed to closedown */
2575  if ((indspec->behaviour & INDUSTRYBEH_DONT_INCR_PROD) && _settings_game.game_creation.landscape == LT_TEMPERATE) return false;
2576  return (indspec->behaviour & INDUSTRYBEH_CANCLOSE_LASTINSTANCE) == 0 && Industry::GetIndustryTypeCount(type) <= 1;
2577 }
2578 
2588 static void CanCargoServiceIndustry(CargoID cargo, Industry *ind, bool *c_accepts, bool *c_produces)
2589 {
2590  if (cargo == CT_INVALID) return;
2591 
2592  /* Check for acceptance of cargo */
2593  for (byte j = 0; j < lengthof(ind->accepts_cargo); j++) {
2594  if (cargo == ind->accepts_cargo[j] && !IndustryTemporarilyRefusesCargo(ind, cargo)) {
2595  *c_accepts = true;
2596  break;
2597  }
2598  }
2599 
2600  /* Check for produced cargo */
2601  for (byte j = 0; j < lengthof(ind->produced_cargo); j++) {
2602  if (cargo == ind->produced_cargo[j]) {
2603  *c_produces = true;
2604  break;
2605  }
2606  }
2607 }
2608 
2623 {
2624  if (ind->stations_near.size() == 0) return 0; // No stations found at all => nobody services
2625 
2626  int result = 0;
2627  for (const Vehicle *v : Vehicle::Iterate()) {
2628  /* Is it worthwhile to try this vehicle? */
2629  if (v->owner != _local_company && result != 0) continue;
2630 
2631  /* Check whether it accepts the right kind of cargo */
2632  bool c_accepts = false;
2633  bool c_produces = false;
2634  if (v->type == VEH_TRAIN && v->IsFrontEngine()) {
2635  for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
2636  CanCargoServiceIndustry(u->cargo_type, ind, &c_accepts, &c_produces);
2637  }
2638  } else if (v->type == VEH_ROAD || v->type == VEH_SHIP || v->type == VEH_AIRCRAFT) {
2639  CanCargoServiceIndustry(v->cargo_type, ind, &c_accepts, &c_produces);
2640  } else {
2641  continue;
2642  }
2643  if (!c_accepts && !c_produces) continue; // Wrong cargo
2644 
2645  /* Check orders of the vehicle.
2646  * We cannot check the first of shared orders only, since the first vehicle in such a chain
2647  * may have a different cargo type.
2648  */
2649  for (const Order *o : v->Orders()) {
2650  if (o->IsType(OT_GOTO_STATION) && !(o->GetUnloadType() & OUFB_TRANSFER)) {
2651  /* Vehicle visits a station to load or unload */
2652  Station *st = Station::Get(o->GetDestination());
2653  assert(st != nullptr);
2654 
2655  /* Same cargo produced by industry is dropped here => not serviced by vehicle v */
2656  if ((o->GetUnloadType() & OUFB_UNLOAD) && !c_accepts) break;
2657 
2658  if (ind->stations_near.find(st) != ind->stations_near.end()) {
2659  if (v->owner == _local_company) return 2; // Company services industry
2660  result = 1; // Competitor services industry
2661  }
2662  }
2663  }
2664  }
2665  return result;
2666 }
2667 
2675 static void ReportNewsProductionChangeIndustry(Industry *ind, CargoID type, int percent)
2676 {
2677  NewsType nt;
2678 
2679  switch (WhoCanServiceIndustry(ind)) {
2680  case 0: nt = NT_INDUSTRY_NOBODY; break;
2681  case 1: nt = NT_INDUSTRY_OTHER; break;
2682  case 2: nt = NT_INDUSTRY_COMPANY; break;
2683  default: NOT_REACHED();
2684  }
2685  SetDParam(2, abs(percent));
2686  SetDParam(0, CargoSpec::Get(type)->name);
2687  SetDParam(1, ind->index);
2688  AddIndustryNewsItem(
2689  percent >= 0 ? STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_SMOOTH : STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_SMOOTH,
2690  nt,
2691  ind->index
2692  );
2693 }
2694 
2695 static const uint PERCENT_TRANSPORTED_60 = 153;
2696 static const uint PERCENT_TRANSPORTED_80 = 204;
2697 
2703 static void ChangeIndustryProduction(Industry *i, bool monthly)
2704 {
2705  StringID str = STR_NULL;
2706  bool closeit = false;
2707  const IndustrySpec *indspec = GetIndustrySpec(i->type);
2708  bool standard = false;
2709  bool suppress_message = false;
2710  bool recalculate_multipliers = false;
2711  /* use original economy for industries using production related callbacks */
2712  bool original_economy = indspec->UsesOriginalEconomy();
2713  byte div = 0;
2714  byte mul = 0;
2715  int8 increment = 0;
2716 
2717  bool callback_enabled = HasBit(indspec->callback_mask, monthly ? CBM_IND_MONTHLYPROD_CHANGE : CBM_IND_PRODUCTION_CHANGE);
2718  if (callback_enabled) {
2720  if (res != CALLBACK_FAILED) { // failed callback means "do nothing"
2721  suppress_message = HasBit(res, 7);
2722  /* Get the custom message if any */
2723  if (HasBit(res, 8)) str = MapGRFStringID(indspec->grf_prop.grffile->grfid, GB(GetRegister(0x100), 0, 16));
2724  res = GB(res, 0, 4);
2725  switch (res) {
2726  default: NOT_REACHED();
2727  case 0x0: break; // Do nothing, but show the custom message if any
2728  case 0x1: div = 1; break; // Halve industry production. If production reaches the quarter of the default, the industry is closed instead.
2729  case 0x2: mul = 1; break; // Double industry production if it hasn't reached eight times of the original yet.
2730  case 0x3: closeit = true; break; // The industry announces imminent closure, and is physically removed from the map next month.
2731  case 0x4: standard = true; break; // Do the standard random production change as if this industry was a primary one.
2732  case 0x5: case 0x6: case 0x7: // Divide production by 4, 8, 16
2733  case 0x8: div = res - 0x3; break; // Divide production by 32
2734  case 0x9: case 0xA: case 0xB: // Multiply production by 4, 8, 16
2735  case 0xC: mul = res - 0x7; break; // Multiply production by 32
2736  case 0xD: // decrement production
2737  case 0xE: // increment production
2738  increment = res == 0x0D ? -1 : 1;
2739  break;
2740  case 0xF: // Set production to third byte of register 0x100
2742  recalculate_multipliers = true;
2743  break;
2744  }
2745  }
2746  } else {
2747  if (monthly == original_economy) return;
2748  if (!original_economy && _settings_game.economy.type == ET_FROZEN) return;
2749  if (indspec->life_type == INDUSTRYLIFE_BLACK_HOLE) return;
2750  }
2751 
2752  if (standard || (!callback_enabled && (indspec->life_type & (INDUSTRYLIFE_ORGANIC | INDUSTRYLIFE_EXTRACTIVE)) != 0)) {
2753  /* decrease or increase */
2754  bool only_decrease = (indspec->behaviour & INDUSTRYBEH_DONT_INCR_PROD) && _settings_game.game_creation.landscape == LT_TEMPERATE;
2755 
2756  if (original_economy) {
2757  if (only_decrease || Chance16(1, 3)) {
2758  /* If more than 60% transported, 66% chance of increase, else 33% chance of increase */
2759  if (!only_decrease && (i->last_month_pct_transported[0] > PERCENT_TRANSPORTED_60) != Chance16(1, 3)) {
2760  mul = 1; // Increase production
2761  } else {
2762  div = 1; // Decrease production
2763  }
2764  }
2765  } else if (_settings_game.economy.type == ET_SMOOTH) {
2767  for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
2768  if (i->produced_cargo[j] == CT_INVALID) continue;
2769  uint32 r = Random();
2770  int old_prod, new_prod, percent;
2771  /* If over 60% is transported, mult is 1, else mult is -1. */
2772  int mult = (i->last_month_pct_transported[j] > PERCENT_TRANSPORTED_60) ? 1 : -1;
2773 
2774  new_prod = old_prod = i->production_rate[j];
2775 
2776  /* For industries with only_decrease flags (temperate terrain Oil Wells),
2777  * the multiplier will always be -1 so they will only decrease. */
2778  if (only_decrease) {
2779  mult = -1;
2780  /* For normal industries, if over 60% is transported, 33% chance for decrease.
2781  * Bonus for very high station ratings (over 80%): 16% chance for decrease. */
2782  } else if (Chance16I(1, ((i->last_month_pct_transported[j] > PERCENT_TRANSPORTED_80) ? 6 : 3), r)) {
2783  mult *= -1;
2784  }
2785 
2786  /* 4.5% chance for 3-23% (or 1 unit for very low productions) production change,
2787  * determined by mult value. If mult = 1 prod. increases, else (-1) it decreases. */
2788  if (Chance16I(1, 22, r >> 16)) {
2789  new_prod += mult * (std::max(((RandomRange(50) + 10) * old_prod) >> 8, 1U));
2790  }
2791 
2792  /* Prevent production to overflow or Oil Rig passengers to be over-"produced" */
2793  new_prod = Clamp(new_prod, 1, 255);
2794  if (i->produced_cargo[j] == CT_PASSENGERS && !(indspec->behaviour & INDUSTRYBEH_NO_PAX_PROD_CLAMP)) {
2795  new_prod = Clamp(new_prod, 0, 16);
2796  }
2797 
2798  /* If override flags are set, prevent actually changing production if any was decided on */
2799  if ((i->ctlflags & INDCTL_NO_PRODUCTION_DECREASE) && new_prod < old_prod) continue;
2800  if ((i->ctlflags & INDCTL_NO_PRODUCTION_INCREASE) && new_prod > old_prod) continue;
2801 
2802  /* Do not stop closing the industry when it has the lowest possible production rate */
2803  if (new_prod == old_prod && old_prod > 1) {
2804  closeit = false;
2805  continue;
2806  }
2807 
2808  percent = (old_prod == 0) ? 100 : (new_prod * 100 / old_prod - 100);
2809  i->production_rate[j] = new_prod;
2810 
2811  /* Close the industry when it has the lowest possible production rate */
2812  if (new_prod > 1) closeit = false;
2813 
2814  if (abs(percent) >= 10) {
2816  }
2817  }
2818  }
2819  }
2820 
2821  /* If override flags are set, prevent actually changing production if any was decided on */
2822  if ((i->ctlflags & INDCTL_NO_PRODUCTION_DECREASE) && (div > 0 || increment < 0)) return;
2823  if ((i->ctlflags & INDCTL_NO_PRODUCTION_INCREASE) && (mul > 0 || increment > 0)) return;
2824 
2825  if (!callback_enabled && (indspec->life_type & INDUSTRYLIFE_PROCESSING)) {
2826  if ( (byte)(_cur_year - i->last_prod_year) >= 5 && Chance16(1, original_economy ? 2 : 180)) {
2827  closeit = true;
2828  }
2829  }
2830 
2831  /* Increase if needed */
2832  while (mul-- != 0 && i->prod_level < PRODLEVEL_MAXIMUM) {
2833  i->prod_level = std::min<int>(i->prod_level * 2, PRODLEVEL_MAXIMUM);
2834  recalculate_multipliers = true;
2835  if (str == STR_NULL) str = indspec->production_up_text;
2836  }
2837 
2838  /* Decrease if needed */
2839  while (div-- != 0 && !closeit) {
2840  if (i->prod_level == PRODLEVEL_MINIMUM) {
2841  closeit = true;
2842  break;
2843  } else {
2844  i->prod_level = std::max<int>(i->prod_level / 2, PRODLEVEL_MINIMUM);
2845  recalculate_multipliers = true;
2846  if (str == STR_NULL) str = indspec->production_down_text;
2847  }
2848  }
2849 
2850  /* Increase or Decreasing the production level if needed */
2851  if (increment != 0) {
2852  if (increment < 0 && i->prod_level == PRODLEVEL_MINIMUM) {
2853  closeit = true;
2854  } else {
2856  recalculate_multipliers = true;
2857  }
2858  }
2859 
2860  /* Recalculate production_rate
2861  * For non-smooth economy these should always be synchronized with prod_level */
2862  if (recalculate_multipliers) i->RecomputeProductionMultipliers();
2863 
2864  /* Close if needed and allowed */
2865  if (closeit && !CheckIndustryCloseDownProtection(i->type) && !(i->ctlflags & INDCTL_NO_CLOSURE)) {
2868  str = indspec->closure_text;
2869  }
2870 
2871  if (!suppress_message && str != STR_NULL) {
2872  NewsType nt;
2873  /* Compute news category */
2874  if (closeit) {
2875  nt = NT_INDUSTRY_CLOSE;
2876  AI::BroadcastNewEvent(new ScriptEventIndustryClose(i->index));
2877  Game::NewEvent(new ScriptEventIndustryClose(i->index));
2878  } else {
2879  switch (WhoCanServiceIndustry(i)) {
2880  case 0: nt = NT_INDUSTRY_NOBODY; break;
2881  case 1: nt = NT_INDUSTRY_OTHER; break;
2882  case 2: nt = NT_INDUSTRY_COMPANY; break;
2883  default: NOT_REACHED();
2884  }
2885  }
2886  /* Set parameters of news string */
2887  if (str > STR_LAST_STRINGID) {
2888  SetDParam(0, STR_TOWN_NAME);
2889  SetDParam(1, i->town->index);
2890  SetDParam(2, indspec->name);
2891  } else if (closeit) {
2892  SetDParam(0, STR_FORMAT_INDUSTRY_NAME);
2893  SetDParam(1, i->town->index);
2894  SetDParam(2, indspec->name);
2895  } else {
2896  SetDParam(0, i->index);
2897  }
2898  /* and report the news to the user */
2899  if (closeit) {
2900  AddTileNewsItem(str, nt, i->location.tile + TileDiffXY(1, 1));
2901  } else {
2902  AddIndustryNewsItem(str, nt, i->index);
2903  }
2904  }
2905 }
2906 
2915 {
2917 
2918  /* Bits 16-31 of industry_construction_counter contain the number of industries to change/create today,
2919  * the lower 16 bit are a fractional part that might accumulate over several days until it
2920  * is sufficient for an industry. */
2921  uint16 change_loop = _economy.industry_daily_change_counter >> 16;
2922 
2923  /* Reset the active part of the counter, just keeping the "fractional part" */
2924  _economy.industry_daily_change_counter &= 0xFFFF;
2925 
2926  if (change_loop == 0) {
2927  return; // Nothing to do? get out
2928  }
2929 
2930  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2931 
2932  /* perform the required industry changes for the day */
2933 
2934  uint perc = 3; // Between 3% and 9% chance of creating a new industry.
2936  perc = std::min(9u, perc + (_industry_builder.wanted_inds >> 16) - GetCurrentTotalNumberOfIndustries());
2937  }
2938  for (uint16 j = 0; j < change_loop; j++) {
2939  if (Chance16(perc, 100)) {
2941  } else {
2943  if (i != nullptr) {
2944  ChangeIndustryProduction(i, false);
2946  }
2947  }
2948  }
2949 
2950  cur_company.Restore();
2951 
2952  /* production-change */
2953  InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, IDIWD_PRODUCTION_CHANGE);
2954 }
2955 
2956 void IndustryMonthlyLoop()
2957 {
2958  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2959 
2961 
2962  for (Industry *i : Industry::Iterate()) {
2964  if (i->prod_level == PRODLEVEL_CLOSURE) {
2965  delete i;
2966  } else {
2967  ChangeIndustryProduction(i, true);
2969  }
2970  }
2971 
2972  cur_company.Restore();
2973 
2974  /* production-change */
2975  InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, IDIWD_PRODUCTION_CHANGE);
2976 }
2977 
2978 
2979 void InitializeIndustries()
2980 {
2982  _industry_sound_tile = 0;
2983 
2985 }
2986 
2989 {
2990  int count = 0;
2991  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2992  if (Industry::GetIndustryTypeCount(it) > 0) continue; // Types of existing industries can be skipped.
2993 
2994  bool force_at_least_one;
2995  uint32 chance = GetScaledIndustryGenerationProbability(it, &force_at_least_one);
2996  if (chance == 0 || !force_at_least_one) continue; // Types that are not available can be skipped.
2997 
2998  const IndustrySpec *is = GetIndustrySpec(it);
2999  SetDParam(0, is->name);
3000  ShowErrorMessage(STR_ERROR_NO_SUITABLE_PLACES_FOR_INDUSTRIES, STR_ERROR_NO_SUITABLE_PLACES_FOR_INDUSTRIES_EXPLANATION, WL_WARNING);
3001 
3002  count++;
3003  if (count >= 3) break; // Don't swamp the user with errors.
3004  }
3005 }
3006 
3012 {
3013  return (this->life_type & (INDUSTRYLIFE_EXTRACTIVE | INDUSTRYLIFE_ORGANIC)) != 0;
3014 }
3015 
3021 {
3022  /* Lumber mills are neither raw nor processing */
3023  return (this->life_type & INDUSTRYLIFE_PROCESSING) != 0 &&
3024  (this->behaviour & INDUSTRYBEH_CUT_TREES) == 0;
3025 }
3026 
3032 {
3033  /* Building raw industries like secondary uses different price base */
3034  return (_price[(_settings_game.construction.raw_industry_construction == 1 && this->IsRawIndustry()) ?
3035  PR_BUILD_INDUSTRY_RAW : PR_BUILD_INDUSTRY] * this->cost_multiplier) >> 8;
3036 }
3037 
3045 {
3046  return (_price[PR_CLEAR_INDUSTRY] * this->removal_cost_multiplier) >> 8;
3047 }
3048 
3054 {
3055  return _settings_game.economy.type == ET_ORIGINAL ||
3058 }
3059 
3060 IndustrySpec::~IndustrySpec()
3061 {
3062  if (HasBit(this->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3063  free(this->random_sounds);
3064  }
3065 }
3066 
3067 static CommandCost TerraformTile_Industry(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3068 {
3069  if (AutoslopeEnabled()) {
3070  /* We imitate here TTDP's behaviour:
3071  * - Both new and old slope must not be steep.
3072  * - TileMaxZ must not be changed.
3073  * - Allow autoslope by default.
3074  * - Disallow autoslope if callback succeeds and returns non-zero.
3075  */
3076  Slope tileh_old = GetTileSlope(tile);
3077  /* TileMaxZ must not be changed. Slopes must not be steep. */
3078  if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3079  const IndustryGfx gfx = GetIndustryGfx(tile);
3080  const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
3081 
3082  /* Call callback 3C 'disable autosloping for industry tiles'. */
3083  if (HasBit(itspec->callback_mask, CBM_INDT_AUTOSLOPE)) {
3084  /* If the callback fails, allow autoslope. */
3085  uint16 res = GetIndustryTileCallback(CBID_INDTILE_AUTOSLOPE, 0, 0, gfx, Industry::GetByTile(tile), tile);
3086  if (res == CALLBACK_FAILED || !ConvertBooleanCallback(itspec->grf_prop.grffile, CBID_INDTILE_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3087  } else {
3088  /* allow autoslope */
3089  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3090  }
3091  }
3092  }
3093  return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
3094 }
3095 
3096 extern const TileTypeProcs _tile_type_industry_procs = {
3097  DrawTile_Industry, // draw_tile_proc
3098  GetSlopePixelZ_Industry, // get_slope_z_proc
3099  ClearTile_Industry, // clear_tile_proc
3100  AddAcceptedCargo_Industry, // add_accepted_cargo_proc
3101  GetTileDesc_Industry, // get_tile_desc_proc
3102  GetTileTrackStatus_Industry, // get_tile_track_status_proc
3103  ClickTile_Industry, // click_tile_proc
3104  AnimateTile_Industry, // animate_tile_proc
3105  TileLoop_Industry, // tile_loop_proc
3106  ChangeTileOwner_Industry, // change_tile_owner_proc
3107  nullptr, // add_produced_cargo_proc
3108  nullptr, // vehicle_enter_tile_proc
3109  GetFoundation_Industry, // get_foundation_proc
3110  TerraformTile_Industry, // terraform_tile_proc
3111 };
3112 
3113 bool IndustryCompare::operator() (const IndustryListEntry &lhs, const IndustryListEntry &rhs) const
3114 {
3115  /* Compare by distance first and use index as a tiebreaker. */
3116  return std::tie(lhs.distance, lhs.industry->index) < std::tie(rhs.distance, rhs.industry->index);
3117 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
game.hpp
INDUSTRYBEH_ONLY_INTOWN
@ INDUSTRYBEH_ONLY_INTOWN
can only be built in towns (arctic/tropic banks, water tower)
Definition: industrytype.h:67
CheckScaledDistanceFromEdge
static bool CheckScaledDistanceFromEdge(TileIndex tile, uint maxdist)
Check if a tile is within a distance from map edges, scaled by map dimensions independently.
Definition: industry_cmd.cpp:1251
TileInfo::z
int z
Height.
Definition: tile_cmd.h:47
MP_CLEAR
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:48
MP_HOUSE
@ MP_HOUSE
A house by a town.
Definition: tile_type.h:51
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:730
IsTileFlat
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:100
DIAGDIR_SE
@ DIAGDIR_SE
Southeast.
Definition: direction_type.h:80
SLOPE_SE
@ SLOPE_SE
south and east corner are raised
Definition: slope_type.h:57
TileDesc::grf
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:61
PRODLEVEL_MINIMUM
@ PRODLEVEL_MINIMUM
below this level, the industry is set to be closing
Definition: industry.h:31
CLEAR_SNOW
@ CLEAR_SNOW
0-3
Definition: clear_map.h:24
TROPICZONE_DESERT
@ TROPICZONE_DESERT
Tile is desert.
Definition: tile_type.h:78
CheckIfIndustryTileSlopes
static CommandCost CheckIfIndustryTileSlopes(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)
Check slope requirements for industry tiles.
Definition: industry_cmd.cpp:1497
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3254
Industry::owner
Owner owner
owner of the industry. Which SHOULD always be (imho) OWNER_NONE
Definition: industry.h:84
sound_func.h
AXIS_Y
@ AXIS_Y
The y axis.
Definition: direction_type.h:127
ID_FUND_ONLY
@ ID_FUND_ONLY
The game does not build industries.
Definition: settings_type.h:54
CBM_IND_PRODUCTION_CARGO_ARRIVAL
@ CBM_IND_PRODUCTION_CARGO_ARRIVAL
call production callback when cargo arrives at the industry
Definition: newgrf_callbacks.h:353
NUM_INDUSTRYTYPES
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like INV...
Definition: industry_type.h:26
SND_30_TOFFEE_QUARRY
@ SND_30_TOFFEE_QUARRY
48 == 0x30 Industry animation: toffee quarry: drill
Definition: sound_type.h:87
Industry::this_month_production
uint16 this_month_production[INDUSTRY_NUM_OUTPUTS]
stats of this month's production per cargo
Definition: industry.h:76
Cheats::magic_bulldozer
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:27
OUFB_UNLOAD
@ OUFB_UNLOAD
Force unloading all cargo onto the platform, possibly not getting paid.
Definition: order_type.h:54
Chance16
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
Definition: random_func.hpp:131
CheckNewIndustryProc
CommandCost CheckNewIndustryProc(TileIndex tile)
Industrytype check function signature.
Definition: industry_cmd.cpp:1370
SND_0B_MINE
@ SND_0B_MINE
9 == 0x09 Industry animation: coal/copper/gold mine: headgear
Definition: sound_type.h:48
Pool::PoolItem<&_industry_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
ReportNewsProductionChangeIndustry
static void ReportNewsProductionChangeIndustry(Industry *ind, CargoID type, int percent)
Report news that industry production has changed significantly.
Definition: industry_cmd.cpp:2675
INDUSTRYBEH_CARGOTYPES_UNLIMITED
@ INDUSTRYBEH_CARGOTYPES_UNLIMITED
Allow produced/accepted cargoes callbacks to supply more than 2 and 3 types.
Definition: industrytype.h:82
IndustrySpec::UsesOriginalEconomy
bool UsesOriginalEconomy() const
Determines whether this industrytype uses standard/newgrf production changes.
Definition: industry_cmd.cpp:3053
CargoSpec::label
CargoLabel label
Unique label of the cargo type.
Definition: cargotype.h:59
SND_2B_TOY_FACTORY_2
@ SND_2B_TOY_FACTORY_2
43 == 0x2B Industry animation: toy factory (2): stamp product
Definition: sound_type.h:82
DeleteIndustryNews
void DeleteIndustryNews(IndustryID iid)
Remove news regarding given industry.
Definition: news_gui.cpp:955
GameSettings::station
StationSettings station
settings related to station management
Definition: settings_type.h:598
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3156
AdvertiseIndustryOpening
static void AdvertiseIndustryOpening(const Industry *ind)
Advertise about a new industry opening.
Definition: industry_cmd.cpp:1699
water.h
GetTileMaxZ
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:141
SetIndustryGfx
static void SetIndustryGfx(TileIndex t, IndustryGfx gfx)
Set the industry graphics ID for the given industry tile.
Definition: industry_map.h:149
ID_VERY_LOW
@ ID_VERY_LOW
Very few industries at game start.
Definition: settings_type.h:56
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
EV_BUBBLE
@ EV_BUBBLE
Bubble of bubble generator (industry).
Definition: effectvehicle_func.h:26
INDCTL_NONE
@ INDCTL_NONE
No flags in effect.
Definition: industry.h:49
GetIndustryGfx
static IndustryGfx GetIndustryGfx(TileIndex t)
Get the industry graphics ID for the given industry tile.
Definition: industry_map.h:137
HasTileWaterClass
static bool HasTileWaterClass(TileIndex t)
Checks whether the tile has an waterclass associated.
Definition: water_map.h:106
command_func.h
INDUSTRYBEH_AFTER_1960
@ INDUSTRYBEH_AFTER_1960
can only be built after 1960 (oil rigs)
Definition: industrytype.h:72
TileInfo::x
uint x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:43
EV_CHIMNEY_SMOKE
@ EV_CHIMNEY_SMOKE
Smoke of power plant (industry).
Definition: effectvehicle_func.h:17
Pool::PoolItem<&_industry_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:348
IAT_TILELOOP
@ IAT_TILELOOP
Trigger in the periodic tile loop.
Definition: newgrf_animation_type.h:39
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
INDCTL_NO_CLOSURE
@ INDCTL_NO_CLOSURE
Industry can not close regardless of production level or time since last delivery.
Definition: industry.h:57
INDUSTRYBEH_NO_PAX_PROD_CLAMP
@ INDUSTRYBEH_NO_PAX_PROD_CLAMP
Do not clamp production of passengers. (smooth economy only)
Definition: industrytype.h:83
IndustryBuildData::builddata
IndustryTypeBuildData builddata[NUM_INDUSTRYTYPES]
Industry build data for every industry type.
Definition: industry.h:229
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3594
CheckIndustryCloseDownProtection
static bool CheckIndustryCloseDownProtection(IndustryType type)
Protects an industry from closure if the appropriate flags and conditions are met INDUSTRYBEH_CANCLOS...
Definition: industry_cmd.cpp:2570
WL_WARNING
@ WL_WARNING
Other information.
Definition: error.h:23
TileInfo
Tile information, used while rendering the tile.
Definition: tile_cmd.h:42
Industry::this_month_transported
uint16 this_month_transported[INDUSTRY_NUM_OUTPUTS]
stats of this month's transport per cargo
Definition: industry.h:77
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:328
Backup
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
ID_CUSTOM
@ ID_CUSTOM
Custom number of industries.
Definition: settings_type.h:61
SpriteLayoutPaletteTransform
static PaletteID SpriteLayoutPaletteTransform(SpriteID image, PaletteID pal, PaletteID default_pal)
Applies PALETTE_MODIFIER_TRANSPARENT and PALETTE_MODIFIER_COLOUR to a palette entry of a sprite layou...
Definition: sprite.h:149
terraform_cmd.h
GetTreeGrowth
static uint GetTreeGrowth(TileIndex t)
Returns the tree growth status.
Definition: tree_map.h:181
company_base.h
IsTransparencySet
static bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:48
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
SpecializedVehicle::Next
T * Next() const
Get next vehicle in the chain.
Definition: vehicle_base.h:1098
EXPENSES_OTHER
@ EXPENSES_OTHER
Other expenses.
Definition: economy_type.h:170
OUFB_TRANSFER
@ OUFB_TRANSFER
Transfer all cargo onto the platform.
Definition: order_type.h:55
TileDesc::owner
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:53
IndustrySpec::GetRemovalCost
Money GetRemovalCost() const
Get the cost for removing this industry Take note that the cost will always be zero for non-grf indus...
Definition: industry_cmd.cpp:3044
CheckIndustries
void CheckIndustries()
Verify whether the generated industries are complete, and warn the user if not.
Definition: industry_cmd.cpp:2988
SND_2A_TOY_FACTORY_3
@ SND_2A_TOY_FACTORY_3
42 == 0x2A Industry animation: toy factory (3): eject product
Definition: sound_type.h:81
CBID_INDUSTRY_PRODUCTION_CHANGE
@ CBID_INDUSTRY_PRODUCTION_CHANGE
Called on production changes, so it can be adjusted.
Definition: newgrf_callbacks.h:111
SLOPE_NW
@ SLOPE_NW
north and west corner are raised
Definition: slope_type.h:55
Station
Station data structure.
Definition: station_base.h:454
Randomizer::Next
uint32 Next()
Generate the next pseudo random number.
Definition: random_func.cpp:31
Economy::industry_daily_change_counter
uint32 industry_daily_change_counter
Bits 31-16 are number of industry to be performed, 15-0 are fractional collected daily.
Definition: economy_type.h:34
PRODLEVEL_CLOSURE
@ PRODLEVEL_CLOSURE
signal set to actually close the industry
Definition: industry.h:30
IndustrySpec::GetConstructionCost
Money GetConstructionCost() const
Get the cost for constructing this industry.
Definition: industry_cmd.cpp:3031
CargoPacket::InvalidateAllFrom
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
Definition: cargopacket.cpp:127
CBID_INDTILE_CARGO_ACCEPTANCE
@ CBID_INDTILE_CARGO_ACCEPTANCE
Called to query the cargo acceptance of the industry tile.
Definition: newgrf_callbacks.h:117
ChopLumberMillTrees
static void ChopLumberMillTrees(Industry *i)
Perform a circular search around the Lumber Mill in order to find trees to cut.
Definition: industry_cmd.cpp:1117
IndustryAction::SetText
@ SetText
Set additional text.
Industry::last_month_transported
uint16 last_month_transported[INDUSTRY_NUM_OUTPUTS]
total units transported per cargo in the last full month
Definition: industry.h:80
SetIndustryConstructionStage
static void SetIndustryConstructionStage(TileIndex tile, byte value)
Sets the industry construction stage of the specified tile.
Definition: industry_map.h:112
DiagDirToAxis
static Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition: direction_func.h:214
IAT_INDUSTRY_TICK
@ IAT_INDUSTRY_TICK
Trigger every tick.
Definition: newgrf_animation_type.h:40
IndustryTileSpec::anim_state
bool anim_state
When true, the tile has to be drawn using the animation state instead of the construction state.
Definition: industrytype.h:166
GetIndustryType
IndustryType GetIndustryType(TileIndex tile)
Retrieve the type for this industry.
Definition: industry_cmd.cpp:106
SND_0C_POWER_STATION
@ SND_0C_POWER_STATION
10 == 0x0A Industry animation: power station: spark
Definition: sound_type.h:49
CBM_INDT_SHAPE_CHECK
@ CBM_INDT_SHAPE_CHECK
decides slope suitability
Definition: newgrf_callbacks.h:377
_industry_builder
IndustryBuildData _industry_builder
In-game manager of industries.
Definition: industry_cmd.cpp:67
WC_INDUSTRY_VIEW
@ WC_INDUSTRY_VIEW
Industry view; Window numbers:
Definition: window_type.h:356
IndustrySpec::removal_cost_multiplier
uint32 removal_cost_multiplier
Base removal cost multiplier.
Definition: industrytype.h:110
IsIndustryCompleted
static bool IsIndustryCompleted(TileIndex t)
Is this industry tile fully built?
Definition: industry_map.h:75
TREE_GROUND_SHORE
@ TREE_GROUND_SHORE
shore
Definition: tree_map.h:56
Pool::PoolItem<&_industry_pool >::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
NT_INDUSTRY_COMPANY
@ NT_INDUSTRY_COMPANY
Production changes of industry serviced by local company.
Definition: news_type.h:30
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
IACT_RANDOMCREATION
@ IACT_RANDOMCREATION
during creation of random ingame industry
Definition: newgrf_industries.h:84
CargoArray
Class for storing amounts of cargo.
Definition: cargo_type.h:82
Industry::was_cargo_delivered
byte was_cargo_delivered
flag that indicate this has been the closest industry chosen for cargo delivery by a station....
Definition: industry.h:87
TROPICZONE_RAINFOREST
@ TROPICZONE_RAINFOREST
Rainforest tile.
Definition: tile_type.h:79
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
ClampU
static uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:148
CmdIndustryCtrl
CommandCost CmdIndustryCtrl(DoCommandFlag flags, IndustryID ind_id, IndustryAction action, IndustryControlFlags ctlflags, Owner company_id, const std::string &text)
Change industry properties.
Definition: industry_cmd.cpp:2110
Industry::produced_cargo_waiting
uint16 produced_cargo_waiting[INDUSTRY_NUM_OUTPUTS]
amount of cargo produced per cargo
Definition: industry.h:71
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:586
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
GetTileZ
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition: tile_map.cpp:121
INVALID_TILE
static constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:108
Industry::last_month_production
uint16 last_month_production[INDUSTRY_NUM_OUTPUTS]
total units produced per cargo in the last full month
Definition: industry.h:79
CheckNewIndustry_Farm
static CommandCost CheckNewIndustry_Farm(TileIndex tile)
Check the conditions of CHECK_FARM (Industry should be below snow-line in arctic).
Definition: industry_cmd.cpp:1303
IsClearGround
static bool IsClearGround(TileIndex t, ClearGround ct)
Set the type of clear tile.
Definition: clear_map.h:71
INDUSTRYBEH_DONT_INCR_PROD
@ INDUSTRYBEH_DONT_INCR_PROD
do not increase production (oil wells) in the temperate climate
Definition: industrytype.h:70
TileIndex
The index/ID of a Tile.
Definition: tile_type.h:85
DrawIndustryAnimationStruct::x
int x
coordinate x of the first image offset
Definition: industry_land.h:19
SetDParamX
static void SetDParamX(uint64 *s, uint n, uint64 v)
Set a string parameter v at index n in a given array s.
Definition: strings_func.h:186
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
IndustryAction::SetExclusiveConsumer
@ SetExclusiveConsumer
Set exclusive consumer.
CBM_INDT_ACCEPT_CARGO
@ CBM_INDT_ACCEPT_CARGO
decides accepted types
Definition: newgrf_callbacks.h:376
build_industry.h
Industry::RecomputeProductionMultipliers
void RecomputeProductionMultipliers()
Recompute production_rate for current prod_level.
Definition: industry_cmd.cpp:2409
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:218
Industry::construction_type
uint8 construction_type
Way the industry was constructed (.
Definition: industry.h:96
TileInfo::y
uint y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:44
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:53
GetRegister
static uint32 GetRegister(uint i)
Gets the value of a so-called newgrf "register".
Definition: newgrf_spritegroup.h:29
Town::xy
TileIndex xy
town center tile
Definition: town.h:51
GWP_INDUSTRY
@ GWP_INDUSTRY
Generate industries.
Definition: genworld.h:75
DC_NO_WATER
@ DC_NO_WATER
don't allow building on water
Definition: command_type.h:360
CBID_INDTILE_DRAW_FOUNDATIONS
@ CBID_INDTILE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for industry tile.
Definition: newgrf_callbacks.h:135
MP_INDUSTRY
@ MP_INDUSTRY
Part of an industry.
Definition: tile_type.h:56
newgrf_debug.h
town.h
TileY
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:215
CBM_IND_PRODUCTION_256_TICKS
@ CBM_IND_PRODUCTION_256_TICKS
call production callback every 256 ticks
Definition: newgrf_callbacks.h:354
IsTileForestIndustry
bool IsTileForestIndustry(TileIndex tile)
Check whether the tile is a forest.
Definition: industry_cmd.cpp:964
OrthogonalTileArea::Add
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition: tilearea.cpp:43
SLOPE_S
@ SLOPE_S
the south corner of the tile is raised
Definition: slope_type.h:51
effectvehicle_base.h
DIAGDIR_NW
@ DIAGDIR_NW
Northwest.
Definition: direction_type.h:82
RandomRange
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:81
Chance16I
static bool Chance16I(const uint a, const uint b, const uint32 r)
Checks if a given randomize-number is below a given probability.
Definition: random_func.hpp:112
Industry::construction_date
Date construction_date
Date of the construction of the industry.
Definition: industry.h:95
NT_INDUSTRY_NOBODY
@ NT_INDUSTRY_NOBODY
Other industry production changes.
Definition: news_type.h:32
Industry::exclusive_consumer
Owner exclusive_consumer
Which company has exclusive rights to take cargo (INVALID_OWNER = anyone)
Definition: industry.h:100
SND_2C_TOY_FACTORY_1
@ SND_2C_TOY_FACTORY_1
44 == 0x2C Industry animation: toy factory (1): conveyor belt
Definition: sound_type.h:83
clear_map.h
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
PRODLEVEL_DEFAULT
@ PRODLEVEL_DEFAULT
default level set when the industry is created
Definition: industry.h:32
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:224
Industry
Defines the internal data of a functional industry.
Definition: industry.h:66
INDUSTRY_TRIGGER_INDUSTRY_TICK
@ INDUSTRY_TRIGGER_INDUSTRY_TICK
The industry has been triggered via its tick.
Definition: newgrf_industrytiles.h:72
TILE_MASK
#define TILE_MASK(x)
'Wraps' the given tile to it is within the map.
Definition: map_func.h:26
ConvertBooleanCallback
bool ConvertBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:550
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:288
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
Industry::ctlflags
IndustryControlFlags ctlflags
flags overriding standard behaviours
Definition: industry.h:88
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:357
CBID_INDUSTRY_OUTPUT_CARGO_TYPES
@ CBID_INDUSTRY_OUTPUT_CARGO_TYPES
Customize the output cargo types of a newly build industry.
Definition: newgrf_callbacks.h:221
MemCpyT
static void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:23
GFX_WATERTILE_SPECIALCHECK
@ GFX_WATERTILE_SPECIALCHECK
not really a tile, but rather a very special check
Definition: industry_map.h:54
CBID_INDTILE_ACCEPT_CARGO
@ CBID_INDTILE_ACCEPT_CARGO
Called to determine which cargoes an industry should accept.
Definition: newgrf_callbacks.h:120
TriggerIndustry
void TriggerIndustry(Industry *ind, IndustryTileTrigger trigger)
Trigger a random trigger for all industry tiles.
Definition: newgrf_industrytiles.cpp:372
WATER_CLASS_INVALID
@ WATER_CLASS_INVALID
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition: water_map.h:51
IsLocalCompany
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:43
TileDesc
Tile description for the 'land area information' tool.
Definition: tile_cmd.h:51
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:196
CBID_INDUSTRY_SPECIAL_EFFECT
@ CBID_INDUSTRY_SPECIAL_EFFECT
Called to determine industry special effects.
Definition: newgrf_callbacks.h:174
CBM_INDT_AUTOSLOPE
@ CBM_INDT_AUTOSLOPE
decides allowance of autosloping
Definition: newgrf_callbacks.h:379
SLOPE_E
@ SLOPE_E
the east corner of the tile is raised
Definition: slope_type.h:52
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:355
SetFence
static void SetFence(TileIndex t, DiagDirection side, uint h)
Sets the type of fence (and whether there is one) for the given border.
Definition: clear_map.h:240
genworld.h
NT_INDUSTRY_CLOSE
@ NT_INDUSTRY_CLOSE
Closing of industries.
Definition: news_type.h:28
Foundation
Foundation
Enumeration for Foundations.
Definition: slope_type.h:93
EnsureNoVehicleOnGround
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition: vehicle.cpp:539
INDUSTRYBEH_NOBUILT_MAPCREATION
@ INDUSTRYBEH_NOBUILT_MAPCREATION
Do not force one instance of this type to appear on map generation.
Definition: industrytype.h:80
IncreaseGeneratingWorldProgress
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Definition: genworld_gui.cpp:1572
Industry::neutral_station
Station * neutral_station
Associated neutral station.
Definition: industry.h:69
FlatteningFoundation
static Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:369
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:151
ResetIndustryConstructionStage
static void ResetIndustryConstructionStage(TileIndex tile)
Reset the construction stage counter of the industry, as well as the completion bit.
Definition: industry_map.h:187
object_base.h
TileX
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:205
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:377
IndustryDailyLoop
void IndustryDailyLoop()
Daily handler for the industry changes Taking the original map size of 256*256, the number of random ...
Definition: industry_cmd.cpp:2914
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:587
_coal_plant_sparks
static const DrawIndustryCoordinates _coal_plant_sparks[]
Movement of the sparks , only used for Power Station.
Definition: industry_land.h:948
effectvehicle_func.h
IndustryTileLayout
std::vector< IndustryTileLayoutTile > IndustryTileLayout
A complete tile layout for an industry is a list of tiles.
Definition: industrytype.h:102
ai.hpp
SND_2D_SUGAR_MINE_1
@ SND_2D_SUGAR_MINE_1
45 == 0x2D Industry animation: sugar mine (1): shaking sieve
Definition: sound_type.h:84
IndustryAction
IndustryAction
Definition: industry.h:36
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:45
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
GetIndustryProbabilityCallback
uint32 GetIndustryProbabilityCallback(IndustryType type, IndustryAvailabilityCallType creation_type, uint32 default_prob)
Check with callback CBID_INDUSTRY_PROBABILITY whether the industry can be built.
Definition: newgrf_industries.cpp:569
MapSizeX
static uint MapSizeX()
Get the size of the map along the X.
Definition: map_func.h:72
IsTileOnWater
static bool IsTileOnWater(TileIndex t)
Tests if the tile was built on water.
Definition: water_map.h:141
INDUSTRYBEH_PLANT_ON_BUILT
@ INDUSTRYBEH_PLANT_ON_BUILT
Fields are planted around when built (all farms)
Definition: industrytype.h:69
ClearDockingTilesCheckingNeighbours
void ClearDockingTilesCheckingNeighbours(TileIndex tile)
Clear docking tile status from tiles around a removed dock, if the tile has no neighbours which would...
Definition: station_cmd.cpp:2583
GetStringWithArgs
char * GetStringWithArgs(char *buffr, StringID string, StringParameters *args, const char *last, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition: strings.cpp:222
SoundSettings::ambient
bool ambient
Play ambient, industry and town sounds.
Definition: settings_type.h:220
IndustrySpec::closure_text
StringID closure_text
Message appearing when the industry closes.
Definition: industrytype.h:129
Pool::MAX_SIZE
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:85
Industry::GetRandom
static Industry * GetRandom()
Return a random valid industry.
Definition: industry_cmd.cpp:220
IndustryAction::SetExclusiveSupplier
@ SetExclusiveSupplier
Set exclusive supplier.
IndustryTileSpec::special_flags
IndustryTileSpecialFlags special_flags
Bitmask of extra flags used by the tile.
Definition: industrytype.h:170
INDUSTRY_COMPLETED
static const int INDUSTRY_COMPLETED
final stage of industry construction.
Definition: industry_type.h:36
ToTileIndexDiff
static TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition: map_func.h:230
Pool::PoolItem<&_industry_pool >::GetPoolSize
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:358
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
Vehicle::Orders
IterateWrapper Orders() const
Returns an iterable ensemble of orders of a vehicle.
Definition: vehicle_base.h:1052
Economy::industry_daily_increment
uint32 industry_daily_increment
The value which will increment industry_daily_change_counter. Computed value. NOSAVE.
Definition: economy_type.h:35
GetSlopeMaxZ
static int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height)
Definition: slope_func.h:160
DIAGDIR_SW
@ DIAGDIR_SW
Southwest.
Definition: direction_type.h:81
UpdateIndustryStatistics
static void UpdateIndustryStatistics(Industry *i)
Monthly update of industry statistics.
Definition: industry_cmd.cpp:2385
CheckIfIndustryTilesAreFree
static CommandCost CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileLayout &layout, IndustryType type)
Are the tiles of the industry free?
Definition: industry_cmd.cpp:1435
TownCache::population
uint32 population
Current population of people.
Definition: town.h:42
Industry::PostDestructor
static void PostDestructor(size_t index)
Invalidating some stuff after removing item from the pool.
Definition: industry_cmd.cpp:210
landscape_cmd.h
CHECK_END
@ CHECK_END
End marker of the industry check procedures.
Definition: industrytype.h:49
GetAnimationFrame
static byte GetAnimationFrame(TileIndex t)
Get the current animation frame.
Definition: tile_map.h:250
SND_29_SUGAR_MINE_2
@ SND_29_SUGAR_MINE_2
41 == 0x29 Industry animation: sugar mine (2): shaking sieve
Definition: sound_type.h:80
IndustryTileSpec::acceptance
int8 acceptance[INDUSTRY_NUM_INPUTS]
Level of acceptance per cargo type (signed, may be negative!)
Definition: industrytype.h:158
CheckIfCanLevelIndustryPlatform
static bool CheckIfCanLevelIndustryPlatform(TileIndex tile, DoCommandFlag flags, const IndustryTileLayout &layout, int type)
This function tries to flatten out the land below an industry, without damaging the surroundings too ...
Definition: industry_cmd.cpp:1583
StationSettings::serve_neutral_industries
bool serve_neutral_industries
company stations can serve industries with attached neutral stations
Definition: settings_type.h:559
IndustryTypeBuildData::wait_count
uint16 wait_count
Number of turns to wait before trying to build again.
Definition: industry.h:218
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
IndustrySpec::IsRawIndustry
bool IsRawIndustry() const
Is an industry with the spec a raw industry?
Definition: industry_cmd.cpp:3011
MapSize
static uint MapSize()
Get the size of the map.
Definition: map_func.h:92
WhoCanServiceIndustry
static int WhoCanServiceIndustry(Industry *ind)
Compute who can service the industry.
Definition: industry_cmd.cpp:2622
SetIndustryConstructionCounter
static void SetIndustryConstructionCounter(TileIndex tile, byte value)
Sets this industry tile's construction counter value.
Definition: industry_map.h:174
PlaceIndustry
static Industry * PlaceIndustry(IndustryType type, IndustryAvailabilityCallType creation_type, bool try_hard)
Try to place the industry in the game.
Definition: industry_cmd.cpp:2259
EXPENSES_CONSTRUCTION
@ EXPENSES_CONSTRUCTION
Construction costs.
Definition: economy_type.h:158
Industry::stations_near
StationList stations_near
NOSAVE: List of nearby stations.
Definition: industry.h:91
TileAddWrap
TileIndex TileAddWrap(TileIndex tile, int addx, int addy)
This function checks if we add addx/addy to tile, if we do wrap around the edges.
Definition: map.cpp:114
GetIndustryAnimationLoop
static byte GetIndustryAnimationLoop(TileIndex tile)
Get the animation loop number.
Definition: industry_map.h:199
IsSteepSlope
static bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
CommandCost
Common return value for all commands.
Definition: command_type.h:24
Industry::random
uint16 random
Random value used for randomisation of all kinds of things.
Definition: industry.h:103
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:656
Industry::location
TileArea location
Location of the industry.
Definition: industry.h:67
IndustryAction::SetControlFlags
@ SetControlFlags
Set IndustryControlFlags.
IndustryTypeBuildData::Reset
void Reset()
Reset the entry.
Definition: industry_cmd.cpp:2297
WaterClass
WaterClass
classes of water (for WATER_TILE_CLEAR water tile type).
Definition: water_map.h:47
SetClearCounter
static void SetClearCounter(TileIndex t, uint c)
Sets the counter used to advance to the next clear density/field type.
Definition: clear_map.h:144
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
CheckNewIndustry_OilRefinery
static CommandCost CheckNewIndustry_OilRefinery(TileIndex tile)
Check the conditions of CHECK_REFINERY (Industry should be positioned near edge of the map).
Definition: industry_cmd.cpp:1272
NEW_INDUSTRYOFFSET
static const IndustryType NEW_INDUSTRYOFFSET
original number of industry types
Definition: industry_type.h:25
TileHeight
static uint TileHeight(TileIndex tile)
Returns the height of a tile.
Definition: tile_map.h:29
ClientSettings::sound
SoundSettings sound
sound effect settings
Definition: settings_type.h:607
CircularTileSearch
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Definition: map.cpp:258
Industry::cached_name
std::string cached_name
NOSAVE: Cache of the resolved name of the industry.
Definition: industry.h:92
SLOPE_NE
@ SLOPE_NE
north and east corner are raised
Definition: slope_type.h:58
Industry::GetByTile
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:144
IndustrySpec::conflicting
IndustryType conflicting[3]
Industries this industry cannot be close to.
Definition: industrytype.h:112
Industry::exclusive_supplier
Owner exclusive_supplier
Which company has exclusive rights to deliver cargo (INVALID_OWNER = anyone)
Definition: industry.h:99
INDUSTRYBEH_PLANT_FIELDS
@ INDUSTRYBEH_PLANT_FIELDS
periodically plants fields around itself (temp and arctic farms)
Definition: industrytype.h:63
GetScaledIndustryGenerationProbability
static uint32 GetScaledIndustryGenerationProbability(IndustryType it, bool *force_at_least_one)
Compute the appearance probability for an industry during map creation.
Definition: industry_cmd.cpp:2180
Industry::type
IndustryType type
type of industry.
Definition: industry.h:83
SND_36_LUMBER_MILL_3
@ SND_36_LUMBER_MILL_3
54 == 0x36 Industry animation: lumber mill (3): crashing tree
Definition: sound_type.h:93
NT_INDUSTRY_OTHER
@ NT_INDUSTRY_OTHER
Production changes of industry serviced by competitor(s)
Definition: news_type.h:31
IndustryTypeBuildData::max_wait
uint16 max_wait
Starting number of turns to wait (copied to wait_count).
Definition: industry.h:217
TileIndexDiff
int32 TileIndexDiff
An offset value between two tiles.
Definition: map_func.h:154
NewsType
NewsType
Type of news.
Definition: news_type.h:21
autoslope.h
CBM_IND_PRODUCTION_CHANGE
@ CBM_IND_PRODUCTION_CHANGE
controls random production change
Definition: newgrf_callbacks.h:356
SND_2E_BUBBLE_GENERATOR
@ SND_2E_BUBBLE_GENERATOR
46 == 0x2E Industry animation: bubble generator (1): generate bubble
Definition: sound_type.h:85
WC_INDUSTRY_DIRECTORY
@ WC_INDUSTRY_DIRECTORY
Industry directory; Window numbers:
Definition: window_type.h:259
TransportType
TransportType
Available types of transport.
Definition: transport_type.h:19
_cheats
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
IndustryBuildData
Data for managing the number and type of industries in the game.
Definition: industry.h:228
CBID_INDUSTRY_MONTHLYPROD_CHANGE
@ CBID_INDUSTRY_MONTHLYPROD_CHANGE
Called monthly on production changes, so it can be adjusted more frequently.
Definition: newgrf_callbacks.h:153
IndustrySpec::layouts
std::vector< IndustryTileLayout > layouts
List of possible tile layouts for the industry.
Definition: industrytype.h:108
IndustrySpec::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 accepted cargoes.
Definition: industrytype.h:121
INVALID_OWNER
@ INVALID_OWNER
An invalid owner.
Definition: company_type.h:29
OrthogonalTileArea::w
uint16 w
The width of the area.
Definition: tilearea_type.h:20
INDUSTRYTILE_NOANIM
static const IndustryGfx INDUSTRYTILE_NOANIM
flag to mark industry tiles as having no animation
Definition: industry_type.h:31
CBM_INDT_DRAW_FOUNDATIONS
@ CBM_INDT_DRAW_FOUNDATIONS
decides if default foundations need to be drawn
Definition: newgrf_callbacks.h:378
INVALID_INDUSTRYTILE
static const IndustryGfx INVALID_INDUSTRYTILE
one above amount is considered invalid
Definition: industry_type.h:34
Industry::produced_cargo
CargoID produced_cargo[INDUSTRY_NUM_OUTPUTS]
16 production cargo slots
Definition: industry.h:70
IndustrySpec::number_of_sounds
uint8 number_of_sounds
Number of sounds available in the sounds array.
Definition: industrytype.h:135
CBM_IND_LOCATION
@ CBM_IND_LOCATION
check industry construction on given area
Definition: newgrf_callbacks.h:355
CBM_IND_INPUT_CARGO_TYPES
@ CBM_IND_INPUT_CARGO_TYPES
customize the cargoes the industry requires
Definition: newgrf_callbacks.h:364
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:160
Industry::incoming_cargo_waiting
uint16 incoming_cargo_waiting[INDUSTRY_NUM_INPUTS]
incoming cargo waiting to be processed
Definition: industry.h:72
EV_COPPER_MINE_SMOKE
@ EV_COPPER_MINE_SMOKE
Smoke at copper mine.
Definition: effectvehicle_func.h:28
INDUSTRYBEH_BUILT_ONWATER
@ INDUSTRYBEH_BUILT_ONWATER
is built on water (oil rig)
Definition: industrytype.h:65
IndustrySpec::production_up_text
StringID production_up_text
Message appearing when the industry's production is increasing.
Definition: industrytype.h:130
IsInvisibilitySet
static bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:59
ST_INDUSTRY
@ ST_INDUSTRY
Source/destination is an industry.
Definition: cargo_type.h:148
CBID_INDUSTRY_INPUT_CARGO_TYPES
@ CBID_INDUSTRY_INPUT_CARGO_TYPES
Customize the input cargo types of a newly build industry.
Definition: newgrf_callbacks.h:218
OrthogonalTileArea
Represents the covered area of e.g.
Definition: tilearea_type.h:18
PerformIndustryTileSlopeCheck
CommandCost PerformIndustryTileSlopeCheck(TileIndex ind_base_tile, TileIndex ind_tile, const IndustryTileSpec *its, IndustryType type, IndustryGfx gfx, size_t layout_index, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type)
Check the slope of a tile of a new industry.
Definition: newgrf_industrytiles.cpp:230
ConstructionSettings::raw_industry_construction
uint8 raw_industry_construction
type of (raw) industry construction (none, "normal", prospecting)
Definition: settings_type.h:352
CLEAR_DESERT
@ CLEAR_DESERT
1,3
Definition: clear_map.h:25
IndustrySpec::minimal_cargo
byte minimal_cargo
minimum amount of cargo transported to the stations.
Definition: industrytype.h:120
Vehicle::IsFrontEngine
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:913
Industry::DecIndustryTypeCount
static void DecIndustryTypeCount(IndustryType type)
Decrement the count of industries for this type.
Definition: industry.h:168
DrawIndustryAnimationStruct::image_2
byte image_2
image offset 2
Definition: industry_land.h:21
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
ANIM_STATUS_NO_ANIMATION
static const uint8 ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition: newgrf_animation_type.h:15
GetTropicZone
static TropicZone GetTropicZone(TileIndex tile)
Get the tropic zone.
Definition: tile_map.h:238
DeleteSubsidyWith
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
Definition: subsidy.cpp:149
SetupFarmFieldFence
static void SetupFarmFieldFence(TileIndex tile, int size, byte type, DiagDirection side)
Build farm field fence.
Definition: industry_cmd.cpp:1008
Game::NewEvent
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:146
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:596
IndustryBuildData::MonthlyLoop
void MonthlyLoop()
Monthly update of industry build data.
Definition: industry_cmd.cpp:2317
WL_INFO
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:22
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
PRODLEVEL_MAXIMUM
@ PRODLEVEL_MAXIMUM
the industry is running at full speed
Definition: industry.h:33
AI::BroadcastNewEvent
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:261
industry.h
industry_land.h
safeguards.h
GetNumberOfIndustries
static uint GetNumberOfIndustries()
Get wanted number of industries on the map.
Definition: industry_cmd.cpp:2230
HighestSnowLine
byte HighestSnowLine()
Get the highest possible snow line height, either variable or static.
Definition: landscape.cpp:670
SetIndustryIndexOfField
static void SetIndustryIndexOfField(TileIndex t, IndustryID i)
Set the industry (farm) that made the field.
Definition: clear_map.h:207
DistanceFromEdgeDir
uint DistanceFromEdgeDir(TileIndex tile, DiagDirection dir)
Gets the distance to the edge of the map in given direction.
Definition: map.cpp:234
IsValidTile
static bool IsValidTile(TileIndex tile)
Checks if a tile is valid.
Definition: tile_map.h:161
IndustryTileSpec::slopes_refused
Slope slopes_refused
slope pattern on which this tile cannot be built
Definition: industrytype.h:159
Industry::ResetIndustryCounts
static void ResetIndustryCounts()
Resets industry counts.
Definition: industry.h:186
GetTileSlope
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:59
DifficultySettings::industry_density
byte industry_density
The industry density.
Definition: settings_type.h:80
RandomTile
#define RandomTile()
Get a valid random tile.
Definition: map_func.h:435
DC_NO_TEST_TOWN_RATING
@ DC_NO_TEST_TOWN_RATING
town rating does not disallow you from building
Definition: command_type.h:362
INDUSTRYBEH_BEFORE_1950
@ INDUSTRYBEH_BEFORE_1950
can only be built before 1950 (oil wells)
Definition: industrytype.h:71
CheckNewIndustry_BubbleGen
static CommandCost CheckNewIndustry_BubbleGen(TileIndex tile)
Check the conditions of CHECK_BUBBLEGEN (Industry should be in low land).
Definition: industry_cmd.cpp:1357
AutoslopeEnabled
static bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:44
IndustryBuildData::SetupTargetCount
void SetupTargetCount()
Decide how many industries of each type are needed.
Definition: industry_cmd.cpp:2452
CBM_IND_SPECIAL_EFFECT
@ CBM_IND_SPECIAL_EFFECT
control special effects
Definition: newgrf_callbacks.h:361
IsSuitableForFarmField
static bool IsSuitableForFarmField(TileIndex tile, bool allow_fields)
Check whether the tile can be replaced by a farm field.
Definition: industry_cmd.cpp:992
NUM_INDUSTRYTILES
static const IndustryGfx NUM_INDUSTRYTILES
total number of industry tiles, new and old
Definition: industry_type.h:33
IndustryAvailabilityCallType
IndustryAvailabilityCallType
From where has callback CBID_INDUSTRY_PROBABILITY been called.
Definition: newgrf_industries.h:82
FOUNDATION_NONE
@ FOUNDATION_NONE
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:94
error.h
SetIndustryAnimationLoop
static void SetIndustryAnimationLoop(TileIndex tile, byte count)
Set the animation loop number.
Definition: industry_map.h:211
GameCreationSettings::oil_refinery_limit
byte oil_refinery_limit
distance oil refineries allowed from map edge
Definition: settings_type.h:318
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:77
IndustryBuildData::TryBuildNewIndustry
void TryBuildNewIndustry()
Try to create a random industry, during gameplay.
Definition: industry_cmd.cpp:2497
INDUSTRYLIFE_BLACK_HOLE
@ INDUSTRYLIFE_BLACK_HOLE
Like power plants and banks.
Definition: industrytype.h:29
MapSizeY
static uint MapSizeY()
Get the size of the map along the Y.
Definition: map_func.h:82
IndustrySpec::appear_creation
byte appear_creation[NUM_LANDSCAPE]
Probability of appearance during map creation.
Definition: industrytype.h:134
IACT_PROSPECTCREATION
@ IACT_PROSPECTCREATION
from the Fund/build using prospecting
Definition: newgrf_industries.h:86
IndustryTileSpec::anim_production
byte anim_production
Animation frame to start when goods are produced.
Definition: industrytype.h:160
DrawIndustryAnimationStruct::image_3
byte image_3
image offset 3
Definition: industry_land.h:22
date_func.h
TileDesc::dparam
uint64 dparam[2]
Parameters of the str string.
Definition: tile_cmd.h:62
stdafx.h
GetIndustryIndexOfField
static IndustryID GetIndustryIndexOfField(TileIndex t)
Get the industry (farm) that made the field.
Definition: clear_map.h:195
landscape.h
TileTypeProcs
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:145
SoundFx
SoundFx
Sound effects from baseset.
Definition: sound_type.h:37
SND_38_LUMBER_MILL_1
@ SND_38_LUMBER_MILL_1
56 == 0x38 Industry animation: lumber mill (1): chainsaw
Definition: sound_type.h:95
ReleaseDisastersTargetingIndustry
void ReleaseDisastersTargetingIndustry(IndustryID i)
Marks all disasters targeting this industry in such a way they won't call Industry::Get(v->dest_tile)...
Definition: disaster_vehicle.cpp:939
IndustrySpec
Defines the data structure for constructing industry.
Definition: industrytype.h:107
GetIndustryConstructionStage
static byte GetIndustryConstructionStage(TileIndex tile)
Returns the industry construction stage of the specified tile.
Definition: industry_map.h:100
IndustryTileSpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:172
Cheat::value
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
CreateNewIndustry
static Industry * CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAvailabilityCallType creation_type)
Create a new industry of random layout.
Definition: industry_cmd.cpp:2161
viewport_func.h
Industry::text
std::string text
General text with additional information.
Definition: industry.h:101
TileLoop_Water
void TileLoop_Water(TileIndex tile)
Let a water tile floods its diagonal adjoining tiles called from tunnelbridge_cmd,...
Definition: water_cmd.cpp:1216
IACT_USERCREATION
@ IACT_USERCREATION
from the Fund/build window
Definition: newgrf_industries.h:85
IsTileType
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
DrawIndustryAnimationStruct
This is used to gather some data about animation drawing in the industry code Image_1-2-3 are in fact...
Definition: industry_land.h:18
TO_INDUSTRIES
@ TO_INDUSTRIES
industries
Definition: transparency.h:26
animated_tile_func.h
ICT_MAP_GENERATION
@ ICT_MAP_GENERATION
during random map creation
Definition: industrytype.h:56
AddSortableSpriteToDraw
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition: viewport.cpp:667
SLOPE_W
@ SLOPE_W
the west corner of the tile is raised
Definition: slope_type.h:50
GroundSpritePaletteTransform
static PaletteID GroundSpritePaletteTransform(SpriteID image, PaletteID pal, PaletteID default_pal)
Applies PALETTE_MODIFIER_COLOUR to a palette entry of a ground sprite.
Definition: sprite.h:168
OrthogonalTileArea::h
uint16 h
The height of the area.
Definition: tilearea_type.h:21
Industry::last_month_pct_transported
byte last_month_pct_transported[INDUSTRY_NUM_OUTPUTS]
percentage transported per cargo in the last full month
Definition: industry.h:78
_industry_draw_tile_data
static const DrawBuildingsTileStruct _industry_draw_tile_data[NEW_INDUSTRYTILEOFFSET *4]
Structure for industry tiles drawing.
Definition: industry_land.h:51
DistanceMax
uint DistanceMax(TileIndex t0, TileIndex t1)
Gets the biggest distance component (x or y) between the two given tiles.
Definition: map.cpp:189
MP_TREES
@ MP_TREES
Tile got trees.
Definition: tile_type.h:52
DrawFoundation
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:474
NT_INDUSTRY_OPEN
@ NT_INDUSTRY_OPEN
Opening of industries.
Definition: news_type.h:27
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:61
CreateEffectVehicle
EffectVehicle * CreateEffectVehicle(int x, int y, int z, EffectVehicleType type)
Create an effect vehicle at a particular location.
Definition: effectvehicle.cpp:594
IndustryTemporarilyRefusesCargo
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
Definition: newgrf_industries.cpp:680
Industry::town
Town * town
Nearest town.
Definition: industry.h:68
INDUSTRYLIFE_PROCESSING
@ INDUSTRYLIFE_PROCESSING
Like factories.
Definition: industrytype.h:32
CBM_IND_MONTHLYPROD_CHANGE
@ CBM_IND_MONTHLYPROD_CHANGE
controls monthly random production change
Definition: newgrf_callbacks.h:357
CBID_INDUSTRY_PROD_CHANGE_BUILD
@ CBID_INDUSTRY_PROD_CHANGE_BUILD
Called when industry is built to set initial production level.
Definition: newgrf_callbacks.h:278
CheckNewIndustry_Lumbermill
static CommandCost CheckNewIndustry_Lumbermill(TileIndex tile)
Check the conditions of CHECK_LUMBERMILL (Industry should be in the rain forest).
Definition: industry_cmd.cpp:1344
IndustryTileSpec::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
Cargo accepted by this tile.
Definition: industrytype.h:157
string_func.h
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:140
IndustryBuildData::Reset
void Reset()
Completely reset the industry build data.
Definition: industry_cmd.cpp:2307
EconomyIsInRecession
static bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:47
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:408
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
Station::industries_near
IndustryList industries_near
Cached list of industries near the station that can accept cargo,.
Definition: station_base.h:486
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
vehicle_func.h
IndustryBuildData::wanted_inds
uint32 wanted_inds
Number of wanted industries (bits 31-16), and a fraction (bits 15-0).
Definition: industry.h:230
IndustrySpec::IsProcessingIndustry
bool IsProcessingIndustry() const
Is an industry with the spec a processing industry?
Definition: industry_cmd.cpp:3020
station_base.h
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
DrawIndustryAnimationStruct::image_1
byte image_1
image offset 1
Definition: industry_land.h:20
Pool::PoolItem<&_industry_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:386
CHECK_OIL_RIG
@ CHECK_OIL_RIG
Industries at sea should be positioned near edge of the map.
Definition: industrytype.h:48
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:321
strings_func.h
CLEAN_RANDOMSOUNDS
@ CLEAN_RANDOMSOUNDS
Free the dynamically allocated sounds table.
Definition: industrytype.h:24
Industry::selected_layout
byte selected_layout
Which tile layout was used when creating the industry.
Definition: industry.h:98
Pool
Base class for all pools.
Definition: pool_type.hpp:81
Industry::GetIndustryTypeCount
static uint16 GetIndustryTypeCount(IndustryType type)
Get the count of industries for this type.
Definition: industry.h:179
GetWaterClass
static WaterClass GetWaterClass(TileIndex t)
Get the water class at a tile.
Definition: water_map.h:117
ScaleByMapSize
static uint ScaleByMapSize(uint n)
Scales the given value by the map size, where the given value is for a 256 by 256 map.
Definition: map_func.h:122
newgrf_industrytiles.h
EconomySettings::type
EconomyType type
economy type (original/smooth/frozen)
Definition: settings_type.h:512
MapMaxY
static uint MapMaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition: map_func.h:111
StringParameters
Definition: strings_func.h:60
PopulateStationsNearby
static void PopulateStationsNearby(Industry *ind)
Populate an industry's list of nearby stations, and if it accepts any cargo, also add the industry to...
Definition: industry_cmd.cpp:1719
MP_VOID
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition: tile_type.h:55
subsidy_func.h
CheckNewIndustry_Plantation
static CommandCost CheckNewIndustry_Plantation(TileIndex tile)
Check the conditions of CHECK_PLANTATION (Industry should NOT be in the desert).
Definition: industry_cmd.cpp:1318
INDTILE_TRIGGER_TILE_LOOP
@ INDTILE_TRIGGER_TILE_LOOP
The tile of the industry has been triggered during the tileloop.
Definition: newgrf_industrytiles.h:71
FindTownForIndustry
static CommandCost FindTownForIndustry(TileIndex tile, int type, Town **t)
Find a town for the industry, while checking for multiple industries in the same town.
Definition: industry_cmd.cpp:1395
Pool::PoolItem<&_industry_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:367
DeleteAnimatedTile
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
Definition: animated_tile.cpp:26
Backup::Restore
void Restore()
Restore the variable.
Definition: backup_type.hpp:112
INDUSTRYBEH_ONLY_NEARTOWN
@ INDUSTRYBEH_ONLY_NEARTOWN
is always built near towns (toy shop)
Definition: industrytype.h:68
SLOPE_N
@ SLOPE_N
the north corner of the tile is raised
Definition: slope_type.h:53
Randomizer
Structure to encapsulate the pseudo random number generators.
Definition: random_func.hpp:21
IndustryTileSpec::animation
AnimationInfo animation
Information about the animation (is it looping, how many loops etc)
Definition: industrytype.h:169
GameCreationSettings::land_generator
byte land_generator
the landscape generator
Definition: settings_type.h:317
IsWaterTile
static bool IsWaterTile(TileIndex t)
Is it a water tile with plain water?
Definition: water_map.h:195
Industry::founder
Owner founder
Founder of the industry.
Definition: industry.h:94
CheckIfFarEnoughFromConflictingIndustry
static CommandCost CheckIfFarEnoughFromConflictingIndustry(TileIndex tile, int type)
Check that the new industry is far enough from conflicting industries.
Definition: industry_cmd.cpp:1656
ICT_SCENARIO_EDITOR
@ ICT_SCENARIO_EDITOR
while editing a scenario
Definition: industrytype.h:57
SetGeneratingWorldProgress
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
Definition: genworld_gui.cpp:1558
CreateNewIndustryHelper
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)
Helper function for Build/Fund an industry.
Definition: industry_cmd.cpp:1949
GetIndustryTileSpec
const IndustryTileSpec * GetIndustryTileSpec(IndustryGfx gfx)
Accessor for array _industry_tile_specs.
Definition: industry_cmd.cpp:137
Industry::IncIndustryTypeCount
static void IncIndustryTypeCount(IndustryType type)
Increment the count of industries for this type.
Definition: industry.h:157
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
endof
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:394
CBM_INDT_CARGO_ACCEPTANCE
@ CBM_INDT_CARGO_ACCEPTANCE
decides amount of cargo acceptance
Definition: newgrf_callbacks.h:375
GetIndustryGamePlayProbability
static uint16 GetIndustryGamePlayProbability(IndustryType it, byte *min_number)
Compute the probability for constructing a new industry during game play.
Definition: industry_cmd.cpp:2206
INDUSTRYLIFE_ORGANIC
@ INDUSTRYLIFE_ORGANIC
Like forests.
Definition: industrytype.h:31
SLOPE_SW
@ SLOPE_SW
south and west corner are raised
Definition: slope_type.h:56
GetIndustryIndex
static IndustryID GetIndustryIndex(TileIndex t)
Get the industry ID of the given tile.
Definition: industry_map.h:63
DrawBuildingsTileStruct
This structure is the same for both Industries and Houses.
Definition: sprite.h:67
cheat_type.h
CheckNewIndustry_OilRig
static CommandCost CheckNewIndustry_OilRig(TileIndex tile)
Check the conditions of CHECK_OIL_RIG (Industries at sea should be positioned near edge of the map).
Definition: industry_cmd.cpp:1288
Pool::PoolItem<&_industry_pool >::CleaningPool
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:316
tree_map.h
industry_cmd.h
MarkTileDirtyByTile
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:1998
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
GenerateIndustries
void GenerateIndustries()
This function will create random industries during game creation.
Definition: industry_cmd.cpp:2334
FOUNDATION_LEVELED
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition: slope_type.h:95
IndustrySpec::production_down_text
StringID production_down_text
Message appearing when the industry's production is decreasing.
Definition: industrytype.h:131
TileDiffXY
static TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:179
Industry::last_cargo_accepted_at
Date last_cargo_accepted_at[INDUSTRY_NUM_INPUTS]
Last day each cargo type was accepted by this industry.
Definition: industry.h:97
LG_TERRAGENESIS
@ LG_TERRAGENESIS
TerraGenesis Perlin landscape generator.
Definition: genworld.h:21
IndustrySpec::cleanup_flag
uint8 cleanup_flag
flags indicating which data should be freed upon cleaning up
Definition: industrytype.h:139
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
IndustrySpec::appear_ingame
byte appear_ingame[NUM_LANDSCAPE]
Probability of appearance in game.
Definition: industrytype.h:133
IndustrySpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:141
Town::cache
TownCache cache
Container for all cacheable data.
Definition: town.h:53
OverrideManagerBase::ResetOverride
void ResetOverride()
Resets the override, which is used while initializing game.
Definition: newgrf_commons.cpp:88
IACT_MAPGENERATION
@ IACT_MAPGENERATION
during random map generation
Definition: newgrf_industries.h:83
GameCreationSettings::custom_industry_number
uint16 custom_industry_number
manually entered number of industries
Definition: settings_type.h:331
SearchLumberMillTrees
static bool SearchLumberMillTrees(TileIndex tile, void *user_data)
Search callback function for ChopLumberMillTrees.
Definition: industry_cmd.cpp:1094
GetCargoTranslation
CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:79
IndustrySpec::prospecting_chance
uint32 prospecting_chance
Chance prospecting succeeds.
Definition: industrytype.h:111
ForAllStationsAroundTiles
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
Definition: station_base.h:574
Pool::PoolItem<&_industry_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:307
IndustryTileLayoutTile
Definition of one tile in an industry tile layout.
Definition: industrytype.h:96
ChangeIndustryProduction
static void ChangeIndustryProduction(Industry *i, bool monthly)
Change industry production or do closure.
Definition: industry_cmd.cpp:2703
Industry::last_prod_year
Year last_prod_year
last year of production
Definition: industry.h:86
IndustryTypeBuildData::min_number
byte min_number
Smallest number of industries that should exist (either 0 or 1).
Definition: industry.h:215
TriggerIndustryTile
void TriggerIndustryTile(TileIndex tile, IndustryTileTrigger trigger)
Trigger a random trigger for a single industry tile.
Definition: newgrf_industrytiles.cpp:359
MAX_UVALUE
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:479
CBID_INDTILE_AUTOSLOPE
@ CBID_INDTILE_AUTOSLOPE
Called to determine if industry can alter the ground below industry tile.
Definition: newgrf_callbacks.h:177
IndustryTypeBuildData
Data for managing the number of industries of a single industry type.
Definition: industry.h:213
OWNER_DEITY
@ OWNER_DEITY
The object is owned by a superuser / goal script.
Definition: company_type.h:27
TileDesc::str
StringID str
Description of the tile.
Definition: tile_cmd.h:52
DC_AUTO
@ DC_AUTO
don't allow building on structures
Definition: command_type.h:358
GetTileMaxPixelZ
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:304
ScaleByMapSize1D
static uint ScaleByMapSize1D(uint n)
Scales the given value by the maps circumference, where the given value is for a 256 by 256 map.
Definition: map_func.h:136
EffectVehicle
A special vehicle is one of the following:
Definition: effectvehicle_base.h:24
DC_NO_MODIFY_TOWN_RATING
@ DC_NO_MODIFY_TOWN_RATING
do not change town rating
Definition: command_type.h:367
IndustryListEntry
Definition: station_base.h:440
CreateEffectVehicleAbove
EffectVehicle * CreateEffectVehicleAbove(int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular location.
Definition: effectvehicle.cpp:622
Backup::GetOriginalValue
const T & GetOriginalValue() const
Returns the backupped value.
Definition: backup_type.hpp:72
CheckNewIndustry_Forest
static CommandCost CheckNewIndustry_Forest(TileIndex tile)
Check the conditions of CHECK_FOREST (Industry should be build above snow-line in arctic climate).
Definition: industry_cmd.cpp:1234
IndustrySpec::callback_mask
uint16 callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:138
IndustrySpec::random_sounds
const uint8 * random_sounds
array of random sounds.
Definition: industrytype.h:136
MapMaxX
static uint MapMaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition: map_func.h:102
CanCargoServiceIndustry
static void CanCargoServiceIndustry(CargoID cargo, Industry *ind, bool *c_accepts, bool *c_produces)
Can given cargo type be accepted or produced by the industry?
Definition: industry_cmd.cpp:2588
EconomySettings::multiple_industry_per_town
bool multiple_industry_per_town
allow many industries of the same type per town
Definition: settings_type.h:522
CmdBuildIndustry
CommandCost CmdBuildIndustry(DoCommandFlag flags, TileIndex tile, IndustryType it, uint32 first_layout, bool fund, uint32 seed)
Build/Fund an industry.
Definition: industry_cmd.cpp:2013
IndustrySpec::life_type
IndustryLifeType life_type
This is also known as Industry production flag, in newgrf specs.
Definition: industrytype.h:123
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:224
CheckIfCallBackAllowsCreation
CommandCost CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, size_t layout, uint32 seed, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type)
Check that the industry callback allows creation of the industry.
Definition: newgrf_industries.cpp:538
abs
static T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:21
TILE_ADDXY
#define TILE_ADDXY(tile, x, y)
Adds a given offset to a tile.
Definition: map_func.h:258
GetTreeGround
static TreeGround GetTreeGround(TileIndex t)
Returns the groundtype for tree tiles.
Definition: tree_map.h:88
TileArea
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:102
IndustryTileSpec::callback_mask
uint8 callback_mask
Bitmask of industry tile callbacks that have to be called.
Definition: industrytype.h:168
_check_new_industry_procs
static CheckNewIndustryProc *const _check_new_industry_procs[CHECK_END]
Check functions for different types of industry.
Definition: industry_cmd.cpp:1373
CommandHelper
Definition: command_func.h:94
window_func.h
Industry::random_colour
byte random_colour
randomized colour of the industry, for display purpose
Definition: industry.h:85
IndustrySpec::behaviour
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
Definition: industrytype.h:125
AnimationInfo::status
uint8 status
Status; 0: no looping, 1: looping, 0xFF: no animation.
Definition: newgrf_animation_type.h:20
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
Town
Town data structure.
Definition: town.h:50
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
SetIndustryCompleted
static void SetIndustryCompleted(TileIndex tile)
Set if the industry that owns the tile as under construction or not.
Definition: industry_map.h:88
INDUSTRYBEH_CANCLOSE_LASTINSTANCE
@ INDUSTRYBEH_CANCLOSE_LASTINSTANCE
Allow closing down the last instance of this type.
Definition: industrytype.h:81
AddChildSpriteScreen
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
Add a child sprite to a parent sprite.
Definition: viewport.cpp:823
CBID_INDUSTRY_DECIDE_COLOUR
@ CBID_INDUSTRY_DECIDE_COLOUR
Called to determine the colour of an industry.
Definition: newgrf_callbacks.h:215
OverflowSafeInt< int64 >
TransportIndustryGoods
static bool TransportIndustryGoods(TileIndex tile)
Move produced cargo from industry to nearby stations.
Definition: industry_cmd.cpp:531
IsOilRig
static bool IsOilRig(TileIndex t)
Is tile t part of an oilrig?
Definition: station_map.h:274
DoCreateNewIndustry
static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type, const IndustryTileLayout &layout, size_t layout_index, Town *t, Owner founder, uint16 initial_random_bits)
Put an industry on the map.
Definition: industry_cmd.cpp:1748
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
INDUSTRY_CUT_TREE_TICKS
static const int INDUSTRY_CUT_TREE_TICKS
cycle duration for lumber mill's extra action
Definition: date_type.h:39
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1191
MemSetT
static void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
Chance16R
static bool Chance16R(const uint a, const uint b, uint32 &r)
Flips a coin with a given probability and saves the randomize-number in a variable.
Definition: random_func.hpp:155
MakeField
static void MakeField(TileIndex t, uint field_type, IndustryID industry)
Make a (farm) field tile.
Definition: clear_map.h:280
INDCTL_NO_PRODUCTION_DECREASE
@ INDCTL_NO_PRODUCTION_DECREASE
When industry production change is evaluated, rolls to decrease are ignored.
Definition: industry.h:51
CBM_IND_DECIDE_COLOUR
@ CBM_IND_DECIDE_COLOUR
give a custom colour to newly build industries
Definition: newgrf_callbacks.h:363
GetIndustryConstructionCounter
static byte GetIndustryConstructionCounter(TileIndex tile)
Returns this industry tile's construction counter value.
Definition: industry_map.h:162
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:320
OrthogonalTileArea::Expand
OrthogonalTileArea & Expand(int rad)
Expand a tile area by rad tiles in each direction, keeping within map bounds.
Definition: tilearea.cpp:123
GetCurrentTotalNumberOfIndustries
static uint GetCurrentTotalNumberOfIndustries()
Get total number of industries existing in the game.
Definition: industry_cmd.cpp:2288
CheckNewIndustry_NULL
static CommandCost CheckNewIndustry_NULL(TileIndex tile)
Check the conditions of CHECK_NOTHING (Always succeeds).
Definition: industry_cmd.cpp:1224
INDUSTRYBEH_TOWN1200_MORE
@ INDUSTRYBEH_TOWN1200_MORE
can only be built in towns larger than 1200 inhabitants (temperate bank)
Definition: industrytype.h:66
ID_END
@ ID_END
Number of industry density settings.
Definition: settings_type.h:63
IndustryTypeBuildData::probability
uint32 probability
Relative probability of building this industry.
Definition: industry.h:214
IndustrySpec::check_proc
byte check_proc
Index to a procedure to check for conflicting circumstances.
Definition: industrytype.h:113
NEW_INDUSTRYTILEOFFSET
static const IndustryGfx NEW_INDUSTRYTILEOFFSET
original number of tiles
Definition: industry_type.h:32
CeilDiv
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:280
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
TileInfo::tile
TileIndex tile
Tile index.
Definition: tile_cmd.h:46
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:588
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition: newgrf_commons.cpp:516
GetIndustrySpec
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
Definition: industry_cmd.cpp:123
DC_NONE
@ DC_NONE
no flag is set
Definition: command_type.h:356
CBM_IND_PROD_CHANGE_BUILD
@ CBM_IND_PROD_CHANGE_BUILD
initialise production level on construction
Definition: newgrf_callbacks.h:366
IAT_CONSTRUCTION_STATE_CHANGE
@ IAT_CONSTRUCTION_STATE_CHANGE
Trigger whenever the construction state changes.
Definition: newgrf_animation_type.h:38
GetTileType
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
Definition: tile_map.h:96
CheckNewIndustry_Water
static CommandCost CheckNewIndustry_Water(TileIndex tile)
Check the conditions of CHECK_WATER (Industry should be in the desert).
Definition: industry_cmd.cpp:1331
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
Industry::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 input cargo slots
Definition: industry.h:75
IndustrySpec::name
StringID name
Displayed name of the industry.
Definition: industrytype.h:127
Pool::PoolItem<&_industry_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:326
IndustryBehaviour
IndustryBehaviour
Various industry behaviours mostly to represent original TTD specialities.
Definition: industrytype.h:61
IndustrySpec::new_industry_text
StringID new_industry_text
Message appearing when the industry is built.
Definition: industrytype.h:128
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
INDCTL_MASK
@ INDCTL_MASK
Mask of all flags set.
Definition: industry.h:59
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:320
Industry::prod_level
byte prod_level
general production level
Definition: industry.h:74
Industry::counts
static uint16 counts[NUM_INDUSTRYTYPES]
Number of industries per type ingame.
Definition: industry.h:201
Randomizer::SetSeed
void SetSeed(uint32 seed)
(Re)set the state of the random number generator.
Definition: random_func.cpp:55
MakeIndustry
static void MakeIndustry(TileIndex t, IndustryID index, IndustryGfx gfx, uint8 random, WaterClass wc)
Make the given tile an industry tile.
Definition: industry_map.h:278
Industry::psa
PersistentStorage * psa
Persistent storage for NewGRF industries.
Definition: industry.h:105
INDCTL_NO_PRODUCTION_INCREASE
@ INDCTL_NO_PRODUCTION_INCREASE
When industry production change is evaluated, rolls to increase are ignored.
Definition: industry.h:53
IAT_INDUSTRY_DISTRIBUTES_CARGO
@ IAT_INDUSTRY_DISTRIBUTES_CARGO
Trigger when cargo is distributed.
Definition: newgrf_animation_type.h:42
SLOPE_FLAT
@ SLOPE_FLAT
a flat tile
Definition: slope_type.h:49
pool_func.hpp
IndustryControlFlags
IndustryControlFlags
Flags to control/override the behaviour of an industry.
Definition: industry.h:47
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
CheckIfIndustryIsAllowed
static CommandCost CheckIfIndustryIsAllowed(TileIndex tile, int type, const Town *t)
Is the industry allowed to be built at this place for the town?
Definition: industry_cmd.cpp:1539
CT_INVALID
@ CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:69
_tick_counter
uint64 _tick_counter
Ever incrementing tick counter for setting off various events.
Definition: date.cpp:30
MapGRFStringID
StringID MapGRFStringID(uint32 grfid, StringID str)
Used when setting an object's property to map to the GRF's strings while taking in consideration the ...
Definition: newgrf.cpp:557
SetAnimationFrame
static void SetAnimationFrame(TileIndex t, byte frame)
Set a new animation frame.
Definition: tile_map.h:262
INDUSTRYBEH_CUT_TREES
@ INDUSTRYBEH_CUT_TREES
cuts trees and produce first output cargo from them (lumber mill)
Definition: industrytype.h:64
DIAGDIR_NE
@ DIAGDIR_NE
Northeast, upper right on your monitor.
Definition: direction_type.h:79
ResetIndustries
void ResetIndustries()
This function initialize the spec arrays of both industry and industry tiles.
Definition: industry_cmd.cpp:75
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
IndustryTileSpec::anim_next
byte anim_next
Next frame in an animation.
Definition: industrytype.h:161
CLEAR_FIELDS
@ CLEAR_FIELDS
3
Definition: clear_map.h:23
IndustryTileSpec
Defines the data structure of each individual tile of an industry.
Definition: industrytype.h:156
Industry::production_rate
byte production_rate[INDUSTRY_NUM_OUTPUTS]
production rate for each cargo
Definition: industry.h:73
OWNER_WATER
@ OWNER_WATER
The tile/execution is done by "water".
Definition: company_type.h:26
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
IndustryTypeBuildData::target_count
uint16 target_count
Desired number of industries of this type.
Definition: industry.h:216
Order
Definition: order_base.h:36
IndustryTypeBuildData::GetIndustryTypeData
bool GetIndustryTypeData(IndustryType it)
Set the probability and min_number fields for the industry type it for a running game.
Definition: industry_cmd.cpp:2441
newgrf_cargo.h
IndustryProductionCallback
void IndustryProductionCallback(Industry *ind, int reason)
Get the industry production callback and apply it to the industry.
Definition: newgrf_industries.cpp:602
CHECK_REFINERY
@ CHECK_REFINERY
Industry should be positioned near edge of the map.
Definition: industrytype.h:42
EffectVehicle::animation_substate
byte animation_substate
Sub state to time the change of the graphics/behaviour.
Definition: effectvehicle_base.h:26
ComplementSlope
static Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition: slope_func.h:76
GetGRFConfig
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:771
CBM_IND_OUTPUT_CARGO_TYPES
@ CBM_IND_OUTPUT_CARGO_TYPES
customize the cargoes the industry produces
Definition: newgrf_callbacks.h:365
OWNER_TOWN
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
PlaceInitialIndustry
static void PlaceInitialIndustry(IndustryType type, bool try_hard)
Try to build a industry on the map.
Definition: industry_cmd.cpp:2274
DrawGroundSprite
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition: viewport.cpp:583
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
Delta
static T Delta(const T a, const T b)
Returns the (absolute) difference between two (scalar) variables.
Definition: math_func.hpp:196
Industry::counter
uint16 counter
used for animation and/or production (if available cargo)
Definition: industry.h:81
ConstructionSettings::industry_platform
uint8 industry_platform
the amount of flat land around an industry
Definition: settings_type.h:353
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:105
INDTILE_SPECIAL_ACCEPTS_ALL_CARGO
@ INDTILE_SPECIAL_ACCEPTS_ALL_CARGO
Tile always accepts all cargoes the associated industry accepts.
Definition: industrytype.h:91
GetTranslatedIndustryTileID
static IndustryGfx GetTranslatedIndustryTileID(IndustryGfx gfx)
Do industry gfx ID translation for NewGRFs.
Definition: industrytype.h:194
ICT_NORMAL_GAMEPLAY
@ ICT_NORMAL_GAMEPLAY
either by user or random creation process
Definition: industrytype.h:55
news_func.h
IsBridgeAbove
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
AddAnimatedTile
void AddAnimatedTile(TileIndex tile)
Add the given tile to the animated tile table (if it does not exist on that table yet).
Definition: animated_tile.cpp:41
GetIndustryCallback
uint16 GetIndustryCallback(CallbackID callback, uint32 param1, uint32 param2, Industry *industry, IndustryType type, TileIndex tile)
Perform an industry callback.
Definition: newgrf_industries.cpp:521
INDUSTRY_PRODUCE_TICKS
static const int INDUSTRY_PRODUCE_TICKS
cycle duration for industry production
Definition: date_type.h:37
Industry::TileBelongsToIndustry
bool TileBelongsToIndustry(TileIndex tile) const
Check if a given tile belongs to this industry.
Definition: industry.h:117
backup_type.hpp
SND_37_LUMBER_MILL_2
@ SND_37_LUMBER_MILL_2
55 == 0x37 Industry animation: lumber mill (2): falling tree
Definition: sound_type.h:94
INDUSTRYLIFE_EXTRACTIVE
@ INDUSTRYLIFE_EXTRACTIVE
Like mines.
Definition: industrytype.h:30