24 #include "table/strings.h"
42 if (grf_type == IT_INVALID)
return IT_INVALID;
43 if (!
HasBit(grf_type, 7))
return GB(grf_type, 0, 7);
45 return _industry_mngr.
GetID(
GB(grf_type, 0, 7), grf_id);
69 return 0xFF << 8 | gfx;
89 return 0xFF << 8 | indtsp->
grf_prop.subst_id;
92 static uint32_t GetClosestIndustry(
TileIndex tile, IndustryType type,
const Industry *current)
94 uint32_t best_dist = UINT32_MAX;
96 if (i->type != type || i == current)
continue;
117 IndustryType ind_index;
118 uint32_t closest_dist = UINT32_MAX;
124 ind_index = param_setID;
140 if (layout_filter == 0 && !town_filter) {
143 closest_dist = GetClosestIndustry(current->
location.
tile, ind_index, current);
149 if (i->type == ind_index && i != current && (i->selected_layout == layout_filter || layout_filter == 0) && (!town_filter || i->town == current->
town)) {
156 return count << 16 |
GB(closest_dist, 0, 16);
165 case 0x80:
return this->tile.base();
166 case 0x81:
return GB(this->tile.base(), 8, 8);
172 case 0x85:
Debug(grf, 0,
"NewGRFs shouldn't be doing pointer magic");
break;
203 Debug(grf, 1,
"Unhandled variable 0x{:X} (no available industry) in callback 0x{:x}", variable, this->
ro.
callback);
241 const Livery *l = &c->livery[LS_DEFAULT];
247 return this->
industry->
founder | (is_ai ? 0x10000 : 0) | (colours << 24);
301 uint8_t layout_filter = 0;
302 bool town_filter =
false;
303 if (variable == 0x68) {
305 layout_filter =
GB(reg, 0, 8);
306 town_filter =
HasBit(reg, 8);
323 case 0x69:
return it->waiting;
324 case 0x6A:
return it->history[THIS_MONTH].production;
325 case 0x6B:
return it->history[THIS_MONTH].transported;
326 case 0x6C:
return it->history[LAST_MONTH].production;
327 case 0x6D:
return it->history[LAST_MONTH].transported;
328 case 0x70:
return it->rate;
329 case 0x71:
return it->history[LAST_MONTH].PctTransported();
330 default: NOT_REACHED();
341 if (variable == 0x6E)
return it->last_accepted.base();
342 if (variable == 0x6F)
return it->waiting;
356 case 0x85:
Debug(grf, 0,
"NewGRFs shouldn't be doing pointer magic");
break;
408 auto it = std::max_element(std::begin(this->
industry->
accepted), std::end(this->industry->accepted), [](
const auto &a,
const auto &b) { return a.last_accepted < b.last_accepted; });
413 Debug(grf, 1,
"Unhandled industry variable 0x{:X}", variable);
435 if (value == 0)
return;
469 CallbackID callback, uint32_t callback_param1, uint32_t callback_param2)
471 industries_scope(*this, tile, indus, type, random_bits)
484 bool readonly =
true;
491 if (t ==
nullptr)
return nullptr;
499 return GSF_INDUSTRIES;
520 return object.ResolveCallback();
539 ind.
index = INVALID_INDUSTRY;
545 ind.
random = initial_random_bits;
550 uint16_t result =
object.ResolveCallback();
574 if (res != 0) default_prob = 0;
579 }
else if (res > 0x100) {
588 static int32_t DerefIndProd(
int field,
bool use_register)
590 return use_register ? (int32_t)
GetRegister(field) : field;
605 object.callback_param2 = reason;
607 for (uint loop = 0;; loop++) {
610 if (loop >= 0x10000) {
620 SB(
object.callback_param2, 8, 16, loop);
622 if (tgroup ==
nullptr || tgroup->type != SGT_INDUSTRY_PRODUCTION)
break;
636 bool deref = (group->
version >= 1);
646 ind->
produced[i].waiting = ClampTo<uint16_t>(ind->
produced[i].waiting + std::max(DerefIndProd(group->
add_output[i], deref), 0) * multiplier);
650 for (uint i = 0; i < group->
num_input; i++) {
652 if (it == std::end(ind->
accepted))
continue;
653 it->waiting = ClampTo<uint16_t>(it->waiting - DerefIndProd(group->
subtract_input[i], deref) * multiplier);
655 for (uint i = 0; i < group->
num_output; i++) {
657 if (it == std::end(ind->
produced))
continue;
658 it->waiting = ClampTo<uint16_t>(it->waiting + std::max(DerefIndProd(group->
add_output[i], deref), 0) * multiplier);
662 int32_t again = DerefIndProd(group->again, deref);
663 if (again == 0)
break;
665 SB(
object.callback_param2, 24, 8, again);
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
uint8_t CargoID
Cargo slots to indicate a cargo type within a game.
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Common return value for all commands.
uint16_t GetID(uint16_t grf_local_id, uint32_t grfid) const override
Return the ID (if ever available) of a previously inserted entity.
static constexpr TimerGame< struct Economy >::Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
The date of the first day of the original base year.
Definition of stuff that is very close to a company, like the company struct itself.
Owner
Enum for all companies/owners.
Functions related to debugging.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Functions related to errors.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
@ WL_WARNING
Other information.
const IndustryTileSpec * GetIndustryTileSpec(IndustryGfx gfx)
Accessor for array _industry_tile_specs.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
IndustryGfx GetCleanIndustryGfx(Tile t)
Get the industry graphics ID for the given industry tile as stored in the without translation.
uint8_t GetIndustryRandomBits(Tile tile)
Get the random bits for this tile.
static const IndustryGfx NEW_INDUSTRYTILEOFFSET
original number of tiles
static const IndustryType NEW_INDUSTRYOFFSET
original number of industry types
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like INV...
static const IndustryType INVALID_INDUSTRYTYPE
one above amount is considered invalid
static const IndustryGfx INVALID_INDUSTRYTILE
one above amount is considered invalid
static const IndustryGfx NUM_INDUSTRYTILES
total number of industry tiles, new and old
@ INDUSTRYBEH_PROD_MULTI_HNDLING
Automatic production multiplier handling.
@ INDUSTRYBEH_PRODCALLBACK_RANDOM
Production callback needs random bits in var 10.
@ INDUSTRYBEH_BUILT_ONWATER
is built on water (oil rig)
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
@ CBM_IND_PROBABILITY
industry availability/probability callback
@ CBM_IND_REFUSE_CARGO
option out of accepting cargo
@ CBM_IND_PRODUCTION_CARGO_ARRIVAL
call production callback when cargo arrives at the industry
@ CBM_IND_PRODUCTION_256_TICKS
call production callback every 256 ticks
CallbackID
List of implemented NewGRF callbacks.
@ CBID_INDUSTRY_PROBABILITY
Called to determine if the given industry type is available.
@ CBID_INDUSTRY_REFUSE_CARGO
Called to determine if the industry can still accept or refuse more cargo arrival.
@ CBID_INDUSTRY_LOCATION
Called to determine if the given industry can be built on specific area.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
CargoID GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Cargo support for NewGRFs.
CommandCost GetErrorMessageFromLocationCallbackResult(uint16_t cb_res, const GRFFile *grffile, StringID default_error)
Get the error message from a shape/location/slope check callback result.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
uint32_t GetTerrainType(TileIndex tile, TileContext context)
Function used by houses (and soon industries) to get information on type of "terrain" the tile it is ...
TileIndex GetNearbyTile(uint8_t parameter, TileIndex tile, bool signed_offsets, Axis axis)
Get the tile at the given offset.
uint32_t GetIndustryIDAtOffset(TileIndex tile, const Industry *i, uint32_t cur_grfid)
Make an analysis of a tile and check for its belonging to the same industry, and/or the same grf file...
static const GRFFile * GetGrffile(IndustryType type)
Get the grf file associated with the given industry type.
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32_t grf_id)
Map the GRF local type to an industry type.
static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t param_setID, uint8_t layout_filter, bool town_filter, const Industry *current)
Implementation of both var 67 and 68 since the mechanism is almost the same, it is easier to regroup ...
CommandCost CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, size_t layout, uint32_t seed, uint16_t initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type)
Check that the industry callback allows creation of the industry.
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
void IndustryProductionCallback(Industry *ind, int reason)
Get the industry production callback and apply it to the industry.
uint32_t GetIndustryProbabilityCallback(IndustryType type, IndustryAvailabilityCallType creation_type, uint32_t default_prob)
Check with callback CBID_INDUSTRY_PROBABILITY whether the industry can be built.
uint16_t GetIndustryCallback(CallbackID callback, uint32_t param1, uint32_t param2, Industry *industry, IndustryType type, TileIndex tile)
Perform an industry callback.
Functions for NewGRF industries.
IndustryAvailabilityCallType
From where has callback CBID_INDUSTRY_PROBABILITY been called.
uint32_t GetNearbyIndustryTileInformation(uint8_t parameter, TileIndex tile, IndustryID index, bool signed_offsets, bool grf_version8)
Based on newhouses equivalent, but adapted for newindustries.
uint32_t GetRegister(uint i)
Gets the value of a so-called newgrf "register".
Functions to handle the town part of NewGRF towns.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Functions related to OTTD's strings.
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
uint16_t local_id
id defined by the grf file for this entity
const struct GRFFile * grffile
grf file that introduced this entity
std::array< const struct SpriteGroup *, Tcnt > spritegroup
pointers to the different sprites of the entity
uint16_t override
id of the entity been replaced by
Dynamic data of a loaded NewGRF.
std::array< uint8_t, NUM_CARGO > cargo_map
Inverse cargo translation table (CargoID -> local ID)
IndustriesResolverObject(TileIndex tile, Industry *indus, IndustryType type, uint32_t random_bits=0, CallbackID callback=CBID_NO_CALLBACK, uint32_t callback_param1=0, uint32_t callback_param2=0)
Constructor of the industries resolver.
std::optional< TownScopeResolver > town_scope
Scope resolver for the associated town (if needed and available, else std::nullopt).
TownScopeResolver * GetTown()
Get or create the town scope object associated with the industry.
GrfSpecFeature GetFeature() const override
Get the feature number being resolved for.
uint32_t GetDebugID() const override
Get an identifier for the item being resolved.
IndustriesScopeResolver industries_scope
Scope resolver for the industry.
uint32_t GetTriggers() const override
Get the triggers.
uint32_t GetVariable(uint8_t variable, [[maybe_unused]] uint32_t parameter, bool &available) const override
Get a variable value.
IndustryType type
Type of the industry.
uint32_t random_bits
Random bits of the new industry.
uint32_t GetRandomBits() const override
Get a few random bits.
void StorePSA(uint pos, int32_t value) override
Store a value into the persistent storage area (PSA).
TileIndex tile
Tile owned by the industry.
Industry * industry
Industry being resolved.
uint16_t add_output[INDUSTRY_NUM_OUTPUTS]
Add this much output cargo when successful (unsigned, is indirect in cb version 1+)
CargoID cargo_input[INDUSTRY_NUM_INPUTS]
Which input cargoes to take from (only cb version 2)
uint8_t num_input
How many subtract_input values are valid.
int16_t subtract_input[INDUSTRY_NUM_INPUTS]
Take this much of the input cargo (can be negative, is indirect in cb version 1+)
uint8_t version
Production callback version used, or 0xFF if marked invalid.
uint8_t num_output
How many add_output values are valid.
CargoID cargo_output[INDUSTRY_NUM_OUTPUTS]
Which output cargoes to add to (only cb version 2)
Defines the data structure for constructing industry.
uint16_t callback_mask
Bitmask of industry callbacks that have to be called.
StringID name
Displayed name of the industry.
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
GRFFileProps grf_prop
properties related to the grf file
Defines the data structure of each individual tile of an industry.
GRFFileProps grf_prop
properties related to the grf file
uint16_t waiting
Amount of cargo waiting to processed.
uint16_t waiting
Amount of cargo produced.
std::array< ProducedHistory, 25 > history
History of cargo produced and transported for this month and 24 previous months.
uint8_t rate
Production rate.
Defines the internal data of a functional industry.
IndustryType type
type of industry.
TimerGameCalendar::Date construction_date
Date of the construction of the industry.
IndustryControlFlags ctlflags
flags overriding standard behaviours
bool IsCargoAccepted() const
Test if this industry accepts any cargo.
PersistentStorage * psa
Persistent storage for NewGRF industries.
uint8_t prod_level
general production level
Colours random_colour
randomized colour of the industry, for display purpose
AcceptedCargoes::iterator GetCargoAccepted(CargoID cargo)
Get accepted cargo slot for a specific cargo type.
uint8_t construction_type
Way the industry was constructed (.
TimerGameEconomy::Year last_prod_year
last economy year of production
ProducedCargoes produced
produced cargo slots
uint16_t random
Random value used for randomisation of all kinds of things.
Owner founder
Founder of the industry.
uint8_t selected_layout
Which tile layout was used when creating the industry.
AcceptedCargoes accepted
accepted cargo slots
static uint16_t GetIndustryTypeCount(IndustryType type)
Get the count of industries for this type.
TileArea location
Location of the industry.
const ProducedCargo & GetProduced(size_t slot) const
Safely get a produced cargo slot, or an empty data if the slot does not exist.
uint16_t counter
used for animation and/or production (if available cargo)
ProducedCargoes::iterator GetCargoProduced(CargoID cargo)
Get produced cargo slot for a specific cargo type.
uint8_t was_cargo_delivered
flag that indicate this has been the closest industry chosen for cargo delivery by a station....
bool TileBelongsToIndustry(TileIndex tile) const
Check if a given tile belongs to this industry.
const AcceptedCargo & GetAccepted(size_t slot) const
Safely get an accepted cargo slot, or an empty data if the slot does not exist.
Information about a particular livery.
Colours colour2
Second colour, for vehicles with 2CC support.
Colours colour1
First colour, for all vehicles.
uint16_t w
The width of the area.
TileIndex tile
The base tile of the area.
uint16_t h
The height of the area.
TYPE GetValue(uint pos) const
Gets the value from a given position.
void StoreValue(uint pos, int32_t value)
Stores some value at a given position.
Class for pooled persistent storage of data.
Tindex index
Index of this pool item.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Interface for SpriteGroup-s to access the gamestate.
const GRFFile * grffile
GRFFile the resolved SpriteGroup belongs to.
CallbackID callback
Callback being resolved.
const SpriteGroup * root_spritegroup
Root SpriteGroup to use for resolving.
ResolverObject & ro
Surrounding resolver object.
virtual const SpriteGroup * Resolve([[maybe_unused]] ResolverObject &object) const
Base sprite group resolver.
Scope resolver for a town.
TileIndex xy
town center tile
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
uint8_t GetAnimationFrame(Tile t)
Get the current animation frame.
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_BASE.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition of the game-calendar-timer.
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Window functions not directly related to making/drawing windows.
@ WC_INDUSTRY_VIEW
Industry view; Window numbers: