diff --git a/CMakeLists.txt b/CMakeLists.txt index cde49e1..b59acde 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,9 +44,23 @@ add_custom_command( COMMENT "Baking level data into the client") add_custom_target(bake_level DEPENDS ${BAKED_HPP}) +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") +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 + COMMAND level_tool --check ${CMAKE_SOURCE_DIR}/tests/data/valid.json) +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) + add_executable(editor src/editor/main.cpp - src/editor/editor_app.cpp) + src/editor/editor_app.cpp + src/render/raygui_impl.cpp) target_include_directories(editor PRIVATE src third_party/raygui third_party/clay) target_link_libraries(editor PRIVATE raylib level_core) diff --git a/README.md b/README.md index 7088686..7510b9f 100644 --- a/README.md +++ b/README.md @@ -86,28 +86,40 @@ The editor is a **separate binary** (`editor`) and shares only the raylib-free ```sh cmake --build build -j6 -./build/editor # loads assets/levels/floor01.json +./build/editor # loads assets/levels/floor01.json ./build/editor --level my_level.json +./build/editor --level my_level.json --game ./build/cntrl ``` LMB selects/drags props, RMB orbits, MMB pans, wheel zooms, `F` frames the level. Keys `1`–`4` switch between Select, Wall, Door and Decor tools: walls and doors are drawn by clicking two ground points, decor is dragged from the asset browser (all GLBs under `assets/models/`) into the 3D view. `Del` deletes -the selection, `Ctrl+Z`/`Ctrl+Y` undo/redo, `Ctrl+S` saves. The validation -panel runs a walkable-grid flood fill from the spawn and reports unreachable -rooms, the key or the exit; `level_tool --validate ` does the same -headlessly. +the selection, `Ctrl+Z`/`Ctrl+Y` (`Ctrl+Shift+Z`) undo/redo, `Ctrl+S` saves, +`Tab` toggles the inspector, `Esc` quits. Deleting a wall segment opens a gap +which can be restored from the inspector. See `docs/LEVEL_EDITOR.md` for the +full key map and field reference. -The level file is the authoring source of truth. `Floor 01` is baked into the +The **inspector** (right dock) edits every field of the current selection: +prop kind, position, size, yaw, scale, model, `solid`/`destructible`; wall +lines and gaps; doors; rooms; rituals; thermo doors; and the spawn/key/exit +anchors. With nothing selected it edits the level name and map dimensions. +The validation panel runs a walkable-grid flood fill from the spawn (with +gated doors both open and closed) and reports unreachable rooms, the key or +the exit, overlapping rooms, duplicate ids and missing models. + +`Ctrl+P` saves if needed and launches the game on the current level +(`cntrl --level `), so drafts can be playtested without baking. The +level file is the authoring source of truth; `Floor 01` is baked into the client at build time (`src/game/level_baked.hpp`, regenerated by `level_tool --bake` when the JSON changes), so `cntrl` ships without a level -file dependency: +file dependency. Baking refuses invalid levels: ```sh ./build/level_tool --dump-floor01 assets/levels/floor01.json ./build/level_tool --check assets/levels/floor01.json ./build/level_tool --validate assets/levels/floor01.json +cmake --build build --target check_level cmake --build build --target bake_level ctest --test-dir build --output-on-failure ``` diff --git a/assets/blender/fbc_agent.blend b/assets/blender/fbc_agent.blend index 2f08602..e71c61c 100644 Binary files a/assets/blender/fbc_agent.blend and b/assets/blender/fbc_agent.blend differ diff --git a/assets/models/agent.glb b/assets/models/agent.glb index 61abe2a..ebf3f97 100644 Binary files a/assets/models/agent.glb and b/assets/models/agent.glb differ diff --git a/docs/LEVEL_DESIGN_REVIEW.md b/docs/LEVEL_DESIGN_REVIEW.md index 3fe73fb..f66f9a5 100644 --- a/docs/LEVEL_DESIGN_REVIEW.md +++ b/docs/LEVEL_DESIGN_REVIEW.md @@ -39,6 +39,8 @@ The findings above are the audit baseline. Fixes have since landed in four phase Verification performed: `cmake --build build -j6` clean; standalone C++ harnesses for the ritual state machine and clearance/side-room flow pass; `--floor-overview` screenshots confirm the new corridor, projector marker, locked doors and HUD stamp. +**Level-editor iteration (same date, follow-up work):** the standalone editor gained a raygui inspector covering every `LevelData` field, stable wall/segment IDs (deleting a segment opens a reversible gap), two-state connectivity validation (doors open *and* closed), a bake gate that refuses invalid levels, `cntrl --level ` for playtesting drafts, and fixture-backed CTest coverage. This is tooling only; the open gameplay findings below are unchanged. See `docs/LEVEL_EDITOR.md`. + --- ## 2. Sources reviewed diff --git a/docs/LEVEL_EDITOR.md b/docs/LEVEL_EDITOR.md new file mode 100644 index 0000000..070c38b --- /dev/null +++ b/docs/LEVEL_EDITOR.md @@ -0,0 +1,95 @@ +# FBC: NIGHT SHIFT — Level Editor + +The editor authors `assets/levels/*.json`, the single source of truth for the +playable floor. The game reads a JSON at runtime (`cntrl --level `) and +falls back to the build-time baked copy (`src/game/level_baked.hpp`), which is +regenerated by `level_tool --bake` whenever the JSON changes. + +## Build and launch + +```sh +cmake --build build -j6 +./build/editor # assets/levels/floor01.json +./build/editor --level my_level.json --game ./build/cntrl +./build/editor --screenshot /tmp/editor.png # headless smoke capture +./build/editor --place plant 12.5 44 # debug: place an asset by name +``` + +`--game` sets the binary launched by `Ctrl+P`; without it the editor detects +`./cntrl`, `./build/cntrl` or `../cntrl` in that order. `--place` +selects the placed prop so its inspector fields can be inspected in a capture. + +## Controls + +| Input | Action | +|---|---| +| LMB (Select) | Select nearest prop/wall/door/room/ritual/thermo/anchor; drag props | +| LMB (Wall / Door) | First click starts the span, second click finishes it | +| LMB (Decor) | Place the selected asset from the browser | +| LMB drag from browser | Place the selected asset at the drop point | +| RMB or Alt+LMB | Orbit | +| MMB | Pan | +| Wheel | Zoom (scrolls the asset browser over its panel) | +| `1`–`4` | Select / Wall / Door / Decor tools | +| `Del` / `Backspace` | Delete the selection (anchors can only be moved) | +| `Ctrl+Z` / `Ctrl+Y` / `Ctrl+Shift+Z` | Undo / redo | +| `Ctrl+S` | Save to the current level path | +| `Ctrl+P` | Save if dirty, then launch `cntrl --level ` | +| `F` | Frame the whole level | +| `Tab` | Toggle the inspector | +| `Esc` | Quit | + +## Inspector field reference + +The right-hand dock edits the current selection. Numeric fields are sliders, +enums are combo boxes, booleans are check boxes and names/paths are text boxes. +Edits share one undo step per interaction (one per drag or text-box focus). + +| Selection | Fields | +|---|---| +| none (level) | `name`, `map_width`, `map_height`, `scale` | +| Prop | `kind`, `pos`, `w`, `d`, `h`, `y offset`, `yaw deg`, `scale`, `model`, `room_kind`, `solid`, `destructible` | +| Wall line | `axis`, `coord`, `from`, `to`, `height`, each gap's start/end, **DEL GAP**, **OPEN SEGMENT GAP** | +| Door | `id`, `rect` (`x0/y0/x1/y1`), `height` | +| Room | `name`, `rect`, `kind`, `flow`, `side idx` | +| Ritual | `type`, `pos`, `radius`, `duration`, `ring radius`, `ring count`, `light radius`, `light mult`, `light dur` | +| Thermo door | `pos`, `span`, `yaw deg` | +| Spawn / Key / Exit | `pos`; Key/Exit also their pickup/trigger radius | + +**Scale convention:** `scale` is the multiplier passed straight to raylib's +`DrawModelEx`, identical to the game's presenter. `w/d/h` are metadata used for +selection boxes and (for `solid` props) collision. Deleting a wall segment +adds a gap to the wall line; gaps are normalized (clamped, sorted, merged) and +can be removed from the inspector to close a passage again. + +## Validation and baking + +The validation readout at the top of the inspector is computed by +`level::validate()` (the same code `level_tool --validate` uses): + +- gated doors are tested both open and closed; a main room reachable only + through a gated door is an error, a gated side room is expected; +- solid props and walls both block the walkable-grid flood fill from spawn; +- spawn/key/exit must lie inside the map and outside walls; +- rooms must be reachable from spawn, key and exit too; +- duplicate door ids, duplicate ritual types, overlapping rooms, malformed + gaps, missing/out-of-range numeric fields and missing model files are + reported. + +```sh +./build/level_tool --check assets/levels/floor01.json # round-trip + validation +./build/level_tool --validate assets/levels/floor01.json # validation only +./build/level_tool --bake # refuses invalid levels +cmake --build build --target check_level +ctest --test-dir build --output-on-failure +``` + +Schema is `version: 1`; `from_json` accepts unknown optional fields but +rejects out-of-range values. New fields should default safely when absent. + +## Other tools + +`tools/blender/import_level.py` reads the same JSON into a reviewable Blender +blockout (set `CNTRL_LEVEL` for a different file, `CNTRL_OUT` for a different +`.blend` output). `tests/data/` holds a valid fixture and an intentionally +invalid one wired into CTest. diff --git a/docs/concept/agent_detail.png b/docs/concept/agent_detail.png index 930ca74..03030b3 100644 Binary files a/docs/concept/agent_detail.png and b/docs/concept/agent_detail.png differ diff --git a/docs/concept/agent_reference.png b/docs/concept/agent_reference.png index e7b1f56..a73540d 100644 Binary files a/docs/concept/agent_reference.png and b/docs/concept/agent_reference.png differ diff --git a/src/editor/editor_app.cpp b/src/editor/editor_app.cpp index 16349ba..d2a0962 100644 --- a/src/editor/editor_app.cpp +++ b/src/editor/editor_app.cpp @@ -1,23 +1,34 @@ #include "editor/editor_app.hpp" +#include "raygui.h" #include "raymath.h" #include #include #include #include +#include #include -#include +#include namespace editor { namespace { constexpr int kPanelWidth = 260; +constexpr int kInspectorWidth = 320; constexpr int kTopBar = 42; constexpr int kToolbar = 36; constexpr int kBottomBar = 30; constexpr int kItemHeight = 26; +constexpr const char* kRoomKinds = "Gate;Plaza;Projector;OfficeSuite;Silos;Stairwell;Side"; +constexpr const char* kRoomKindChoices = + "(none);Gate;Plaza;Projector;OfficeSuite;Silos;Stairwell;Side"; +constexpr const char* kPropKinds = + "Turnstile;Desk;MeetingTable;Screen;Seat;Silo;Shelf;ArchiveShelf;" + "HazardDoor;Key;Pillar;Decor"; +constexpr const char* kDoorKinds = "Janitor;Booth;Locker"; + Color tint(RoomKind kind, unsigned char alpha) { switch (kind) { case RoomKind::Gate: return {94, 143, 190, alpha}; @@ -78,7 +89,6 @@ App::App(std::string path) : path_(std::move(path)) { } assets_ = level::scan_assets(); if (!assets_.empty()) selected_asset_ = 0; - next_door_ = static_cast(level_.doors.size()); } Vector3 App::world(Vec2 p, float y) const { @@ -119,7 +129,7 @@ void App::init() { void App::frame_level() { target_ = {0.0f, 0.0f, 0.0f}; - distance_ = std::max(level_.map_width, level_.map_height) * level_.scale * 1.25f; + distance_ = std::max(level_.map_width, level_.map_height) * level_.scale * 1.4f; yaw_ = 0.0f; pitch_ = 0.85f; } @@ -151,7 +161,7 @@ void App::update_camera() { const int max_scroll = std::max(0, static_cast(assets_.size()) - 12); asset_scroll_ = std::clamp(asset_scroll_ - static_cast(wheel), 0, max_scroll); - } else { + } else if (!inside_inspector(mouse)) { distance_ = std::clamp(distance_ * std::exp(-wheel * 0.12f), 6.0f, 900.0f); } @@ -166,6 +176,11 @@ bool App::inside_panel(Vector2 mouse) const { && mouse.y <= GetScreenHeight() - kBottomBar; } +bool App::inside_inspector(Vector2 mouse) const { + return inspector_ && mouse.x >= GetScreenWidth() - kInspectorWidth + && mouse.y >= kTopBar && mouse.y <= GetScreenHeight() - kBottomBar; +} + int App::asset_at(Vector2 mouse) const { if (!inside_panel(mouse)) return -1; const float top = static_cast(kTopBar + kToolbar + 24); @@ -180,18 +195,34 @@ bool App::ground_point(Vec2& map_pos) const { if (std::fabs(ray.direction.y) < 1e-6f) return false; const float t = -ray.position.y / ray.direction.y; if (t <= 0.0f) return false; - const Vector3 point = Vector3Add(ray.position, - Vector3Scale(ray.direction, t)); + const Vector3 point = Vector3Add(ray.position, Vector3Scale(ray.direction, t)); map_pos = snap(level::to_map(level_, {point.x, point.z})); return true; } -void App::push_undo() { - undo_.push_back(level::serialize(level_)); +void App::push_snapshot(const std::string& snapshot) { + undo_.push_back(snapshot); if (undo_.size() > 64) undo_.erase(undo_.begin()); redo_.clear(); } +void App::push_undo() { + push_snapshot(level::serialize(level_)); +} + +void App::begin_edit() { + if (interacting_) return; + push_undo(); + interacting_ = true; +} + +void App::end_edit() { interacting_ = false; } + +void App::commit() { + dirty_ = true; + revalidate(); +} + void App::restore(const std::string& snapshot) { json::Value root; std::string error; @@ -199,10 +230,9 @@ void App::restore(const std::string& snapshot) { level::LevelData next; if (!level::from_json(root, next, error)) return; level_ = std::move(next); + selection_ = {}; + commit_text(); dirty_ = true; - selected_prop_ = -1; - selected_wall_ = -1; - selected_room_ = -1; revalidate(); } @@ -253,10 +283,12 @@ void App::place_decor(Vec2 map_pos) { p.d = size.z > 0.01f ? size.z : 1.0f; p.h = size.y > 0.01f ? size.y : 1.0f; p.model = path; + p.scale = 1.0f; level_.props.push_back(p); - selected_prop_ = static_cast(level_.props.size()) - 1; - dirty_ = true; - revalidate(); + selection_ = {Entity::Prop, static_cast(level_.props.size()) - 1, -1}; + status_message_ = "placed decor"; + status_timer_ = 2.0f; + commit(); } void App::finish_wall(Vec2 map_pos) { @@ -283,8 +315,10 @@ void App::finish_wall(Vec2 map_pos) { } push_undo(); level_.walls.push_back(w); - dirty_ = true; - revalidate(); + selection_ = {Entity::Wall, static_cast(level_.walls.size()) - 1, 0}; + status_message_ = "added wall line"; + status_timer_ = 2.0f; + commit(); } void App::finish_door(Vec2 map_pos) { @@ -297,152 +331,230 @@ void App::finish_door(Vec2 map_pos) { const Vec2 b = map_pos; pending_set_ = false; if (std::fabs(b.x - a.x) < 0.01f || std::fabs(b.y - a.y) < 0.01f) return; + const int id = level::allocate_door_id(level_); + if (id < 0) { + status_message_ = "all door ids are taken"; + status_timer_ = 3.0f; + return; + } level::Door d; - d.id = static_cast(next_door_ % static_cast(DoorId::Count)); + d.id = static_cast(id); d.rect = {std::min(a.x, b.x), std::min(a.y, b.y), std::max(a.x, b.x), std::max(a.y, b.y)}; - ++next_door_; push_undo(); level_.doors.push_back(d); - dirty_ = true; - revalidate(); + selection_ = {Entity::Door, static_cast(level_.doors.size()) - 1, -1}; + status_message_ = std::string("added door: ") + level::door_name(d.id); + status_timer_ = 2.0f; + commit(); +} + +void App::select_at(Vector2 mouse) { + float best_dist = 22.0f; + Selection best; + + for (size_t i = 0; i < level_.props.size(); ++i) { + const level::Prop& p = level_.props[i]; + const float d = screen_distance(mouse, + GetWorldToScreen(world_direct(prop_world_pos(p), + p.room_kind.empty() ? p.h * 0.5f : p.y), camera_)); + if (d < best_dist) { + best_dist = d; + best = {Entity::Prop, static_cast(i), -1}; + } + } + const auto walls = level::build_indexed_walls(level_); + for (const level::IndexedWall& wall : walls) { + const level::Rect& r = wall.wall.rect; + const Vector3 center{(r.x0 + r.x1) * 0.5f, wall.wall.height * 0.5f, + (r.y0 + r.y1) * 0.5f}; + const float d = screen_distance(mouse, GetWorldToScreen(center, camera_)); + if (d < best_dist) { + best_dist = d; + if (wall.source == level::WallSource::Line) { + best = {Entity::Wall, static_cast(wall.line), + static_cast(wall.segment)}; + } else if (wall.source == level::WallSource::Door) { + best = {Entity::Door, static_cast(wall.line), -1}; + } else { + best = {Entity::Prop, static_cast(wall.line), -1}; + } + } + } + for (size_t i = 0; i < level_.rooms.size(); ++i) { + const level::Rect& r = level_.rooms[i].rect; + const Vector3 center = world({(r.x0 + r.x1) * 0.5f, + (r.y0 + r.y1) * 0.5f}, 0.5f); + const float d = screen_distance(mouse, GetWorldToScreen(center, camera_)); + if (d < best_dist) { + best_dist = d; + best = {Entity::Room, static_cast(i), -1}; + } + } + for (size_t i = 0; i < level_.rituals.size(); ++i) { + const Vector3 center = world(level_.rituals[i].pos, 1.0f); + const float d = screen_distance(mouse, GetWorldToScreen(center, camera_)); + if (d < best_dist) { + best_dist = d; + best = {Entity::Ritual, static_cast(i), -1}; + } + } + for (size_t i = 0; i < level_.thermo.size(); ++i) { + const Vector3 center = world(level_.thermo[i].pos, 2.4f); + const float d = screen_distance(mouse, GetWorldToScreen(center, camera_)); + if (d < best_dist) { + best_dist = d; + best = {Entity::Thermo, static_cast(i), -1}; + } + } + const std::pair anchors[] = { + {Entity::Spawn, level_.anchors.spawn}, + {Entity::Key, level_.anchors.key}, + {Entity::Exit, level_.anchors.exit}}; + for (const auto& anchor : anchors) { + const float d = screen_distance(mouse, + GetWorldToScreen(world(anchor.second, 1.2f), camera_)); + if (d < best_dist) { + best_dist = d; + best = {anchor.first, -1, -1}; + } + } + + selection_ = best; + if (selection_.kind == Entity::Prop && selection_.index >= 0) { + dragged_prop_ = selection_.index; + } } void App::delete_selection() { - if (selected_prop_ >= 0) { - push_undo(); - level_.props.erase(level_.props.begin() + selected_prop_); - selected_prop_ = -1; - dirty_ = true; - revalidate(); - } else if (selected_wall_ >= 0) { - const auto walls = level::build_world_walls(level_); - if (selected_wall_ >= static_cast(walls.size())) return; - int counters = selected_wall_; - size_t line_index = level_.walls.size(); - for (size_t i = 0; i < level_.walls.size(); ++i) { - const level::WallLine& w = level_.walls[i]; - int count = 0; - float cur = w.from; - for (const auto& g : w.gaps) { - if (g.first > cur) ++count; - cur = std::max(cur, g.second); + switch (selection_.kind) { + case Entity::Prop: + if (selection_.index >= 0 + && selection_.index < static_cast(level_.props.size())) { + push_undo(); + level_.props.erase(level_.props.begin() + selection_.index); + status_message_ = "deleted prop"; + commit(); } - if (cur < w.to) ++count; - if (counters < count) { - line_index = i; - break; + break; + case Entity::Room: + if (selection_.index >= 0 + && selection_.index < static_cast(level_.rooms.size())) { + push_undo(); + level_.rooms.erase(level_.rooms.begin() + selection_.index); + status_message_ = "deleted room"; + commit(); } - counters -= count; + break; + case Entity::Wall: { + const std::string before = level::serialize(level_); + if (remove_wall_segment(level_, static_cast(selection_.index), + static_cast(selection_.sub))) { + push_snapshot(before); + status_message_ = "opened a gap in the wall"; + commit(); + } else { + status_message_ = "could not delete that wall segment"; + status_timer_ = 3.0f; + } + break; } - push_undo(); - if (line_index < level_.walls.size()) { - level_.walls.erase(level_.walls.begin() + static_cast(line_index)); - } else if (counters < static_cast(level_.doors.size())) { - level_.doors.erase(level_.doors.begin() + static_cast(counters)); - } else { - counters -= static_cast(level_.doors.size()); - size_t prop_index = 0; - int seen = 0; - for (size_t i = 0; i < level_.props.size(); ++i) { - if (!level_.props[i].solid) continue; - if (seen == counters) { - prop_index = i; - break; - } - ++seen; + case Entity::Door: + if (selection_.index >= 0 + && selection_.index < static_cast(level_.doors.size())) { + push_undo(); + level_.doors.erase(level_.doors.begin() + selection_.index); + status_message_ = "deleted door"; + commit(); } - if (prop_index < level_.props.size()) { - level_.props.erase(level_.props.begin() + static_cast(prop_index)); + break; + case Entity::Ritual: + if (selection_.index >= 0 + && selection_.index < static_cast(level_.rituals.size())) { + push_undo(); + level_.rituals.erase(level_.rituals.begin() + selection_.index); + status_message_ = "deleted ritual"; + commit(); } - } - selected_wall_ = -1; - dirty_ = true; - revalidate(); - } else if (selected_room_ >= 0) { - push_undo(); - level_.rooms.erase(level_.rooms.begin() + selected_room_); - selected_room_ = -1; - dirty_ = true; - revalidate(); + break; + case Entity::Thermo: + if (selection_.index >= 0 + && selection_.index < static_cast(level_.thermo.size())) { + push_undo(); + level_.thermo.erase(level_.thermo.begin() + selection_.index); + status_message_ = "deleted thermo door"; + commit(); + } + break; + default: + status_message_ = "anchors cannot be deleted; move them instead"; + status_timer_ = 3.0f; + break; } + selection_ = {}; +} + +void App::playtest() { + if (dirty_) { + if (!level::save(path_, level_)) { + status_message_ = "save failed; cannot playtest"; + status_timer_ = 3.0f; + return; + } + dirty_ = false; + } + const std::string command = "\"" + game_path_ + "\" --level \"" + path_ + "\" &"; + std::system(command.c_str()); + status_message_ = "launched playtest: " + game_path_; + status_timer_ = 4.0f; } void App::handle_keys() { const bool ctrl = IsKeyDown(KEY_LEFT_CONTROL) || IsKeyDown(KEY_RIGHT_CONTROL); + const bool shift = IsKeyDown(KEY_LEFT_SHIFT) || IsKeyDown(KEY_RIGHT_SHIFT); if (IsKeyPressed(KEY_ESCAPE)) should_close_ = true; - if (IsKeyPressed(KEY_F)) frame_level(); + if (IsKeyPressed(KEY_F) && text_focus_ < 0) frame_level(); + if (IsKeyPressed(KEY_TAB) && text_focus_ < 0) inspector_ = !inspector_; if (ctrl && IsKeyPressed(KEY_S)) { - if (level::save(path_, level_)) dirty_ = false; + if (level::save(path_, level_)) { + dirty_ = false; + status_message_ = "saved " + path_; + status_timer_ = 2.0f; + } else { + status_message_ = "save failed"; + status_timer_ = 3.0f; + } } - if (ctrl && IsKeyPressed(KEY_Z)) undo(); + if (ctrl && IsKeyPressed(KEY_P)) playtest(); + if (ctrl && (IsKeyPressed(KEY_Z) && shift)) redo(); + else if (ctrl && IsKeyPressed(KEY_Z)) undo(); if (ctrl && IsKeyPressed(KEY_Y)) redo(); - if (IsKeyPressed(KEY_DELETE) || IsKeyPressed(KEY_BACKSPACE)) delete_selection(); - if (IsKeyPressed(KEY_ONE)) tool_ = Tool::Select; - if (IsKeyPressed(KEY_TWO)) tool_ = Tool::Wall; - if (IsKeyPressed(KEY_THREE)) tool_ = Tool::Door; - if (IsKeyPressed(KEY_FOUR)) tool_ = Tool::Decor; + if (text_focus_ < 0 + && (IsKeyPressed(KEY_DELETE) || IsKeyPressed(KEY_BACKSPACE))) { + delete_selection(); + } + if (text_focus_ < 0) { + if (IsKeyPressed(KEY_ONE)) tool_ = Tool::Select; + if (IsKeyPressed(KEY_TWO)) tool_ = Tool::Wall; + if (IsKeyPressed(KEY_THREE)) tool_ = Tool::Door; + if (IsKeyPressed(KEY_FOUR)) tool_ = Tool::Decor; + } } void App::handle_pointer() { const Vector2 mouse = GetMousePosition(); if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) { - if (inside_panel(mouse)) { + if (inside_inspector(mouse) || inside_panel(mouse)) { const int index = asset_at(mouse); - if (index >= 0) { + if (inside_panel(mouse) && index >= 0) { selected_asset_ = index; dragging_panel_asset_ = true; } return; } if (tool_ == Tool::Select) { - float best_dist = 22.0f; - int best_kind = -1; - int best_index = -1; - for (size_t i = 0; i < level_.props.size(); ++i) { - const level::Prop& p = level_.props[i]; - const float d = screen_distance(mouse, - GetWorldToScreen(world_direct(prop_world_pos(p), p.room_kind.empty() ? p.h * 0.5f : p.y), camera_)); - if (d < best_dist) { - best_dist = d; - best_kind = 0; - best_index = static_cast(i); - } - } - const auto walls = level::build_world_walls(level_); - for (size_t i = 0; i < walls.size(); ++i) { - const level::Rect& r = walls[i].rect; - const Vector3 center{(r.x0 + r.x1) * 0.5f, walls[i].height * 0.5f, - (r.y0 + r.y1) * 0.5f}; - const float d = screen_distance(mouse, - GetWorldToScreen(center, camera_)); - if (d < best_dist) { - best_dist = d; - best_kind = 1; - best_index = static_cast(i); - } - } - for (size_t i = 0; i < level_.rooms.size(); ++i) { - const level::Rect& r = level_.rooms[i].rect; - const Vector3 center = world({(r.x0 + r.x1) * 0.5f, - (r.y0 + r.y1) * 0.5f}, 0.5f); - const float d = screen_distance(mouse, - GetWorldToScreen(center, camera_)); - if (d < best_dist) { - best_dist = d; - best_kind = 2; - best_index = static_cast(i); - } - } - selected_prop_ = best_kind == 0 ? best_index : -1; - selected_wall_ = best_kind == 1 ? best_index : -1; - selected_room_ = best_kind == 2 ? best_index : -1; - if (selected_prop_ >= 0) { - dragging_prop_ = true; - dragged_prop_ = selected_prop_; - drag_undo_pushed_ = false; - } + select_at(mouse); } else { Vec2 map_pos; if (ground_point(map_pos)) { @@ -454,50 +566,47 @@ void App::handle_pointer() { } if (dragging_panel_asset_ && IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) { - if (!inside_panel(mouse)) { + if (!inside_panel(mouse) && !inside_inspector(mouse)) { Vec2 map_pos; if (ground_point(map_pos)) place_decor(map_pos); } dragging_panel_asset_ = false; } - if (dragging_prop_ && IsMouseButtonDown(MOUSE_BUTTON_LEFT)) { + if (dragging_prop_ >= 0 && IsMouseButtonDown(MOUSE_BUTTON_LEFT) + && tool_ == Tool::Select && !inside_panel(mouse) && !inside_inspector(mouse)) { Vec2 map_pos; - if (ground_point(map_pos) && dragged_prop_ >= 0 - && dragged_prop_ < static_cast(level_.props.size())) { - level::Prop& p = level_.props[static_cast(dragged_prop_)]; + if (ground_point(map_pos) && dragging_prop_ < static_cast(level_.props.size())) { + level::Prop& p = level_.props[static_cast(dragging_prop_)]; Vec2 next_pos = map_pos; if (!p.room_kind.empty()) { - const Vec2 world = level::to_world(level_, map_pos); + const Vec2 wpos = level::to_world(level_, map_pos); for (const level::Room& r : level_.rooms) { - if (std::string(level::room_kind_name(r.kind)) != p.room_kind) - continue; + if (std::string(level::room_kind_name(r.kind)) != p.room_kind) continue; const level::Rect wr = level::to_world_rect(level_, r.rect); - next_pos = {world.x - (wr.x0 + wr.x1) * 0.5f, - world.y - (wr.y0 + wr.y1) * 0.5f}; + next_pos = {wpos.x - (wr.x0 + wr.x1) * 0.5f, + wpos.y - (wr.y0 + wr.y1) * 0.5f}; break; } } if (p.pos.x != next_pos.x || p.pos.y != next_pos.y) { - if (!drag_undo_pushed_) { - push_undo(); - drag_undo_pushed_ = true; - } + begin_edit(); p.pos = next_pos; - dirty_ = true; + commit(); } } } - if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) { - if (dragging_prop_) revalidate(); - dragging_prop_ = false; - } + if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) dragging_prop_ = -1; } void App::update() { update_camera(); handle_keys(); handle_pointer(); + if (interacting_ && text_focus_ < 0 && !IsMouseButtonDown(MOUSE_BUTTON_LEFT)) { + end_edit(); + } + if (status_timer_ > 0.0f) status_timer_ -= GetFrameTime(); } Model& App::model_for(const std::string& path) { @@ -551,8 +660,8 @@ void App::draw_model(const std::string& path, Vec2 world_pos, float yaw, float scale, float y) { Model& model = model_for(path); if (model.meshCount == 0) return; - DrawModel(model, world_direct(world_pos, y), scale, WHITE); - (void)yaw; + DrawModelEx(model, world_direct(world_pos, y), {0.0f, 1.0f, 0.0f}, + yaw * 180.0f / PI, {scale, scale, scale}, WHITE); } void App::draw_grid() const { @@ -577,15 +686,17 @@ void App::draw_rooms() const { const Vector3 center{(w.x0 + w.x1) * 0.5f, 0.03f, (w.y0 + w.y1) * 0.5f}; const Vector3 size{w.x1 - w.x0, 0.04f, w.y1 - w.y0}; DrawCube(center, size.x, size.y, size.z, tint(r.kind, 46)); + const bool selected = selection_.kind == Entity::Room + && selection_.index == static_cast(i); DrawCubeWires(center, size.x, size.y, size.z, - static_cast(i) == selected_room_ ? GOLD : tint(r.kind, 190)); + selected ? GOLD : tint(r.kind, 190)); } } void App::draw_walls() const { - const auto walls = level::build_world_walls(level_); - for (size_t i = 0; i < walls.size(); ++i) { - const level::WorldWall& w = walls[i]; + const auto walls = level::build_indexed_walls(level_); + for (const level::IndexedWall& iw : walls) { + const level::WorldWall& w = iw.wall; const Vector3 center{(w.rect.x0 + w.rect.x1) * 0.5f, w.height * 0.5f, (w.rect.y0 + w.rect.y1) * 0.5f}; const Vector3 size{w.rect.x1 - w.rect.x0, w.height, @@ -595,7 +706,15 @@ void App::draw_walls() const { if (w.door == static_cast(DoorId::Booth)) c = {200, 160, 60, 255}; if (w.door == static_cast(DoorId::Locker)) c = {160, 90, 200, 255}; DrawCube(center, size.x, size.y, size.z, c); - if (static_cast(i) == selected_wall_) { + const bool selected = + (iw.source == level::WallSource::Line + && selection_.kind == Entity::Wall + && selection_.index == static_cast(iw.line) + && selection_.sub == static_cast(iw.segment)) + || (iw.source == level::WallSource::Door + && selection_.kind == Entity::Door + && selection_.index == static_cast(iw.line)); + if (selected) { DrawCubeWires(center, size.x + 0.1f, size.y + 0.1f, size.z + 0.1f, GOLD); } } @@ -607,10 +726,7 @@ void App::draw_walls() const { across_x ? span : 0.35f, 0.3f, across_x ? 0.35f : span, {90, 200, 210, 220}); } - if (pending_set_) { - const Vector3 pos = world(pending_, 1.0f); - DrawSphere(pos, 1.0f, GOLD); - } + if (pending_set_) DrawSphere(world(pending_, 1.0f), 1.0f, GOLD); } void App::draw_props() { @@ -626,7 +742,7 @@ void App::draw_props() { } else { DrawCube(world_direct(wp, base_y), p.w, p.h, p.d, prop_color(p.kind)); } - if (static_cast(i) == selected_prop_) { + if (selection_.kind == Entity::Prop && selection_.index == static_cast(i)) { DrawCubeWires(world_direct(wp, base_y), p.w + 0.12f, p.h + 0.12f, p.d + 0.12f, GOLD); } @@ -634,12 +750,20 @@ void App::draw_props() { } void App::draw_anchors() const { - const auto marker = [&](Vec2 p, Color c) { - DrawCylinder(world(p, 1.2f), 1.0f, 1.0f, 2.4f, 8, c); + const auto marker = [&](Vec2 p, Entity kind, Color c) { + const bool selected = selection_.kind == kind; + DrawCylinder(world(p, 1.2f), 1.0f, 1.0f, 2.4f, 8, + selected ? GOLD : c); }; - marker(level_.anchors.spawn, {80, 220, 120, 255}); - marker(level_.anchors.key, {240, 210, 70, 255}); - marker(level_.anchors.exit, {230, 80, 70, 255}); + marker(level_.anchors.spawn, Entity::Spawn, {80, 220, 120, 255}); + marker(level_.anchors.key, Entity::Key, {240, 210, 70, 255}); + marker(level_.anchors.exit, Entity::Exit, {230, 80, 70, 255}); + for (const level::Ritual& r : level_.rituals) { + const Vec2 center = level::to_world(level_, r.pos); + DrawCylinder({center.x, 0.6f, center.y}, r.radius, r.radius, 0.08f, 18, + {210, 170, 60, 90}); + DrawCylinder({center.x, 1.1f, center.y}, 0.6f, 0.6f, 2.2f, 8, GOLD); + } } void App::draw_asset_panel() const { @@ -677,63 +801,372 @@ void App::draw_asset_panel() const { } } +bool App::field_header(const char* text, float x, float y, float w) { + DrawRectangle(x, y, w, 20, {44, 46, 54, 255}); + DrawText(text, x + 6, y + 4, 12, {235, 200, 90, 255}); + return false; +} + +bool App::field_bool(float x, float y, float w, const char* label, bool& value) { + DrawText(label, x, y + 3, 11, {200, 200, 205, 255}); + Rectangle r{x + 120, y, w - 128, 18}; + bool v = value; + const int changed = GuiCheckBox(r, nullptr, &v); + if (changed && v != value) { + begin_edit(); + value = v; + commit(); + } + return changed != 0; +} + +bool App::field_float(float x, float y, float w, const char* label, float& value, + float lo, float hi) { + DrawText(label, x, y + 3, 11, {200, 200, 205, 255}); + Rectangle r{x + 120, y, w - 128, 18}; + float v = std::clamp(value, lo, hi); + const int changed = GuiSlider(r, nullptr, TextFormat("%.2f", v), &v, lo, hi); + if (changed && std::fabs(v - value) > 1e-6f) { + begin_edit(); + value = v; + commit(); + } + return changed != 0; +} + +bool App::field_int(float x, float y, float w, const char* label, int& value, + int lo, int hi) { + DrawText(label, x, y + 3, 11, {200, 200, 205, 255}); + Rectangle r{x + 120, y, w - 128, 18}; + float v = static_cast(std::clamp(value, lo, hi)); + const int changed = GuiSlider(r, nullptr, + TextFormat("%d", static_cast(std::lround(v))), + &v, static_cast(lo), static_cast(hi)); + const int next = std::clamp(static_cast(std::lround(v)), lo, hi); + if (changed && next != value) { + begin_edit(); + value = next; + commit(); + } + return changed != 0; +} + +bool App::field_enum(float x, float y, float w, const char* label, int& value, + const char* items, int count) { + DrawText(label, x, y + 3, 11, {200, 200, 205, 255}); + Rectangle r{x + 120, y, w - 128, 18}; + int v = std::clamp(value, 0, count - 1); + const int changed = GuiComboBox(r, items, &v); + if (changed && v != value) { + begin_edit(); + value = v; + commit(); + } + return changed != 0; +} + +void App::commit_text() { + text_focus_ = -1; + end_edit(); +} + +bool App::field_text(float x, float y, float w, int id, const char* label, + std::string& value) { + DrawText(label, x, y + 3, 11, {200, 200, 205, 255}); + Rectangle r{x + 120, y, w - 128, 18}; + const Vector2 mouse = GetMousePosition(); + if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT) && CheckCollisionPointRec(mouse, r) + && text_focus_ != id) { + commit_text(); + text_focus_ = id; + text_rect_ = r; + std::snprintf(text_buf_, sizeof(text_buf_), "%s", value.c_str()); + begin_edit(); + } + if (text_focus_ == id) { + text_rect_ = r; + const int changed = GuiTextBox(r, text_buf_, static_cast(sizeof(text_buf_)), true); + if (changed) { + value = text_buf_; + commit(); + } + return changed != 0; + } + char display[256]; + std::snprintf(display, sizeof(display), "%s", value.c_str()); + GuiTextBox(r, display, static_cast(sizeof(display)), false); + return false; +} + +void App::draw_inspector_fields(float x, float y, float w) { + int row = 0; + const auto next_y = [&]() { return y + static_cast(row++) * 22.0f; }; + const float max_y = static_cast(GetScreenHeight() - kBottomBar - 24); + + switch (selection_.kind) { + case Entity::None: { + field_header("LEVEL", x, next_y(), w); + field_text(x, next_y(), w, 1, "name", level_.name); + field_float(x, next_y(), w, "map width", level_.map_width, 16.0f, 1000.0f); + field_float(x, next_y(), w, "map height", level_.map_height, 16.0f, 1000.0f); + field_float(x, next_y(), w, "scale", level_.scale, 0.1f, 10.0f); + field_header("COUNTS", x, next_y(), w); + char counts[128]; + std::snprintf(counts, sizeof(counts), "rooms %zu walls %zu props %zu", + level_.rooms.size(), level_.walls.size(), level_.props.size()); + DrawText(counts, x + 6, next_y(), 11, {200, 200, 205, 255}); + break; + } + case Entity::Prop: { + if (selection_.index < 0 + || selection_.index >= static_cast(level_.props.size())) break; + level::Prop& p = level_.props[static_cast(selection_.index)]; + field_header("PROP", x, next_y(), w); + int kind = static_cast(p.kind); + if (field_enum(x, next_y(), w, "kind", kind, kPropKinds, 12)) { + p.kind = static_cast(std::clamp(kind, 0, 11)); + } + field_float(x, next_y(), w, "pos x", p.pos.x, 0.0f, level_.map_width); + field_float(x, next_y(), w, "pos y", p.pos.y, 0.0f, level_.map_height); + field_float(x, next_y(), w, "width", p.w, 0.01f, 60.0f); + field_float(x, next_y(), w, "depth", p.d, 0.01f, 60.0f); + field_float(x, next_y(), w, "height", p.h, 0.01f, 60.0f); + field_float(x, next_y(), w, "y offset", p.y, -5.0f, 30.0f); + float yaw_deg = p.yaw * 180.0f / PI; + if (field_float(x, next_y(), w, "yaw deg", yaw_deg, -180.0f, 180.0f)) { + p.yaw = yaw_deg * PI / 180.0f; + } + field_float(x, next_y(), w, "scale", p.scale, 0.01f, 20.0f); + field_text(x, next_y(), w, 2, "model", p.model); + int room_kind = 0; + for (int i = 0; i < 7; ++i) { + if (p.room_kind == level::room_kind_name(static_cast(i))) { + room_kind = i + 1; + break; + } + } + if (field_enum(x, next_y(), w, "room kind", room_kind, + kRoomKindChoices, 8)) { + p.room_kind = room_kind == 0 + ? "" + : level::room_kind_name( + static_cast(room_kind - 1)); + } + field_bool(x, next_y(), w, "solid", p.solid); + field_bool(x, next_y(), w, "destructible", p.destructible); + break; + } + case Entity::Room: { + if (selection_.index < 0 + || selection_.index >= static_cast(level_.rooms.size())) break; + level::Room& r = level_.rooms[static_cast(selection_.index)]; + field_header("ROOM", x, next_y(), w); + field_text(x, next_y(), w, 4, "name", r.name); + field_float(x, next_y(), w, "x0", r.rect.x0, 0.0f, level_.map_width); + field_float(x, next_y(), w, "y0", r.rect.y0, 0.0f, level_.map_height); + field_float(x, next_y(), w, "x1", r.rect.x1, 0.0f, level_.map_width); + field_float(x, next_y(), w, "y1", r.rect.y1, 0.0f, level_.map_height); + int kind = static_cast(r.kind); + if (field_enum(x, next_y(), w, "kind", kind, kRoomKinds, 7)) { + r.kind = static_cast(std::clamp(kind, 0, 6)); + } + field_int(x, next_y(), w, "flow", r.flow, 0, 20); + field_int(x, next_y(), w, "side idx", r.side_index, -1, 7); + break; + } + case Entity::Wall: { + if (selection_.index < 0 + || selection_.index >= static_cast(level_.walls.size())) break; + level::WallLine& line = level_.walls[static_cast(selection_.index)]; + field_header("WALL LINE", x, next_y(), w); + field_int(x, next_y(), w, "axis", line.axis, 0, 1); + field_float(x, next_y(), w, "coord", line.coord, 0.0f, + std::max(level_.map_width, level_.map_height)); + field_float(x, next_y(), w, "from", line.from, 0.0f, + std::max(level_.map_width, level_.map_height)); + field_float(x, next_y(), w, "to", line.to, 0.0f, + std::max(level_.map_width, level_.map_height)); + field_float(x, next_y(), w, "height", line.height, 0.5f, 12.0f); + for (size_t g = 0; g < line.gaps.size() && next_y() < max_y; ++g) { + char label[32]; + std::snprintf(label, sizeof(label), "gap %zu", g); + field_float(x, next_y(), w, label, line.gaps[g].first, line.from, line.to); + std::snprintf(label, sizeof(label), " end %zu", g); + field_float(x, next_y(), w, label, line.gaps[g].second, line.from, line.to); + char button[32]; + std::snprintf(button, sizeof(button), "DEL GAP %zu", g); + if (GuiButton({x + 120, next_y(), w - 128, 18}, button)) { + push_undo(); + restore_wall_gap(level_, static_cast(selection_.index), g); + commit(); + } + } + if (GuiButton({x + 6, next_y(), w - 12, 20}, "OPEN SEGMENT GAP")) { + const std::string before = level::serialize(level_); + if (remove_wall_segment(level_, static_cast(selection_.index), + static_cast(selection_.sub))) { + push_snapshot(before); + commit(); + } + } + break; + } + case Entity::Door: { + if (selection_.index < 0 + || selection_.index >= static_cast(level_.doors.size())) break; + level::Door& d = level_.doors[static_cast(selection_.index)]; + field_header("DOOR", x, next_y(), w); + int id = static_cast(d.id); + if (field_enum(x, next_y(), w, "id", id, kDoorKinds, 3)) { + d.id = static_cast(std::clamp(id, 0, 2)); + } + field_float(x, next_y(), w, "x0", d.rect.x0, 0.0f, level_.map_width); + field_float(x, next_y(), w, "y0", d.rect.y0, 0.0f, level_.map_height); + field_float(x, next_y(), w, "x1", d.rect.x1, 0.0f, level_.map_width); + field_float(x, next_y(), w, "y1", d.rect.y1, 0.0f, level_.map_height); + field_float(x, next_y(), w, "height", d.height, 0.5f, 12.0f); + break; + } + case Entity::Ritual: { + if (selection_.index < 0 + || selection_.index >= static_cast(level_.rituals.size())) break; + level::Ritual& r = level_.rituals[static_cast(selection_.index)]; + field_header("RITUAL", x, next_y(), w); + field_text(x, next_y(), w, 5, "type", r.type); + field_float(x, next_y(), w, "pos x", r.pos.x, 0.0f, level_.map_width); + field_float(x, next_y(), w, "pos y", r.pos.y, 0.0f, level_.map_height); + field_float(x, next_y(), w, "radius", r.radius, 0.1f, 40.0f); + field_float(x, next_y(), w, "duration", r.duration, 1.0f, 900.0f); + field_float(x, next_y(), w, "ring radius", r.ring_radius, 0.0f, 60.0f); + field_int(x, next_y(), w, "ring count", r.ring_count, 0, 32); + field_float(x, next_y(), w, "light radius", r.light_radius, 0.0f, 80.0f); + field_float(x, next_y(), w, "light mult", r.light_damage_mult, 0.01f, 5.0f); + field_float(x, next_y(), w, "light dur", r.light_duration, 0.0f, 300.0f); + break; + } + case Entity::Thermo: { + if (selection_.index < 0 + || selection_.index >= static_cast(level_.thermo.size())) break; + level::ThermoDoor& t = level_.thermo[static_cast(selection_.index)]; + field_header("THERMO DOOR", x, next_y(), w); + field_float(x, next_y(), w, "pos x", t.pos.x, 0.0f, level_.map_width); + field_float(x, next_y(), w, "pos y", t.pos.y, 0.0f, level_.map_height); + field_float(x, next_y(), w, "span", t.span, 0.5f, 120.0f); + float yaw_deg = t.yaw * 180.0f / PI; + if (field_float(x, next_y(), w, "yaw deg", yaw_deg, -180.0f, 180.0f)) { + t.yaw = yaw_deg * PI / 180.0f; + } + break; + } + case Entity::Spawn: + case Entity::Key: + case Entity::Exit: { + field_header("ANCHOR", x, next_y(), w); + Vec2* p = selection_.kind == Entity::Spawn ? &level_.anchors.spawn + : selection_.kind == Entity::Key ? &level_.anchors.key + : &level_.anchors.exit; + field_float(x, next_y(), w, "pos x", p->x, 0.0f, level_.map_width); + field_float(x, next_y(), w, "pos y", p->y, 0.0f, level_.map_height); + if (selection_.kind == Entity::Key) { + field_float(x, next_y(), w, "key radius", level_.anchors.key_radius, + 0.1f, 30.0f); + } + if (selection_.kind == Entity::Exit) { + field_float(x, next_y(), w, "exit radius", level_.anchors.exit_radius, + 0.1f, 30.0f); + } + break; + } + } +} + +void App::draw_inspector() { + if (!inspector_) return; + const float x = static_cast(GetScreenWidth() - kInspectorWidth); + const float top = static_cast(kTopBar); + const float h = static_cast(GetScreenHeight() - kTopBar - kBottomBar); + DrawRectangle(x, top, static_cast(kInspectorWidth), h, {20, 21, 26, 248}); + DrawLine(x, top, x, top + h, {70, 70, 78, 255}); + DrawText("INSPECTOR [TAB]", x + 8, top + 6, 12, {230, 195, 90, 255}); + + if (text_focus_ >= 0 && IsMouseButtonPressed(MOUSE_BUTTON_LEFT) + && !CheckCollisionPointRec(GetMousePosition(), text_rect_)) { + commit_text(); + } + + float y = top + 26.0f; + char summary[96]; + std::snprintf(summary, sizeof(summary), "VALIDATION %s %d err / %d warn", + validation_.ok() ? "OK" : "FAILED", + static_cast(validation_.errors.size()), + static_cast(validation_.warnings.size())); + DrawText(summary, x + 8, y, 11, + validation_.ok() ? Color{110, 220, 140, 255} : Color{240, 110, 90, 255}); + y += 16.0f; + int issues = 0; + for (const auto& e : validation_.errors) { + if (issues++ >= 4) break; + DrawText(e.c_str(), x + 8, y, 10, {240, 130, 110, 255}); + y += 13.0f; + } + for (const auto& w : validation_.warnings) { + if (issues++ >= 4) break; + DrawText(w.c_str(), x + 8, y, 10, {220, 190, 110, 255}); + y += 13.0f; + } + if (status_timer_ > 0.0f && !status_message_.empty()) { + DrawText(status_message_.c_str(), x + 8, y, 10, {150, 210, 240, 255}); + y += 13.0f; + } + DrawLine(x + 6, y, x + kInspectorWidth - 6, y, {70, 70, 78, 255}); + draw_inspector_fields(x + 8, y + 6, static_cast(kInspectorWidth) - 16); +} + void App::draw_ui() const { DrawRectangle(0, 0, GetScreenWidth(), kTopBar, {18, 18, 22, 235}); DrawText("FBC: NIGHT SHIFT / LEVEL EDITOR", 14, 12, 18, {235, 200, 90, 255}); const std::string status = path_ + (dirty_ ? " * UNSAVED" : ""); DrawText(status.c_str(), 420, 14, 14, {190, 190, 195, 255}); - const int vx = GetScreenWidth() - 366; - char validation_text[96]; - std::snprintf(validation_text, sizeof(validation_text), "VALIDATION: %s (%d err, %d warn)", - validation_.ok() ? "OK" : "FAILED", - static_cast(validation_.errors.size()), - static_cast(validation_.warnings.size())); - DrawRectangle(vx - 6, kTopBar + 4, 364, 24, {24, 26, 30, 230}); - DrawText(validation_text, vx, kTopBar + 9, 13, - validation_.ok() ? Color{110, 220, 140, 255} : Color{240, 110, 90, 255}); - int row = 0; - for (const auto& e : validation_.errors) { - if (row >= 3) break; - DrawText(e.c_str(), vx, kTopBar + 34 + row * 16, 11, {240, 130, 110, 255}); - ++row; - } - for (const auto& w : validation_.warnings) { - if (row >= 3) break; - DrawText(w.c_str(), vx, kTopBar + 34 + row * 16, 11, {220, 190, 110, 255}); - ++row; - } - char info[256]; - if (selected_prop_ >= 0) { - const auto& p = level_.props[static_cast(selected_prop_)]; - std::snprintf(info, sizeof(info), - "PROP %d %s %s map(%.1f, %.1f) size %.2f x %.2f x %.2f", - selected_prop_, level::prop_kind_name(p.kind), - p.model.empty() ? "-" : p.model.c_str(), p.pos.x, p.pos.y, - p.w, p.d, p.h); - } else if (selected_wall_ >= 0) { - const auto walls = level::build_world_walls(level_); - const auto& w = walls[static_cast(selected_wall_)]; - std::snprintf(info, sizeof(info), "WALL %d height %.1f door %d", - selected_wall_, w.height, w.door); - } else if (selected_room_ >= 0) { - const auto& r = level_.rooms[static_cast(selected_room_)]; - std::snprintf(info, sizeof(info), "ROOM %d %s kind %s flow %d", - selected_room_, r.name.c_str(), level::room_kind_name(r.kind), - r.flow); - } else { - std::snprintf(info, sizeof(info), - "%zu rooms | %zu wall lines | %zu doors | %zu props | %zu rituals | undo %zu", - level_.rooms.size(), level_.walls.size(), level_.doors.size(), - level_.props.size(), level_.rituals.size(), undo_.size()); + switch (selection_.kind) { + case Entity::Prop: + if (selection_.index >= 0 + && selection_.index < static_cast(level_.props.size())) { + const auto& p = level_.props[static_cast(selection_.index)]; + std::snprintf(info, sizeof(info), + "PROP %d %s %s map(%.1f, %.1f) scale %.2f", + selection_.index, level::prop_kind_name(p.kind), + p.model.empty() ? "-" : p.model.c_str(), + p.pos.x, p.pos.y, p.scale); + } else info[0] = '\0'; + break; + case Entity::Wall: + std::snprintf(info, sizeof(info), "WALL LINE %d SEGMENT %d", + selection_.index, selection_.sub); + break; + case Entity::Room: + if (selection_.index >= 0 + && selection_.index < static_cast(level_.rooms.size())) { + const auto& r = level_.rooms[static_cast(selection_.index)]; + std::snprintf(info, sizeof(info), "ROOM %d %s kind %s flow %d", + selection_.index, r.name.c_str(), + level::room_kind_name(r.kind), r.flow); + } else info[0] = '\0'; + break; + default: + std::snprintf(info, sizeof(info), + "%zu rooms | %zu wall lines | %zu doors | %zu props | %zu rituals | undo %zu", + level_.rooms.size(), level_.walls.size(), level_.doors.size(), + level_.props.size(), level_.rituals.size(), undo_.size()); + break; } DrawText(info, kPanelWidth + 12, kTopBar + 10, 14, {220, 220, 225, 255}); DrawRectangle(0, GetScreenHeight() - kBottomBar, GetScreenWidth(), kBottomBar, {18, 18, 22, 235}); - DrawText("LMB select/drag | 1-4 tools | Del delete | Ctrl+Z/Y undo | F frame | Ctrl+S save | Esc quit", - 14, GetScreenHeight() - 23, 14, {170, 170, 178, 255}); + DrawText("LMB select/drag | 1-4 tools | Del delete | Ctrl+Z/Y undo | F frame | Tab inspector | Ctrl+S save | Ctrl+P playtest | Esc quit", + 14, GetScreenHeight() - 23, 14, {170, 170, 178, 255}); } void App::draw() { @@ -748,10 +1181,12 @@ void App::draw() { EndMode3D(); draw_asset_panel(); draw_ui(); + draw_inspector(); EndDrawing(); } void App::shutdown() { + commit_text(); for (auto& item : models_) UnloadModel(item.second); models_.clear(); } diff --git a/src/editor/editor_app.hpp b/src/editor/editor_app.hpp index df9c3c6..7b799d0 100644 --- a/src/editor/editor_app.hpp +++ b/src/editor/editor_app.hpp @@ -13,6 +13,14 @@ namespace editor { enum class Tool { Select, Wall, Door, Decor }; +enum class Entity { None, Prop, Room, Wall, Door, Ritual, Thermo, Spawn, Key, Exit }; + +struct Selection { + Entity kind = Entity::None; + int index = -1; // entity index; for Wall this is the WallLine index + int sub = -1; // visible segment index for Wall +}; + class App { public: explicit App(std::string path); @@ -26,24 +34,32 @@ public: const std::string& path() const { return path_; } bool dirty() const { return dirty_; } void debug_place(const std::string& asset_name, Vec2 map_pos); + void set_game_path(const std::string& path) { game_path_ = path; } private: void update_camera(); void handle_keys(); void handle_pointer(); + void select_at(Vector2 mouse); void place_decor(Vec2 map_pos); void finish_wall(Vec2 map_pos); void finish_door(Vec2 map_pos); void delete_selection(); void push_undo(); + void push_snapshot(const std::string& snapshot); + void begin_edit(); + void end_edit(); + void commit(); void revalidate(); void undo(); void redo(); void restore(const std::string& snapshot); void frame_level(); + void playtest(); bool ground_point(Vec2& map_pos) const; bool inside_panel(Vector2 mouse) const; + bool inside_inspector(Vector2 mouse) const; int asset_at(Vector2 mouse) const; Model& model_for(const std::string& path); Vector3 model_size(const std::string& path); @@ -61,18 +77,31 @@ private: void draw_anchors() const; void draw_ui() const; void draw_asset_panel() const; + void draw_inspector(); + void draw_inspector_fields(float x, float y, float w); + + bool field_header(const char* text, float x, float y, float w); + bool field_bool(float x, float y, float w, const char* label, bool& value); + bool field_float(float x, float y, float w, const char* label, float& value, + float lo, float hi); + bool field_int(float x, float y, float w, const char* label, int& value, + int lo, int hi); + bool field_enum(float x, float y, float w, const char* label, int& value, + const char* items, int count); + bool field_text(float x, float y, float w, int id, const char* label, + std::string& value); + void commit_text(); level::LevelData level_; level::ValidationResult validation_; std::string path_; + std::string game_path_ = "./cntrl"; Camera3D camera_{}; Vector3 target_{}; float yaw_ = 0.0f; float pitch_ = 0.85f; float distance_ = 320.0f; - int selected_prop_ = -1; - int selected_wall_ = -1; - int selected_room_ = -1; + Selection selection_; bool dirty_ = false; bool should_close_ = false; Vector2 last_mouse_{}; @@ -83,15 +112,21 @@ private: int asset_scroll_ = 0; bool dragging_panel_asset_ = false; bool dragging_prop_ = false; - bool drag_undo_pushed_ = false; int dragged_prop_ = -1; bool pending_set_ = false; Vec2 pending_{}; - int next_door_ = 0; std::vector undo_; std::vector redo_; std::unordered_map models_; std::unordered_map model_sizes_; + + bool inspector_ = true; + bool interacting_ = false; + int text_focus_ = -1; + Rectangle text_rect_{}; + char text_buf_[256] = {}; + std::string status_message_; + float status_timer_ = 0.0f; }; } // namespace editor diff --git a/src/editor/main.cpp b/src/editor/main.cpp index 0cf79d4..f2975ce 100644 --- a/src/editor/main.cpp +++ b/src/editor/main.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include "editor/editor_app.hpp" @@ -7,6 +8,7 @@ int main(int argc, char** argv) { std::string path = "assets/levels/floor01.json"; + std::string game_path; std::string screenshot; std::string place_asset; float place_x = 0.0f; @@ -14,6 +16,8 @@ int main(int argc, char** argv) { for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--level") == 0 && i + 1 < argc) { path = argv[++i]; + } else if (std::strcmp(argv[i], "--game") == 0 && i + 1 < argc) { + game_path = argv[++i]; } else if (std::strcmp(argv[i], "--screenshot") == 0 && i + 1 < argc) { screenshot = argv[++i]; } else if (std::strcmp(argv[i], "--place") == 0 && i + 3 < argc) { @@ -21,16 +25,28 @@ int main(int argc, char** argv) { place_x = std::stof(argv[++i]); place_y = std::stof(argv[++i]); } else if (std::strcmp(argv[i], "--help") == 0) { - std::printf("usage: editor [--level ]\n"); + std::printf("usage: editor [--level ] [--game ]\n" + " [--screenshot ]\n" + " [--place ]\n"); return 0; } } + if (game_path.empty()) { + for (const char* candidate : {"./cntrl", "./build/cntrl", "../cntrl"}) { + if (std::filesystem::exists(candidate)) { + game_path = candidate; + break; + } + } + if (game_path.empty()) game_path = "./build/cntrl"; + } SetTraceLogLevel(LOG_WARNING); InitWindow(1400, 900, "FBC: NIGHT SHIFT - Level Editor"); SetTargetFPS(60); editor::App app(path); + app.set_game_path(game_path); app.init(); if (!place_asset.empty()) app.debug_place(place_asset, {place_x, place_y}); int frames = 0; diff --git a/src/game/game.cpp b/src/game/game.cpp index 534699a..a44f7f3 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -105,7 +105,8 @@ void apply_offer(Game& g, const Offer& o) { } // namespace -Game::Game(std::uint64_t seed) : rng(seed), seed_(seed) { +Game::Game(std::uint64_t seed, const std::string& level_path) + : floor(level_path), rng(seed), seed_(seed) { weapon_system.reset(); ritual_system.init(floor); player.pos = floor.spawn(); diff --git a/src/game/game.hpp b/src/game/game.hpp index 5007305..83196ec 100644 --- a/src/game/game.hpp +++ b/src/game/game.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include "core/events.hpp" @@ -38,7 +39,8 @@ struct GameConfig { // main fills InputState, the presenter reads the world and drains `events`. class Game { public: - explicit Game(std::uint64_t seed); + explicit Game(std::uint64_t seed, + const std::string& level_path = Floor::kDefaultPath); void update(const InputState& in, float dt); void reset(); diff --git a/src/level/level_data.cpp b/src/level/level_data.cpp index 34c29ae..978b730 100644 --- a/src/level/level_data.cpp +++ b/src/level/level_data.cpp @@ -332,6 +332,10 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { if (!read_float_field(root, "map_width", l.map_width, error)) return false; if (!read_float_field(root, "map_height", l.map_height, error)) return false; if (!read_float_field(root, "scale", l.scale, error)) return false; + if (!(l.map_width > 0.0f) || !(l.map_height > 0.0f)) { + error = "map dimensions must be positive"; + return false; + } if (!(l.scale > 0.0f)) { error = "scale must be positive"; return false; @@ -344,6 +348,10 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { Room r; if (!read_string_field(item, "name", r.name, error)) return false; if (!read_rect_field(item, "rect", r.rect, error)) return false; + if (!(r.rect.x1 > r.rect.x0) || !(r.rect.y1 > r.rect.y0)) { + error = "room " + r.name + " has an invalid rect"; + return false; + } std::string kind; if (!read_string_field(item, "kind", kind, error) || !room_kind_from_name(kind, r.kind)) { @@ -361,6 +369,10 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { for (const json::Value& item : corridors->array) { Rect r; if (!read_rect(item, r, error)) return false; + if (!(r.x1 > r.x0) || !(r.y1 > r.y0)) { + error = "corridor has an invalid rect"; + return false; + } l.corridors.push_back(r); } @@ -380,6 +392,24 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { if (!read_float_field(item, "height", w.height, error)) return false; const json::Value* gaps = field(item, "gaps", error); if (gaps == nullptr || !read_spans(*gaps, w.gaps, error)) return false; + if (!(w.to > w.from)) { + error = "wall " + std::to_string(l.walls.size()) + " has from >= to"; + return false; + } + if (!(w.height > 0.0f)) { + error = "wall " + std::to_string(l.walls.size()) + " has non-positive height"; + return false; + } + float gap_end = w.from; + for (const Span& gap : w.gaps) { + if (!(gap.second > gap.first) || gap.first < w.from || gap.second > w.to + || gap.first < gap_end - 1e-4f) { + error = "wall " + std::to_string(l.walls.size()) + + " has an invalid or unordered gap"; + return false; + } + gap_end = gap.second; + } l.walls.push_back(std::move(w)); } @@ -396,6 +426,14 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { } if (!read_rect_field(item, "rect", d.rect, error)) return false; if (!read_float_field(item, "height", d.height, error)) return false; + if (!(d.rect.x1 > d.rect.x0) || !(d.rect.y1 > d.rect.y0)) { + error = "door " + id + " has an invalid rect"; + return false; + } + if (!(d.height > 0.0f)) { + error = "door " + id + " has non-positive height"; + return false; + } l.doors.push_back(d); } @@ -450,6 +488,15 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { } p.destructible = destructible->boolean; } + const std::string prop_label = "prop " + std::to_string(l.props.size()); + if (!(p.w > 0.0f) || !(p.d > 0.0f) || !(p.h > 0.0f)) { + error = prop_label + " has non-positive size"; + return false; + } + if (!(p.scale > 0.0f)) { + error = prop_label + " has non-positive scale"; + return false; + } l.props.push_back(p); } @@ -469,6 +516,16 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { return false; if (!read_float_field(item, "light_duration", r.light_duration, error)) return false; + const std::string ritual_label = "ritual " + std::to_string(l.rituals.size()); + if (!(r.radius > 0.0f) || !(r.duration > 0.0f)) { + error = ritual_label + " has non-positive radius or duration"; + return false; + } + if (r.ring_radius < 0.0f || r.ring_count < 0 || r.light_radius < 0.0f + || !(r.light_damage_mult > 0.0f) || r.light_duration < 0.0f) { + error = ritual_label + " has invalid parameters"; + return false; + } l.rituals.push_back(r); } @@ -480,6 +537,10 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { if (!read_vec2_field(item, "pos", t.pos, error)) return false; if (!read_float_field(item, "span", t.span, error)) return false; if (!read_float_field(item, "yaw", t.yaw, error)) return false; + if (!(t.span > 0.0f)) { + error = "thermo door " + std::to_string(l.thermo.size()) + " has non-positive span"; + return false; + } l.thermo.push_back(t); } @@ -492,6 +553,10 @@ bool from_json(const json::Value& root, LevelData& l, std::string& error) { return false; if (!read_float_field(*anchors, "exit_radius", l.anchors.exit_radius, error)) return false; + if (l.anchors.key_radius < 0.0f || l.anchors.exit_radius < 0.0f) { + error = "anchor radii must be non-negative"; + return false; + } return true; } @@ -539,48 +604,122 @@ Rect to_world_rect(const LevelData& l, Rect r) { return {a.x, a.y, b.x, b.y}; } -std::vector build_world_walls(const LevelData& l) { - std::vector out; - constexpr float kHalfThickness = 0.35f; +namespace { - for (const WallLine& w : l.walls) { - float cur = w.from; - auto emit = [&](float a, float b) { - if (w.axis == 0) { - const Vec2 p = to_world(l, {a, w.coord}); - const Vec2 q = to_world(l, {b, w.coord}); - out.push_back({{std::min(p.x, q.x), p.y - kHalfThickness, - std::max(p.x, q.x), p.y + kHalfThickness}, - w.height}); - } else { - const Vec2 p = to_world(l, {w.coord, a}); - const Vec2 q = to_world(l, {w.coord, b}); - out.push_back({{p.x - kHalfThickness, std::min(p.y, q.y), - p.x + kHalfThickness, std::max(p.y, q.y)}, - w.height}); - } - }; - for (const Span& gap : w.gaps) { - if (gap.first > cur) emit(cur, std::min(gap.first, w.to)); - cur = std::max(cur, gap.second); +constexpr float kEpsilon = 1e-4f; + +std::vector visible_segments(float from, float to, const std::vector& gaps) { + std::vector out; + float cur = from; + for (const Span& gap : gaps) { + if (gap.first > cur + kEpsilon) out.push_back({cur, std::min(gap.first, to)}); + cur = std::max(cur, gap.second); + } + if (cur < to - kEpsilon) out.push_back({cur, to}); + return out; +} + +} // namespace + +std::vector normalize_gaps(float from, float to, const std::vector& gaps) { + std::vector spans; + for (Span s : gaps) { + s.first = std::max(s.first, from); + s.second = std::min(s.second, to); + if (s.second - s.first <= kEpsilon) continue; + spans.push_back(s); + } + std::sort(spans.begin(), spans.end(), [](const Span& a, const Span& b) { + return a.first < b.first || (a.first == b.first && a.second < b.second); + }); + std::vector out; + for (const Span& s : spans) { + if (!out.empty() && s.first <= out.back().second + kEpsilon) { + out.back().second = std::max(out.back().second, s.second); + } else { + out.push_back(s); } - if (cur < w.to) emit(cur, w.to); - } - - for (const Door& d : l.doors) { - const int id = static_cast(d.id); - if (id < 0 || id >= static_cast(DoorId::Count)) continue; - const Rect r = to_world_rect(l, d.rect); - out.push_back({r, d.height, id}); - } - - for (const Prop& p : l.props) { - if (!p.solid) continue; - const Vec2 c = to_world(l, p.pos); - out.push_back({{c.x - p.w * 0.5f, c.y - p.d * 0.5f, - c.x + p.w * 0.5f, c.y + p.d * 0.5f}, p.h}); } return out; } +bool remove_wall_segment(LevelData& l, std::size_t line, std::size_t segment) { + if (line >= l.walls.size()) return false; + const WallLine& w = l.walls[line]; + const auto segments = visible_segments(w.from, w.to, w.gaps); + if (segment >= segments.size()) return false; + auto gaps = w.gaps; + gaps.push_back(segments[segment]); + l.walls[line].gaps = normalize_gaps(w.from, w.to, gaps); + return true; +} + +bool restore_wall_gap(LevelData& l, std::size_t line, std::size_t gap) { + if (line >= l.walls.size() || gap >= l.walls[line].gaps.size()) return false; + l.walls[line].gaps.erase(l.walls[line].gaps.begin() + static_cast(gap)); + return true; +} + +int allocate_door_id(const LevelData& l) { + bool used[static_cast(DoorId::Count)] = {}; + for (const Door& d : l.doors) { + const int id = static_cast(d.id); + if (id >= 0 && id < static_cast(DoorId::Count)) used[id] = true; + } + for (int i = 0; i < static_cast(DoorId::Count); ++i) { + if (!used[i]) return i; + } + return -1; +} + +std::vector build_indexed_walls(const LevelData& l) { + std::vector out; + constexpr float kHalfThickness = 0.35f; + + for (std::size_t li = 0; li < l.walls.size(); ++li) { + const WallLine& w = l.walls[li]; + const auto segments = visible_segments(w.from, w.to, w.gaps); + for (std::size_t si = 0; si < segments.size(); ++si) { + const Span s = segments[si]; + WorldWall wall; + if (w.axis == 0) { + const Vec2 p = to_world(l, {s.first, w.coord}); + const Vec2 q = to_world(l, {s.second, w.coord}); + wall = {{std::min(p.x, q.x), p.y - kHalfThickness, + std::max(p.x, q.x), p.y + kHalfThickness}, w.height}; + } else { + const Vec2 p = to_world(l, {w.coord, s.first}); + const Vec2 q = to_world(l, {w.coord, s.second}); + wall = {{p.x - kHalfThickness, std::min(p.y, q.y), + p.x + kHalfThickness, std::max(p.y, q.y)}, w.height}; + } + out.push_back({wall, WallSource::Line, li, si}); + } + } + + for (std::size_t di = 0; di < l.doors.size(); ++di) { + const Door& d = l.doors[di]; + const int id = static_cast(d.id); + if (id < 0 || id >= static_cast(DoorId::Count)) continue; + const Rect r = to_world_rect(l, d.rect); + out.push_back({{r, d.height, id}, WallSource::Door, di, kNoIndex}); + } + + for (std::size_t pi = 0; pi < l.props.size(); ++pi) { + const Prop& p = l.props[pi]; + if (!p.solid) continue; + const Vec2 c = to_world(l, p.pos); + WorldWall wall = {{c.x - p.w * 0.5f, c.y - p.d * 0.5f, + c.x + p.w * 0.5f, c.y + p.d * 0.5f}, p.h}; + out.push_back({wall, WallSource::Prop, pi, kNoIndex}); + } + return out; +} + +std::vector build_world_walls(const LevelData& l) { + std::vector out; + for (const IndexedWall& wall : build_indexed_walls(l)) out.push_back(wall.wall); + return out; +} + } // namespace level diff --git a/src/level/level_data.hpp b/src/level/level_data.hpp index 581b6da..8d6ddd8 100644 --- a/src/level/level_data.hpp +++ b/src/level/level_data.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -105,6 +106,20 @@ struct WorldWall { int door = -1; }; +constexpr std::size_t kNoIndex = static_cast(-1); + +enum class WallSource { Line, Door, Prop }; + +// A world-space wall plus the authored entity it came from. `line` indexes +// LevelData::walls; `segment` indexes the visible segments of that line after +// gaps are applied. Doors and solid props use their own index in `line`. +struct IndexedWall { + WorldWall wall; + WallSource source = WallSource::Line; + std::size_t line = kNoIndex; + std::size_t segment = kNoIndex; +}; + struct LevelData { int version = 1; std::string name; @@ -140,6 +155,14 @@ bool save(const std::string& path, const LevelData& level); Vec2 to_world(const LevelData& level, Vec2 p); Vec2 to_map(const LevelData& level, Vec2 p); Rect to_world_rect(const LevelData& level, Rect r); +std::vector build_indexed_walls(const LevelData& level); std::vector build_world_walls(const LevelData& level); +// Gap editing helpers. `normalize_gaps` clamps spans to [from, to], drops +// inverted spans and merges overlaps/adjacent spans in place. +std::vector normalize_gaps(float from, float to, const std::vector& gaps); +bool remove_wall_segment(LevelData& level, std::size_t line, std::size_t segment); +bool restore_wall_gap(LevelData& level, std::size_t line, std::size_t gap); +int allocate_door_id(const LevelData& level); + } // namespace level diff --git a/src/level/level_tool.cpp b/src/level/level_tool.cpp index cbebdd0..021f4d7 100644 --- a/src/level/level_tool.cpp +++ b/src/level/level_tool.cpp @@ -31,6 +31,12 @@ int main(int argc, char** argv) { std::cerr << error << '\n'; return 1; } + const auto validation = level::validate(data); + for (const auto& e : validation.errors) std::cerr << "ERROR: " << e << '\n'; + if (!validation.ok()) { + 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'; @@ -86,12 +92,14 @@ int main(int argc, char** argv) { return 1; } const bool stable = once == level::serialize(again); + const auto validation = level::validate(data); + for (const auto& e : validation.errors) std::cerr << "ERROR: " << e << '\n'; std::cout << path << ": " << data.rooms.size() << " rooms, " << data.walls.size() << " wall lines, " << data.doors.size() << " doors, " << data.props.size() << " props, " << data.rituals.size() << " rituals, roundtrip " << (stable ? "stable" : "UNSTABLE") << '\n'; - return stable ? 0 : 1; + return stable && validation.ok() ? 0 : 1; } return usage(); diff --git a/src/level/validation.cpp b/src/level/validation.cpp index 3a972a0..2e4f8e9 100644 --- a/src/level/validation.cpp +++ b/src/level/validation.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include @@ -14,9 +13,9 @@ namespace { constexpr float kPlayerRadius = 0.45f; -bool blocked(const std::vector& walls, Vec2 p) { +bool blocked(const std::vector& walls, Vec2 p, bool doors_open) { for (const WorldWall& w : walls) { - if (w.door >= 0) continue; + if (w.door >= 0 && doors_open) continue; const Rect& r = w.rect; if (p.x > r.x0 - kPlayerRadius && p.x < r.x1 + kPlayerRadius && p.y > r.y0 - kPlayerRadius && p.y < r.y1 + kPlayerRadius) { @@ -45,6 +44,15 @@ ValidationResult validate(const LevelData& level) { door_ids.insert(id); } + std::set ritual_types; + for (const Ritual& r : level.rituals) { + if (r.type.empty()) { + result.errors.push_back("ritual with empty type"); + } else if (!ritual_types.insert(r.type).second) { + result.errors.push_back("duplicate ritual type: " + r.type); + } + } + for (size_t i = 0; i < level.rooms.size(); ++i) { for (size_t j = i + 1; j < level.rooms.size(); ++j) { const Rect& a = level.rooms[i].rect; @@ -72,6 +80,21 @@ ValidationResult validate(const LevelData& level) { } for (const auto& message : missing_models) result.warnings.push_back(message); + const auto inside_map = [&](Vec2 p) { + return p.x >= 0.0f && p.y >= 0.0f + && p.x <= level.map_width && p.y <= level.map_height; + }; + struct NamedAnchor { const char* name; Vec2 pos; }; + for (const NamedAnchor& a : {NamedAnchor{"spawn", level.anchors.spawn}, + NamedAnchor{"threshold key", level.anchors.key}, + NamedAnchor{"threshold exit", level.anchors.exit}}) { + if (!inside_map(a.pos)) { + result.errors.push_back(std::string(a.name) + " outside the map"); + } else if (blocked(walls, to_world(level, a.pos), true)) { + result.errors.push_back(std::string(a.name) + " is inside a wall"); + } + } + const int width = static_cast(level.map_width); const int height = static_cast(level.map_height); if (width <= 0 || height <= 0) { @@ -82,20 +105,21 @@ ValidationResult validate(const LevelData& level) { const auto index = [width](int x, int y) { return static_cast(y) * static_cast(width) + static_cast(x); }; - auto walkable = [&](int x, int y) { + auto walkable = [&](int x, int y, bool doors_open) { if (x < 0 || y < 0 || x >= width || y >= height) return false; const Vec2 world = to_world(level, {x + 0.5f, y + 0.5f}); - return !blocked(walls, world); + return !blocked(walls, world, doors_open); }; - const auto nearest_walkable = [&](Vec2 map_pos, int& out_x, int& out_y) { + const auto nearest_walkable = [&](Vec2 map_pos, int& out_x, int& out_y, + bool doors_open) { const int cx = static_cast(map_pos.x); const int cy = static_cast(map_pos.y); for (int radius = 0; radius <= 6; ++radius) { for (int dy = -radius; dy <= radius; ++dy) { for (int dx = -radius; dx <= radius; ++dx) { if (std::max(std::abs(dx), std::abs(dy)) != radius) continue; - if (walkable(cx + dx, cy + dy)) { + if (walkable(cx + dx, cy + dy, doors_open)) { out_x = cx + dx; out_y = cy + dy; return true; @@ -106,42 +130,48 @@ ValidationResult validate(const LevelData& level) { return false; }; - int sx = 0; - int sy = 0; - if (!nearest_walkable(level.anchors.spawn, sx, sy)) { - result.errors.push_back("spawn is not walkable"); - return result; - } - int next_component = 0; - std::queue> queue; - queue.push({sx, sy}); - component[index(sx, sy)] = next_component; - while (!queue.empty()) { - const auto [x, y] = queue.front(); - queue.pop(); - for (const auto [dx, dy] : {std::pair{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) { - const int nx = x + dx; - const int ny = y + dy; - if (!walkable(nx, ny)) continue; - if (component[index(nx, ny)] >= 0) continue; - component[index(nx, ny)] = next_component; - queue.push({nx, ny}); + const auto flood_fill = [&](std::vector& out, int sx, int sy, + bool doors_open) { + std::fill(out.begin(), out.end(), -1); + std::queue> queue; + queue.push({sx, sy}); + out[index(sx, sy)] = 0; + while (!queue.empty()) { + const auto [x, y] = queue.front(); + queue.pop(); + for (const auto [dx, dy] : {std::pair{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) { + const int nx = x + dx; + const int ny = y + dy; + if (!walkable(nx, ny, doors_open)) continue; + if (out[index(nx, ny)] >= 0) continue; + out[index(nx, ny)] = 0; + queue.push({nx, ny}); + } } - } - ++next_component; + }; const auto reachable = [&](Vec2 p, const std::string& what) { int x = 0; int y = 0; - if (!nearest_walkable(p, x, y)) { + if (!nearest_walkable(p, x, y, true)) { result.errors.push_back(what + " has no walkable cell"); - return; + return false; } if (component[index(x, y)] != 0) { result.errors.push_back(what + " unreachable from spawn"); + return false; } + return true; }; + int sx = 0; + int sy = 0; + if (!nearest_walkable(level.anchors.spawn, sx, sy, true)) { + result.errors.push_back("spawn is not walkable"); + return result; + } + flood_fill(component, sx, sy, true); + for (const Room& r : level.rooms) { reachable({(r.rect.x0 + r.rect.x1) * 0.5f, (r.rect.y0 + r.rect.y1) * 0.5f}, "room " + r.name); @@ -149,10 +179,38 @@ ValidationResult validate(const LevelData& level) { reachable(level.anchors.key, "threshold key"); reachable(level.anchors.exit, "threshold exit"); + int closed_sx = 0; + int closed_sy = 0; + bool closed_spawn = nearest_walkable(level.anchors.spawn, closed_sx, closed_sy, false); + if (closed_spawn) { + std::vector closed(component.size(), -1); + flood_fill(closed, closed_sx, closed_sy, false); + + const auto closed_reachable = [&](Vec2 p) { + int x = 0; + int y = 0; + return nearest_walkable(p, x, y, false) && closed[index(x, y)] == 0; + }; + for (const Room& r : level.rooms) { + if (!closed_reachable({(r.rect.x0 + r.rect.x1) * 0.5f, + (r.rect.y0 + r.rect.y1) * 0.5f}) + && (r.kind != RoomKind::Side || r.side_index < 0)) { + result.errors.push_back("room " + r.name + + " is only reachable through a gated door"); + } + } + if (!closed_reachable(level.anchors.key)) { + result.warnings.push_back("threshold key is behind a gated door"); + } + if (!closed_reachable(level.anchors.exit)) { + result.warnings.push_back("threshold exit is behind a gated door"); + } + } + size_t outside = 0; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { - if (walkable(x, y) && component[index(x, y)] != 0) ++outside; + if (walkable(x, y, true) && component[index(x, y)] != 0) ++outside; } } if (outside > 0) { diff --git a/src/main.cpp b/src/main.cpp index 308c671..d310102 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -53,12 +53,15 @@ struct Options { float fov = 0.0f; // --fov : initial camera FOV float cam_height = 0.0f; // --cam-height : initial camera height float cam_forward = 0.0f; // --cam-forward : initial forward offset + const char* level_path = nullptr; // --level : authoring JSON to load }; Options parse_options(int argc, char** argv) { Options opts; for (int i = 1; i < argc; ++i) { - if (std::strcmp(argv[i], "--seed") == 0 && i + 1 < argc) { + if (std::strcmp(argv[i], "--level") == 0 && i + 1 < argc) { + opts.level_path = argv[++i]; + } else if (std::strcmp(argv[i], "--seed") == 0 && i + 1 < argc) { opts.seed = std::strtoull(argv[i + 1], nullptr, 10); } else if (std::strcmp(argv[i], "--screenshot") == 0 && i + 1 < argc) { opts.screenshot_path = argv[i + 1]; @@ -229,7 +232,8 @@ int main(int argc, char** argv) { ui_font::init(); ui_font::init_gui_style(); clay_ui::init(); - Game game(opts.seed); + Game game(opts.seed, opts.level_path != nullptr ? opts.level_path + : Floor::kDefaultPath); game.state = (opts.bot || opts.hiss_test || opts.room_test || opts.aoe_test || opts.floor_overview || opts.plaza_test || opts.office_test) ? GameState::Playing : GameState::Title; diff --git a/tests/data/bad_gap.json b/tests/data/bad_gap.json new file mode 100644 index 0000000..1a9908b --- /dev/null +++ b/tests/data/bad_gap.json @@ -0,0 +1,28 @@ +{ + "version": 1, + "name": "INVALID GAP FIXTURE", + "map_width": 160, + "map_height": 120, + "scale": 1.5, + "rooms": [ + {"name": "TEST ROOM", "rect": [0, 0, 160, 120], "kind": "Gate", "flow": 1, "side_index": -1} + ], + "corridors": [], + "walls": [ + {"axis": 0, "coord": 0, "from": 0, "to": 160, "height": 4.2, "gaps": [[50, 40]]}, + {"axis": 0, "coord": 120, "from": 0, "to": 160, "height": 4.2, "gaps": []}, + {"axis": 1, "coord": 0, "from": 0, "to": 120, "height": 4.2, "gaps": []}, + {"axis": 1, "coord": 160, "from": 0, "to": 120, "height": 4.2, "gaps": []} + ], + "doors": [], + "props": [], + "rituals": [], + "thermo": [], + "anchors": { + "spawn": [60, 50], + "key": [80, 60], + "exit": [100, 70], + "key_radius": 3, + "exit_radius": 4 + } +} diff --git a/tests/data/valid.json b/tests/data/valid.json new file mode 100644 index 0000000..4dd565d --- /dev/null +++ b/tests/data/valid.json @@ -0,0 +1,28 @@ +{ + "version": 1, + "name": "VALIDATION FIXTURE", + "map_width": 160, + "map_height": 120, + "scale": 1.5, + "rooms": [ + {"name": "TEST ROOM", "rect": [0, 0, 160, 120], "kind": "Gate", "flow": 1, "side_index": -1} + ], + "corridors": [], + "walls": [ + {"axis": 0, "coord": 0, "from": 0, "to": 160, "height": 4.2, "gaps": []}, + {"axis": 0, "coord": 120, "from": 0, "to": 160, "height": 4.2, "gaps": []}, + {"axis": 1, "coord": 0, "from": 0, "to": 120, "height": 4.2, "gaps": []}, + {"axis": 1, "coord": 160, "from": 0, "to": 120, "height": 4.2, "gaps": []} + ], + "doors": [], + "props": [], + "rituals": [], + "thermo": [], + "anchors": { + "spawn": [60, 50], + "key": [80, 60], + "exit": [100, 70], + "key_radius": 3, + "exit_radius": 4 + } +} diff --git a/tests/level_core_test.cpp b/tests/level_core_test.cpp index e858248..28b91be 100644 --- a/tests/level_core_test.cpp +++ b/tests/level_core_test.cpp @@ -90,6 +90,74 @@ int main() { broken.rooms.push_back({"ISLAND", {300, 300, 310, 310}, RoomKind::Side, 0, 0}); check(!level::validate(broken).ok(), "unreachable room is reported"); + level::LevelData dup_door = original; + dup_door.doors.push_back(dup_door.doors.front()); + check(!level::validate(dup_door).ok(), "duplicate door id is reported"); + level::LevelData dup_ritual = original; + dup_ritual.rituals.push_back(dup_ritual.rituals.front()); + check(!level::validate(dup_ritual).ok(), "duplicate ritual type is reported"); + level::LevelData moved_spawn = original; + moved_spawn.anchors.spawn = {999.0f, 999.0f}; + check(!level::validate(moved_spawn).ok(), "out-of-map anchor is reported"); + + const auto gaps = level::normalize_gaps( + 0.0f, 100.0f, {{80.0f, 120.0f}, {20.0f, 40.0f}, + {30.0f, 50.0f}, {-10.0f, 5.0f}}); + check(gaps.size() == 3, "gaps clamp, sort and merge"); + if (gaps.size() == 3) { + check(near(gaps[0].first, 0.0f) && near(gaps[0].second, 5.0f), "gap 0 clamped"); + check(near(gaps[1].first, 20.0f) && near(gaps[1].second, 50.0f), "gap 1 merged"); + check(near(gaps[2].first, 80.0f) && near(gaps[2].second, 100.0f), "gap 2 clamped"); + } + check(level::remove_wall_segment(single, 0, 0), "remove first wall segment"); + check(level::build_world_walls(single).size() == 1, "segment became a gap"); + check(level::restore_wall_gap(single, 0, 0), "restore wall gap"); + const auto restored = level::build_world_walls(single); + check(restored.size() == 1 && near(restored.front().rect.x1 + - restored.front().rect.x0, 150.0f), + "gap merged back into a full wall segment"); + check(!level::remove_wall_segment(single, 0, 99), "bad segment index rejected"); + + check(level::allocate_door_id(single) == 0, "first door id is free in empty level"); + check(level::allocate_door_id(original) == -1, "all door ids taken in Floor 01"); + level::LevelData one_door; + one_door.doors.push_back({DoorId::Booth, {0, 0, 1, 1}, 3.2f}); + check(level::allocate_door_id(one_door) == 0, "Janitor allocated before Booth"); + + const auto indexed = level::build_indexed_walls(original); + check(indexed.size() == level::build_world_walls(original).size(), + "indexed walls cover every world wall"); + bool saw_line = false; + bool saw_door = false; + bool saw_prop = false; + for (const auto& wall : indexed) { + if (wall.source == level::WallSource::Line) { + saw_line = true; + check(wall.line < original.walls.size(), "line index in range"); + check(wall.segment != level::kNoIndex, "segment index present"); + } else if (wall.source == level::WallSource::Door) { + saw_door = true; + check(wall.line < original.doors.size(), "door index in range"); + } else { + saw_prop = true; + check(wall.line < original.props.size(), "prop index in range"); + } + } + check(saw_line && saw_door && saw_prop, "all wall sources represented"); + + for (const Vec2 p : {Vec2{0.0f, 0.0f}, Vec2{80.0f, 13.0f}, Vec2{159.0f, 119.0f}}) { + const Vec2 round = level::to_map(original, level::to_world(original, p)); + check(near(round.x, p.x) && near(round.y, p.y), "map/world round trip"); + } + + level::LevelData rejected; + check(!level::parse("{", rejected, error), "malformed JSON rejected"); + check(!level::parse("{}", rejected, error), "missing fields rejected"); + check(!level::parse("{\"version\":2}", rejected, error), "wrong version rejected"); + check(!level::parse("{\"version\":1,\"name\":\"x\",\"map_width\":0," + "\"map_height\":1,\"scale\":1}", rejected, error), + "invalid dimensions rejected"); + if (failures == 0) std::printf("level_core_test: all checks passed\n"); return failures == 0 ? 0 : 1; } diff --git a/tools/blender/build_agent.py b/tools/blender/build_agent.py index 4b9b5fa..b812532 100644 --- a/tools/blender/build_agent.py +++ b/tools/blender/build_agent.py @@ -16,7 +16,7 @@ import re import sys import bpy -from mathutils import Euler, Vector +from mathutils import Euler, Matrix, Vector REPO = "/home/dandovlatov/Documents/cntrl" MODEL_DIR = os.path.join(REPO, "assets", "models") @@ -31,6 +31,10 @@ import actor_kit as K importlib.reload(K) K.clear_scene() +# Re-running in a live session must not leave stale fake-user actions in the +# saved .blend or the GLB's animation list. +for old_action in list(bpy.data.actions): + bpy.data.actions.remove(old_action) P = K.PALETTE P.update({ "coverall": "#6f7f6d", "coverall_dk": "#566452", "coverall_sh": "#414c3e", @@ -259,12 +263,12 @@ def build_agent(): 1.25, 1.27, 1.0, P["steel_dk"], ao=0.0) K.plate(r, "rifle_stock", rect(0.04, 0.27, -0.14, 0.06), 1.12, 1.23, 0.94, P["leather"], ao=0.06) - K.plate(r, "rifle_grip", rect(0.10, 0.21, -0.29, -0.17), - 0.92, 1.12, 0.86, P["black"], ao=0.06) + grip_rear = K.plate(r, "rifle_grip", rect(0.10, 0.21, -0.29, -0.17), + 0.92, 1.12, 0.86, P["black"], ao=0.06) K.plate(r, "rifle_magazine", rect(0.09, 0.22, -0.52, -0.32), 0.84, 1.10, 0.92, P["steel_dk"], ao=0.06) - K.plate(r, "rifle_foregrip", rect(0.09, 0.21, -0.76, -0.62), - 0.97, 1.12, 0.9, P["black"], ao=0.06) + grip_front = K.plate(r, "rifle_foregrip", rect(0.09, 0.21, -0.76, -0.62), + 0.97, 1.12, 0.9, P["black"], ao=0.06) K.plate(r, "rifle_barrel", rect(0.12, 0.20, -0.98, -0.62), 1.15, 1.20, 1.0, P["steel_dk"], ao=0.0) K.plate(r, "rifle_brake", rect(0.11, 0.21, -1.06, -0.98), @@ -289,7 +293,21 @@ def build_agent(): if obj.type == "MESH" and obj.name.lower().startswith("rifle"): for v in obj.data.vertices: v.co = pivot + turn @ (v.co - pivot) + # The original carry buried the stock in the chest. Nudge the + # weapon forward toward the vest face so the grip is reachable, + # then move the weapon bone with it. + v.co.y -= 0.08 obj.data.update() + # Sample the real grip surfaces after the rifle has been turned. The rig + # uses these points as IK targets, so the hands never drift off the gun. + for side, obj in (("R", grip_rear), ("L", grip_front)): + vs = obj.data.vertices + GRIP_REST[side] = Vector(( + sum(v.co.x for v in vs) / len(vs), + sum(v.co.y for v in vs) / len(vs), + sum(v.co.z for v in vs) / len(vs), + )) + print("[grip] %s %.3f %.3f %.3f" % (side, *GRIP_REST[side])) for i, (x, y, z, tilt) in enumerate([ (0.12, 0.22, 1.40, (0.3, 0.2, 0.4)), (-0.10, 0.23, 1.24, (-0.4, 0.1, -0.3)), @@ -304,6 +322,11 @@ def build_agent(): return r +# Rest-space centres of the rifle's rear grip and foregrip, filled in by +# build_agent() once the rifle has been angled across the chest. +GRIP_REST = {} + + # ------------------------------------------------------------------- rigging BONES = [ ("root", (0, 0, 0.0), (0, 0, 0.20), None), @@ -312,16 +335,19 @@ BONES = [ ("chest", (0, 0, 1.26), (0, 0, 1.48), "spine"), ("neck", (0, 0, 1.50), (0, 0, 1.62), "chest"), ("head", (0, 0, 1.62), (0, 0, 1.98), "neck"), - ("weapon", (0.15, -0.25, 1.17), (-0.20, -0.75, 1.17), "chest"), + ("weapon", (0.15, -0.33, 1.17), (-0.20, -0.83, 1.17), "chest"), ] for SIDE, SIGN in (("L", -1), ("R", 1)): BONES += [ - ("upperarm." + SIDE, (SIGN * 0.43, 0, 1.46), - (SIGN * 0.50, -0.04, 1.09), "chest"), - ("forearm." + SIDE, (SIGN * 0.50, -0.04, 1.09), - (SIGN * 0.54, -0.08, 0.78), "upperarm." + SIDE), - ("hand." + SIDE, (SIGN * 0.54, -0.08, 0.78), - (SIGN * 0.54, -0.20, 0.62), "forearm." + SIDE), + # Joints follow the authored arm meshes (sleeve -> elbow -> wrist -> + # fingers). The old bones hung at the hips while the mesh held the + # rifle, so arm rotations swung the hands away from the gun. + ("upperarm." + SIDE, (SIGN * 0.41, -0.02, 1.46), + (SIGN * 0.43, -0.20, 1.14), "chest"), + ("forearm." + SIDE, (SIGN * 0.43, -0.22, 1.14), + (SIGN * 0.31, -0.60, 1.17), "upperarm." + SIDE), + ("hand." + SIDE, (SIGN * 0.31, -0.60, 1.17), + (SIGN * 0.27, -0.84, 1.14), "forearm." + SIDE), ("thigh." + SIDE, (SIGN * 0.17, 0, 0.88), (SIGN * 0.18, 0, 0.51), "hips"), ("shin." + SIDE, (SIGN * 0.18, 0, 0.51), @@ -421,12 +447,79 @@ def reset_pose(bones): pb.location = (0.0, 0.0, 0.0) +# Every clip finishes with the same two-bone IK pass. The targets come from +# the rifle's own grip surfaces (GRIP_REST), skinned by the current weapon +# pose, so neither hand can drift off the gun when the chest leans or recoils. +RECOIL_SCALE = 0.85 # 15% softer than the original firing kick + + +def aim_bone(pb, parent_pose, head, tail): + direction = (tail - head).normalized() + up = Vector((0.0, 0.0, 1.0)) + if abs(direction.dot(up)) > 0.95: + up = Vector((0.0, 1.0, 0.0)) + right = direction.cross(up).normalized() + up2 = right.cross(direction).normalized() + desired = Matrix((right, direction, up2)).transposed().to_4x4() + desired.translation = head + rest_parent = pb.parent.bone.matrix_local if pb.parent else Matrix.Identity(4) + basis = parent_pose @ rest_parent.inverted() @ pb.bone.matrix_local + pb.matrix_basis = basis.inverted() @ desired + return desired + + +def solve_arm(pb, side, target, pole, parent_pose, hand_dir): + upper = pb["upperarm." + side] + lower = pb["forearm." + side] + hand = pb["hand." + side] + shoulder = upper.head.copy() + l1 = (upper.bone.tail_local - upper.bone.head_local).length + l2 = (lower.bone.tail_local - lower.bone.head_local).length + delta = target - shoulder + reach = max(abs(l1 - l2) + 1e-3, min(delta.length, l1 + l2 - 1e-3)) + direction = delta.normalized() + along = (l1 * l1 - l2 * l2 + reach * reach) / (2.0 * reach) + height = math.sqrt(max(0.0, l1 * l1 - along * along)) + bend = pole - direction * pole.dot(direction) + if bend.length < 1e-5: + bend = Vector((1.0 if side == "R" else -1.0, 0.0, 0.0)) + bend -= direction * bend.dot(direction) + bend.normalize() + elbow = shoulder + direction * along + bend * height + upper_pose = aim_bone(upper, parent_pose, shoulder, elbow) + lower_pose = aim_bone(lower, upper_pose, elbow, target) + # Fingers follow the barrel instead of hanging off the wrist. + aim_bone(hand, lower_pose, target, target + hand_dir) + + +def grip_weapon(pb, recoil=0.0): + """Pin both wrists to the rifle; optional pitch is the firing recoil.""" + bpy.context.view_layer.update() + weapon = pb["weapon"] + if recoil: + pivot = pb["chest"].head.copy() + around_chest = (Matrix.Translation(pivot) + @ Matrix.Rotation(-0.22 * recoil, 4, "X") + @ Matrix.Translation(-pivot)) + weapon.matrix = around_chest @ weapon.matrix.copy() + bpy.context.view_layer.update() + + # Skin the sampled grip centres by the weapon's current pose. + skin = weapon.matrix @ weapon.bone.matrix_local.inverted() + forward = (weapon.tail - weapon.head).normalized() + hand_dir = (forward - Vector((0.0, 0.0, 0.55))).normalized() + chest_pose = pb["chest"].matrix.copy() + for side, behind in (("R", 0.05), ("L", 0.07)): + target = skin @ GRIP_REST[side] - forward * behind + pole = Vector((0.5 if side == "R" else -0.5, 0.1, -1.0)) + solve_arm(pb, side, target, pole, chest_pose, hand_dir) + + def pose_idle(pb, t): breath = math.sin(t * 2.0 * math.pi) pb["chest"].rotation_euler.x = 0.015 + 0.018 * breath pb["head"].rotation_euler.z = 0.025 * math.sin(t * math.pi) - pb["upperarm.L"].rotation_euler.x = -0.03 - pb["upperarm.R"].rotation_euler.x = 0.03 + grip_weapon(pb) def pose_run(pb, t): @@ -439,10 +532,7 @@ def pose_run(pb, t): pb["thigh.R"].rotation_euler.x = -0.62 * s pb["shin.L"].rotation_euler.x = 0.55 * max(0.0, -s) pb["shin.R"].rotation_euler.x = 0.55 * max(0.0, s) - pb["upperarm.L"].rotation_euler.x = -0.28 * s - pb["upperarm.R"].rotation_euler.x = 0.18 * s - pb["forearm.L"].rotation_euler.x = 0.35 - pb["forearm.R"].rotation_euler.x = 0.42 + grip_weapon(pb) def pose_dash(pb, t): @@ -452,27 +542,21 @@ def pose_dash(pb, t): pb["thigh.L"].rotation_euler.x = 0.80 pb["thigh.R"].rotation_euler.x = -0.55 pb["shin.L"].rotation_euler.x = 0.30 - pb["upperarm.L"].rotation_euler.x = -0.55 - pb["upperarm.R"].rotation_euler.x = -0.35 - pb["forearm.L"].rotation_euler.x = 0.30 - pb["forearm.R"].rotation_euler.x = 0.30 + grip_weapon(pb) def pose_fire(pb, t): - kick = math.exp(-9.0 * t) - pb["weapon"].rotation_euler.x = -0.22 * kick + kick = math.exp(-9.0 * t) * RECOIL_SCALE pb["chest"].rotation_euler.x = 0.06 * kick - pb["upperarm.R"].rotation_euler.x = 0.16 * kick - pb["forearm.R"].rotation_euler.x = 0.20 * kick pb["head"].rotation_euler.x = -0.05 * kick + grip_weapon(pb, recoil=kick) def pose_stagger(pb, t): fade = 1.0 - t pb["chest"].rotation_euler.x = -0.30 * fade pb["head"].rotation_euler.x = -0.35 * fade - pb["upperarm.L"].rotation_euler.x = -0.35 * fade - pb["upperarm.R"].rotation_euler.x = 0.30 * fade + grip_weapon(pb) def make_actions(arm): @@ -497,7 +581,8 @@ def make_actions(arm): for pb in arm.pose.bones: pb.keyframe_insert(data_path="rotation_euler", frame=frame, group=name) - if pb.name == "root": + if pb.name in ("root", "weapon", "upperarm.L", "upperarm.R", + "forearm.L", "forearm.R", "hand.L", "hand.R"): pb.keyframe_insert(data_path="location", frame=frame, group=name) made.append((name, act)) diff --git a/tools/blender/import_level.py b/tools/blender/import_level.py index 47b5d06..2b122e8 100644 --- a/tools/blender/import_level.py +++ b/tools/blender/import_level.py @@ -6,7 +6,7 @@ from mathutils import Vector REPO = "/home/dandovlatov/Documents/cntrl" LEVEL = os.environ.get("CNTRL_LEVEL", REPO + "/assets/levels/floor01.json") -OUTPUT = REPO + "/assets/blender/fbc_level01_blockout.blend" +OUTPUT = os.environ.get("CNTRL_OUT", REPO + "/assets/blender/fbc_level01_blockout.blend") ACTOR_PATHS = { "TV": "assets/models/props/tv.glb",