Repository navigation
Expand file tree
/
Copy pathgame_scene_renderer.cpp
More file actions
1978 lines (1933 loc) · 107 KB
/
Copy pathgame_scene_renderer.cpp
File metadata and controls
1978 lines (1933 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "eb/game_scene_renderer.hpp"
#include "eb/overworld_sprite_bridge.hpp"
#include "eb/overworld_sprite_runtime.hpp"
#include "eb/render_distance.hpp"
#include "eb/native/overlay_sprites.hpp"
#include "eb/native/custom_sprites.hpp"
#include "eb/native/battle_background.hpp"
#include "generated_profile.hpp"
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <stdexcept>
#include "snes_ppu_constants.hpp"
namespace eb {
void GameSceneRenderer::capture_aperture(int x, int y, unsigned radius_x, unsigned radius_y) {
aperture_valid_ = x >= 0 && x <= 255 && y >= 0 && y <= 255 &&
radius_x > 0 && radius_x <= 256 && radius_y > 0 && radius_y <= 256;
aperture_x_ = x; aperture_y_ = y;
aperture_radius_x_ = radius_x; aperture_radius_y_ = radius_y;
}
bool GameSceneRenderer::presentation_window_contains(const SceneReadView &view, unsigned layer,
int x, unsigned y) const {
if (presentation_encounter_swirl_) {
// BATTLE_SWIRL_SEQUENCE's source HDMA rows cover one screen. Project
// that screen once across the viewport, including its initially empty
// inverted window, rather than cropping the world to the old canvas.
const int output_x = x + int(presentation_width_ - 256) / 2;
return view.layer_window_contains(layer, unsigned(std::clamp(
output_x * 256 / int(presentation_width_), 0, 255)));
}
const unsigned selection = (view.ppu_registers[0x23 + layer / 2] >> ((layer & 1) * 4)) & 15;
if (!presentation_aperture_ || !(selection & 2))
return view.layer_window_contains(layer, unsigned(std::clamp(x, 0, 255)));
// Enlarge both radii equally around the source focus. Stretching only X
// would turn the circular opening into a wide oval.
const double scale = double(presentation_width_) / 256;
const double dx = (x - aperture_x_) / (aperture_radius_x_ * scale);
const double dy = (int(y) - aperture_y_) / (aperture_radius_y_ * scale);
bool first = dx * dx + dy * dy <= 1;
if (selection & 1) first = !first;
if (!(selection & 8)) return first;
// SET_WINDOW_MASK enables both windows during actual prayer cutscenes.
// Extend the captured first window, then preserve the hardware operation
// and second window. Its inverted empty interval is AND's neutral input.
const unsigned native_x = unsigned(std::clamp(x, 0, 255));
bool second = native_x >= view.ppu_registers[0x28] && native_x <= view.ppu_registers[0x29];
if (selection & 4) second = !second;
const unsigned logic = layer < 4 ? (view.ppu_registers[0x2a] >> (layer * 2)) & 3
: (view.ppu_registers[0x2b] >> ((layer - 4) * 2)) & 3;
switch (logic) {
case 0: return first || second;
case 1: return first && second;
case 2: return first != second;
default: return first == second;
}
}
namespace {
bool coffee_tea_backgrounds(const SceneReadView &view) {
// COFFEETEA_SCENE configures BG3, then LOAD_BACKGROUND_ANIMATION loads
// the two four-bit layers without setting BATTLE_MODE_FLAG. Identify the
// live pair from its retained original palettes and animation definitions.
const auto ®s = view.ppu_registers;
if (regs[5] != 9 || regs[7] != 0x58 || regs[8] != 0x5c || regs[9] != 0x7c ||
regs[11] != 0x10 || (regs[12] & 15) != 6)
return false;
const auto layout = native::battle_background_layout(view.game_version);
const auto rom = view.cartridge_rom;
const auto matches = [&](unsigned record, unsigned id, unsigned target) {
const unsigned definition = layout.configurations + id * 17;
if (definition + 17 > rom.size() || view.work_ram[record] != target ||
view.work_ram[record + 1] != 4)
return false;
const unsigned pointer = layout.palettes + rom[definition + 1] * 4;
if (pointer + 4 > rom.size()) return false;
const unsigned address = unsigned(rom[pointer]) | unsigned(rom[pointer + 1]) << 8 |
unsigned(rom[pointer + 2]) << 16;
if (address < 0xc00000 || address - 0xc00000 + 32 > rom.size()) return false;
if (!std::equal(rom.begin() + address - 0xc00000,
rom.begin() + address - 0xc00000 + 32,
view.work_ram.begin() + record + 44)) return false;
return std::equal(rom.begin() + definition + 9, rom.begin() + definition + 13,
view.work_ram.begin() + record + 78) &&
std::equal(rom.begin() + definition + 13, rom.begin() + definition + 17,
view.work_ram.begin() + record + 97);
};
for (unsigned first : {231u, 233u})
if (matches(view.source_profile.wram_battle_backgrounds.layer1, first, 2) &&
matches(view.source_profile.wram_battle_backgrounds.layer2, first + 1, 1))
return true;
return false;
}
bool scripted_world_camera(const SceneReadView &view) {
// UNKNOWN_C46698/C466A8 direct the camera at a scripted entity and set
// GAME_STATE::unknownB0 to 2. C466B8 restores ordinary control. Other
// nonzero modes include ordinary camera adjustment and are not cutscenes.
const unsigned at = view.game_version == GameVersion::JP ? 0x9b56 : 0x98a5;
return (unsigned(view.work_ram[at]) | unsigned(view.work_ram[at + 1]) << 8) == 2;
}
bool robot_ending_scene(const SceneReadView &view) {
// EEVENT5's D7 stage contains these four source-owned corpse NPCs.
// Check the active list and authored region, never a sprite/palette guess.
const auto word = [&](unsigned at) { return unsigned(view.work_ram[at]) | unsigned(view.work_ram[at + 1]) << 8; };
const auto &source = view.source_profile;
const unsigned ids = view.game_version == GameVersion::JP ? 0x3098 : 0x2c9a;
unsigned found = 0;
std::array<bool, 30> seen{};
for (unsigned slot = word(source.wram_first_entity); slot < 60 && !(slot & 1) && !seen[slot / 2];
slot = word(source.wram_entity_next + slot)) {
seen[slot / 2] = true;
const auto npc = word(ids + slot), x = word(source.wram_entity_world_coordinates.x + slot),
y = word(source.wram_entity_world_coordinates.y + slot);
if (npc >= 1306 && npc <= 1309 && x >= 160 && x <= 224 && y >= 6060 && y <= 6120)
found |= 1u << (npc - 1306);
}
return found == 15;
}
bool natural_presentation_border(unsigned combination) {
// Authored combination IDs from TILESET_TABLE / the sector grid, shared
// by US and JP. Twoson/Threed (2/3), Peaceful Rest/Saturn Valley (6) and
// Winters (13) have natural outdoor borders; 10-12, 14-17 and 19-26 use
// room/cave voids. Keep the short road
// tunnels (5), desert traffic (8), and unclassified scenery constrained.
return combination == 2 || combination == 3 || combination == 6 ||
(combination >= 10 && combination <= 17) ||
(combination >= 19 && combination <= 26);
}
bool intro_interference(const SceneReadView &view) {
// GAS_STATION_LOAD mixes its procedural BG2 static into the BG1 card.
// UNKNOWN_C0F21E later disables that subscreen/color math for the still card.
return (view.ppu_registers[5] & 7) == 3 && view.ppu_registers[7] == 0x78 &&
view.ppu_registers[8] == 0x7c && (view.ppu_registers[0x2c] & 1) &&
(view.ppu_registers[0x2d] & 2) && (view.ppu_registers[0x30] & 2) &&
(view.ppu_registers[0x31] & 1);
}
// Bounded presentation-only counterpart of the source's DECOMP routine. The
// two gas-station palettes are imported data, never embedded retail colors.
// Decode exactly one 512-byte palette; malformed input simply disables this
// optional reference and cannot write game memory or walk outside the image.
bool decode_presentation_palette(std::span<const uint8_t> rom, unsigned start,
std::array<uint16_t, 256> &palette) {
std::array<uint8_t, 512> bytes{};
std::size_t input = start, output = 0;
bool valid = true;
const auto next = [&]() -> unsigned {
if (input >= rom.size()) {
valid = false;
return 0;
}
return rom[input++];
};
for (;;) {
const unsigned header = next();
if (!valid)
return false;
if (header == 255)
break;
unsigned command = header >> 5, count = (header & 31) + 1;
if (command == 7) {
command = (header >> 2) & 7;
count = (((header & 3) << 8) | next()) + 1;
}
const unsigned length = count * (command == 2 ? 2 : 1);
if (!valid || length > bytes.size() - output)
return false;
if (!command) {
for (unsigned i = 0; i < count; ++i)
bytes[output++] = uint8_t(next());
} else if (command <= 3) {
const unsigned first = next(), second = command == 2 ? next() : 0;
for (unsigned i = 0; i < count; ++i) {
bytes[output++] = uint8_t(first + (command == 3 ? i : 0));
if (command == 2)
bytes[output++] = uint8_t(second);
}
} else {
int source = int(next() << 8);
source |= int(next());
for (unsigned i = 0; i < count; ++i) {
if (source < 0 || std::size_t(source) >= output)
return false;
unsigned value = bytes[unsigned(source)];
if (command == 5) {
unsigned reversed = 0;
for (unsigned bit = 0; bit < 8; ++bit) {
reversed = (reversed << 1) | (value & 1);
value >>= 1;
}
value = reversed;
}
bytes[output++] = uint8_t(value);
source += command == 6 ? -1 : 1;
}
}
if (!valid)
return false;
}
if (output != bytes.size())
return false;
for (unsigned index = 0; index < palette.size(); ++index)
palette[index] = (bytes[index * 2] | (bytes[index * 2 + 1] << 8)) & 0x7fff;
return true;
}
} // namespace
// Changing the host viewport allocates only a presentation buffer. Seed its
// center from the last native frame to avoid stale pixels before the next
// scanline; no game camera, PPU register, or emulated clock is adjusted here.
void GameSceneRenderer::set_presentation_width(const SceneReadView &view, unsigned width) {
if (width < 256 || width > 1024 || (width & 1))
throw std::invalid_argument("presentation width must be even and between 256 and 1024");
requested_presentation_width_ = width;
resize_presentation_width(view, presentation_frame_aspect_ ? 256 : width);
}
void GameSceneRenderer::resize_presentation_width(const SceneReadView &view, unsigned width) {
if (width == presentation_width_)
return;
presentation_width_ = width;
presentation_boundary_frame_ = UINT64_MAX;
presentation_camera_ = {};
presentation_framebuffer_.assign(width == 256 ? 0 : width * 224, 0xff000000);
if (width > 256)
for (unsigned y = 0; y < 224; ++y)
std::copy_n(view.native_framebuffer.begin() + y * 256, 256,
presentation_framebuffer_.begin() + y * width + (width - 256) / 2);
if (presentation_effects_enabled_) {
presentation_effect_mask_.assign(width * 224, 0);
presentation_unfiltered_mask_.assign(width * 224, 0);
const auto pixels = presentation_pixels(view.native_framebuffer);
presentation_effect_reference_.assign(pixels.begin(), pixels.end());
}
}
std::span<const uint32_t>
GameSceneRenderer::presentation_pixels(std::span<const uint32_t, 256 * 224> native) const {
return presentation_width_ == 256 ? std::span<const uint32_t>(native)
: std::span<const uint32_t>(presentation_framebuffer_);
}
double GameSceneRenderer::presentation_fixed_aspect() const { return presentation_frame_aspect_; }
void GameSceneRenderer::set_presentation_effects_enabled(const SceneReadView &view, bool enabled) {
if (presentation_effects_enabled_ == enabled)
return;
presentation_effects_enabled_ = enabled;
if (enabled) {
if (!presentation_gas_palettes_loaded_) {
presentation_gas_palettes_loaded_ = true;
presentation_gas_palettes_valid_ =
decode_presentation_palette(view.cartridge_rom,
view.source_profile.rom_gas_station_palettes.normal,
presentation_gas_palettes_[0]) &&
decode_presentation_palette(view.cartridge_rom,
view.source_profile.rom_gas_station_palettes.alternate,
presentation_gas_palettes_[1]);
}
presentation_effect_mask_.assign(presentation_width_ * 224, 0);
presentation_unfiltered_mask_.assign(presentation_width_ * 224, 0);
const auto pixels = presentation_pixels(view.native_framebuffer);
presentation_effect_reference_.assign(pixels.begin(), pixels.end());
} else {
presentation_effect_mask_.clear();
presentation_effect_reference_.clear();
presentation_unfiltered_mask_.clear();
}
}
bool GameSceneRenderer::source_window_layer(const SceneReadView &view, unsigned layer) const {
// OVERWORLD_SETUP_VRAM / LOAD_BATTLE_BG: two-bit art at word $6000,
// tilemap at $7c00. Lightning temporarily borrows this same page.
return layer < 4 && !(presentation_screen_overlay_layer_ & (1u << layer)) &&
background_color_depths[view.ppu_registers[5] & 7][layer] == 2 &&
(view.ppu_registers[7 + layer] & 0xfc) == 0x7c &&
((view.ppu_registers[0x0b + layer / 2] >> ((layer & 1) * 4)) & 15) == 6;
}
void GameSceneRenderer::prepare_presentation_windows(const SceneReadView &view) {
presentation_ui_window_count_ = 0;
presentation_ui_layer_ = 4;
presentation_left_windows_ = false;
if (presentation_width_ == 256) return;
for (unsigned layer = 0; layer < 4; ++layer)
if (source_window_layer(view, layer) &&
((view.ppu_registers[0x2c] | view.ppu_registers[0x2d]) & (1u << layer))) {
presentation_ui_layer_ = layer;
break;
}
if (presentation_ui_layer_ == 4) return;
// Regional WINDOW_STATS, OPEN_WINDOW_TABLE, WINDOW_HEAD/TAIL and
// window_stats offsets from ebsrc. CREATE_WINDOW stores content size;
// its drawn border adds two tiles in each dimension.
const bool jp = view.game_version == GameVersion::JP;
const unsigned records = jp ? 0x89c2 : 0x8650, size = jp ? 76 : 82,
table = jp ? 0x8c26 : 0x88e4, head = jp ? 0x8c22 : 0x88e0;
const auto word = [&](unsigned at) { return unsigned(view.work_ram[at]) | unsigned(view.work_ram[at + 1]) << 8; };
std::array<UiWindow, 8> windows{};
std::array<unsigned, 8> ids{};
unsigned count = 0, previous = 0xffff;
std::array<bool, 8> seen{};
bool moved = false;
const unsigned layer = presentation_ui_layer_;
const int scroll_x = int((view.background_scroll_x[layer] + 512) & 1023) - 512,
scroll_y = int((view.background_scroll_y[layer] + 512) & 1023) - 512;
for (unsigned slot = word(head); slot != 0xffff;) {
if (slot >= 8 || seen[slot]) return;
seen[slot] = true;
const unsigned at = records + slot * size, id = word(at + 4), x = word(at + 6),
y = word(at + 8), w = word(at + 10) + 2, h = word(at + 12) + 2;
if (id >= (jp ? 52u : 53u) || word(table + id * 2) != slot || word(at) != previous ||
x >= 32 || y >= 32 || w < 2 || h < 2 || w > 32 - x || h > 32 - y)
return;
// Retain standalone left-inset gameplay windows outside the ordinary
// world layout. Whole world/command groups are classified below.
const bool edge = x == 1 && (id == 0 || id == 3 || id == 4 ||
id == 10 || id == 11 || id == 15 || id == 18);
ids[count] = id;
windows[count++] = {int(x * 8) - scroll_x, int(y * 8) - scroll_y - 1,
int((x + w) * 8) - scroll_x, int((y + h) * 8) - scroll_y - 1, edge};
moved |= edge;
previous = slot;
slot = word(at + 2);
}
if (word(head + 2) != previous) return;
// MENU_HANDLER keeps the battle command window open while its goods,
// PSI and target children run. C120D6's "To ..." box is window $31;
// it and the other children retain their authored offsets from that menu.
// Battle narration has no command parent and keeps its centered position;
// temporary messages opened inside a command follow that command too.
const unsigned battle = view.source_profile.wram_battle_mode_flag;
const bool command_group = word(battle) &&
std::any_of(ids.begin(), ids.begin() + count, [](unsigned id) { return id == 15 || id == 18; });
const bool world_group = !word(battle) && (view.ppu_registers[5] & 0x37) == 1 &&
view.ppu_registers[7] == 0x39 && view.ppu_registers[8] == 0x59;
// The source flattens overlapping windows onto one page. Dialogue, goods,
// equip, PSI and the A-button check/talk path must share their parent's
// translation, otherwise covered portions of the parent become holes.
// Status and its PSI-information children retain the centered source page.
const bool status_group = world_group &&
std::any_of(ids.begin(), ids.begin() + count, [](unsigned id) { return id == 8 || id == 46 || id == 47; });
if (status_group) {
moved = false;
for (unsigned i = 0; i < count; ++i) windows[i].left_edge = false;
} else if (command_group || world_group)
for (unsigned i = 0; i < count; ++i)
moved |= windows[i].left_edge = true;
presentation_ui_windows_ = windows;
presentation_ui_window_count_ = count;
presentation_left_windows_ = moved;
}
std::optional<int> GameSceneRenderer::presentation_window_sample_x(int x, unsigned y) const {
const auto owner = [&](int sample_x) {
for (unsigned index = presentation_ui_window_count_; index > 0; --index)
if (presentation_ui_windows_[index - 1].contains(sample_x, int(y)))
return int(index - 1);
return -1;
};
const int current = owner(x), shifted_x = x + int(presentation_width_ - 256) / 2,
shifted = owner(shifted_x);
// The source page already contains the topmost window's visible artwork.
// Translate the topmost owner's artwork with its entire window group.
if (shifted >= 0 && presentation_ui_windows_[shifted].left_edge &&
(current < 0 || presentation_ui_windows_[current].left_edge || shifted > current))
return shifted_x;
if (x < 0 || x >= 256 || (current >= 0 && presentation_ui_windows_[current].left_edge))
return std::nullopt;
return x;
}
void GameSceneRenderer::prepare_presentation_objects(const SceneReadView &view) {
presentation_objects_frame_ = view.completed_frames;
presentation_objects_.clear();
const auto &source = view.source_profile;
const auto ram = [&view](unsigned a) {
return unsigned(view.work_ram[a]) | (unsigned(view.work_ram[a + 1]) << 8);
};
struct Entity {
unsigned slot, priority;
int depth;
};
std::vector<Entity> entities;
std::array<bool, 30> visited{};
for (unsigned slot = ram(source.wram_first_entity); slot < 60 && !(slot & 1) && !visited[slot / 2];
slot = ram(source.wram_entity_next + slot)) {
visited[slot / 2] = true;
const unsigned bank = ram(source.wram_entity_spritemap_pointers.high + slot);
if ((bank & (view.native_sprites ? 0x8000 : 0xc000)) ||
(ram(source.wram_entity_animation_frame + slot) & 0x8000))
continue;
const unsigned callback = ram(source.wram_entity_draw_callback + slot);
if (callback != source.entity_draw_callbacks.screen_space &&
callback != source.entity_draw_callbacks.world_space)
continue;
unsigned priority = ram(source.wram_entity_draw_priority + slot);
if (priority & 0x8000) {
const unsigned owner = (priority & 0x3f) * 2;
if (owner >= 60)
continue;
priority = ram(source.wram_entity_draw_priority + owner);
}
if (priority > 3)
continue;
entities.push_back({slot, priority, int16_t(ram(source.wram_entity_world_coordinates.y + slot))});
}
// The source queues priorities 0..3, sorting ordinary world actors by
// descending world Y within priority 1. No allocation or callback executes.
std::stable_sort(entities.begin(), entities.end(), [](const Entity &a, const Entity &b) {
return a.priority != b.priority ? a.priority < b.priority : a.priority == 1 && a.depth > b.depth;
});
for (const auto &entity : entities)
append_presentation_entity(view, entity.slot, presentation_objects_);
}
std::optional<std::uint32_t> GameSceneRenderer::append_presentation_entity(
const SceneReadView &view, unsigned slot, std::vector<PresentationObject> &objects) {
const auto &source = view.source_profile;
const auto ram = [&view](unsigned a) {
return unsigned(view.work_ram[a]) | (unsigned(view.work_ram[a + 1]) << 8);
};
// Inspection must not acknowledge hardware ports or touch the open bus.
const auto peek = [&view](uint32_t address, int &value) {
if (address >= 0x7e0000 && address < 0x800000) {
value = view.work_ram[address - 0x7e0000];
return true;
}
if (address >= 0xc00000 && address < 0xf00000 && address - 0xc00000 < view.cartridge_rom.size()) {
value = view.cartridge_rom[address - 0xc00000];
return true;
}
return false;
};
if (view.native_sprites &&
ram(source.wram_entity_draw_callback + slot) == source.entity_draw_callbacks.world_space &&
!view.native_sprites->custom_descriptor(slot))
throw std::runtime_error("Unmarked native actor entered source custom presentation");
if (view.native_sprites &&
ram(source.wram_entity_draw_callback + slot) == source.entity_draw_callbacks.screen_space) {
const auto actor = view.native_sprites->snapshot(slot);
if (!actor || !actor->image)
return {};
const int x = std::int16_t(ram(source.wram_entity_screen_coordinates.x + slot));
const int y = std::int16_t(ram(source.wram_entity_screen_coordinates.y + slot));
const unsigned surface = ram(source.wram_entity_surface_flags + slot);
for (unsigned part = 0; part < actor->image->parts.size(); ++part) {
const auto &piece = actor->image->parts[part];
const unsigned level = surface & (piece.upper ? 2 : 1) ? 0x20 : 0x30;
PresentationObject object{std::int16_t(x + piece.left), std::int16_t(y + piece.top - 1), 0,
std::uint8_t(level | (actor->creation.sprite.palette << 1)), false,
(std::uint64_t{1} << 63) | actor->id, x, y - 1};
object.host_image = actor->image; object.host_part = part;
object.host_palette = actor->creation.sprite.palette; object.native_owned = true;
objects.push_back(std::move(object));
}
// No source address represents a native command, including the
// read-only far-edge preparation path before a source frame upload.
return {};
}
const unsigned bank = ram(source.wram_entity_spritemap_pointers.high + slot) & 255;
unsigned pointer = ram(source.wram_entity_spritemap_pointers.low + slot);
const bool ordinary =
ram(source.wram_entity_draw_callback + slot) == source.entity_draw_callbacks.screen_space;
if (ordinary && (ram(source.wram_entity_displayed_sprites + slot) & 1))
pointer = (pointer + ram(source.wram_entity_spritemap_sizes + slot)) & 0xffff;
const int x = int16_t(ram(
(ordinary ? source.wram_entity_screen_coordinates.x : source.wram_entity_world_coordinates.x) +
slot));
const int y = int16_t(ram(
(ordinary ? source.wram_entity_screen_coordinates.y : source.wram_entity_world_coordinates.y) +
slot));
if (!ordinary) {
const unsigned frame = ram(source.wram_entity_animation_frame + slot);
int lo{}, hi{};
if (!peek((bank << 16) | ((pointer + frame * 2) & 0xffff), lo) ||
!peek((bank << 16) | ((pointer + frame * 2 + 1) & 0xffff), hi))
return {};
pointer = unsigned(lo) | (unsigned(hi) << 8);
}
const auto map_address = (bank << 16) | pointer;
const unsigned surface = ram(source.wram_entity_surface_flags + slot),
upper = ram(source.wram_entity_body_divides + slot) >> 8;
const auto first_part = objects.size();
bool complete = false;
unsigned part = 0;
// Spritemaps may chain through a $80 Y sentinel. Bound both chain walks
// and output so corrupt/stale descriptors can never stall a frame.
for (unsigned step = 0; step < 128 && objects.size() < 3840; ++step) {
std::array<int, 5> entry{};
bool valid = true;
for (unsigned i = 0; i < 5; ++i)
valid &= peek((bank << 16) | ((pointer + i) & 0xffff), entry[i]);
if (!valid)
break;
if (entry[0] == 0x80) {
pointer = unsigned(entry[1]) | (unsigned(entry[2]) << 8);
continue;
}
unsigned attributes = entry[2];
if (ordinary)
attributes = (attributes & 0xcf) | ((surface & (part < upper ? 2 : 1)) ? 0x20 : 0x30);
objects.push_back({x + int8_t(entry[3]), y + int8_t(entry[0]) - 1,
uint8_t(entry[1]), uint8_t(attributes), bool(entry[4] & 1),
(std::uint64_t(1) << 32) | (ram(source.wram_entity_script_ids + slot) << 8) | slot,
x, y - 1});
++part;
if (entry[4] & 0x80) {
complete = true;
break;
}
pointer = (pointer + 5) & 0xffff;
}
if (ordinary && view.host_sprites) {
const auto &pose = view.host_sprites->pose(slot);
if (pose && pose->image) {
const bool display_mirror = ram(source.wram_entity_displayed_sprites + slot) & 1;
// Replacements may retain their creation geometry. Never crop
// or stretch a differently shaped image into that descriptor.
constexpr unsigned sizes[8][2][2] = {
{{8, 8}, {16, 16}}, {{8, 8}, {32, 32}}, {{8, 8}, {64, 64}},
{{16, 16}, {32, 32}}, {{16, 16}, {64, 64}}, {{32, 32}, {64, 64}},
{{16, 32}, {32, 64}}, {{16, 32}, {32, 32}}};
const auto *shape = pose->image->layout ? &pose->image->layout->parts[display_mirror] : nullptr;
bool matches = complete && (shape ? shape->size() : pose->image->parts.size()) == part;
for (unsigned i = 0; matches && i < part; ++i) {
const auto &object = objects[first_part + i];
const int left = shape ? (*shape)[i].left : pose->image->parts[i].left;
const int top = shape ? (*shape)[i].top : pose->image->parts[i].top;
const auto &size = sizes[view.ppu_registers[1] >> 5][object.large];
matches = size[0] == 16 && size[1] == 16 && object.x == x + left &&
object.y == y + top - 1;
}
if (matches) {
for (unsigned i = 0; i < part; ++i) {
auto &object = objects[first_part + i];
object.host_image = pose->image;
object.host_part = i;
// Palette belongs to the displayed descriptor; an
// authored palette edit need not reload the artwork.
object.host_palette = (object.attributes >> 1) & 7;
object.host_generation = pose->generation;
object.host_orientation = display_mirror
? native::SpriteOrientation::Mirrored : native::SpriteOrientation::Normal;
object.identity = (std::uint64_t(1) << 63) | pose->generation;
}
} else
++host_sprite_geometry_mismatches_;
}
}
return map_address;
}
bool GameSceneRenderer::owns_presentation_oam_part(int x, int y, std::uint8_t tile,
std::uint8_t attributes, bool large,
unsigned oam_index) const {
const auto matches = [&](const PresentationObject &object) {
return object.x >= -256 && object.x < 256 && object.y >= -32 && object.y < 224 &&
((unsigned(object.x) - unsigned(x)) & 511) == 0 &&
((unsigned(object.y) - unsigned(y)) & 255) == 0 && object.tile == tile &&
object.attributes == attributes && object.large == large;
};
// Emitted overlays can have no actor identity. Only their actual OAM
// ordinal owns them; an equal actor tuple must not claim a UI indicator.
if (presentation_oam_indexed_)
return oam_index < presentation_oam_.size() && presentation_oam_[oam_index] &&
matches(*presentation_oam_[oam_index]);
return std::any_of(presentation_objects_.begin(), presentation_objects_.end(),
[&](const auto &object) { return object.identity && matches(object); });
}
std::optional<GameSceneRenderer::HostObjectPart>
GameSceneRenderer::host_oam_part(int x, int y, std::uint8_t tile, std::uint8_t attributes, bool large,
unsigned oam_index) const {
const auto matches = [&](const PresentationObject &object) {
// C08CD5 can publish signed X -256..255 and Y -32..223. Exclude
// offscreen host continuations which merely alias an OAM coordinate.
return object.host_image && object.x >= -256 && object.x < 256 && object.y >= -32 && object.y < 224 &&
((unsigned(object.x) - unsigned(x)) & 511) == 0 &&
((unsigned(object.y) - unsigned(y)) & 255) == 0 && object.tile == tile &&
object.attributes == attributes && object.large == large;
};
if (presentation_oam_indexed_) {
if (oam_index >= presentation_oam_.size())
return {};
const auto &object = presentation_oam_[oam_index];
if (object && matches(*object))
return HostObjectPart{object->host_image->parts[object->host_part].indices, object->host_palette,
object->host_generation};
return {};
}
for (const auto &object : presentation_objects_) {
if (matches(object))
return HostObjectPart{object.host_image->parts[object.host_part].indices, object.host_palette,
object.host_generation};
}
return {};
}
void GameSceneRenderer::presentation_object_pixels(const SceneReadView &view, unsigned y,
std::span<Pixel> result, int origin) const {
object_pixels(view, view.native_sprites && native_sprite_frame_ ? native_sprite_objects_ : presentation_objects_,
y, result, origin, true);
}
int GameSceneRenderer::ending_soul_shift(const PresentationObject &object) const {
if (!presentation_robot_ending_ || object.ending_departure < 0)
return 0;
return int(object.ending_departure * float((presentation_width_ - 256) / 2) + 0.5f);
}
void GameSceneRenderer::object_pixels(const SceneReadView &view,
std::span<const PresentationObject> objects, unsigned y,
std::span<Pixel> result, int origin, bool presentation) const {
constexpr unsigned sizes[8][2][2] = {{{8, 8}, {16, 16}}, {{8, 8}, {32, 32}}, {{8, 8}, {64, 64}},
{{16, 16}, {32, 32}}, {{16, 16}, {64, 64}}, {{32, 32}, {64, 64}},
{{16, 32}, {32, 64}}, {{16, 32}, {32, 32}}};
constexpr int priorities[3][4] = {{2, 5, 8, 11}, {1, 3, 7, 10}, {1, 3, 5, 7}};
for (const auto &object : objects) {
const unsigned width = object.fragment_pixels ? object.fragment_pixels->width :
object.native_owned ? 16 : sizes[view.ppu_registers[1] >> 5][object.large][0],
height = object.fragment_pixels ? object.fragment_pixels->height :
object.native_owned ? 16 : sizes[view.ppu_registers[1] >> 5][object.large][1];
const bool fragment = view.native_sprites && object.fragment_pixels;
const bool host = (object.native_owned ? bool(view.native_sprites) : bool(view.host_sprites)) &&
object.host_image && width == 16 && height == 16;
int row = int(y) - object.y;
if (row < 0 || row >= int(height))
continue;
const unsigned attr = object.attributes,
pal = host ? object.host_palette : (attr >> 1) & 7,
mode = view.ppu_registers[5] & 7;
const int priority = priorities[std::min(mode, 2u)][(attr >> 4) & 3];
if (!host && !fragment && (attr & 0x80))
row = int(height) - 1 - row;
const unsigned base = (view.ppu_registers[1] & 7) * 16384 +
((attr & 1) ? (((view.ppu_registers[1] >> 3) & 3) + 1) * 8192 : 0);
for (unsigned col = 0; col < width; ++col) {
const int out = object.x + int(col) - origin - (presentation ? ending_soul_shift(object) : 0);
if (out < 0 || out >= int(result.size()) || result[out].priority >= 0)
continue;
unsigned color = 0;
if (fragment)
color = object.fragment_pixels->indices[unsigned(row) * width + col];
else if (host)
color = object.host_image->parts[object.host_part].indices[unsigned(row) * 16 + col];
else {
const unsigned ix = (attr & 0x40) ? width - 1 - col : col;
const unsigned tile =
(((object.tile & 0xf0) + unsigned(row / 8) * 16) & 0xf0) | ((object.tile + ix / 8) & 15);
const unsigned address = base + tile * 32 + unsigned(row & 7) * 2;
for (unsigned plane = 0; plane < 4; ++plane)
color |=
((view.video_ram[(address + (plane / 2) * 16 + (plane & 1)) & 0xffff] >> (7 - (ix & 7))) &
1)
<< plane;
}
if (color)
result[out] = {view.palette(128 + pal * 16 + color), priority, 4, pal >= 4,
128 + pal * 16 + color};
}
}
}
void GameSceneRenderer::prepare_presentation_scene(const SceneReadView &view) {
// In the US source, ordinary window/HUD tiles use BG3/BG4. The two
// generated battle backgrounds can instead target BG2 or BG3; honor the
// actual loaded_bg_data records rather than dropping that battle layer.
const auto ram_word = [&view](unsigned address) {
return unsigned(view.work_ram[address]) | (unsigned(view.work_ram[address + 1]) << 8);
};
// Address metadata is generated separately for US and JP. Scene probes
// read that selected profile rather than assuming the English RAM layout.
const auto &source = view.source_profile;
// BATTLE_ROUTINE clears its mode flag before FADE_OUT completes. Keep the
// last battle layout until it is black or replaced; never infer a new battle
// from stale loaded-background records in an unrelated menu/world scene.
const std::array<uint8_t, 7> layout{view.ppu_registers[5], view.ppu_registers[7], view.ppu_registers[8],
view.ppu_registers[9], view.ppu_registers[10], view.ppu_registers[11],
view.ppu_registers[12]};
if (ram_word(source.wram_battle_mode_flag)) {
presentation_battle_scene_ = true;
presentation_battle_layout_ = layout;
} else if ((view.ppu_registers[0] & 0x80) || !(view.ppu_registers[0] & 15) ||
layout != presentation_battle_layout_) {
presentation_battle_scene_ = false;
}
presentation_psi_display_layer_ = 0;
presentation_screen_overlay_layer_ = 0;
if (!presentation_battle_scene_)
for (unsigned slot = 0; slot < 30; ++slot) {
const unsigned event = ram_word(source.wram_entity_script_ids + slot * 2);
const unsigned phase = ram_word(source.wram_entity_script_variable0 + slot * 2);
// EVENT_452 is also Photo Man's snapshot iris. C47B77 uploads
// one 32x28 BG3 page for it and the Carpainter strike sequences.
if ((event == source.lightning_scripts.franklin_badge_reflection && phase == 1) ||
((event == source.lightning_scripts.strike_event_705 ||
event == source.lightning_scripts.strike_event_706) &&
(phase == 2 || phase == 0 || phase == 10)))
presentation_screen_overlay_layer_ = 4;
}
// Static full-screen art/text has no authored offscreen continuation.
// In particular SHOW_TITLE_SCREEN's BG1 map ($58) must not repeat the
// copyright line. Only identified scenery/animation layers extend.
presentation_layer_mask_ = 0x10;
presentation_intro_static_ = intro_interference(view);
if (presentation_intro_static_)
presentation_layer_mask_ |= 2; // Extend procedural BG2 only, keeping the BG1 card centered.
if ((view.ppu_registers[5] & 7) == 7)
presentation_layer_mask_ = 0x13; // affine scenery
presentation_jp_title_ = false;
for (unsigned slot = 0; slot < 30; ++slot)
if (ram_word(source.wram_entity_script_ids + slot * 2) == source.file_select_script)
presentation_layer_mask_ = 2; // FILE_SELECT_INIT: BG2 animation, centered BG3/OBJ
else if (view.game_version == GameVersion::JP &&
ram_word(source.wram_entity_script_ids + slot * 2) >= source.title_script_first &&
ram_word(source.wram_entity_script_ids + slot * 2) <= source.title_script_last &&
(view.ppu_registers[5] & 7) == source.title_background_mode &&
view.ppu_registers[7] == source.title_background_maps.layer1 &&
view.ppu_registers[8] == source.title_background_maps.layer2) {
presentation_jp_title_ = true;
presentation_layer_mask_ = 0x13;
}
if (presentation_battle_scene_) {
presentation_layer_mask_ = 0x10;
for (unsigned record :
{source.wram_battle_backgrounds.layer1, source.wram_battle_backgrounds.layer2}) {
const unsigned target = view.work_ram[record], depth = view.work_ram[record + 1];
if (target >= 1 && target <= 4 &&
depth == background_color_depths[view.ppu_registers[5] & 7][target - 1])
presentation_layer_mask_ |= 1u << (target - 1);
}
// SHOW_PSI_ANIMATION selects BG2 over two-bit backgrounds, BG1 over
// four-bit backgrounds. All animations use this path, including those
// without palette cycling. This is independent of flash filtering.
if (view.work_ram[source.wram_psi_animation_state]) {
presentation_psi_display_layer_ =
view.work_ram[source.wram_battle_backgrounds.layer1 + 1] == 2 ? 2u : 1u;
presentation_layer_mask_ |= presentation_psi_display_layer_;
}
}
if (!presentation_battle_scene_ && coffee_tea_backgrounds(view))
presentation_layer_mask_ = 0x13; // Animated BG1/BG2; centered BG3 captions; existing OBJ policy.
presentation_world_map_ = false;
if ((view.ppu_registers[5] & 0x37) == 1 && view.ppu_registers[7] == 0x39 &&
view.ppu_registers[8] == 0x59 && !presentation_battle_scene_ &&
view.cartridge_rom.size() >= source.rom_map_tileset_palette_sectors + 2560) {
// Align the source's full map position to the actual latched scroll;
// a game tick may have prepared the following frame's position already.
for (unsigned bg = 0; bg < 2; ++bg) {
const int camera_x = int16_t(ram_word((bg ? source.wram_background_scroll.layer2_x
: source.wram_background_scroll.layer1_x))),
camera_y = int16_t(ram_word((bg ? source.wram_background_scroll.layer2_y
: source.wram_background_scroll.layer1_y)));
presentation_world_x_[bg] =
camera_x + ((int(view.background_scroll_x[bg]) - (camera_x & 1023) + 512) & 1023) - 512;
presentation_world_y_[bg] =
camera_y + ((int(view.background_scroll_y[bg]) - (camera_y & 1023) + 512) & 1023) - 512;
}
// Confirm the source map/arrangement interpretation against displayed
// native tiles before applying it outside the viewport. These points
// avoid the centered Lumine Hall message patch and ordinary text HUD.
bool matches = true;
for (unsigned y : {8u, 216u})
for (unsigned x : {8u, 128u, 248u}) {
const unsigned mx = ((x + view.background_scroll_x[0]) & 511) / 8,
my = ((y + view.background_scroll_y[0]) & 255) / 8;
const auto actual = view.vram_word(0x7000 + (mx / 32) * 2048 + (my * 32 + (mx & 31)) * 2);
const int wx = presentation_world_x_[0] + int(x), wy = presentation_world_y_[0] + int(y);
const int tx = wx >= 0 ? wx / 8 : (wx - 7) / 8, ty = wy >= 0 ? wy / 8 : (wy - 7) / 8;
matches &= actual == presentation_map_tile(view, tx, ty, 0);
}
presentation_world_map_ = matches;
if (matches)
presentation_layer_mask_ = 0x13;
}
presentation_robot_ending_ = presentation_world_map_ && robot_ending_scene(view);
if (presentation_world_map_)
prepare_presentation_boundary(view);
else {
presentation_shift_x_ = 0;
presentation_clip_left_ = -448;
presentation_clip_right_ = 704;
presentation_camera_ = {};
}
if (presentation_world_map_ && presentation_objects_frame_ != view.completed_frames) {
if (presentation_objects_uploaded_) {
presentation_objects_ = presentation_uploaded_objects_;
presentation_oam_ = presentation_uploaded_oam_;
presentation_oam_indexed_ = presentation_uploaded_oam_indexed_;
host_artwork_revision_ = UINT64_MAX;
presentation_objects_frame_ = view.completed_frames;
} else
prepare_presentation_objects(view); // Direct-register hardware fixtures.
}
if (!presentation_world_map_) {
presentation_objects_.clear();
presentation_oam_ = {};
presentation_oam_indexed_ = false;
presentation_objects_frame_ = UINT64_MAX;
}
presentation_lumine_phase_ = -1;
// EVENT_353 -> C4880C builds both half-tile phases of the complete wall
// message in BUFFER. C48A6D uploads 30 columns by eight rows to BG1 at
// world tile (808,588), then increments that entity's VAR1. Detect the
// phase actually in VRAM, since the DMA can lag behind the script tick.
if ((view.ppu_registers[5] & 0x17) != 1 || view.ppu_registers[7] != 0x39 ||
view.work_ram[source.wram_lumine_text_header] != 8 ||
view.work_ram[source.wram_lumine_text_header + 1] != 30)
return;
for (unsigned slot = 0; slot < 30; ++slot) {
const unsigned offset = slot * 2;
if (ram_word(source.wram_entity_script_ids + offset) != source.lumine_text_script)
continue;
const unsigned limit = ram_word(source.wram_entity_script_variable0 + offset),
next = ram_word(source.wram_entity_script_variable1 + offset);
if (!limit || limit > 1400 || next > limit + 1)
continue;
for (int delta : {-1, 0, -2, -3}) {
const int phase = int(next) + delta;
if (phase < 0 || unsigned(phase) > limit)
continue;
const unsigned source_address = ((phase & 1) ? source.wram_lumine_text_maps.odd_columns
: source.wram_lumine_text_maps.even_columns) +
unsigned(phase / 2) * 16;
bool match = true;
for (unsigned column = 0; column < 30 && match; ++column)
for (unsigned row = 0; row < 8; ++row) {
const unsigned mx = (40 + column) & 63;
const unsigned actual =
view.vram_word(0x7000 + (mx / 32) * 2048 + ((12 + row) * 32 + (mx & 31)) * 2);
const unsigned expected = ram_word(source_address + column * 16 + row * 2);
if (expected < 0x0c10 || expected > 0x0c1f || actual != expected) {
match = false;
break;
}
}
if (match) {
presentation_lumine_phase_ = phase;
presentation_lumine_columns_ = limit / 2 + 30;
presentation_layer_mask_ |= 1;
return;
}
}
}
}
// Natural borders follow the source camera and extend using authored block
// zero. Constrained scenery fits within its connected sector run; narrow runs
// receive black margins instead of exposing the short road/tunnel endpoints.
void GameSceneRenderer::prepare_presentation_boundary(const SceneReadView &view) {
const auto reset = [&] {
presentation_shift_x_ = 0;
presentation_clip_left_ = -448;
presentation_clip_right_ = 704;
presentation_camera_ = {};
presentation_boundary_frame_ = view.completed_frames;
};
// Window effects use authored screen coordinates, including scanline-varying
// apertures in the title demo. Moving the world independently would move
// its subject out of the opening. Keep the source framing for both layer
// masks and color windows; map sampling still handles out-of-area tiles.
const auto ®s = view.ppu_registers;
if (presentation_width_ == 256 || (regs[0] & 0x80) || !(regs[0] & 15)) {
reset();
return;
}
const auto authored_canvas = [&] {
reset();
presentation_clip_left_ = 0;
presentation_clip_right_ = 256;
};
// Camera control does not change a map's presentation width. Ordinary
// story scenes (including the robot ending) use the same map borders as
// walking. Screen-space raster apertures still describe one authored
// canvas; repeating their membership leaks horizontal strips of scenery.
if (!presentation_aperture_ && !presentation_encounter_swirl_ && (regs[0x30] & 0xf0)) {
authored_canvas();
return;
}
const unsigned masked_layers = (regs[0x2c] & regs[0x2e]) | (regs[0x2d] & regs[0x2f]);
for (unsigned layer = 0; layer < 5; ++layer) {
const unsigned selection = (regs[0x23 + layer / 2] >> ((layer & 1) * 4)) & 15;
if (!presentation_aperture_ && !presentation_encounter_swirl_ &&
(masked_layers & (1u << layer)) && (selection & 0x0a)) {
authored_canvas();
return;
}
}
if (presentation_aperture_) { reset(); return; }
const unsigned address = view.source_profile.wram_loaded_map_tile_combination;
const unsigned combo = view.work_ram[address] | (view.work_ram[address + 1] << 8);
// Sector storage edges are not camera walls in forests or around a cave's
// black void. The existing map lookup still replaces unrelated sectors
// with this area's own border metatile, never another area's artwork.
if (presentation_robot_ending_ || natural_presentation_border(combo)) {
reset();
return;
}
// Window eligibility can change mid-frame. Honor the authored aperture
// immediately, but advance ordinary camera history only once per frame.
if (presentation_boundary_frame_ == view.completed_frames)
return;
const auto previous_frame = presentation_boundary_frame_;
presentation_boundary_frame_ = view.completed_frames;
presentation_clip_left_ = -448;
presentation_clip_right_ = 704;
// The original camera itself is not clamped. This optional display policy
// derives a horizontal region from the very same sector IDs that LOAD_MAP
// uses to hide unrelated maps. Anchor at the native viewport center and
// hold the result throughout the frame, avoiding scanline-shaped warping.
const int camera = presentation_world_x_[0];
const int center_x = camera + 128, center_y = presentation_world_y_[0] + 112;
if (center_x < 0 || center_x >= 8192 || center_y < 0 || center_y >= 10240) {
reset();
return;
}
const unsigned row = unsigned(center_y) / 128;
const auto valid = [&](int column) {
return column >= 0 && column < 32 &&
(view.cartridge_rom[view.source_profile.rom_map_tileset_palette_sectors + row * 32 +
unsigned(column)] >>
3) == combo;
};
int left = center_x / 256, right = left + 1;
if (!valid(left)) {
reset();
return;
}
while (valid(left - 1))
--left;
while (valid(right))
++right;
left *= 256;
right *= 256;
auto &history = presentation_camera_;
const bool fresh = !history.valid || history.combination != combo ||
previous_frame == UINT64_MAX || view.completed_frames != previous_frame + 1 ||
std::abs(camera - history.x) > 64 ||
std::abs(presentation_world_y_[0] - history.y) > 64 ||
left >= history.right || right <= history.left;
if (fresh) {
history = {true, combo, camera, presentation_world_y_[0], left, right, left, right, 0};
} else if (left == history.left && right == history.right) {
history.pending_frames = 0;
} else {
// A sector seam is only a coarse map-storage boundary. Require eight
// consecutive logical frames in its new span before reframing, so a
// player straddling the seam cannot keep reversing the camera target.
if (left != history.pending_left || right != history.pending_right) {
history.pending_left = left;
history.pending_right = right;
history.pending_frames = 0;
}
if (++history.pending_frames >= 8) {
history.left = left;
history.right = right;
history.pending_frames = 0;
}
}
history.x = camera;
history.y = presentation_world_y_[0];
const int width = int(presentation_width_), margin = (width - 256) / 2;
const int available = history.right - history.left;
// origin is the displayed world's left edge. The derived shift converts
// back to native coordinates for tile/sprite sampling; clip bounds remain
// in centered output coordinates, so HUD placement never follows the shift.
const int target_origin = available >= width
? std::clamp(camera - margin, history.left, history.right - width)
: history.left - (width - available) / 2;
const int target_shift = target_origin + margin - camera;
if (fresh) {
presentation_shift_x_ = target_shift;
} else {
// Ease the correction, not the native camera. Native walking/scrolling
// is still visible on its original frame. Integer steps taper to one
// pixel near the target and settle exactly without overshooting.
const int distance = target_shift - presentation_shift_x_;
const int step = std::min(4, (std::abs(distance) + 7) / 8);
presentation_shift_x_ += distance < 0 ? -step : step;
}
const int origin = camera - margin + presentation_shift_x_;
// Clip against the current authored span while its camera target settles;
// easing must never expose a neighboring map's artwork.
presentation_clip_left_ = left - origin - margin;
presentation_clip_right_ = right - origin - margin;
}
uint16_t GameSceneRenderer::presentation_map_tile(const SceneReadView &view, int tile_x, int tile_y,
unsigned bg) const {
// Read-only equivalents of C0A156/C0A1CE and C00FCB/C00E16. No map-cache
// loads, event processing, entity traversal, or spawn routine is invoked.