OpenTTD Source 20260731-master-g77ba2b244a
newgrf_act2.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 <ranges>
12#include "../debug.h"
13#include "../newgrf_engine.h"
14#include "../newgrf_cargo.h"
15#include "../error.h"
16#include "../vehicle_base.h"
17#include "../road.h"
18#include "newgrf_bytereader.h"
19#include "newgrf_internal.h"
20
21#include "table/strings.h"
22
23#include "../safeguards.h"
24
25constexpr uint16_t GROUPID_CALLBACK_FAILED = 0x7FFF;
26constexpr uint16_t GROUPID_CALCULATED_RESULT = 0x7FFE;
27
33{
34 if (HasBit(grf_sprite->pal, 14)) {
35 ClrBit(grf_sprite->pal, 14);
37 }
38
39 if (HasBit(grf_sprite->sprite, 14)) {
40 ClrBit(grf_sprite->sprite, 14);
42 }
43
44 if (HasBit(grf_sprite->sprite, 15)) {
45 ClrBit(grf_sprite->sprite, 15);
47 }
48}
49
63TileLayoutFlags ReadSpriteLayoutSprite(ByteReader &buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, GrfSpecFeature feature, PalSpriteID *grf_sprite, uint16_t *max_sprite_offset, uint16_t *max_palette_offset)
64{
65 grf_sprite->sprite = buf.ReadWord();
66 grf_sprite->pal = buf.ReadWord();
67 TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf.ReadWord() : TLF_NOTHING;
68
69 MapSpriteMappingRecolour(grf_sprite);
70
71 bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
72 ClrBit(grf_sprite->pal, 15);
73 if (custom_sprite) {
74 /* Use sprite from Action 1 */
75 uint index = GB(grf_sprite->sprite, 0, 14);
76 if (use_cur_spritesets && (!_cur_gps.IsValidSpriteSet(feature, index) || _cur_gps.GetNumEnts(feature, index) == 0)) {
77 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {}", index);
78 grf_sprite->sprite = SPR_IMG_QUERY;
79 grf_sprite->pal = PAL_NONE;
80 } else {
81 SpriteID sprite = use_cur_spritesets ? _cur_gps.GetSprite(feature, index) : index;
82 if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur_gps.GetNumEnts(feature, index) : UINT16_MAX;
83 SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
85 }
86 } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
87 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
88 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
89 return flags;
90 }
91
92 if (flags & TLF_CUSTOM_PALETTE) {
93 /* Use palette from Action 1 */
94 uint index = GB(grf_sprite->pal, 0, 14);
95 if (use_cur_spritesets && (!_cur_gps.IsValidSpriteSet(feature, index) || _cur_gps.GetNumEnts(feature, index) == 0)) {
96 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {} for 'palette'", index);
97 grf_sprite->pal = PAL_NONE;
98 } else {
99 SpriteID sprite = use_cur_spritesets ? _cur_gps.GetSprite(feature, index) : index;
100 if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur_gps.GetNumEnts(feature, index) : UINT16_MAX;
101 SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
103 }
104 } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
105 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
106 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
107 return flags;
108 }
109
110 return flags;
111}
112
121static void ReadSpriteLayoutRegisters(ByteReader &buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
122{
123 if (!(flags & TLF_DRAWING_FLAGS)) return;
124
125 if (dts->registers.empty()) dts->AllocateRegisters();
126 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
127 regs.flags = flags & TLF_DRAWING_FLAGS;
128
129 if (flags & TLF_DODRAW) regs.dodraw = buf.ReadByte();
130 if (flags & TLF_SPRITE) regs.sprite = buf.ReadByte();
131 if (flags & TLF_PALETTE) regs.palette = buf.ReadByte();
132
133 if (is_parent) {
134 if (flags & TLF_BB_XY_OFFSET) {
135 regs.delta.parent[0] = buf.ReadByte();
136 regs.delta.parent[1] = buf.ReadByte();
137 }
138 if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf.ReadByte();
139 } else {
140 if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf.ReadByte();
141 if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf.ReadByte();
142 }
143
144 if (flags & TLF_SPRITE_VAR10) {
145 regs.sprite_var10 = buf.ReadByte();
146 if (regs.sprite_var10 > TLR_MAX_VAR10) {
147 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.sprite_var10, TLR_MAX_VAR10);
148 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
149 return;
150 }
151 }
152
153 if (flags & TLF_PALETTE_VAR10) {
154 regs.palette_var10 = buf.ReadByte();
155 if (regs.palette_var10 > TLR_MAX_VAR10) {
156 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.palette_var10, TLR_MAX_VAR10);
157 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
158 return;
159 }
160 }
161}
162
174bool ReadSpriteLayout(ByteReader &buf, uint num_building_sprites, bool use_cur_spritesets, GrfSpecFeature feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
175{
176 bool has_flags = HasBit(num_building_sprites, 6);
177 ClrBit(num_building_sprites, 6);
178 TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
179 if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
180 dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
181
182 std::vector<uint16_t> max_sprite_offset(num_building_sprites + 1, 0);
183 std::vector<uint16_t> max_palette_offset(num_building_sprites + 1, 0);
184
185 /* Groundsprite */
186 TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset.data(), max_palette_offset.data());
187 if (_cur_gps.skip_sprites < 0) return true;
188
189 if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
190 GrfMsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x{:X} for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
191 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
192 return true;
193 }
194
195 ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
196 if (_cur_gps.skip_sprites < 0) return true;
197
198 for (uint i = 0; i < num_building_sprites; i++) {
199 DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
200
201 flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset.data() + i + 1, max_palette_offset.data() + i + 1);
202 if (_cur_gps.skip_sprites < 0) return true;
203
204 if (flags & ~valid_flags) {
205 GrfMsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x{:X}", flags & ~valid_flags);
206 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
207 return true;
208 }
209
210 seq->origin.x = buf.ReadByte();
211 seq->origin.y = buf.ReadByte();
212
213 if (!no_z_position) seq->origin.z = buf.ReadByte();
214
215 if (seq->IsParentSprite()) {
216 seq->extent.x = buf.ReadByte();
217 seq->extent.y = buf.ReadByte();
218 seq->extent.z = buf.ReadByte();
219 }
220
221 ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
222 if (_cur_gps.skip_sprites < 0) return true;
223 }
224
225 /* Check if the number of sprites per spriteset is consistent */
226 bool is_consistent = true;
227 dts->consistent_max_offset = 0;
228 for (uint i = 0; i < num_building_sprites + 1; i++) {
229 if (max_sprite_offset[i] > 0) {
230 if (dts->consistent_max_offset == 0) {
231 dts->consistent_max_offset = max_sprite_offset[i];
232 } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
233 is_consistent = false;
234 break;
235 }
236 }
237 if (max_palette_offset[i] > 0) {
238 if (dts->consistent_max_offset == 0) {
239 dts->consistent_max_offset = max_palette_offset[i];
240 } else if (dts->consistent_max_offset != max_palette_offset[i]) {
241 is_consistent = false;
242 break;
243 }
244 }
245 }
246
247 /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
248 assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
249
250 if (!is_consistent || !dts->registers.empty()) {
251 dts->consistent_max_offset = 0;
252 if (dts->registers.empty()) dts->AllocateRegisters();
253
254 for (uint i = 0; i < num_building_sprites + 1; i++) {
255 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
256 regs.max_sprite_offset = max_sprite_offset[i];
257 regs.max_palette_offset = max_palette_offset[i];
258 }
259 }
260
261 return false;
262}
263
264using CachedCallback = std::pair<uint16_t, SpriteGroupID>;
265static std::vector<CachedCallback> _cached_callback_groups;
266
267void ResetCallbacks(bool final)
268{
270 if (final) _cached_callback_groups.shrink_to_fit();
271}
272
273static const SpriteGroup *GetCallbackResultGroup(uint16_t value)
274{
275 /* Old style callback results (only valid for version < 8) have the highest byte 0xFF to signify it is a callback result.
276 * New style ones only have the highest bit set (allows 15-bit results, instead of just 8) */
277 if (_cur_gps.grffile->grf_version < 8 && GB(value, 8, 8) == 0xFF) {
278 value &= ~0xFF00;
279 } else {
280 value &= ~0x8000;
281 }
282
283 /* Find position for value within the cached callback list. */
284 auto it = std::ranges::lower_bound(_cached_callback_groups, value, std::less{}, &CachedCallback::first);
285 if (it != std::end(_cached_callback_groups) && it->first == value) return SpriteGroup::Get(it->second);
286
287 /* Result value is not present, so make it and add to cache. */
290 it = _cached_callback_groups.emplace(it, value, group->index);
291 return group;
292}
293
294/* Helper function to either create a callback or link to a previously
295 * defined spritegroup. */
296static const SpriteGroup *GetGroupFromGroupID(uint8_t setid, uint8_t type, uint16_t groupid)
297{
298 if (HasBit(groupid, 15)) return GetCallbackResultGroup(groupid);
299 if (groupid == GROUPID_CALLBACK_FAILED) return nullptr;
300
301 if (groupid > MAX_SPRITEGROUP || _cur_gps.spritegroups[groupid] == nullptr) {
302 GrfMsg(1, "GetGroupFromGroupID(0x{:02X}:0x{:02X}): Groupid 0x{:04X} does not exist, leaving empty", setid, type, groupid);
303 return nullptr;
304 }
305
306 return _cur_gps.spritegroups[groupid];
307}
308
317static const SpriteGroup *CreateGroupFromGroupID(GrfSpecFeature feature, uint8_t setid, uint8_t type, uint16_t spriteid)
318{
319 if (HasBit(spriteid, 15)) return GetCallbackResultGroup(spriteid);
320
321 if (!_cur_gps.IsValidSpriteSet(feature, spriteid)) {
322 GrfMsg(1, "CreateGroupFromGroupID(0x{:02X}:0x{:02X}): Sprite set {} invalid", setid, type, spriteid);
323 return nullptr;
324 }
325
326 SpriteID spriteset_start = _cur_gps.GetSprite(feature, spriteid);
327 uint num_sprites = _cur_gps.GetNumEnts(feature, spriteid);
328
329 /* Ensure that the sprites are loeded */
330 assert(spriteset_start + num_sprites <= _cur_gps.spriteid);
331
333 return ResultSpriteGroup::Create(spriteset_start, num_sprites);
334}
335
343static const SpriteGroup *ReadDeterministicSpriteGroup(ByteReader &buf, uint8_t setid, uint8_t type)
344{
347 group->nfo_line = _cur_gps.nfo_line;
348 group->var_scope = HasBit(type, 1) ? VarSpriteGroupScope::Parent : VarSpriteGroupScope::Self;
349
350 uint8_t varsize;
351 switch (GB(type, 2, 2)) {
352 default: NOT_REACHED();
353 case 0: group->size = DeterministicSpriteGroupSize::Byte; varsize = 1; break;
354 case 1: group->size = DeterministicSpriteGroupSize::Word; varsize = 2; break;
355 case 2: group->size = DeterministicSpriteGroupSize::DWord; varsize = 4; break;
356 }
357
358 /* Loop through the var adjusts. Unfortunately we don't know how many we have
359 * from the outset, so we shall have to keep reallocing. */
360 uint8_t varadjust;
361 do {
362 DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
363
364 /* The first var adjust doesn't have an operation specified, so we set it to add. */
365 adjust.operation = group->adjusts.size() == 1 ? DeterministicSpriteGroupAdjustOperation::Add : static_cast<DeterministicSpriteGroupAdjustOperation>(buf.ReadByte());
366 adjust.variable = buf.ReadByte();
367 if (adjust.variable == 0x7E) {
368 /* Link subroutine group */
369 adjust.subroutine = GetGroupFromGroupID(setid, type, buf.ReadByte());
370 } else {
371 adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf.ReadByte() : 0;
372 }
373
374 varadjust = buf.ReadByte();
375 adjust.shift_num = GB(varadjust, 0, 5);
376 adjust.type = static_cast<DeterministicSpriteGroupAdjustType>(GB(varadjust, 6, 2));
377 adjust.and_mask = buf.ReadVarSize(varsize);
378
379 if (adjust.type != DeterministicSpriteGroupAdjustType::None) {
380 adjust.add_val = buf.ReadVarSize(varsize);
381 adjust.divmod_val = buf.ReadVarSize(varsize);
382 if (adjust.divmod_val == 0) adjust.divmod_val = 1; // Ensure that divide by zero cannot occur
383 } else {
384 adjust.add_val = 0;
385 adjust.divmod_val = 0;
386 }
387
388 /* Continue reading var adjusts while bit 5 is set. */
389 } while (HasBit(varadjust, 5));
390
391 std::vector<DeterministicSpriteGroupRange> ranges;
392 ranges.resize(buf.ReadByte());
393 for (auto &range : ranges) {
394 auto groupid = buf.ReadWord();
395 if (groupid == GROUPID_CALCULATED_RESULT) {
396 range.result.calculated_result = true;
397 } else {
398 range.result.group = GetGroupFromGroupID(setid, type, groupid);
399 }
400 range.low = buf.ReadVarSize(varsize);
401 range.high = buf.ReadVarSize(varsize);
402 }
403
404 auto defgroupid = buf.ReadWord();
405 if (defgroupid == GROUPID_CALCULATED_RESULT) {
406 group->default_result.calculated_result = true;
407 } else {
408 group->default_result.group = GetGroupFromGroupID(setid, type, defgroupid);
409 }
410 /* 'calculated_result' makes no sense for the 'error' case. Use callback failure (nullptr) instead */
411 group->error_group = ranges.empty() ? group->default_result.group : ranges[0].result.group;
412 /* nvar == 0 is a special case:
413 * - set "default_result" to "calculated_result".
414 * - the old value specifies the "error_group". */
415 if (ranges.empty()) {
416 group->default_result.calculated_result = true;
417 group->default_result.group = nullptr;
418 }
419
420 /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
421 std::vector<uint32_t> bounds;
422 bounds.reserve(ranges.size());
423 for (const auto &range : ranges) {
424 bounds.push_back(range.low);
425 if (range.high != UINT32_MAX) bounds.push_back(range.high + 1);
426 }
427 std::sort(bounds.begin(), bounds.end());
428 bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
429
430 std::vector<DeterministicSpriteGroupResult> target;
431 target.reserve(bounds.size());
432 for (const auto &bound : bounds) {
433 auto t = group->default_result;
434 for (const auto &range : ranges) {
435 if (range.low <= bound && bound <= range.high) {
436 t = range.result;
437 break;
438 }
439 }
440 target.push_back(t);
441 }
442 assert(target.size() == bounds.size());
443
444 for (uint j = 0; j < bounds.size(); ) {
445 if (target[j] != group->default_result) {
446 DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
447 r.result = target[j];
448 r.low = bounds[j];
449 while (j < bounds.size() && target[j] == r.result) {
450 j++;
451 }
452 r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
453 } else {
454 j++;
455 }
456 }
457
458 return group;
459}
460
469static const SpriteGroup *ReadRandomizedSpriteGroup(ByteReader &buf, GrfSpecFeature feature, uint8_t setid, uint8_t type)
470{
473 group->nfo_line = _cur_gps.nfo_line;
475
476 if (HasBit(type, 2)) {
478 group->count = buf.ReadByte();
479 }
480
481 uint8_t triggers = buf.ReadByte();
482 group->triggers = GB(triggers, 0, 7);
484 group->lowest_randbit = buf.ReadByte();
485
486 uint8_t num_groups = buf.ReadByte();
487 if (!HasExactlyOneBit(num_groups)) {
488 GrfMsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
489 }
490
491 group->groups.reserve(num_groups);
492 for (uint i = 0; i < num_groups; i++) {
493 group->groups.push_back(GetGroupFromGroupID(setid, type, buf.ReadWord()));
494 }
495
496 return group;
497}
498
507static const SpriteGroup *ReadRealSpriteGroup(ByteReader &buf, GrfSpecFeature feature, uint8_t setid, uint8_t type)
508{
509 uint8_t num_loaded = type;
510 uint8_t num_loading = buf.ReadByte();
511
512 if (!_cur_gps.HasValidSpriteSets(feature)) {
513 GrfMsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
514 return nullptr;
515 }
516
517 GrfMsg(6, "NewSpriteGroup: New SpriteGroup 0x{:02X}, {} loaded, {} loading", setid, num_loaded, num_loading);
518
519 if (num_loaded + num_loading == 0) {
520 GrfMsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
521 return nullptr;
522 }
523
524 if (num_loaded + num_loading == 1) {
525 /* Avoid creating 'Real' sprite group if only one option. */
526 uint16_t spriteid = buf.ReadWord();
527 GrfMsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset {}", spriteid);
528 return CreateGroupFromGroupID(feature, setid, type, spriteid);
529 }
530
531 std::vector<uint16_t> loaded;
532 std::vector<uint16_t> loading;
533
534 loaded.reserve(num_loaded);
535 for (uint i = 0; i < num_loaded; i++) {
536 loaded.push_back(buf.ReadWord());
537 GrfMsg(8, "NewSpriteGroup: + rg->loaded[{}] = subset {}", i, loaded[i]);
538 }
539
540 loading.reserve(num_loading);
541 for (uint i = 0; i < num_loading; i++) {
542 loading.push_back(buf.ReadWord());
543 GrfMsg(8, "NewSpriteGroup: + rg->loading[{}] = subset {}", i, loading[i]);
544 }
545
546 bool loaded_same = !loaded.empty() && std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end();
547 bool loading_same = !loading.empty() && std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end();
548 if (loaded_same && loading_same && loaded[0] == loading[0]) {
549 /* Both lists only contain the same value, so don't create 'Real' sprite group */
550 GrfMsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset {}", loaded[0]);
551 return CreateGroupFromGroupID(feature, setid, type, loaded[0]);
552 }
553
556 group->nfo_line = _cur_gps.nfo_line;
557
558 if (loaded_same && loaded.size() > 1) loaded.resize(1);
559 group->loaded.reserve(loaded.size());
560 for (uint16_t spriteid : loaded) {
561 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
562 group->loaded.push_back(t);
563 }
564
565 if (loading_same && loading.size() > 1) loading.resize(1);
566 group->loading.reserve(loading.size());
567 for (uint16_t spriteid : loading) {
568 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
569 group->loading.push_back(t);
570 }
571
572 return group;
573}
574
582static const SpriteGroup *ReadTileLayoutSpriteGroup(ByteReader &buf, GrfSpecFeature feature, uint8_t type)
583{
584 uint8_t num_building_sprites = std::max<uint8_t>(1, type);
585
588 group->nfo_line = _cur_gps.nfo_line;
589
590 /* On error, bail out immediately. Temporary GRF data was already freed */
591 if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return nullptr;
592
593 return group;
594}
595
603{
604 if (type > 2) {
605 GrfMsg(1, "NewSpriteGroup: Unsupported industry production version {}, skipping", type);
606 return nullptr;
607 }
608
611 group->nfo_line = _cur_gps.nfo_line;
612 group->version = type;
613
614 if (type == 0) {
616 for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) {
617 group->subtract_input[i] = static_cast<int16_t>(buf.ReadWord()); // signed
618 }
620 for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) {
621 group->add_output[i] = buf.ReadWord(); // unsigned
622 }
623 group->again = buf.ReadByte();
624 } else if (type == 1) {
626 for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) {
627 group->subtract_input[i] = buf.ReadByte();
628 }
630 for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) {
631 group->add_output[i] = buf.ReadByte();
632 }
633 group->again = buf.ReadByte();
634 } else if (type == 2) {
635 group->num_input = buf.ReadByte();
636 if (group->num_input > std::size(group->subtract_input)) {
637 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
638 error->data = "too many inputs (max 16)";
639 return nullptr;
640 }
641 for (uint i = 0; i < group->num_input; i++) {
642 uint8_t rawcargo = buf.ReadByte();
643 CargoType cargo = GetCargoTranslation(rawcargo, _cur_gps.grffile);
644 if (!IsValidCargoType(cargo)) {
645 /* The mapped cargo is invalid. This is permitted at this point,
646 * as long as the result is not used. Mark it invalid so this
647 * can be tested later. */
648 group->version = 0xFF;
649 } else if (auto v = group->cargo_input | std::views::take(i); std::ranges::find(v, cargo) != v.end()) {
650 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
651 error->data = "duplicate input cargo";
652 return nullptr;
653 }
654 group->cargo_input[i] = cargo;
655 group->subtract_input[i] = buf.ReadByte();
656 }
657 group->num_output = buf.ReadByte();
658 if (group->num_output > std::size(group->add_output)) {
659 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
660 error->data = "too many outputs (max 16)";
661 return nullptr;
662 }
663 for (uint i = 0; i < group->num_output; i++) {
664 uint8_t rawcargo = buf.ReadByte();
665 CargoType cargo = GetCargoTranslation(rawcargo, _cur_gps.grffile);
666 if (!IsValidCargoType(cargo)) {
667 /* Mark this result as invalid to use */
668 group->version = 0xFF;
669 } else if (auto v = group->cargo_output | std::views::take(i); std::ranges::find(v, cargo) != v.end()) {
670 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
671 error->data = "duplicate output cargo";
672 return nullptr;
673 }
674 group->cargo_output[i] = cargo;
675 group->add_output[i] = buf.ReadByte();
676 }
677 group->again = buf.ReadByte();
678 } else {
679 NOT_REACHED();
680 }
681
682 return group;
683}
684
693static const SpriteGroup *ReadSpriteGroup(ByteReader &buf, GrfSpecFeature feature, uint8_t setid, uint8_t type)
694{
695 if (feature >= GrfSpecFeature::End) {
696 GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
697 return nullptr;
698 }
699
700 /* Sprite Groups are created here but they are allocated from a pool, so
701 * we do not need to delete anything if there is an exception from the
702 * ByteReader. */
703 switch (type) {
704 /* Deterministic Sprite Group */
705 case 0x81: // Self scope, byte
706 case 0x82: // Parent scope, byte
707 case 0x85: // Self scope, word
708 case 0x86: // Parent scope, word
709 case 0x89: // Self scope, dword
710 case 0x8A: // Parent scope, dword
711 return ReadDeterministicSpriteGroup(buf, setid, type);
712
713 /* Randomized Sprite Group */
714 case 0x80: // Self scope
715 case 0x83: // Parent scope
716 case 0x84: // Relative scope
717 return ReadRandomizedSpriteGroup(buf, feature, setid, type);
718
719 /* Neither a variable or randomized sprite group... must be a real group */
720 default:
721 if (type >= 0x80) {
722 GrfMsg(0, "NewSpriteGroup: Reserved group type 0x{:02X}, skipping", type);
723 return nullptr;
724 }
725
726 switch (feature) {
739 return ReadRealSpriteGroup(buf, feature, setid, type);
740
746 return ReadTileLayoutSpriteGroup(buf, feature, type);
747
749 return ReadIndustryProductionSpriteGroup(buf, type);
750
751 default:
752 GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
753 return nullptr;
754 }
755 }
756}
757
758/* Action 0x02 */
759static void NewSpriteGroup(ByteReader &buf)
760{
761 /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
762 *
763 * B feature see action 1
764 * B set-id ID of this particular definition
765 * B type/num-entries
766 * if 80 or greater, this is a randomized or variational
767 * list definition, see below
768 * otherwise it specifies a number of entries, the exact
769 * meaning depends on the feature
770 * V feature-specific-data (huge mess, don't even look it up --pasky) */
771 GrfSpecFeature feature{buf.ReadByte()};
772 uint8_t setid = buf.ReadByte();
773 uint8_t type = buf.ReadByte();
774
775 _cur_gps.spritegroups[setid] = ReadSpriteGroup(buf, feature, setid, type);
776}
777
789template <> void GrfActionHandler<0x02>::Activation(ByteReader &buf) { NewSpriteGroup(buf); }
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit 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.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:110
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
Class to read from a NewGRF file.
uint16_t ReadWord()
Read a single Word (16 bits).
uint32_t ReadVarSize(uint8_t size)
Read a value of the given number of bytes.
uint8_t ReadByte()
Read a single byte (8 bits).
Functions related to debugging.
Functions related to errors.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
static const int INDUSTRY_ORIGINAL_NUM_INPUTS
Original number of accepted cargo types.
static const int INDUSTRY_ORIGINAL_NUM_OUTPUTS
Original number of produced cargo types.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
GRFError * DisableGrf(StringID message, GRFConfig *config)
Disable a GRF.
Definition newgrf.cpp:140
GrfSpecFeature
Definition newgrf.h:78
@ RoadStops
Road stops feature.
Definition newgrf.h:99
@ RailTypes
Rail types feature.
Definition newgrf.h:95
@ Trains
Trains feature.
Definition newgrf.h:79
@ Cargoes
Cargoes feature.
Definition newgrf.h:90
@ RoadVehicles
Road vehicles feature.
Definition newgrf.h:80
@ TramTypes
Tram types feature.
Definition newgrf.h:98
@ RoadTypes
Road types feature.
Definition newgrf.h:97
@ Ships
Ships feature.
Definition newgrf.h:81
@ Houses
Houses feature.
Definition newgrf.h:86
@ End
End marker.
Definition newgrf.h:101
@ Stations
Stations feature.
Definition newgrf.h:83
@ Airports
Airports feature.
Definition newgrf.h:92
@ Aircraft
Aircraft feature.
Definition newgrf.h:82
@ IndustryTiles
Industry tiles feature.
Definition newgrf.h:88
@ Objects
Objects feature.
Definition newgrf.h:94
@ AirportTiles
Airport tiles feature.
Definition newgrf.h:96
@ Canals
Canals feature.
Definition newgrf.h:84
@ Industries
Industries feature.
Definition newgrf.h:89
@ Badges
Badges feature.
Definition newgrf.h:100
constexpr uint16_t GROUPID_CALLBACK_FAILED
Explicit "failure" result.
static const SpriteGroup * ReadDeterministicSpriteGroup(ByteReader &buf, uint8_t setid, uint8_t type)
Read a Deterministic SpriteGroup.
constexpr uint16_t GROUPID_CALCULATED_RESULT
Return calculated result from VarAction2.
TileLayoutFlags ReadSpriteLayoutSprite(ByteReader &buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, GrfSpecFeature feature, PalSpriteID *grf_sprite, uint16_t *max_sprite_offset, uint16_t *max_palette_offset)
Read a sprite and a palette from the GRF and convert them into a format suitable to OpenTTD.
static void ReadSpriteLayoutRegisters(ByteReader &buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
Preprocess the TileLayoutFlags and read register modifiers from the GRF.
static const SpriteGroup * ReadRandomizedSpriteGroup(ByteReader &buf, GrfSpecFeature feature, uint8_t setid, uint8_t type)
Read a Randomized SpriteGroup.
static const SpriteGroup * ReadSpriteGroup(ByteReader &buf, GrfSpecFeature feature, uint8_t setid, uint8_t type)
Read a SpriteGroup.
static const SpriteGroup * ReadRealSpriteGroup(ByteReader &buf, GrfSpecFeature feature, uint8_t setid, uint8_t type)
Read a Real SpriteGroup.
static const SpriteGroup * ReadIndustryProductionSpriteGroup(ByteReader &buf, uint8_t type)
Read an Industry Production SpriteGroup.
static const SpriteGroup * ReadTileLayoutSpriteGroup(ByteReader &buf, GrfSpecFeature feature, uint8_t type)
Read a Tile Layout SpriteGroup.
bool ReadSpriteLayout(ByteReader &buf, uint num_building_sprites, bool use_cur_spritesets, GrfSpecFeature feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
Read a spritelayout from the GRF.
void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
Map the colour modifiers of TTDPatch to those that Open is using.
static std::vector< CachedCallback > _cached_callback_groups
Sorted list of cached callback result spritegroups.
static const SpriteGroup * CreateGroupFromGroupID(GrfSpecFeature feature, uint8_t setid, uint8_t type, uint16_t spriteid)
Helper function to either create a callback or a result sprite group.
NewGRF buffer reader definition.
CargoType GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoType.
Cargo support for NewGRFs.
TileLayoutFlags
Flags to enable register usage in sprite layouts.
@ TLF_BB_Z_OFFSET
Add signed offset to bounding box Z positions from register TileLayoutRegisters::delta....
@ TLF_CUSTOM_PALETTE
Palette is from Action 1 (moved to SPRITE_MODIFIER_CUSTOM_SPRITE in palette during loading).
@ TLF_SPRITE
Add signed offset to sprite from register TileLayoutRegisters::sprite.
@ TLF_CHILD_X_OFFSET
Add signed offset to child sprite X positions from register TileLayoutRegisters::delta....
@ TLF_DRAWING_FLAGS
Flags which are still required after loading the GRF.
@ TLF_DODRAW
Only draw sprite if value of register TileLayoutRegisters::dodraw is non-zero.
@ TLF_PALETTE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the palette, even if it is no action-1 palet...
@ TLF_NON_GROUND_FLAGS
Flags which do not work for the (first) ground sprite.
@ TLF_BB_XY_OFFSET
Add signed offset to bounding box X and Y positions from register TileLayoutRegisters::delta....
@ TLF_SPRITE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the sprite, even if it is no action-1 sprite...
@ TLF_PALETTE_VAR10
Resolve palette with a specific value in variable 10.
@ TLF_SPRITE_VAR10
Resolve sprite with a specific value in variable 10.
@ TLF_KNOWN_FLAGS
Known flags. Any unknown set flag will disable the GRF.
@ TLF_VAR10_FLAGS
Flags which refer to using multiple action-1-2-3 chains.
@ TLF_PALETTE
Add signed offset to palette from register TileLayoutRegisters::palette.
@ TLF_CHILD_Y_OFFSET
Add signed offset to child sprite Y positions from register TileLayoutRegisters::delta....
static const uint TLR_MAX_VAR10
Maximum value for var 10.
Functions for NewGRF engines.
NewGRF internal processing state.
static constexpr uint MAX_SPRITEGROUP
Maximum GRF-local ID for a spritegroup.
@ DWord
Treat variable as a DWord.
@ Word
Treat variable as a Word.
@ Byte
Treat variable as a Byte.
DeterministicSpriteGroupAdjustOperation
Deterministic sprite group adjust operation.
@ Relative
Relative position (vehicles only).
@ Parent
Related object of the resolved one.
@ Self
Resolved object itself.
@ All
Match if all bits are triggered.
@ Any
Match if any bit is triggered.
DeterministicSpriteGroupAdjustType
Deterministic sprite group adjust type.
Road specific functions.
A number of safeguards to prevent using unsafe methods.
static constexpr uint8_t SPRITE_MODIFIER_OPAQUE
Set when a sprite must not ever be displayed transparently.
Definition sprites.h:1732
static constexpr uint8_t PALETTE_MODIFIER_TRANSPARENT
when a sprite is to be displayed transparently, this bit needs to be set.
Definition sprites.h:1733
static constexpr uint8_t SPRITE_MODIFIER_CUSTOM_SPRITE
these masks change the colours of the palette for a sprite.
Definition sprites.h:1731
static const SpriteID SPR_IMG_QUERY
Definition sprites.h:1274
static constexpr uint8_t SPRITE_WIDTH
number of bits for the sprite number
Definition sprites.h:1721
static constexpr uint8_t PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition sprites.h:1734
Definition of base types and functions in a cross-platform compatible way.
T x
X coordinate.
T y
Y coordinate.
T z
Z coordinate.
uint8_t parameter
Used for variables between 0x60 and 0x7F inclusive.
DeterministicSpriteGroupResult default_result
Dynamically allocated, this is the sole owner.
const SpriteGroup * error_group
Was first range, before sorting ranges.
A tile child sprite and palette to draw for stations etc, with 3D bounding box.
Definition sprite.h:33
bool IsParentSprite() const
Check whether this is a parent sprite with a boundingbox.
Definition sprite.h:44
PalSpriteID ground
Palette and sprite for the ground.
Definition sprite.h:56
Information about why GRF had problems during initialisation.
std::string data
Additional data for message and custom_message.
static void FileScan(ByteReader &buf)
Implementation of the GrfLoadingStage::FileScan stage of this action.
static void SafetyScan(ByteReader &buf)
Implementation of the GrfLoadingStage::SafetyScan stage of this action.
static void Reserve(ByteReader &buf)
Implementation of the GrfLoadingStage::Reserve stage of this action.
static void Activation(ByteReader &buf)
Implementation of the GrfLoadingStage::Activation stage of this action.
static void Init(ByteReader &buf)
Implementation of the GrfLoadingStage::Init stage of this action.
static void LabelScan(ByteReader &buf)
Implementation of the GrfLoadingStage::LabelScan stage of this action.
std::array< uint16_t, INDUSTRY_NUM_OUTPUTS > add_output
Add this much output cargo when successful (unsigned, is indirect in cb version 1+).
std::array< CargoType, INDUSTRY_NUM_OUTPUTS > cargo_output
Which output cargoes to add to (only cb version 2).
std::array< CargoType, INDUSTRY_NUM_INPUTS > cargo_input
Which input cargoes to take from (only cb version 2).
std::array< int16_t, INDUSTRY_NUM_INPUTS > subtract_input
Take this much of the input cargo (can be negative, is indirect in cb version 1+).
uint8_t num_input
How many subtract_input values are valid.
uint8_t version
Production callback version used, or 0xFF if marked invalid.
uint8_t num_output
How many add_output values are valid.
NewGRF supplied spritelayout.
void Allocate(uint num_sprites)
Allocate a spritelayout for num_sprites building sprites.
uint consistent_max_offset
Number of sprites in all referenced spritesets.
void AllocateRegisters()
Allocate memory for register modifiers.
Combination of a palette sprite and a 'real' sprite.
Definition gfx_type.h:22
SpriteID sprite
The 'real' sprite.
Definition gfx_type.h:23
PaletteID pal
The palette (use PAL_NONE) if not needed).
Definition gfx_type.h:24
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:
RandomizedSpriteGroupCompareMode cmp_mode
Check for these triggers:
'Real' sprite groups contain a list of other result or callback sprite groups.
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).
Coord3D< int8_t > origin
Position of northern corner within tile.
Definition sprite.h:19
Coord3D< uint8_t > extent
Size of bounding box.
Definition sprite.h:20
Common wrapper for all the different sprite group types.
Additional modifiers for items in sprite layouts.
uint8_t parent[3]
Registers for signed offsets for the bounding box position of parent sprites.
TileLayoutFlags flags
Flags defining which members are valid and to be used.
uint8_t dodraw
Register deciding whether the sprite shall be drawn at all. Non-zero means drawing.
uint16_t max_sprite_offset
Maximum offset to add to the sprite. (limited by size of the spriteset).
uint8_t palette
Register specifying a signed offset for the palette.
uint8_t sprite_var10
Value for variable 10 when resolving the sprite.
uint16_t max_palette_offset
Maximum offset to add to the palette. (limited by size of the spriteset).
uint8_t palette_var10
Value for variable 10 when resolving the palette.
uint8_t child[2]
Registers for signed offsets for the position of child sprites.
uint8_t sprite
Register specifying a signed offset for the sprite.
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Base class for all vehicles.