Cook levels into a checksummed binary; load binary at runtime
Replace the tracked JSON-in-header bake with a deterministic, bounds-checked CLB binary cooked by the build step. cntrl now loads only the binary; direct JSON loading is restricted to debug builds. Add codec/CLI tests, binary checker, editor bake-on-playtest, and pipeline docs.
This commit is contained in:
parent
fff8360c71
commit
f36654ff42
13 changed files with 768 additions and 2750 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -3,6 +3,9 @@ compile_commands.json
|
|||
__pycache__/
|
||||
*.blend1
|
||||
|
||||
# Cooked level binaries are build artifacts; authoring JSON is the source.
|
||||
assets/levels/*.bin
|
||||
|
||||
# The standalone level editor is local-only, never pushed.
|
||||
src/editor/
|
||||
docs/LEVEL_EDITOR.md
|
||||
|
|
|
|||
|
|
@ -20,10 +20,15 @@ FetchContent_Declare(raylib
|
|||
GIT_TAG 6.2)
|
||||
FetchContent_MakeAvailable(raylib)
|
||||
|
||||
# Authoring JSON may only be read directly in debug/editor builds. Release
|
||||
# clients load the cooked binary produced by the asset build step.
|
||||
add_compile_definitions($<$<CONFIG:Debug>:CNTRL_LEVEL_JSON_HOT_RELOAD=1>)
|
||||
|
||||
add_library(level_core STATIC
|
||||
src/core/debug.cpp
|
||||
src/level/json.cpp
|
||||
src/level/level_data.cpp
|
||||
src/level/level_binary.cpp
|
||||
src/level/asset_catalog.cpp
|
||||
src/level/validation.cpp
|
||||
src/level/default_floor01.cpp)
|
||||
|
|
@ -40,6 +45,10 @@ add_executable(debug_test tests/debug_test.cpp)
|
|||
target_link_libraries(debug_test PRIVATE level_core)
|
||||
add_test(NAME debug_trace_toggle COMMAND debug_test)
|
||||
|
||||
add_executable(level_binary_test tests/level_binary_test.cpp)
|
||||
target_link_libraries(level_binary_test PRIVATE level_core)
|
||||
add_test(NAME level_binary_roundtrip COMMAND level_binary_test)
|
||||
|
||||
# Simulation-only test: the player must keep moving through enemy contact.
|
||||
set(GAME_SIM_SOURCES
|
||||
src/game/beacon.cpp
|
||||
|
|
@ -90,19 +99,21 @@ add_dependencies(debris_test bake_level)
|
|||
add_test(NAME debris_surface_wiring COMMAND debris_test)
|
||||
|
||||
set(LEVEL_JSON ${CMAKE_SOURCE_DIR}/assets/levels/floor01.json)
|
||||
set(BAKED_HPP ${CMAKE_SOURCE_DIR}/src/game/level_baked.hpp)
|
||||
set(BAKED_BIN ${CMAKE_BINARY_DIR}/assets/levels/floor01.bin)
|
||||
add_custom_command(
|
||||
OUTPUT ${BAKED_HPP}
|
||||
COMMAND level_tool --bake ${LEVEL_JSON} ${BAKED_HPP}
|
||||
OUTPUT ${BAKED_BIN}
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/assets/levels
|
||||
COMMAND $<TARGET_FILE:level_tool> --bake ${LEVEL_JSON} ${BAKED_BIN}
|
||||
DEPENDS level_tool ${LEVEL_JSON}
|
||||
COMMENT "Baking level data into the client")
|
||||
add_custom_target(bake_level DEPENDS ${BAKED_HPP})
|
||||
COMMENT "Cooking level JSON into the runtime binary")
|
||||
add_custom_target(bake_level DEPENDS ${BAKED_BIN})
|
||||
|
||||
add_custom_target(check_level
|
||||
COMMAND level_tool --check ${LEVEL_JSON}
|
||||
COMMAND level_tool --validate ${LEVEL_JSON}
|
||||
DEPENDS level_tool ${LEVEL_JSON}
|
||||
COMMENT "Checking level data")
|
||||
COMMAND level_tool --check-binary ${BAKED_BIN}
|
||||
DEPENDS level_tool ${LEVEL_JSON} ${BAKED_BIN}
|
||||
COMMENT "Checking level data and its cooked binary")
|
||||
add_test(NAME level_data_check COMMAND level_tool --check ${LEVEL_JSON})
|
||||
add_test(NAME level_data_validate COMMAND level_tool --validate ${LEVEL_JSON})
|
||||
add_test(NAME level_fixture_valid
|
||||
|
|
@ -111,6 +122,22 @@ add_test(NAME level_fixture_bad_gap
|
|||
COMMAND level_tool --check ${CMAKE_SOURCE_DIR}/tests/data/bad_gap.json)
|
||||
set_tests_properties(level_fixture_bad_gap PROPERTIES WILL_FAIL TRUE)
|
||||
|
||||
# Exercise the cook step through the CLI, not just the codec: a fresh bake must
|
||||
# decode, match the build's artifact byte-for-byte, and refuse invalid input.
|
||||
set(TOOL_BAKED_BIN ${CMAKE_BINARY_DIR}/level_tool_bake_test.bin)
|
||||
add_test(NAME level_tool_bake
|
||||
COMMAND level_tool --bake ${LEVEL_JSON} ${TOOL_BAKED_BIN})
|
||||
add_test(NAME level_tool_check_baked
|
||||
COMMAND level_tool --check-binary ${TOOL_BAKED_BIN})
|
||||
set_tests_properties(level_tool_check_baked PROPERTIES DEPENDS level_tool_bake)
|
||||
add_test(NAME level_bake_deterministic
|
||||
COMMAND ${CMAKE_COMMAND} -E compare_files ${BAKED_BIN} ${TOOL_BAKED_BIN})
|
||||
set_tests_properties(level_bake_deterministic PROPERTIES DEPENDS level_tool_bake)
|
||||
add_test(NAME level_tool_bake_rejects_invalid
|
||||
COMMAND level_tool --bake ${CMAKE_SOURCE_DIR}/tests/data/bad_gap.json
|
||||
${CMAKE_BINARY_DIR}/should_not_exist.bin)
|
||||
set_tests_properties(level_tool_bake_rejects_invalid PROPERTIES WILL_FAIL TRUE)
|
||||
|
||||
# The standalone level editor is local-only and not shipped with the game.
|
||||
# Build it only when its sources are present in the working tree.
|
||||
if(EXISTS ${CMAKE_SOURCE_DIR}/src/editor/main.cpp)
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ C++23 (GCC 13+) and OpenGL/X11 headers; raylib 6.2 is fetched by CMake. Automate
|
|||
|
||||
## Level data & tools
|
||||
|
||||
`assets/levels/floor01.json` is the authoring source of truth, baked into `src/game/level_baked.hpp` by `level_tool --bake`; `cntrl` ships without a runtime level dependency. Validate with `cmake --build build --target check_level` and `ctest --test-dir build --output-on-failure`. The standalone level editor is local-only and not included. `tools/blender/` holds reproducible asset generators, and `import_level.py` rebuilds a Blender blockout from the level JSON.
|
||||
`assets/levels/floor01.json` is the authoring source of truth: designers and scripts edit JSON, the build step cooks it into a checksummed binary (`level_tool --bake`, target `bake_level`), and `cntrl` loads only that binary at runtime. Debug builds accept `--level <file.json>` for hot-reload iteration. Validate with `cmake --build build --target check_level` and `ctest --test-dir build --output-on-failure`. The standalone level editor is local-only and not included. `tools/blender/` holds reproducible asset generators, and `import_level.py` rebuilds a Blender blockout from the level JSON. See `docs/LEVEL_DATA_PIPELINE.md` for the full schema.
|
||||
|
||||
## Layout
|
||||
|
||||
|
|
@ -49,6 +49,7 @@ C++23 (GCC 13+) and OpenGL/X11 headers; raylib 6.2 is fetched by CMake. Automate
|
|||
- `docs/MAP_FLOW.md` + `docs/maps/` — run flow and 2D maps
|
||||
- `docs/BLACKOUT_RITUAL.md` — projector-screen phone puzzle
|
||||
- `docs/LEVEL_DESIGN_REVIEW.md` — map vs. client audit
|
||||
- `docs/LEVEL_DATA_PIPELINE.md` — JSON authoring → cooked binary → runtime load
|
||||
- `docs/ART_DIRECTION.md` + `docs/concept/` — visual target
|
||||
- `docs/GAME_DESIGN_PASS.md` — recent design changes, including the Beacon pass
|
||||
- `docs/ROADMAP.md` — milestones M0–M7
|
||||
|
|
|
|||
88
docs/LEVEL_DATA_PIPELINE.md
Normal file
88
docs/LEVEL_DATA_PIPELINE.md
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
# Level data pipeline
|
||||
|
||||
Floor 01 is **authored data**, not C++ source. The pipeline has three stages and
|
||||
one source of truth:
|
||||
|
||||
1. **Author in JSON.** `assets/levels/floor01.json` (schema `version: 1`) is the
|
||||
only file designers, the editor and scripts edit. Plain text keeps git diffs
|
||||
readable and the level reviewable in a normal editor.
|
||||
2. **Cook to binary at build time.** The CMake `bake_level` target runs
|
||||
`level_tool --bake <level.json> <level.bin>`. It validates the level first and
|
||||
refuses to cook invalid data. The output is generated into the build tree
|
||||
(`assets/levels/floor01.bin` relative to the build directory); binaries are
|
||||
never hand-edited or committed.
|
||||
3. **Load only the binary at runtime.** `cntrl` reads the cooked `.bin` and never
|
||||
parses JSON in a release build. Debug builds may pass `--level <file.json>`
|
||||
for hot-reload iteration; the standalone editor cooks its draft before it
|
||||
launches `cntrl --level <file.bin>` for playtest.
|
||||
|
||||
This keeps authoring friendly and diffs clean without shipping a JSON parser (or
|
||||
a JSON text asset) in the client. The binary is deterministic: cooking an
|
||||
unchanged JSON produces identical bytes.
|
||||
|
||||
## Why a custom binary instead of FlatBuffers
|
||||
|
||||
The project deliberately has no third-party runtime dependencies beyond raylib
|
||||
(see `docs/TECHNICAL.md`). A small, fixed-layout, bounds-checked codec in
|
||||
`src/level/level_binary.*` gives the same benefits — one compact file, no parse
|
||||
ambiguity, integrity checking — without pulling in a schema compiler and generated
|
||||
headers. The JSON-to-`LevelData` conversion in `src/level/level_data.cpp` remains
|
||||
the single definition of the authoring schema; the binary is just its cooked form.
|
||||
|
||||
## Cooked binary layout (CLB v1)
|
||||
|
||||
All integers are little-endian. Floats are IEEE-754 bits. Strings are a `u32`
|
||||
byte count followed by that many UTF-8 bytes (no terminator). Vectors are a
|
||||
`u32` count followed by that many records. There is no padding. Enums are stored
|
||||
as their authoring names and validated against the same name tables the JSON
|
||||
reader uses, so reordering an enum cannot silently reinterpret an old file.
|
||||
|
||||
```
|
||||
header 8 bytes magic "CNTRLLVL" + u32 version (= 1)
|
||||
level str name, f32 map_width, f32 map_height, f32 scale,
|
||||
f32 spawn.x, f32 spawn.y
|
||||
rooms u32 count; per room: str name, f32 x0,y0,x1,y1, str kind,
|
||||
i32 flow, i32 side_index
|
||||
corr. u32 count; per rect: f32 x0,y0,x1,y1
|
||||
walls u32 count; per line: i32 axis, f32 coord,from,to,height,
|
||||
u32 gap_count; per gap: f32 from,to
|
||||
doors u32 count; per door: str id, f32 x0,y0,x1,y1, f32 height
|
||||
props u32 count; per prop: str kind, f32 pos.x,pos.y, f32 w,d,h,
|
||||
u8 solid, str model, f32 yaw, str room_kind, f32 y, f32 scale,
|
||||
u8 destructible
|
||||
ritual u32 count; per ritual: str type, f32 pos.x,pos.y,
|
||||
f32 radius,duration,ring_radius, i32 ring_count,
|
||||
f32 light_radius,light_damage_mult,light_duration
|
||||
thermo u32 count; per door: f32 pos.x,pos.y, span, yaw
|
||||
footer u32 FNV-1a checksum of every preceding byte
|
||||
```
|
||||
|
||||
`decode_binary` checks the magic, version, exact length, per-string and per-vector
|
||||
limits, enum names and the checksum before returning a `LevelData`. It never
|
||||
modifies the caller's level on failure. `level_tool --check-binary <file.bin>`
|
||||
performs the same decode and re-runs gameplay validation on the result.
|
||||
|
||||
## Working with it
|
||||
|
||||
```sh
|
||||
cmake --build build --target bake_level # cook JSON -> build/assets/levels/floor01.bin
|
||||
cmake --build build --target check_level # JSON checks + cooked-binary check
|
||||
./build/level_tool --bake assets/levels/floor01.json /tmp/floor01.bin
|
||||
./build/level_tool --check-binary /tmp/floor01.bin
|
||||
ctest --test-dir build --output-on-failure
|
||||
```
|
||||
|
||||
`Floor` resolves the baked path from the working directory or the executable
|
||||
directory, so both `./build/cntrl` and `cd build && ./cntrl` find the same file.
|
||||
If a cooked file cannot be loaded, the client warns and falls back to the
|
||||
built-in Floor 01 so a missing asset never bricks a build.
|
||||
|
||||
### Adding a field
|
||||
|
||||
1. Add it to `LevelData` in `src/level/level_data.hpp` with a safe default.
|
||||
2. Add JSON read/write in `src/level/level_data.cpp` (unknown fields are already
|
||||
tolerated; new fields must default when absent).
|
||||
3. Add it to `write_level`/`read_level` in `src/level/level_binary.cpp`, then bump
|
||||
`kBinaryVersion` in `src/level/level_binary.hpp`. Old binaries are rejected
|
||||
rather than misread; the build step regenerates them from JSON.
|
||||
4. Extend `tests/level_binary_test.cpp` and rerun `check_level` + CTest.
|
||||
|
|
@ -14,8 +14,9 @@
|
|||
`actor.vs` (the shader deliberately has no bone attributes, so raylib's CPU
|
||||
fallback runs). The horde keeps shader-side procedural rigs, which stay one
|
||||
draw call per actor.
|
||||
- No other third-party deps until they earn their place. Data lives in C++ tables
|
||||
(JSON only when content volume demands it).
|
||||
- No other third-party deps until they earn their place. Authored level data is
|
||||
JSON; it is cooked into a small custom binary during the build and only that
|
||||
binary is loaded at runtime (see `docs/LEVEL_DATA_PIPELINE.md`).
|
||||
|
||||
## Repo layout
|
||||
|
||||
|
|
@ -68,6 +69,10 @@ src/
|
|||
allocation) for enemy separation and projectile collision at horde scale.
|
||||
7. **Credit-based spawn Director** (`game/director.*`) with RoR2's "too cheap"
|
||||
rule and the elite-bank rule (implemented in M2).
|
||||
8. **Data pipeline, not code-generated data.** Levels are authored in JSON,
|
||||
validated and cooked to a deterministic binary by `level_tool --bake` during
|
||||
the asset build step, and the client loads only the binary. Debug/editor
|
||||
builds may read JSON directly for hot-reload; release builds cannot.
|
||||
|
||||
## Rendering pipeline (hybrid)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,19 @@
|
|||
#include "game/floor.hpp"
|
||||
|
||||
#include "core/rng.hpp"
|
||||
#include "game/level_baked.hpp"
|
||||
#include "level/level_binary.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
|
|
@ -23,6 +29,44 @@ bool file_exists(const std::string& path) {
|
|||
return file.good();
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& value, const char* suffix) {
|
||||
const std::string tail(suffix);
|
||||
return value.size() >= tail.size()
|
||||
&& value.compare(value.size() - tail.size(), tail.size(), tail) == 0;
|
||||
}
|
||||
|
||||
std::string executable_dir() {
|
||||
#if defined(__linux__)
|
||||
std::vector<char> buffer(4096);
|
||||
const ssize_t n = ::readlink("/proc/self/exe", buffer.data(), buffer.size());
|
||||
if (n > 0) {
|
||||
const std::string exe(buffer.data(), static_cast<std::size_t>(n));
|
||||
const std::size_t slash = exe.find_last_of('/');
|
||||
if (slash != std::string::npos) return exe.substr(0, slash);
|
||||
}
|
||||
#endif
|
||||
return {};
|
||||
}
|
||||
|
||||
// The cooked binary lives in the build tree next to the client. Resolve it
|
||||
// from the working directory or the executable so both `./build/cntrl` and
|
||||
// `cd build && ./cntrl` find the same file.
|
||||
std::string resolve_level_path(const std::string& path) {
|
||||
if (file_exists(path)) return path;
|
||||
if (!path.empty() && path.front() != '/') {
|
||||
for (const char* prefix : {"../", "../../"}) {
|
||||
const std::string candidate = std::string(prefix) + path;
|
||||
if (file_exists(candidate)) return candidate;
|
||||
}
|
||||
const std::string dir = executable_dir();
|
||||
if (!dir.empty()) {
|
||||
const std::string candidate = dir + "/" + path;
|
||||
if (file_exists(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
// Cheap axis-aligned push-out used for both walls and beacon plinths.
|
||||
bool push_out(Vec2& p, const FloorRect& r, float radius) {
|
||||
const float x0 = r.x0 - radius, x1 = r.x1 + radius;
|
||||
|
|
@ -43,13 +87,33 @@ bool push_out(Vec2& p, const FloorRect& r, float radius) {
|
|||
Floor::Floor() : Floor(kDefaultPath) {}
|
||||
|
||||
Floor::Floor(const std::string& path) : path_(path) {
|
||||
std::string resolved = path_;
|
||||
if (!file_exists(resolved)) resolved = "../" + path_;
|
||||
|
||||
const std::string resolved = resolve_level_path(path_);
|
||||
std::string error;
|
||||
if (!level::load(resolved, data_, error)) {
|
||||
if (!level::parse(game::kBakedLevel, data_, error)) {
|
||||
std::fprintf(stderr, "Floor: %s; using built-in Floor 01\n", error.c_str());
|
||||
bool loaded = false;
|
||||
|
||||
if (ends_with(path_, ".json")) {
|
||||
#if defined(CNTRL_LEVEL_JSON_HOT_RELOAD)
|
||||
// Debug/editor builds only: read the designer's authoring file as-is.
|
||||
loaded = level::load(resolved, data_, error);
|
||||
#else
|
||||
error = "release builds load cooked .bin levels only; JSON hot-reload "
|
||||
"requires a debug build";
|
||||
#endif
|
||||
} else {
|
||||
loaded = level::read_binary(resolved, data_, error);
|
||||
}
|
||||
|
||||
if (!loaded) {
|
||||
const std::string fallback = resolve_level_path(kDefaultPath);
|
||||
std::string fallback_error;
|
||||
if (fallback != resolved
|
||||
&& level::read_binary(fallback, data_, fallback_error)) {
|
||||
std::fprintf(stderr, "Floor: %s; using baked Floor 01\n",
|
||||
error.c_str());
|
||||
} else {
|
||||
if (!fallback_error.empty()) error = fallback_error;
|
||||
std::fprintf(stderr, "Floor: %s; using built-in Floor 01\n",
|
||||
error.c_str());
|
||||
data_ = level::floor01_default();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,7 +51,9 @@ struct FloorProp {
|
|||
// below are world-space; the authoring file keeps the original map space.
|
||||
class Floor {
|
||||
public:
|
||||
static constexpr const char* kDefaultPath = "assets/levels/floor01.json";
|
||||
// The client only loads cooked binaries. Designers still edit the JSON;
|
||||
// debug/editor builds may pass a .json path for hot-reload iteration.
|
||||
static constexpr const char* kDefaultPath = "assets/levels/floor01.bin";
|
||||
|
||||
Floor();
|
||||
explicit Floor(const std::string& path);
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
424
src/level/level_binary.cpp
Normal file
424
src/level/level_binary.cpp
Normal file
|
|
@ -0,0 +1,424 @@
|
|||
#include "level/level_binary.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <utility>
|
||||
|
||||
namespace level {
|
||||
namespace {
|
||||
|
||||
constexpr std::array<std::uint8_t, 8> kMagic = {
|
||||
'C', 'N', 'T', 'R', 'L', 'L', 'V', 'L'};
|
||||
constexpr std::size_t kHeaderBytes = kMagic.size() + sizeof(std::uint32_t);
|
||||
constexpr std::size_t kChecksumBytes = sizeof(std::uint32_t);
|
||||
// Corrupt files must not be able to make us allocate unbounded memory.
|
||||
constexpr std::uint32_t kMaxStringBytes = 1u << 20;
|
||||
constexpr std::uint32_t kMaxCount = 1u << 20;
|
||||
|
||||
bool set_error(std::string& error, const char* message) {
|
||||
error = message;
|
||||
return false;
|
||||
}
|
||||
|
||||
std::uint32_t checksum(const std::uint8_t* data, std::size_t size) {
|
||||
constexpr std::uint32_t kOffset = 2166136261u;
|
||||
constexpr std::uint32_t kPrime = 16777619u;
|
||||
std::uint32_t hash = kOffset;
|
||||
for (std::size_t i = 0; i < size; ++i) {
|
||||
hash ^= data[i];
|
||||
hash *= kPrime;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
std::uint32_t load_le32(const std::uint8_t* p) {
|
||||
return static_cast<std::uint32_t>(p[0])
|
||||
| (static_cast<std::uint32_t>(p[1]) << 8)
|
||||
| (static_cast<std::uint32_t>(p[2]) << 16)
|
||||
| (static_cast<std::uint32_t>(p[3]) << 24);
|
||||
}
|
||||
|
||||
class Writer {
|
||||
public:
|
||||
void raw(const std::uint8_t* data, std::size_t size) {
|
||||
bytes.insert(bytes.end(), data, data + size);
|
||||
}
|
||||
|
||||
void u8(std::uint8_t value) { bytes.push_back(value); }
|
||||
|
||||
void u32(std::uint32_t value) {
|
||||
for (int shift = 0; shift < 32; shift += 8) {
|
||||
bytes.push_back(static_cast<std::uint8_t>(value >> shift));
|
||||
}
|
||||
}
|
||||
|
||||
void i32(std::int32_t value) { u32(std::bit_cast<std::uint32_t>(value)); }
|
||||
void f32(float value) { u32(std::bit_cast<std::uint32_t>(value)); }
|
||||
|
||||
void str(const std::string& value) {
|
||||
u32(static_cast<std::uint32_t>(value.size()));
|
||||
raw(reinterpret_cast<const std::uint8_t*>(value.data()), value.size());
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> bytes;
|
||||
};
|
||||
|
||||
class Reader {
|
||||
public:
|
||||
Reader(const std::vector<std::uint8_t>& bytes, std::string& error,
|
||||
std::size_t start = 0)
|
||||
: bytes_(bytes), error_(error), pos_(start) {}
|
||||
|
||||
bool fail(const char* message) {
|
||||
if (error_.empty()) error_ = message;
|
||||
return false;
|
||||
}
|
||||
|
||||
std::size_t remaining() const { return bytes_.size() - pos_; }
|
||||
|
||||
bool take(std::size_t size, const std::uint8_t*& out) {
|
||||
if (size > remaining()) return fail("truncated level binary");
|
||||
out = bytes_.data() + pos_;
|
||||
pos_ += size;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool u8(std::uint8_t& out) {
|
||||
const std::uint8_t* p = nullptr;
|
||||
if (!take(sizeof(out), p)) return false;
|
||||
out = *p;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool u32(std::uint32_t& out) {
|
||||
const std::uint8_t* p = nullptr;
|
||||
if (!take(sizeof(out), p)) return false;
|
||||
out = load_le32(p);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool i32(std::int32_t& out) {
|
||||
std::uint32_t raw = 0;
|
||||
if (!u32(raw)) return false;
|
||||
out = std::bit_cast<std::int32_t>(raw);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool f32(float& out) {
|
||||
std::uint32_t raw = 0;
|
||||
if (!u32(raw)) return false;
|
||||
out = std::bit_cast<float>(raw);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool flag(bool& out) {
|
||||
std::uint8_t raw = 0;
|
||||
if (!u8(raw)) return false;
|
||||
if (raw > 1) return fail("invalid boolean in level binary");
|
||||
out = raw != 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool str(std::string& out) {
|
||||
std::uint32_t size = 0;
|
||||
if (!u32(size)) return false;
|
||||
if (size > kMaxStringBytes) return fail("level binary string too long");
|
||||
const std::uint8_t* p = nullptr;
|
||||
if (!take(size, p)) return false;
|
||||
out.assign(reinterpret_cast<const char*>(p), size);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool count(std::uint32_t& out) {
|
||||
if (!u32(out)) return false;
|
||||
if (out > kMaxCount) return fail("level binary count too large");
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
const std::vector<std::uint8_t>& bytes_;
|
||||
std::string& error_;
|
||||
std::size_t pos_ = 0;
|
||||
};
|
||||
|
||||
void write_rect(Writer& w, const Rect& r) {
|
||||
w.f32(r.x0);
|
||||
w.f32(r.y0);
|
||||
w.f32(r.x1);
|
||||
w.f32(r.y1);
|
||||
}
|
||||
|
||||
void write_level(Writer& w, const LevelData& level) {
|
||||
w.str(level.name);
|
||||
w.f32(level.map_width);
|
||||
w.f32(level.map_height);
|
||||
w.f32(level.scale);
|
||||
w.f32(level.anchors.spawn.x);
|
||||
w.f32(level.anchors.spawn.y);
|
||||
|
||||
w.u32(static_cast<std::uint32_t>(level.rooms.size()));
|
||||
for (const Room& r : level.rooms) {
|
||||
w.str(r.name);
|
||||
write_rect(w, r.rect);
|
||||
w.str(room_kind_name(r.kind));
|
||||
w.i32(r.flow);
|
||||
w.i32(r.side_index);
|
||||
}
|
||||
|
||||
w.u32(static_cast<std::uint32_t>(level.corridors.size()));
|
||||
for (const Rect& r : level.corridors) write_rect(w, r);
|
||||
|
||||
w.u32(static_cast<std::uint32_t>(level.walls.size()));
|
||||
for (const WallLine& line : level.walls) {
|
||||
w.i32(line.axis);
|
||||
w.f32(line.coord);
|
||||
w.f32(line.from);
|
||||
w.f32(line.to);
|
||||
w.f32(line.height);
|
||||
w.u32(static_cast<std::uint32_t>(line.gaps.size()));
|
||||
for (const Span& gap : line.gaps) {
|
||||
w.f32(gap.first);
|
||||
w.f32(gap.second);
|
||||
}
|
||||
}
|
||||
|
||||
w.u32(static_cast<std::uint32_t>(level.doors.size()));
|
||||
for (const Door& d : level.doors) {
|
||||
w.str(door_name(d.id));
|
||||
write_rect(w, d.rect);
|
||||
w.f32(d.height);
|
||||
}
|
||||
|
||||
w.u32(static_cast<std::uint32_t>(level.props.size()));
|
||||
for (const Prop& p : level.props) {
|
||||
w.str(prop_kind_name(p.kind));
|
||||
w.f32(p.pos.x);
|
||||
w.f32(p.pos.y);
|
||||
w.f32(p.w);
|
||||
w.f32(p.d);
|
||||
w.f32(p.h);
|
||||
w.u8(p.solid ? 1 : 0);
|
||||
w.str(p.model);
|
||||
w.f32(p.yaw);
|
||||
w.str(p.room_kind);
|
||||
w.f32(p.y);
|
||||
w.f32(p.scale);
|
||||
w.u8(p.destructible ? 1 : 0);
|
||||
}
|
||||
|
||||
w.u32(static_cast<std::uint32_t>(level.rituals.size()));
|
||||
for (const Ritual& r : level.rituals) {
|
||||
w.str(r.type);
|
||||
w.f32(r.pos.x);
|
||||
w.f32(r.pos.y);
|
||||
w.f32(r.radius);
|
||||
w.f32(r.duration);
|
||||
w.f32(r.ring_radius);
|
||||
w.i32(r.ring_count);
|
||||
w.f32(r.light_radius);
|
||||
w.f32(r.light_damage_mult);
|
||||
w.f32(r.light_duration);
|
||||
}
|
||||
|
||||
w.u32(static_cast<std::uint32_t>(level.thermo.size()));
|
||||
for (const ThermoDoor& t : level.thermo) {
|
||||
w.f32(t.pos.x);
|
||||
w.f32(t.pos.y);
|
||||
w.f32(t.span);
|
||||
w.f32(t.yaw);
|
||||
}
|
||||
}
|
||||
|
||||
bool read_rect(Reader& r, Rect& out) {
|
||||
return r.f32(out.x0) && r.f32(out.y0) && r.f32(out.x1) && r.f32(out.y1);
|
||||
}
|
||||
|
||||
bool read_level(Reader& r, LevelData& level) {
|
||||
if (!r.str(level.name)) return false;
|
||||
if (!r.f32(level.map_width) || !r.f32(level.map_height)
|
||||
|| !r.f32(level.scale)) return false;
|
||||
if (!r.f32(level.anchors.spawn.x) || !r.f32(level.anchors.spawn.y)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::uint32_t count = 0;
|
||||
if (!r.count(count)) return false;
|
||||
level.rooms.reserve(count);
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
Room room;
|
||||
std::string kind;
|
||||
if (!r.str(room.name) || !read_rect(r, room.rect)
|
||||
|| !r.str(kind) || !r.i32(room.flow) || !r.i32(room.side_index)) {
|
||||
return false;
|
||||
}
|
||||
if (!room_kind_from_name(kind, room.kind)) {
|
||||
return r.fail("unknown room kind in level binary");
|
||||
}
|
||||
level.rooms.push_back(std::move(room));
|
||||
}
|
||||
|
||||
if (!r.count(count)) return false;
|
||||
level.corridors.reserve(count);
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
Rect rect;
|
||||
if (!read_rect(r, rect)) return false;
|
||||
level.corridors.push_back(rect);
|
||||
}
|
||||
|
||||
if (!r.count(count)) return false;
|
||||
level.walls.reserve(count);
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
WallLine line;
|
||||
std::uint32_t gaps = 0;
|
||||
if (!r.i32(line.axis) || !r.f32(line.coord) || !r.f32(line.from)
|
||||
|| !r.f32(line.to) || !r.f32(line.height) || !r.count(gaps)) {
|
||||
return false;
|
||||
}
|
||||
line.gaps.reserve(gaps);
|
||||
for (std::uint32_t g = 0; g < gaps; ++g) {
|
||||
Span gap;
|
||||
if (!r.f32(gap.first) || !r.f32(gap.second)) return false;
|
||||
line.gaps.push_back(gap);
|
||||
}
|
||||
level.walls.push_back(std::move(line));
|
||||
}
|
||||
|
||||
if (!r.count(count)) return false;
|
||||
level.doors.reserve(count);
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
Door door;
|
||||
std::string id;
|
||||
if (!r.str(id) || !read_rect(r, door.rect) || !r.f32(door.height)) {
|
||||
return false;
|
||||
}
|
||||
if (!door_from_name(id, door.id)) {
|
||||
return r.fail("unknown door id in level binary");
|
||||
}
|
||||
level.doors.push_back(std::move(door));
|
||||
}
|
||||
|
||||
if (!r.count(count)) return false;
|
||||
level.props.reserve(count);
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
Prop prop;
|
||||
std::string kind;
|
||||
if (!r.str(kind) || !r.f32(prop.pos.x) || !r.f32(prop.pos.y)
|
||||
|| !r.f32(prop.w) || !r.f32(prop.d) || !r.f32(prop.h)
|
||||
|| !r.flag(prop.solid) || !r.str(prop.model) || !r.f32(prop.yaw)
|
||||
|| !r.str(prop.room_kind) || !r.f32(prop.y) || !r.f32(prop.scale)
|
||||
|| !r.flag(prop.destructible)) {
|
||||
return false;
|
||||
}
|
||||
if (!prop_kind_from_name(kind, prop.kind)) {
|
||||
return r.fail("unknown prop kind in level binary");
|
||||
}
|
||||
level.props.push_back(std::move(prop));
|
||||
}
|
||||
|
||||
if (!r.count(count)) return false;
|
||||
level.rituals.reserve(count);
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
Ritual ritual;
|
||||
if (!r.str(ritual.type) || !r.f32(ritual.pos.x) || !r.f32(ritual.pos.y)
|
||||
|| !r.f32(ritual.radius) || !r.f32(ritual.duration)
|
||||
|| !r.f32(ritual.ring_radius) || !r.i32(ritual.ring_count)
|
||||
|| !r.f32(ritual.light_radius) || !r.f32(ritual.light_damage_mult)
|
||||
|| !r.f32(ritual.light_duration)) {
|
||||
return false;
|
||||
}
|
||||
level.rituals.push_back(std::move(ritual));
|
||||
}
|
||||
|
||||
if (!r.count(count)) return false;
|
||||
level.thermo.reserve(count);
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
ThermoDoor thermo;
|
||||
if (!r.f32(thermo.pos.x) || !r.f32(thermo.pos.y) || !r.f32(thermo.span)
|
||||
|| !r.f32(thermo.yaw)) {
|
||||
return false;
|
||||
}
|
||||
level.thermo.push_back(thermo);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<std::uint8_t> encode_binary(const LevelData& level) {
|
||||
Writer w;
|
||||
w.raw(kMagic.data(), kMagic.size());
|
||||
w.u32(kBinaryVersion);
|
||||
write_level(w, level);
|
||||
w.u32(checksum(w.bytes.data(), w.bytes.size()));
|
||||
return std::move(w.bytes);
|
||||
}
|
||||
|
||||
bool decode_binary(const std::vector<std::uint8_t>& bytes, LevelData& level,
|
||||
std::string& error) {
|
||||
error.clear();
|
||||
if (bytes.size() < kHeaderBytes + kChecksumBytes) {
|
||||
return set_error(error, "level binary is too short");
|
||||
}
|
||||
if (!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
|
||||
return set_error(error, "bad level binary magic");
|
||||
}
|
||||
const std::uint32_t version = load_le32(bytes.data() + kMagic.size());
|
||||
if (version != kBinaryVersion) {
|
||||
return set_error(error, "unsupported level binary version");
|
||||
}
|
||||
const std::uint32_t stored =
|
||||
load_le32(bytes.data() + bytes.size() - kChecksumBytes);
|
||||
if (stored != checksum(bytes.data(), bytes.size() - kChecksumBytes)) {
|
||||
return set_error(error, "level binary checksum mismatch");
|
||||
}
|
||||
|
||||
Reader reader(bytes, error, kHeaderBytes);
|
||||
LevelData decoded;
|
||||
decoded.version = static_cast<int>(version);
|
||||
if (!read_level(reader, decoded)) return false;
|
||||
if (reader.remaining() != kChecksumBytes) {
|
||||
return set_error(error, "trailing bytes in level binary");
|
||||
}
|
||||
level = std::move(decoded);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool write_binary(const std::string& path, const LevelData& level,
|
||||
std::string& error) {
|
||||
error.clear();
|
||||
const std::filesystem::path target(path);
|
||||
if (target.has_parent_path()) {
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(target.parent_path(), ec);
|
||||
}
|
||||
std::ofstream file(path, std::ios::binary | std::ios::trunc);
|
||||
if (!file) return set_error(error, ("failed to write " + path).c_str());
|
||||
const auto bytes = encode_binary(level);
|
||||
file.write(reinterpret_cast<const char*>(bytes.data()),
|
||||
static_cast<std::streamsize>(bytes.size()));
|
||||
if (!file) return set_error(error, ("failed to write " + path).c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read_binary(const std::string& path, LevelData& level,
|
||||
std::string& error) {
|
||||
error.clear();
|
||||
std::ifstream file(path, std::ios::binary | std::ios::ate);
|
||||
if (!file) return set_error(error, ("failed to open " + path).c_str());
|
||||
const std::streampos end = file.tellg();
|
||||
if (end < 0) return set_error(error, ("failed to read " + path).c_str());
|
||||
std::vector<std::uint8_t> bytes(static_cast<std::size_t>(end));
|
||||
file.seekg(0);
|
||||
if (!bytes.empty()) {
|
||||
file.read(reinterpret_cast<char*>(bytes.data()),
|
||||
static_cast<std::streamsize>(bytes.size()));
|
||||
if (!file) return set_error(error, ("failed to read " + path).c_str());
|
||||
}
|
||||
return decode_binary(bytes, level, error);
|
||||
}
|
||||
|
||||
} // namespace level
|
||||
34
src/level/level_binary.hpp
Normal file
34
src/level/level_binary.hpp
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "level/level_data.hpp"
|
||||
|
||||
namespace level {
|
||||
|
||||
// CNTRL level binary ("CLB"): the cooked form of the authoring JSON.
|
||||
//
|
||||
// Designers and scripts only ever touch assets/levels/*.json. `level_tool
|
||||
// --bake` validates that JSON and emits this deterministic, checksummed binary
|
||||
// during the asset build step. The game loads the binary; it never parses JSON
|
||||
// in release builds. See docs/LEVEL_DATA_PIPELINE.md for the byte layout.
|
||||
constexpr std::uint32_t kBinaryVersion = 1;
|
||||
|
||||
// Encode a level into bytes. The result is byte-for-byte stable for a given
|
||||
// LevelData, so cooked files produce clean diffs when regenerated.
|
||||
std::vector<std::uint8_t> encode_binary(const LevelData& level);
|
||||
|
||||
// Decode bytes, validating the magic, version, lengths/counts, enum names and
|
||||
// FNV-1a checksum. `level` is only modified on success.
|
||||
bool decode_binary(const std::vector<std::uint8_t>& bytes, LevelData& level,
|
||||
std::string& error);
|
||||
|
||||
// File helpers. Both open in binary mode; errors are written to `error`.
|
||||
bool write_binary(const std::string& path, const LevelData& level,
|
||||
std::string& error);
|
||||
bool read_binary(const std::string& path, LevelData& level,
|
||||
std::string& error);
|
||||
|
||||
} // namespace level
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include "level/level_binary.hpp"
|
||||
#include "level/level_data.hpp"
|
||||
#include "level/validation.hpp"
|
||||
|
||||
|
|
@ -9,10 +9,11 @@ namespace {
|
|||
|
||||
int usage() {
|
||||
std::cerr << "usage:\n"
|
||||
<< " level_tool --dump-floor01 <path>\n"
|
||||
<< " level_tool --check <path>\n"
|
||||
<< " level_tool --validate <path>\n"
|
||||
<< " level_tool --bake <level.json> <baked.hpp>\n";
|
||||
<< " level_tool --dump-floor01 <path.json>\n"
|
||||
<< " level_tool --check <path.json>\n"
|
||||
<< " level_tool --validate <path.json>\n"
|
||||
<< " level_tool --bake <level.json> <level.bin>\n"
|
||||
<< " level_tool --check-binary <level.bin>\n";
|
||||
return 2;
|
||||
}
|
||||
|
||||
|
|
@ -37,14 +38,10 @@ int main(int argc, char** argv) {
|
|||
std::cerr << "refusing to bake an invalid level\n";
|
||||
return 1;
|
||||
}
|
||||
std::ofstream file(output, std::ios::binary | std::ios::trunc);
|
||||
if (!file) {
|
||||
std::cerr << "failed to write " << output << '\n';
|
||||
if (!level::write_binary(output, data, error)) {
|
||||
std::cerr << error << '\n';
|
||||
return 1;
|
||||
}
|
||||
file << "#pragma once\n\nnamespace game {\n"
|
||||
<< "inline constexpr const char* kBakedLevel = R\"LEVEL(\n"
|
||||
<< level::serialize(data) << ")LEVEL\";\n\n} // namespace game\n";
|
||||
std::cout << "baked " << input << " -> " << output << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -76,6 +73,22 @@ int main(int argc, char** argv) {
|
|||
return result.ok() ? 0 : 1;
|
||||
}
|
||||
|
||||
if (command == "--check-binary") {
|
||||
level::LevelData data;
|
||||
std::string error;
|
||||
if (!level::read_binary(path, data, error)) {
|
||||
std::cerr << error << '\n';
|
||||
return 1;
|
||||
}
|
||||
const auto result = level::validate(data);
|
||||
for (const auto& e : result.errors) std::cerr << "ERROR: " << e << '\n';
|
||||
std::cout << path << ": cooked level " << data.name << ", "
|
||||
<< data.rooms.size() << " rooms, " << data.walls.size()
|
||||
<< " wall lines, " << data.props.size() << " props, "
|
||||
<< result.errors.size() << " errors\n";
|
||||
return result.ok() ? 0 : 1;
|
||||
}
|
||||
|
||||
if (command == "--check") {
|
||||
level::LevelData data;
|
||||
std::string error;
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ struct Options {
|
|||
float fov = 0.0f; // --fov <deg>: initial camera FOV
|
||||
float cam_height = 0.0f; // --cam-height <m>: initial camera height
|
||||
float cam_forward = 0.0f; // --cam-forward <m>: initial forward offset
|
||||
const char* level_path = nullptr; // --level <path>: authoring JSON to load
|
||||
const char* level_path = nullptr; // --level <path>: cooked .bin (JSON in debug builds)
|
||||
const char* trace = nullptr; // --trace <list>: opt-in debug categories
|
||||
};
|
||||
|
||||
|
|
|
|||
77
tests/level_binary_test.cpp
Normal file
77
tests/level_binary_test.cpp
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "level/level_binary.hpp"
|
||||
#include "level/level_data.hpp"
|
||||
|
||||
namespace {
|
||||
|
||||
int failures = 0;
|
||||
|
||||
void check(bool ok, const char* what) {
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "FAIL: %s\n", what);
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
|
||||
bool rejects(const std::vector<std::uint8_t>& bytes, level::LevelData& level,
|
||||
std::string& error, const char* what) {
|
||||
const std::string before = level::serialize(level);
|
||||
const bool ok = level::decode_binary(bytes, level, error);
|
||||
check(!ok, what);
|
||||
check(level::serialize(level) == before, "rejected binary leaves level untouched");
|
||||
return !ok;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
const level::LevelData original = level::floor01_default();
|
||||
const std::string expected = level::serialize(original);
|
||||
|
||||
std::string error;
|
||||
const auto bytes = level::encode_binary(original);
|
||||
check(bytes.size() > 16, "binary is non-trivial");
|
||||
|
||||
level::LevelData decoded;
|
||||
check(level::decode_binary(bytes, decoded, error), error.c_str());
|
||||
check(level::serialize(decoded) == expected, "binary round-trip preserves level");
|
||||
check(level::encode_binary(decoded) == bytes, "encoding is deterministic");
|
||||
|
||||
// The client path: write the cooked file, then read it back from disk.
|
||||
const std::string path = "level_binary_test.bin";
|
||||
check(level::write_binary(path, original, error), error.c_str());
|
||||
level::LevelData from_file;
|
||||
check(level::read_binary(path, from_file, error), error.c_str());
|
||||
check(level::serialize(from_file) == expected, "file round-trip preserves level");
|
||||
std::filesystem::remove(path);
|
||||
|
||||
// Corrupt inputs must be rejected without touching the caller's level.
|
||||
std::vector<std::uint8_t> bad = bytes;
|
||||
bad[0] ^= 0xff;
|
||||
rejects(bad, decoded, error, "bad magic rejected");
|
||||
|
||||
bad = bytes;
|
||||
bad[8] ^= 0xff;
|
||||
rejects(bad, decoded, error, "unsupported version rejected");
|
||||
|
||||
bad = bytes;
|
||||
bad.back() ^= 0xff;
|
||||
rejects(bad, decoded, error, "checksum mismatch rejected");
|
||||
|
||||
bad = bytes;
|
||||
bad.pop_back();
|
||||
rejects(bad, decoded, error, "truncated binary rejected");
|
||||
|
||||
bad = bytes;
|
||||
bad.insert(bad.begin() + 12, 0);
|
||||
rejects(bad, decoded, error, "trailing bytes rejected");
|
||||
|
||||
check(!level::read_binary("no_such_level.bin", decoded, error),
|
||||
"missing file rejected");
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue