Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
cc1b032
Compiled libraries: IOP software registers, sifcmd init/sregs, more c…
boubou666 Nov 9, 2026
3316162
tests: library_sregs, sregs both ways, set-sreg, sifcmd init/exit, cd…
boubou666 Nov 9, 2026
67c5867
libpad2 and libvib: native DualShock 2 sockets, report, profile and m…
boubou666 Nov 9, 2026
ad1ed60
Merge branch 'tta/libpad2' into tta/integration
boubou666 Nov 9, 2026
54b5eb7
libmpeg: sceMpegAddBs and MpegOptions for games on the SDK's model
boubou666 Nov 9, 2026
53a2915
Merge branch 'tta/libmpeg-addbs' into tta/integration
boubou666 Nov 9, 2026
c5d6408
libmpeg: sceMpegInit returns the SDK's 1 off the reference layout, an…
boubou666 Nov 9, 2026
77757f3
Merge branch 'tta/libmpeg-addbs' into tta/integration
boubou666 Nov 9, 2026
7acd01e
Free host: opt-in advanceLibrariesWhileStalled, the libraries' engine…
boubou666 Nov 9, 2026
bdc9ec9
Merge branch 'tta/sif-sregs' into tta/integration
boubou666 Nov 9, 2026
725fa5d
Controls panel: Add no longer crashes at the next input
boubou666 Nov 12, 2026
42643dd
Native IRX host: vblank waits 4 and 6, data guesses left out of disco…
boubou666 Nov 15, 2026
a7e97e6
Native IRX vblank 7; module lookup fast paths for ports with many ove…
boubou666 Nov 16, 2026
d463ecd
MeshBatch: per-batch texture clamp
boubou666 Nov 17, 2026
8beaf96
Memory card: entries listed in creation order
boubou666 Nov 18, 2026
5ffadf8
CD: opt-in timed completion of sceCdRead
boubou666 Nov 18, 2026
3a520a8
Native IRX: no ready tasks run inside a running task
boubou666 Nov 18, 2026
9261dfd
Dispatcher: outside guest code an out-call's context is its own
boubou666 Nov 18, 2026
b73692e
Save states: the whole runtime saved and loaded at the dispatcher's s…
boubou666 Nov 18, 2026
b6dc6cd
Merge JC2's save states (jc2/native-irx-host b73692e) into TTA's inte…
boubou666 Nov 18, 2026
a11c1e6
Merge master into TTA's integration (save states)
boubou666 Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions docs/save-states.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Save states

BozoEngine saves the whole running game to a file and loads it back, in the same process or a new one, so a port
can come back to the same frame later (to test a scene, to debug, or for players). A loaded state goes on exactly as
the saved run did: a headless run of Jade Cocoon 2 saved at frame 9000 and loaded in a new process has the same EE RAM
1500 frames later as the run that never stopped.

## What is saved

A state is taken at the dispatcher's **safe point**, the top of `Dispatcher::run`'s loop. No guest code is on the
host stack there: every thread's registers are in its kernel frame, and no out-call, override or native IOP code is
running. Requests (`FreeHost::requestSave` / `requestLoad`, from any thread) wait for the next safe point.

| Part | Section | Code |
| --- | --- | --- |
| EE RAM, scratchpad, VU0 data | `memory` | `Dispatcher::serialize` |
| Dispatcher clocks, counters, COP0 | `dispatcher` | `Dispatcher::serialize` |
| Threads and their frames, ready queues, semaphores, handlers, queued handlers, vblanks, deadlines | `kernel` | `Kernel::serialize` |
| Heap, pad, memory cards (in memory), CD, VU0 image, I/O, MPEG, SIF, timers, library continuations | `libraries` | `libs/libraries_state.cpp` |
| Frame count, last frame's clock | `host` | `FreeHost::serializeAll` |
| Whatever a port adds | its own name | `state::Sections` |

The native IOP host (`native::irx::CompiledLibraries`) has `serialize` too: IOP memory, tasks and their registers,
semaphores, event flags, timers, events, frame listeners, the RPC servers IOP code registered, the mixer (voices,
reverb, sound memory) and libsd. A port that owns one adds it to its section (see below).

What a port or host sets up once is **not** saved: overrides, callbacks, paths, switches, IRX images and bindings. The
loading run must be set up the same way (same build, same command line apart from the state options). A file
records a game tag (`FreeOptions::gameTag`) and a format version; a section that reads a different number of bytes
than was written fails the load with its name.

## Continuations and deadlines are data

