diff --git a/.gitignore b/.gitignore index 2b8fe8a..e7c895b 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,8 @@ !/docs/ps5-generator.md !/docs/release-v0.8.0.md !/docs/release-v0.9.0.md +!/docs/release-v0.9.1.md +!/docs/pr-review-2026-11.md !/native/ !/profiles/ /profiles/* diff --git a/README.md b/README.md index 59769f1..19efd9f 100644 --- a/README.md +++ b/README.md @@ -11,14 +11,14 @@ is Windows-first. The fork adds a Linux build (also packaged for macOS), a Linux (`sf3patch`), profiles for the Translation Project V25.1 discs, an optional accurate CD-drive timing mode, and a large automated test harness. Upstream's Windows releases, artwork tools and documentation are kept below. -**Source updates after v0.9.0:** reviewed community fixes improve memory mirrors, non-local returns, save-file flushing, overlay snapshot dispatch, scene callback discovery and composition/lookup caching. Seven additional exact disc profiles are experimental registrations. See the [PR review and validation limits](docs/pr-review-2026-11.md). These source updates are not yet in the v0.9.0 downloads below. - > **Status: work in progress.** All three scenarios boot, play and save, and save transfer between scenarios works. > End-to-end playthroughs of every scenario are still being tested. The Premium Disc (Translation V25.1) is > **experimental**: it boots and its menus work in headless smoke tests. > See [Status and known issues](#status-and-known-issues). -Upstream [v0.9.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.0) adds 2160-line rendering (**1× / 2× / 5× / 9×**) with optional four-sample SSAA, five display filters (Nearest, Bilinear, Integer smooth, Bicubic and Lanczos), guarded vertex precision for reviewed Scenario 1–3 BOOT families, sharper sampling for supported rotation backgrounds, smoother audio when presentation falls behind, fullscreen/VSync/toolbar controls, and an Apple Silicon Mac package alongside Windows and Linux. Widescreen still uses **original game graphics** — turn **AI graphics** to **Off** when using 16:9. See the [v0.9.0 release notes](docs/release-v0.9.0.md). Upstream [v0.8.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.8.0) added official widescreen support (16:9 with GPU rendering; Windows hybrid-GPU laptops request the high-performance GPU before SDL starts). +Upstream [v0.9.1](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.1) is a maintenance release that ships the community fixes reviewed in [docs/pr-review-2026-11.md](docs/pr-review-2026-11.md) (memory mirroring, non-local returns, save flushing, overlay snapshot dispatch, scene callback discovery, composition/lookup caching) and registers seven additional exact disc profiles as experimental. See the [v0.9.1 release notes](docs/release-v0.9.1.md). + +Upstream [v0.9.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.0) added 2160-line rendering (**1× / 2× / 5× / 9×**) with optional four-sample SSAA, five display filters (Nearest, Bilinear, Integer smooth, Bicubic and Lanczos), guarded vertex precision for reviewed Scenario 1–3 BOOT families, sharper sampling for supported rotation backgrounds, smoother audio when presentation falls behind, fullscreen/VSync/toolbar controls, and an Apple Silicon Mac package alongside Windows and Linux. Widescreen still uses **original game graphics** — turn **AI graphics** to **Off** when using 16:9. See the [v0.9.0 release notes](docs/release-v0.9.0.md). Upstream [v0.8.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.8.0) added official widescreen support (16:9 with GPU rendering; Windows hybrid-GPU laptops request the high-performance GPU before SDL starts). ## Contents @@ -102,7 +102,7 @@ To check a dump, `python3 -m tools.sf3patch identify DISC.cue --content-id` prin The fork has no releases of its own yet. Upstream's published packages are: -- **Windows x64:** [v0.9.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.0). +- **Windows x64:** [v0.9.1](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.1). 1. Extract the whole ZIP and open **SFIII Native.exe**. 2. Choose the scenario, your CUE or CHD, and a data folder. 3. Click **Prepare game**, then **Play**. @@ -110,17 +110,17 @@ The fork has no releases of its own yet. Upstream's published packages are: There is also an optional [offline AI graphics builder](https://github.com/mattkuhnQAAI/sfiii-native/releases/download/v0.9.0/SFIII-Offline-Graphics-Builder-0.9.0-Windows-x64.zip). See [docs/DESKTOP.md](docs/DESKTOP.md). -- **Linux x64:** [v0.9.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.0). Upstream built and +- **Linux x64:** [v0.9.1](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.1). Upstream built and synthetically tested the Linux package; real-disc gameplay, widescreen and AI graphics on Linux remain - unvalidated upstream. See [docs/POSIX.md](docs/POSIX.md) and [docs/release-v0.9.0.md](docs/release-v0.9.0.md). -- **Apple Silicon macOS:** [v0.9.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.0). Upstream + unvalidated upstream. See [docs/POSIX.md](docs/POSIX.md) and [docs/release-v0.9.1.md](docs/release-v0.9.1.md). +- **Apple Silicon macOS:** [v0.9.1](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.1). Upstream built and synthetically tested an Apple Silicon package (ad-hoc signed, not notarized). Intel Mac packages are not included in the upstream release. Real-disc gameplay, physical controllers and hardware audio on macOS remain unvalidated upstream. -Upstream releases accept only upstream's six registered discs (Sc1 USA, Sc1 V25.1, Sc2 v24, the Sc2 v24-to-V25.1 -migration, the supplied Sc2 V1.003 image whose header reports V24, and Sc3 V25.1), and they do not include the fork's -changes. To use the fork's other profiles (the V25+ add-on discs, the other Sc2 and Sc3 revisions and the Premium Disc) +Upstream v0.9.1 registers 13 exact-content profiles: its original six (Sc1 USA, Sc1 V25.1, Sc2 v24, the Sc2 +v24-to-V25.1 migration, the supplied Sc2 V1.003 image whose header reports V24, and Sc3 V25.1) plus seven experimental +registrations contributed from this fork. Upstream releases do not include the fork's other changes. To use the fork's other profiles (the V25+ add-on discs, the other Sc2 and Sc3 revisions and the Premium Disc) and the fork's fixes, build from source. Upstream's earlier v0.6.1-preview1 included faster same-address module identification, reduced repeated GPU artwork uploads, larger demand-filled artwork caches on PCs with sufficient RAM, and an adaptive audio cushion (it starts at 100 ms and grows to 150 ms after repeated underruns, trading latency for fewer interruptions). Upstream tested these on selected Windows Scenario 2 routes. It also labels the artwork styles **Animated**, **Illustrated** and **General** (with **Off** in the game); older packs and saved settings keep their internal identifiers and stay compatible. diff --git a/desktop/dependencies.json b/desktop/dependencies.json index 51fe23d..06a90f8 100644 --- a/desktop/dependencies.json +++ b/desktop/dependencies.json @@ -1,5 +1,5 @@ { - "version": "0.9.0", + "version": "0.9.1", "licenses": [ { "file": "ninja-LICENSE.txt", diff --git a/desktop/posix-dependencies.json b/desktop/posix-dependencies.json index 74b966b..22b45de 100644 --- a/desktop/posix-dependencies.json +++ b/desktop/posix-dependencies.json @@ -1,5 +1,5 @@ { - "version": "0.9.0", + "version": "0.9.1", "git": { "sdl": { "url": "https://github.com/libsdl-org/SDL.git", diff --git a/docs/DESKTOP.md b/docs/DESKTOP.md index decadac..5784f9d 100644 --- a/docs/DESKTOP.md +++ b/docs/DESKTOP.md @@ -1,12 +1,12 @@ # Automatic Windows preparation -## v0.9.0 +## v0.9.1 -Download [**SFIII-Native-0.9.0-win64.zip**](https://github.com/mattkuhnQAAI/sfiii-native/releases/download/v0.9.0/SFIII-Native-0.9.0-win64.zip), extract the complete ZIP to a new application folder and open **SFIII Native.exe**. Players do not install a compiler or enter build commands. Choose your supported disc and separate scenario data folder, then **Prepare game** and **Play**. If updating, prepare against your existing scenario data folder to retain ordinary saves; keep the old application and build for their build-specific quick states. +Download [**SFIII-Native-0.9.1-win64.zip**](https://github.com/mattkuhnQAAI/sfiii-native/releases/download/v0.9.1/SFIII-Native-0.9.1-win64.zip), extract the complete ZIP to a new application folder and open **SFIII Native.exe**. Players do not install a compiler or enter build commands. Choose your supported disc and separate scenario data folder, then **Prepare game** and **Play**. If updating, prepare against your existing scenario data folder to retain ordinary saves; keep the old application and build for their build-specific quick states. -This release adds **9×/2160-line rendering**, optional four-sample SSAA, five display filters including GPU Bicubic/Lanczos, vertex precision, sharper supported backgrounds, fullscreen/toolbar/VSync controls and smoother audio. It retains original-graphics 16:9, optional artwork, indexed pack loading, controller setup and save import/export. Rendering choices are **1× / 2× / 5× / 9×**. Use **AI graphics > Off** with 16:9 because optional artwork can misalign or pop in. See [release notes](release-v0.9.0.md) and [optional graphics setup](#optional-graphics-builder). +v0.9.1 improves loader and save reliability, caches overlay lookups, and adds experimental disc profiles. It includes **9×/2160-line rendering**, optional four-sample SSAA, five display filters including GPU Bicubic/Lanczos, vertex precision, and sharper supported backgrounds. It retains original-graphics 16:9, optional artwork, indexed pack loading, controller setup and save import/export. Rendering choices are **1× / 2× / 5× / 9×**. Use **AI graphics > Off** with 16:9 because optional artwork can misalign or pop in. See [release notes](release-v0.9.1.md) and [optional graphics setup](#optional-graphics-builder). -Linux x64 and Apple Silicon macOS archives are attached to [v0.9.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.0), subject to the validation limits in [portable setup](POSIX.md). Intel Mac is excluded. Windows gameplay checks do not establish Linux/macOS gameplay compatibility. The optional builder remains Windows x64 only. +Linux x64 and Apple Silicon macOS archives are attached to [v0.9.1](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.1), subject to the validation limits in [portable setup](POSIX.md). Intel Mac is excluded. Windows gameplay checks do not establish Linux/macOS gameplay compatibility. The optional builder remains Windows x64 only. ## v0.5.0-alpha additions diff --git a/docs/POSIX.md b/docs/POSIX.md index 744515a..f0e24f7 100644 --- a/docs/POSIX.md +++ b/docs/POSIX.md @@ -1,6 +1,6 @@ # Linux and Apple Silicon macOS -v0.9.0 supplies **Linux x86-64** and **Apple Silicon ARM64** packages alongside Windows. Intel Mac is excluded. Download the appropriate archive from [v0.9.0](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.0). +v0.9.1 supplies **Linux x86-64** and **Apple Silicon ARM64** packages alongside Windows. Intel Mac is excluded. Download the appropriate archive from [v0.9.1](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.1). ## Player setup diff --git a/docs/pr-review-2026-11.md b/docs/pr-review-2026-11.md index b430d68..debb6d7 100644 --- a/docs/pr-review-2026-11.md +++ b/docs/pr-review-2026-11.md @@ -2,7 +2,7 @@ The 17 open contributions were reviewed against v0.9.0. Changes from twelve were adapted into the current source, one was superseded, and four proposals were deferred as written. Adaptation preserves current renderer, save-identity and packaging behavior rather than replacing the runtime patch with an older snapshot. Credit: [damiantw](https://github.com/damiantw). -These are source updates after v0.9.0; existing published archives have not been replaced. New builds and new generated game programs are required to use them. Ordinary saves remain the cross-build progress path. Retain old applications/prepared builds for their native states and replay checkpoints. +These changes ship in [v0.9.1](release-v0.9.1.md). New builds and new generated game programs are required to use them. Ordinary saves remain the cross-build progress path. Retain old applications/prepared builds for their native states and replay checkpoints. | PR | Disposition | Reason and retained work | | --- | --- | --- | diff --git a/docs/release-v0.9.1.md b/docs/release-v0.9.1.md new file mode 100644 index 0000000..c7cebc1 --- /dev/null +++ b/docs/release-v0.9.1.md @@ -0,0 +1,21 @@ +# v0.9.1 — Loader, save and runtime fixes + +- Fixes Saturn RAM and backup-memory mirroring, native returns across overlay calls, scene callback discovery, and a recompiler edge case involving stores in branch delay slots. +- Flushes backup memory before replacing the save file and restores native states saved between an overlay load and its first call. +- Caches overlay dispatch and balances background composition across CPU workers. +- Returns complete CD status replies and prevents reserved sound-register writes from overwriting DSP delay taps. +- Registers seven experimental exact disc profiles, including three additional v25.1 images and four default V25+ add-on combinations. See the [edition table](../README.md#registered-game-editions). + +Thanks to [damiantw](https://github.com/damiantw) for the contributions behind these fixes. See the [PR review](pr-review-2026-11.md) for individual changes and deferred work. + +## Download and update + +Applications are available for Windows x64, Linux x86-64, and Apple Silicon macOS 13+. Extract the full archive and use **Prepare game** with your own supported CUE or CHD. The tools are bundled. No BIOS is required. The optional Windows graphics builder remains a separate download on the [v0.9.0 release](https://github.com/mattkuhnQAAI/sfiii-native/releases/tag/v0.9.0). + +To update, extract into a new application folder and prepare against your existing scenario data folder. Ordinary in-game saves stay in that folder. Keep the previous application and prepared build for its build-specific native states and replay checkpoints. The launcher save manager imports and exports individual BIN and YSBAK saves. + +Use **AI graphics Off** with 16:9. Optional artwork can misalign in widescreen. + +## Validation + +Windows checks cover fresh disc preparation, save import, runtime regressions, and 16 recorded routes across original and translated Scenario 1, the supplied Scenario 2 V1.003 edition, and translated Scenario 3. The seven new disc profiles lack local gameplay fixtures. Linux and Apple Silicon packages use hosted native builds and synthetic tests. Gameplay and physical-device behavior on those platforms remain unverified. The macOS app uses an ad-hoc signature. diff --git a/tools/check-source-package.py b/tools/check-source-package.py index eecf35a..772e5be 100644 --- a/tools/check-source-package.py +++ b/tools/check-source-package.py @@ -38,7 +38,7 @@ def main(): failures.append([name,'unreviewed generation profile']) if path.parts[0] == 'desktop' and name not in {'desktop/dependencies.json','desktop/posix-dependencies.json'} and path.suffix not in {'.py','.cs'}: failures.append([name,'not desktop application source']) - if path.parts[0] == 'docs' and name not in {'docs/BUILDING.md','docs/USAGE.md','docs/DEVELOPMENT.md','docs/DESKTOP.md','docs/POSIX.md','docs/linux-bringup.md','docs/testing-plan.md','docs/translation-patcher.md','docs/ps5-generator.md','docs/release-v0.8.0.md','docs/release-v0.9.0.md','docs/pr-review-2026-11.md'}: + if path.parts[0] == 'docs' and name not in {'docs/BUILDING.md','docs/USAGE.md','docs/DEVELOPMENT.md','docs/DESKTOP.md','docs/POSIX.md','docs/linux-bringup.md','docs/testing-plan.md','docs/translation-patcher.md','docs/ps5-generator.md','docs/release-v0.8.0.md','docs/release-v0.9.0.md','docs/release-v0.9.1.md','docs/pr-review-2026-11.md'}: failures.append([name,'local history or unreviewed documentation']) if path.suffix.lower() in FORBIDDEN or any(x in {'.local','research','sessions','captures','generated','build','data','extract'} for x in path.parts): failures.append([name, 'game/build/debug artifact path']) diff --git a/tools/runtime-diagnostics.patch b/tools/runtime-diagnostics.patch index 64ff7fc..6fd120b 100644 --- a/tools/runtime-diagnostics.patch +++ b/tools/runtime-diagnostics.patch @@ -215,6 +215,61 @@ index 566fcfd..18c8628 100644 else if (!std::strcmp(a, "--trace")) cfg.trace = true; else if (!std::strcmp(a, "--peek") && more) cfg.peek = argv[++i]; else if (!std::strcmp(a, "--coverage") && more) cfg.coverage = argv[++i]; +diff --git a/runtime/src/core/call_frames.h b/runtime/src/core/call_frames.h +new file mode 100644 +index 0000000..cf76e2d +--- /dev/null ++++ b/runtime/src/core/call_frames.h +@@ -0,0 +1,49 @@ ++// saturn-recomp runtime — the return addresses of the calls in flight, so a return can skip frames. ++// ++// Recompiled code keeps the SH-2 call chain on the host stack, and each call checks that its callee came ++// back to the instruction after it. Some code returns further out than its caller: a shared epilogue ++// entered in the middle of a function pops a frame its own caller never pushed (an `add #n,r15; ++// lds.l @r15+,pr; rts` reached by a jsr), and the rts lands on a return address an outer call is ++// waiting for. The SH-2 just goes on there. Here the frame that waits for that address is found among ++// the calls in flight and the host stack unwinds to it (SH2ReturnTo), which then goes on as if its ++// callee had returned normally. ++// ++// Each host stack (the master's, each task fiber's) has its own list. A barrier (an interrupt's entry) ++// ends the search: a handler cannot return into the code it interrupted that way. ++#pragma once ++#include ++#include ++#include ++ ++struct SH2ReturnTo { uint32_t pc; size_t depth; }; ++ ++class SH2CallFrames { ++public: ++ static constexpr uint32_t kBarrier = 0xFFFFFFFFu; ++ size_t push(uint32_t ret) { v_.push_back(ret); return v_.size() - 1; } ++ void pop(size_t depth) { if (v_.size() > depth) v_.resize(depth); } ++ void clear() { v_.clear(); } ++ size_t size() const { return v_.size(); } ++ // The innermost call in flight that returns to pc, above the innermost barrier; -1 if none. ++ long find(uint32_t pc) const { ++ if (pc == kBarrier) return -1; ++ for (size_t i = v_.size(); i-- > 0;) { ++ if (v_[i] == kBarrier) return -1; ++ if (v_[i] == pc) return (long)i; ++ } ++ return -1; ++ } ++private: ++ std::vector v_; ++}; ++ ++// The list of the host stack that runs now (tasks.cpp switches it with the fiber). ++extern thread_local SH2CallFrames* g_sh2_frames; ++extern thread_local SH2CallFrames g_sh2_master_frames; // this CPU thread's host stack ++ ++// Pushes a call (or a barrier) for the scope. ++struct SH2CallFrame { ++ size_t depth; ++ explicit SH2CallFrame(uint32_t ret) : depth(g_sh2_frames->push(ret)) {} ++ ~SH2CallFrame() { g_sh2_frames->pop(depth); } ++}; diff --git a/runtime/src/core/core.cpp b/runtime/src/core/core.cpp index cb6af72..4cd45c3 100644 --- a/runtime/src/core/core.cpp @@ -655,6 +710,47 @@ index cb6af72..4cd45c3 100644 for (int i = 0; i < g_nhooks; ++i) if (g_hooks[i].addr == addr) { if (g_hooks[i].fn) g_hooks[i].fn(c, addr); +diff --git a/runtime/src/host/frame_stats.h b/runtime/src/host/frame_stats.h +new file mode 100644 +index 0000000..00c23c1 +--- /dev/null ++++ b/runtime/src/host/frame_stats.h +@@ -0,0 +1,35 @@ ++// saturn-recomp runtime — how evenly the window shows its pictures: intervals between presents ++// and the time each field took to run, for SF3_FRAMETIME (summary at exit, optional CSV). ++#pragma once ++#include ++#include ++#include ++#include ++#include ++ ++struct FrameStats { ++ std::vector ms; // one sample per event, milliseconds ++ ++ void add(double v) { ms.push_back(v); } ++ ++ struct Summary { size_t n = 0; double mean = 0, stddev = 0, p50 = 0, p99 = 0, max = 0; size_t over = 0; }; ++ ++ // `limit`: samples above it count in `over` (a picture held on screen too long, a late field). ++ Summary summary(double limit) const { ++ Summary s; ++ s.n = ms.size(); ++ if (!s.n) return s; ++ double sum = 0; ++ for (double v : ms) { sum += v; s.over += v > limit; s.max = std::max(s.max, v); } ++ s.mean = sum / s.n; ++ double var = 0; ++ for (double v : ms) var += (v - s.mean) * (v - s.mean); ++ s.stddev = std::sqrt(var / s.n); ++ std::vector sorted = ms; ++ std::sort(sorted.begin(), sorted.end()); ++ auto at = [&](double q) { return sorted[std::min(s.n - 1, (size_t)(q * (s.n - 1) + 0.5))]; }; ++ s.p50 = at(0.5); ++ s.p99 = at(0.99); ++ return s; ++ } ++}; diff --git a/runtime/src/host/host.cpp b/runtime/src/host/host.cpp index feded39..1db8e01 100644 --- a/runtime/src/host/host.cpp @@ -6599,6 +6695,140 @@ index 15c677f..65ccb23 100644 line(c, l, r, v, gl, gr); } } +diff --git a/runtime/src/video/vdp1_steps.h b/runtime/src/video/vdp1_steps.h +new file mode 100644 +index 0000000..2e324b1 +--- /dev/null ++++ b/runtime/src/video/vdp1_steps.h +@@ -0,0 +1,128 @@ ++// saturn-recomp runtime — the step arithmetic of VDP1's shape drawing, kept apart from the ++// drawing so tests can check it. Clean-room: written from Sega's VDP1 User's Manual ++// (ST-013-R3-061694) and black-box comparison of output frames only. ++#pragma once ++#include ++ ++namespace vdp1_steps { ++ ++// a + (b - a) * k / n with an exact half rounded toward minus infinity. ++inline int lerp_half_down(int a, int b, int k, int n) { ++ if (n <= 0) return a; ++ const int64_t t = (int64_t)(b - a) * k * 2 - n; // 2n * (exact offset) - n ++ const int64_t q = t >= 0 ? (t + 2 * n - 1) / (2 * n) : -((-t) / (2 * n)); ++ return a + (int)q; ++} ++// a + (b - a) * k / n with an exact half rounded toward plus infinity. ++inline int lerp_half_up(int a, int b, int k, int n) { ++ if (n <= 0) return a; ++ const int64_t t = (int64_t)(b - a) * k * 2 + n; ++ const int64_t q = t >= 0 ? t / (2 * n) : -((-t + 2 * n - 1) / (2 * n)); ++ return a + (int)q; ++} ++// a + (b - a) * k / n with an exact half rounded away from a. ++inline int lerp_half_away(int a, int b, int k, int n) { ++ if (n <= 0) return a; ++ const int64_t d = (int64_t)(b - a) * k * 2; ++ return a + (int)(d >= 0 ? (d + n) / (2 * n) : -((-d + n) / (2 * n))); ++} ++ ++// Edge walk: the point of edge a->b at step i of n. ++inline int edge(int a, int b, int i, int n) { return lerp_half_down(a, b, i, n); } ++ ++// The texel a dot takes along a span of `len + 1` steps over a character `span` texels long, ++// counted from the character's first texel, for an unflipped character. Shrinking (more texels ++// than steps): the texel under the step's centre, floor((q + 1/2) * span / (len + 1)). ++// Otherwise corner to corner: the first texel on the first step, the last on the last, an exact ++// half rounded down. Black-box: coordinate-coded characters (every texel holding its own ++// column and row) written into the reference's VRAM through its save state and drawn by it from ++// Shining Force III's own command lists (graveyard, field, bridge battle), compared with these ++// rules texel for texel; the manual puts the character's corners on the vertices but does not ++// give the sampling. ++inline int shrink_sample(int q, int span, int len) { ++ if (len < 0 || span <= 0) return 0; ++ const int s = (int)((int64_t)(2 * q + 1) * span / (2 * (len + 1))); ++ return s < span ? s : span - 1; ++} ++inline int stretch_sample(int q, int span, int len) { ++ if (len <= 0 || span <= 0) return 0; ++ return lerp_half_down(0, span - 1, q, len); ++} ++inline int sample(int q, int span, int len) { ++ return span > len + 1 ? shrink_sample(q, span, len) : stretch_sample(q, span, len); ++} ++// A flipped character is sampled as the unflipped one turned around: step q takes the texel ++// that step len - q would take unflipped, counted from the other end. (So an exact half or a ++// centre on a texel boundary goes the other way: toward the flipped character's first texel.) ++// Returned in drawing order, before the flip the texel fetch applies. ++inline int sample_flip(int q, int span, int len, bool flip) { ++ return flip ? span - 1 - sample(len - q, span, len) : sample(q, span, len); ++} ++// The texture column for dot k of a line of len + 1 dots, and the row for line i of n + 1. ++inline int column(int k, int w, int len, bool hflip = false) { return sample_flip(k, w, len, hflip); } ++inline int row(int i, int h, int n, bool vflip = false) { return sample_flip(i, h, n, vflip); } ++ ++// High speed shrink (manual, PMOD bit 12 and FBCR EOS), applied to a line with fewer dots than ++// the character's width: the line steps over the character's w/2 column pairs as column() steps ++// over columns (flip included), and takes the even (eos 0) or odd (eos 1) column of each, counted ++// in the character as stored, so a flipped character keeps the parity of its stored columns. ++// Returns the column in drawing order, like column(). Black-box, as above. ++inline int hss_column(int k, int w, int len, bool hflip, int eos) { ++ const int half = w / 2; ++ if (half <= 0) return 0; ++ int j = column(k, half, len, hflip); ++ if (hflip) j = half - 1 - j; // the pair, counted in the stored character ++ int u = 2 * j + (eos & 1); ++ if (u > w - 1) u = w - 1; ++ return hflip ? w - 1 - u : u; ++} ++// The step an anti-aliasing dot (see aa_corner) takes its texel and Gouraud colour from: the ++// next step's, where the line is heading. Black-box, as above. ++inline int aa_step(int k, int len) { return k < len ? k + 1 : len; } ++ ++// One Gouraud channel (5 bits) at step k of n between two colours: stepped as a texture is, over ++// the |b - a| + 1 values from a to b as if they were a character's texels (sample(): the centre ++// when there are more values than steps, else corner to corner, halves down), a falling run being ++// the rising one from b turned around (sample_flip()). Black-box: the reference drawing Shining ++// Force III's own command lists with every texel a flat mid grey and coded Gouraud tables written ++// into its VRAM, so each dot shows the Gouraud value; the manual gives the vertex colours only. ++inline int shade(int a, int b, int k, int n) { ++ const int span = (b > a ? b - a : a - b) + 1; ++ return b >= a ? a + sample(k, span, n) : b + sample(n - k, span, n); ++} ++// A quadrilateral's sides are walked together in n steps, n the longer side's length in dots ++// (the larger of |dx| and |dy|). Each side steps over its own length: walk step i of n is the ++// side's step i * len / n, an exact half taken toward the smaller coordinate on the side's major ++// axis (rounded down when that coordinate rises along the side, up when it falls), and the side's ++// point and Gouraud colour are those of its own step (side_point(), shade()). Black-box: the ++// reference's frames of Shining Force III's distorted sprites, where the shorter side's points and ++// colours otherwise land a dot or a shade off on exactly those halves. ++inline int side_step(int i, int len, int n, int major_delta) { ++ return major_delta >= 0 ? lerp_half_down(0, len, i, n) : lerp_half_up(0, len, i, n); ++} ++inline int side_point(int a, int b, int j, int len) { return lerp_half_down(a, b, j, len); } ++ ++// Anti-aliasing (manual, figure 1.6): where a line steps both x and y, an extra pixel fills the ++// corner: (new x, old y) when x and y step the same way, (old x, new y) when they step opposite ways. ++struct Corner { int x, y; }; ++inline Corner aa_corner(int x, int y, int xi, int yi) { ++ return xi == yi ? Corner{x + xi, y} : Corner{x, y + yi}; ++} ++ ++// Mesh (manual, PMOD bit 8): only the dots whose x and y have equal low bits are drawn. ++inline bool mesh_drawn(int x, int y) { return ((x ^ y) & 1) == 0; } ++ ++// End codes (manual, ECD): an end code is transparent, and a line stops drawing at the second ++// end code read from the character. A texel repeated by enlargement is one read. ++struct EndCodes { ++ int seen = 0; ++ bool stopped = false; ++ // A texel read: returns false once the line has stopped. ++ bool read(bool end, bool new_texel) { ++ if (stopped) return false; ++ if (end && new_texel && ++seen == 2) stopped = true; ++ return !stopped; ++ } ++}; ++ ++} // namespace vdp1_steps diff --git a/runtime/src/video/vdp2.cpp b/runtime/src/video/vdp2.cpp index 4c8bcb1..432d521 100644 --- a/runtime/src/video/vdp2.cpp @@ -7915,6 +8145,79 @@ index 6943552..0c64057 100644 } TEST(a_damaged_file_keeps_the_saves_before_the_damage) { +diff --git a/runtime/tests/call_frames_test.cpp b/runtime/tests/call_frames_test.cpp +new file mode 100644 +index 0000000..1156811 +--- /dev/null ++++ b/runtime/tests/call_frames_test.cpp +@@ -0,0 +1,67 @@ ++// The calls in flight that a return past its caller unwinds to (src/core/call_frames.h). ++#include "test.h" ++#include "../src/core/call_frames.h" ++#include ++#include ++ ++TEST(call_frames_are_isolated_between_master_and_slave_host_threads) { ++ SH2CallFrame master(0x06001000u); ++ std::atomic ready{false},release{false}; ++ bool separate=false; ++ auto* master_frames=g_sh2_frames; ++ std::thread slave([&] { ++ SH2CallFrame call(0x06002000u); ++ separate=g_sh2_frames!=master_frames && g_sh2_frames->find(0x06001000u)<0 ++ && g_sh2_frames->find(0x06002000u)==0; ++ ready=true; ++ while(!release.load())std::this_thread::yield(); ++ }); ++ while(!ready.load())std::this_thread::yield(); ++ const bool hidden=g_sh2_frames->find(0x06002000u)<0; ++ release=true;slave.join(); ++ CHECK_EQ(separate,true);CHECK_EQ(hidden,true); ++} ++ ++TEST(call_frames_find_the_innermost_call_returning_there) { ++ SH2CallFrames f; ++ f.push(0x06001000u); ++ f.push(0x06002000u); ++ f.push(0x06001000u); ++ CHECK_EQ(f.find(0x06001000u), 2L); ++ CHECK_EQ(f.find(0x06002000u), 1L); ++ CHECK_EQ(f.find(0x06003000u), -1L); ++} ++ ++TEST(call_frames_stop_at_an_interrupt_barrier) { ++ SH2CallFrames f; ++ f.push(0x06001000u); ++ f.push(SH2CallFrames::kBarrier); ++ f.push(0x06002000u); ++ CHECK_EQ(f.find(0x06002000u), 2L); ++ CHECK_EQ(f.find(0x06001000u), -1L); ++ f.pop(1); ++ CHECK_EQ(f.find(0x06001000u), 0L); ++} ++ ++// The shape of Sc3's X1RYUTA -> X006 06044550 call: the callee's rts lands on the return address of ++// the call that entered its caller, and that call goes on from there. ++static SH2CallFrames g_test_frames; ++static uint32_t outer_frame_resumed_at; ++static void inner_returns_past_its_caller(uint32_t outer_ret) { ++ SH2CallFrame caller(0x060602C0u); // the caller's call in flight ++ long depth = g_test_frames.find(outer_ret); ++ if (depth >= 0) throw SH2ReturnTo{outer_ret, (size_t)depth}; ++} ++TEST(call_frames_unwind_to_the_waiting_call) { ++ SH2CallFrames* saved = g_sh2_frames; ++ g_sh2_frames = &g_test_frames; ++ { ++ SH2CallFrame outer(0x0605540Cu); ++ try { inner_returns_past_its_caller(0x0605540Cu); } ++ catch (const SH2ReturnTo& r) { if (r.depth == outer.depth) outer_frame_resumed_at = r.pc; else throw; } ++ CHECK_EQ(g_test_frames.size(), (size_t)1); // the caller's frame is gone ++ } ++ CHECK_EQ(outer_frame_resumed_at, 0x0605540Cu); ++ CHECK_EQ(g_test_frames.size(), (size_t)0); ++ g_sh2_frames = saved; ++} diff --git a/runtime/tests/cdblock_test.cpp b/runtime/tests/cdblock_test.cpp index 1c7acb5..71f0a98 100644 --- a/runtime/tests/cdblock_test.cpp @@ -8076,6 +8379,37 @@ index ab9b24b..bb26d61 100644 + scu_write(kT1md, 0, 4); + scu_write(kIst, 0, 4); +} +diff --git a/runtime/tests/memmap_test.cpp b/runtime/tests/memmap_test.cpp +new file mode 100644 +index 0000000..6b71f96 +--- /dev/null ++++ b/runtime/tests/memmap_test.cpp +@@ -0,0 +1,25 @@ ++// The address map outside the work RAMs. ++#include "saturn.h" ++#include "test.h" ++ ++// Backup RAM (64 KiB window at 0x00180000) repeats through 0x001FFFFF: Shining Force III ++// Scenario 3 reads a table at a negative index from 0x00200030 and lands at 0x001FFEAA. ++TEST(backup_ram_repeats_every_64k_up_to_the_low_work_ram) { ++ uint32_t keep = sh2_mmio_read(0x0018FEAB, 1); ++ sh2_mmio_write(0x0018FEAB, 0x5A, 1); ++ CHECK_EQ(sh2_io_read(0x001FFEAB, 1), 0x5Au); ++ CHECK_EQ(sh2_io_read(0x0019FEAB, 1), 0x5Au); ++ CHECK_EQ(sh2_io_read(0x201FFEAB, 1), 0x5Au); // cache-through ++ sh2_io_write(0x001FFEAB, 0xA5, 1); ++ CHECK_EQ(sh2_mmio_read(0x0018FEAB, 1), 0xA5u); ++ sh2_mmio_write(0x0018FEAB, keep, 1); ++} ++ ++// SINIT/MINIT (0x01000000-0x01FFFFFF) take writes only. Shining Force III Scenario 2 V2.000 reads a ++// battle table at index -1 and follows the word before it, 0x012C0002, as a pointer: a read there ++// must not stop the machine. ++TEST(sinit_minit_reads_float_high) { ++ CHECK_EQ(sh2_mmio_read(0x012C0002, 1), 0xFFu); ++ CHECK_EQ(sh2_mmio_read(0x012C0002, 2), 0xFFFFu); ++ CHECK_EQ(sh2_mmio_read(0x01800000, 4), 0xFFFFFFFFu); ++} diff --git a/runtime/tests/pace_test.cpp b/runtime/tests/pace_test.cpp index 7bb79b6..7db24c2 100644 --- a/runtime/tests/pace_test.cpp @@ -8106,6 +8440,1006 @@ index 7bb79b6..7db24c2 100644 + CHECK_EQ(s.n, 0u); + CHECK_EQ(s.over, 0u); +} +diff --git a/runtime/tests/runtime_bench.cpp b/runtime/tests/runtime_bench.cpp +new file mode 100644 +index 0000000..0603a4f +--- /dev/null ++++ b/runtime/tests/runtime_bench.cpp +@@ -0,0 +1,315 @@ ++// runtime_bench: disc-free timings of the runtime's hot paths, for comparing hosts (Apple Silicon, ++// x86-64 Linux) and builds. No game code or game data: invented modules, command tables and ++// screens, fixed seeds. Each faster path is timed beside the path it stands in for, and its ++// output is checked against it; any difference fails the run. ++// runtime_bench [--quick] [--markdown] [--json FILE] ++// ++// vdp1 VDP1 command tables drawn into the native framebuffer: the native line walk against ++// the general walk (vdp1_reference_raster). ++// vdp2 VDP2 composition of a 320x224 field (two bitmap screens, sprites, colour calculation): ++// bands of rows on worker threads against all rows on one thread. ++// lookup sh2_lookup over an invented module table with an overlay swapped at one address; also ++// checks that the lookup cache sees a module header overwritten in memory. ++#include "saturn/sh2.h" ++#include "video.h" ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++// ---- an invented module table (what a game's generated modules.cpp defines) ----------------- ++namespace { ++template void fn(SH2Context& c) { c.r[0] += N; } ++template constexpr std::array fns(std::integer_sequence) { return {&fn...}; } ++const auto kFns = fns(std::make_integer_sequence{}); ++ ++SH2Module g_boot{"BENCH_BOOT", 0x06004000, 0x40000, 0, nullptr, 0, nullptr, nullptr, false}; ++SH2Module g_ova{"BENCH_OVA", 0x06050000, 0x20000, 0, nullptr, 0, nullptr, nullptr, true}; ++SH2Module g_ovb{"BENCH_OVB", 0x06050000, 0x20000, 0, nullptr, 0, nullptr, nullptr, true}; ++SH2Module g_low{"BENCH_LOW", 0x00200000, 0x40000, 0, nullptr, 0, nullptr, nullptr, true}; ++std::vector g_entries[4]; ++} // namespace ++ ++extern const SH2Module* const g_sh2_modules[] = {&g_boot, &g_ova, &g_ovb, &g_low}; ++extern const int g_sh2_nmodules = 4; ++extern const uint32_t g_sh2_tasks[2] = {0, 0}; ++extern const SH2TaskSwitch g_sh2_task_switches[] = {{0, 0, 0, 0, 0}}; ++extern const int g_sh2_ntask_switches = 0; ++ ++namespace { ++ ++using Clock = std::chrono::steady_clock; ++double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } ++ ++struct Row { std::string group, name, unit; double base, fast; }; ++std::vector g_rows; ++int g_failures; ++void fail(const char* what) { std::fprintf(stderr, "FAIL: %s\n", what); ++g_failures; } ++ ++uint64_t fnv(const void* p, size_t n, uint64_t h = 1469598103934665603ull) { ++ for (size_t i = 0; i < n; ++i) { h ^= ((const uint8_t*)p)[i]; h *= 1099511628211ull; } ++ return h; ++} ++ ++// ---- VDP1 ------------------------------------------------------------------------------- ++void be16(uint32_t a, uint16_t v) { g_vdp1_vram[a & 0x7FFFF] = (uint8_t)(v >> 8); g_vdp1_vram[(a + 1) & 0x7FFFF] = (uint8_t)v; } ++ ++struct Table { ++ uint32_t a = 0; ++ void cmd(uint16_t ctrl, uint16_t pmod, uint16_t colr, uint32_t srca, int w, int h, const int* xy, uint32_t grda = 0) { ++ be16(a, ctrl); be16(a + 2, 0); be16(a + 4, pmod); be16(a + 6, colr); be16(a + 8, (uint16_t)(srca / 8)); ++ be16(a + 10, (uint16_t)((w / 8) << 8 | h)); ++ for (int i = 0; i < 8; ++i) be16(a + 12 + i * 2, (uint16_t)(xy[i] & 0x1FFF)); ++ be16(a + 28, (uint16_t)(grda / 8)); be16(a + 30, 0); ++ a += 0x20; ++ } ++ void end() { be16(a, 0x8000); } ++}; ++ ++// Textures from 0x20000: 16-bit RGB and 4-bit colour-table characters, transparent dots and all. ++void textures(std::mt19937& rng) { ++ for (uint32_t a = 0x20000; a < 0x80000; a += 2) { ++ uint32_t r = rng(); ++ uint16_t v = (r & 7) == 0 ? 0 : (uint16_t)(0x8000 | (r >> 8 & 0x7FFF)); ++ be16(a, v); ++ } ++ for (uint32_t a = 0x7F000; a < 0x7F800; a += 2) be16(a, (uint16_t)(0x8000 | (rng() & 0x7FFF))); // colour tables ++ for (uint32_t a = 0x7F800; a < 0x80000; a += 2) be16(a, (uint16_t)(rng() & 0x7FFF)); // Gouraud tables ++} ++ ++void scene(const char* name, std::mt19937& rng, Table& t) { ++ auto r = [&](int lo, int hi) { return std::uniform_int_distribution(lo, hi)(rng); }; ++ int sys[8] = {0, 0, 0, 0, 319, 223, 0, 0}; ++ t.cmd(0x0009, 0, 0, 0, 0, 0, sys); ++ int user[8] = {0, 0, 0, 0, 319, 223, 0, 0}; ++ t.cmd(0x0008, 0, 0, 0, 0, 0, user); ++ int local[8] = {0, 0, 0, 0, 0, 0, 0, 0}; ++ t.cmd(0x000A, 0, 0, 0, 0, 0, local); ++ std::string s = name; ++ auto tex = [&](int w, int h) { return (uint32_t)(0x20000 + r(0, (0x5E000 - w * h * 2) / 8) * 8); }; ++ if (s == "sprites") { // normal sprites, 32x32, RGB and colour table ++ for (int i = 0; i < 400; ++i) { ++ int xy[8] = {r(-16, 304), r(-16, 208)}; ++ bool lut = i & 1; ++ t.cmd((uint16_t)(0x0000 | r(0, 3) << 4), (uint16_t)((lut ? 1 : 5) << 3 | 0x80), ++ (uint16_t)(lut ? (0x7F000 + r(0, 63) * 32) / 8 : 0), tex(32, 32), 32, 32, xy); ++ } ++ } else if (s == "scaled") { // scaled sprites, 32x32 to 16..64 on screen ++ for (int i = 0; i < 200; ++i) { ++ int x = r(-20, 300), y = r(-20, 200), w = r(16, 64), h = r(16, 64); ++ int xy[8] = {x, y, 0, 0, x + w, y + h}; ++ t.cmd(0x0001, 5 << 3 | 0x80, 0, tex(32, 32), 32, 32, xy); ++ } ++ } else if (s == "floor") { // distorted sprites as perspective floor tiles, some shaded ++ for (int row = 0; row < 14; ++row) ++ for (int col = 0; col < 20; ++col) { ++ double y0 = 40 + row * row * 0.95, y1 = 40 + (row + 1) * (row + 1) * 0.95; ++ double s0 = 0.4 + row * 0.07, s1 = 0.4 + (row + 1) * 0.07; ++ auto px = [&](double c, double sc) { return (int)(160 + (c - 10) * 32 * sc); }; ++ int xy[8] = {px(col, s0), (int)y0, px(col + 1, s0), (int)y0, px(col + 1, s1), (int)y1, px(col, s1), (int)y1}; ++ bool shade = (row + col) % 3 == 0; ++ t.cmd(0x0002, (uint16_t)(5 << 3 | 0x80 | (shade ? 4 : 0)), 0, tex(32, 32), 32, 32, xy, ++ 0x7F800 + r(0, 255) * 8); ++ } ++ } else { // untextured polygons: Gouraud, half-transparency ++ for (int i = 0; i < 300; ++i) { ++ int x = r(0, 300), y = r(0, 200); ++ int xy[8] = {x, y, x + r(5, 60), y + r(-10, 10), x + r(5, 60), y + r(5, 60), x + r(-10, 10), y + r(5, 60)}; ++ uint16_t ccb = (uint16_t)(i % 4 == 0 ? 4 : i % 4 == 1 ? 3 : 0); ++ t.cmd(0x0004, (uint16_t)(0xC0 | ccb), (uint16_t)(0x8000 | r(0, 0x7FFF)), 0, 0, 0, xy, 0x7F800 + r(0, 255) * 8); ++ } ++ } ++ t.end(); ++} ++ ++uint64_t fb_hash(int* lit = nullptr) { ++ std::vector fb(512 * 256); ++ for (int i = 0; i < 512 * 256; ++i) fb[i] = (uint16_t)vdp1_fb_read(i * 2, 2); ++ if (lit) *lit = (int)std::count_if(fb.begin(), fb.end(), [](uint16_t d) { return d != 0; }); ++ return fnv(fb.data(), fb.size() * 2); ++} ++void fb_clear() { for (int i = 0; i < 512 * 256; ++i) vdp1_fb_write(i * 2, 0, 2); } ++ ++void bench_vdp1(bool quick) { ++ vdp1_init(); ++ vdp1_reg_write(0x00, 0, 2); // TVMR: 16 bits a pixel ++ vdp1_reg_write(0x02, 0, 2); ++ for (const char* name : {"sprites", "scaled", "floor", "polygons"}) { ++ std::mt19937 rng(1996); ++ std::memset(g_vdp1_vram, 0, sizeof g_vdp1_vram); ++ textures(rng); ++ Table t; ++ scene(name, rng, t); ++ const int draws = quick ? 10 : 150; ++ double ms[2]; ++ uint64_t hash[2]; ++ for (int reference = 1; reference >= 0; --reference) { ++ vdp1_reference_raster(reference); ++ fb_clear(); ++ vdp1_reg_write(0x04, 1, 2); ++ int lit = 0; ++ hash[reference] = fb_hash(&lit); ++ if (lit < 320 * 224 / 5) fail((std::string("vdp1 ") + name + ": the invented scene did not draw").c_str()); ++ if (std::getenv("BENCH_VERBOSE")) std::fprintf(stderr, "vdp1 %s: %d dots drawn\n", name, lit); ++ auto t0 = Clock::now(); ++ for (int i = 0; i < draws; ++i) vdp1_reg_write(0x04, 1, 2); // PTMR 1: draw now ++ ms[reference] = ms_since(t0) / draws; ++ } ++ vdp1_reference_raster(false); ++ if (hash[0] != hash[1]) fail((std::string("vdp1 ") + name + ": native walk differs from the general walk").c_str()); ++ g_rows.push_back({"vdp1", name, "ms/draw", ms[1], ms[0]}); ++ } ++} ++ ++// ---- VDP2 ------------------------------------------------------------------------------- ++void reg2(uint32_t off, uint16_t v) { g_vdp2_regs[off] = v >> 8; g_vdp2_regs[off + 1] = (uint8_t)v; } ++ ++void bench_vdp2(bool quick) { ++ std::mt19937 rng(1998); ++ std::memset(g_vdp2_regs, 0, sizeof g_vdp2_regs); ++ for (auto& b : g_vdp2_vram) b = (uint8_t)rng(); ++ for (size_t i = 0; i < sizeof g_vdp2_cram; i += 2) { uint16_t v = (uint16_t)(rng() & 0x7FFF); g_vdp2_cram[i] = v >> 8; g_vdp2_cram[i + 1] = (uint8_t)v; } ++ reg2(0x00, 0x8000); // TVMD: display on, 320x224 ++ reg2(0x20, 0x0003); // BGON: NBG0, NBG1 ++ reg2(0x28, 0x1212); // CHCTLA: NBG0 and NBG1 bitmaps, 256 colours, 512x256 ++ reg2(0x3C, 0x0010); // MPOFN: NBG1's bitmap at 0x20000 ++ reg2(0x78, 0x0001); reg2(0x7C, 0x0001); // NBG0 zoom 1.0 ++ reg2(0x88, 0x0001); reg2(0x8C, 0x0001); // NBG1 zoom 1.0 ++ reg2(0x80, 0x0013); reg2(0x84, 0x0007); // NBG1 scrolled ++ reg2(0xF8, 0x0302); // PRINA: NBG0 2, NBG1 3 ++ reg2(0xF0, 0x0505); reg2(0xF2, 0x0505); reg2(0xF4, 0x0505); reg2(0xF6, 0x0505); // sprites 5 ++ reg2(0xE0, 0x0020); // SPCTL: RGB and palette sprite dots ++ reg2(0xEC, 0x0002); // CCCTL: NBG1 colour calculation ++ reg2(0x108, 0x0C00); // CCRNA: NBG1 ratio ++ reg2(0xAC, 0x0003); reg2(0xAE, 0xFFFF); // back screen at the end of VRAM ++ // VDP1 shows sprites: rectangles of RGB dots and transparent gaps ++ for (int y = 0; y < 256; ++y) ++ for (int x = 0; x < 512; ++x) { ++ bool on = ((x / 24 + y / 20) % 3) != 0; ++ vdp1_fb_write((uint32_t)(y * 512 + x) * 2, on ? (uint32_t)(0x8000 | ((x * 7 + y * 3) & 0x7FFF)) : 0, 2); ++ } ++ vdp1_vblank_out(); ++ const int frames = quick ? 20 : 300; ++ double ms[2]; ++ uint64_t hash[2]; ++ for (int serial = 1; serial >= 0; --serial) { ++ vdp2_serial_composition(serial); ++ Frame f; ++ vdp2_compose(f); ++ hash[serial] = fnv(f.px.data(), f.px.size() * 4); ++ size_t lit = std::count_if(f.px.begin(), f.px.end(), [](uint32_t p) { return p != 0; }); ++ if (f.w != 320 || f.h != 224 || lit < f.px.size() / 2) fail("vdp2: the invented screen did not show"); ++ auto t0 = Clock::now(); ++ for (int i = 0; i < frames; ++i) vdp2_compose(f); ++ ms[serial] = ms_since(t0) / frames; ++ } ++ vdp2_serial_composition(false); ++ if (hash[0] != hash[1]) fail("vdp2: rows composed on worker threads differ from one thread's"); ++ g_rows.push_back({"vdp2", std::string("compose 320x224 (") + std::to_string(std::thread::hardware_concurrency()) + " hw threads)", ++ "ms/field", ms[1], ms[0]}); ++} ++ ++// ---- sh2_lookup ------------------------------------------------------------------------- ++uint8_t* mem(uint32_t a) { return a >> 20 == 0x060 ? g_wram_h + (a & 0xFFFFF) : g_wram_l + (a & 0xFFFFF); } ++ ++void image(SH2Module& m, uint32_t seed, int stride, int offset) { ++ std::mt19937 rng(seed); ++ for (uint32_t i = 0; i < m.size; ++i) mem(m.base)[i] = (uint8_t)rng(); ++ m.crc = sh2_crc32(mem(m.base), m.size); ++ auto& e = g_entries[&m == &g_boot ? 0 : &m == &g_ova ? 1 : &m == &g_ovb ? 2 : 3]; ++ e.clear(); ++ for (uint32_t a = (uint32_t)offset; a < m.size; a += (uint32_t)stride) e.push_back({m.base + a, kFns[(a / stride) & 63]}); ++ m.funcs = e.data(); m.nfuncs = (uint32_t)e.size(); ++} ++ ++SH2Func expected(const SH2Module& m, uint32_t addr) { ++ for (uint32_t i = 0; i < m.nfuncs; ++i) if (m.funcs[i].addr == addr) return m.funcs[i].fn; ++ return nullptr; ++} ++ ++void bench_lookup(bool quick) { ++ image(g_ovb, 3, 0x40, 0x10); // B's image first: its CRC from its own bytes ++ std::vector ovb(mem(g_ovb.base), mem(g_ovb.base) + g_ovb.size); ++ image(g_boot, 1, 0x20, 0); ++ image(g_ova, 2, 0x40, 0); ++ image(g_low, 4, 0x30, 0); ++ sh2_activate(&g_boot); sh2_activate(&g_low); sh2_activate(&g_ova); ++ // a trace: hot functions called again and again, as a game's main loop does ++ std::mt19937 rng(2026); ++ std::vector hot; ++ for (int i = 0; i < 1500; ++i) { ++ const SH2Module& m = i % 3 == 0 ? g_boot : i % 3 == 1 ? g_ova : g_low; ++ hot.push_back(m.funcs[rng() % m.nfuncs].addr); ++ } ++ std::vector trace(1 << 16); ++ std::geometric_distribution pick(0.01); ++ for (auto& a : trace) a = hot[std::min(pick(rng), (int)hot.size() - 1)]; ++ for (uint32_t a : hot) { ++ const SH2Module& m = a >> 20 == 0x002 ? g_low : a < g_ova.base ? g_boot : g_ova; ++ if (sh2_lookup(a) != expected(m, a)) { fail("lookup: wrong function"); break; } ++ } ++ const long n = quick ? 2000000 : 40000000; ++ uintptr_t sink = 0; ++ auto t0 = Clock::now(); ++ for (long i = 0; i < n; ++i) sink += (uintptr_t)sh2_lookup(trace[i & 0xFFFF]); ++ double ns = ms_since(t0) * 1e6 / n; ++ if (!sink) fail("lookup: nothing found"); ++ g_rows.push_back({"lookup", "sh2_lookup, 1500 hot entries", "ns/lookup", 0, ns}); ++ // An overlay loaded over A (by the module loader, DMA or the CPU): an address that was A's ++ // entry must now come from B, or from nothing, exactly as without the cache. ++ const uint32_t a_only = g_ova.base + 0x40; // A's entry, not B's ++ const uint32_t b_only = g_ovb.base + 0x50; // B's entry, not A's ++ if (sh2_lookup(a_only) != expected(g_ova, a_only)) fail("lookup: A before the swap"); ++ std::memcpy(mem(g_ovb.base), ovb.data(), ovb.size()); ++ if (sh2_lookup(a_only) != nullptr) fail("lookup: A's entry still found after B was loaded over it"); ++ if (sh2_lookup(b_only) != expected(g_ovb, b_only)) fail("lookup: B's entry after the swap"); ++ // a header byte overwritten in place: an unknown image, so nothing is trusted there ++ mem(g_ovb.base)[5] ^= 0xFF; ++ if (sh2_lookup(b_only) != nullptr) fail("lookup: an entry found in an overwritten image"); ++} ++ ++} // namespace ++ ++int main(int argc, char** argv) { ++ bool quick = false, markdown = false; ++ const char* json = nullptr; ++ for (int i = 1; i < argc; ++i) { ++ if (!std::strcmp(argv[i], "--quick")) quick = true; ++ else if (!std::strcmp(argv[i], "--markdown")) markdown = true; ++ else if (!std::strcmp(argv[i], "--json") && i + 1 < argc) json = argv[++i]; ++ else { std::fprintf(stderr, "usage: runtime_bench [--quick] [--markdown] [--json FILE]\n"); return 2; } ++ } ++ bench_lookup(quick); ++ bench_vdp1(quick); ++ bench_vdp2(quick); ++ if (markdown) { ++ std::printf("| group | case | unit | reference path | fast path | speed-up |\n|---|---|---|---:|---:|---:|\n"); ++ for (auto& r : g_rows) ++ if (r.base > 0) std::printf("| %s | %s | %s | %.3f | %.3f | %.2fx |\n", r.group.c_str(), r.name.c_str(), r.unit.c_str(), r.base, r.fast, r.base / r.fast); ++ else std::printf("| %s | %s | %s | | %.2f | |\n", r.group.c_str(), r.name.c_str(), r.unit.c_str(), r.fast); ++ } else { ++ for (auto& r : g_rows) ++ if (r.base > 0) std::printf("%-7s %-34s %9.3f -> %9.3f %-9s (%.2fx)\n", r.group.c_str(), r.name.c_str(), r.base, r.fast, r.unit.c_str(), r.base / r.fast); ++ else std::printf("%-7s %-34s %9s %9.2f %-9s\n", r.group.c_str(), r.name.c_str(), "", r.fast, r.unit.c_str()); ++ } ++ if (json) { ++ FILE* f = std::fopen(json, "w"); ++ if (f) { ++ std::fprintf(f, "{\"quick\": %s, \"rows\": [", quick ? "true" : "false"); ++ for (size_t i = 0; i < g_rows.size(); ++i) ++ std::fprintf(f, "%s{\"group\": \"%s\", \"case\": \"%s\", \"unit\": \"%s\", \"reference\": %.4f, \"fast\": %.4f}", i ? ", " : "", ++ g_rows[i].group.c_str(), g_rows[i].name.c_str(), g_rows[i].unit.c_str(), g_rows[i].base, g_rows[i].fast); ++ std::fprintf(f, "], \"failures\": %d}\n", g_failures); ++ std::fclose(f); ++ } ++ } ++ if (g_failures) std::fprintf(stderr, "%d check(s) failed\n", g_failures); ++ return g_failures ? 1 : 0; ++} +diff --git a/runtime/tests/scsp_replay.cpp b/runtime/tests/scsp_replay.cpp +new file mode 100644 +index 0000000..64371d5 +--- /dev/null ++++ b/runtime/tests/scsp_replay.cpp +@@ -0,0 +1,99 @@ ++// SCSP replay: the sound chip alone, outside any game, from a script, so the same registers and ++// sound RAM given to a reference can be compared sample for sample (no 68000, no game timing). ++// scsp_replay SCRIPT.bin OUT.raw ++// SCRIPT.bin: sound RAM (512 KiB, as the bus sees it), then records of little-endian u32 words: ++// 1 OFF VALUE a 16-bit register write (OFF 0x000-0xFFF) ++// 2 N N samples, appended to OUT.raw as 16-bit little-endian stereo ++// 3 L R the external input (EXTS 0-1) from here on ++// 4 FIELD I V scsp_set_internal(FIELD, I, V): inner state (sound.h's ScspField) ++// 5 FIELD N print scsp_get_internal(FIELD, 0..N-1) on a line to stdout ++// 6 REG V the 68000's register REG (Musashi's m68k_register_t) = V ++// 7 ON the 68000 runs (1) or not (0) beside the samples, from the registers given ++// 8 ADDR N print N bytes of sound RAM from ADDR as hex on a line to stdout ++// 9 print the 68000's registers D0-D7 A0-A7 PC SR USP ISP on a line to stdout ++#include "../src/sound/sound.h" ++#include "m68k.h" ++#include ++#include ++#include ++#include ++ ++int main(int argc, char** argv) { ++ if (argc < 3) { std::fprintf(stderr, "usage: scsp_replay SCRIPT.bin OUT.raw\n"); return 2; } ++ FILE* f = std::fopen(argv[1], "rb"); ++ if (!f) return 1; ++ std::vector in; ++ uint8_t buf[65536]; ++ for (size_t n; (n = std::fread(buf, 1, sizeof buf, f)) > 0;) in.insert(in.end(), buf, buf + n); ++ std::fclose(f); ++ if (in.size() < sizeof g_sound_ram) { std::fprintf(stderr, "short script\n"); return 1; } ++ scsp_reset(); ++ sound_replay_cpu(false); // Musashi's tables, before any register is set ++ std::memcpy(g_sound_ram, in.data(), sizeof g_sound_ram); ++ FILE* o = std::fopen(argv[2], "wb"); ++ if (!o) return 1; ++ auto word = [&](size_t& p) { uint32_t v; std::memcpy(&v, &in[p], 4); p += 4; return v; }; ++ int16_t ext[2] = {0, 0}; ++ for (size_t p = sizeof g_sound_ram; p + 4 <= in.size();) { ++ uint32_t op = word(p); ++ if (op == 1) { uint32_t off = word(p), v = word(p); scsp_write(off, v, 2); } ++ else if (op == 2) { ++ for (uint32_t i = word(p); i--;) { ++ int16_t s[2]; ++ sound_replay_sample(ext[0], ext[1], s); ++ uint8_t le[4] = {(uint8_t)s[0], (uint8_t)(s[0] >> 8), (uint8_t)s[1], (uint8_t)(s[1] >> 8)}; ++ std::fwrite(le, 1, 4, o); ++ } ++ } else if (op == 3) { ext[0] = (int16_t)word(p); ext[1] = (int16_t)word(p); } ++ else if (op == 5) { // print a field for indices 0..N-1 to stdout ++ uint32_t fl = word(p), n = word(p); ++ std::printf("F%u", fl); ++ for (uint32_t i = 0; i < n; ++i) std::printf(" %d", (int)scsp_get_internal((ScspField)fl, (int)i)); ++ std::printf("\n"); ++ } ++ else if (op == 6) { uint32_t reg = word(p), v = word(p); m68k_set_reg((m68k_register_t)reg, v); } ++ else if (op == 7) sound_replay_cpu(word(p) != 0); ++ else if (op == 14) { // print N register words from OFF (scsp_read) ++ uint32_t off = word(p), n = word(p); ++ std::printf("W%u", off); ++ for (uint32_t i = 0; i < n; ++i) std::printf(" %x", scsp_read(off + 2 * i, 2)); ++ std::printf("\n"); ++ } ++ else if (op == 13) { uint32_t a = word(p), v = word(p); g_sound_ram[a & 0x7FFFF] = (uint8_t)v; } // a byte the SH-2 writes (byte address) ++ else if (op == 8) { ++ uint32_t a = word(p), n = word(p); ++ std::printf("M%u ", a); ++ for (uint32_t i = 0; i < n; ++i) std::printf("%02x", g_sound_ram[(a + i) & 0x7FFFF]); ++ std::printf("\n"); ++ } ++ else if (op == 9) { ++ std::printf("R"); ++ for (int i = 0; i <= 20; ++i) if (i != 18) std::printf(" %x", m68k_get_reg(nullptr, (m68k_register_t)i)); ++ std::printf("\n"); ++ } ++ else if (op == 10) { // profile the 68000's PCs from here on (N = 1) or print the top N ++ extern uint32_t* g_m68k_pc_hist; ++ static std::vector hist(0x40000); ++ uint32_t n = word(p); ++ if (n == 1) { std::fill(hist.begin(), hist.end(), 0); g_m68k_pc_hist = hist.data(); } ++ else { ++ std::vector idx(hist.size()); ++ for (uint32_t i = 0; i < idx.size(); ++i) idx[i] = i; ++ std::partial_sort(idx.begin(), idx.begin() + n, idx.end(), [&](uint32_t a, uint32_t b) { return hist[a] > hist[b]; }); ++ for (uint32_t k = 0; k < n && hist[idx[k]]; ++k) { ++ char s[128]; unsigned len = m68k_disassemble(s, idx[k] * 2, M68K_CPU_TYPE_68000); ++ printf("P %05X %9u %u %s\n", idx[k] * 2, hist[idx[k]], len, s); ++ } ++ } ++ } ++ else if (op == 11) { // disassemble N instructions from ADDR ++ uint32_t a = word(p), n = word(p); ++ for (uint32_t k = 0; k < n; ++k) { char s[128]; unsigned len = m68k_disassemble(s, a, M68K_CPU_TYPE_68000); printf("D %05X %s\n", a, s); a += len; } ++ } ++ else if (op == 12) sound_replay_first_slice((int)word(p)); // 68000 cycles before the next sample ++ else if (op == 4) { uint32_t fl = word(p), i = word(p), v = word(p); scsp_set_internal((ScspField)fl, (int)i, v); } ++ else { std::fprintf(stderr, "bad op %u\n", op); return 1; } ++ } ++ std::fclose(o); ++ return 0; ++} +diff --git a/runtime/tests/scsp_test.cpp b/runtime/tests/scsp_test.cpp +new file mode 100644 +index 0000000..9a4d3a7 +--- /dev/null ++++ b/runtime/tests/scsp_test.cpp +@@ -0,0 +1,245 @@ ++// The SCSP and the sound 68000 against numbers measured on Beetle Saturn as a black box (its output ++// and save states only). ++#include ++#include "m68k.h" ++#include "../src/sound/sound.h" ++#include "saturn.h" ++#include ++#include "test.h" ++ ++// A released slot stops once its envelope reaches 0x3C0: it still plays that sample, then its ++// attenuation reads 0x3FF and it no longer runs. Below 0x3C0 it keeps going. ++TEST(a_released_slot_stops_when_its_envelope_reaches_0x3C0) { ++ scsp_reset(); ++ int16_t out[2]; ++ scsp_set_internal(SCSP_PLAYING, 0, 1); scsp_set_internal(SCSP_ENV_PHASE, 0, 3); scsp_set_internal(SCSP_ENV, 0, 0x3BF); ++ scsp_set_internal(SCSP_PLAYING, 1, 1); scsp_set_internal(SCSP_ENV_PHASE, 1, 3); scsp_set_internal(SCSP_ENV, 1, 0x3C0); ++ scsp_sample(0, 0, out); ++ CHECK_EQ(scsp_get_internal(SCSP_PLAYING, 0), 1u); // RR 0: the envelope holds ++ CHECK_EQ(scsp_get_internal(SCSP_ENV, 0), 0x3BFu); ++ CHECK_EQ(scsp_get_internal(SCSP_PLAYING, 1), 0u); ++ CHECK_EQ(scsp_get_internal(SCSP_ENV, 1), 0x3FFu); ++} ++ ++// The 68000's loop BODY; addq.l #1,d7; bra.s back, run for 735 samples (256 cycles each) with ++// interrupts masked: the iterations, D7. ++static uint32_t loop_iterations(const char* hex) { ++ scsp_reset(); ++ sound_replay_cpu(false); ++ std::memset(g_sound_ram, 0, sizeof g_sound_ram); ++ uint8_t code[64]; size_t n = 0; ++ for (const char* p = hex; p[0] && p[1]; p += 2) { unsigned b; sscanf(p, "%2x", &b); code[n++] = (uint8_t)b; } ++ code[n++] = 0x52; code[n++] = 0x87; // addq.l #1,d7 ++ code[n] = 0x60; code[n + 1] = (uint8_t)-(int)(n + 2); n += 2; // bra.s to the body ++ std::memcpy(g_sound_ram + 0x7E000, code, n); ++ for (int r = M68K_REG_D0; r <= M68K_REG_A6; ++r) m68k_set_reg((m68k_register_t)r, r >= M68K_REG_A0 ? 0x70000 : 0); ++ m68k_set_reg(M68K_REG_SR, 0x2700); ++ m68k_set_reg(M68K_REG_A7, 0x7F000); ++ m68k_set_reg(M68K_REG_PC, 0x7E000); ++ sound_replay_cpu(true); ++ int16_t out[2]; ++ for (int i = 0; i < 735; ++i) sound_replay_sample(0, 0, out); ++ sound_replay_cpu(false); ++ return m68k_get_reg(nullptr, M68K_REG_D7); ++} ++ ++// Cycles per iteration on Beetle (the loop's own addq.l and bra.s are 24): the 68000 manual's ++// counts plus 2 per bus access, and the instructions Beetle times otherwise. ++TEST(the_sound_68000_runs_loops_at_beetles_speed) { ++ struct { const char* body; uint32_t cycles; } cases[] = { ++ {"", 24}, // addq.l 8 + 2, bra.s 10 + 4 ++ {"4e71", 30}, // nop ++ {"3010", 36}, // move.w (a0),d0 ++ {"2010", 42}, // move.l (a0),d0 ++ {"30390007 0000", 48}, // move.w $70000,d0 ++ {"d081", 34}, // add.l d1,d0 ++ {"b081", 30}, // cmp.l d1,d0 ++ {"d2fc0060", 40}, // adda.w #$60,a1 ++ {"544a", 34}, // addq.w #2,a2 ++ {"3100", 38}, // move.w d0,-(a0) ++ {"08810003", 36}, // bclr #3,d1 ++ {"61026002 4e75", 82}, // bsr.s; bra.s; rts ++ {"487a0004 4e75", 66}, // pea; rts ++ {"4eba0004 6002 4e75", 80}, // jsr d16(pc); bra.s; rts ++ {"4efb0002", 38}, // jmp 2(pc,d0.w) ++ }; ++ for (auto& c : cases) { ++ char hex[64]; size_t k = 0; ++ for (const char* p = c.body; *p; ++p) if (*p != ' ') hex[k++] = *p; ++ hex[k] = 0; ++ uint32_t it = loop_iterations(hex), want = 735 * 256 / c.cycles; ++ if (it + 1 < want || it > want + 1) CHECK_EQ(it, want); ++ } ++} ++ ++// Timer A polled the way the sound driver does: clear SCIRE bit 6, load TIMA, then count polls ++// of SCIPD bit 6 until the timer overflows; D7 per tick is stored at 0x70000. Beetle's counts fit ++// one rule (checked offline against 11 TIMA/prescale cases): the timer steps at each sample ++// boundary whose global sample number is a multiple of the prescale, a read sees the state at ++// the time of its access, and loading TIMA does not restart the prescaler. ++static void timer_a_polls(uint8_t tima, uint8_t ctl, uint16_t* counts, int n) { ++ scsp_reset(); ++ sound_replay_cpu(false); ++ std::memset(g_sound_ram, 0, sizeof g_sound_ram); ++ const uint8_t code[] = { ++ 0x4b, 0xf9, 0x00, 0x10, 0x00, 0x00, // lea $100000,a5 ++ 0x41, 0xf9, 0x00, 0x07, 0x00, 0x00, // lea $70000,a0 ++ 0x3b, 0x7c, 0x00, 0x40, 0x04, 0x22, // move.w #$40,$422(a5) SCIRE ++ 0x3b, 0x7c, ctl, tima, 0x04, 0x18, // move.w #ctl:tima,$418(a5) ++ 0x7e, 0x00, // moveq #0,d7 ++ 0x52, 0x87, // addq.l #1,d7 ++ 0x30, 0x2d, 0x04, 0x20, // move.w $420(a5),d0 SCIPD ++ 0x08, 0x00, 0x00, 0x06, // btst #6,d0 ++ 0x67, 0xf4, // beq.s addq ++ 0x30, 0xc7, // move.w d7,(a0)+ ++ 0x60, 0xe2, // bra.s SCIRE ++ }; ++ std::memcpy(g_sound_ram + 0x7E000, code, sizeof code); ++ for (int r = M68K_REG_D0; r <= M68K_REG_A6; ++r) m68k_set_reg((m68k_register_t)r, 0); ++ m68k_set_reg(M68K_REG_SR, 0x2700); ++ m68k_set_reg(M68K_REG_A7, 0x7F000); ++ m68k_set_reg(M68K_REG_PC, 0x7E000); ++ sound_replay_cpu(true); ++ int16_t out[2]; ++ for (int i = 0; i < 735; ++i) sound_replay_sample(0, 0, out); ++ sound_replay_cpu(false); ++ for (int i = 0; i < n; ++i) counts[i] = (uint16_t)(g_sound_ram[0x70000 + 2 * i] << 8 | g_sound_ram[0x70001 + 2 * i]); ++} ++ ++// The counts below are what that rule gives for this start (program at the first cycle of sample ++// 0), so they pin the rule rather than our own output. ++TEST(timer_a_ticks_on_global_sample_boundaries_like_beetle) { ++ struct { uint8_t tima, ctl; int n; uint16_t want[8]; } cases[] = { ++ {0xFF, 0, 8, {4, 4, 3, 3, 4, 3, 3, 4}}, ++ {0xFE, 0, 8, {9, 8, 8, 8, 8, 8, 9, 8}}, ++ {0xF0, 0, 8, {75, 75, 74, 75, 74, 75, 74, 75}}, ++ {0xFF, 1, 8, {4, 8, 9, 8, 8, 8, 8, 8}}, ++ {0x80, 1, 2, {1209, 1212}}, ++ {0xF0, 2, 8, {289, 302, 302, 302, 302, 302, 302, 302}}, ++ }; ++ for (auto& c : cases) { ++ uint16_t got[8]; ++ timer_a_polls(c.tima, c.ctl, got, c.n); ++ for (int i = 0; i < c.n; ++i) CHECK_EQ(got[i], c.want[i]); ++ } ++} ++ ++// An SH-2 access to sound RAM between two polls first brings the 68000 up to the master's time ++// (sat_now_cpu: the poll's time plus what the master has spent since), to the cycle. ++TEST(an_sh2_sound_access_runs_the_68000_up_to_the_masters_time) { ++ sound_replay_cpu(false); ++ sound_power(false); ++ std::memset(g_sound_ram, 0, sizeof g_sound_ram); ++ const uint8_t vec[] = {0x00, 0x07, 0xF0, 0x00, 0x00, 0x07, 0xE0, 0x00}; // SSP, PC ++ std::memcpy(g_sound_ram, vec, sizeof vec); ++ const uint8_t loop[] = {0x52, 0x87, 0x60, 0xFC}; // addq.l #1,d7; bra.s ++ std::memcpy(g_sound_ram + 0x7E000, loop, sizeof loop); ++ SH2Context* const was = g_cpu; ++ g_cpu = &g_master; ++ const int32_t budget = g_master.budget; ++ g_master.budget = 0; // its slice spent ++ sound_power(true); ++ m68k_set_reg(M68K_REG_D7, 0); ++ sound_read(0x05A00000u, 2); ++ const uint64_t t0 = sat_now_cpu(); ++ const uint32_t d0 = m68k_get_reg(nullptr, M68K_REG_D7); ++ // 1 ms more of cycles (overspent) at the SH-2's clock (φ: 26.87 MHz after a reset) ++ g_master.budget -= 4 * (int32_t)(1000000000ull / onchip_ps_per_cycle()); ++ CHECK_EQ(sat_now_cpu() - t0 >= 999950 && sat_now_cpu() - t0 <= 1000010, true); ++ sound_read(0x05A00000u, 2); ++ const uint32_t d1 = m68k_get_reg(nullptr, M68K_REG_D7); ++ // 1 ms of the 68000 (11 289.6 cycles) is 470 loops of 24 cycles ++ CHECK_EQ(d1 - d0 >= 469 && d1 - d0 <= 471, true); ++ g_master.budget = budget; ++ g_cpu = was; ++ sound_power(false); ++} ++ ++// The LFO steps its 8-bit position once every kLfoPeriod[LFOF] samples (1 at LFOF 31, 1020 at 0); ++// LFORE holds it at 0. ++TEST(the_lfo_steps_every_period_samples_and_lfore_holds_it) { ++ scsp_reset(); ++ int16_t out[2]; ++ scsp_write(0 * 0x20 + 0x12, 31 << 10, 2); ++ scsp_write(1 * 0x20 + 0x12, 0 << 10, 2); ++ scsp_write(2 * 0x20 + 0x12, 0x8000 | 31 << 10, 2); ++ for (int i = 0; i < 5; i++) scsp_sample(0, 0, out); ++ CHECK_EQ(scsp_get_internal(SCSP_LFO_PHASE, 0), 5u); ++ CHECK_EQ(scsp_get_internal(SCSP_LFO_PHASE, 1), 1u); // its first step, then 1020 to go ++ CHECK_EQ(scsp_get_internal(SCSP_LFO_TIME, 1), 1020u - 4); ++ CHECK_EQ(scsp_get_internal(SCSP_LFO_PHASE, 2), 0u); ++} ++ ++// An attack rate of 64 or more (AR 31 with key-rate scaling) attacks at once: level 0 at key-on. ++TEST(an_attack_rate_past_62_attacks_at_once) { ++ scsp_reset(); ++ int16_t out[2]; ++ scsp_write(0x08, 31, 2); // AR 31 ++ scsp_write(0x0A, 1 << 10, 2); // KRS 1: rate 64 ++ scsp_write(0x00, 0x1800, 2); // KYONB, KYONEX ++ scsp_sample(0, 0, out); ++ CHECK_EQ(scsp_get_internal(SCSP_ENV, 0), 0u); ++ scsp_reset(); ++ scsp_write(0x08, 31, 2); // KRS 0: rate 62, from 0x280 ++ scsp_write(0x00, 0x1800, 2); ++ scsp_sample(0, 0, out); ++ CHECK_EQ(scsp_get_internal(SCSP_ENV, 0) > 0u, true); ++} ++ ++// Decay 1 ends on reaching DL even when D1R is 0 and nothing moved; an instant attack checks DL on ++// its own step, a stepped one on the next. ++TEST(decay_1_ends_at_dl_whatever_its_rate) { ++ for (int dl = 0; dl <= 1; dl++) { ++ scsp_reset(); ++ int16_t out[2]; ++ scsp_write(0x0A, dl << 5, 2); // D1R 0, DL ++ scsp_set_internal(SCSP_PLAYING, 0, 1); scsp_set_internal(SCSP_ENV, 0, 0); ++ scsp_set_internal(SCSP_ENV_PHASE, 0, 1); // decay 1 ++ scsp_sample(0, 0, out); scsp_sample(0, 0, out); ++ CHECK_EQ(scsp_get_internal(SCSP_ENV_PHASE, 0), dl ? 1u : 2u); ++ } ++ scsp_reset(); ++ int16_t out[2]; ++ scsp_write(0x08, 31, 2); scsp_write(0x0A, 1 << 10, 2); // AR 31, KRS 1: instant, DL 0 ++ scsp_write(0x00, 0x1800, 2); ++ for (int i = 0; i < 4; i++) scsp_sample(0, 0, out); ++ CHECK_EQ(scsp_get_internal(SCSP_ENV_PHASE, 0), 2u); ++} ++ ++// Unused slot register bits are not kept (black box): word 0 keeps bits 11-0, word 6 11-0, word 10 7-0. ++TEST(unused_slot_register_bits_read_back_as_0) { ++ scsp_reset(); ++ scsp_write(0x00, 0xE7FF, 2); scsp_write(0x0C, 0xFFFF, 2); scsp_write(0x14, 0xFFFF, 2); ++ CHECK_EQ(scsp_read(0x00, 2), 0x07FFu); ++ CHECK_EQ(scsp_read(0x0C, 2), 0x0FFFu); ++ CHECK_EQ(scsp_read(0x14, 2), 0x00FFu); ++} ++ ++// Backwards in a reverse loop, a step that ends past the wave's start (more than LSA samples past ++// LEA in the mirrored count) is not turned: the slot reads on below the wave until a key-on. ++TEST(a_reverse_step_past_the_waves_start_is_not_turned) { ++ for (int from = 8; from <= 9; from++) { ++ scsp_reset(); ++ int16_t out[2]; ++ scsp_write(0x00, 2 << 5, 2); // LPCTL 2 (reverse) ++ scsp_write(0x04, 0, 2); scsp_write(0x06, 10, 2); // LSA 0, LEA 10 ++ scsp_write(0x10, 1 << 11, 2); // OCT 1: 2 samples a step ++ scsp_set_internal(SCSP_PLAYING, 0, 1); scsp_set_internal(SCSP_IN_LOOP, 0, 1); ++ scsp_set_internal(SCSP_REVERSE, 0, 1); scsp_set_internal(SCSP_ADDR, 0, from); ++ scsp_sample(0, 0, out); ++ CHECK_EQ(scsp_get_internal(SCSP_LOST, 0), from == 9 ? 1u : 0u); ++ CHECK_EQ(scsp_get_internal(SCSP_ADDR, 0), from == 9 ? 11u : 0u); ++ } ++} ++ ++// MADRS is 32 words at 0x780-0x7BF; 0x7C0-0x7FF holds no register. A sound driver that clears the ++// whole 0x700-0x7FF block after setting MADRS (Shining Force III's) must keep its delay taps. ++TEST(writes_past_madrs_leave_the_delay_addresses_alone) { ++ scsp_reset(); ++ scsp_write(0x782, 0x1234, 2); ++ scsp_write(0x7C2, 0x0000, 2); ++ scsp_write(0x7FE, 0xFFFF, 2); ++ CHECK_EQ(scsp_read(0x782, 2), 0x1234u); ++ CHECK_EQ(scsp_read(0x7BE, 2), 0u); ++ CHECK_EQ(scsp_read(0x7C2, 2), 0u); ++} +diff --git a/runtime/tests/vdp1_raster_test.cpp b/runtime/tests/vdp1_raster_test.cpp +new file mode 100644 +index 0000000..fb24b1d +--- /dev/null ++++ b/runtime/tests/vdp1_raster_test.cpp +@@ -0,0 +1,84 @@ ++// The native-framebuffer line walk (vdp1_raster.inc, line_native) against the general one it ++// stands in for: random command tables over random VRAM, drawn both ways, dot for dot. ++#include "test.h" ++#include "video.h" ++#include ++#include ++#include ++ ++namespace { ++ ++void be16(uint32_t a, uint16_t v) { g_vdp1_vram[a & 0x7FFFF] = (uint8_t)(v >> 8); g_vdp1_vram[(a + 1) & 0x7FFFF] = (uint8_t)v; } ++ ++std::vector draw(bool reference, uint16_t fbcr) { ++ vdp1_reference_raster(reference); ++ vdp1_reg_write(0x00, 0, 2); // TVMR: 16 bits a pixel ++ vdp1_reg_write(0x02, fbcr & 0x10, 2); // FBCR: EOS for high speed shrink only ++ for (int i = 0; i < 512 * 256; ++i) vdp1_fb_write(i * 2, (uint32_t)(i * 2654435761u >> 16), 2); ++ vdp1_reg_write(0x04, 1, 2); // PTMR 1: draw now ++ std::vector fb(512 * 256); ++ for (int i = 0; i < 512 * 256; ++i) fb[i] = (uint16_t)vdp1_fb_read(i * 2, 2); ++ vdp1_reference_raster(false); ++ return fb; ++} ++ ++// A table of `n` random commands after system clipping, user clipping and local coordinates. ++void random_table(std::mt19937& rng, int n) { ++ auto r = [&](int lo, int hi) { return std::uniform_int_distribution(lo, hi)(rng); }; ++ // textures, colour tables and Gouraud tables: values biased toward 0 and the end codes ++ for (uint32_t a = 0x10000; a < 0x80000; a += 2) { ++ int k = r(0, 15); ++ uint16_t v = k == 0 ? 0 : k == 1 ? 0x7FFF : k == 2 ? 0xFFFF : k == 3 ? 0xF0F0 : (uint16_t)r(0, 0xFFFF); ++ be16(a, v); ++ } ++ uint32_t a = 0; ++ auto cmd = [&](uint16_t ctrl, uint16_t pmod, uint16_t colr, uint16_t srca, uint16_t size, const int* xy, uint16_t grda) { ++ be16(a, ctrl); be16(a + 2, 0); be16(a + 4, pmod); be16(a + 6, colr); be16(a + 8, srca); be16(a + 10, size); ++ for (int i = 0; i < 8; ++i) be16(a + 12 + i * 2, (uint16_t)xy[i]); ++ be16(a + 28, grda); be16(a + 30, 0); ++ a += 0x20; ++ }; ++ int z[8] = {}; ++ int sys[8] = {0, 0, 0, 0, r(100, 511), r(60, 255), 0, 0}; ++ cmd(0x0009, 0, 0, 0, 0, sys, 0); ++ int user[8] = {r(0, 200), r(0, 120), 0, 0, r(100, 400), r(60, 250), 0, 0}; ++ cmd(0x0008, 0, 0, 0, 0, user, 0); ++ int local[8] = {r(-30, 60), r(-30, 60), 0, 0, 0, 0, 0, 0}; ++ cmd(0x000A, 0, 0, 0, 0, local, 0); ++ (void)z; ++ for (int i = 0; i < n; ++i) { ++ int comm = r(0, 7); ++ uint16_t ctrl = (uint16_t)(comm | (r(0, 3) << 4) | (comm == 1 ? r(0, 15) << 8 : 0)); ++ int cmode = r(0, 5); ++ uint16_t pmod = (uint16_t)(r(0, 7) | cmode << 3 | r(0, 1) << 6 | r(0, 1) << 7 | (r(0, 3) == 0) << 8 | ++ r(0, 1) << 9 | r(0, 1) << 10 | (r(0, 7) == 0) << 15 | r(0, 1) << 12); ++ uint16_t colr = (uint16_t)(cmode == 1 ? (0x10000 + r(0, 0x1000) * 32) / 8 : r(0, 0xFFFF)); ++ uint16_t srca = (uint16_t)((0x10000 + r(0, 0x6000) * 8) / 8); ++ uint16_t size = (uint16_t)(r(1, 8) << 8 | r(1, 64)); ++ int xy[8]; ++ for (int k = 0; k < 8; ++k) xy[k] = r(0, 9) == 0 ? r(-400, 900) : r(-40, 360); ++ if (comm == 1 && (ctrl >> 8 & 15)) { xy[2] = r(-20, 200); xy[3] = r(-20, 200); } ++ for (int& v : xy) v &= 0x1FFF; ++ cmd(ctrl, pmod, colr, srca, size, xy, (uint16_t)((0x10000 + r(0, 0x1000) * 8) / 8)); ++ } ++ be16(a, 0x8000); // END ++} ++ ++} // namespace ++ ++TEST(native_line_walk_draws_as_the_general_one) { ++ std::mt19937 rng(20261025); ++ int differing = 0, drawn = 0; ++ for (int round = 0; round < 60; ++round) { ++ std::memset(g_vdp1_vram, 0, sizeof g_vdp1_vram); ++ random_table(rng, 40); ++ const uint16_t fbcr = (uint16_t)(round & 1 ? 0x10 : 0); ++ std::vector fast = draw(false, fbcr), ref = draw(true, fbcr); ++ for (int i = 0; i < 512 * 256; ++i) { ++ differing += fast[i] != ref[i]; ++ drawn += ref[i] != (uint16_t)(i * 2654435761u >> 16); ++ } ++ } ++ CHECK_EQ(differing, 0); ++ CHECK_EQ(drawn > 100000, true); ++} +diff --git a/runtime/tests/vdp1_replay.cpp b/runtime/tests/vdp1_replay.cpp +new file mode 100644 +index 0000000..9985dee +--- /dev/null ++++ b/runtime/tests/vdp1_replay.cpp +@@ -0,0 +1,36 @@ ++// VDP1 replay: draws a VRAM snapshot's command list with the runtime's own rasterizer, outside any ++// game, so a reference framebuffer for the same VRAM can be compared dot for dot (no game timing). ++// vdp1_replay VRAM.bin OUT.bin TVMR FBCR EWDR EWLR EWRR (registers in hex) ++// VRAM.bin: the 512 KiB of VDP1 VRAM, big-endian as the bus sees it. OUT.bin: the 512x256 16-bit ++// draw framebuffer, big-endian. The erase window is filled with EWDR first, the rest with 0. ++#include "../src/video/video.h" ++#include ++#include ++#include ++ ++int main(int argc, char** argv) { ++ if (argc < 8) { std::fprintf(stderr, "usage: vdp1_replay VRAM.bin OUT.bin TVMR FBCR EWDR EWLR EWRR\n"); return 2; } ++ FILE* f = std::fopen(argv[1], "rb"); ++ if (!f || std::fread(g_vdp1_vram, 1, sizeof g_vdp1_vram, f) != sizeof g_vdp1_vram) { std::fprintf(stderr, "bad VRAM file\n"); return 1; } ++ std::fclose(f); ++ unsigned r[5]; ++ for (int i = 0; i < 5; ++i) r[i] = (unsigned)std::strtoul(argv[3 + i], nullptr, 16) & 0xFFFF; ++ vdp1_init(); ++ vdp1_reg_write(0x00, r[0], 2); // TVMR ++ vdp1_reg_write(0x02, r[1] & ~3u, 2); // FBCR, no frame change or erase request ++ vdp1_reg_write(0x06, r[2], 2); vdp1_reg_write(0x08, r[3], 2); vdp1_reg_write(0x0A, r[4], 2); ++ for (int i = 0; i < 512 * 256; ++i) vdp1_fb_write(i * 2, 0, 2); ++ int x0 = (r[3] >> 9 & 0x7F) * 8, y0 = r[3] & 0x1FF, x1 = (r[4] >> 9 & 0x7F) * 8, y1 = r[4] & 0x1FF; ++ for (int y = y0; y <= y1 && y < 256; ++y) ++ for (int x = x0; x < x1 && x < 512; ++x) vdp1_fb_write((y * 512 + x) * 2, r[2], 2); ++ vdp1_reg_write(0x04, 1, 2); // PTMR 1: draw now ++ FILE* o = std::fopen(argv[2], "wb"); ++ if (!o) return 1; ++ for (int i = 0; i < 512 * 256; ++i) { ++ uint16_t v = (uint16_t)vdp1_fb_read(i * 2, 2); ++ uint8_t b[2] = {(uint8_t)(v >> 8), (uint8_t)v}; ++ std::fwrite(b, 1, 2, o); ++ } ++ std::fclose(o); ++ return 0; ++} +diff --git a/runtime/tests/vdp1_steps_test.cpp b/runtime/tests/vdp1_steps_test.cpp +new file mode 100644 +index 0000000..472e126 +--- /dev/null ++++ b/runtime/tests/vdp1_steps_test.cpp +@@ -0,0 +1,137 @@ ++// VDP1's step arithmetic (vdp1_steps.h) against the rules of Sega's VDP1 User's Manual. ++#include "../src/video/vdp1_steps.h" ++#include "test.h" ++ ++using namespace vdp1_steps; ++ ++// Figure 1.6: x and y stepping the same way put the extra dot at (new x, old y). ++TEST(aa_corner_same_direction_is_new_x_old_y) { ++ auto a = aa_corner(10, 20, 1, 1); CHECK_EQ(a.x, 11); CHECK_EQ(a.y, 20); ++ auto b = aa_corner(10, 20, -1, -1); CHECK_EQ(b.x, 9); CHECK_EQ(b.y, 20); ++} ++// Figure 1.6: opposite directions put it at (old x, new y). ++TEST(aa_corner_opposite_direction_is_old_x_new_y) { ++ auto a = aa_corner(10, 20, 1, -1); CHECK_EQ(a.x, 10); CHECK_EQ(a.y, 19); ++ auto b = aa_corner(10, 20, -1, 1); CHECK_EQ(b.x, 10); CHECK_EQ(b.y, 21); ++} ++TEST(mesh_draws_dots_with_equal_low_bits) { ++ CHECK_EQ(mesh_drawn(0, 0), true); CHECK_EQ(mesh_drawn(1, 1), true); ++ CHECK_EQ(mesh_drawn(1, 0), false); CHECK_EQ(mesh_drawn(0, 3), false); ++ CHECK_EQ(mesh_drawn(-2, 4), true); ++} ++TEST(end_code_stops_the_line_at_the_second_read) { ++ EndCodes e; ++ CHECK_EQ(e.read(false, true), true); ++ CHECK_EQ(e.read(true, true), true); // first end code: transparent, line goes on ++ CHECK_EQ(e.read(true, false), true); // the same texel again (enlarged): not a new read ++ CHECK_EQ(e.read(false, true), true); ++ CHECK_EQ(e.read(true, true), false); // second end code: stop ++ CHECK_EQ(e.read(false, true), false); ++} ++// Texture columns map the character's first and last columns on the line's ends. ++TEST(column_maps_corners_to_ends) { ++ CHECK_EQ(column(0, 16, 15), 0); ++ CHECK_EQ(column(15, 16, 15), 15); ++ for (int k = 0; k < 16; ++k) CHECK_EQ(column(k, 16, 15), k); // 1:1 is the identity ++ CHECK_EQ(column(31, 16, 31), 15); // enlarged x2 ++ CHECK_EQ(column(7, 16, 7), 15); // reduced to 8 dots ++ CHECK_EQ(column(0, 16, 7), 1); // its dots' centres ++ CHECK_EQ(column(0, 8, 0), 4); // one dot: the middle ++} ++// A flipped character is sampled as the unflipped one turned around (drawing order returned). ++TEST(flipped_columns_mirror_the_unflipped_sampling) { ++ for (int len = 0; len < 40; ++len) ++ for (int w = 1; w <= 33; ++w) ++ for (int k = 0; k <= len; ++k) ++ CHECK_EQ(column(k, w, len, true), w - 1 - column(len - k, w, len)); ++ for (int k = 0; k < 16; ++k) CHECK_EQ(column(k, 16, 15, true), k); // 1:1 still the identity ++ CHECK_EQ(column(0, 8, 0, true), 3); // one dot: the other middle ++ // the flipped 48 -> 45 shrink: centres on texel boundaries go toward the first texel ++ CHECK_EQ(column(7, 48, 44), 8); CHECK_EQ(column(7, 48, 44, true), 7); ++} ++TEST(exact_halves_round_down_unflipped_and_up_flipped) { ++ // 3 texels over 5 dots: k*(2)/4 has halves at k=1 and k=3 ++ CHECK_EQ(column(1, 3, 4), 0); CHECK_EQ(column(3, 3, 4), 1); ++ CHECK_EQ(column(1, 3, 4, true), 1); CHECK_EQ(column(3, 3, 4, true), 2); ++ CHECK_EQ(row(1, 3, 4), 0); CHECK_EQ(row(3, 3, 4), 1); ++ CHECK_EQ(row(4, 3, 4), 2); ++ CHECK_EQ(row(1, 32, 5), 3 * 32 / 12); CHECK_EQ(row(1, 32, 5, true), 7); // shrink: 8 -> 7 flipped ++} ++TEST(edge_walk_hits_both_vertices_and_rounds_halves_down) { ++ CHECK_EQ(edge(5, 9, 0, 4), 5); CHECK_EQ(edge(5, 9, 4, 4), 9); ++ CHECK_EQ(edge(0, 1, 1, 2), 0); // 0.5 -> 0 ++ CHECK_EQ(edge(0, -1, 1, 2), -1); // -0.5 -> -1 ++ CHECK_EQ(edge(0, 3, 1, 2), 1); // 1.5 -> 1 ++ CHECK_EQ(edge(7, 7, 3, 0), 7); ++} ++TEST(gouraud_steps_like_a_texture) { ++ // 32 values over 5 dots: more values than dots, so the centres (2k + 1) * 32 / 10 ++ CHECK_EQ(shade(0, 31, 0, 4), 3); CHECK_EQ(shade(0, 31, 1, 4), 9); ++ CHECK_EQ(shade(0, 31, 3, 4), 22); CHECK_EQ(shade(0, 31, 4, 4), 28); ++ // a falling run is the rising one turned around ++ for (int k = 0; k <= 4; ++k) CHECK_EQ(shade(31, 0, k, 4), shade(0, 31, 4 - k, 4)); ++ // fewer values than dots: corner to corner, halves down ++ CHECK_EQ(shade(16, 18, 0, 8), 16); CHECK_EQ(shade(16, 18, 8, 8), 18); ++ CHECK_EQ(shade(16, 18, 2, 8), 16); CHECK_EQ(shade(16, 18, 6, 8), 17); ++ CHECK_EQ(shade(7, 7, 3, 9), 7); ++} ++TEST(quad_sides_step_over_their_own_length) { ++ // a side of 4 dots walked in 5 steps: ends on both vertices, 2.4 -> 2 ++ CHECK_EQ(side_step(0, 4, 5, 4), 0); CHECK_EQ(side_step(5, 4, 5, 4), 4); ++ CHECK_EQ(side_step(3, 4, 5, 4), 2); ++ // an exact half goes toward the smaller major coordinate: 52 dots in 56 steps, step 7 is 6.5 ++ CHECK_EQ(side_step(7, 52, 56, 52), 6); // rising side: down ++ CHECK_EQ(side_step(7, 52, 56, -52), 7); // falling side: up, i.e. further toward the minus end ++ CHECK_EQ(side_point(-5, -4, 6, 52), -5); CHECK_EQ(side_point(-107, -55, 6, 52), -101); ++ CHECK_EQ(side_point(10, -42, 7, 52), 3); ++ CHECK_EQ(side_step(0, 0, 9, 0), 0); ++} ++ ++// High speed shrink steps over column pairs and takes one parity of the stored character. ++TEST(high_speed_shrink_samples_one_parity_of_stored_columns) { ++ for (int len = 0; len < 15; ++len) ++ for (int k = 0; k <= len; ++k) { ++ CHECK_EQ(hss_column(k, 16, len, false, 0) % 2, 0); ++ CHECK_EQ(hss_column(k, 16, len, false, 1) % 2, 1); ++ // flipped: the stored column (15 - drawn) keeps the parity ++ CHECK_EQ((15 - hss_column(k, 16, len, true, 0)) % 2, 0); ++ CHECK_EQ((15 - hss_column(k, 16, len, true, 1)) % 2, 1); ++ } ++ // 48 wide on 32 dots (the church wall): 24 pairs enlarged onto 32 dots, every pair used ++ bool used[24] = {}; ++ for (int k = 0; k < 32; ++k) used[hss_column(k, 48, 31, false, 0) / 2] = true; ++ for (bool u : used) CHECK_EQ(u, true); ++ // 48 wide on 8 dots: pairs sampled at the dots' centres, (2k + 1) * 24 / 16 ++ CHECK_EQ(hss_column(0, 48, 7, false, 0), 2); ++ CHECK_EQ(hss_column(7, 48, 7, false, 1), 2 * 22 + 1); ++ // a flipped 16-wide character on 4 dots, eos 0: the 8 pairs shrink onto 4 dots at centres ++ // 1,3,5,7 counted from the flipped end, i.e. stored pairs 7,5,3,1 (columns 14,10,6,2), ++ // which the flip draws at 1,5,9,13 ++ CHECK_EQ(hss_column(0, 16, 3, true, 0), 1); ++ CHECK_EQ(hss_column(1, 16, 3, true, 0), 5); ++ CHECK_EQ(hss_column(3, 16, 3, true, 0), 13); ++ CHECK_EQ(hss_column(0, 15, 3, false, 1), 1); ++ CHECK_EQ(hss_column(5, 1, 3, false, 1), 0); // no pair: column 0 ++} ++// Shrinking samples under the dot's centre; enlarging maps corner to corner. ++TEST(shrink_samples_at_dot_centres) { ++ for (int q = 0; q < 8; ++q) CHECK_EQ(shrink_sample(q, 16, 7), 2 * q + 1); ++ CHECK_EQ(shrink_sample(0, 48, 31), 0); CHECK_EQ(shrink_sample(31, 48, 31), 47); ++ CHECK_EQ(shrink_sample(1, 48, 31), 2); // 1.5 * 48 / 32 = 2.25 ++ CHECK_EQ(shrink_sample(0, 5, 0), 2); // one dot: the middle texel ++ CHECK_EQ(column(3, 16, 7), 7); // shrunk columns sample centres ++ CHECK_EQ(row(3, 16, 7), 7); // and so do rows ++ CHECK_EQ(row(1, 3, 4), 0); // enlarged rows: corner to corner, halves down ++ CHECK_EQ(row(1, 3, 4, true), 1); // a vertically flipped one rounds halves up ++ CHECK_EQ(row(3, 3, 4, true), 2); ++ CHECK_EQ(row(2, 3, 4, true), 1); ++ CHECK_EQ(row(3, 16, 7, true), 6); // shrunk rows mirror too: a centre on a boundary goes up ++ CHECK_EQ(column(1, 3, 4), 0); // enlarged columns: halves down too ++} ++// An anti-aliasing dot takes the next step's texel and colour, never past the line's end. ++TEST(aa_dot_takes_the_next_step) { ++ CHECK_EQ(aa_step(0, 5), 1); ++ CHECK_EQ(aa_step(4, 5), 5); ++ CHECK_EQ(aa_step(5, 5), 5); ++ CHECK_EQ(aa_step(0, 0), 0); ++} +diff --git a/runtime/tests/vdp2_replay.cpp b/runtime/tests/vdp2_replay.cpp +new file mode 100644 +index 0000000..3a25230 +--- /dev/null ++++ b/runtime/tests/vdp2_replay.cpp +@@ -0,0 +1,42 @@ ++// VDP2 replay: composes one field from a snapshot of VDP2 VRAM, colour RAM and registers with the ++// sprite layer taken from a given VDP1 framebuffer, outside any game, so a reference picture of ++// the same state can be compared dot for dot (no game timing). ++// vdp2_replay STATE.bin OUT.bin ++// STATE.bin, all 16-bit words big-endian as the bus sees them: VDP2 VRAM (512 KiB), colour RAM ++// (4 KiB), registers (512 bytes), the VDP1 framebuffer shown (512x256 words), then TVMR and FBCR ++// (one word each). OUT.bin: width and height (u32 little-endian), then 0x00RRGGBB per dot (u32 ++// little-endian), top row first. ++#include "../src/video/video.h" ++#include ++#include ++#include ++ ++int main(int argc, char** argv) { ++ if (argc < 3) { std::fprintf(stderr, "usage: vdp2_replay STATE.bin OUT.bin\n"); return 2; } ++ const size_t fb_bytes = 512 * 256 * 2, n = sizeof g_vdp2_vram + sizeof g_vdp2_cram + sizeof g_vdp2_regs + fb_bytes + 4; ++ std::vector in(n); ++ FILE* f = std::fopen(argv[1], "rb"); ++ if (!f || std::fread(in.data(), 1, n, f) != n) { std::fprintf(stderr, "bad state file\n"); return 1; } ++ std::fclose(f); ++ const uint8_t* p = in.data(); ++ std::memcpy(g_vdp2_vram, p, sizeof g_vdp2_vram); p += sizeof g_vdp2_vram; ++ std::memcpy(g_vdp2_cram, p, sizeof g_vdp2_cram); p += sizeof g_vdp2_cram; ++ std::memcpy(g_vdp2_regs, p, sizeof g_vdp2_regs); p += sizeof g_vdp2_regs; ++ const uint8_t* fb = p; p += fb_bytes; ++ const unsigned tvmr = p[0] << 8 | p[1], fbcr = p[2] << 8 | p[3]; ++ vdp1_init(); ++ vdp1_reg_write(0x00, tvmr, 2); ++ vdp1_reg_write(0x02, 0, 2); // one-cycle mode: the next VBlank-OUT swaps ++ for (int i = 0; i < 512 * 256; ++i) vdp1_fb_write(i * 2, fb[2 * i] << 8 | fb[2 * i + 1], 2); ++ vdp1_vblank_out(); // ... so the framebuffer written is shown ++ vdp1_reg_write(0x02, fbcr & ~3u, 2); ++ Frame out; ++ vdp2_compose(out); ++ FILE* o = std::fopen(argv[2], "wb"); ++ if (!o) return 1; ++ uint32_t wh[2] = {(uint32_t)out.w, (uint32_t)out.h}; ++ std::fwrite(wh, 4, 2, o); ++ std::fwrite(out.px.data(), 4, out.px.size(), o); ++ std::fclose(o); ++ return 0; ++} diff --git a/runtime/tests/vdp2_test.cpp b/runtime/tests/vdp2_test.cpp index 8229575..6a5ab11 100644 --- a/runtime/tests/vdp2_test.cpp @@ -8690,3 +10024,141 @@ index 4cf69d5..1bd92be 100644 + for a in sorted(self.resume_points | {self.f.entry}): + lines.append("void %s(SH2Context& c) { body_%08X(c, %s); }" % (fname(a), self.f.entry, _h(a))) return lines +diff --git a/tests/test_block_coverage.py b/tests/test_block_coverage.py +new file mode 100644 +index 0000000..442a4fa +--- /dev/null ++++ b/tests/test_block_coverage.py +@@ -0,0 +1,38 @@ ++from conftest import BASE, assemble ++ ++from saturnrecomp import sh2 ++from saturnrecomp.recomp import discover ++from saturnrecomp.recomp import emit as E ++ ++NOP, RTS = 0x0009, 0x000B ++CODE = assemble( ++ NOP, NOP, 0x8BFD, # L: nop; nop; bf L ++ 0xB001, NOP, # bsr Y ++ RTS, NOP, ++ RTS, NOP, # Y ++) ++ ++ ++def body(block_base=None): ++ img = sh2.Image(CODE, BASE) ++ prog = discover.Program(img, [BASE]) ++ b = E.Body(prog, prog.funcs[BASE], set(prog.funcs)) ++ b.block_base = block_base ++ return b, [l.strip() for l in b.emit()] ++ ++ ++def test_off_by_default_emits_nothing_extra(): ++ _, off = body() ++ assert not any(l.startswith("SH2_BLK(") for l in off) ++ ++ ++def test_every_charged_block_is_marked_once_in_order(): ++ b, on = body(block_base=10) ++ _, off = body() ++ marks = [l for l in on if l.startswith("SH2_BLK(")] ++ charges = [i for i, l in enumerate(on) if l.startswith("SH2_CYC(")] ++ assert len(marks) == len(charges) == len(b.blocks) ++ assert marks == ["SH2_BLK(c, %d);" % (10 + k) for k in range(len(marks))] ++ assert all(on[i + 1].startswith("SH2_BLK(") for i in charges) ++ assert [l for l in on if not l.startswith("SH2_BLK(")] == off # the code itself is unchanged ++ assert b.blocks[0][0] == BASE and all(n >= 1 for _, n in b.blocks) +diff --git a/tests/test_contention.py b/tests/test_contention.py +new file mode 100644 +index 0000000..6ca8cea +--- /dev/null ++++ b/tests/test_contention.py +@@ -0,0 +1,48 @@ ++"""The bus model's extra cycles (emit.contended, SH2_CYC2's last count). Each rule is a black-box ++measurement on a reference emulator: timed loops of the instruction at each pc parity, a baseline ++subtracted (see the comment above emit._READS).""" ++from conftest import BASE, assemble ++ ++from saturnrecomp import sh2 ++from saturnrecomp.recomp import discover ++from saturnrecomp.recomp import emit as E ++ ++NOP, RTS = 0x0009, 0x000B ++ ++ ++def charge(*words): ++ """The first block's charge: (its line, its extra cycles).""" ++ assert BASE % 4 == 0 ++ img = sh2.Image(assemble(*words), BASE) ++ prog = discover.Program(img, [BASE]) ++ out = [l.strip() for l in E.Body(prog, prog.funcs[BASE], set(prog.funcs)).emit()] ++ line = [l for l in out if l.startswith("SH2_CYC")][0] ++ return line, (int(line.rstrip(");").split(",")[-1]) if line.startswith("SH2_CYC2(") else 0) ++ ++ ++def test_a_read_or_a_write_at_pc_2_mod_4_costs_a_cycle(): ++ # nop; mov.l @r4,r1 (2 mod 4); nop; mov.l r0,@r4 (2 mod 4); mov.l r0,@r4 (0 mod 4); nop; rts; nop ++ assert charge(NOP, 0x6142, NOP, 0x2402, 0x2402, NOP, RTS, NOP)[1] == 2 ++ ++ ++def test_no_such_cycle_just_before_an_unconditional_branch(): ++ assert charge(NOP, 0x6142, RTS, NOP)[0].startswith("SH2_CYC(") ++ assert charge(NOP, 0x6142, NOP, RTS, NOP)[1] == 1 ++ ++ ++def test_lds_l_and_sts_l_pay_at_0_mod_4(): ++ # sts.l pr,@-r15 (0 mod 4: +1); lds.l @r15+,pr (2 mod 4: +0) ++ assert charge(0x4F22, 0x4F26, NOP, NOP, RTS, NOP)[1] == 1 ++ ++ ++def test_using_the_register_the_instruction_before_loaded(): ++ assert charge(0x6142, 0x321C, NOP, NOP, RTS, NOP)[1] == 1 # mov.l @r4,r1; add r1,r2 ++ assert charge(0x6142, 0x323C, NOP, NOP, RTS, NOP)[1] == 0 # mov.l @r4,r1; add r3,r2 ++ ++ ++def test_mul_l_and_tas_b(): ++ assert charge(0x0217, NOP, 0x441B, NOP, RTS, NOP)[1] == 1 + 7 # mul.l r1,r2; tas.b @r4 (0 mod 4) ++ ++ ++def test_code_without_such_accesses_keeps_the_plain_charge(): ++ assert charge(0x6042, NOP, RTS, NOP)[0].startswith("SH2_CYC(") +diff --git a/tests/test_state_points.py b/tests/test_state_points.py +new file mode 100644 +index 0000000..2af6ff8 +--- /dev/null ++++ b/tests/test_state_points.py +@@ -0,0 +1,34 @@ ++from conftest import BASE, assemble ++ ++from saturnrecomp import sh2 ++from saturnrecomp.recomp import discover ++from saturnrecomp.recomp import emit as E ++ ++NOP, RTS = 0x0009, 0x000B ++# BASE: a loop of two nops (bf back to BASE), then a call and its return. ++CODE = assemble( ++ NOP, NOP, 0x8BFD, # L: nop; nop; bf L ++ 0xB001, NOP, # bsr Y ++ RTS, NOP, # (resume point BASE+0x0A) ++ RTS, NOP, # Y ++) ++ ++ ++def lines(): ++ img = sh2.Image(CODE, BASE) ++ prog = discover.Program(img, [BASE]) ++ body = E.Body(prog, prog.funcs[BASE], set(prog.funcs), resume_points=[BASE + 0x0A]) ++ return [l.strip() for l in body.emit()] ++ ++ ++def test_a_state_point_is_taken_before_its_block_is_charged(): ++ # A loaded state resumes at the label and runs the block's charge again, ++ # so a dump taken after the charge would bill the block twice. ++ out = lines() ++ points = [i for i, l in enumerate(out) if l.startswith("SH2_STATE_POINT(")] ++ assert points ++ for i in points: ++ assert out[i - 1].startswith("L_"), out[i - 1:i + 2] ++ assert out[i + 1].startswith("SH2_CYC("), out[i - 1:i + 2] ++ assert not any(out[i + 1].startswith("SH2_STATE_POINT(") for i, l in enumerate(out[:-1]) ++ if l.startswith("SH2_CYC("))