1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
8 /** @file industry.h Base of all industries. */
9 
10 #ifndef INDUSTRY_H
11 #define INDUSTRY_H
12 
13 #include "newgrf_storage.h"
14 #include "subsidy_type.h"
15 #include "industry_map.h"
16 #include "industrytype.h"
17 #include "tilearea_type.h"
18 #include "station_base.h"
19 
20 
21 typedef Pool<Industry, IndustryID, 64, 64000> IndustryPool;
22 extern IndustryPool _industry_pool;
23 
24 /**
25  * Production level maximum, minimum and default values.
26  * It is not a value been really used in order to change, but rather an indicator
27  * of how the industry is behaving.
28  */
29 enum ProductionLevels {
30 	PRODLEVEL_CLOSURE = 0x00,  ///< signal set to actually close the industry
31 	PRODLEVEL_MINIMUM = 0x04,  ///< below this level, the industry is set to be closing
32 	PRODLEVEL_DEFAULT = 0x10,  ///< default level set when the industry is created
33 	PRODLEVEL_MAXIMUM = 0x80,  ///< the industry is running at full speed
34 };
35 
36 enum class IndustryAction : byte {
37 	SetControlFlags = 0,       ///< Set IndustryControlFlags
38 	SetExclusiveSupplier = 1,  ///< Set exclusive supplier
39 	SetExclusiveConsumer = 2,  ///< Set exclusive consumer
40 	SetText = 3,               ///< Set additional text
41 };
42 
43 /**
44  * Flags to control/override the behaviour of an industry.
45  * These flags are controlled by game scripts.
46  */
47 enum IndustryControlFlags : byte {
48 	/** No flags in effect */
49 	INDCTL_NONE                   = 0,
50 	/** When industry production change is evaluated, rolls to decrease are ignored. */
51 	INDCTL_NO_PRODUCTION_DECREASE = 1 << 0,
52 	/** When industry production change is evaluated, rolls to increase are ignored. */
53 	INDCTL_NO_PRODUCTION_INCREASE = 1 << 1,
54 	/**
55 	 * Industry can not close regardless of production level or time since last delivery.
56 	 * This does not prevent a closure already announced. */
57 	INDCTL_NO_CLOSURE             = 1 << 2,
58 	/** Mask of all flags set */
59 	INDCTL_MASK = INDCTL_NO_PRODUCTION_DECREASE | INDCTL_NO_PRODUCTION_INCREASE | INDCTL_NO_CLOSURE,
60 };
61 DECLARE_ENUM_AS_BIT_SET(IndustryControlFlags);
62 
63 /**
64  * Defines the internal data of a functional industry.
65  */
66 struct Industry : IndustryPool::PoolItem<&_industry_pool> {
67 	TileArea location;                                     ///< Location of the industry
68 	Town *town;                                            ///< Nearest town
69 	Station *neutral_station;                              ///< Associated neutral station
70 	CargoID produced_cargo[INDUSTRY_NUM_OUTPUTS];          ///< 16 production cargo slots
71 	uint16 produced_cargo_waiting[INDUSTRY_NUM_OUTPUTS];   ///< amount of cargo produced per cargo
72 	uint16 incoming_cargo_waiting[INDUSTRY_NUM_INPUTS];    ///< incoming cargo waiting to be processed
73 	byte production_rate[INDUSTRY_NUM_OUTPUTS];            ///< production rate for each cargo
74 	byte prod_level;                                       ///< general production level
75 	CargoID accepts_cargo[INDUSTRY_NUM_INPUTS];            ///< 16 input cargo slots
76 	uint16 this_month_production[INDUSTRY_NUM_OUTPUTS];    ///< stats of this month's production per cargo
77 	uint16 this_month_transported[INDUSTRY_NUM_OUTPUTS];   ///< stats of this month's transport per cargo
78 	byte last_month_pct_transported[INDUSTRY_NUM_OUTPUTS]; ///< percentage transported per cargo in the last full month
79 	uint16 last_month_production[INDUSTRY_NUM_OUTPUTS];    ///< total units produced per cargo in the last full month
80 	uint16 last_month_transported[INDUSTRY_NUM_OUTPUTS];   ///< total units transported per cargo in the last full month
81 	uint16 counter;                                        ///< used for animation and/or production (if available cargo)
82 
83 	IndustryType type;             ///< type of industry.
84 	Owner owner;                   ///< owner of the industry.  Which SHOULD always be (imho) OWNER_NONE
85 	byte random_colour;            ///< randomized colour of the industry, for display purpose
86 	Year last_prod_year;           ///< last year of production
87 	byte was_cargo_delivered;      ///< flag that indicate this has been the closest industry chosen for cargo delivery by a station. see DeliverGoodsToIndustry
88 	IndustryControlFlags ctlflags; ///< flags overriding standard behaviours
89 
90 	PartOfSubsidy part_of_subsidy; ///< NOSAVE: is this industry a source/destination of a subsidy?
91 	StationList stations_near;     ///< NOSAVE: List of nearby stations.
92 	mutable std::string cached_name; ///< NOSAVE: Cache of the resolved name of the industry
93 
94 	Owner founder;                 ///< Founder of the industry
95 	Date construction_date;        ///< Date of the construction of the industry
96 	uint8 construction_type;       ///< Way the industry was constructed (@see IndustryConstructionType)
97 	Date last_cargo_accepted_at[INDUSTRY_NUM_INPUTS]; ///< Last day each cargo type was accepted by this industry
98 	byte selected_layout;          ///< Which tile layout was used when creating the industry
99 	Owner exclusive_supplier;      ///< Which company has exclusive rights to deliver cargo (INVALID_OWNER = anyone)
100 	Owner exclusive_consumer;      ///< Which company has exclusive rights to take cargo (INVALID_OWNER = anyone)
101 	std::string text;              ///< General text with additional information.
102 
103 	uint16 random;                 ///< Random value used for randomisation of all kinds of things
104 
105 	PersistentStorage *psa;        ///< Persistent storage for NewGRF industries.
106 
107 	Industry(TileIndex tile = INVALID_TILE) : location(tile, 0, 0) {}
108 	~Industry();
109 
110 	void RecomputeProductionMultipliers();
111 
112 	/**
113 	 * Check if a given tile belongs to this industry.
114 	 * @param tile The tile to check.
115 	 * @return True if the tile is part of this industry.
116 	 */
TileBelongsToIndustryIndustry117 	inline bool TileBelongsToIndustry(TileIndex tile) const
118 	{
119 		return IsTileType(tile, MP_INDUSTRY) && GetIndustryIndex(tile) == this->index;
120 	}
121 
GetCargoProducedIndexIndustry122 	inline int GetCargoProducedIndex(CargoID cargo) const
123 	{
124 		if (cargo == CT_INVALID) return -1;
125 		const CargoID *pos = std::find(this->produced_cargo, endof(this->produced_cargo), cargo);
126 		if (pos == endof(this->produced_cargo)) return -1;
127 		return pos - this->produced_cargo;
128 	}
129 
GetCargoAcceptedIndexIndustry130 	inline int GetCargoAcceptedIndex(CargoID cargo) const
131 	{
132 		if (cargo == CT_INVALID) return -1;
133 		const CargoID *pos = std::find(this->accepts_cargo, endof(this->accepts_cargo), cargo);
134 		if (pos == endof(this->accepts_cargo)) return -1;
135 		return pos - this->accepts_cargo;
136 	}
137 
138 	/**
139 	 * Get the industry of the given tile
140 	 * @param tile the tile to get the industry from
141 	 * @pre IsTileType(t, MP_INDUSTRY)
142 	 * @return the industry
143 	 */
GetByTileIndustry144 	static inline Industry *GetByTile(TileIndex tile)
145 	{
146 		return Industry::Get(GetIndustryIndex(tile));
147 	}
148 
149 	static Industry *GetRandom();
150 	static void PostDestructor(size_t index);
151 
152 	/**
153 	 * Increment the count of industries for this type.
154 	 * @param type IndustryType to increment
155 	 * @pre type < NUM_INDUSTRYTYPES
156 	 */
IncIndustryTypeCountIndustry157 	static inline void IncIndustryTypeCount(IndustryType type)
158 	{
159 		assert(type < NUM_INDUSTRYTYPES);
160 		counts[type]++;
161 	}
162 
163 	/**
164 	 * Decrement the count of industries for this type.
165 	 * @param type IndustryType to decrement
166 	 * @pre type < NUM_INDUSTRYTYPES
167 	 */
DecIndustryTypeCountIndustry168 	static inline void DecIndustryTypeCount(IndustryType type)
169 	{
170 		assert(type < NUM_INDUSTRYTYPES);
171 		counts[type]--;
172 	}
173 
174 	/**
175 	 * Get the count of industries for this type.
176 	 * @param type IndustryType to query
177 	 * @pre type < NUM_INDUSTRYTYPES
178 	 */
GetIndustryTypeCountIndustry179 	static inline uint16 GetIndustryTypeCount(IndustryType type)
180 	{
181 		assert(type < NUM_INDUSTRYTYPES);
182 		return counts[type];
183 	}
184 
185 	/** Resets industry counts. */
ResetIndustryCountsIndustry186 	static inline void ResetIndustryCounts()
187 	{
188 		memset(&counts, 0, sizeof(counts));
189 	}
190 
GetCachedNameIndustry191 	inline const char *GetCachedName() const
192 	{
193 		if (this->cached_name.empty()) this->FillCachedName();
194 		return this->cached_name.c_str();
195 	}
196 
197 private:
198 	void FillCachedName() const;
199 
200 protected:
201 	static uint16 counts[NUM_INDUSTRYTYPES]; ///< Number of industries per type ingame
202 };
203 
204 void ClearAllIndustryCachedNames();
205 
206 void PlantRandomFarmField(const Industry *i);
207 
208 void ReleaseDisastersTargetingIndustry(IndustryID);
209 
210 bool IsTileForestIndustry(TileIndex tile);
211 
212 /** Data for managing the number of industries of a single industry type. */
213 struct IndustryTypeBuildData {
214 	uint32 probability;  ///< Relative probability of building this industry.
215 	byte   min_number;   ///< Smallest number of industries that should exist (either \c 0 or \c 1).
216 	uint16 target_count; ///< Desired number of industries of this type.
217 	uint16 max_wait;     ///< Starting number of turns to wait (copied to #wait_count).
218 	uint16 wait_count;   ///< Number of turns to wait before trying to build again.
219 
220 	void Reset();
221 
222 	bool GetIndustryTypeData(IndustryType it);
223 };
224 
225 /**
226  * Data for managing the number and type of industries in the game.
227  */
228 struct IndustryBuildData {
229 	IndustryTypeBuildData builddata[NUM_INDUSTRYTYPES]; ///< Industry build data for every industry type.
230 	uint32 wanted_inds; ///< Number of wanted industries (bits 31-16), and a fraction (bits 15-0).
231 
232 	void Reset();
233 
234 	void SetupTargetCount();
235 	void TryBuildNewIndustry();
236 
237 	void MonthlyLoop();
238 };
239 
240 extern IndustryBuildData _industry_builder;
241 
242 
243 /** Special values for the industry list window for the data parameter of #InvalidateWindowData. */
244 enum IndustryDirectoryInvalidateWindowData {
245 	IDIWD_FORCE_REBUILD,
246 	IDIWD_PRODUCTION_CHANGE,
247 	IDIWD_FORCE_RESORT,
248 };
249 
250 #endif /* INDUSTRY_H */
251