OpenTTD Source 20261112-master-gbcbec5e63f
newgrf_spritegroup.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "debug.h"
12#include "newgrf_spritegroup.h"
13#include "newgrf_profiling.h"
14#include "core/pool_func.hpp"
15
16#include "safeguards.h"
17
18SpriteGroupPool _spritegroup_pool("SpriteGroup");
20
21/* static */ TemporaryStorageArray<int32_t, 0x110> ResolverObject::temp_store;
22
23
34/* static */ ResolverResult SpriteGroup::Resolve(const SpriteGroup *group, ResolverObject &object, bool top_level)
35{
36 if (group == nullptr) return std::monostate{};
37
38 const GRFFile *grf = object.grffile;
39 auto profiler = std::ranges::find(_newgrf_profilers, grf, &NewGRFProfiler::grffile);
40
41 if (profiler == _newgrf_profilers.end() || !profiler->active) {
42 return group->Resolve(object);
43 } else if (top_level) {
44 profiler->BeginResolve(object);
45 auto result = group->Resolve(object);
46 profiler->EndResolve(result);
47 return result;
48 } else {
49 profiler->RecursiveResolve();
50 return group->Resolve(object);
51 }
52}
53
54static inline uint32_t GetVariable(const ResolverObject &object, ScopeResolver *scope, uint8_t variable, uint32_t parameter, bool &available)
55{
56 uint32_t value;
57 switch (variable) {
58 case 0x0C: return object.callback;
59 case 0x10: return object.callback_param1;
60 case 0x18: return object.callback_param2;
61 case 0x1C: return object.last_value;
62
63 case 0x5F: return (scope->GetRandomBits() << 8) | scope->GetRandomTriggers();
64
65 case 0x7D: return object.GetRegister(parameter);
66
67 case 0x7F:
68 if (object.grffile == nullptr) return 0;
69 return object.grffile->GetParam(parameter);
70
71 default:
72 /* First handle variables common with Action7/9/D */
73 if (variable < 0x40 && GetGlobalVariable(variable, &value, object.grffile)) return value;
74 /* Not a common variable, so evaluate the feature specific variables */
75 return scope->GetVariable(variable, parameter, available);
76 }
77}
78
83/* virtual */ uint32_t ScopeResolver::GetRandomBits() const
84{
85 return 0;
86}
87
92/* virtual */ uint32_t ScopeResolver::GetRandomTriggers() const
93{
94 return 0;
95}
96
104/* virtual */ uint32_t ScopeResolver::GetVariable(uint8_t variable, [[maybe_unused]] uint32_t parameter, bool &available) const
105{
106 this->ro.UnhandledVariable(variable);
107 available = false;
108 return UINT_MAX;
109}
110
116/* virtual */ void ScopeResolver::StorePSA([[maybe_unused]] uint pos, [[maybe_unused]] int32_t value) {}
117
123/* virtual */ const SpriteGroup *ResolverObject::ResolveReal(const RealSpriteGroup &group) const
124{
125 if (!group.loaded.empty()) return group.loaded[0];
126 if (!group.loading.empty()) return group.loading[0];
127
128 return nullptr;
129}
130
137/* virtual */ ScopeResolver *ResolverObject::GetScope([[maybe_unused]] VarSpriteGroupScope scope, [[maybe_unused]] uint8_t relative)
138{
139 return &this->default_scope;
140}
141
155
157std::set<UnhandledVariableItem> _unhandled_variables;
158
166
171/* virtual */ void ResolverObject::UnhandledVariable(uint8_t variable) const
172{
174 if (!_unhandled_variables.emplace(this->grffile->grfid, this->GetFeature(), variable, this->callback).second) return;
175
176 Debug(Facility::Grf, Severity::Error, "[{}:{}] Unhandled feature 0x{:X} variable 0x{:X} during callback 0x{:X}", this->grffile->filename, this->root_spritegroup->nfo_line, this->GetFeature(), variable, this->callback);
177}
178
179/* Evaluate an adjustment for a variable of the given size.
180 * U is the unsigned type and S is the signed type to use. */
181template <typename U, typename S>
182static U EvalAdjustT(const DeterministicSpriteGroupAdjust &adjust, ResolverObject &object, ScopeResolver *scope, U last_value, uint32_t value)
183{
184 value >>= adjust.shift_num;
185 value &= adjust.and_mask;
186
187 switch (adjust.type) {
188 case DeterministicSpriteGroupAdjustType::Div: value = ((S)value + (S)adjust.add_val) / (S)adjust.divmod_val; break;
189 case DeterministicSpriteGroupAdjustType::Mod: value = ((S)value + (S)adjust.add_val) % (S)adjust.divmod_val; break;
191 }
192
193 switch (adjust.operation) {
194 case DeterministicSpriteGroupAdjustOperation::Add: return last_value + value;
195 case DeterministicSpriteGroupAdjustOperation::Sub: return last_value - value;
196 case DeterministicSpriteGroupAdjustOperation::SMin: return std::min<S>(last_value, value);
197 case DeterministicSpriteGroupAdjustOperation::SMax: return std::max<S>(last_value, value);
198 case DeterministicSpriteGroupAdjustOperation::UMin: return std::min<U>(last_value, value);
199 case DeterministicSpriteGroupAdjustOperation::UMax: return std::max<U>(last_value, value);
200 case DeterministicSpriteGroupAdjustOperation::SDiv: return value == 0 ? (S)last_value : (S)last_value / (S)value;
201 case DeterministicSpriteGroupAdjustOperation::SMod: return value == 0 ? (S)last_value : (S)last_value % (S)value;
202 case DeterministicSpriteGroupAdjustOperation::UDiv: return value == 0 ? (U)last_value : (U)last_value / (U)value;
203 case DeterministicSpriteGroupAdjustOperation::UMod: return value == 0 ? (U)last_value : (U)last_value % (U)value;
204 case DeterministicSpriteGroupAdjustOperation::Mul: return last_value * value;
205 case DeterministicSpriteGroupAdjustOperation::And: return last_value & value;
206 case DeterministicSpriteGroupAdjustOperation::Or: return last_value | value;
207 case DeterministicSpriteGroupAdjustOperation::Xor: return last_value ^ value;
208 case DeterministicSpriteGroupAdjustOperation::Sto: object.SetRegister((U)value, (S)last_value); return last_value;
210 case DeterministicSpriteGroupAdjustOperation::Stop: scope->StorePSA((U)value, (S)last_value); return last_value;
211 case DeterministicSpriteGroupAdjustOperation::Ror: return std::rotr<uint32_t>((U)last_value, (U)value & 0x1F); // mask 'value' to 5 bits, which should behave the same on all architectures.
212 case DeterministicSpriteGroupAdjustOperation::SCmp: return ((S)last_value == (S)value) ? 1 : ((S)last_value < (S)value ? 0 : 2);
213 case DeterministicSpriteGroupAdjustOperation::UCmp: return ((U)last_value == (U)value) ? 1 : ((U)last_value < (U)value ? 0 : 2);
214 case DeterministicSpriteGroupAdjustOperation::Shl: return (uint32_t)(U)last_value << ((U)value & 0x1F); // Same behaviour as in ParamSet, mask 'value' to 5 bits, which should behave the same on all architectures.
215 case DeterministicSpriteGroupAdjustOperation::Shr: return (uint32_t)(U)last_value >> ((U)value & 0x1F);
216 case DeterministicSpriteGroupAdjustOperation::Sar: return (int32_t)(S)last_value >> ((U)value & 0x1F);
217 default: return value;
218 }
219}
220
221
222static bool RangeHighComparator(const DeterministicSpriteGroupRange &range, uint32_t value)
223{
224 return range.high < value;
225}
226
228{
229 uint32_t last_value = 0;
230 uint32_t value = 0;
231
232 ScopeResolver *scope = object.GetScope(this->var_scope);
233
234 for (const auto &adjust : this->adjusts) {
235 /* Try to get the variable. We shall assume it is available, unless told otherwise. */
236 bool available = true;
237 if (adjust.variable == 0x7E) {
238 auto subgroup = SpriteGroup::Resolve(adjust.subroutine, object, false);
239 auto *subvalue = std::get_if<CallbackResult>(&subgroup);
240 value = subvalue != nullptr ? *subvalue : UINT16_MAX;
241
242 /* Note: 'last_value' and 'reseed' are shared between the main chain and the procedure */
243 } else if (adjust.variable == 0x7B) {
244 value = GetVariable(object, scope, adjust.parameter, last_value, available);
245 } else {
246 value = GetVariable(object, scope, adjust.variable, adjust.parameter, available);
247 }
248
249 if (!available) {
250 /* Unsupported variable: skip further processing and return either
251 * the group from the first range or the default group. */
252 return SpriteGroup::Resolve(this->error_group, object, false);
253 }
254
255 switch (this->size) {
256 case DeterministicSpriteGroupSize::Byte: value = EvalAdjustT<uint8_t, int8_t>(adjust, object, scope, last_value, value); break;
257 case DeterministicSpriteGroupSize::Word: value = EvalAdjustT<uint16_t, int16_t>(adjust, object, scope, last_value, value); break;
258 case DeterministicSpriteGroupSize::DWord: value = EvalAdjustT<uint32_t, int32_t>(adjust, object, scope, last_value, value); break;
259 default: NOT_REACHED();
260 }
261 last_value = value;
262 }
263
264 object.last_value = last_value;
265
266 auto result = this->default_result;
267
268 if (this->ranges.size() > 4) {
269 const auto &lower = std::lower_bound(this->ranges.begin(), this->ranges.end(), value, RangeHighComparator);
270 if (lower != this->ranges.end() && lower->low <= value) {
271 assert(lower->low <= value && value <= lower->high);
272 result = lower->result;
273 }
274 } else {
275 for (const auto &range : this->ranges) {
276 if (range.low <= value && value <= range.high) {
277 result = range.result;
278 break;
279 }
280 }
281 }
282
283 if (result.calculated_result) {
284 return static_cast<CallbackResult>(GB(value, 0, 15));
285 }
286 return SpriteGroup::Resolve(result.group, object, false);
287}
288
289
291{
292 ScopeResolver *scope = object.GetScope(this->var_scope, this->count);
293 if (object.callback == CBID_RANDOM_TRIGGER) {
294 /* Handle triggers */
295 uint8_t match = this->triggers & object.GetWaitingRandomTriggers();
296 bool res = (this->cmp_mode == RandomizedSpriteGroupCompareMode::Any) ? (match != 0) : (match == this->triggers);
297
298 if (res) {
299 object.AddUsedRandomTriggers(match);
300 object.reseed[this->var_scope] |= (this->groups.size() - 1) << this->lowest_randbit;
301 }
302 }
303
304 uint32_t mask = ((uint)this->groups.size() - 1) << this->lowest_randbit;
305 uint8_t index = (scope->GetRandomBits() & mask) >> this->lowest_randbit;
306
307 return SpriteGroup::Resolve(this->groups[index], object, false);
308}
309
311{
312 return this->result;
313}
314
316{
317 /* Call the feature specific evaluation via ResultSpriteGroup::ResolveReal.
318 * The result is either ResultSpriteGroup, CallbackResultSpriteGroup, or nullptr.
319 */
320 return SpriteGroup::Resolve(object.ResolveReal(*this), object, false);
321}
322
332{
333 if (!this->dts.NeedsPreprocessing()) {
334 if (stage != nullptr && this->dts.consistent_max_offset > 0) *stage = GetConstructionStageOffset(*stage, this->dts.consistent_max_offset);
335 return SpriteLayoutProcessor(this->dts);
336 }
337
338 uint8_t actual_stage = stage != nullptr ? *stage : 0;
339 SpriteLayoutProcessor result(this->dts, 0, 0, 0, actual_stage, false);
340 result.ProcessRegisters(object, 0, 0);
341
342 /* Stage has been processed by PrepareLayout(), set it to zero. */
343 if (stage != nullptr) *stage = 0;
344
345 return result;
346}
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Add dynamic register values to a sprite layout.
void ProcessRegisters(const struct ResolverObject &object, uint8_t resolved_var10, uint32_t resolved_sprite)
Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
Functions related to debugging.
bool IsVisibleSeverity(Facility facility, Severity severity)
Test if debug severity is visible for the given facility.
Definition debug.h:24
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Grf
Grf message facility.
Definition debug_type.h:30
@ Error
Error, but we are recovering.
Definition debug_type.h:16
#define S
Climate sub-tropic.
Definition engines.h:95
bool GetGlobalVariable(uint8_t param, uint32_t *value, const GRFFile *grffile)
Reads a variable common to VarAction2 and Action7/9/D.
GrfSpecFeature
Definition newgrf.h:81
CallbackID
List of implemented NewGRF callbacks.
@ CBID_RANDOM_TRIGGER
Set when calling a randomizing trigger (almost undocumented).
uint GetConstructionStageOffset(uint construction_stage, uint num_sprites)
Determines which sprite to use from a spriteset for a specific construction stage.
Profiling of NewGRF action 2 handling.
std::set< UnhandledVariableItem > _unhandled_variables
Set of unhandled variables that have been seen.
void ResetUnhandledVariableWarnings()
Reset unhandled variable warnings.
Action 2 handling.
@ DWord
Treat variable as a DWord.
@ Word
Treat variable as a Word.
@ Byte
Treat variable as a Byte.
@ Stop
store a into persistent storage, indexed by b, return a
@ Sto
store a into temporary storage, indexed by b. return a
@ UCmp
(unsigned) comparison (a < b -> 0, a == b = 1, a > b = 2)
@ Ror
rotate a b positions to the right
@ SCmp
(signed) comparison (a < b -> 0, a == b = 1, a > b = 2)
VarSpriteGroupScope
Shared by deterministic and random groups.
@ Any
Match if any bit is triggered.
@ Div
Apply divide adjustment to value.
@ Mod
Apply modulus adjustment to value.
std::variant< std::monostate, CallbackResult, const ResultSpriteGroup *, const TileLayoutSpriteGroup *, const IndustryProductionSpriteGroup * > ResolverResult
Result of resolving sprite groups:
Label< struct GrfIDTag > GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:17
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
ResolverResult Resolve(ResolverObject &object) const override
Resolves a callback or rerandomisation callback to a NewGRF.
uint8_t parameter
Used for variables between 0x60 and 0x7F inclusive.
ResolverResult Resolve(ResolverObject &object) const override
Resolves a callback or rerandomisation callback to a NewGRF.
DeterministicSpriteGroupResult default_result
Dynamically allocated, this is the sole owner.
const SpriteGroup * error_group
Was first range, before sorting ranges.
Dynamic data of a loaded NewGRF.
Definition newgrf.h:126
const GRFFile * grffile
Which GRF is being profiled.
uint8_t lowest_randbit
Look for this in the per-object randomized bitmask:
VarSpriteGroupScope var_scope
Take this object:
std::vector< const SpriteGroup * > groups
Take the group with appropriate index:
ResolverResult Resolve(ResolverObject &object) const override
Resolves a callback or rerandomisation callback to a NewGRF.
RandomizedSpriteGroupCompareMode cmp_mode
Check for these triggers:
'Real' sprite groups contain a list of other result or callback sprite groups.
ResolverResult Resolve(ResolverObject &object) const override
Resolves a callback or rerandomisation callback to a NewGRF.
std::vector< const SpriteGroup * > loaded
List of loaded groups (can be SpriteIDs or Callback results).
std::vector< const SpriteGroup * > loading
List of loading groups (can be SpriteIDs or Callback results).
Interface for SpriteGroup-s to access the gamestate.
const GRFFile * grffile
GRFFile the resolved SpriteGroup belongs to.
void UnhandledVariable(uint8_t variable) const
Log a message for an unhandled NewGRF variable.
ScopeResolver default_scope
Default implementation of the grf scope.
virtual ScopeResolver * GetScope(VarSpriteGroupScope scope=VarSpriteGroupScope::Self, uint8_t relative=0)
Get a resolver for the scope.
virtual const SpriteGroup * ResolveReal(const RealSpriteGroup &group) const
Get the real sprites of the grf.
Interface to query and set values specific to a single VarSpriteGroupScope (action 2 scope).
virtual void StorePSA(uint reg, int32_t value)
Store a value into the persistent storage area (PSA).
virtual uint32_t GetVariable(uint8_t variable, uint32_t parameter, bool &available) const
Get a variable value.
ResolverObject & ro
Surrounding resolver object.
virtual uint32_t GetRandomTriggers() const
Get the triggers.
virtual uint32_t GetRandomBits() const
Get a few random bits.
Common wrapper for all the different sprite group types.
SpriteGroup(SpriteGroupID index)
Create the SpriteGroup.
virtual ResolverResult Resolve(ResolverObject &object) const =0
Resolves a callback or rerandomisation callback to a NewGRF.
Class for temporary storage of data.
SpriteLayoutProcessor ProcessRegisters(const ResolverObject &object, uint8_t *stage) const
Process registers and the construction stage into the sprite layout.
Record of unhandled variables.
CallbackID callback
The callback.
uint8_t variable
The variable.
constexpr auto operator<=>(const UnhandledVariableItem &) const =default
Compare with another instance of this class.
GrfSpecFeature feature
The feature.