Lambdas cannot be written to a file. Library code that leaves work for later passes a `libs::Resume` instead, a kind
plus four words:

```cpp
l.waitVblank(token, -1, Resume{kResumeCdStreamRead, {n}});
l.queueHandler(h, Resume{kResumeTimerHandlerEnd, {slot, tag, id}});
l.scheduleDeadline(key, cycle, kDeadlineDelayDue, {thread, 0, 0});
```

The kind picks a function from the libraries' table (`libraries.h`, `ResumeKind`, `NativeDeadlineKind`). A port adds
its own kinds from `kPortResumeKinds` / `kPortDeadlineKinds` with `Libraries::addResumeKind` / `addDeadlineKind`.
The `std::function` overloads still work, but while one is pending the state cannot be saved (a save waits and says
why).

## Using it in a port

```cpp
bozo::host::FreeOptions options;
options.gameTag = "SLUS-12345"; // a state loads only into the game that wrote it
options.loadState = "..."; // load before the first frame
options.loadStateFrame = 0; // or when this many frames have ended
options.saveState = "..."; // save when saveStateFrame frames have ended
options.saveStateFrame = 2000;
bozo::host::FreeHost host(options);

// The port's own state: what it registered at run time, what it keeps about guest data.
host.stateSections()->add({"myport",
[&](bozo::state::Archive &a) {
myIop->serialize(a); // a native IOP host, if the port has one
bozo::state::fields(a, myCounter, myMap); // the port's own fields
if (a.loading())
myTextureCache.clear(); // anything decoded from the old guest memory
},
[] { return myIop->unsaveable(); }}); // optional: why it cannot be saved right now

// Window builds: F5 save, F7 load, F6 / Shift+F6 pick the slot (0-9), and a "Save states" tab in F2.
game.saveState = [&](int slot) { host.requestSave(bozo::app::stateSlotPath(slot)); };
game.loadState = [&](int slot) { host.requestLoad(bozo::app::stateSlotPath(slot)); };
host.onStateMessage = [](bool, const std::string &m) { bozo::app::notify(m); };
```

A port's section walks its fields with `bozo::state::fields` (scalars, enums, strings, `std::vector`, `deque`,
`map`, `unordered_map`, `set`, `array`, C arrays, `pair`, `unique_ptr`, and any struct with an `io(Archive &, T &)`
next to it). `state::pod` writes a trivially copyable struct with no pointers as its bytes.

Things a port must think about:

- **Run-time registrations.** Anything the game made the port register (a SIF RPC server bridged to EE code, a
callback) must be kept as data in the section and registered again on load, after dropping the ones of the run
being replaced (a load can happen mid-run, from F7).
- **Caches of guest data.** Textures, meshes or pictures keyed by guest addresses are stale after a load: clear them.
- **Facts the game told the port once.** If the port noted something as the game loaded it (where a resource sits),
save it: the loaded state will not tell it again.

## Not covered yet

- The 989SND driver (`libs::SndDriver` with its engine) and a playing movie (the decoder): a save waits, with the
reason, until they are idle.
- Recorded and pinned runs (`--out`, the reference harness): their records do not follow a load.

A failed load in the middle of a run puts the state back as it was (the runtime saves itself first); a failed load
before the first frame ends the run.

## Checking a port

Headless runs are deterministic, so a state can be checked against a run that never stopped:

```
game --headless --frames 3000 --save-state s.state --save-state-at 2000 --dump-ram a.bin
game --headless --frames 3000 --load-state s.state --dump-ram b.bin # a new process
game --headless --frames 3000 --load-state s.state --load-state-at 2500 --dump-ram c.bin # a load mid-run
```

