industry_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "clear_map.h"
00014 #include "industry.h"
00015 #include "station_base.h"
00016 #include "train.h"
00017 #include "viewport_func.h"
00018 #include "command_func.h"
00019 #include "town.h"
00020 #include "news_func.h"
00021 #include "cheat_type.h"
00022 #include "genworld.h"
00023 #include "tree_map.h"
00024 #include "newgrf_cargo.h"
00025 #include "newgrf_debug.h"
00026 #include "newgrf_industrytiles.h"
00027 #include "autoslope.h"
00028 #include "water.h"
00029 #include "strings_func.h"
00030 #include "window_func.h"
00031 #include "date_func.h"
00032 #include "vehicle_func.h"
00033 #include "sound_func.h"
00034 #include "animated_tile_func.h"
00035 #include "effectvehicle_func.h"
00036 #include "effectvehicle_base.h"
00037 #include "ai/ai.hpp"
00038 #include "core/pool_func.hpp"
00039 #include "subsidy_func.h"
00040 #include "core/backup_type.hpp"
00041 #include "object_base.h"
00042 
00043 #include "table/strings.h"
00044 #include "table/industry_land.h"
00045 #include "table/build_industry.h"
00046 
00047 IndustryPool _industry_pool("Industry");
00048 INSTANTIATE_POOL_METHODS(Industry)
00049 
00050 void ShowIndustryViewWindow(int industry);
00051 void BuildOilRig(TileIndex tile);
00052 
00053 static byte _industry_sound_ctr;
00054 static TileIndex _industry_sound_tile;
00055 
00056 uint16 Industry::counts[NUM_INDUSTRYTYPES];
00057 
00058 IndustrySpec _industry_specs[NUM_INDUSTRYTYPES];
00059 IndustryTileSpec _industry_tile_specs[NUM_INDUSTRYTILES];
00060 IndustryBuildData _industry_builder; 
00061 
00068 void ResetIndustries()
00069 {
00070   memset(&_industry_specs, 0, sizeof(_industry_specs));
00071   memcpy(&_industry_specs, &_origin_industry_specs, sizeof(_origin_industry_specs));
00072 
00073   /* once performed, enable only the current climate industries */
00074   for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
00075     _industry_specs[i].enabled = i < NEW_INDUSTRYOFFSET &&
00076         HasBit(_origin_industry_specs[i].climate_availability, _settings_game.game_creation.landscape);
00077   }
00078 
00079   memset(&_industry_tile_specs, 0, sizeof(_industry_tile_specs));
00080   memcpy(&_industry_tile_specs, &_origin_industry_tile_specs, sizeof(_origin_industry_tile_specs));
00081 
00082   /* Reset any overrides that have been set. */
00083   _industile_mngr.ResetOverride();
00084   _industry_mngr.ResetOverride();
00085 }
00086 
00095 IndustryType GetIndustryType(TileIndex tile)
00096 {
00097   assert(IsTileType(tile, MP_INDUSTRY));
00098 
00099   const Industry *ind = Industry::GetByTile(tile);
00100   assert(ind != NULL);
00101   return ind->type;
00102 }
00103 
00112 const IndustrySpec *GetIndustrySpec(IndustryType thistype)
00113 {
00114   assert(thistype < NUM_INDUSTRYTYPES);
00115   return &_industry_specs[thistype];
00116 }
00117 
00126 const IndustryTileSpec *GetIndustryTileSpec(IndustryGfx gfx)
00127 {
00128   assert(gfx < INVALID_INDUSTRYTILE);
00129   return &_industry_tile_specs[gfx];
00130 }
00131 
00132 Industry::~Industry()
00133 {
00134   if (CleaningPool()) return;
00135 
00136   /* Industry can also be destroyed when not fully initialized.
00137    * This means that we do not have to clear tiles either.
00138    * Also we must not decrement industry counts in that case. */
00139   if (this->location.w == 0) return;
00140 
00141   TILE_AREA_LOOP(tile_cur, this->location) {
00142     if (IsTileType(tile_cur, MP_INDUSTRY)) {
00143       if (GetIndustryIndex(tile_cur) == this->index) {
00144         DeleteNewGRFInspectWindow(GSF_INDUSTRYTILES, tile_cur);
00145 
00146         /* MakeWaterKeepingClass() can also handle 'land' */
00147         MakeWaterKeepingClass(tile_cur, OWNER_NONE);
00148       }
00149     } else if (IsTileType(tile_cur, MP_STATION) && IsOilRig(tile_cur)) {
00150       DeleteOilRig(tile_cur);
00151     }
00152   }
00153 
00154   if (GetIndustrySpec(this->type)->behaviour & INDUSTRYBEH_PLANT_FIELDS) {
00155     TileArea ta(this->location.tile - TileDiffXY(min(TileX(this->location.tile), 21), min(TileY(this->location.tile), 21)), 42, 42);
00156     ta.ClampToMap();
00157 
00158     /* Remove the farmland and convert it to regular tiles over time. */
00159     TILE_AREA_LOOP(tile_cur, ta) {
00160       if (IsTileType(tile_cur, MP_CLEAR) && IsClearGround(tile_cur, CLEAR_FIELDS) &&
00161           GetIndustryIndexOfField(tile_cur) == this->index) {
00162         SetIndustryIndexOfField(tile_cur, INVALID_INDUSTRY);
00163       }
00164     }
00165   }
00166 
00167   /* don't let any disaster vehicle target invalid industry */
00168   ReleaseDisastersTargetingIndustry(this->index);
00169 
00170   DecIndustryTypeCount(this->type);
00171 
00172   DeleteIndustryNews(this->index);
00173   DeleteWindowById(WC_INDUSTRY_VIEW, this->index);
00174   DeleteNewGRFInspectWindow(GSF_INDUSTRIES, this->index);
00175 
00176   DeleteSubsidyWith(ST_INDUSTRY, this->index);
00177   CargoPacket::InvalidateAllFrom(ST_INDUSTRY, this->index);
00178 }
00179 
00184 void Industry::PostDestructor(size_t index)
00185 {
00186   InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, 0);
00187   Station::RecomputeIndustriesNearForAll();
00188 }
00189 
00190 
00195 /* static */ Industry *Industry::GetRandom()
00196 {
00197   if (Industry::GetNumItems() == 0) return NULL;
00198   int num = RandomRange((uint16)Industry::GetNumItems());
00199   size_t index = MAX_UVALUE(size_t);
00200 
00201   while (num >= 0) {
00202     num--;
00203     index++;
00204 
00205     /* Make sure we have a valid industry */
00206     while (!Industry::IsValidID(index)) {
00207       index++;
00208       assert(index < Industry::GetPoolSize());
00209     }
00210   }
00211 
00212   return Industry::Get(index);
00213 }
00214 
00215 
00216 static void IndustryDrawSugarMine(const TileInfo *ti)
00217 {
00218   if (!IsIndustryCompleted(ti->tile)) return;
00219 
00220   const DrawIndustryAnimationStruct *d = &_draw_industry_spec1[GetAnimationFrame(ti->tile)];
00221 
00222   AddChildSpriteScreen(SPR_IT_SUGAR_MINE_SIEVE + d->image_1, PAL_NONE, d->x, 0);
00223 
00224   if (d->image_2 != 0) {
00225     AddChildSpriteScreen(SPR_IT_SUGAR_MINE_CLOUDS + d->image_2 - 1, PAL_NONE, 8, 41);
00226   }
00227 
00228   if (d->image_3 != 0) {
00229     AddChildSpriteScreen(SPR_IT_SUGAR_MINE_PILE + d->image_3 - 1, PAL_NONE,
00230       _drawtile_proc1[d->image_3 - 1].x, _drawtile_proc1[d->image_3 - 1].y);
00231   }
00232 }
00233 
00234 static void IndustryDrawToffeeQuarry(const TileInfo *ti)
00235 {
00236   uint8 x = 0;
00237 
00238   if (IsIndustryCompleted(ti->tile)) {
00239     x = _industry_anim_offs_toffee[GetAnimationFrame(ti->tile)];
00240     if (x == 0xFF) {
00241       x = 0;
00242     }
00243   }
00244 
00245   AddChildSpriteScreen(SPR_IT_TOFFEE_QUARRY_SHOVEL, PAL_NONE, 22 - x, 24 + x);
00246   AddChildSpriteScreen(SPR_IT_TOFFEE_QUARRY_TOFFEE, PAL_NONE, 6, 14);
00247 }
00248 
00249 static void IndustryDrawBubbleGenerator( const TileInfo *ti)
00250 {
00251   if (IsIndustryCompleted(ti->tile)) {
00252     AddChildSpriteScreen(SPR_IT_BUBBLE_GENERATOR_BUBBLE, PAL_NONE, 5, _industry_anim_offs_bubbles[GetAnimationFrame(ti->tile)]);
00253   } else {
00254     AddChildSpriteScreen(SPR_IT_BUBBLE_GENERATOR_SPRING, PAL_NONE, 3, 67);
00255   }
00256 }
00257 
00258 static void IndustryDrawToyFactory(const TileInfo *ti)
00259 {
00260   const DrawIndustryAnimationStruct *d = &_industry_anim_offs_toys[GetAnimationFrame(ti->tile)];
00261 
00262   if (d->image_1 != 0xFF) {
00263     AddChildSpriteScreen(SPR_IT_TOY_FACTORY_CLAY, PAL_NONE, d->x, 96 + d->image_1);
00264   }
00265 
00266   if (d->image_2 != 0xFF) {
00267     AddChildSpriteScreen(SPR_IT_TOY_FACTORY_ROBOT, PAL_NONE, 16 - d->image_2 * 2, 100 + d->image_2);
00268   }
00269 
00270   AddChildSpriteScreen(SPR_IT_TOY_FACTORY_STAMP, PAL_NONE, 7, d->image_3);
00271   AddChildSpriteScreen(SPR_IT_TOY_FACTORY_STAMP_HOLDER, PAL_NONE, 0, 42);
00272 }
00273 
00274 static void IndustryDrawCoalPlantSparks(const TileInfo *ti)
00275 {
00276   if (IsIndustryCompleted(ti->tile)) {
00277     uint8 image = GetAnimationFrame(ti->tile);
00278 
00279     if (image != 0 && image < 7) {
00280       AddChildSpriteScreen(image + SPR_IT_POWER_PLANT_TRANSFORMERS,
00281         PAL_NONE,
00282         _coal_plant_sparks[image - 1].x,
00283         _coal_plant_sparks[image - 1].y
00284       );
00285     }
00286   }
00287 }
00288 
00289 typedef void IndustryDrawTileProc(const TileInfo *ti);
00290 static IndustryDrawTileProc * const _industry_draw_tile_procs[5] = {
00291   IndustryDrawSugarMine,
00292   IndustryDrawToffeeQuarry,
00293   IndustryDrawBubbleGenerator,
00294   IndustryDrawToyFactory,
00295   IndustryDrawCoalPlantSparks,
00296 };
00297 
00298 static void DrawTile_Industry(TileInfo *ti)
00299 {
00300   IndustryGfx gfx = GetIndustryGfx(ti->tile);
00301   Industry *ind = Industry::GetByTile(ti->tile);
00302   const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
00303 
00304   /* Retrieve pointer to the draw industry tile struct */
00305   if (gfx >= NEW_INDUSTRYTILEOFFSET) {
00306     /* Draw the tile using the specialized method of newgrf industrytile.
00307      * DrawNewIndustry will return false if ever the resolver could not
00308      * find any sprite to display.  So in this case, we will jump on the
00309      * substitute gfx instead. */
00310     if (indts->grf_prop.spritegroup[0] != NULL && DrawNewIndustryTile(ti, ind, gfx, indts)) {
00311       return;
00312     } else {
00313       /* No sprite group (or no valid one) found, meaning no graphics associated.
00314        * Use the substitute one instead */
00315       if (indts->grf_prop.subst_id != INVALID_INDUSTRYTILE) {
00316         gfx = indts->grf_prop.subst_id;
00317         /* And point the industrytile spec accordingly */
00318         indts = GetIndustryTileSpec(gfx);
00319       }
00320     }
00321   }
00322 
00323   const DrawBuildingsTileStruct *dits = &_industry_draw_tile_data[gfx << 2 | (indts->anim_state ?
00324       GetAnimationFrame(ti->tile) & INDUSTRY_COMPLETED :
00325       GetIndustryConstructionStage(ti->tile))];
00326 
00327   SpriteID image = dits->ground.sprite;
00328 
00329   /* DrawFoundation() modifes ti->z and ti->tileh */
00330   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00331 
00332   /* If the ground sprite is the default flat water sprite, draw also canal/river borders.
00333    * Do not do this if the tile's WaterClass is 'land'. */
00334   if (image == SPR_FLAT_WATER_TILE && IsTileOnWater(ti->tile)) {
00335     DrawWaterClassGround(ti);
00336   } else {
00337     DrawGroundSprite(image, GroundSpritePaletteTransform(image, dits->ground.pal, GENERAL_SPRITE_COLOUR(ind->random_colour)));
00338   }
00339 
00340   /* If industries are transparent and invisible, do not draw the upper part */
00341   if (IsInvisibilitySet(TO_INDUSTRIES)) return;
00342 
00343   /* Add industry on top of the ground? */
00344   image = dits->building.sprite;
00345   if (image != 0) {
00346     AddSortableSpriteToDraw(image, SpriteLayoutPaletteTransform(image, dits->building.pal, GENERAL_SPRITE_COLOUR(ind->random_colour)),
00347       ti->x + dits->subtile_x,
00348       ti->y + dits->subtile_y,
00349       dits->width,
00350       dits->height,
00351       dits->dz,
00352       ti->z,
00353       IsTransparencySet(TO_INDUSTRIES));
00354 
00355     if (IsTransparencySet(TO_INDUSTRIES)) return;
00356   }
00357 
00358   {
00359     int proc = dits->draw_proc - 1;
00360     if (proc >= 0) _industry_draw_tile_procs[proc](ti);
00361   }
00362 }
00363 
00364 static uint GetSlopeZ_Industry(TileIndex tile, uint x, uint y)
00365 {
00366   return GetTileMaxZ(tile);
00367 }
00368 
00369 static Foundation GetFoundation_Industry(TileIndex tile, Slope tileh)
00370 {
00371   IndustryGfx gfx = GetIndustryGfx(tile);
00372 
00373   /* For NewGRF industry tiles we might not be drawing a foundation. We need to
00374    * account for this, as other structures should
00375    * draw the wall of the foundation in this case.
00376    */
00377   if (gfx >= NEW_INDUSTRYTILEOFFSET) {
00378     const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
00379     if (indts->grf_prop.spritegroup[0] != NULL && HasBit(indts->callback_mask, CBM_INDT_DRAW_FOUNDATIONS)) {
00380       uint32 callback_res = GetIndustryTileCallback(CBID_INDTILE_DRAW_FOUNDATIONS, 0, 0, gfx, Industry::GetByTile(tile), tile);
00381       if (callback_res == 0) return FOUNDATION_NONE;
00382     }
00383   }
00384   return FlatteningFoundation(tileh);
00385 }
00386 
00387 static void AddAcceptedCargo_Industry(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00388 {
00389   IndustryGfx gfx = GetIndustryGfx(tile);
00390   const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
00391 
00392   /* When we have to use a callback, we put our data in the next two variables */
00393   CargoID raw_accepts_cargo[lengthof(itspec->accepts_cargo)];
00394   uint8 raw_cargo_acceptance[lengthof(itspec->acceptance)];
00395 
00396   /* And then these will always point to a same sized array with the required data */
00397   const CargoID *accepts_cargo = itspec->accepts_cargo;
00398   const uint8 *cargo_acceptance = itspec->acceptance;
00399 
00400   if (HasBit(itspec->callback_mask, CBM_INDT_ACCEPT_CARGO)) {
00401     uint16 res = GetIndustryTileCallback(CBID_INDTILE_ACCEPT_CARGO, 0, 0, gfx, Industry::GetByTile(tile), tile);
00402     if (res != CALLBACK_FAILED) {
00403       accepts_cargo = raw_accepts_cargo;
00404       for (uint i = 0; i < lengthof(itspec->accepts_cargo); i++) raw_accepts_cargo[i] = GetCargoTranslation(GB(res, i * 5, 5), itspec->grf_prop.grffile);
00405     }
00406   }
00407 
00408   if (HasBit(itspec->callback_mask, CBM_INDT_CARGO_ACCEPTANCE)) {
00409     uint16 res = GetIndustryTileCallback(CBID_INDTILE_CARGO_ACCEPTANCE, 0, 0, gfx, Industry::GetByTile(tile), tile);
00410     if (res != CALLBACK_FAILED) {
00411       cargo_acceptance = raw_cargo_acceptance;
00412       for (uint i = 0; i < lengthof(itspec->accepts_cargo); i++) raw_cargo_acceptance[i] = GB(res, i * 4, 4);
00413     }
00414   }
00415 
00416   const Industry *ind = Industry::GetByTile(tile);
00417   for (byte i = 0; i < lengthof(itspec->accepts_cargo); i++) {
00418     CargoID a = accepts_cargo[i];
00419     if (a == CT_INVALID || cargo_acceptance[i] == 0) continue; // work only with valid cargos
00420 
00421     /* Add accepted cargo */
00422     acceptance[a] += cargo_acceptance[i];
00423 
00424     /* Maybe set 'always accepted' bit (if it's not set already) */
00425     if (HasBit(*always_accepted, a)) continue;
00426 
00427     bool accepts = false;
00428     for (uint cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00429       /* Test whether the industry itself accepts the cargo type */
00430       if (ind->accepts_cargo[cargo_index] == a) {
00431         accepts = true;
00432         break;
00433       }
00434     }
00435 
00436     if (accepts) continue;
00437 
00438     /* If the industry itself doesn't accept this cargo, set 'always accepted' bit */
00439     SetBit(*always_accepted, a);
00440   }
00441 }
00442 
00443 static void GetTileDesc_Industry(TileIndex tile, TileDesc *td)
00444 {
00445   const Industry *i = Industry::GetByTile(tile);
00446   const IndustrySpec *is = GetIndustrySpec(i->type);
00447 
00448   td->owner[0] = i->owner;
00449   td->str = is->name;
00450   if (!IsIndustryCompleted(tile)) {
00451     SetDParamX(td->dparam, 0, td->str);
00452     td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00453   }
00454 
00455   if (is->grf_prop.grffile != NULL) {
00456     td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
00457   }
00458 }
00459 
00460 static CommandCost ClearTile_Industry(TileIndex tile, DoCommandFlag flags)
00461 {
00462   Industry *i = Industry::GetByTile(tile);
00463   const IndustrySpec *indspec = GetIndustrySpec(i->type);
00464 
00465   /* water can destroy industries
00466    * in editor you can bulldoze industries
00467    * with magic_bulldozer cheat you can destroy industries
00468    * (area around OILRIG is water, so water shouldn't flood it
00469    */
00470   if ((_current_company != OWNER_WATER && _game_mode != GM_EDITOR &&
00471       !_cheats.magic_bulldozer.value) ||
00472       ((flags & DC_AUTO) != 0) ||
00473       (_current_company == OWNER_WATER &&
00474         ((indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) ||
00475         HasBit(GetIndustryTileSpec(GetIndustryGfx(tile))->slopes_refused, 5)))) {
00476     SetDParam(1, indspec->name);
00477     return_cmd_error(flags & DC_AUTO ? STR_ERROR_GENERIC_OBJECT_IN_THE_WAY : INVALID_STRING_ID);
00478   }
00479 
00480   if (flags & DC_EXEC) {
00481     AI::BroadcastNewEvent(new AIEventIndustryClose(i->index));
00482     delete i;
00483   }
00484   return CommandCost(EXPENSES_CONSTRUCTION, indspec->GetRemovalCost());
00485 }
00486 
00487 static void TransportIndustryGoods(TileIndex tile)
00488 {
00489   Industry *i = Industry::GetByTile(tile);
00490   const IndustrySpec *indspec = GetIndustrySpec(i->type);
00491   bool moved_cargo = false;
00492 
00493   StationFinder stations(i->location);
00494 
00495   for (uint j = 0; j < lengthof(i->produced_cargo_waiting); j++) {
00496     uint cw = min(i->produced_cargo_waiting[j], 255);
00497     if (cw > indspec->minimal_cargo && i->produced_cargo[j] != CT_INVALID) {
00498       i->produced_cargo_waiting[j] -= cw;
00499 
00500       /* fluctuating economy? */
00501       if (EconomyIsInRecession()) cw = (cw + 1) / 2;
00502 
00503       i->this_month_production[j] += cw;
00504 
00505       uint am = MoveGoodsToStation(i->produced_cargo[j], cw, ST_INDUSTRY, i->index, stations.GetStations());
00506       i->this_month_transported[j] += am;
00507 
00508       moved_cargo |= (am != 0);
00509     }
00510   }
00511 
00512   if (moved_cargo && !StartStopIndustryTileAnimation(i, IAT_INDUSTRY_DISTRIBUTES_CARGO)) {
00513     uint newgfx = GetIndustryTileSpec(GetIndustryGfx(tile))->anim_production;
00514 
00515     if (newgfx != INDUSTRYTILE_NOANIM) {
00516       ResetIndustryConstructionStage(tile);
00517       SetIndustryCompleted(tile, true);
00518       SetIndustryGfx(tile, newgfx);
00519       MarkTileDirtyByTile(tile);
00520     }
00521   }
00522 }
00523 
00524 
00525 static void AnimateTile_Industry(TileIndex tile)
00526 {
00527   IndustryGfx gfx = GetIndustryGfx(tile);
00528 
00529   if (GetIndustryTileSpec(gfx)->animation.status != ANIM_STATUS_NO_ANIMATION) {
00530     AnimateNewIndustryTile(tile);
00531     return;
00532   }
00533 
00534   switch (gfx) {
00535   case GFX_SUGAR_MINE_SIEVE:
00536     if ((_tick_counter & 1) == 0) {
00537       byte m = GetAnimationFrame(tile) + 1;
00538 
00539       switch (m & 7) {
00540       case 2: SndPlayTileFx(SND_2D_RIP_2, tile); break;
00541       case 6: SndPlayTileFx(SND_29_RIP, tile); break;
00542       }
00543 
00544       if (m >= 96) {
00545         m = 0;
00546         DeleteAnimatedTile(tile);
00547       }
00548       SetAnimationFrame(tile, m);
00549 
00550       MarkTileDirtyByTile(tile);
00551     }
00552     break;
00553 
00554   case GFX_TOFFEE_QUARY:
00555     if ((_tick_counter & 3) == 0) {
00556       byte m = GetAnimationFrame(tile);
00557 
00558       if (_industry_anim_offs_toffee[m] == 0xFF) {
00559         SndPlayTileFx(SND_30_CARTOON_SOUND, tile);
00560       }
00561 
00562       if (++m >= 70) {
00563         m = 0;
00564         DeleteAnimatedTile(tile);
00565       }
00566       SetAnimationFrame(tile, m);
00567 
00568       MarkTileDirtyByTile(tile);
00569     }
00570     break;
00571 
00572   case GFX_BUBBLE_CATCHER:
00573     if ((_tick_counter & 1) == 0) {
00574       byte m = GetAnimationFrame(tile);
00575 
00576       if (++m >= 40) {
00577         m = 0;
00578         DeleteAnimatedTile(tile);
00579       }
00580       SetAnimationFrame(tile, m);
00581 
00582       MarkTileDirtyByTile(tile);
00583     }
00584     break;
00585 
00586   /* Sparks on a coal plant */
00587   case GFX_POWERPLANT_SPARKS:
00588     if ((_tick_counter & 3) == 0) {
00589       byte m = GetAnimationFrame(tile);
00590       if (m == 6) {
00591         SetAnimationFrame(tile, 0);
00592         DeleteAnimatedTile(tile);
00593       } else {
00594         SetAnimationFrame(tile, m + 1);
00595         MarkTileDirtyByTile(tile);
00596       }
00597     }
00598     break;
00599 
00600   case GFX_TOY_FACTORY:
00601     if ((_tick_counter & 1) == 0) {
00602       byte m = GetAnimationFrame(tile) + 1;
00603 
00604       switch (m) {
00605         case  1: SndPlayTileFx(SND_2C_MACHINERY, tile); break;
00606         case 23: SndPlayTileFx(SND_2B_COMEDY_HIT, tile); break;
00607         case 28: SndPlayTileFx(SND_2A_EXTRACT_AND_POP, tile); break;
00608         default:
00609           if (m >= 50) {
00610             int n = GetIndustryAnimationLoop(tile) + 1;
00611             m = 0;
00612             if (n >= 8) {
00613               n = 0;
00614               DeleteAnimatedTile(tile);
00615             }
00616             SetIndustryAnimationLoop(tile, n);
00617           }
00618       }
00619 
00620       SetAnimationFrame(tile, m);
00621       MarkTileDirtyByTile(tile);
00622     }
00623     break;
00624 
00625   case GFX_PLASTIC_FOUNTAIN_ANIMATED_1: case GFX_PLASTIC_FOUNTAIN_ANIMATED_2:
00626   case GFX_PLASTIC_FOUNTAIN_ANIMATED_3: case GFX_PLASTIC_FOUNTAIN_ANIMATED_4:
00627   case GFX_PLASTIC_FOUNTAIN_ANIMATED_5: case GFX_PLASTIC_FOUNTAIN_ANIMATED_6:
00628   case GFX_PLASTIC_FOUNTAIN_ANIMATED_7: case GFX_PLASTIC_FOUNTAIN_ANIMATED_8:
00629     if ((_tick_counter & 3) == 0) {
00630       IndustryGfx gfx = GetIndustryGfx(tile);
00631 
00632       gfx = (gfx < 155) ? gfx + 1 : 148;
00633       SetIndustryGfx(tile, gfx);
00634       MarkTileDirtyByTile(tile);
00635     }
00636     break;
00637 
00638   case GFX_OILWELL_ANIMATED_1:
00639   case GFX_OILWELL_ANIMATED_2:
00640   case GFX_OILWELL_ANIMATED_3:
00641     if ((_tick_counter & 7) == 0) {
00642       bool b = Chance16(1, 7);
00643       IndustryGfx gfx = GetIndustryGfx(tile);
00644 
00645       byte m = GetAnimationFrame(tile) + 1;
00646       if (m == 4 && (m = 0, ++gfx) == GFX_OILWELL_ANIMATED_3 + 1 && (gfx = GFX_OILWELL_ANIMATED_1, b)) {
00647         SetIndustryGfx(tile, GFX_OILWELL_NOT_ANIMATED);
00648         SetIndustryConstructionStage(tile, 3);
00649         DeleteAnimatedTile(tile);
00650       } else {
00651         SetAnimationFrame(tile, m);
00652         SetIndustryGfx(tile, gfx);
00653         MarkTileDirtyByTile(tile);
00654       }
00655     }
00656     break;
00657 
00658   case GFX_COAL_MINE_TOWER_ANIMATED:
00659   case GFX_COPPER_MINE_TOWER_ANIMATED:
00660   case GFX_GOLD_MINE_TOWER_ANIMATED: {
00661       int state = _tick_counter & 0x7FF;
00662 
00663       if ((state -= 0x400) < 0) return;
00664 
00665       if (state < 0x1A0) {
00666         if (state < 0x20 || state >= 0x180) {
00667           byte m = GetAnimationFrame(tile);
00668           if (!(m & 0x40)) {
00669             SetAnimationFrame(tile, m | 0x40);
00670             SndPlayTileFx(SND_0B_MINING_MACHINERY, tile);
00671           }
00672           if (state & 7) return;
00673         } else {
00674           if (state & 3) return;
00675         }
00676         byte m = (GetAnimationFrame(tile) + 1) | 0x40;
00677         if (m > 0xC2) m = 0xC0;
00678         SetAnimationFrame(tile, m);
00679         MarkTileDirtyByTile(tile);
00680       } else if (state >= 0x200 && state < 0x3A0) {
00681         int i = (state < 0x220 || state >= 0x380) ? 7 : 3;
00682         if (state & i) return;
00683 
00684         byte m = (GetAnimationFrame(tile) & 0xBF) - 1;
00685         if (m < 0x80) m = 0x82;
00686         SetAnimationFrame(tile, m);
00687         MarkTileDirtyByTile(tile);
00688       }
00689       break;
00690     }
00691   }
00692 }
00693 
00694 static void CreateChimneySmoke(TileIndex tile)
00695 {
00696   uint x = TileX(tile) * TILE_SIZE;
00697   uint y = TileY(tile) * TILE_SIZE;
00698   uint z = GetTileMaxZ(tile);
00699 
00700   CreateEffectVehicle(x + 15, y + 14, z + 59, EV_CHIMNEY_SMOKE);
00701 }
00702 
00703 static void MakeIndustryTileBigger(TileIndex tile)
00704 {
00705   byte cnt = GetIndustryConstructionCounter(tile) + 1;
00706   if (cnt != 4) {
00707     SetIndustryConstructionCounter(tile, cnt);
00708     return;
00709   }
00710 
00711   byte stage = GetIndustryConstructionStage(tile) + 1;
00712   SetIndustryConstructionCounter(tile, 0);
00713   SetIndustryConstructionStage(tile, stage);
00714   StartStopIndustryTileAnimation(tile, IAT_CONSTRUCTION_STATE_CHANGE);
00715   if (stage == INDUSTRY_COMPLETED) SetIndustryCompleted(tile, true);
00716 
00717   MarkTileDirtyByTile(tile);
00718 
00719   if (!IsIndustryCompleted(tile)) return;
00720 
00721   IndustryGfx gfx = GetIndustryGfx(tile);
00722   if (gfx >= NEW_INDUSTRYTILEOFFSET) {
00723     /* New industries are already animated on construction. */
00724     return;
00725   }
00726 
00727   switch (gfx) {
00728   case GFX_POWERPLANT_CHIMNEY:
00729     CreateChimneySmoke(tile);
00730     break;
00731 
00732   case GFX_OILRIG_1: {
00733     /* Do not require an industry tile to be after the first two GFX_OILRIG_1
00734      * tiles (like the default oil rig). Do a proper check to ensure the
00735      * tiles belong to the same industry and based on that build the oil rig's
00736      * station. */
00737     TileIndex other = tile + TileDiffXY(0, 1);
00738 
00739     if (IsTileType(other, MP_INDUSTRY) &&
00740         GetIndustryGfx(other) == GFX_OILRIG_1 &&
00741         GetIndustryIndex(tile) == GetIndustryIndex(other)) {
00742       BuildOilRig(tile);
00743     }
00744     break;
00745   }
00746 
00747   case GFX_TOY_FACTORY:
00748   case GFX_BUBBLE_CATCHER:
00749   case GFX_TOFFEE_QUARY:
00750     SetAnimationFrame(tile, 0);
00751     SetIndustryAnimationLoop(tile, 0);
00752     break;
00753 
00754   case GFX_PLASTIC_FOUNTAIN_ANIMATED_1: case GFX_PLASTIC_FOUNTAIN_ANIMATED_2:
00755   case GFX_PLASTIC_FOUNTAIN_ANIMATED_3: case GFX_PLASTIC_FOUNTAIN_ANIMATED_4:
00756   case GFX_PLASTIC_FOUNTAIN_ANIMATED_5: case GFX_PLASTIC_FOUNTAIN_ANIMATED_6:
00757   case GFX_PLASTIC_FOUNTAIN_ANIMATED_7: case GFX_PLASTIC_FOUNTAIN_ANIMATED_8:
00758     AddAnimatedTile(tile);
00759     break;
00760   }
00761 }
00762 
00763 static void TileLoopIndustry_BubbleGenerator(TileIndex tile)
00764 {
00765   static const int8 _bubble_spawn_location[3][4] = {
00766     { 11,   0, -4, -14 },
00767     { -4, -10, -4,   1 },
00768     { 49,  59, 60,  65 },
00769   };
00770 
00771   SndPlayTileFx(SND_2E_EXTRACT_AND_POP, tile);
00772 
00773   int dir = Random() & 3;
00774 
00775   EffectVehicle *v = CreateEffectVehicleAbove(
00776     TileX(tile) * TILE_SIZE + _bubble_spawn_location[0][dir],
00777     TileY(tile) * TILE_SIZE + _bubble_spawn_location[1][dir],
00778     _bubble_spawn_location[2][dir],
00779     EV_BUBBLE
00780   );
00781 
00782   if (v != NULL) v->animation_substate = dir;
00783 }
00784 
00785 static void TileLoop_Industry(TileIndex tile)
00786 {
00787   if (IsTileOnWater(tile)) TileLoop_Water(tile);
00788 
00789   /* Normally this doesn't happen, but if an industry NewGRF is removed
00790    * an industry that was previously build on water can now be flooded.
00791    * If this happens the tile is no longer an industry tile after
00792    * returning from TileLoop_Water. */
00793   if (!IsTileType(tile, MP_INDUSTRY)) return;
00794 
00795   TriggerIndustryTile(tile, INDTILE_TRIGGER_TILE_LOOP);
00796 
00797   if (!IsIndustryCompleted(tile)) {
00798     MakeIndustryTileBigger(tile);
00799     return;
00800   }
00801 
00802   if (_game_mode == GM_EDITOR) return;
00803 
00804   TransportIndustryGoods(tile);
00805 
00806   if (StartStopIndustryTileAnimation(tile, IAT_TILELOOP)) return;
00807 
00808   IndustryGfx newgfx = GetIndustryTileSpec(GetIndustryGfx(tile))->anim_next;
00809   if (newgfx != INDUSTRYTILE_NOANIM) {
00810     ResetIndustryConstructionStage(tile);
00811     SetIndustryGfx(tile, newgfx);
00812     MarkTileDirtyByTile(tile);
00813     return;
00814   }
00815 
00816   IndustryGfx gfx = GetIndustryGfx(tile);
00817   switch (gfx) {
00818   case GFX_COAL_MINE_TOWER_NOT_ANIMATED:
00819   case GFX_COPPER_MINE_TOWER_NOT_ANIMATED:
00820   case GFX_GOLD_MINE_TOWER_NOT_ANIMATED:
00821     if (!(_tick_counter & 0x400) && Chance16(1, 2)) {
00822       switch (gfx) {
00823         case GFX_COAL_MINE_TOWER_NOT_ANIMATED:   gfx = GFX_COAL_MINE_TOWER_ANIMATED;   break;
00824         case GFX_COPPER_MINE_TOWER_NOT_ANIMATED: gfx = GFX_COPPER_MINE_TOWER_ANIMATED; break;
00825         case GFX_GOLD_MINE_TOWER_NOT_ANIMATED:   gfx = GFX_GOLD_MINE_TOWER_ANIMATED;   break;
00826       }
00827       SetIndustryGfx(tile, gfx);
00828       SetAnimationFrame(tile, 0x80);
00829       AddAnimatedTile(tile);
00830     }
00831     break;
00832 
00833   case GFX_OILWELL_NOT_ANIMATED:
00834     if (Chance16(1, 6)) {
00835       SetIndustryGfx(tile, GFX_OILWELL_ANIMATED_1);
00836       SetAnimationFrame(tile, 0);
00837       AddAnimatedTile(tile);
00838     }
00839     break;
00840 
00841   case GFX_COAL_MINE_TOWER_ANIMATED:
00842   case GFX_COPPER_MINE_TOWER_ANIMATED:
00843   case GFX_GOLD_MINE_TOWER_ANIMATED:
00844     if (!(_tick_counter & 0x400)) {
00845       switch (gfx) {
00846         case GFX_COAL_MINE_TOWER_ANIMATED:   gfx = GFX_COAL_MINE_TOWER_NOT_ANIMATED;   break;
00847         case GFX_COPPER_MINE_TOWER_ANIMATED: gfx = GFX_COPPER_MINE_TOWER_NOT_ANIMATED; break;
00848         case GFX_GOLD_MINE_TOWER_ANIMATED:   gfx = GFX_GOLD_MINE_TOWER_NOT_ANIMATED;   break;
00849       }
00850       SetIndustryGfx(tile, gfx);
00851       SetIndustryCompleted(tile, true);
00852       SetIndustryConstructionStage(tile, 3);
00853       DeleteAnimatedTile(tile);
00854     }
00855     break;
00856 
00857   case GFX_POWERPLANT_SPARKS:
00858     if (Chance16(1, 3)) {
00859       SndPlayTileFx(SND_0C_ELECTRIC_SPARK, tile);
00860       AddAnimatedTile(tile);
00861     }
00862     break;
00863 
00864   case GFX_COPPER_MINE_CHIMNEY:
00865     CreateEffectVehicleAbove(TileX(tile) * TILE_SIZE + 6, TileY(tile) * TILE_SIZE + 6, 43, EV_SMOKE);
00866     break;
00867 
00868 
00869   case GFX_TOY_FACTORY: {
00870       Industry *i = Industry::GetByTile(tile);
00871       if (i->was_cargo_delivered) {
00872         i->was_cargo_delivered = false;
00873         SetIndustryAnimationLoop(tile, 0);
00874         AddAnimatedTile(tile);
00875       }
00876     }
00877     break;
00878 
00879   case GFX_BUBBLE_GENERATOR:
00880     TileLoopIndustry_BubbleGenerator(tile);
00881     break;
00882 
00883   case GFX_TOFFEE_QUARY:
00884     AddAnimatedTile(tile);
00885     break;
00886 
00887   case GFX_SUGAR_MINE_SIEVE:
00888     if (Chance16(1, 3)) AddAnimatedTile(tile);
00889     break;
00890   }
00891 }
00892 
00893 static bool ClickTile_Industry(TileIndex tile)
00894 {
00895   ShowIndustryViewWindow(GetIndustryIndex(tile));
00896   return true;
00897 }
00898 
00899 static TrackStatus GetTileTrackStatus_Industry(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00900 {
00901   return 0;
00902 }
00903 
00904 static void ChangeTileOwner_Industry(TileIndex tile, Owner old_owner, Owner new_owner)
00905 {
00906   /* If the founder merges, the industry was created by the merged company */
00907   Industry *i = Industry::GetByTile(tile);
00908   if (i->founder == old_owner) i->founder = (new_owner == INVALID_OWNER) ? OWNER_NONE : new_owner;
00909 }
00910 
00911 static const byte _plantfarmfield_type[] = {1, 1, 1, 1, 1, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6};
00912 
00913 static bool IsBadFarmFieldTile(TileIndex tile)
00914 {
00915   switch (GetTileType(tile)) {
00916     case MP_CLEAR: return IsClearGround(tile, CLEAR_FIELDS) || IsClearGround(tile, CLEAR_SNOW) || IsClearGround(tile, CLEAR_DESERT);
00917     case MP_TREES: return (GetTreeGround(tile) == TREE_GROUND_SHORE);
00918     default:       return true;
00919   }
00920 }
00921 
00922 static bool IsBadFarmFieldTile2(TileIndex tile)
00923 {
00924   switch (GetTileType(tile)) {
00925     case MP_CLEAR: return IsClearGround(tile, CLEAR_SNOW) || IsClearGround(tile, CLEAR_DESERT);
00926     case MP_TREES: return (GetTreeGround(tile) == TREE_GROUND_SHORE);
00927     default:       return true;
00928   }
00929 }
00930 
00931 static void SetupFarmFieldFence(TileIndex tile, int size, byte type, Axis direction)
00932 {
00933   do {
00934     tile = TILE_MASK(tile);
00935 
00936     if (IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) {
00937       byte or_ = type;
00938 
00939       if (or_ == 1 && Chance16(1, 7)) or_ = 2;
00940 
00941       if (direction == AXIS_X) {
00942         SetFenceSE(tile, or_);
00943       } else {
00944         SetFenceSW(tile, or_);
00945       }
00946     }
00947 
00948     tile += (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00949   } while (--size);
00950 }
00951 
00952 static void PlantFarmField(TileIndex tile, IndustryID industry)
00953 {
00954   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
00955     if (GetTileZ(tile) + TILE_HEIGHT * 2 >= GetSnowLine()) return;
00956   }
00957 
00958   /* determine field size */
00959   uint32 r = (Random() & 0x303) + 0x404;
00960   if (_settings_game.game_creation.landscape == LT_ARCTIC) r += 0x404;
00961   uint size_x = GB(r, 0, 8);
00962   uint size_y = GB(r, 8, 8);
00963 
00964   TileArea ta(tile - TileDiffXY(min(TileX(tile), size_x / 2), min(TileY(tile), size_y / 2)), size_x, size_y);
00965   ta.ClampToMap();
00966 
00967   if (ta.w == 0 || ta.h == 0) return;
00968 
00969   /* check the amount of bad tiles */
00970   int count = 0;
00971   TILE_AREA_LOOP(cur_tile, ta) {
00972     assert(cur_tile < MapSize());
00973     count += IsBadFarmFieldTile(cur_tile);
00974   }
00975   if (count * 2 >= ta.w * ta.h) return;
00976 
00977   /* determine type of field */
00978   r = Random();
00979   uint counter = GB(r, 5, 3);
00980   uint field_type = GB(r, 8, 8) * 9 >> 8;
00981 
00982   /* make field */
00983   TILE_AREA_LOOP(cur_tile, ta) {
00984     assert(cur_tile < MapSize());
00985     if (!IsBadFarmFieldTile2(cur_tile)) {
00986       MakeField(cur_tile, field_type, industry);
00987       SetClearCounter(cur_tile, counter);
00988       MarkTileDirtyByTile(cur_tile);
00989     }
00990   }
00991 
00992   int type = 3;
00993   if (_settings_game.game_creation.landscape != LT_ARCTIC && _settings_game.game_creation.landscape != LT_TROPIC) {
00994     type = _plantfarmfield_type[Random() & 0xF];
00995   }
00996 
00997   SetupFarmFieldFence(ta.tile - TileDiffXY(1, 0), ta.h, type, AXIS_Y);
00998   SetupFarmFieldFence(ta.tile - TileDiffXY(0, 1), ta.w, type, AXIS_X);
00999   SetupFarmFieldFence(ta.tile + TileDiffXY(ta.w - 1, 0), ta.h, type, AXIS_Y);
01000   SetupFarmFieldFence(ta.tile + TileDiffXY(0, ta.h - 1), ta.w, type, AXIS_X);
01001 }
01002 
01003 void PlantRandomFarmField(const Industry *i)
01004 {
01005   int x = i->location.w / 2 + Random() % 31 - 16;
01006   int y = i->location.h / 2 + Random() % 31 - 16;
01007 
01008   TileIndex tile = TileAddWrap(i->location.tile, x, y);
01009 
01010   if (tile != INVALID_TILE) PlantFarmField(tile, i->index);
01011 }
01012 
01019 static bool SearchLumberMillTrees(TileIndex tile, void *user_data)
01020 {
01021   if (IsTileType(tile, MP_TREES) && GetTreeGrowth(tile) > 2) { 
01022     /* found a tree */
01023 
01024     Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01025 
01026     _industry_sound_ctr = 1;
01027     _industry_sound_tile = tile;
01028     SndPlayTileFx(SND_38_CHAINSAW, tile);
01029 
01030     DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
01031 
01032     cur_company.Restore();
01033     return true;
01034   }
01035   return false;
01036 }
01037 
01042 static void ChopLumberMillTrees(Industry *i)
01043 {
01044   TileIndex tile = i->location.tile;
01045 
01046   if (!IsIndustryCompleted(tile)) return;  // Can't proceed if not completed.
01047 
01048   if (CircularTileSearch(&tile, 40, SearchLumberMillTrees, NULL)) { // 40x40 tiles  to search.
01049     i->produced_cargo_waiting[0] = min(0xffff, i->produced_cargo_waiting[0] + 45); // Found a tree, add according value to waiting cargo.
01050   }
01051 }
01052 
01053 static void ProduceIndustryGoods(Industry *i)
01054 {
01055   const IndustrySpec *indsp = GetIndustrySpec(i->type);
01056 
01057   /* play a sound? */
01058   if ((i->counter & 0x3F) == 0) {
01059     uint32 r;
01060     uint num;
01061     if (Chance16R(1, 14, r) && (num = indsp->number_of_sounds) != 0) {
01062       SndPlayTileFx(
01063         (SoundFx)(indsp->random_sounds[((r >> 16) * num) >> 16]),
01064         i->location.tile);
01065     }
01066   }
01067 
01068   i->counter--;
01069 
01070   /* produce some cargo */
01071   if ((i->counter & 0xFF) == 0) {
01072     if (HasBit(indsp->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) IndustryProductionCallback(i, 1);
01073 
01074     IndustryBehaviour indbehav = indsp->behaviour;
01075     i->produced_cargo_waiting[0] = min(0xffff, i->produced_cargo_waiting[0] + i->production_rate[0]);
01076     i->produced_cargo_waiting[1] = min(0xffff, i->produced_cargo_waiting[1] + i->production_rate[1]);
01077 
01078     if ((indbehav & INDUSTRYBEH_PLANT_FIELDS) != 0) {
01079       bool plant;
01080       if (HasBit(indsp->callback_mask, CBM_IND_SPECIAL_EFFECT)) {
01081         plant = (GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, Random(), 0, i, i->type, i->location.tile) != 0);
01082       } else {
01083         plant = Chance16(1, 8);
01084       }
01085 
01086       if (plant) PlantRandomFarmField(i);
01087     }
01088     if ((indbehav & INDUSTRYBEH_CUT_TREES) != 0) {
01089       bool cut = ((i->counter & 0x1FF) == 0);
01090       if (HasBit(indsp->callback_mask, CBM_IND_SPECIAL_EFFECT)) {
01091         cut = (GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, 0, 1, i, i->type, i->location.tile) != 0);
01092       }
01093 
01094       if (cut) ChopLumberMillTrees(i);
01095     }
01096 
01097     TriggerIndustry(i, INDUSTRY_TRIGGER_INDUSTRY_TICK);
01098     StartStopIndustryTileAnimation(i, IAT_INDUSTRY_TICK);
01099   }
01100 }
01101 
01102 void OnTick_Industry()
01103 {
01104   if (_industry_sound_ctr != 0) {
01105     _industry_sound_ctr++;
01106 
01107     if (_industry_sound_ctr == 75) {
01108       SndPlayTileFx(SND_37_BALLOON_SQUEAK, _industry_sound_tile);
01109     } else if (_industry_sound_ctr == 160) {
01110       _industry_sound_ctr = 0;
01111       SndPlayTileFx(SND_36_CARTOON_CRASH, _industry_sound_tile);
01112     }
01113   }
01114 
01115   if (_game_mode == GM_EDITOR) return;
01116 
01117   Industry *i;
01118   FOR_ALL_INDUSTRIES(i) {
01119     ProduceIndustryGoods(i);
01120   }
01121 }
01122 
01128 static CommandCost CheckNewIndustry_NULL(TileIndex tile)
01129 {
01130   return CommandCost();
01131 }
01132 
01138 static CommandCost CheckNewIndustry_Forest(TileIndex tile)
01139 {
01140   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
01141     if (GetTileZ(tile) < HighestSnowLine() + TILE_HEIGHT * 2U) {
01142       return_cmd_error(STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED);
01143     }
01144   }
01145   return CommandCost();
01146 }
01147 
01153 static CommandCost CheckNewIndustry_OilRefinery(TileIndex tile)
01154 {
01155   if (_game_mode == GM_EDITOR) return CommandCost();
01156   if (DistanceFromEdge(TILE_ADDXY(tile, 1, 1)) < _settings_game.game_creation.oil_refinery_limit) return CommandCost();
01157 
01158   return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
01159 }
01160 
01161 extern bool _ignore_restrictions;
01162 
01168 static CommandCost CheckNewIndustry_OilRig(TileIndex tile)
01169 {
01170   if (_game_mode == GM_EDITOR && _ignore_restrictions) return CommandCost();
01171   if (TileHeight(tile) == 0 &&
01172       DistanceFromEdge(TILE_ADDXY(tile, 1, 1)) < _settings_game.game_creation.oil_refinery_limit) return CommandCost();
01173 
01174   return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
01175 }
01176 
01182 static CommandCost CheckNewIndustry_Farm(TileIndex tile)
01183 {
01184   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
01185     if (GetTileZ(tile) + TILE_HEIGHT * 2 >= HighestSnowLine()) {
01186       return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01187     }
01188   }
01189   return CommandCost();
01190 }
01191 
01197 static CommandCost CheckNewIndustry_Plantation(TileIndex tile)
01198 {
01199   if (GetTropicZone(tile) == TROPICZONE_DESERT) {
01200     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01201   }
01202   return CommandCost();
01203 }
01204 
01210 static CommandCost CheckNewIndustry_Water(TileIndex tile)
01211 {
01212   if (GetTropicZone(tile) != TROPICZONE_DESERT) {
01213     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT);
01214   }
01215   return CommandCost();
01216 }
01217 
01223 static CommandCost CheckNewIndustry_Lumbermill(TileIndex tile)
01224 {
01225   if (GetTropicZone(tile) != TROPICZONE_RAINFOREST) {
01226     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST);
01227   }
01228   return CommandCost();
01229 }
01230 
01236 static CommandCost CheckNewIndustry_BubbleGen(TileIndex tile)
01237 {
01238   if (GetTileZ(tile) > TILE_HEIGHT * 4) {
01239     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_LOW_AREAS);
01240   }
01241   return CommandCost();
01242 }
01243 
01249 typedef CommandCost CheckNewIndustryProc(TileIndex tile);
01250 
01252 static CheckNewIndustryProc * const _check_new_industry_procs[CHECK_END] = {
01253   CheckNewIndustry_NULL,        
01254   CheckNewIndustry_Forest,      
01255   CheckNewIndustry_OilRefinery, 
01256   CheckNewIndustry_Farm,        
01257   CheckNewIndustry_Plantation,  
01258   CheckNewIndustry_Water,       
01259   CheckNewIndustry_Lumbermill,  
01260   CheckNewIndustry_BubbleGen,   
01261   CheckNewIndustry_OilRig,      
01262 };
01263 
01274 static CommandCost FindTownForIndustry(TileIndex tile, int type, const Town **t)
01275 {
01276   *t = ClosestTownFromTile(tile, UINT_MAX);
01277 
01278   if (_settings_game.economy.multiple_industry_per_town) return CommandCost();
01279 
01280   const Industry *i;
01281   FOR_ALL_INDUSTRIES(i) {
01282     if (i->type == (byte)type && i->town == *t) {
01283       *t = NULL;
01284       return_cmd_error(STR_ERROR_ONLY_ONE_ALLOWED_PER_TOWN);
01285     }
01286   }
01287 
01288   return CommandCost();
01289 }
01290 
01291 bool IsSlopeRefused(Slope current, Slope refused)
01292 {
01293   if (IsSteepSlope(current)) return true;
01294   if (current != SLOPE_FLAT) {
01295     if (IsSteepSlope(refused)) return true;
01296 
01297     Slope t = ComplementSlope(current);
01298 
01299     if ((refused & SLOPE_W) && (t & SLOPE_NW)) return true;
01300     if ((refused & SLOPE_S) && (t & SLOPE_NE)) return true;
01301     if ((refused & SLOPE_E) && (t & SLOPE_SW)) return true;
01302     if ((refused & SLOPE_N) && (t & SLOPE_SE)) return true;
01303   }
01304 
01305   return false;
01306 }
01307 
01320 static CommandCost CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileTable *it, uint itspec_index, int type, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type, bool *custom_shape_check = NULL)
01321 {
01322   bool refused_slope = false;
01323   bool custom_shape = false;
01324 
01325   do {
01326     IndustryGfx gfx = GetTranslatedIndustryTileID(it->gfx);
01327     TileIndex cur_tile = TileAddWrap(tile, it->ti.x, it->ti.y);
01328 
01329     if (!IsValidTile(cur_tile)) {
01330       return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01331     }
01332 
01333     if (gfx == GFX_WATERTILE_SPECIALCHECK) {
01334       if (!IsTileType(cur_tile, MP_WATER) ||
01335           GetTileSlope(cur_tile, NULL) != SLOPE_FLAT) {
01336         return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01337       }
01338     } else {
01339       CommandCost ret = EnsureNoVehicleOnGround(cur_tile);
01340       if (ret.Failed()) return ret;
01341       if (MayHaveBridgeAbove(cur_tile) && IsBridgeAbove(cur_tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01342 
01343       const IndustryTileSpec *its = GetIndustryTileSpec(gfx);
01344 
01345       IndustryBehaviour ind_behav = GetIndustrySpec(type)->behaviour;
01346 
01347       /* Perform land/water check if not disabled */
01348       if (!HasBit(its->slopes_refused, 5) && ((HasTileWaterClass(cur_tile) && IsTileOnWater(cur_tile)) == !(ind_behav & INDUSTRYBEH_BUILT_ONWATER))) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01349 
01350       if (HasBit(its->callback_mask, CBM_INDT_SHAPE_CHECK)) {
01351         custom_shape = true;
01352         CommandCost ret = PerformIndustryTileSlopeCheck(tile, cur_tile, its, type, gfx, itspec_index, initial_random_bits, founder, creation_type);
01353         if (ret.Failed()) return ret;
01354       } else {
01355         Slope tileh = GetTileSlope(cur_tile, NULL);
01356         refused_slope |= IsSlopeRefused(tileh, its->slopes_refused);
01357       }
01358 
01359       if ((ind_behav & (INDUSTRYBEH_ONLY_INTOWN | INDUSTRYBEH_TOWN1200_MORE)) || // Tile must be a house
01360           ((ind_behav & INDUSTRYBEH_ONLY_NEARTOWN) && IsTileType(cur_tile, MP_HOUSE))) { // Tile is allowed to be a house (and it is a house)
01361         if (!IsTileType(cur_tile, MP_HOUSE)) {
01362           return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_TOWNS);
01363         }
01364 
01365         /* Clear the tiles as OWNER_TOWN to not affect town rating, and to not clear protected buildings */
01366         Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01367         CommandCost ret = DoCommand(cur_tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
01368         cur_company.Restore();
01369 
01370         if (ret.Failed()) return ret;
01371       } else {
01372         /* Clear the tiles, but do not affect town ratings */
01373         CommandCost ret = DoCommand(cur_tile, 0, 0, DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
01374 
01375         if (ret.Failed()) return ret;
01376       }
01377     }
01378   } while ((++it)->ti.x != -0x80);
01379 
01380   if (custom_shape_check != NULL) *custom_shape_check = custom_shape;
01381 
01382   /* It is almost impossible to have a fully flat land in TG, so what we
01383    *  do is that we check if we can make the land flat later on. See
01384    *  CheckIfCanLevelIndustryPlatform(). */
01385   if (!refused_slope || (_settings_game.game_creation.land_generator == LG_TERRAGENESIS && _generating_world && !custom_shape && !_ignore_restrictions)) {
01386     return CommandCost();
01387   }
01388   return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01389 }
01390 
01398 static CommandCost CheckIfIndustryIsAllowed(TileIndex tile, int type, const Town *t)
01399 {
01400   if ((GetIndustrySpec(type)->behaviour & INDUSTRYBEH_TOWN1200_MORE) && t->population < 1200) {
01401     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_TOWNS_WITH_POPULATION_OF_1200);
01402   }
01403 
01404   if ((GetIndustrySpec(type)->behaviour & INDUSTRYBEH_ONLY_NEARTOWN) && DistanceMax(t->xy, tile) > 9) {
01405     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01406   }
01407 
01408   return CommandCost();
01409 }
01410 
01411 static bool CheckCanTerraformSurroundingTiles(TileIndex tile, uint height, int internal)
01412 {
01413   /* Check if we don't leave the map */
01414   if (TileX(tile) == 0 || TileY(tile) == 0 || GetTileType(tile) == MP_VOID) return false;
01415 
01416   TileArea ta(tile - TileDiffXY(1, 1), 2, 2);
01417   TILE_AREA_LOOP(tile_walk, ta) {
01418     uint curh = TileHeight(tile_walk);
01419     /* Is the tile clear? */
01420     if ((GetTileType(tile_walk) != MP_CLEAR) && (GetTileType(tile_walk) != MP_TREES)) return false;
01421 
01422     /* Don't allow too big of a change if this is the sub-tile check */
01423     if (internal != 0 && Delta(curh, height) > 1) return false;
01424 
01425     /* Different height, so the surrounding tiles of this tile
01426      *  has to be correct too (in level, or almost in level)
01427      *  else you get a chain-reaction of terraforming. */
01428     if (internal == 0 && curh != height) {
01429       if (TileX(tile_walk) == 0 || TileY(tile_walk) == 0 || !CheckCanTerraformSurroundingTiles(tile_walk + TileDiffXY(-1, -1), height, internal + 1)) {
01430         return false;
01431       }
01432     }
01433   }
01434 
01435   return true;
01436 }
01437 
01442 static bool CheckIfCanLevelIndustryPlatform(TileIndex tile, DoCommandFlag flags, const IndustryTileTable *it, int type)
01443 {
01444   const int MKEND = -0x80;   // used for last element in an IndustryTileTable (see build_industry.h)
01445   int max_x = 0;
01446   int max_y = 0;
01447 
01448   /* Finds dimensions of largest variant of this industry */
01449   do {
01450     if (it->gfx == 0xFF) continue;  //  FF been a marquer for a check on clear water, skip it
01451     if (it->ti.x > max_x) max_x = it->ti.x;
01452     if (it->ti.y > max_y) max_y = it->ti.y;
01453   } while ((++it)->ti.x != MKEND);
01454 
01455   /* Remember level height */
01456   uint h = TileHeight(tile);
01457 
01458   if (TileX(tile) <= _settings_game.construction.industry_platform + 1U || TileY(tile) <= _settings_game.construction.industry_platform + 1U) return false;
01459   /* Check that all tiles in area and surrounding are clear
01460    * this determines that there are no obstructing items */
01461 
01462   TileArea ta(tile + TileDiffXY(-_settings_game.construction.industry_platform, -_settings_game.construction.industry_platform),
01463       max_x + 2 + 2 * _settings_game.construction.industry_platform, max_y + 2 + 2 * _settings_game.construction.industry_platform);
01464 
01465   if (TileX(ta.tile) + ta.w >= MapMaxX() || TileY(ta.tile) + ta.h >= MapMaxY()) return false;
01466 
01467   /* _current_company is OWNER_NONE for randomly generated industries and in editor, or the company who funded or prospected the industry.
01468    * Perform terraforming as OWNER_TOWN to disable autoslope and town ratings. */
01469   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01470 
01471   TILE_AREA_LOOP(tile_walk, ta) {
01472     uint curh = TileHeight(tile_walk);
01473     if (curh != h) {
01474       /* This tile needs terraforming. Check if we can do that without
01475        *  damaging the surroundings too much. */
01476       if (!CheckCanTerraformSurroundingTiles(tile_walk, h, 0)) {
01477         cur_company.Restore();
01478         return false;
01479       }
01480       /* This is not 100% correct check, but the best we can do without modifying the map.
01481        *  What is missing, is if the difference in height is more than 1.. */
01482       if (DoCommand(tile_walk, SLOPE_N, (curh > h) ? 0 : 1, flags & ~DC_EXEC, CMD_TERRAFORM_LAND).Failed()) {
01483         cur_company.Restore();
01484         return false;
01485       }
01486     }
01487   }
01488 
01489   if (flags & DC_EXEC) {
01490     /* Terraform the land under the industry */
01491     TILE_AREA_LOOP(tile_walk, ta) {
01492       uint curh = TileHeight(tile_walk);
01493       while (curh != h) {
01494         /* We give the terraforming for free here, because we can't calculate
01495          *  exact cost in the test-round, and as we all know, that will cause
01496          *  a nice assert if they don't match ;) */
01497         DoCommand(tile_walk, SLOPE_N, (curh > h) ? 0 : 1, flags, CMD_TERRAFORM_LAND);
01498         curh += (curh > h) ? -1 : 1;
01499       }
01500     }
01501   }
01502 
01503   cur_company.Restore();
01504   return true;
01505 }
01506 
01507 
01514 static CommandCost CheckIfFarEnoughFromConflictingIndustry(TileIndex tile, int type)
01515 {
01516   const IndustrySpec *indspec = GetIndustrySpec(type);
01517   const Industry *i;
01518   FOR_ALL_INDUSTRIES(i) {
01519     /* Within 14 tiles from another industry is considered close */
01520     if (DistanceMax(tile, i->location.tile) > 14) continue;
01521 
01522     /* check if there are any conflicting industry types around */
01523     if (i->type == indspec->conflicting[0] ||
01524         i->type == indspec->conflicting[1] ||
01525         i->type == indspec->conflicting[2]) {
01526       return_cmd_error(STR_ERROR_INDUSTRY_TOO_CLOSE);
01527     }
01528   }
01529   return CommandCost();
01530 }
01531 
01543 static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type, const IndustryTileTable *it, byte layout, const Town *t, Owner founder, uint16 initial_random_bits)
01544 {
01545   const IndustrySpec *indspec = GetIndustrySpec(type);
01546 
01547   i->location = TileArea(tile, 1, 1);
01548   i->type = type;
01549   Industry::IncIndustryTypeCount(type);
01550 
01551   i->produced_cargo[0] = indspec->produced_cargo[0];
01552   i->produced_cargo[1] = indspec->produced_cargo[1];
01553   i->accepts_cargo[0] = indspec->accepts_cargo[0];
01554   i->accepts_cargo[1] = indspec->accepts_cargo[1];
01555   i->accepts_cargo[2] = indspec->accepts_cargo[2];
01556   i->production_rate[0] = indspec->production_rate[0];
01557   i->production_rate[1] = indspec->production_rate[1];
01558 
01559   /* don't use smooth economy for industries using production related callbacks */
01560   if (indspec->UsesSmoothEconomy()) {
01561     i->production_rate[0] = min((RandomRange(256) + 128) * i->production_rate[0] >> 8, 255);
01562     i->production_rate[1] = min((RandomRange(256) + 128) * i->production_rate[1] >> 8, 255);
01563   }
01564 
01565   i->town = t;
01566   i->owner = OWNER_NONE;
01567 
01568   uint16 r = Random();
01569   i->random_colour = GB(r, 0, 4);
01570   i->counter = GB(r, 4, 12);
01571   i->random = initial_random_bits;
01572   i->produced_cargo_waiting[0] = 0;
01573   i->produced_cargo_waiting[1] = 0;
01574   i->incoming_cargo_waiting[0] = 0;
01575   i->incoming_cargo_waiting[1] = 0;
01576   i->incoming_cargo_waiting[2] = 0;
01577   i->this_month_production[0] = 0;
01578   i->this_month_production[1] = 0;
01579   i->this_month_transported[0] = 0;
01580   i->this_month_transported[1] = 0;
01581   i->last_month_pct_transported[0] = 0;
01582   i->last_month_pct_transported[1] = 0;
01583   i->last_month_transported[0] = 0;
01584   i->last_month_transported[1] = 0;
01585   i->was_cargo_delivered = false;
01586   i->last_prod_year = _cur_year;
01587   i->last_month_production[0] = i->production_rate[0] * 8;
01588   i->last_month_production[1] = i->production_rate[1] * 8;
01589   i->founder = founder;
01590 
01591   i->construction_date = _date;
01592   i->construction_type = (_game_mode == GM_EDITOR) ? ICT_SCENARIO_EDITOR :
01593       (_generating_world ? ICT_MAP_GENERATION : ICT_NORMAL_GAMEPLAY);
01594 
01595   /* Adding 1 here makes it conform to specs of var44 of varaction2 for industries
01596    * 0 = created prior of newindustries
01597    * else, chosen layout + 1 */
01598   i->selected_layout = layout + 1;
01599 
01600   if (!_generating_world) i->last_month_production[0] = i->last_month_production[1] = 0;
01601 
01602   i->prod_level = PRODLEVEL_DEFAULT;
01603 
01604   /* Call callbacks after the regular fields got initialised. */
01605 
01606   if (HasBit(indspec->callback_mask, CBM_IND_DECIDE_COLOUR)) {
01607     uint16 res = GetIndustryCallback(CBID_INDUSTRY_DECIDE_COLOUR, 0, 0, i, type, INVALID_TILE);
01608     if (res != CALLBACK_FAILED) i->random_colour = GB(res, 0, 4);
01609   }
01610 
01611   if (HasBit(indspec->callback_mask, CBM_IND_INPUT_CARGO_TYPES)) {
01612     for (uint j = 0; j < lengthof(i->accepts_cargo); j++) i->accepts_cargo[j] = CT_INVALID;
01613     for (uint j = 0; j < lengthof(i->accepts_cargo); j++) {
01614       uint16 res = GetIndustryCallback(CBID_INDUSTRY_INPUT_CARGO_TYPES, j, 0, i, type, INVALID_TILE);
01615       if (res == CALLBACK_FAILED || GB(res, 0, 8) == CT_INVALID) break;
01616       i->accepts_cargo[j] = GetCargoTranslation(GB(res, 0, 8), indspec->grf_prop.grffile);
01617     }
01618   }
01619 
01620   if (HasBit(indspec->callback_mask, CBM_IND_OUTPUT_CARGO_TYPES)) {
01621     for (uint j = 0; j < lengthof(i->produced_cargo); j++) i->produced_cargo[j] = CT_INVALID;
01622     for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
01623       uint16 res = GetIndustryCallback(CBID_INDUSTRY_OUTPUT_CARGO_TYPES, j, 0, i, type, INVALID_TILE);
01624       if (res == CALLBACK_FAILED || GB(res, 0, 8) == CT_INVALID) break;
01625       i->produced_cargo[j] = GetCargoTranslation(GB(res, 0, 8), indspec->grf_prop.grffile);
01626     }
01627   }
01628 
01629   /* Plant the tiles */
01630 
01631   do {
01632     TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
01633 
01634     if (it->gfx != GFX_WATERTILE_SPECIALCHECK) {
01635       i->location.Add(cur_tile);
01636 
01637       WaterClass wc = (IsWaterTile(cur_tile) ? GetWaterClass(cur_tile) : WATER_CLASS_INVALID);
01638 
01639       DoCommand(cur_tile, 0, 0, DC_EXEC | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
01640 
01641       MakeIndustry(cur_tile, i->index, it->gfx, Random(), wc);
01642 
01643       if (_generating_world) {
01644         SetIndustryConstructionCounter(cur_tile, 3);
01645         SetIndustryConstructionStage(cur_tile, 2);
01646       }
01647 
01648       /* it->gfx is stored in the map. But the translated ID cur_gfx is the interesting one */
01649       IndustryGfx cur_gfx = GetTranslatedIndustryTileID(it->gfx);
01650       const IndustryTileSpec *its = GetIndustryTileSpec(cur_gfx);
01651       if (its->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(cur_tile);
01652     }
01653   } while ((++it)->ti.x != -0x80);
01654 
01655   if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
01656     for (uint j = 0; j != 50; j++) PlantRandomFarmField(i);
01657   }
01658   InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, 0);
01659 
01660   Station::RecomputeIndustriesNearForAll();
01661 }
01662 
01679 static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, DoCommandFlag flags, const IndustrySpec *indspec, uint itspec_index, uint32 random_var8f, uint16 random_initial_bits, Owner founder, IndustryAvailabilityCallType creation_type, Industry **ip)
01680 {
01681   assert(itspec_index < indspec->num_table);
01682   const IndustryTileTable *it = indspec->table[itspec_index];
01683   bool custom_shape_check = false;
01684 
01685   *ip = NULL;
01686 
01687   SmallVector<ClearedObjectArea, 1> object_areas(_cleared_object_areas);
01688   CommandCost ret = CheckIfIndustryTilesAreFree(tile, it, itspec_index, type, random_initial_bits, founder, creation_type, &custom_shape_check);
01689   _cleared_object_areas = object_areas;
01690   if (ret.Failed()) return ret;
01691 
01692   if (HasBit(GetIndustrySpec(type)->callback_mask, CBM_IND_LOCATION)) {
01693     ret = CheckIfCallBackAllowsCreation(tile, type, itspec_index, random_var8f, random_initial_bits, founder, creation_type);
01694   } else {
01695     ret = _check_new_industry_procs[indspec->check_proc](tile);
01696   }
01697   if (ret.Failed()) return ret;
01698 
01699   if (!custom_shape_check && _settings_game.game_creation.land_generator == LG_TERRAGENESIS && _generating_world &&
01700       !_ignore_restrictions && !CheckIfCanLevelIndustryPlatform(tile, DC_NO_WATER, it, type)) {
01701     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01702   }
01703 
01704   ret = CheckIfFarEnoughFromConflictingIndustry(tile, type);
01705   if (ret.Failed()) return ret;
01706 
01707   const Town *t = NULL;
01708   ret = FindTownForIndustry(tile, type, &t);
01709   if (ret.Failed()) return ret;
01710   assert(t != NULL);
01711 
01712   ret = CheckIfIndustryIsAllowed(tile, type, t);
01713   if (ret.Failed()) return ret;
01714 
01715   if (!Industry::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_INDUSTRIES);
01716 
01717   if (flags & DC_EXEC) {
01718     *ip = new Industry(tile);
01719     if (!custom_shape_check) CheckIfCanLevelIndustryPlatform(tile, DC_NO_WATER | DC_EXEC, it, type);
01720     DoCreateNewIndustry(*ip, tile, type, it, itspec_index, t, founder, random_initial_bits);
01721   }
01722 
01723   return CommandCost();
01724 }
01725 
01737 CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01738 {
01739   IndustryType it = GB(p1, 0, 8);
01740   if (it >= NUM_INDUSTRYTYPES) return CMD_ERROR;
01741 
01742   const IndustrySpec *indspec = GetIndustrySpec(it);
01743 
01744   /* Check if the to-be built/founded industry is available for this climate. */
01745   if (!indspec->enabled || indspec->num_table == 0) return CMD_ERROR;
01746 
01747   /* If the setting for raw-material industries is not on, you cannot build raw-material industries.
01748    * Raw material industries are industries that do not accept cargo (at least for now) */
01749   if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 0 && indspec->IsRawIndustry()) {
01750     return CMD_ERROR;
01751   }
01752 
01753   if (_game_mode != GM_EDITOR && !CheckIfCallBackAllowsAvailability(it, IACT_USERCREATION)) {
01754     return CMD_ERROR;
01755   }
01756 
01757   Randomizer randomizer;
01758   randomizer.SetSeed(p2);
01759   uint16 random_initial_bits = GB(p2, 0, 16);
01760   uint32 random_var8f = randomizer.Next();
01761   int num_layouts = indspec->num_table;
01762   CommandCost ret = CommandCost(STR_ERROR_SITE_UNSUITABLE);
01763 
01764   Industry *ind = NULL;
01765   if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indspec->IsRawIndustry()) {
01766     if (flags & DC_EXEC) {
01767       /* Prospected industries are build as OWNER_TOWN to not e.g. be build on owned land of the founder */
01768       Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01769       /* Prospecting has a chance to fail, however we cannot guarantee that something can
01770        * be built on the map, so the chance gets lower when the map is fuller, but there
01771        * is nothing we can really do about that. */
01772       if (Random() <= indspec->prospecting_chance) {
01773         for (int i = 0; i < 5000; i++) {
01774           /* We should not have more than one Random() in a function call
01775            * because parameter evaluation order is not guaranteed in the c++ standard
01776            */
01777           tile = RandomTile();
01778           /* Start with a random layout */
01779           int layout = RandomRange(num_layouts);
01780           /* Check now each layout, starting with the random one */
01781           for (int j = 0; j < num_layouts; j++) {
01782             layout = (layout + 1) % num_layouts;
01783             ret = CreateNewIndustryHelper(tile, it, flags, indspec, layout, random_var8f, random_initial_bits, cur_company.GetOriginalValue(), IACT_PROSPECTCREATION, &ind);
01784             if (ret.Succeeded()) break;
01785           }
01786           if (ret.Succeeded()) break;
01787         }
01788       }
01789       cur_company.Restore();
01790     }
01791   } else {
01792     int layout = GB(p1, 8, 8);
01793     if (layout >= num_layouts) return CMD_ERROR;
01794 
01795     /* Check subsequently each layout, starting with the given layout in p1 */
01796     for (int i = 0; i < num_layouts; i++) {
01797       layout = (layout + 1) % num_layouts;
01798       ret = CreateNewIndustryHelper(tile, it, flags, indspec, layout, random_var8f, random_initial_bits, _current_company, IACT_USERCREATION, &ind);
01799       if (ret.Succeeded()) break;
01800     }
01801 
01802     /* If it still failed, there's no suitable layout to build here, return the error */
01803     if (ret.Failed()) return ret;
01804   }
01805 
01806   if ((flags & DC_EXEC) && ind != NULL && _game_mode != GM_EDITOR) {
01807     /* Created a new industry in-game, advertise the event. */
01808     SetDParam(0, indspec->name);
01809     if (indspec->new_industry_text > STR_LAST_STRINGID) {
01810       SetDParam(1, STR_TOWN_NAME);
01811       SetDParam(2, ind->town->index);
01812     } else {
01813       SetDParam(1, ind->town->index);
01814     }
01815     AddIndustryNewsItem(indspec->new_industry_text, NS_INDUSTRY_OPEN, ind->index);
01816     AI::BroadcastNewEvent(new AIEventIndustryOpen(ind->index));
01817   }
01818 
01819   return CommandCost(EXPENSES_OTHER, indspec->GetConstructionCost());
01820 }
01821 
01822 
01830 static Industry *CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAvailabilityCallType creation_type)
01831 {
01832   const IndustrySpec *indspec = GetIndustrySpec(type);
01833 
01834   uint32 seed = Random();
01835   uint32 seed2 = Random();
01836   Industry *i = NULL;
01837   CommandCost ret = CreateNewIndustryHelper(tile, type, DC_EXEC, indspec, RandomRange(indspec->num_table), seed, GB(seed2, 0, 16), OWNER_NONE, creation_type, &i);
01838   assert(i != NULL || ret.Failed());
01839   return i;
01840 }
01841 
01848 static uint32 GetScaledIndustryGenerationProbability(IndustryType it, bool *force_at_least_one)
01849 {
01850   const IndustrySpec *ind_spc = GetIndustrySpec(it);
01851   uint32 chance = ind_spc->appear_creation[_settings_game.game_creation.landscape] * 16; // * 16 to increase precision
01852   if (!ind_spc->enabled || chance == 0 || ind_spc->num_table == 0 ||
01853       !CheckIfCallBackAllowsAvailability(it, IACT_MAPGENERATION) ||
01854       (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY)) {
01855     *force_at_least_one = false;
01856     return 0;
01857   } else {
01858     /* We want industries appearing at coast to appear less often on bigger maps, as length of coast increases slower than map area.
01859      * For simplicity we scale in both cases, though scaling the probabilities of all industries has no effect. */
01860     chance = (ind_spc->check_proc == CHECK_REFINERY || ind_spc->check_proc == CHECK_OIL_RIG) ? ScaleByMapSize1D(chance) : ScaleByMapSize(chance);
01861 
01862     *force_at_least_one = (chance > 0) && !(ind_spc->behaviour & INDUSTRYBEH_NOBUILT_MAPCREATION) && (_game_mode != GM_EDITOR);
01863     return chance;
01864   }
01865 }
01866 
01873 static uint16 GetIndustryGamePlayProbability(IndustryType it, byte *min_number)
01874 {
01875   if (_settings_game.difficulty.industry_density == ID_FUND_ONLY) {
01876     *min_number = 0;
01877     return 0;
01878   }
01879 
01880   const IndustrySpec *ind_spc = GetIndustrySpec(it);
01881   byte chance = ind_spc->appear_ingame[_settings_game.game_creation.landscape];
01882   if (!ind_spc->enabled || chance == 0 || ind_spc->num_table == 0 ||
01883       ((ind_spc->behaviour & INDUSTRYBEH_BEFORE_1950) && _cur_year > 1950) ||
01884       ((ind_spc->behaviour & INDUSTRYBEH_AFTER_1960) && _cur_year < 1960) ||
01885       !CheckIfCallBackAllowsAvailability(it, IACT_RANDOMCREATION)) {
01886     *min_number = 0;
01887     return 0;
01888   }
01889   *min_number = (ind_spc->behaviour & INDUSTRYBEH_CANCLOSE_LASTINSTANCE) ? 1 : 0;
01890   return chance;
01891 }
01892 
01897 static uint GetNumberOfIndustries()
01898 {
01899   /* Number of industries on a 256x256 map. */
01900   static const uint16 numof_industry_table[] = {
01901     0,    // none
01902     0,    // minimal
01903     10,   // very low
01904     25,   // low
01905     55,   // normal
01906     80,   // high
01907   };
01908 
01909   assert(lengthof(numof_industry_table) == ID_END);
01910   uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
01911   return ScaleByMapSize(numof_industry_table[difficulty]);
01912 }
01913 
01918 static void AdvertiseIndustryOpening(const Industry *ind)
01919 {
01920   const IndustrySpec *ind_spc = GetIndustrySpec(ind->type);
01921   SetDParam(0, ind_spc->name);
01922   if (ind_spc->new_industry_text > STR_LAST_STRINGID) {
01923     SetDParam(1, STR_TOWN_NAME);
01924     SetDParam(2, ind->town->index);
01925   } else {
01926     SetDParam(1, ind->town->index);
01927   }
01928   AddIndustryNewsItem(ind_spc->new_industry_text, NS_INDUSTRY_OPEN, ind->index);
01929   AI::BroadcastNewEvent(new AIEventIndustryOpen(ind->index));
01930 }
01931 
01940 static Industry *PlaceIndustry(IndustryType type, IndustryAvailabilityCallType creation_type, bool try_hard)
01941 {
01942   uint tries = try_hard ? 10000u : 2000u;
01943   for (; tries > 0; tries--) {
01944     Industry *ind = CreateNewIndustry(RandomTile(), type, creation_type);
01945     if (ind != NULL) return ind;
01946   }
01947   return NULL;
01948 }
01949 
01955 static void PlaceInitialIndustry(IndustryType type, bool try_hard)
01956 {
01957   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01958 
01959   IncreaseGeneratingWorldProgress(GWP_INDUSTRY);
01960   PlaceIndustry(type, IACT_MAPGENERATION, try_hard);
01961 
01962   cur_company.Restore();
01963 }
01964 
01969 static uint GetCurrentTotalNumberOfIndustries()
01970 {
01971   int total = 0;
01972   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) total += Industry::GetIndustryTypeCount(it);
01973   return total;
01974 }
01975 
01976 
01978 void IndustryTypeBuildData::Reset()
01979 {
01980   this->probability  = 0;
01981   this->min_number   = 0;
01982   this->target_count = 0;
01983   this->max_wait     = 1;
01984   this->wait_count   = 0;
01985 }
01986 
01988 void IndustryBuildData::Reset()
01989 {
01990   this->wanted_inds = GetCurrentTotalNumberOfIndustries() << 16;
01991 
01992   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
01993     this->builddata[it].Reset();
01994   }
01995 }
01996 
01998 void IndustryBuildData::MonthlyLoop()
01999 {
02000   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.
02001   if (_settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // 'no industries' setting,
02002 
02003   /* To prevent running out of unused industries for the player to connect,
02004    * add a fraction of new industries each month, but only if the manager can keep up. */
02005   uint max_behind = 1 + min(99u, ScaleByMapSize(3)); // At most 2 industries for small maps, and 100 at the biggest map (about 6 months industry build attempts).
02006   if (GetCurrentTotalNumberOfIndustries() + max_behind >= (this->wanted_inds >> 16)) {
02007     this->wanted_inds += ScaleByMapSize(NEWINDS_PER_MONTH);
02008   }
02009 }
02010 
02015 void GenerateIndustries()
02016 {
02017   if (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // No industries in the game.
02018 
02019   uint32 industry_probs[NUM_INDUSTRYTYPES];
02020   bool force_at_least_one[NUM_INDUSTRYTYPES];
02021   uint32 total_prob = 0;
02022   uint num_forced = 0;
02023 
02024   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02025     industry_probs[it] = GetScaledIndustryGenerationProbability(it, force_at_least_one + it);
02026     total_prob += industry_probs[it];
02027     if (force_at_least_one[it]) num_forced++;
02028   }
02029 
02030   uint total_amount = GetNumberOfIndustries();
02031   if (total_prob == 0 || total_amount < num_forced) {
02032     /* Only place the forced ones */
02033     total_amount = num_forced;
02034   }
02035 
02036   SetGeneratingWorldProgress(GWP_INDUSTRY, total_amount);
02037 
02038   /* Try to build one industry per type independent of any probabilities */
02039   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02040     if (force_at_least_one[it]) {
02041       assert(total_amount > 0);
02042       total_amount--;
02043       PlaceInitialIndustry(it, true);
02044     }
02045   }
02046 
02047   /* Add the remaining industries according to their probabilities */
02048   for (uint i = 0; i < total_amount; i++) {
02049     uint32 r = RandomRange(total_prob);
02050     IndustryType it = 0;
02051     while (r >= industry_probs[it]) {
02052       r -= industry_probs[it];
02053       it++;
02054       assert(it < NUM_INDUSTRYTYPES);
02055     }
02056     assert(industry_probs[it] > 0);
02057     PlaceInitialIndustry(it, false);
02058   }
02059   _industry_builder.Reset();
02060 }
02061 
02066 static void UpdateIndustryStatistics(Industry *i)
02067 {
02068   for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
02069     if (i->produced_cargo[j] != CT_INVALID) {
02070       byte pct = 0;
02071       if (i->this_month_production[j] != 0) {
02072         i->last_prod_year = _cur_year;
02073         pct = min(i->this_month_transported[j] * 256 / i->this_month_production[j], 255);
02074       }
02075       i->last_month_pct_transported[j] = pct;
02076 
02077       i->last_month_production[j] = i->this_month_production[j];
02078       i->this_month_production[j] = 0;
02079 
02080       i->last_month_transported[j] = i->this_month_transported[j];
02081       i->this_month_transported[j] = 0;
02082     }
02083   }
02084 }
02085 
02090 void Industry::RecomputeProductionMultipliers()
02091 {
02092   const IndustrySpec *indspec = GetIndustrySpec(this->type);
02093   assert(!indspec->UsesSmoothEconomy());
02094 
02095   /* Rates are rounded up, so e.g. oilrig always produces some passengers */
02096   this->production_rate[0] = min(CeilDiv(indspec->production_rate[0] * this->prod_level, PRODLEVEL_DEFAULT), 0xFF);
02097   this->production_rate[1] = min(CeilDiv(indspec->production_rate[1] * this->prod_level, PRODLEVEL_DEFAULT), 0xFF);
02098 }
02099 
02100 
02106 bool IndustryTypeBuildData::GetIndustryTypeData(IndustryType it)
02107 {
02108   byte min_number;
02109   uint32 probability = GetIndustryGamePlayProbability(it, &min_number);
02110   bool changed = min_number != this->min_number || probability != this->probability;
02111   this->min_number = min_number;
02112   this->probability = probability;
02113   return changed;
02114 }
02115 
02117 void IndustryBuildData::SetupTargetCount()
02118 {
02119   bool changed = false;
02120   uint num_planned = 0; // Number of industries planned in the industry build data.
02121   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02122     changed |= this->builddata[it].GetIndustryTypeData(it);
02123     num_planned += this->builddata[it].target_count;
02124   }
02125   uint total_amount = this->wanted_inds >> 16; // Desired total number of industries.
02126   changed |= num_planned != total_amount;
02127   if (!changed) return; // All industries are still the same, no need to re-randomize.
02128 
02129   /* Initialize the target counts. */
02130   uint force_build = 0;  // Number of industries that should always be available.
02131   uint32 total_prob = 0; // Sum of probabilities.
02132   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02133     IndustryTypeBuildData *ibd = this->builddata + it;
02134     force_build += ibd->min_number;
02135     ibd->target_count = ibd->min_number;
02136     total_prob += ibd->probability;
02137   }
02138 
02139   if (total_prob == 0) return; // No buildable industries.
02140 
02141   /* Subtract forced industries from the number of industries available for construction. */
02142   total_amount = (total_amount <= force_build) ? 0 : total_amount - force_build;
02143 
02144   /* Assign number of industries that should be aimed for, by using the probability as a weight. */
02145   while (total_amount > 0) {
02146     uint32 r = RandomRange(total_prob);
02147     IndustryType it = 0;
02148     while (r >= this->builddata[it].probability) {
02149       r -= this->builddata[it].probability;
02150       it++;
02151       assert(it < NUM_INDUSTRYTYPES);
02152     }
02153     assert(this->builddata[it].probability > 0);
02154     this->builddata[it].target_count++;
02155     total_amount--;
02156   }
02157 }
02158 
02162 void IndustryBuildData::TryBuildNewIndustry()
02163 {
02164   this->SetupTargetCount();
02165 
02166   int missing = 0;       // Number of industries that need to be build.
02167   uint count = 0;        // Number of industry types eligible for build.
02168   uint32 total_prob = 0; // Sum of probabilities.
02169   IndustryType forced_build = NUM_INDUSTRYTYPES; // Industry type that should be forcibly build.
02170   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02171     int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it);
02172     missing += difference;
02173     if (this->builddata[it].wait_count > 0) continue; // This type may not be built now.
02174     if (difference > 0) {
02175       if (Industry::GetIndustryTypeCount(it) == 0 && this->builddata[it].min_number > 0) {
02176         /* An industry that should exist at least once, is not available. Force it, trying the most needed one first. */
02177         if (forced_build == NUM_INDUSTRYTYPES ||
02178             difference > this->builddata[forced_build].target_count - Industry::GetIndustryTypeCount(forced_build)) {
02179           forced_build = it;
02180         }
02181       }
02182       total_prob += difference;
02183       count++;
02184     }
02185   }
02186 
02187   if (EconomyIsInRecession() || (forced_build == NUM_INDUSTRYTYPES && (missing <= 0 || total_prob == 0))) count = 0; // Skip creation of an industry.
02188 
02189   if (count >= 1) {
02190     /* If not forced, pick a weighted random industry to build.
02191      * For the case that count == 1, there is no need to draw a random number. */
02192     IndustryType it;
02193     if (forced_build != NUM_INDUSTRYTYPES) {
02194       it = forced_build;
02195     } else {
02196       /* Non-forced, select an industry type to build (weighted random). */
02197       uint32 r = 0; // Initialized to silence the compiler.
02198       if (count > 1) r = RandomRange(total_prob);
02199       for (it = 0; it < NUM_INDUSTRYTYPES; it++) {
02200         if (this->builddata[it].wait_count > 0) continue; // Type may not be built now.
02201         int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it);
02202         if (difference <= 0) continue; // Too many of this kind.
02203         if (count == 1) break;
02204         if (r < (uint)difference) break;
02205         r -= difference;
02206       }
02207       assert(it < NUM_INDUSTRYTYPES && this->builddata[it].target_count > Industry::GetIndustryTypeCount(it));
02208     }
02209 
02210     /* Try to create the industry. */
02211     const Industry *ind = PlaceIndustry(it, IACT_RANDOMCREATION, false);
02212     if (ind == NULL) {
02213       this->builddata[it].wait_count = this->builddata[it].max_wait + 1; // Compensate for decrementing below.
02214       this->builddata[it].max_wait = min(1000, this->builddata[it].max_wait + 2);
02215     } else {
02216       AdvertiseIndustryOpening(ind);
02217       this->builddata[it].max_wait = max(this->builddata[it].max_wait / 2, 1); // Reduce waiting time of the industry type.
02218     }
02219   }
02220 
02221   /* Decrement wait counters. */
02222   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02223     if (this->builddata[it].wait_count > 0) this->builddata[it].wait_count--;
02224   }
02225 }
02226 
02235 static bool CheckIndustryCloseDownProtection(IndustryType type)
02236 {
02237   const IndustrySpec *indspec = GetIndustrySpec(type);
02238 
02239   /* oil wells (or the industries with that flag set) are always allowed to closedown */
02240   if ((indspec->behaviour & INDUSTRYBEH_DONT_INCR_PROD) && _settings_game.game_creation.landscape == LT_TEMPERATE) return false;
02241   return (indspec->behaviour & INDUSTRYBEH_CANCLOSE_LASTINSTANCE) == 0 && Industry::GetIndustryTypeCount(type) <= 1;
02242 }
02243 
02253 static void CanCargoServiceIndustry(CargoID cargo, Industry *ind, bool *c_accepts, bool *c_produces)
02254 {
02255   if (cargo == CT_INVALID) return;
02256 
02257   /* Check for acceptance of cargo */
02258   for (byte j = 0; j < lengthof(ind->accepts_cargo); j++) {
02259     if (cargo == ind->accepts_cargo[j] && !IndustryTemporarilyRefusesCargo(ind, cargo)) {
02260       *c_accepts = true;
02261       break;
02262     }
02263   }
02264 
02265   /* Check for produced cargo */
02266   for (byte j = 0; j < lengthof(ind->produced_cargo); j++) {
02267     if (cargo == ind->produced_cargo[j]) {
02268       *c_produces = true;
02269       break;
02270     }
02271   }
02272 }
02273 
02287 static int WhoCanServiceIndustry(Industry *ind)
02288 {
02289   /* Find all stations within reach of the industry */
02290   StationList stations;
02291   FindStationsAroundTiles(ind->location, &stations);
02292 
02293   if (stations.Length() == 0) return 0; // No stations found at all => nobody services
02294 
02295   const Vehicle *v;
02296   int result = 0;
02297   FOR_ALL_VEHICLES(v) {
02298     /* Is it worthwhile to try this vehicle? */
02299     if (v->owner != _local_company && result != 0) continue;
02300 
02301     /* Check whether it accepts the right kind of cargo */
02302     bool c_accepts = false;
02303     bool c_produces = false;
02304     if (v->type == VEH_TRAIN && v->IsFrontEngine()) {
02305       for (const Vehicle *u = v; u != NULL; u = u->Next()) {
02306         CanCargoServiceIndustry(u->cargo_type, ind, &c_accepts, &c_produces);
02307       }
02308     } else if (v->type == VEH_ROAD || v->type == VEH_SHIP || v->type == VEH_AIRCRAFT) {
02309       CanCargoServiceIndustry(v->cargo_type, ind, &c_accepts, &c_produces);
02310     } else {
02311       continue;
02312     }
02313     if (!c_accepts && !c_produces) continue; // Wrong cargo
02314 
02315     /* Check orders of the vehicle.
02316      * We cannot check the first of shared orders only, since the first vehicle in such a chain
02317      * may have a different cargo type.
02318      */
02319     const Order *o;
02320     FOR_VEHICLE_ORDERS(v, o) {
02321       if (o->IsType(OT_GOTO_STATION) && !(o->GetUnloadType() & OUFB_TRANSFER)) {
02322         /* Vehicle visits a station to load or unload */
02323         Station *st = Station::Get(o->GetDestination());
02324         assert(st != NULL);
02325 
02326         /* Same cargo produced by industry is dropped here => not serviced by vehicle v */
02327         if ((o->GetUnloadType() & OUFB_UNLOAD) && !c_accepts) break;
02328 
02329         if (stations.Contains(st)) {
02330           if (v->owner == _local_company) return 2; // Company services industry
02331           result = 1; // Competitor services industry
02332         }
02333       }
02334     }
02335   }
02336   return result;
02337 }
02338 
02346 static void ReportNewsProductionChangeIndustry(Industry *ind, CargoID type, int percent)
02347 {
02348   NewsSubtype ns;
02349 
02350   switch (WhoCanServiceIndustry(ind)) {
02351     case 0: ns = NS_INDUSTRY_NOBODY;  break;
02352     case 1: ns = NS_INDUSTRY_OTHER;   break;
02353     case 2: ns = NS_INDUSTRY_COMPANY; break;
02354     default: NOT_REACHED();
02355   }
02356   SetDParam(2, abs(percent));
02357   SetDParam(0, CargoSpec::Get(type)->name);
02358   SetDParam(1, ind->index);
02359   AddIndustryNewsItem(
02360     percent >= 0 ? STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_SMOOTH : STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_SMOOTH,
02361     ns,
02362     ind->index
02363   );
02364 }
02365 
02366 static const uint PERCENT_TRANSPORTED_60 = 153;
02367 static const uint PERCENT_TRANSPORTED_80 = 204;
02368 
02374 static void ChangeIndustryProduction(Industry *i, bool monthly)
02375 {
02376   StringID str = STR_NULL;
02377   bool closeit = false;
02378   const IndustrySpec *indspec = GetIndustrySpec(i->type);
02379   bool standard = false;
02380   bool suppress_message = false;
02381   bool recalculate_multipliers = false; 
02382   /* don't use smooth economy for industries using production related callbacks */
02383   bool smooth_economy = indspec->UsesSmoothEconomy();
02384   byte div = 0;
02385   byte mul = 0;
02386   int8 increment = 0;
02387 
02388   bool callback_enabled = HasBit(indspec->callback_mask, monthly ? CBM_IND_MONTHLYPROD_CHANGE : CBM_IND_PRODUCTION_CHANGE);
02389   if (callback_enabled) {
02390     uint16 res = GetIndustryCallback(monthly ? CBID_INDUSTRY_MONTHLYPROD_CHANGE : CBID_INDUSTRY_PRODUCTION_CHANGE, 0, Random(), i, i->type, i->location.tile);
02391     if (res != CALLBACK_FAILED) { // failed callback means "do nothing"
02392       suppress_message = HasBit(res, 7);
02393       /* Get the custom message if any */
02394       if (HasBit(res, 8)) str = MapGRFStringID(indspec->grf_prop.grffile->grfid, GB(GetRegister(0x100), 0, 16));
02395       res = GB(res, 0, 4);
02396       switch (res) {
02397         default: NOT_REACHED();
02398         case 0x0: break;                  // Do nothing, but show the custom message if any
02399         case 0x1: div = 1; break;         // Halve industry production. If production reaches the quarter of the default, the industry is closed instead.
02400         case 0x2: mul = 1; break;         // Double industry production if it hasn't reached eight times of the original yet.
02401         case 0x3: closeit = true; break;  // The industry announces imminent closure, and is physically removed from the map next month.
02402         case 0x4: standard = true; break; // Do the standard random production change as if this industry was a primary one.
02403         case 0x5: case 0x6: case 0x7:     // Divide production by 4, 8, 16
02404         case 0x8: div = res - 0x3; break; // Divide production by 32
02405         case 0x9: case 0xA: case 0xB:     // Multiply production by 4, 8, 16
02406         case 0xC: mul = res - 0x7; break; // Multiply production by 32
02407         case 0xD:                         // decrement production
02408         case 0xE:                         // increment production
02409           increment = res == 0x0D ? -1 : 1;
02410           break;
02411         case 0xF:                         // Set production to third byte of register 0x100
02412           i->prod_level = Clamp(GB(GetRegister(0x100), 16, 8), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
02413           recalculate_multipliers = true;
02414           break;
02415       }
02416     }
02417   } else {
02418     if (monthly != smooth_economy) return;
02419     if (indspec->life_type == INDUSTRYLIFE_BLACK_HOLE) return;
02420   }
02421 
02422   if (standard || (!callback_enabled && (indspec->life_type & (INDUSTRYLIFE_ORGANIC | INDUSTRYLIFE_EXTRACTIVE)) != 0)) {
02423     /* decrease or increase */
02424     bool only_decrease = (indspec->behaviour & INDUSTRYBEH_DONT_INCR_PROD) && _settings_game.game_creation.landscape == LT_TEMPERATE;
02425 
02426     if (smooth_economy) {
02427       closeit = true;
02428       for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
02429         if (i->produced_cargo[j] == CT_INVALID) continue;
02430         uint32 r = Random();
02431         int old_prod, new_prod, percent;
02432         /* If over 60% is transported, mult is 1, else mult is -1. */
02433         int mult = (i->last_month_pct_transported[j] > PERCENT_TRANSPORTED_60) ? 1 : -1;
02434 
02435         new_prod = old_prod = i->production_rate[j];
02436 
02437         /* For industries with only_decrease flags (temperate terrain Oil Wells),
02438          * the multiplier will always be -1 so they will only decrease. */
02439         if (only_decrease) {
02440           mult = -1;
02441         /* For normal industries, if over 60% is transported, 33% chance for decrease.
02442          * Bonus for very high station ratings (over 80%): 16% chance for decrease. */
02443         } else if (Chance16I(1, ((i->last_month_pct_transported[j] > PERCENT_TRANSPORTED_80) ? 6 : 3), r)) {
02444           mult *= -1;
02445         }
02446 
02447         /* 4.5% chance for 3-23% (or 1 unit for very low productions) production change,
02448          * determined by mult value. If mult = 1 prod. increases, else (-1) it decreases. */
02449         if (Chance16I(1, 22, r >> 16)) {
02450           new_prod += mult * (max(((RandomRange(50) + 10) * old_prod) >> 8, 1U));
02451         }
02452 
02453         /* Prevent production to overflow or Oil Rig passengers to be over-"produced" */
02454         new_prod = Clamp(new_prod, 1, 255);
02455 
02456         if (((indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) && j == 1) {
02457           new_prod = Clamp(new_prod, 0, 16);
02458         }
02459 
02460         /* Do not stop closing the industry when it has the lowest possible production rate */
02461         if (new_prod == old_prod && old_prod > 1) {
02462           closeit = false;
02463           continue;
02464         }
02465 
02466         percent = (old_prod == 0) ? 100 : (new_prod * 100 / old_prod - 100);
02467         i->production_rate[j] = new_prod;
02468 
02469         /* Close the industry when it has the lowest possible production rate */
02470         if (new_prod > 1) closeit = false;
02471 
02472         if (abs(percent) >= 10) {
02473           ReportNewsProductionChangeIndustry(i, i->produced_cargo[j], percent);
02474         }
02475       }
02476     } else {
02477       if (only_decrease || Chance16(1, 3)) {
02478         /* If more than 60% transported, 66% chance of increase, else 33% chance of increase */
02479         if (!only_decrease && (i->last_month_pct_transported[0] > PERCENT_TRANSPORTED_60) != Chance16(1, 3)) {
02480           mul = 1; // Increase production
02481         } else {
02482           div = 1; // Decrease production
02483         }
02484       }
02485     }
02486   }
02487 
02488   if (!callback_enabled && (indspec->life_type & INDUSTRYLIFE_PROCESSING)) {
02489     if ( (byte)(_cur_year - i->last_prod_year) >= 5 && Chance16(1, smooth_economy ? 180 : 2)) {
02490       closeit = true;
02491     }
02492   }
02493 
02494   /* Increase if needed */
02495   while (mul-- != 0 && i->prod_level < PRODLEVEL_MAXIMUM) {
02496     i->prod_level = min(i->prod_level * 2, PRODLEVEL_MAXIMUM);
02497     recalculate_multipliers = true;
02498     if (str == STR_NULL) str = indspec->production_up_text;
02499   }
02500 
02501   /* Decrease if needed */
02502   while (div-- != 0 && !closeit) {
02503     if (i->prod_level == PRODLEVEL_MINIMUM) {
02504       closeit = true;
02505     } else {
02506       i->prod_level = max(i->prod_level / 2, (int)PRODLEVEL_MINIMUM); // typecast to int required to please MSVC
02507       recalculate_multipliers = true;
02508       if (str == STR_NULL) str = indspec->production_down_text;
02509     }
02510   }
02511 
02512   /* Increase or Decreasing the production level if needed */
02513   if (increment != 0) {
02514     if (increment < 0 && i->prod_level == PRODLEVEL_MINIMUM) {
02515       closeit = true;
02516     } else {
02517       i->prod_level = ClampU(i->prod_level + increment, PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
02518       recalculate_multipliers = true;
02519     }
02520   }
02521 
02522   /* Recalculate production_rate
02523    * For non-smooth economy these should always be synchronized with prod_level */
02524   if (recalculate_multipliers) i->RecomputeProductionMultipliers();
02525 
02526   /* Close if needed and allowed */
02527   if (closeit && !CheckIndustryCloseDownProtection(i->type)) {
02528     i->prod_level = PRODLEVEL_CLOSURE;
02529     str = indspec->closure_text;
02530   }
02531 
02532   if (!suppress_message && str != STR_NULL) {
02533     NewsSubtype ns;
02534     /* Compute news category */
02535     if (closeit) {
02536       ns = NS_INDUSTRY_CLOSE;
02537       AI::BroadcastNewEvent(new AIEventIndustryClose(i->index));
02538     } else {
02539       switch (WhoCanServiceIndustry(i)) {
02540         case 0: ns = NS_INDUSTRY_NOBODY;  break;
02541         case 1: ns = NS_INDUSTRY_OTHER;   break;
02542         case 2: ns = NS_INDUSTRY_COMPANY; break;
02543         default: NOT_REACHED();
02544       }
02545     }
02546     /* Set parameters of news string */
02547     if (str > STR_LAST_STRINGID) {
02548       SetDParam(0, STR_TOWN_NAME);
02549       SetDParam(1, i->town->index);
02550       SetDParam(2, indspec->name);
02551     } else if (closeit) {
02552       SetDParam(0, STR_FORMAT_INDUSTRY_NAME);
02553       SetDParam(1, i->town->index);
02554       SetDParam(2, indspec->name);
02555     } else {
02556       SetDParam(0, i->index);
02557     }
02558     /* and report the news to the user */
02559     AddNewsItem(str,
02560       ns,
02561       closeit ? NR_TILE : NR_INDUSTRY,
02562       closeit ? i->location.tile + TileDiffXY(1, 1) : i->index);
02563   }
02564 }
02565 
02573 void IndustryDailyLoop()
02574 {
02575   _economy.industry_daily_change_counter += _economy.industry_daily_increment;
02576 
02577   /* Bits 16-31 of industry_construction_counter contain the number of industries to change/create today,
02578    * the lower 16 bit are a fractional part that might accumulate over several days until it
02579    * is sufficient for an industry. */
02580   uint16 change_loop = _economy.industry_daily_change_counter >> 16;
02581 
02582   /* Reset the active part of the counter, just keeping the "factional part" */
02583   _economy.industry_daily_change_counter &= 0xFFFF;
02584 
02585   if (change_loop == 0) {
02586     return;  // Nothing to do? get out
02587   }
02588 
02589   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02590 
02591   /* perform the required industry changes for the day */
02592 
02593   uint perc = 3; // Between 3% and 9% chance of creating a new industry.
02594   if ((_industry_builder.wanted_inds >> 16) > GetCurrentTotalNumberOfIndustries()) {
02595     perc = min(9u, perc + (_industry_builder.wanted_inds >> 16) - GetCurrentTotalNumberOfIndustries());
02596   }
02597   for (uint16 j = 0; j < change_loop; j++) {
02598     if (Chance16(perc, 100)) {
02599       _industry_builder.TryBuildNewIndustry();
02600     } else {
02601       Industry *i = Industry::GetRandom();
02602       if (i != NULL) {
02603         ChangeIndustryProduction(i, false);
02604         SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
02605       }
02606     }
02607   }
02608 
02609   cur_company.Restore();
02610 
02611   /* production-change */
02612   InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, 1);
02613 }
02614 
02615 void IndustryMonthlyLoop()
02616 {
02617   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02618 
02619   _industry_builder.MonthlyLoop();
02620 
02621   Industry *i;
02622   FOR_ALL_INDUSTRIES(i) {
02623     UpdateIndustryStatistics(i);
02624     if (i->prod_level == PRODLEVEL_CLOSURE) {
02625       delete i;
02626     } else {
02627       ChangeIndustryProduction(i, true);
02628       SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
02629     }
02630   }
02631 
02632   cur_company.Restore();
02633 
02634   /* production-change */
02635   InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, 1);
02636 }
02637 
02638 
02639 void InitializeIndustries()
02640 {
02641   _industry_pool.CleanPool();
02642 
02643   Industry::ResetIndustryCounts();
02644   _industry_sound_tile = 0;
02645 
02646   _industry_builder.Reset();
02647 }
02648 
02653 bool IndustrySpec::IsRawIndustry() const
02654 {
02655   /* Lumber mills are extractive/organic, but can always be built like a non-raw industry */
02656   return (this->life_type & (INDUSTRYLIFE_EXTRACTIVE | INDUSTRYLIFE_ORGANIC)) != 0 &&
02657       (this->behaviour & INDUSTRYBEH_CUT_TREES) == 0;
02658 }
02659 
02664 Money IndustrySpec::GetConstructionCost() const
02665 {
02666   /* Building raw industries like secondary uses different price base */
02667   return (_price[(_settings_game.construction.raw_industry_construction == 1 && this->IsRawIndustry()) ?
02668       PR_BUILD_INDUSTRY_RAW : PR_BUILD_INDUSTRY] * this->cost_multiplier) >> 8;
02669 }
02670 
02677 Money IndustrySpec::GetRemovalCost() const
02678 {
02679   return (_price[PR_CLEAR_INDUSTRY] * this->removal_cost_multiplier) >> 8;
02680 }
02681 
02686 bool IndustrySpec::UsesSmoothEconomy() const
02687 {
02688   return _settings_game.economy.smooth_economy &&
02689     !(HasBit(this->callback_mask, CBM_IND_PRODUCTION_256_TICKS) || HasBit(this->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) && // production callbacks
02690     !(HasBit(this->callback_mask, CBM_IND_MONTHLYPROD_CHANGE) || HasBit(this->callback_mask, CBM_IND_PRODUCTION_CHANGE));            // production change callbacks
02691 }
02692 
02693 static CommandCost TerraformTile_Industry(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
02694 {
02695   if (AutoslopeEnabled()) {
02696     /* We imitate here TTDP's behaviour:
02697      *  - Both new and old slope must not be steep.
02698      *  - TileMaxZ must not be changed.
02699      *  - Allow autoslope by default.
02700      *  - Disallow autoslope if callback succeeds and returns non-zero.
02701      */
02702     Slope tileh_old = GetTileSlope(tile, NULL);
02703     /* TileMaxZ must not be changed. Slopes must not be steep. */
02704     if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
02705       const IndustryGfx gfx = GetIndustryGfx(tile);
02706       const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
02707 
02708       /* Call callback 3C 'disable autosloping for industry tiles'. */
02709       if (HasBit(itspec->callback_mask, CBM_INDT_AUTOSLOPE)) {
02710         /* If the callback fails, allow autoslope. */
02711         uint16 res = GetIndustryTileCallback(CBID_INDTILE_AUTOSLOPE, 0, 0, gfx, Industry::GetByTile(tile), tile);
02712         if ((res == 0) || (res == CALLBACK_FAILED)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
02713       } else {
02714         /* allow autoslope */
02715         return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
02716       }
02717     }
02718   }
02719   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02720 }
02721 
02722 extern const TileTypeProcs _tile_type_industry_procs = {
02723   DrawTile_Industry,           // draw_tile_proc
02724   GetSlopeZ_Industry,          // get_slope_z_proc
02725   ClearTile_Industry,          // clear_tile_proc
02726   AddAcceptedCargo_Industry,   // add_accepted_cargo_proc
02727   GetTileDesc_Industry,        // get_tile_desc_proc
02728   GetTileTrackStatus_Industry, // get_tile_track_status_proc
02729   ClickTile_Industry,          // click_tile_proc
02730   AnimateTile_Industry,        // animate_tile_proc
02731   TileLoop_Industry,           // tile_loop_proc
02732   ChangeTileOwner_Industry,    // change_tile_owner_proc
02733   NULL,                        // add_produced_cargo_proc
02734   NULL,                        // vehicle_enter_tile_proc
02735   GetFoundation_Industry,      // get_foundation_proc
02736   TerraformTile_Industry,      // terraform_tile_proc
02737 };

Generated on Thu Apr 14 00:48:13 2011 for OpenTTD by  doxygen 1.6.1