Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / newgrf_spritegroup.cpp
blob8454b869b824f56266da9ebfde5605bb499f9ffc
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file newgrf_spritegroup.cpp Handling of primarily NewGRF action 2. */
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "newgrf_spritegroup.h"
13 #include "newgrf_profiling.h"
14 #include "core/pool_func.hpp"
16 #include "safeguards.h"
18 SpriteGroupPool _spritegroup_pool("SpriteGroup");
19 INSTANTIATE_POOL_METHODS(SpriteGroup)
21 TemporaryStorageArray<int32, 0x110> _temp_store;
24 /**
25 * ResolverObject (re)entry point.
26 * This cannot be made a call to a virtual function because virtual functions
27 * do not like nullptr and checking for nullptr *everywhere* is more cumbersome than
28 * this little helper function.
29 * @param group the group to resolve for
30 * @param object information needed to resolve the group
31 * @param top_level true if this is a top-level SpriteGroup, false if used nested in another SpriteGroup.
32 * @return the resolved group
34 /* static */ const SpriteGroup *SpriteGroup::Resolve(const SpriteGroup *group, ResolverObject &object, bool top_level)
36 if (group == nullptr) return nullptr;
38 const GRFFile *grf = object.grffile;
39 auto profiler = std::find_if(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](const NewGRFProfiler &pr) { return pr.grffile == grf; });
41 if (profiler == _newgrf_profilers.end() || !profiler->active) {
42 if (top_level) _temp_store.ClearChanges();
43 return group->Resolve(object);
44 } else if (top_level) {
45 profiler->BeginResolve(object);
46 _temp_store.ClearChanges();
47 const SpriteGroup *result = group->Resolve(object);
48 profiler->EndResolve(result);
49 return result;
50 } else {
51 profiler->RecursiveResolve();
52 return group->Resolve(object);
56 static inline uint32 GetVariable(const ResolverObject &object, ScopeResolver *scope, byte variable, uint32 parameter, bool *available)
58 uint32 value;
59 switch (variable) {
60 case 0x0C: return object.callback;
61 case 0x10: return object.callback_param1;
62 case 0x18: return object.callback_param2;
63 case 0x1C: return object.last_value;
65 case 0x5F: return (scope->GetRandomBits() << 8) | scope->GetTriggers();
67 case 0x7D: return _temp_store.GetValue(parameter);
69 case 0x7F:
70 if (object.grffile == nullptr) return 0;
71 return object.grffile->GetParam(parameter);
73 default:
74 /* First handle variables common with Action7/9/D */
75 if (variable < 0x40 && GetGlobalVariable(variable, &value, object.grffile)) return value;
76 /* Not a common variable, so evaluate the feature specific variables */
77 return scope->GetVariable(variable, parameter, available);
81 /**
82 * Get a few random bits. Default implementation has no random bits.
83 * @return Random bits.
85 /* virtual */ uint32 ScopeResolver::GetRandomBits() const
87 return 0;
90 /**
91 * Get the triggers. Base class returns \c 0 to prevent trouble.
92 * @return The triggers.
94 /* virtual */ uint32 ScopeResolver::GetTriggers() const
96 return 0;
99 /**
100 * Get a variable value. Default implementation has no available variables.
101 * @param variable Variable to read
102 * @param parameter Parameter for 60+x variables
103 * @param[out] available Set to false, in case the variable does not exist.
104 * @return Value
106 /* virtual */ uint32 ScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
108 Debug(grf, 1, "Unhandled scope variable 0x{:X}", variable);
109 *available = false;
110 return UINT_MAX;
114 * Store a value into the persistent storage area (PSA). Default implementation does nothing (for newgrf classes without storage).
115 * @param reg Position to store into.
116 * @param value Value to store.
118 /* virtual */ void ScopeResolver::StorePSA(uint reg, int32 value) {}
121 * Get the real sprites of the grf.
122 * @param group Group to get.
123 * @return The available sprite group.
125 /* virtual */ const SpriteGroup *ResolverObject::ResolveReal(const RealSpriteGroup *group) const
127 if (!group->loaded.empty()) return group->loaded[0];
128 if (!group->loading.empty()) return group->loading[0];
130 return nullptr;
134 * Get a resolver for the \a scope.
135 * @param scope Scope to return.
136 * @param relative Additional parameter for #VSG_SCOPE_RELATIVE.
137 * @return The resolver for the requested scope.
139 /* virtual */ ScopeResolver *ResolverObject::GetScope(VarSpriteGroupScope scope, byte relative)
141 return &this->default_scope;
144 /* Evaluate an adjustment for a variable of the given size.
145 * U is the unsigned type and S is the signed type to use. */
146 template <typename U, typename S>
147 static U EvalAdjustT(const DeterministicSpriteGroupAdjust &adjust, ScopeResolver *scope, U last_value, uint32 value)
149 value >>= adjust.shift_num;
150 value &= adjust.and_mask;
152 switch (adjust.type) {
153 case DSGA_TYPE_DIV: value = ((S)value + (S)adjust.add_val) / (S)adjust.divmod_val; break;
154 case DSGA_TYPE_MOD: value = ((S)value + (S)adjust.add_val) % (S)adjust.divmod_val; break;
155 case DSGA_TYPE_NONE: break;
158 switch (adjust.operation) {
159 case DSGA_OP_ADD: return last_value + value;
160 case DSGA_OP_SUB: return last_value - value;
161 case DSGA_OP_SMIN: return std::min<S>(last_value, value);
162 case DSGA_OP_SMAX: return std::max<S>(last_value, value);
163 case DSGA_OP_UMIN: return std::min<U>(last_value, value);
164 case DSGA_OP_UMAX: return std::max<U>(last_value, value);
165 case DSGA_OP_SDIV: return value == 0 ? (S)last_value : (S)last_value / (S)value;
166 case DSGA_OP_SMOD: return value == 0 ? (S)last_value : (S)last_value % (S)value;
167 case DSGA_OP_UDIV: return value == 0 ? (U)last_value : (U)last_value / (U)value;
168 case DSGA_OP_UMOD: return value == 0 ? (U)last_value : (U)last_value % (U)value;
169 case DSGA_OP_MUL: return last_value * value;
170 case DSGA_OP_AND: return last_value & value;
171 case DSGA_OP_OR: return last_value | value;
172 case DSGA_OP_XOR: return last_value ^ value;
173 case DSGA_OP_STO: _temp_store.StoreValue((U)value, (S)last_value); return last_value;
174 case DSGA_OP_RST: return value;
175 case DSGA_OP_STOP: scope->StorePSA((U)value, (S)last_value); return last_value;
176 case DSGA_OP_ROR: return ROR<uint32>((U)last_value, (U)value & 0x1F); // mask 'value' to 5 bits, which should behave the same on all architectures.
177 case DSGA_OP_SCMP: return ((S)last_value == (S)value) ? 1 : ((S)last_value < (S)value ? 0 : 2);
178 case DSGA_OP_UCMP: return ((U)last_value == (U)value) ? 1 : ((U)last_value < (U)value ? 0 : 2);
179 case DSGA_OP_SHL: return (uint32)(U)last_value << ((U)value & 0x1F); // Same behaviour as in ParamSet, mask 'value' to 5 bits, which should behave the same on all architectures.
180 case DSGA_OP_SHR: return (uint32)(U)last_value >> ((U)value & 0x1F);
181 case DSGA_OP_SAR: return (int32)(S)last_value >> ((U)value & 0x1F);
182 default: return value;
187 static bool RangeHighComparator(const DeterministicSpriteGroupRange& range, uint32 value)
189 return range.high < value;
192 const SpriteGroup *DeterministicSpriteGroup::Resolve(ResolverObject &object) const
194 uint32 last_value = 0;
195 uint32 value = 0;
197 ScopeResolver *scope = object.GetScope(this->var_scope);
199 for (const auto &adjust : this->adjusts) {
200 /* Try to get the variable. We shall assume it is available, unless told otherwise. */
201 bool available = true;
202 if (adjust.variable == 0x7E) {
203 const SpriteGroup *subgroup = SpriteGroup::Resolve(adjust.subroutine, object, false);
204 if (subgroup == nullptr) {
205 value = CALLBACK_FAILED;
206 } else {
207 value = subgroup->GetCallbackResult();
210 /* Note: 'last_value' and 'reseed' are shared between the main chain and the procedure */
211 } else if (adjust.variable == 0x7B) {
212 value = GetVariable(object, scope, adjust.parameter, last_value, &available);
213 } else {
214 value = GetVariable(object, scope, adjust.variable, adjust.parameter, &available);
217 if (!available) {
218 /* Unsupported variable: skip further processing and return either
219 * the group from the first range or the default group. */
220 return SpriteGroup::Resolve(this->error_group, object, false);
223 switch (this->size) {
224 case DSG_SIZE_BYTE: value = EvalAdjustT<uint8, int8> (adjust, scope, last_value, value); break;
225 case DSG_SIZE_WORD: value = EvalAdjustT<uint16, int16>(adjust, scope, last_value, value); break;
226 case DSG_SIZE_DWORD: value = EvalAdjustT<uint32, int32>(adjust, scope, last_value, value); break;
227 default: NOT_REACHED();
229 last_value = value;
232 object.last_value = last_value;
234 if (this->calculated_result) {
235 /* nvar == 0 is a special case -- we turn our value into a callback result */
236 if (value != CALLBACK_FAILED) value = GB(value, 0, 15);
237 static CallbackResultSpriteGroup nvarzero(0, true);
238 nvarzero.result = value;
239 return &nvarzero;
242 if (this->ranges.size() > 4) {
243 const auto &lower = std::lower_bound(this->ranges.begin(), this->ranges.end(), value, RangeHighComparator);
244 if (lower != this->ranges.end() && lower->low <= value) {
245 assert(lower->low <= value && value <= lower->high);
246 return SpriteGroup::Resolve(lower->group, object, false);
248 } else {
249 for (const auto &range : this->ranges) {
250 if (range.low <= value && value <= range.high) {
251 return SpriteGroup::Resolve(range.group, object, false);
256 return SpriteGroup::Resolve(this->default_group, object, false);
260 const SpriteGroup *RandomizedSpriteGroup::Resolve(ResolverObject &object) const
262 ScopeResolver *scope = object.GetScope(this->var_scope, this->count);
263 if (object.callback == CBID_RANDOM_TRIGGER) {
264 /* Handle triggers */
265 byte match = this->triggers & object.waiting_triggers;
266 bool res = (this->cmp_mode == RSG_CMP_ANY) ? (match != 0) : (match == this->triggers);
268 if (res) {
269 object.used_triggers |= match;
270 object.reseed[this->var_scope] |= (this->groups.size() - 1) << this->lowest_randbit;
274 uint32 mask = ((uint)this->groups.size() - 1) << this->lowest_randbit;
275 byte index = (scope->GetRandomBits() & mask) >> this->lowest_randbit;
277 return SpriteGroup::Resolve(this->groups[index], object, false);
281 const SpriteGroup *RealSpriteGroup::Resolve(ResolverObject &object) const
283 return object.ResolveReal(this);
287 * Process registers and the construction stage into the sprite layout.
288 * The passed construction stage might get reset to zero, if it gets incorporated into the layout
289 * during the preprocessing.
290 * @param[in,out] stage Construction stage (0-3), or nullptr if not applicable.
291 * @return sprite layout to draw.
293 const DrawTileSprites *TileLayoutSpriteGroup::ProcessRegisters(uint8 *stage) const
295 if (!this->dts.NeedsPreprocessing()) {
296 if (stage != nullptr && this->dts.consistent_max_offset > 0) *stage = GetConstructionStageOffset(*stage, this->dts.consistent_max_offset);
297 return &this->dts;
300 static DrawTileSprites result;
301 uint8 actual_stage = stage != nullptr ? *stage : 0;
302 this->dts.PrepareLayout(0, 0, 0, actual_stage, false);
303 this->dts.ProcessRegisters(0, 0, false);
304 result.seq = this->dts.GetLayout(&result.ground);
306 /* Stage has been processed by PrepareLayout(), set it to zero. */
307 if (stage != nullptr) *stage = 0;
309 return &result;