Saving
A save is a rmp::Value — a tree of
numbers, strings, lists and objects — written to a slot with
rmp::save::write() and read back with
rmp::save::read(). Every read has a default, a write
never leaves half a file behind, and the file goes where each platform expects a game's data to
be.
rmp::Value v;
v["level"] = 7;
v["name"] = "Ada";
v["unlocked"].push("forest");
rmp::save::write("slot1", v);and, the next time the game starts:
rmp::Value v;
rmp::save::read("slot1", v);
const int level = v["level"].as_int(1); // 1 on the first run: there was nothing to readThere is no if around the read, and the first run needs no code of its own. When
there is no save, v stays empty, and an empty Value answers every question with the
default it is given.
rmp::Value#
A Value is one of six things — exactly what JSON can hold, so a real structure fits and not only flat pairs:
Type | Holds | Read with |
|---|---|---|
NONE | nothing: a missing key, an index out of range, a Value never assigned | every reader returns its fallback |
BOOL | true or false | as_bool(fallback) |
NUMBER | a double: every integer up to 253 is exact | as_int(fallback), as_float(fallback) |
STRING | text | as_string(fallback) |
LIST | Values in order | v[i], size() |
OBJECT | keys naming Values, in the order they were added | v["key"], contains(), key(i) |
Assigning makes the Value what was assigned, and assigning through a key or an index makes whatever path leads there:
rmp::Value v;
v["player"]["x"] = 120.5f; // creates "player", an object, on the way
v["player"]["hp"] = 3;
v["inventory"] = rmp::Value::list(); // an empty list, for "nothing yet"
v["inventory"].push("sword");
v["inventory"].push("rope");
v["options"]["subtitles"] = true;rmp::Value::list() and
rmp::Value::object() make an empty one of each;
push() appends to a list, and turns a Value that
holds nothing into one first. erase(key) removes a
key, and assigning rmp::Value{} to a key amounts to the same: a key that holds nothing
and a key that is not there read the same everywhere, in size(), in
contains(), in == and in the file.
A Value can also come from a JSON file of your game's: rmp::assets::load_value(), which
remembers the file, so a Debug build can reload
it while the game runs.
Reading never creates anything#
Reading through [] walks the tree and returns what is there, or nothing. It does
not add the keys it asks about, even on a Value that is not const:
rmp::Value v;
const int coins = v["stats"]["coins"].as_int(0); // 0, and v is still emptyThat is the difference from std::map, where asking is adding. Reading a save never
grows it, and reading a Value never warns about anything, so going through what a load returned
can never be what trips [dev] strict.
A read gives the fallback whenever the Value is not of the type asked for. Types are not
converted: a number is not a bool, and "7" is not 7. as_int() cuts a
number towards zero and clamps it to the range of an int, so an edited save holding a
number too big for one cannot overflow anything. as_float() clamps to the range of a
float the same way, so a finite number never reads as an infinity.
as_string() returns a view that is valid while the Value is alive and unchanged; copy it
into a std::string to keep it.
A write that cannot land#
Writing through a path creates what is missing, but it does not change what is there into
something else. Writing a key into a number — a number read from an old save, say — goes nowhere,
and says so once; so does an index past the end of a list. Turning that number into an object
behind your back would lose it. To change what a key is, assign the whole thing first:
v["stats"] = rmp::Value::object();. A list is written at 0 up to
size(), and writing at size() appends.
Walking a Value you did not write#
Reading a save never needs type(): a read of the
wrong type gives its fallback. A tree of unknown shape — one a modding tool wrote, say — is walked
with type(), size() and key(i):
rmp::Value v;
rmp::save::read("slot1", v);
const rmp::Value &items = v["inventory"];
std::vector<std::string> names;
for (int i = 0; i < items.size(); ++i) names.emplace_back(items[i].as_string("?"));
const rmp::Value &stats = v["stats"];
for (int i = 0; i < stats.size(); ++i) {
const std::string_view key = stats.key(i);
const int value = stats[key].as_int(0);
}Two Values are == when they hold the same things, whatever order an object's keys
were added in.
Writing and reading#
write(slot, value) returns whether it worked. A
write that fails leaves the previous save exactly as it was: the new file is written beside the
old one, flushed to the disk, and only then put in its place, so at every instant there is one
whole save on disk — the old or the new. The power going out in the middle of a save does not lose
the game.
A slot is the name of the file, without its extension: letters, digits,
_, - and ., not starting with a dot, at most 64 of them. Each
slot is a file of its own, so a game with three save slots, settings and a best score uses five
names. Anything else — a path above all — is refused and said once.
A Value that could not be read back is refused too, rather than written and lost: more than
64 lists and objects inside each other, a NUL character in a string or a key, or a number that is not
finite — a NaN or an infinity, which JSON cannot hold. A file holding a number too large for a
double, such as 1e400, is not a save at all: read() says UNREADABLE.
A write flushes the file to the disk, so it is a thing to do at a checkpoint, on a menu, when a level ends — not every frame.
What a read tells you#
read(slot, value) fills the Value you hand it, by
reference, and returns a
Result that is true in an if only when
the save was read and checked. When it is false,
status says why, because each reason is a
different thing to tell a player:
Status | Means |
|---|---|
OK | Read, checked, and the Value filled. |
MISSING | Nothing has been saved in that slot: the first run. |
TRUNCATED | The file is cut short, as a write the power went out on would be. |
MODIFIED | The checksum or the seal does not match: the file was edited, or the disk damaged it. |
UNREADABLE | Not a save at all, a save from a newer version of the framework, a slot name that is refused, or a file too large to be one. |
On anything but OK, the Value passed in is left exactly as it was. That gives the
pattern for loading settings: fill a struct with its defaults, read, and let each field take the
saved value when there is one.
struct Settings {
float music = 0.8f;
bool subtitles = false;
};
// Each field keeps its default unless the save has it. True when the file
// was there and could not be trusted.
bool load_settings(Settings &s) {
rmp::Value v;
const rmp::save::Result read = rmp::save::read("settings", v);
s.music = v["music"].as_float(s.music);
s.subtitles = v["subtitles"].as_bool(s.subtitles);
return read.status == rmp::save::Status::MODIFIED ||
read.status == rmp::save::Status::TRUNCATED;
}A missing file is simply the first run and needs no message; a damaged one is worth telling the player about before the next write replaces it. That is what examples/ui/04_settings does.
Slots, and where they are#
exists(slot)- Whether there is a save in that slot — what decides if a title screen offers "Continue". It does not open the file, so a damaged save exists too.
remove(slot)- Deletes it. False when there was nothing to delete.
directory()- The folder saves are written to this session, with a trailing separator.
Where saves go#
Each platform has a place for an application's own data, and the saves go there, in a folder
named after [project] name:
| Platform | Folder |
|---|---|
| Windows | %APPDATA%\<name>\ |
| macOS | ~/Library/Application Support/<name>/ |
| Linux and the BSDs | $XDG_DATA_HOME/<name>/ when that is set to an absolute path, otherwise ~/.local/share/<name>/ |
| Android | the app's private internal storage, in a saves folder: no permission needed, invisible to other apps, removed with the app |
| iOS | Library/Application Support/ in the app's own container — not Documents, which Apple keeps for files the user made |
| Web | the browser's IndexedDB, one database per game |
On the web, every write and every remove is copied into IndexedDB, and the game does not start until the saves already there have been read in, so the first scene finds them. Where the browser refuses IndexedDB — a private window, storage turned off — the game still runs, and its saves last as long as the tab.
Portable saves#
A
game handed out as a zip — on itch.io, say — is expected to keep everything in its own
folder, so that deleting the folder deletes the game. [save] portable = true puts the
saves in a saves folder next to the executable instead. Only Windows, Linux and
FreeBSD have such a place; on macOS, Android, iOS and the web the setting is ignored. NetBSD and
OpenBSD cannot say where an executable is — raylib's GetApplicationDirectory() has no
answer there — so the saves go to the user's folder, and the log says so once:
SAVE: [save] portable: this system does not say where the executable is; saving in the user's folder instead
If that folder cannot be written — a portable build copied into Program Files — the saves go to the user's folder instead, and the log says so once:
SAVE: cannot write in … (a portable build in a read-only folder, like Program Files?); saving in … instead
Reads look in both folders and take the newer save, so a session that had to fall back and a
later one that did not — the game was moved out of Program Files — do not disagree about where the
player's progress is. directory() returns where the saves really went.
The .toml#
[save]
portable = false
encrypt = false
version = 1portable- Saves next to the executable, as above. Off by default: the user's data folder is what installers and Steam Cloud expect.
encrypt- Whether
write()seals the file by default. See below. version- The version of your save format, a whole number from 1 up, stored in every file.
Nothing in [save] is a secret, and there is no password to put there; a key the
section does not have is refused:
[save]
password = "hunter2" raylib_multiplatform.toml:2: password = "hunter2"
^^^^^^^^^^^^^^^^^^^^
configure: error: unknown key [save.password] in raylib_multiplatform.tomlChanging what a save means#
Most updates need no migration at all. A save written by yesterday's version is not broken, it is only missing the keys added since, and a missing key reads as its default. Adding a key never needs a version bump.
Bump [save] version when a key changes meaning — when gold
becomes coins, or a time is stored in milliseconds instead of seconds. The version
the file was written with comes back in version(),
and the game moves the old meaning to the new one as it reads:
rmp::Value v;
if (rmp::save::read("slot1", v) && v.version() < 2) {
v["coins"] = v["gold"].as_int(0);
v.erase("gold");
}write() always stores the version this build has, so once the migrated Value is
written back, the save is migrated for good.
[save]
version = 2The version is a counter that only goes up, from 1:
[save]
version = 0 raylib_multiplatform.toml:2: version = 0
^^^^^^^^^^^
configure: error: [save] version = 0 has to be between 1 and 2000000000.
It is a counter that only goes up, starting at 1; it is stored as an int.Sealed saves#
A plain save is readable: it is one line of header followed by the JSON, and anyone who opens
it in a text editor can see the coins and change them. A sealed save is encrypted and
authenticated, so it cannot be read, and any change to it — a single byte, even with the checksum
worked out again — reads as MODIFIED.
[save] encrypt = true seals every write; a single write can ask either way:
rmp::save::write("slot1", v, { .encrypted = true });
rmp::save::write("debug", v, { .encrypted = false });With sealing on, a plain file in a slot reads as MODIFIED too — otherwise
anyone could replace a sealed save with a plain one of their own. A game that turns sealing on in
an update still has players with plain saves; it reads them for as long as they may exist
with:
rmp::save::read("slot1", v, { .sealed_only = false });The seal is XChaCha20-Poly1305, from the copy of Monocypher the framework already carries for its resource pack, with a fresh random nonce for every write.
The file#
Every save is one line of ASCII, then the payload:
rmp-save 1 <version> <plain|sealed> <payload bytes> <crc32>
{"level":7,"name":"Ada","unlocked":["forest"]}The 1 is the layout of the file itself; a framework that meets a bigger one says
UNREADABLE rather than guessing. The checksum, a CRC-32, spans the first line and
the payload, so an edited version or length is caught like an edited byte, and the length is what tells a file cut
short (TRUNCATED) from one with something added (MODIFIED). A file of
more than 64 MB is not a save and is not read.
Numbers are written with as many digits as it takes to read back exactly the same number, and
read and written with a . as the decimal point whatever language the player's system
is set to, so a save made under a German locale reads anywhere.