`a.bin`, `b.bin` and `c.bin` must be identical. `tests/runtime/state_tests.cpp` covers the archive, the files and a
dispatcher saved and loaded.
4 changes: 4 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# per-frame reference record (bozo/reference.h); the native libraries (bozo/libs/).
add_library(bozo_runtime_core STATIC
core/runtime_core.cpp
core/state.cpp
ee/kernel.cpp
ee/dispatcher.cpp
harness/reference.cpp)
Expand All @@ -23,10 +24,13 @@ target_compile_options(bozo_audio PRIVATE -Wall -Wextra -ffp-contract=off)
add_library(bozo_libs STATIC
native/compiled_libraries.cpp
libs/libraries.cpp
libs/libraries_state.cpp
audio/audio_state.cpp
libs/libc.cpp
libs/libm.cpp
libs/gs.cpp
libs/pad.cpp
libs/pad2.cpp
libs/timer.cpp
libs/mc.cpp
libs/cd.cpp
Expand Down
115 changes: 114 additions & 1 deletion runtime/app/panel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include "bozo/app/input_bindings.h"
#include "bozo/app/settings_tabs.h"
#include "bozo/app/video_settings.h"
#include "bozo/app/window.h"

#include <SDL3/SDL.h>

Expand All @@ -21,9 +22,12 @@
#include "imgui_impl_sdl3.h"

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <filesystem>
#include <mutex>
#include <numeric>
Expand All @@ -32,6 +36,11 @@

namespace bozo::app
{
namespace
{
void drawNotice();
}

struct Panel::Impl
{
SDL_Window *window = nullptr;
Expand Down Expand Up @@ -133,8 +142,11 @@ namespace bozo::app
binding.source == input::Source::MouseMove;
if (!(mouse && ImGui::GetIO().WantCaptureMouse))
{
// config() takes the same (non-recursive) mutex: fetched before the lock, as the other callers do.
// Under the lock it threw "resource deadlock would occur" at the first input after Add.
input::Config &config = input::config();
std::lock_guard<std::mutex> lock(input::configMutex());
std::vector<input::Binding> &list = input::config().players[m.controlsPlayer].actions[m.bindingAction];
std::vector<input::Binding> &list = config.players[m.controlsPlayer].actions[m.bindingAction];
if (std::find(list.begin(), list.end(), binding) == list.end())
list.push_back(binding);
m.bindingAction = -1;
Expand Down Expand Up @@ -170,10 +182,111 @@ namespace bozo::app
m.drawSettings();
if (m.overlay)
m.drawOverlay();
drawNotice();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}

// ---- Notices (notify): a save state's result, bottom left for a few seconds ----

namespace
{
std::mutex s_noticeMutex;
std::string s_notice;
std::chrono::steady_clock::time_point s_noticeAt;

void drawNotice()
{
std::string text;
{
std::lock_guard lock(s_noticeMutex);
if (s_notice.empty() || std::chrono::steady_clock::now() - s_noticeAt > std::chrono::seconds(4))
return;
text = s_notice;
}
const ImGuiViewport *viewport = ImGui::GetMainViewport();
const float pad = 10.0f * ImGui::GetStyle().FontScaleDpi;
ImGui::SetNextWindowPos(ImVec2(viewport->WorkPos.x + pad, viewport->WorkPos.y + viewport->WorkSize.y - pad),
ImGuiCond_Always, ImVec2(0.0f, 1.0f));
ImGui::SetNextWindowBgAlpha(0.55f);
const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize |
ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing |
ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoInputs;
if (ImGui::Begin("##notice", nullptr, flags))
ImGui::TextUnformatted(text.c_str());
ImGui::End();
}
}

void notify(const std::string &text)
{
std::lock_guard lock(s_noticeMutex);
s_notice = text;
s_noticeAt = std::chrono::steady_clock::now();
}

std::string stateSlotPath(int slot)
{
std::filesystem::path dir = userDirectory().empty() ? std::filesystem::path("states") : userDirectory() / "states";
std::error_code ec;
std::filesystem::create_directories(dir, ec);
return (dir / ("slot" + std::to_string(slot) + ".state")).string();
}

std::string stateSlotSummary(int slot)
{
const std::filesystem::path path = stateSlotPath(slot);
std::error_code ec;
const auto written = std::filesystem::last_write_time(path, ec);
if (ec)
return "Slot " + std::to_string(slot) + ": empty";
const auto system = std::chrono::clock_cast<std::chrono::system_clock>(written);
const std::time_t t = std::chrono::system_clock::to_time_t(system);
char when[32] = "";
if (const std::tm *local = std::localtime(&t))
std::strftime(when, sizeof when, "%Y-%m-%d %H:%M", local);
return "Slot " + std::to_string(slot) + ": saved " + when;
}

namespace
{
std::atomic<int> s_stateSlot{0};
}
int stateSlot() { return s_stateSlot.load(std::memory_order_relaxed); }
void setStateSlot(int slot) { s_stateSlot.store(((slot % kStateSlots) + kStateSlots) % kStateSlots); }

void registerStateTab(std::function<void(int)> save, std::function<void(int)> load)
{
ui::registerTab("Save states", [save, load] {
ImGui::TextDisabled("F5 saves the selected slot, F7 loads it, F6 / Shift+F6 selects the next / previous.");
ImGui::Separator();
for (int slot = 0; slot < kStateSlots; ++slot)
{
ImGui::PushID(slot);
const std::string summary = stateSlotSummary(slot);
if (ImGui::RadioButton(summary.c_str(), stateSlot() == slot))
setStateSlot(slot);
ImGui::SameLine(ImGui::GetContentRegionAvail().x - 120.0f * ImGui::GetStyle().FontScaleDpi);
if (ImGui::Button("Save"))
{
setStateSlot(slot);
save(slot);
}
ImGui::SameLine();
ImGui::BeginDisabled(summary.ends_with(": empty"));
if (ImGui::Button("Load"))
{
setStateSlot(slot);
load(slot);
}
ImGui::EndDisabled();
ImGui::PopID();
}
ImGui::Separator();
ImGui::TextDisabled("Files: %s", std::filesystem::path(stateSlotPath(0)).parent_path().string().c_str());
});
}

// ---- F3: the frame rate counter ----

void Panel::Impl::drawOverlay()
Expand Down
13 changes: 12 additions & 1 deletion runtime/app/window.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ namespace bozo::app
Panel panel;
if (options.panel)
panel.init(window, context);
if (game.saveState && game.loadState)
registerStateTab(game.saveState, game.loadState);

GameThread thread;
thread.game = &game;
Expand Down Expand Up @@ -284,7 +286,16 @@ namespace bozo::app
quit = true;
else if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat)
{
if (event.key.scancode == SDL_SCANCODE_F8 && sequenceLeft == 0)
if (event.key.scancode == SDL_SCANCODE_F5 && game.saveState)
game.saveState(stateSlot());
else if (event.key.scancode == SDL_SCANCODE_F7 && game.loadState)
game.loadState(stateSlot());
else if (event.key.scancode == SDL_SCANCODE_F6 && game.saveState)
{
setStateSlot(stateSlot() + ((event.key.mod & SDL_KMOD_SHIFT) ? -1 : 1));
notify(stateSlotSummary(stateSlot()));
}
else if (event.key.scancode == SDL_SCANCODE_F8 && sequenceLeft == 0)
sequenceLeft = -1; // starts at this present
else if (event.key.scancode == SDL_SCANCODE_F9)
{
Expand Down
66 changes: 66 additions & 0 deletions runtime/audio/audio_state.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// SPDX-License-Identifier: MIT
// Save states of the native mixer and libsd (bozo/state.h). Built into bozo_libs, which has the archive.
#include "bozo/audio/libsd.h"
#include "bozo/audio/mixer.h"
#include "bozo/state.h"

namespace bozo::audio
{
using state::fields;
using state::pod;

void Mixer::serialize(state::Archive &a, const uint8_t *inputBase, size_t inputBytes)
{
std::scoped_lock lock(m_mutex, m_queueMutex, m_digestMutex);
a.begin("mixer");
pod(a, m_stats);
fields(a, m_clocked, m_clockStarted, m_samplesMade, m_memory, m_digestHash, m_digestCount);
for (Group &g : m_groups)
{
for (Voice &v : g.voices)
pod(a, v);
fields(a, g.ended, g.dry, g.wet, g.mix);
for (Volume &v : g.master)
pod(a, v);
for (Volume &v : g.effect)
pod(a, v);
pod(a, g.reverb);
Input &in = g.input;
uint64_t offset = ~0ull;
if (!a.loading() && in.memory)
{
if (!inputBase || in.memory < inputBase || in.memory >= inputBase + inputBytes)
throw state::Error("save state: a mixer input plays from memory outside the IOP's");
offset = static_cast<uint64_t>(in.memory - inputBase);
}
fields(a, offset, in.samples, in.position, in.playing, in.loop, in.volume);
if (a.loading())
{
if (offset != ~0ull && (!inputBase || offset >= inputBytes))
throw state::Error("save state: a mixer input outside the IOP's memory");
in.memory = offset == ~0ull ? nullptr : inputBase + offset;
}
}
a.end();
if (a.loading())
{
// What was mixed for the host belongs to the old state.
m_queueRead = m_queueFill = 0;
}
}

void Libsd::serialize(state::Archive &a)
{
a.begin("libsd");
State &s = m_state;
fields(a, s.params, s.switches, s.addresses, s.coreAttributes, s.transferAddress, s.irqCallback, s.blockBuffer,
s.blockSize, s.halves, s.halvesPending, s.effectEnd);
for (Callback &c : s.transCallback)
pod(a, c);
for (Callback &c : s.transHandler)
pod(a, c);
for (auto &e : s.effect)
pod(a, e);
a.end();
}
}
Loading
Loading