Compare commits

..
Author SHA1 Message Date
Rbanh 1ab3886028 Complete editor operator invariants
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 23:53:46 -04:00
Rbanh 9a67a25a15 Clarify renderer foundation follow-ups
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 23:01:02 -04:00
Rbanh 0ce43fc399 Add collider authoring diagnostics
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 22:48:00 -04:00
Rbanh 0e7aed40f1 Add transactional physics placement
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 22:07:17 -04:00
Rbanh d1a56f77cc Add terrain material layer painting
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 21:00:13 -04:00
Rbanh 293811aecd Add terrain sculpt stroke tools
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 19:50:47 -04:00
Rbanh ed21bcc52d Add chunked terrain authoring foundation
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 18:43:42 -04:00
Rbanh 577d8dcb27 Refresh production readiness matrix
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 18:10:03 -04:00
Rbanh ba59f57a5a Finish non-blocking native dialog workflows
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 18:06:57 -04:00
Rbanh d038cf3670 Add non-blocking native dialog broker 2026-07-12 17:48:51 -04:00
Rbanh 61be2440bd Document collaborative file safety acceptance
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 17:43:07 -04:00
Rbanh 3794faa4aa Document material workflow acceptance
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 13:18:40 -04:00
Rbanh 02247f029a Add material library and targeted surface drops 2026-07-12 13:14:47 -04:00
Rbanh 3931de1f0a Fix hot reload feature matrix
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 11:35:57 -04:00
107 changed files with 11304 additions and 622 deletions

No files matched your search

@@ -0,0 +1,31 @@
# Collider Authoring Diagnostics - 2026-07-12
Issue: Gitea #26 (`BS-JD-305`)
## Outcome
Collider authoring exposes one consistent health result to the inspector, Collider viewport,
Diagnostics panel, and physics placement preflight. Shape changes preserve useful dimensions and
remain one typed undo operation.
## Contract
- Authored box, sphere, and capsule overlays include actor world scale.
- Static mesh colliders show cooked runtime bounds when available.
- Green is ready, cyan is a trigger, gray is disabled, amber is warning/stale, and red is invalid
or missing.
- Invalid dimensions and mesh references block dependent workflows. Missing hydration and
colliders over 1,000 meters in world extent are warnings.
- Physics placement consumes the same collider-health checks instead of maintaining a separate
prerequisite definition.
## Work
- [x] Add shared authored/runtime collider diagnostics and focused fixtures.
- [x] Add shape/status-aware viewport overlays and selected-collider HUD state.
- [x] Add inspector health/repair feedback and dimension-preserving undoable shape switching.
- [x] Add scene-wide selectable collider findings to Diagnostics.
- [x] Reuse diagnostics in physics placement prerequisites.
- [x] Add a committed non-blocking showcase scene and update documentation.
- [x] Run source gates and live Wayland acceptance; packaged tests remain skipped by request.
- [x] Commit, push, attach native Gitea evidence, close #26, and close M3 when empty.
@@ -8,21 +8,26 @@ present; this slice completes the production-facing catalog and drag/drop workfl
## Status
Source audit complete. Implementation starts on a clean branch after collaborative-safety `#49` is
published, because both slices touch the Asset Browser and should remain independently reviewable.
Implemented on `codex/material-library-targeted-drop` after collaborative-safety `#49` was
published and integrated into `main`. Focused and full source-only verification plus live editor
acceptance are green; ticket evidence remains before `#16` / `#18` close.
## Current Gaps
## Resolved Gaps
- Material assets are edited inside generic Asset Browser Details; no dedicated Material Library or
scene-usage view exists.
- Viewport material/texture drops act on the existing selection instead of the surface under the
pointer.
- Multi-slot renderers silently assign all slots; the hydrated draw hit already carries
`HydratedRendererMaterialBinding`, but the drop path does not use it.
- Primitive and brush-face targeting is not explicit, and unsupported authored actors can receive a
generic `MaterialDesc` instead of an actionable rejection.
- Drag UI describes an eventual action but does not preview the actual affected surface or restore a
preview on cancel/target change.
- The dockable Material Library now provides cross-folder Material/Instance catalog, usage counts,
health, creation, thumbnails, drag sources, and the guarded existing details editors.
- Viewport Material/Texture drops resolve the surface under the pointer and never broaden to the
current selection or every renderer slot.
- `HydratedRendererMaterialBinding` identifies the exact static/skinned renderer slot; primitives
and stable brush-face IDs use their authored component paths.
- Unsupported, locked, linked, missing, and payload-incompatible targets reject with an explicit
reason and no scene mutation.
- Hover previews are reversible, target changes restore the prior snapshot, and release records one
typed operator/history transaction.
- Viewport pointer tracking remains active while another egui widget owns the drag, so exact target
resolution cannot stall at the viewport boundary.
- Visibility hierarchy setup now precedes generated hydration content, preventing Bevy parent/child
visibility warnings when brush draws are created after scene load.
## Material Library
@@ -73,12 +78,17 @@ menu; a viewport hit never silently broadens from one slot to all slots.
## Verification
- Unit-test ray-hit to authored target/slot mapping, primitive/face targeting, and invalid reasons.
- Use `OperatorInvariantHarness` for preview target changes, release commit, Escape/outside cancel,
dirty-state preservation, helper cleanup, and one-step undo/redo.
- Cover static one/multi-slot, skinned multi-slot, primitive, brush face, Texture rejection on a
renderer slot, missing material, and linked/locked prefab boundaries.
- Verify Material Library filtering, scene-usage counts, dependency diagnostics, and drag sources in
headless egui tests.
- Run full source/headless checks. Packaged testing remains deferred until the project owner requests
it again; live visual acceptance is still required before closing `#16`/`#18`.
- Focused tests cover exact multi-slot assignment/undo, brush-face-only preview/restore, primitive
Material/Texture resolution, renderer Texture rejection, Material Library filtering, and scene
usage counts.
- Source checks include editor all-target check, focused tests, and strict editor Clippy.
- Live acceptance covered the docked catalog, search/type/usage filters, grid/list views, resolved
Material Instance thumbnails, exact primitive preview, green actor/surface feedback, one-step
commit/undo, and Escape rollback. The same relaunch produced no hydration hierarchy warnings.
- Static/skinned exact-slot, brush-face, locked/linked, incompatible Texture, and non-dirty preview
contracts remain covered by focused automated tests; shared-asset file creation was deliberately
not invoked during live QA to avoid adding throwaway authored files.
- Full verification passed: workspace all-target check, strict workspace Clippy, all workspace tests,
strict editor Clippy with both `dev` and `hot-reload`, level validation with zero blockers, and
navigation artifact freshness. Packaged testing remains deferred until the project owner requests
it again.
@@ -0,0 +1,36 @@
# Non-Blocking Native Dialogs
Working implementation plan for the production-readiness defect discovered during live acceptance
of collaborative file safety. Opening an `rfd` picker synchronously from an egui/Bevy system stops
window event processing long enough for Hyprland to report Blacksite as unresponsive.
## Scope
1. Add one project-level native-dialog broker with a typed intent, one active dialog, background
native work, and a main-thread result queue.
2. Convert scene open/save-as, asset import/export, prefab save/source selection, subscene selection,
conflict Save As, diagnostics export, and project-launcher folder selection to the broker.
3. Keep destructive or stateful application logic on the Bevy main thread after a path result is
received. Background work may only own the native dialog and its returned paths.
4. Show a stable pending state and reject duplicate dialog requests while a picker is active.
5. Replace blocking native dirty-scene confirmation dialogs with an editor-owned modal when the
scene-transition state machine can preserve the original action exactly.
## Contract
- The editor continues rendering and processing compositor pings while a native dialog is open.
- Cancel returns a typed empty result and does not mutate editor state.
- A result is applied once to the intent that created it; stale or duplicate results cannot run.
- Paths are validated at the same ownership boundary as before. The dialog broker does not read,
write, import, save, or canonicalize project content.
- Existing collaborative revision guards remain authoritative after Save As selection.
- Project-launcher dialogs use the same broker before the full editor plugin group is active.
## Verification
- Focused tests cover request exclusivity, cancel, one-shot result delivery, and typed intent
preservation.
- Source-only workspace formatting, check, strict Clippy, and tests run; packaged acceptance remains
deferred by project-owner direction.
- Native Wayland QA opens representative file, folder, and Save As dialogs under Hyprland and
confirms the Blacksite window remains responsive without an unresponsive-application prompt.
@@ -0,0 +1,33 @@
# Operator Invariants Completion
Working plan for Gitea
[`#33`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/33).
## Status
Implementation complete. Source and headless gates pass on the publication branch; the final exact
commit is recorded in the issue closure comment. Packaged-runtime testing remains deferred by the
project owner.
## Scope
1. Make registered commands distinguish immediate completion from modal Preview ownership.
2. Require stable operator IDs and terminal phases for commit, cancel, block, failure, no-op, and
automatic interruption paths.
3. Make Group Selection and lighting changes atomic history transactions with repeatable undo/redo.
4. Exercise production dispatch/finalizers for assets, material drops, brushes, terrain, physics
placement, and transform gizmos through reusable semantic projections.
5. Publish the invariant contract, acceptance evidence, and production-gate status without claiming
release-candidate acceptance.
## Verification
- `cargo test -p editor --lib --no-fail-fast`
- `cargo clippy -p editor --lib --tests -- -D warnings`
- `cargo fmt --all -- --check`
- `cargo test --workspace --all-targets --no-fail-fast`
- `cargo clippy --workspace --all-targets -- -D warnings`
- `cargo validate-levels --project .`
Live editor checks cover command-palette modal ownership and the grouped selection/lighting history
surface. Packaged tests are deliberately excluded until re-enabled by the project owner.
@@ -0,0 +1,36 @@
# Physics Placement Tool - 2026-07-12
Issue: Gitea #25 (`BS-JD-304`)
## Outcome
Selected authored props can be released into deterministic Avian gravity, preview their
settled transforms in the Scene viewport, and either commit the result as one undoable
transform operation or cancel back to the exact pre-placement state.
## Contract
- Physics is paused during normal Edit mode and while Play mode is paused.
- Placement runs only in Edit mode and owns a transactional physics session.
- Selected mutable level objects must have active rigid-body and non-trigger collider
authoring. Invalid selections produce a precise, non-destructive diagnostic.
- Selected bodies are temporarily dynamic with clean motion state.
- Other movable bodies are temporarily static so they remain collision surfaces without
advancing unrelated authored state.
- Commit restores all temporary runtime overrides and records only changed local transforms
as one grouped history command.
- Cancel restores transforms and runtime physics state exactly and creates no history entry.
- Escape cancels. Enter commits once the session has reached rest. A bounded timeout keeps
unstable scenes controllable.
## Work
- [x] Establish Edit/Play ownership of `Time<Physics>` and preserve paused single-step PIE.
- [x] Implement placement validation, runtime snapshots, deterministic stepping, settling,
timeout, commit, and cancel.
- [x] Add the placement action and session controls to the existing horizontal viewport
toolbar plus a compact status HUD.
- [x] Add unit/integration coverage for prerequisites, settling, cancel, commit, and history.
- [x] Update editor workflow documentation and implementation checklist.
- [x] Run source gates and live Wayland acceptance; packaged tests remain skipped by request.
- [x] Commit, push, attach native Gitea evidence, and close #25.
@@ -15,11 +15,12 @@ owner requests it again.
1. Keep one evidence matrix under `docs/editor/evaluations/production-readiness/`; historical H1-H6
notes remain context only.
2. Close implementation blockers before nominating a candidate: collaborative safety `#49`, the
remaining Material/drag-drop contract in `#16`, `#18`, and `#51`, terrain `#22`-`#24`, physics
placement/diagnostics `#25`-`#26`, and their regression fixtures.
3. Complete the representative regression project, mutation-invariant coverage, performance budgets,
and first-hour workflow tracked by `#32`-`#36`.
2. Close implementation blockers before nominating a candidate. Renderer foundation `#51`, terrain
`#22`-`#24`, physics placement/diagnostics `#25`-`#26`, operator invariants `#33`, collaborative
safety `#49`, Material Library/targeted drops `#16`/`#18`, and native-dialog responsiveness `#52`
are accepted and integrated.
3. Complete the representative regression project, performance budgets, and first-hour workflow
tracked by `#32`, `#34`, `#35`, and `#36`.
4. Nominate one exact commit, validate it from a clean checkout, and record source/headless results.
5. When packaged testing is re-enabled, run the candidate's package/build and packaged-runtime
matrix without substituting older artifacts.
@@ -0,0 +1,25 @@
# Renderer Foundation Acceptance Split - 2026-07-12
Issue: Gitea #51 (`BS-JD-207`)
## Outcome
Accept the shipped renderer/material/Surface foundation without claiming two independent future
systems. Preserve the existing safe raster/Forward behavior and track each remaining boundary with
its own implementation and acceptance contract.
## Decisions
- #51 owns stable static/skinned slots, shared Material/Instance assets, Surface ABI parity for
eligible geometry, transactional migration, and the honest exclusion of deformed Solari meshes.
- #53 owns actual runtime Material Property Block application and promote-to-instance UX. The
existing component schema/persistence exclusion is not represented as runtime completion.
- #54 owns dynamic post-morph/post-skin buffers and instance BLAS updates. It is a documented P2
Solari enhancement, not a raster/Forward production blocker.
## Work
- [x] Audit #51 scope and repository evidence against current runtime behavior.
- [x] Create focused Gitea follow-ups with independent acceptance criteria.
- [x] Correct ADR, material guide, README checklist, evaluation, and production matrix claims.
- [x] Run documentation/diff gates, commit, push, and close #51 with exact follow-up links.
@@ -0,0 +1,46 @@
# Terrain Authoring Foundation
Working implementation plan for Gitea
[`#22`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/22).
This establishes the persistent and hydrated terrain contract required by sculpting `#23`, layer
painting `#24`, physics placement `#25`, and the regression pack `#32`.
## Authored Contract
- Add reflected `TerrainDesc` authoring data with a version, square height-grid resolution, inline
finite heights, horizontal sample spacing, vertical scale, chunk quad size, optional shared
Material/Material Instance reference, collider generation, and shadow flags.
- V1 stores the compact height grid in the scene so save/recovery/history/prefab behavior is exact.
A later external heightmap asset migration must be explicit and versioned rather than silently
changing ownership.
- Validate resolution, exact sample count, finite values, positive scale, and chunk bounds before
hydration or publication.
## Hydration
- Partition the grid into deterministic non-overlapping quad chunks with shared boundary samples.
- Generate triangle-list meshes with normals, UVs, U32 indices, and tangents; each generated child
carries owner/chunk coordinates and remains runtime-only.
- Use the authored shared material when resolvable and an explicit terrain fallback otherwise.
- Optionally attach `ColliderConstructor::TrimeshFromMesh` per chunk.
- Rebuild only the owning terrain's generated chunks when descriptor/material/active state changes;
disabling/removing terrain cleans every generated child.
## Editor Integration
- Register Terrain as a stable authoring component and ActorKind with conflicts against primitive,
brush, static renderer, and skinned renderer geometry sources.
- Add an inspector for resolution, world scale, chunk size, collider/shadow state, material summary,
validation, and a guarded flat-grid resize action. All mutations are one typed history step.
- Include terrain bounds in selection framing and generated chunks in authored-parent picking.
- Expose Add Terrain through the existing component shelf; no new permanent toolbar is added.
## Verification
- Tests cover descriptor validation, deterministic chunk coverage/mesh topology, hydration and
cleanup, generated-child stripping, serialization, and history round-trip.
- Source-only workspace format/check/strict-Clippy/tests and level validation run. Packaged tests
remain deferred by project-owner direction.
- Live native-Wayland acceptance creates or loads a terrain actor, verifies chunk rendering and
selection/inspection, changes scale/chunking, exercises undo/redo, and inspects a saved scene to
confirm generated chunks are absent.
@@ -0,0 +1,28 @@
# Terrain Material Layers And Weight Painting (#24)
## Scope
- Persist up to four shared Material/Material Instance references on each `TerrainDesc`.
- Store normalized RGBA8 layer weights per height sample with an implicit channel-zero default.
- Blend layer albedo, normal, metallic, and roughness in the project-owned raster material path.
- Assign, clear, reorder, and tile layers from the Terrain inspector.
- Paint or erase one selected layer from the existing horizontal viewport toolbar.
- Preserve one reflected history transaction per completed pointer stroke and exact cancel restore.
## Implementation
1. Extend the backward-compatible terrain schema with four layer descriptors and compact weights.
2. Emit normalized weights as terrain chunk vertex colors and attach a runtime-only material binding.
3. Build a terrain-specific `ExtendedMaterial` in `blacksite_surface`; keep invalid references on the visible fallback path with diagnostics.
4. Add inspector layer controls and a mutually exclusive modal paint operator beside Sculpt.
5. Cover serialization, validation, blend transport, paint normalization, cancel, undo, and redo.
6. Update ADR 0040, terrain workflow docs, the implementation checklist, and live evidence.
## Acceptance
- Two or more project materials visibly blend on one terrain.
- Layer weights remain exactly normalized and survive scene save/load.
- Live paint preview follows the sampled terrain surface.
- Escape/right-click restores exact pre-stroke weights; release creates one undo entry.
- Missing or invalid material references remain visible as fallback and produce clear diagnostics.
- Formatting, workspace check/clippy/tests, level validation, and live native-Wayland QA pass.
@@ -0,0 +1,25 @@
# Terrain Sculpt Tools (#23)
## Scope
- Add a modal terrain sculpt operator for raise, lower, flatten, smooth, and deterministic noise.
- Keep activation and brush settings in the existing horizontal viewport toolbar.
- Track a terrain-local cursor hit and render a world-space brush footprint preview.
- Apply live stroke previews while preserving one history entry per completed stroke.
- Restore the exact pre-stroke height grid on Escape or right-click.
## Implementation
1. Add pure heightfield sampling, ray-hit, falloff, and brush-dab functions with focused tests.
2. Add editor-only terrain sculpt state and viewport input/preview systems.
3. Commit strokes through the reflected component transaction after restoring the pre-stroke snapshot.
4. Add compact terrain controls to the existing viewport toolbar and update operator hints.
5. Document controls and validation evidence in the terrain editor guide and root checklist.
## Acceptance
- All five modes visibly modify terrain.
- The brush ring follows the actual terrain surface.
- Escape and right-click cancel without dirtying history.
- Mouse release creates exactly one undoable transaction regardless of dab count.
- Formatting, editor/shared checks, focused tests, and live editor QA pass.
+19 -4
View File
@@ -144,6 +144,7 @@ deep-stale variants.
| Brush selected: `1` / `2` / `3` / `4` | Vertex / edge / face / clip edit modes |
| Brush edit mode: LMB / `Shift+LMB` / `W` / `E` / `R` / `Esc` | Select element / toggle element selection / move / rotate / scale selected brush elements / return to object mode |
| Viewport toolbar (sun / brush / box icons) | Shading: Lit, Unlit (albedo), Colliders (mesh off) |
| Collider viewport mode | Inspect world-scale box/sphere/capsule overlays and cooked mesh bounds; green/cyan/gray/amber/red identify ready/trigger/disabled/warning/invalid state, with selected health in the lower-left HUD |
| Viewport eye/options | Toggle actor root icon categories, adjust icon/gizmo size, and control colliders, lights, spawns, gameplay markers, volumes, prefab/model anchors, and runtime player/camera visualizers |
| `Tab` in viewport | Cycle selection through overlapping objects at last click |
| Viewport selection/orientation HUD | Identify the primary selection, multi-selection count, overlapping-pick position, camera axes, shading mode, and active render path |
@@ -152,6 +153,9 @@ deep-stale variants.
| Asset Browser project/file views | Browse `assets/`, search/filter/sort models, textures, materials, audio clips, levels, and prefabs; switch grid/list; expand model subassets; inspect file details; audition audio; drag supported assets/submeshes into the viewport |
| Drag audio clip into viewport | Create an authored audio source; when an audio source is selected, assign the clip instead |
| Asset Browser context/details actions | Apply textures/materials, regenerate thumbnails, reimport models, place assets/submeshes, or move file assets to `assets/.trash/` |
| Window → Material Library | Search/filter project Materials and Material Instances, inspect scene usage and dependency health, create/edit shared assets, and drag them into the viewport |
| Drag Material/Instance onto viewport surface | Preview and assign the exact renderer slot, primitive, or brush face under the pointer; release commits one undo step, while Escape/right-click/outside restores the preview |
| Drag Texture onto viewport surface | Set a primitive base-color texture or exact brush face; renderer slots reject loose textures and direct you to a Material Instance |
| Static/Skinned Mesh Renderer material slots | Assign a shared Material/Material Instance per slot; Browse/Select/Locate the reference, or Clear the override to restore the imported source material |
| `Ctrl+P` | Centered command palette; search human labels or stable command IDs, use arrow keys to select, Enter to run |
| `F7` | While paused in Play: advance one sim tick |
@@ -160,13 +164,17 @@ deep-stale variants.
| Drag actor between rows / onto Scene Root (Hierarchy, Manual sort) | Reorder siblings / unparent to the root |
| Hierarchy lock | Excludes the actor from selection, gizmos, multi-drag, structural drops, and mutating context actions |
| Hierarchy context | Group selection, create authored local children below linked prefab roots, remove/reparent generated members through same-layer structural overrides, or unparent |
| File menu | New, Open, transactional Save/Save As, recovery restore/keep-copy/discard when available, Import Assets, Export Selection, Save Selection As Prefab (including linked-root variants), Recent Scenes |
| File menu | New, non-blocking native Open/Save As, recovery restore/keep-copy/discard when available, Import Assets, Export Selection, Save Selection As Prefab (including linked-root variants), Recent Scenes |
| Status strip / Asset Details source-state chip | Inspect compact clean, modified, untracked, conflicted, read-only, and optional ownership status; hover for the source path and provider details |
| Authored File Not Saved dialog | Resolve an external edit, read-only target, or ownership lock with Reload, Compare Metadata, Save As, or Cancel; the editor never offers force overwrite |
| Main toolbar, right side | Switch or close independent scene tabs, create an untitled tab, and manage loaded/locked composed subscenes |
| Prefab Instance inspector | Inspect/recover source health, Apply/Revert overrides by scope, Apply overrides to source, create a variant, **Unpack Layer**, or recursively **Convert to Local** |
| Inspector component card | Collapse with caret, toggle active with status dot, or use triple-dot menu for reset/copy/paste/move/remove actions |
| Inspector footer → Add Component | Expands an inline search shelf for registered authoring, rendering, physics, gameplay, and volume components with descriptions, availability hints, and undo |
| Inspector footer → Add Component → Terrain | Add a height-grid terrain actor; configure grid scale/chunking/collision in its component card and use Resize Flat only for deliberate grid replacement |
| Selected Terrain → viewport mountains tool | Sculpt Raise/Lower/Flatten/Smooth/Noise strokes with a terrain-following footprint; release commits one undo step, while Escape/right-click restores the pre-stroke grid |
| Terrain card → Material Layers; selected Terrain → viewport paint tool | Assign up to four shared materials, then Paint/Erase normalized layer weights with live blended preview; release commits one undo step and Escape/right-click restores the pre-stroke map |
| Selected physics props → viewport hand/down-arrow tool | Release the selection into real gravity/colliders; check commits one grouped transform edit, while Escape/X restores the exact starting state |
| Audio Source / Listener inspector | Assign and audition clips; edit gain, pitch, loop/autoplay, spatial blend, attenuation, bus, listener priority, and ear gap |
| Edit → Project Settings… | Edit `assets/project.ron` rendering, audio buses, physics, and input |
@@ -395,6 +403,12 @@ crates/
- [x] Filtered hierarchy, inspector, viewport, toolbar, asset browser, and status panels
- [x] Delete, duplicate, rename, and structural/material undo-redo
- [x] Native Bevy scene New/Open/Save/Save As with dirty title tracking
- [x] First-class height-grid Terrain actor with deterministic generated render/collider chunks, reflected history, validation, and a committed showcase fixture ([ADR 0039](docs/adr/0039-inline-height-grid-terrain-foundation.md), [terrain guide](docs/editor/terrain.md), [Gitea #22](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/22))
- [x] Modal terrain Raise/Lower/Flatten/Smooth/Noise sculpting with a terrain-following footprint, deterministic noise, safe cancel restore, and one undo transaction per stroke ([terrain guide](docs/editor/terrain.md), [Gitea #23](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/23))
- [x] Four shared terrain Material/Material Instance layers with compact normalized sample weights, blended raster hydration, drag/browse assignment, Paint/Erase preview, exact cancel, and one undo transaction per stroke ([ADR 0040](docs/adr/0040-terrain-material-layer-weights.md), [terrain guide](docs/editor/terrain.md), [Gitea #24](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/24))
- [x] Transactional physics placement with real Avian gravity/colliders, paused Edit-mode physics, prerequisite diagnostics, isolated non-selected bodies, exact cancel, and grouped transform undo ([ADR 0041](docs/adr/0041-transactional-editor-physics-placement.md), [workflow guide](docs/editor/physics-placement.md), [Gitea #25](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/25))
- [x] Collider authoring health shared by the inspector, Collider viewport, Diagnostics panel, and physics placement, with scaled shape overlays, cooked mesh bounds, missing/stale/invalid/oversized findings, and undoable dimension-preserving shape switching ([collider guide](docs/editor/collider-authoring.md), [Gitea #26](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/26))
- [x] Non-blocking native file/folder/confirmation broker across scene, asset, prefab, composition, collaboration, and Project Browser workflows ([ADR 0038](docs/adr/0038-non-blocking-native-dialog-broker.md), [workflow guide](docs/editor/native-dialogs.md), [Gitea #52](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/52))
- [x] Asset import, static mesh/prefab placement, texture assignment, and selection export
- [x] PIE player-only snapshot/restore (authored `LevelObject` edits persist on stop)
- [x] Unified viewport render-to-texture target + Play session bootstrap
@@ -405,7 +419,7 @@ crates/
- [x] CI workflow for format, check, clippy, tests, and binary builds
- [x] ADRs for roadmap architecture and Bevy migration policy
- [x] Determinism harness: same inputs over same ticks produce the same state summary/hash
- [x] Reusable editor operator harness for commit/cancel/block, helper cleanup, dirty state, grouped undo, and undo/redo round trips
- [x] Production operator invariants across palette dispatch, assets/material drops, brush/terrain/physics modal tools, grouping/lighting, and the transform finalizer: stable terminal status, exact cancel/failure rollback, helper cleanup, grouped history, and repeated undo/redo projections ([testing contract](docs/editor/operator-regression-testing.md), [evaluation](docs/editor/evaluations/operator-invariants/), [Gitea #33](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/33))
- [x] Verify: `cargo fmt --check` / `cargo check --workspace` / `cargo clippy --workspace` / strict foundation clippy / `cargo test -p sim`
- [x] Stable asset registry with UUIDs + import settings in asset browser details
- [x] Asset Browser expandable model subasset shelves, independent mesh/material/texture thumbnails, staged import/material details with shader-schema parameters, context actions, and trash-first file removal
@@ -433,7 +447,8 @@ crates/
- [x] Editor lib/bin split + `EditorPluginGroup`; game EditorPlugin dogfood panel
- [x] FBX/glTF model import + normalized static/skinned renderer routing; explicit generic scene-instance load via `bevy_ufbx` / `ModelRef`
- [x] Asset browser model thumbnails (unified `assets/thumbnails/` pipeline; `ThumbnailState` cache; FBX via `FbxThumbnailSource`)
- [x] Shared Material/Material Instance assets, stable static/skinned renderer material slots, imported-source fallback, orphan preservation, and runtime-only property blocks ([ADR 0035](docs/adr/0035-shared-material-assets-and-renderer-slots.md), [material-system guide](docs/editor/material-system.md))
- [x] Shared Material/Material Instance assets, stable static/skinned renderer material slots, imported-source fallback, orphan preservation, and a persistence-excluded property-block schema; runtime block application/promotion remains tracked in [Gitea #53](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/53) ([ADR 0035](docs/adr/0035-shared-material-assets-and-renderer-slots.md), [material-system guide](docs/editor/material-system.md))
- [x] Docked Material Library with cross-folder type/usage filters, resolved Material Instance thumbnails, shared guarded editors, and exact reversible viewport Material/Texture drops for renderer slots, primitives, and brush faces ([material-system guide](docs/editor/material-system.md); [Gitea #16](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/16), [Gitea #18](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/18))
- [x] Prefab v2 core: shared stable nested override paths, property/component/structural scopes, recursive graph validation, linked-root variants, conflict recovery, transactional source Apply, and undoable unpack/convert ([ADR 0027](docs/adr/0027-stable-prefab-ownership-and-variants.md))
- [x] Prefab v2 production acceptance: committed base/nested/variant fixtures pass workspace tests, recursive headless validation, packaged release startup, and live editor placement/inspection regression coverage ([Gitea #43](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/43))
- [x] Shared project validation: editor Diagnostics and `cargo validate-levels --json` use one owner-attributed dependency/finding report across project settings, registry/import artifacts, materials, shaders, scenes, prefabs, brushes, and colliders; valid/missing/cyclic/incompatible fixtures fail on blocking content errors ([ADR 0028](docs/adr/0028-authoritative-project-content-validation.md), [Gitea #45](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/45))
@@ -476,7 +491,7 @@ crates/
**Unpack Layer** preserves nested links; **Convert to Local** recursively removes them. Current
authoring UI coverage and production-acceptance gaps are tracked in
[prefab-authoring.md](docs/editor/prefab-authoring.md).
- Material and direct-base Material Instance assets live under `assets/materials/`; shader schemas live under `assets/shaders/`. In the Asset Browser, select a Material and use **Create Instance** for sparse inherited variants. Static and skinned renderers own stable per-draw material slots, with explicit assignments taking precedence over imported source defaults; shared edits propagate through live-updated handles without reloading skinned geometry. Custom Surface evaluators share one constrained ABI between raster and Solari-eligible non-deformed geometry. Dynamic skinned/morph Solari geometry and a persisted property-block authoring workflow remain future work; see the [material-system guide](docs/editor/material-system.md).
- Material and direct-base Material Instance assets live under `assets/materials/`; shader schemas live under `assets/shaders/`. **Window > Material Library** provides cross-folder creation, editing, usage filters, and drag sources. Viewport Material drops target one exact renderer slot, primitive, or brush face and use reversible preview plus one-step history; loose Textures target primitives/brush faces and are rejected on renderer slots. Shared edits propagate through live-updated handles without reloading skinned geometry. Custom Surface evaluators share one constrained ABI between raster and Solari-eligible non-deformed geometry. Runtime property-block application/promotion is tracked in [#53](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/53); dynamic skinned/morph Solari geometry is tracked in [#54](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/54). See the [material-system guide](docs/editor/material-system.md).
- Per-field reflect undo for all components remains future work; typed `shared` inspectors cover the common authoring path.
- The authoring/hydration layer is intentionally small so richer asset workflows (terrain,
material graphs, lighting profiles) can be added without changing the scene format foundation.
+54
View File
@@ -197,6 +197,24 @@
),
dependencies: [],
),
(
id: ("78c6850b-5a76-4a4f-b48e-7fb00f6dd1ed"),
path: "assets/levels/physics_placement_showcase.scn.ron",
label: "physics_placement_showcase.scn",
kind_tag: "Level",
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: StaticAsset,
hierarchy_mode: SingleActor,
material_policy: SourceMaterials,
static_mesh_manifest_path: None,
animation_manifest_path: None,
default_animation_clip_id: None,
),
dependencies: [],
),
(
id: ("706e604e-1a63-4e97-b35d-eeb1d88fe3a9"),
path: "assets/levels/navigation_authoring_showcase.scn.ron",
@@ -233,6 +251,24 @@
),
dependencies: [],
),
(
id: ("a7ef65b4-24d6-4c3a-b637-5bb52d8e9a26"),
path: "assets/levels/collider_diagnostics_showcase.scn.ron",
label: "collider_diagnostics_showcase.scn",
kind_tag: "Level",
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: StaticAsset,
hierarchy_mode: SingleActor,
material_policy: SourceMaterials,
static_mesh_manifest_path: None,
animation_manifest_path: None,
default_animation_clip_id: None,
),
dependencies: [],
),
(
id: ("f3dfcd11-aa5b-4fd4-872b-06832b865c99"),
path: "assets/levels/audio_authoring_showcase.scn.ron",
@@ -269,6 +305,24 @@
),
dependencies: [],
),
(
id: ("1b25d451-7b54-41d6-af00-d2e6950f502d"),
path: "assets/levels/terrain_authoring_showcase.scn.ron",
label: "terrain_authoring_showcase.scn",
kind_tag: "Level",
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: StaticAsset,
hierarchy_mode: SingleActor,
material_policy: SourceMaterials,
static_mesh_manifest_path: None,
animation_manifest_path: None,
default_animation_clip_id: None,
),
dependencies: [],
),
(
id: ("dc13ce01-c7ce-43c5-974c-0e659ae49ab9"),
path: "assets/levels/editor_scene 2.scn.ron",
@@ -0,0 +1,175 @@
(schema_version: 4, resources: {}, entities: {
1: (components: {
"bevy_ecs::name::Name": "Valid Box Collider",
"bevy_transform::components::transform::Transform": (
translation: (-4.5, 1.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("collider-showcase-box"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (0),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.18, g: 0.62, b: 0.36, a: 1.0),
metallic: 0.05, roughness: 0.55,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
),
"shared::components::Primitive": (shape: Box, size: (1.8, 2.0, 1.8)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true, is_trigger: false,
shape: Cuboid(x_length: 1.8, y_length: 2.0, z_length: 1.8),
),
}),
2: (components: {
"bevy_ecs::name::Name": "Valid Sphere Collider",
"bevy_transform::components::transform::Transform": (
translation: (-2.25, 1.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.35, 0.8),
),
"shared::components::ActorId": ("collider-showcase-sphere"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (1),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.16, g: 0.52, b: 0.78, a: 1.0),
metallic: 0.08, roughness: 0.42,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
),
"shared::components::Primitive": (shape: Sphere, size: (2.0, 2.0, 2.0)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true, is_trigger: false, shape: Sphere(radius: 1.0),
),
}),
3: (components: {
"bevy_ecs::name::Name": "Valid Capsule Collider",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 1.4, 0.0),
rotation: (0.0, 0.1950903, 0.0, 0.9807853),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("collider-showcase-capsule"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (2),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.58, g: 0.34, b: 0.78, a: 1.0),
metallic: 0.06, roughness: 0.48,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
),
"shared::components::Primitive": (shape: Box, size: (1.4, 2.8, 1.4)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true, is_trigger: false, shape: Capsule(radius: 0.7, height: 2.8),
),
}),
4: (components: {
"bevy_ecs::name::Name": "Trigger Collider",
"bevy_transform::components::transform::Transform": (
translation: (2.25, 1.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("collider-showcase-trigger"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (3),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.12, g: 0.68, b: 0.82, a: 1.0),
metallic: 0.03, roughness: 0.4,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
),
"shared::components::Primitive": (shape: Sphere, size: (2.0, 2.0, 2.0)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true, is_trigger: true, shape: Sphere(radius: 1.0),
),
}),
5: (components: {
"bevy_ecs::name::Name": "Disabled Collider",
"bevy_transform::components::transform::Transform": (
translation: (4.5, 1.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("collider-showcase-disabled"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (4),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.38, g: 0.40, b: 0.46, a: 1.0),
metallic: 0.02, roughness: 0.68,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
),
"shared::components::Primitive": (shape: Box, size: (1.8, 2.0, 1.8)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: false, is_trigger: false,
shape: Cuboid(x_length: 1.8, y_length: 2.0, z_length: 1.8),
),
}),
6: (components: {
"bevy_ecs::name::Name": "Missing Collider",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 1.0, -3.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("collider-showcase-missing"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (5),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.78, g: 0.16, b: 0.20, a: 1.0),
metallic: 0.02, roughness: 0.58,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
),
"shared::components::Primitive": (shape: Box, size: (1.8, 2.0, 1.8)),
"shared::components::RigidBodyDesc": (body: Static),
}),
7: (components: {
"bevy_ecs::name::Name": "Collider Showcase Sun",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 8.0, 4.0),
rotation: (-0.3826834, 0.0, 0.0, 0.9238795),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("collider-showcase-sun"),
"shared::components::ActorKind": Light,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (6),
"shared::components::LevelObject": (),
"shared::components::LightDesc": (
kind: Directional, color: (r: 1.0, g: 0.95, b: 0.88, a: 1.0),
intensity: 100000.0, range: 0.0, shadows: true,
inner_angle_deg: 25.0, outer_angle_deg: 35.0,
),
}),
})
@@ -0,0 +1,164 @@
(schema_version: 4, resources: {}, entities: {
1: (components: {
"bevy_ecs::name::Name": "Placement Floor",
"bevy_transform::components::transform::Transform": (
translation: (0.0, -0.25, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("physics-placement-floor"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (0),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.12, g: 0.14, b: 0.16, a: 1.0),
metallic: 0.05,
roughness: 0.72,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
emissive_intensity: 0.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: None,
parameters: [],
textures: [],
),
"shared::components::Primitive": (shape: Box, size: (14.0, 0.5, 10.0)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true,
is_trigger: false,
shape: Cuboid(x_length: 14.0, y_length: 0.5, z_length: 10.0),
),
}),
2: (components: {
"bevy_ecs::name::Name": "Placement Prop A",
"bevy_transform::components::transform::Transform": (
translation: (-2.0, 3.0, 0.0),
rotation: (0.1305262, 0.0, 0.0, 0.9914449),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("physics-placement-prop-a"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (1),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.88, g: 0.48, b: 0.12, a: 1.0),
metallic: 0.1,
roughness: 0.42,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
emissive_intensity: 0.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: None,
parameters: [],
textures: [],
),
"shared::components::Primitive": (shape: Box, size: (1.2, 1.2, 1.2)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true,
is_trigger: false,
shape: Cuboid(x_length: 1.2, y_length: 1.2, z_length: 1.2),
),
}),
3: (components: {
"bevy_ecs::name::Name": "Placement Prop B",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 5.0, 0.0),
rotation: (0.0, 0.2164396, 0.0, 0.976296),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("physics-placement-prop-b"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (2),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.10, g: 0.58, b: 0.72, a: 1.0),
metallic: 0.15,
roughness: 0.35,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
emissive_intensity: 0.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: None,
parameters: [],
textures: [],
),
"shared::components::Primitive": (shape: Box, size: (1.0, 1.6, 1.0)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true,
is_trigger: false,
shape: Cuboid(x_length: 1.0, y_length: 1.6, z_length: 1.0),
),
}),
4: (components: {
"bevy_ecs::name::Name": "Placement Prop C",
"bevy_transform::components::transform::Transform": (
translation: (2.0, 7.0, 0.0),
rotation: (0.092296, 0.092296, -0.008077, 0.991405),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("physics-placement-prop-c"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (3),
"shared::components::LevelObject": (),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.62, g: 0.24, b: 0.56, a: 1.0),
metallic: 0.08,
roughness: 0.5,
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
emissive_intensity: 0.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: None,
parameters: [],
textures: [],
),
"shared::components::Primitive": (shape: Box, size: (1.4, 0.8, 1.0)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true,
is_trigger: false,
shape: Cuboid(x_length: 1.4, y_length: 0.8, z_length: 1.0),
),
}),
5: (components: {
"bevy_ecs::name::Name": "Placement Sun",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 8.0, 2.0),
rotation: (-0.3826834, 0.0, 0.0, 0.9238795),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("physics-placement-sun"),
"shared::components::ActorKind": Light,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (4),
"shared::components::LevelObject": (),
"shared::components::LightDesc": (
kind: Directional,
color: (r: 1.0, g: 0.95, b: 0.85, a: 1.0),
intensity: 100000.0,
range: 0.0,
shadows: true,
inner_angle_deg: 25.0,
outer_angle_deg: 35.0,
),
}),
})
@@ -0,0 +1,87 @@
(schema_version: 4, resources: {}, entities: {
1: (components: {
"bevy_ecs::name::Name": "Terrain Showcase",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 0.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("terrain-showcase-main"),
"shared::components::ActorKind": Terrain,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (0),
"shared::components::LevelObject": (),
"shared::components::TerrainDesc": (
schema_version: 1,
resolution: 5,
heights: [
0.00, 0.00, 0.05, 0.00, 0.00,
0.00, 0.15, 0.30, 0.10, 0.00,
0.05, 0.35, 0.80, 0.25, 0.05,
0.00, 0.20, 0.40, 0.15, 0.00,
0.00, 0.00, 0.05, 0.00, 0.00,
],
sample_spacing: 2.0,
height_scale: 3.0,
chunk_quads: 2,
base_material: Some((
asset_id: "cc2769da-c9a5-4cb3-866a-cc81d0688ee2",
sub_asset_id: "material:instance",
label: "surface_tint_instance",
source_path: Some("assets/materials/surface_tint_instance.ron"),
)),
material_layers: [
(
material: Some((
asset_id: "a57f2891-8536-47b8-b476-01c08b36ac43",
sub_asset_id: "material:source",
label: "Concrete",
source_path: Some("assets/materials/concrete.ron"),
)),
uv_scale: 6.0,
),
(
material: Some((
asset_id: "d6cb4151-7124-4237-aaf9-f7f8abd5fb76",
sub_asset_id: "material:source",
label: "Surface Tint",
source_path: Some("assets/materials/surface_tint.ron"),
)),
uv_scale: 10.0,
),
],
material_weights: [
(255, 0, 0, 0), (255, 0, 0, 0), (224, 31, 0, 0), (255, 0, 0, 0), (255, 0, 0, 0),
(255, 0, 0, 0), (192, 63, 0, 0), (128, 127, 0, 0), (192, 63, 0, 0), (255, 0, 0, 0),
(224, 31, 0, 0), (128, 127, 0, 0), (0, 255, 0, 0), (128, 127, 0, 0), (224, 31, 0, 0),
(255, 0, 0, 0), (192, 63, 0, 0), (128, 127, 0, 0), (192, 63, 0, 0), (255, 0, 0, 0),
(255, 0, 0, 0), (255, 0, 0, 0), (224, 31, 0, 0), (255, 0, 0, 0), (255, 0, 0, 0),
],
generate_colliders: true,
cast_shadows: true,
receive_shadows: true,
),
}),
2: (components: {
"bevy_ecs::name::Name": "Terrain Sun",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 8.0, 0.0),
rotation: (-0.3826834, 0.0, 0.0, 0.9238795),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("terrain-showcase-sun"),
"shared::components::ActorKind": Light,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (1),
"shared::components::LevelObject": (),
"shared::components::LightDesc": (
kind: Directional,
color: (r: 1.0, g: 0.95, b: 0.85, a: 1.0),
intensity: 100000.0,
range: 0.0,
shadows: true,
inner_angle_deg: 25.0,
outer_angle_deg: 35.0,
),
}),
})
+116
View File
@@ -0,0 +1,116 @@
#import bevy_pbr::{
pbr_fragment::pbr_input_from_standard_material,
pbr_functions::{alpha_discard, calculate_tbn_mikktspace},
}
#ifdef PREPASS_PIPELINE
#import bevy_pbr::{
prepass_io::{VertexOutput, FragmentOutput},
pbr_deferred_functions::deferred_output,
}
#else
#import bevy_pbr::{
forward_io::{VertexOutput, FragmentOutput},
pbr_functions::{apply_pbr_lighting, main_pass_post_lighting_processing},
}
#endif
struct TerrainLayerUniform {
base_colors: array<vec4<f32>, 4>,
properties: array<vec4<f32>, 4>,
uv_scales: vec4<f32>,
base_texture_enabled: vec4<f32>,
}
@group(#{MATERIAL_BIND_GROUP}) @binding(100) var<uniform> terrain_layers: TerrainLayerUniform;
@group(#{MATERIAL_BIND_GROUP}) @binding(101) var base_color0: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(102) var base_sampler0: sampler;
@group(#{MATERIAL_BIND_GROUP}) @binding(103) var normal0: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(104) var normal_sampler0: sampler;
@group(#{MATERIAL_BIND_GROUP}) @binding(105) var base_color1: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(106) var base_sampler1: sampler;
@group(#{MATERIAL_BIND_GROUP}) @binding(107) var normal1: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(108) var normal_sampler1: sampler;
@group(#{MATERIAL_BIND_GROUP}) @binding(109) var base_color2: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(110) var base_sampler2: sampler;
@group(#{MATERIAL_BIND_GROUP}) @binding(111) var normal2: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(112) var normal_sampler2: sampler;
@group(#{MATERIAL_BIND_GROUP}) @binding(113) var base_color3: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(114) var base_sampler3: sampler;
@group(#{MATERIAL_BIND_GROUP}) @binding(115) var normal3: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(116) var normal_sampler3: sampler;
fn layer_base(index: u32, uv: vec2<f32>) -> vec4<f32> {
if index == 0u { return textureSample(base_color0, base_sampler0, uv); }
if index == 1u { return textureSample(base_color1, base_sampler1, uv); }
if index == 2u { return textureSample(base_color2, base_sampler2, uv); }
return textureSample(base_color3, base_sampler3, uv);
}
fn layer_normal(index: u32, uv: vec2<f32>) -> vec3<f32> {
var sample = vec3<f32>(0.5, 0.5, 1.0);
if index == 0u { sample = textureSample(normal0, normal_sampler0, uv).xyz; }
if index == 1u { sample = textureSample(normal1, normal_sampler1, uv).xyz; }
if index == 2u { sample = textureSample(normal2, normal_sampler2, uv).xyz; }
if index == 3u { sample = textureSample(normal3, normal_sampler3, uv).xyz; }
return normalize(sample * 2.0 - 1.0);
}
@fragment
fn fragment(in: VertexOutput, @builtin(front_facing) is_front: bool) -> FragmentOutput {
var pbr_input = pbr_input_from_standard_material(in, is_front);
#ifdef VERTEX_UVS_A
let uv = in.uv;
#else
let uv = vec2<f32>(0.0);
#endif
#ifdef VERTEX_COLORS
var weights = max(in.color, vec4<f32>(0.0));
#else
var weights = vec4<f32>(1.0, 0.0, 0.0, 0.0);
#endif
let enabled = vec4<f32>(
terrain_layers.properties[0].w,
terrain_layers.properties[1].w,
terrain_layers.properties[2].w,
terrain_layers.properties[3].w,
);
weights *= enabled;
let total = dot(weights, vec4<f32>(1.0));
weights = select(vec4<f32>(1.0, 0.0, 0.0, 0.0), weights / total, total > 0.0001);
var color = vec4<f32>(0.0);
var normal_ts = vec3<f32>(0.0);
var metallic = 0.0;
var roughness = 0.0;
for (var index = 0u; index < 4u; index += 1u) {
let weight = weights[index];
let layer_uv = uv * terrain_layers.uv_scales[index];
let base_sample = mix(
vec4<f32>(1.0),
layer_base(index, layer_uv),
terrain_layers.base_texture_enabled[index],
);
color += base_sample * terrain_layers.base_colors[index] * weight;
let normal_enabled = terrain_layers.properties[index].z;
normal_ts += mix(vec3<f32>(0.0, 0.0, 1.0), layer_normal(index, layer_uv), normal_enabled) * weight;
metallic += terrain_layers.properties[index].x * weight;
roughness += terrain_layers.properties[index].y * weight;
}
pbr_input.material.base_color = alpha_discard(pbr_input.material, color);
pbr_input.material.metallic = clamp(metallic, 0.0, 1.0);
pbr_input.material.perceptual_roughness = clamp(roughness, 0.001, 1.0);
#ifdef VERTEX_TANGENTS
let tbn = calculate_tbn_mikktspace(pbr_input.world_normal, in.world_tangent);
let n = normalize(normal_ts);
pbr_input.N = normalize(n.x * tbn[0] + n.y * tbn[1] + n.z * tbn[2]);
#endif
#ifdef PREPASS_PIPELINE
return deferred_output(in, pbr_input);
#else
var out: FragmentOutput;
out.color = apply_pbr_lighting(pbr_input);
out.color = main_pass_post_lighting_processing(pbr_input, out.color);
return out;
#endif
}
+339 -14
View File
@@ -17,15 +17,92 @@ use bevy::render::render_resource::{
};
use bevy::shader::{Shader, ShaderRef};
use shared::{
asset_server_path, material_from_desc, HydratedRendererMaterialBinding, MaterialAsset,
MaterialInstanceAsset, MaterialParameterValue, MaterialRef, ShaderPropertyType,
ShaderSchemaAsset, MATERIAL_INSTANCE_SCHEMA_VERSION,
asset_server_path, material_from_desc, HydratedRendererMaterialBinding,
HydratedTerrainMaterialBinding, MaterialAsset, MaterialDesc, MaterialInstanceAsset,
MaterialParameterValue, MaterialRef, ShaderPropertyType, ShaderSchemaAsset,
TerrainMaterialLayer, MATERIAL_INSTANCE_SCHEMA_VERSION, TERRAIN_MATERIAL_LAYER_LIMIT,
};
pub const SURFACE_ABI_VERSION: u32 = 1;
pub const SURFACE_PARAMETER_LANES: usize = 16;
pub const SURFACE_TEXTURE_SLOTS: usize = 8;
pub const DEFAULT_SURFACE_SHADER_PATH: &str = "shaders/blacksite_surface.wgsl";
pub const TERRAIN_LAYER_SHADER_PATH: &str = "shaders/terrain_layers.wgsl";
#[derive(ShaderType, Reflect, Debug, Clone, Copy, PartialEq)]
pub struct TerrainLayerUniform {
pub base_colors: [Vec4; TERRAIN_MATERIAL_LAYER_LIMIT],
/// Metallic, perceptual roughness, normal-map enabled, layer enabled.
pub properties: [Vec4; TERRAIN_MATERIAL_LAYER_LIMIT],
pub uv_scales: Vec4,
pub base_texture_enabled: Vec4,
}
impl Default for TerrainLayerUniform {
fn default() -> Self {
Self {
base_colors: [Vec4::ONE; TERRAIN_MATERIAL_LAYER_LIMIT],
properties: [Vec4::new(0.0, 0.9, 0.0, 0.0); TERRAIN_MATERIAL_LAYER_LIMIT],
uv_scales: Vec4::splat(8.0),
base_texture_enabled: Vec4::ZERO,
}
}
}
#[derive(Asset, AsBindGroup, Reflect, Debug, Clone, Default)]
pub struct TerrainLayerExtension {
#[uniform(100)]
pub uniform: TerrainLayerUniform,
#[texture(101)]
#[sampler(102)]
pub base_color0: Option<Handle<Image>>,
#[texture(103)]
#[sampler(104)]
pub normal0: Option<Handle<Image>>,
#[texture(105)]
#[sampler(106)]
pub base_color1: Option<Handle<Image>>,
#[texture(107)]
#[sampler(108)]
pub normal1: Option<Handle<Image>>,
#[texture(109)]
#[sampler(110)]
pub base_color2: Option<Handle<Image>>,
#[texture(111)]
#[sampler(112)]
pub normal2: Option<Handle<Image>>,
#[texture(113)]
#[sampler(114)]
pub base_color3: Option<Handle<Image>>,
#[texture(115)]
#[sampler(116)]
pub normal3: Option<Handle<Image>>,
}
impl MaterialExtension for TerrainLayerExtension {
fn fragment_shader() -> ShaderRef {
TERRAIN_LAYER_SHADER_PATH.into()
}
fn deferred_fragment_shader() -> ShaderRef {
TERRAIN_LAYER_SHADER_PATH.into()
}
}
pub type TerrainLayerMaterial = ExtendedMaterial<StandardMaterial, TerrainLayerExtension>;
#[derive(Debug, Clone)]
struct TerrainLayerCacheEntry {
layers: Vec<TerrainMaterialLayer>,
handle: Handle<TerrainLayerMaterial>,
revision: u64,
}
#[derive(Resource, Default)]
struct TerrainLayerMaterialCache(HashMap<Entity, TerrainLayerCacheEntry>);
type TerrainMaterialBindings<'w, 's> =
Query<'w, 's, (Entity, &'static HydratedTerrainMaterialBinding)>;
#[derive(ShaderType, Reflect, Debug, Clone, Copy, PartialEq)]
pub struct SurfaceUniform {
@@ -121,10 +198,6 @@ impl MaterialExtension for SurfaceExtension {
DEFAULT_SURFACE_SHADER_PATH.into()
}
fn prepass_fragment_shader() -> ShaderRef {
DEFAULT_SURFACE_SHADER_PATH.into()
}
fn specialize(
_pipeline: &MaterialExtensionPipeline,
descriptor: &mut RenderPipelineDescriptor,
@@ -179,10 +252,191 @@ pub struct SurfaceMaterialPlugin;
impl Plugin for SurfaceMaterialPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(MaterialPlugin::<SurfaceMaterial>::default())
.add_plugins(MaterialPlugin::<TerrainLayerMaterial>::default())
.init_resource::<SurfaceMaterialCache>()
.init_resource::<TerrainLayerMaterialCache>()
.init_resource::<SurfaceDiagnostics>()
.init_resource::<SurfaceEvaluatorRegistry>()
.add_systems(Update, sync_surface_material_bindings);
.add_systems(
Update,
(
sync_surface_material_bindings,
sync_terrain_layer_material_bindings,
),
);
}
}
fn sync_terrain_layer_material_bindings(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<TerrainLayerMaterial>>,
mut cache: ResMut<TerrainLayerMaterialCache>,
mut diagnostics: ResMut<SurfaceDiagnostics>,
bindings: TerrainMaterialBindings,
) {
for (entity, binding) in &bindings {
if binding.layers.is_empty() {
continue;
}
let revision = terrain_layer_revision(&binding.layers);
let cached = cache
.0
.get(&binding.owner)
.filter(|entry| entry.layers == binding.layers && entry.revision == revision)
.map(|entry| entry.handle.clone());
let handle = cached.unwrap_or_else(|| {
let material =
build_terrain_layer_material(&asset_server, &binding.layers, &mut diagnostics.0);
let handle = cache
.0
.get(&binding.owner)
.map(|entry| entry.handle.clone())
.filter(|handle| {
materials
.get_mut(handle)
.map(|mut slot| {
*slot = material.clone();
})
.is_some()
})
.unwrap_or_else(|| materials.add(material));
cache.0.insert(
binding.owner,
TerrainLayerCacheEntry {
layers: binding.layers.clone(),
handle: handle.clone(),
revision,
},
);
handle
});
queue_terrain_material_binding(&mut commands, entity, handle);
}
}
fn queue_terrain_material_binding(
commands: &mut Commands,
entity: Entity,
handle: Handle<TerrainLayerMaterial>,
) {
// Generated render entities can be removed by a scene switch after this system's query
// but before deferred commands apply. That lifecycle race is expected and must not abort
// the editor while opening another scene.
commands
.entity(entity)
.try_remove::<MeshMaterial3d<StandardMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
fn terrain_layer_revision(layers: &[TerrainMaterialLayer]) -> u64 {
let mut dependencies = layers
.iter()
.filter_map(|layer| layer.material.as_ref())
.filter_map(|reference| reference.source_path.as_deref())
.flat_map(|path| material_dependency_paths(path).unwrap_or_else(|_| vec![path.to_string()]))
.collect::<Vec<_>>();
dependencies.sort();
dependencies.dedup();
dependency_revision(&dependencies)
}
fn build_terrain_layer_material(
asset_server: &AssetServer,
layers: &[TerrainMaterialLayer],
diagnostics: &mut Vec<String>,
) -> TerrainLayerMaterial {
let mut extension = TerrainLayerExtension::default();
for (index, layer) in layers.iter().take(TERRAIN_MATERIAL_LAYER_LIMIT).enumerate() {
extension.uniform.uv_scales[index] = layer.uv_scale;
let desc = resolve_terrain_layer(layer, index, diagnostics);
let color = desc.base_color.to_color().to_linear();
extension.uniform.base_colors[index] =
Vec4::new(color.red, color.green, color.blue, color.alpha);
extension.uniform.properties[index] = Vec4::new(
desc.metallic,
desc.roughness,
f32::from(desc.normal_map_texture.is_some()),
1.0,
);
extension.uniform.base_texture_enabled[index] =
f32::from(desc.base_color_texture.is_some());
let base_color = desc
.base_color_texture
.as_deref()
.map(|path| asset_server.load(asset_server_path(path)));
let normal = desc
.normal_map_texture
.as_deref()
.map(|path| asset_server.load(asset_server_path(path)));
match index {
0 => {
extension.base_color0 = base_color;
extension.normal0 = normal;
}
1 => {
extension.base_color1 = base_color;
extension.normal1 = normal;
}
2 => {
extension.base_color2 = base_color;
extension.normal2 = normal;
}
3 => {
extension.base_color3 = base_color;
extension.normal3 = normal;
}
_ => {}
}
}
TerrainLayerMaterial {
base: StandardMaterial {
base_color: Color::WHITE,
perceptual_roughness: 1.0,
..default()
},
extension,
}
}
fn resolve_terrain_layer(
layer: &TerrainMaterialLayer,
index: usize,
diagnostics: &mut Vec<String>,
) -> MaterialDesc {
let Some(reference) = layer.material.as_ref() else {
diagnostics.push(format!(
"terrain material layer {} is unassigned; using visible fallback",
index + 1
));
return terrain_layer_fallback();
};
let Some(path) = reference.source_path.as_deref() else {
diagnostics.push(format!(
"terrain material layer {} ({}) has no loadable source path; using visible fallback",
index + 1,
reference.label
));
return terrain_layer_fallback();
};
match shared::load_resolved_material_from_path(path) {
Ok((desc, _)) => desc,
Err(error) => {
diagnostics.push(format!(
"terrain material layer {} ({}) could not resolve: {error}; using visible fallback",
index + 1,
reference.label
));
terrain_layer_fallback()
}
}
}
fn terrain_layer_fallback() -> MaterialDesc {
MaterialDesc {
base_color: shared::ColorDesc::srgb(0.24, 0.29, 0.25),
roughness: 0.92,
..Default::default()
}
}
@@ -226,8 +480,8 @@ fn sync_surface_material_bindings(
{
commands
.entity(entity)
.remove::<MeshMaterial3d<SurfaceMaterial>>()
.insert(MeshMaterial3d(handle));
.try_remove::<MeshMaterial3d<SurfaceMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
}
continue;
@@ -297,8 +551,8 @@ fn sync_surface_material_bindings(
{
commands
.entity(entity)
.remove::<MeshMaterial3d<SurfaceMaterial>>()
.insert(MeshMaterial3d(handle));
.try_remove::<MeshMaterial3d<SurfaceMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
continue;
}
@@ -322,8 +576,8 @@ fn sync_surface_material_bindings(
if surface_handle.is_none_or(|current| current.0 != handle) {
commands
.entity(entity)
.remove::<MeshMaterial3d<StandardMaterial>>()
.insert(MeshMaterial3d(handle));
.try_remove::<MeshMaterial3d<StandardMaterial>>()
.try_insert(MeshMaterial3d(handle));
}
}
}
@@ -714,6 +968,21 @@ pub fn compose_surface_shader(evaluator: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use bevy::ecs::world::CommandQueue;
#[test]
fn stale_generated_terrain_binding_is_nonfatal_during_scene_switch() {
let mut world = World::new();
let entity = world.spawn_empty().id();
let mut queue = CommandQueue::default();
let mut commands = Commands::new(&mut queue, &world);
queue_terrain_material_binding(&mut commands, entity, Handle::default());
world.entity_mut(entity).despawn();
queue.apply(&mut world);
assert!(world.get_entity(entity).is_err());
}
#[test]
fn rejects_resource_bindings_and_missing_entry() {
@@ -759,4 +1028,60 @@ mod tests {
assert_eq!(SURFACE_TEXTURE_SLOTS, 8);
assert_eq!(std::mem::size_of::<SurfaceUniform>(), 400);
}
#[test]
fn material_extensions_leave_non_deferred_prepasses_to_standard_material() {
assert!(matches!(
<SurfaceExtension as MaterialExtension>::prepass_fragment_shader(),
ShaderRef::Default
));
assert!(matches!(
<TerrainLayerExtension as MaterialExtension>::prepass_fragment_shader(),
ShaderRef::Default
));
}
#[test]
fn terrain_layer_builder_packs_project_material_values() {
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()));
let asset_server = app.world().resource::<AssetServer>();
let materials_root =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/materials");
let layers = [
TerrainMaterialLayer {
material: Some(
shared::EditorAssetRef::new("concrete", "material:source", "Concrete")
.with_source_path(
materials_root.join("concrete.ron").display().to_string(),
),
),
uv_scale: 6.0,
},
TerrainMaterialLayer {
material: Some(
shared::EditorAssetRef::new("tint", "material:source", "Surface Tint")
.with_source_path(
materials_root
.join("surface_tint.ron")
.display()
.to_string(),
),
),
uv_scale: 10.0,
},
];
let mut diagnostics = Vec::new();
let material = build_terrain_layer_material(asset_server, &layers, &mut diagnostics);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
assert_eq!(material.extension.uniform.uv_scales.x, 6.0);
assert_eq!(material.extension.uniform.uv_scales.y, 10.0);
assert_eq!(material.extension.uniform.properties[0].w, 1.0);
assert_eq!(material.extension.uniform.properties[1].w, 1.0);
assert_ne!(
material.extension.uniform.base_colors[0],
material.extension.uniform.base_colors[1]
);
}
}
+2 -5
View File
@@ -16,10 +16,7 @@ pub fn load_material_asset(catalog_path: &str) -> Result<MaterialAsset, String>
}
pub fn material_desc_from_asset(catalog_path: &str) -> Result<MaterialDesc, String> {
let asset = load_material_asset(catalog_path)?;
let mut desc = asset.material;
desc.material_asset_path = Some(catalog_path.to_string());
Ok(desc)
shared::load_resolved_material_from_path(catalog_path).map(|(desc, _)| desc)
}
pub fn apply_material_asset_to_selection(
@@ -110,7 +107,7 @@ pub fn apply_material_asset_to_selection(
Ok(())
}
fn ensure_static_material_slots(renderer: &mut shared::StaticMeshRenderer) {
pub(crate) fn ensure_static_material_slots(renderer: &mut shared::StaticMeshRenderer) {
for part in &mut renderer.slots {
if part.material_slot_id.0.trim().is_empty() {
part.material_slot_id = if part.id.0.trim().is_empty() {
+2 -2
View File
@@ -13,8 +13,8 @@ pub mod thumbnails;
pub use catalog::*;
pub use thumbnails::{
draw_asset_cell_with, gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon,
prefetch_folder_thumbnails, AssetThumbnailCache, ThumbnailCacheSnapshot, ThumbnailState,
ThumbnailStudio, ThumbnailsPlugin,
prefetch_asset_thumbnails, prefetch_folder_thumbnails, AssetThumbnailCache,
ThumbnailCacheSnapshot, ThumbnailState, ThumbnailStudio, ThumbnailsPlugin,
};
/// Refreshes both generated contracts derived from one imported model source.
+135
View File
@@ -469,6 +469,86 @@ mod tests {
);
}
#[test]
fn multi_actor_material_assignment_is_one_undo_group() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let material_path = std::env::temp_dir().join(format!(
"blacksite-material-operator-{}.material.ron",
uuid::Uuid::new_v4()
));
let fixture = shared::MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Concrete".into(),
shader: None,
shader_ref: None,
render_state: Default::default(),
material: MaterialDesc {
roughness: 0.85,
..Default::default()
},
};
std::fs::write(
&material_path,
ron::ser::to_string_pretty(&fixture, ron::ser::PrettyConfig::default()).unwrap(),
)
.unwrap();
let material_path = material_path.to_string_lossy().into_owned();
world.insert_resource(AssetRegistry {
records: vec![AssetRecord {
id: AssetId::new(),
path: material_path.clone(),
label: "Concrete".into(),
kind_tag: "Material".into(),
import_settings: Default::default(),
dependencies: Vec::new(),
}],
index_dirty: false,
});
let first = world.spawn((LevelObject, MaterialDesc::default())).id();
let second = world.spawn((LevelObject, MaterialDesc::default())).id();
let mut selected = SelectedEntities::default();
selected.select_replace(first);
selected.select_maybe_add(second, true);
let asset = EditorAsset {
label: "Concrete".to_string(),
path: Some(material_path.clone()),
folder_path: "assets/materials".to_string(),
kind: super::super::EditorAssetKind::Material,
};
super::super::materials::material_desc_from_asset(&material_path)
.expect("committed material fixture should resolve");
let harness = OperatorInvariantHarness::capture(&mut world);
let read_materials = move |world: &mut World| {
[first, second]
.into_iter()
.map(|entity| {
world
.get::<MaterialDesc>(entity)
.and_then(|material| material.material_asset_path.clone())
})
.collect::<Vec<_>>()
};
let applied = apply_material_operator(&mut world, asset, &selected);
assert!(
applied,
"material operator failed: {:?}",
world.resource::<ActiveOperator>().status
);
harness.assert_committed(&mut world, 1, 0);
assert_undo_redo_round_trip(
&mut world,
vec![None, None],
vec![Some(material_path.clone()), Some(material_path.clone())],
read_materials,
);
let _ = std::fs::remove_file(material_path);
}
#[test]
fn missing_subasset_commit_cancels_without_side_effects() {
let mut world = World::new();
@@ -533,4 +613,59 @@ mod tests {
harness.assert_blocked(&mut world);
}
#[test]
fn material_assignment_without_authored_selection_is_blocked() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let harness = OperatorInvariantHarness::capture(&mut world);
let asset = EditorAsset {
label: "Concrete".to_string(),
path: Some("assets/materials/concrete.ron".to_string()),
folder_path: "assets/materials".to_string(),
kind: super::super::EditorAssetKind::Material,
};
assert!(!apply_material_operator(
&mut world,
asset,
&SelectedEntities::default()
));
harness.assert_blocked(&mut world);
}
#[test]
fn audio_and_animation_assignment_reject_incompatible_actors() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let entity = world.spawn(LevelObject).id();
let audio = EditorAsset {
label: "Impact".into(),
path: Some("assets/audio/impact.ogg".into()),
folder_path: "assets/audio".into(),
kind: super::super::EditorAssetKind::AudioClip,
};
let audio_harness = OperatorInvariantHarness::capture(&mut world);
assert!(!assign_audio_clip_operator(&mut world, audio, entity));
audio_harness.assert_blocked(&mut world);
let animation_harness = OperatorInvariantHarness::capture(&mut world);
let selection = AssetSelection::SubAsset {
parent_path: "assets/models/missing.glb".into(),
sub_asset_id: "animation:missing".into(),
label: "Missing".into(),
kind: super::super::AssetSubAssetKind::AnimationClip,
source_path: None,
};
assert!(!assign_animation_clip_operator(
&mut world, selection, entity
));
animation_harness.assert_blocked(&mut world);
}
}
+38 -6
View File
@@ -22,6 +22,7 @@ use crate::asset_db::{ensure_asset_record, AssetRegistry};
use crate::history::{
capture_prefab_edit_state, record_prefab_edit_state, record_prefab_source_apply,
};
use crate::native_dialog::NativeDialogBroker;
use crate::ui::inspector::{
apply_component_card_response, component_card, component_card_context, property_row,
ComponentCardOptions,
@@ -751,13 +752,44 @@ fn relink_prefab_source(world: &mut World, entity: Entity) {
else {
return;
};
let Some(path) = rfd::FileDialog::new()
.set_directory(project_root.join("assets/prefabs"))
.add_filter("Bevy prefab", &["scn.ron", "ron"])
.pick_file()
else {
let directory = project_root.join("assets/prefabs");
let result = world.resource::<NativeDialogBroker>().request(
move || {
rfd::FileDialog::new()
.set_directory(directory)
.add_filter("Bevy prefab", &["scn.ron", "ron"])
.pick_file()
},
move |world, path| {
let Some(path) = path else {
world
.resource_mut::<crate::scene_io::SceneIo>()
.set_status("Prefab relink cancelled");
return;
};
finish_relink_prefab_source(world, entity, project_root, path);
},
);
world
.resource_mut::<crate::scene_io::SceneIo>()
.set_status(match result {
Ok(()) => "Choose a prefab source".into(),
Err(error) => format!("Prefab relink unavailable: {error}"),
});
}
fn finish_relink_prefab_source(
world: &mut World,
entity: Entity,
project_root: PathBuf,
path: PathBuf,
) {
if world.get_entity(entity).is_err() {
world
.resource_mut::<crate::scene_io::SceneIo>()
.set_status("Prefab relink failed: the initiating actor no longer exists");
return;
};
}
let Ok(path) = path.canonicalize() else {
return;
};
+41 -4
View File
@@ -188,18 +188,24 @@ impl AssetThumbnailCache {
{
return;
}
let material = match shared::MaterialAsset::load_from_path(&path) {
Ok(asset) => asset,
let material = match shared::load_resolved_material_from_path(&path) {
Ok((material, _)) => material,
Err(error) => {
self.mark_studio_failed(&key, &error, true);
return;
}
};
let label = shared::MaterialAsset::load_from_path(&path)
.map(|asset| asset.label)
.or_else(|_| {
shared::MaterialInstanceAsset::load_from_path(&path).map(|asset| asset.label)
})
.unwrap_or_else(|_| "Material".into());
if studio.enqueue_source(
key.clone(),
ThumbnailJobSource::MaterialAsset {
label: material.label.clone(),
material: Box::new(material.material),
label,
material: Box::new(material),
},
) {
self.studio_pending.insert(key);
@@ -482,6 +488,37 @@ pub fn prefetch_folder_thumbnails(world: &mut World, folder: &str) {
.prefetched_folder = Some(folder.to_string());
}
/// Requests thumbnails for an explicit cross-folder asset set.
pub fn prefetch_asset_thumbnails(world: &mut World, assets: &[EditorAsset]) {
let requests = assets
.iter()
.filter_map(|asset| {
Some((
asset_cache_key(asset),
asset.path.clone()?,
asset.kind.clone(),
))
})
.collect::<Vec<_>>();
let asset_server = world.resource::<AssetServer>().clone();
world.resource_scope(|world, mut cache: Mut<AssetThumbnailCache>| {
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
for (key, path, kind) in requests {
match kind {
EditorAssetKind::Texture => cache.request_texture(key, path, &asset_server),
EditorAssetKind::Model => {
cache.request_model(key, path, &asset_server, &mut studio)
}
EditorAssetKind::Material => {
cache.request_material_asset(key, path, &mut studio)
}
_ => {}
}
}
});
});
}
pub fn invalidate_on_catalog_refresh(world: &mut World) {
world.resource_mut::<AssetThumbnailCache>().invalidate_all();
if !world.contains_resource::<ThumbnailStudio>() {
+3 -2
View File
@@ -8,8 +8,9 @@ mod sources;
mod studio;
pub use cache::{
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_folder_thumbnails,
AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot, ThumbnailState,
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_asset_thumbnails,
prefetch_folder_thumbnails, AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot,
ThumbnailState,
};
pub use job::{ThumbnailJob, ThumbnailJobSource};
pub use sources::{
+305 -33
View File
@@ -4,7 +4,7 @@ use bevy::prelude::*;
use bevy_egui::{egui, EguiContexts, EguiPrimaryContextPass};
use crate::history::group_selection_with_history;
use crate::operators::{run_immediate_operator, OperatorAvailability};
use crate::operators::{run_operator_action, OperatorAction, OperatorAvailability};
use crate::state::{EditorMode, PlayPossession};
use crate::ui::helpers::{
reset_scene_lighting_to_project_defaults, toggle_play_mode, toggle_play_paused,
@@ -27,7 +27,7 @@ pub trait EditorCommand: Send + Sync {
fn disabled_reason(&self, _world: &World) -> Option<String> {
None
}
fn execute(&self, world: &mut World);
fn execute(&self, world: &mut World) -> Result<OperatorAction, String>;
}
#[derive(Resource, Default)]
@@ -70,13 +70,11 @@ impl EditorCommandRegistry {
.map(|cmd| (cmd.label().to_string(), cmd.disabled_reason(world)))
}
pub fn run(&self, world: &mut World, name: &str) -> bool {
if let Some(command) = self.commands.iter().find(|cmd| cmd.name() == name) {
command.execute(world);
true
} else {
false
}
pub fn run(&self, world: &mut World, name: &str) -> Option<Result<OperatorAction, String>> {
self.commands
.iter()
.find(|command| command.name() == name)
.map(|command| command.execute(world))
}
}
@@ -191,6 +189,10 @@ pub fn register_editor_plugin(app: &mut App, plugin: Box<dyn EditorPlugin>) {
}
fn register_builtin_commands(mut registry: ResMut<EditorCommandRegistry>) {
populate_builtin_commands(&mut registry);
}
fn populate_builtin_commands(registry: &mut EditorCommandRegistry) {
registry.register(Box::new(TogglePlayCommand));
registry.register(Box::new(TogglePlayPausedCommand));
registry.register(Box::new(TogglePossessionCommand));
@@ -235,7 +237,7 @@ fn dispatch_editor_command(world: &mut World, name: &str) {
let name_for_commit = name.to_string();
let name_for_status = name.to_string();
let label_for_commit = label.clone();
run_immediate_operator(
run_operator_action(
world,
&name_for_status,
&label,
@@ -244,14 +246,10 @@ fn dispatch_editor_command(world: &mut World, name: &str) {
None => OperatorAvailability::Ready,
},
move |world| {
let ran = world.resource_scope(|world, registry: Mut<EditorCommandRegistry>| {
let result = world.resource_scope(|world, registry: Mut<EditorCommandRegistry>| {
registry.run(world, &name_for_commit)
});
if ran {
Ok(())
} else {
Err(format!("Unknown editor command: {name_for_commit}"))
}
result.unwrap_or_else(|| Err(format!("Unknown editor command: {name_for_commit}")))
},
);
@@ -269,8 +267,9 @@ impl EditorCommand for TogglePlayCommand {
"Toggle Play / Edit"
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
toggle_play_mode(world);
Ok(OperatorAction::Commit)
}
}
@@ -290,8 +289,9 @@ impl EditorCommand for TogglePlayPausedCommand {
.then(|| "Enter Play mode before pausing the simulation".to_string())
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
toggle_play_paused(world);
Ok(OperatorAction::Commit)
}
}
@@ -311,12 +311,13 @@ impl EditorCommand for TogglePossessionCommand {
.then(|| "Enter Play mode before toggling possession".to_string())
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
let next = match *world.resource::<PlayPossession>() {
PlayPossession::Possessed => PlayPossession::Ejected,
PlayPossession::Ejected => PlayPossession::Possessed,
};
*world.resource_mut::<PlayPossession>() = next;
Ok(OperatorAction::Commit)
}
}
@@ -331,8 +332,9 @@ impl EditorCommand for ResetLightingCommand {
"Reset Scene Lighting"
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
reset_scene_lighting_to_project_defaults(world);
Ok(OperatorAction::Commit)
}
}
@@ -347,13 +349,23 @@ impl EditorCommand for GroupSelectionCommand {
"Group Selection"
}
fn execute(&self, world: &mut World) {
fn disabled_reason(&self, world: &World) -> Option<String> {
world
.resource::<UiState>()
.selected_entities
.as_slice()
.is_empty()
.then(|| "Select at least one actor to group".to_string())
}
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
let selected: Vec<Entity> = world
.resource::<UiState>()
.selected_entities
.iter()
.collect();
group_selection_with_history(world, &selected);
Ok(OperatorAction::Commit)
}
}
@@ -368,8 +380,9 @@ impl EditorCommand for FocusSelectionCommand {
"Focus Selection"
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
focus_editor_camera_on_selection(world);
Ok(OperatorAction::Commit)
}
}
@@ -384,8 +397,9 @@ impl EditorCommand for ResetSelectionTransformCommand {
"Reset Selection Transform"
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
reset_selected_transforms(world);
Ok(OperatorAction::Commit)
}
}
@@ -405,8 +419,9 @@ impl EditorCommand for DrawBrushCommand {
.then(|| "Enter Edit mode before drawing brushes".to_string())
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
start_draw_brush_tool(world);
Ok(OperatorAction::ContinuePreview)
}
}
@@ -425,8 +440,9 @@ impl EditorCommand for IntersectBrushesCommand {
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
}
fn execute(&self, world: &mut World) {
intersect_selected_brushes(world);
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
intersect_selected_brushes(world)?;
Ok(OperatorAction::ContinuePreview)
}
}
@@ -445,8 +461,9 @@ impl EditorCommand for MergeBrushesCommand {
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
}
fn execute(&self, world: &mut World) {
merge_selected_brushes(world);
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
merge_selected_brushes(world)?;
Ok(OperatorAction::ContinuePreview)
}
}
@@ -465,8 +482,9 @@ impl EditorCommand for SubtractBrushesCommand {
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
}
fn execute(&self, world: &mut World) {
subtract_selected_brushes(world);
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
subtract_selected_brushes(world)?;
Ok(OperatorAction::ContinuePreview)
}
}
@@ -481,8 +499,9 @@ impl EditorCommand for CreatePostProcessVolumeCommand {
"Create Post-process Volume"
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
crate::rendering_diagnostics::spawn_post_process_volume_at_camera(world);
Ok(OperatorAction::Commit)
}
}
@@ -497,9 +516,10 @@ impl EditorCommand for FocusActiveVolumesCommand {
"Focus Active Post-process Volumes"
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
crate::rendering_diagnostics::select_volumes_at_camera(world);
focus_editor_camera_on_selection(world);
Ok(OperatorAction::Commit)
}
}
@@ -514,8 +534,9 @@ impl EditorCommand for SelectVolumesAtCameraCommand {
"Select Volumes at Camera"
}
fn execute(&self, world: &mut World) {
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
crate::rendering_diagnostics::select_volumes_at_camera(world);
Ok(OperatorAction::Commit)
}
}
@@ -671,6 +692,53 @@ fn command_palette_row(entry: &EditorCommandEntry) -> egui::WidgetText {
#[cfg(test)]
mod tests {
use super::*;
use crate::history::{apply_command_redo, apply_command_undo, EditorHistory};
use crate::operators::test_harness::OperatorInvariantHarness;
use crate::operators::{ActiveOperator, OperatorPhase};
use crate::scene_io::SceneIo;
use crate::selection::{SelectedEntity, ViewportClick};
use crate::viewport::brush_tool::BrushToolState;
use shared::{
ActorKind, AuthoringLightKind, BrushDesc, EditorVisibility, HierarchySiblingIndex,
LevelObject, LightDesc,
};
fn command_world() -> World {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<SelectedEntity>();
world.init_resource::<ViewportClick>();
world.init_resource::<BrushToolState>();
world.init_resource::<crate::viewport::brush_csg::BrushCsgPreview>();
world.insert_resource(State::new(EditorMode::Editing));
world.insert_resource(UiState::default_layout());
let mut registry = EditorCommandRegistry::default();
populate_builtin_commands(&mut registry);
world.insert_resource(registry);
world
}
fn hierarchy_projection(world: &mut World) -> Vec<(String, Option<String>, i32)> {
let mut query = world.query_filtered::<(Entity, &Name), With<LevelObject>>();
let mut result = query
.iter(world)
.map(|(entity, name)| {
let parent = world
.get::<ChildOf>(entity)
.and_then(|child| world.get::<Name>(child.parent()))
.map(|name| name.as_str().to_string());
let sibling_index = world
.get::<HierarchySiblingIndex>(entity)
.map(|index| index.0)
.unwrap_or_default();
(name.as_str().to_string(), parent, sibling_index)
})
.collect::<Vec<_>>();
result.sort();
result
}
#[test]
fn command_filter_matches_human_label_and_stable_id() {
@@ -697,4 +765,208 @@ mod tests {
assert_eq!(entries[0].name, "play.toggle");
assert_eq!(entries[1].name, "scene.reset_lighting");
}
#[test]
fn grouping_dispatch_is_one_history_transaction_and_round_trips() {
let mut world = command_world();
let first = world
.spawn((
Name::new("First"),
LevelObject,
ActorKind::Empty,
Transform::from_xyz(1.0, 0.0, 0.0),
GlobalTransform::default(),
HierarchySiblingIndex(0),
EditorVisibility::default(),
))
.id();
let second = world
.spawn((
Name::new("Second"),
LevelObject,
ActorKind::Empty,
Transform::from_xyz(2.0, 0.0, 0.0),
GlobalTransform::default(),
HierarchySiblingIndex(1),
EditorVisibility::default(),
))
.id();
let unselected = world
.spawn((
Name::new("Unselected"),
LevelObject,
ActorKind::Empty,
Transform::from_xyz(3.0, 0.0, 0.0),
GlobalTransform::default(),
HierarchySiblingIndex(2),
EditorVisibility::default(),
))
.id();
world
.resource_mut::<UiState>()
.selected_entities
.select_replace(first);
world
.resource_mut::<UiState>()
.selected_entities
.select_maybe_add(second, true);
let initial = hierarchy_projection(&mut world);
let harness = OperatorInvariantHarness::capture(&mut world);
dispatch_editor_command(&mut world, "selection.group");
harness.assert_committed(&mut world, 1, 1);
harness.assert_status(&world, "selection.group", OperatorPhase::Committed);
let committed = hierarchy_projection(&mut world);
assert!(committed
.iter()
.any(|(name, parent, _)| name == "First" && parent.as_deref() == Some("Group")));
assert!(committed
.iter()
.any(|(name, parent, _)| name == "Second" && parent.as_deref() == Some("Group")));
apply_command_undo(&mut world);
assert_eq!(hierarchy_projection(&mut world), initial);
apply_command_redo(&mut world);
assert_eq!(hierarchy_projection(&mut world), committed);
assert!(world.get::<ChildOf>(unselected).is_none());
apply_command_undo(&mut world);
assert_eq!(hierarchy_projection(&mut world), initial);
apply_command_redo(&mut world);
assert_eq!(hierarchy_projection(&mut world), committed);
assert!(world.get::<ChildOf>(unselected).is_none());
}
#[test]
fn reset_lighting_dispatch_is_one_undoable_group() {
let mut world = command_world();
let point = world
.spawn((
LevelObject,
ActorKind::Light,
LightDesc {
kind: AuthoringLightKind::Point,
..Default::default()
},
))
.id();
let directional = world
.spawn((
LevelObject,
ActorKind::Light,
LightDesc {
kind: AuthoringLightKind::Directional,
..Default::default()
},
))
.id();
let harness = OperatorInvariantHarness::capture(&mut world);
dispatch_editor_command(&mut world, "scene.reset_lighting");
harness.assert_committed(&mut world, 1, 0);
harness.assert_status(&world, "scene.reset_lighting", OperatorPhase::Committed);
assert!(world.get::<LightDesc>(point).is_none());
assert!(world.get::<LightDesc>(directional).is_none());
apply_command_undo(&mut world);
assert!(world.get::<LightDesc>(point).is_some());
assert!(world.get::<LightDesc>(directional).is_some());
apply_command_redo(&mut world);
assert!(world.get::<LightDesc>(point).is_none());
assert!(world.get::<LightDesc>(directional).is_none());
}
#[test]
fn modal_command_dispatch_retains_preview_ownership() {
let mut world = command_world();
let harness = OperatorInvariantHarness::capture(&mut world);
dispatch_editor_command(&mut world, "brush.draw");
harness.assert_status(&world, "brush.draw", OperatorPhase::Preview);
harness.assert_projection_unchanged(&mut world, 0, |world| {
world.resource::<EditorHistory>().undo_depth()
});
assert!(!world.resource::<SceneIo>().dirty);
assert!(world.resource::<BrushToolState>().active);
}
#[test]
fn failed_csg_dispatch_terminates_without_preview_or_history() {
let mut world = command_world();
let first = world
.spawn((
LevelObject,
BrushDesc::cuboid(Vec3::splat(1.0)),
Transform::IDENTITY,
))
.id();
let mut invalid = BrushDesc::cuboid(Vec3::splat(1.0));
invalid.faces.clear();
let second = world
.spawn((LevelObject, invalid, Transform::IDENTITY))
.id();
world
.resource_mut::<UiState>()
.selected_entities
.select_replace(first);
world
.resource_mut::<UiState>()
.selected_entities
.select_maybe_add(second, true);
let harness = OperatorInvariantHarness::capture(&mut world);
dispatch_editor_command(&mut world, "brush.intersect");
harness.assert_canceled(&mut world);
harness.assert_status(&world, "brush.intersect", OperatorPhase::Canceled);
assert!(!world.resource::<SceneIo>().dirty);
}
#[test]
fn csg_dispatch_blocks_read_only_selection_without_history() {
let mut world = command_world();
let first = world
.spawn((
LevelObject,
BrushDesc::cuboid(Vec3::splat(1.0)),
Transform::IDENTITY,
))
.id();
let second = world
.spawn((
LevelObject,
BrushDesc::cuboid(Vec3::splat(1.0)),
Transform::from_xyz(0.5, 0.0, 0.0),
))
.id();
let mut hierarchy = crate::ui::hierarchy_state::HierarchyPanelState::default();
hierarchy.locked.insert(second);
world.insert_resource(hierarchy);
world
.resource_mut::<UiState>()
.selected_entities
.select_replace(first);
world
.resource_mut::<UiState>()
.selected_entities
.select_maybe_add(second, true);
let harness = OperatorInvariantHarness::capture(&mut world);
dispatch_editor_command(&mut world, "brush.merge_convex");
harness.assert_blocked(&mut world);
harness.assert_status(&world, "brush.merge_convex", OperatorPhase::Blocked);
assert!(!world.resource::<SceneIo>().dirty);
}
#[test]
fn disabled_command_dispatch_is_a_blocked_no_op() {
let mut world = command_world();
let harness = OperatorInvariantHarness::capture(&mut world);
dispatch_editor_command(&mut world, "selection.group");
harness.assert_blocked(&mut world);
harness.assert_status(&world, "selection.group", OperatorPhase::Blocked);
}
}
+13
View File
@@ -106,6 +106,11 @@ pub struct PrefabEditState {
#[derive(Debug, Clone)]
pub enum EditorCommand {
GroupSelection {
snapshot: EditorEntitySnapshot,
group: Option<Entity>,
changes: Vec<SiblingChange>,
},
Spawn {
snapshot: EditorEntitySnapshot,
entity: Option<Entity>,
@@ -152,6 +157,12 @@ pub enum EditorCommand {
old: Option<LightDesc>,
new: LightDesc,
},
SetLightGroup {
entities: Vec<Entity>,
olds: Vec<Option<LightDesc>>,
news: Vec<Option<LightDesc>>,
label: &'static str,
},
SetAnimationController {
entity: Entity,
old: Option<AnimationControllerDesc>,
@@ -293,6 +304,7 @@ pub enum EditorCommand {
impl EditorCommand {
pub fn label(&self) -> &'static str {
match self {
EditorCommand::GroupSelection { .. } => "Group Selection",
EditorCommand::Spawn { .. } => "Spawn",
EditorCommand::SpawnMany { .. } => "Spawn Brushes",
EditorCommand::Despawn { .. } => "Delete",
@@ -303,6 +315,7 @@ impl EditorCommand {
EditorCommand::SetMaterialGroup { .. } => "Apply Material to Selection",
EditorCommand::SetMaterialOverride { .. } => "Set Material Override",
EditorCommand::SetLight { .. } => "Set Light",
EditorCommand::SetLightGroup { label, .. } => label,
EditorCommand::SetAnimationController { .. } => "Set Animation Controller",
EditorCommand::SetAudioSource { .. } => "Set Audio Source",
EditorCommand::SetAudioListener { .. } => "Set Audio Listener",
+229 -60
View File
@@ -17,6 +17,7 @@ use shared::{
TriggerVolume, WeaponSpawn,
};
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
use crate::scene_io::{SceneIo, SceneIoRequest};
use crate::selection::SelectedEntity;
use crate::state::scene_tools_active;
@@ -560,6 +561,40 @@ pub fn set_light_with_history(world: &mut World, entity: Entity, new: LightDesc)
push_history(world, EditorCommand::SetLight { entity, old, new });
}
pub fn set_light_group_with_history(
world: &mut World,
changes: impl IntoIterator<Item = (Entity, Option<LightDesc>)>,
label: &'static str,
) {
let mut entities = Vec::new();
let mut olds = Vec::new();
let mut news = Vec::new();
for (entity, new) in changes {
if !is_mutable_level_object(world, entity) {
continue;
}
let old = world.get::<LightDesc>(entity).cloned();
if old.is_none() && new.is_none() {
continue;
}
apply_light(world, entity, &new);
entities.push(entity);
olds.push(old);
news.push(new);
}
if !entities.is_empty() {
push_history(
world,
EditorCommand::SetLightGroup {
entities,
olds,
news,
label,
},
);
}
}
pub fn set_audio_source_with_history(world: &mut World, entity: Entity, new: AudioSourceDesc) {
if !is_mutable_level_object(world, entity) {
return;
@@ -752,9 +787,13 @@ pub fn apply_brush_csg_with_history(
new_transform: Transform,
new_brush: BrushDesc,
delete_entities: &[Entity],
) {
if !is_level_object(world, primary) {
return;
) -> bool {
if !is_mutable_level_object(world, primary)
|| delete_entities
.iter()
.any(|entity| !is_mutable_level_object(world, *entity))
{
return false;
}
let old_transform = world.get::<Transform>(primary).copied().unwrap_or_default();
let old_brush = world.get::<BrushDesc>(primary).cloned();
@@ -769,7 +808,7 @@ pub fn apply_brush_csg_with_history(
&& old_brush.as_ref() == Some(&new_brush)
&& deleted.is_empty()
{
return;
return false;
}
if let Ok(mut entity_mut) = world.get_entity_mut(primary) {
entity_mut.insert(new_transform);
@@ -790,6 +829,7 @@ pub fn apply_brush_csg_with_history(
},
);
select_one(world, primary);
true
}
pub fn set_static_mesh_renderer_with_history(
@@ -943,14 +983,16 @@ pub fn group_selection_with_history(world: &mut World, entities: &[Entity]) {
children: Vec::new(),
};
let group = spawn_snapshot(world, &snapshot);
let changes = reorder_entities_under_parent(world, &entities, Some(group), i32::MAX);
push_history(
world,
EditorCommand::Spawn {
EditorCommand::GroupSelection {
snapshot,
entity: Some(group),
group: Some(group),
changes,
},
);
reorder_siblings_with_history(world, &entities, Some(group), i32::MAX);
select_one(world, group);
}
pub fn create_empty_child_with_history(world: &mut World, parent: Entity) {
@@ -1415,16 +1457,13 @@ pub fn apply_reflected_component(
let reflected = TypedReflectDeserializer::new(registration, &type_registry)
.deserialize(&mut deserializer)
.map_err(|error| error.to_string())?;
let exists = reflect_component.reflect(world.entity(entity)).is_some();
if exists {
reflect_component.apply(world.entity_mut(entity), reflected.as_ref());
} else {
reflect_component.insert(
&mut world.entity_mut(entity),
reflected.as_ref(),
&type_registry,
);
}
// Reflected `apply` merges list fields and cannot restore a shorter snapshot.
// Inserting the captured concrete component replaces the value atomically.
reflect_component.insert(
&mut world.entity_mut(entity),
reflected.as_ref(),
&type_registry,
);
}
None => reflect_component.remove(&mut world.entity_mut(entity)),
}
@@ -1451,16 +1490,11 @@ pub fn apply_reflected_default(
.data::<ReflectDefault>()
.ok_or_else(|| format!("component `{type_path}` has no reflected Default"))?
.default();
let exists = reflect_component.reflect(world.entity(entity)).is_some();
if exists {
reflect_component.apply(world.entity_mut(entity), default.as_ref());
} else {
reflect_component.insert(
&mut world.entity_mut(entity),
default.as_ref(),
&type_registry,
);
}
reflect_component.insert(
&mut world.entity_mut(entity),
default.as_ref(),
&type_registry,
);
Ok(())
})
}
@@ -1645,6 +1679,13 @@ fn prepare_prefab_source_history(
fn undo_command(world: &mut World, command: &mut EditorCommand) {
match command {
EditorCommand::GroupSelection { group, changes, .. } => {
for change in changes.iter().rev() {
apply_sibling_change(world, change);
}
despawn_entity(world, *group);
clear_selection(world);
}
EditorCommand::Spawn { entity, .. } => {
despawn_entity(world, entity.take());
clear_selection(world);
@@ -1690,6 +1731,11 @@ fn undo_command(world: &mut World, command: &mut EditorCommand) {
EditorCommand::SetLight { entity, old, .. } => {
apply_light(world, *entity, old);
}
EditorCommand::SetLightGroup { entities, olds, .. } => {
for (entity, old) in entities.iter().zip(olds.iter()) {
apply_light(world, *entity, old);
}
}
EditorCommand::SetAnimationController { entity, old, .. } => {
apply_animation_controller(world, *entity, old);
}
@@ -1826,6 +1872,25 @@ fn undo_command(world: &mut World, command: &mut EditorCommand) {
fn redo_command(world: &mut World, command: &mut EditorCommand) {
match command {
EditorCommand::GroupSelection {
snapshot,
group,
changes,
} => {
let previous_group = *group;
let spawned = spawn_snapshot(world, snapshot);
*group = Some(spawned);
for change in changes.iter_mut() {
if Some(change.entity) == previous_group {
change.entity = spawned;
}
if change.new_parent == previous_group {
change.new_parent = Some(spawned);
}
apply_sibling_change_new(world, change);
}
select_one(world, spawned);
}
EditorCommand::Spawn { snapshot, entity } => {
let spawned = spawn_snapshot(world, snapshot);
*entity = Some(spawned);
@@ -1889,6 +1954,11 @@ fn redo_command(world: &mut World, command: &mut EditorCommand) {
entity_mut.insert(new.clone());
}
}
EditorCommand::SetLightGroup { entities, news, .. } => {
for (entity, new) in entities.iter().zip(news.iter()) {
apply_light(world, *entity, new);
}
}
EditorCommand::SetAnimationController { entity, new, .. } => {
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
entity_mut.insert(new.clone());
@@ -2622,25 +2692,41 @@ fn capture_gizmo_transform_edits(world: &mut World) {
let start_group =
active.map(|(entity, transform)| selected_transforms(world, &selection, entity, transform));
let mut started_edit = false;
let (finished_edit, live_edit) = {
let mut tracker = world.resource_mut::<TransformEditTracker>();
if tracker.active.is_none() {
if let (Some((entity, transform)), Some(group)) = (active, start_group) {
tracker.active = Some((entity, transform, group));
return;
started_edit = true;
}
}
match tracker.active.take() {
Some((primary, old, group)) if active.is_none() => (Some((primary, old, group)), None),
Some(state) if active.is_some() => {
let live = Some(state.clone());
tracker.active = Some(state);
(None, live)
if started_edit {
(None, None)
} else {
match tracker.active.take() {
Some((primary, old, group)) if active.is_none() => {
(Some((primary, old, group)), None)
}
Some(state) if active.is_some() => {
let live = Some(state.clone());
tracker.active = Some(state);
(None, live)
}
_ => (None, None),
}
_ => (None, None),
}
};
if started_edit {
set_transform_operator_status(
world,
OperatorPhase::Preview,
"Transform gizmo drag in progress",
);
return;
}
if let Some((primary, old_primary, group)) = live_edit {
let Some(new_primary) = world.get::<Transform>(primary).copied() else {
return;
@@ -2653,14 +2739,50 @@ fn capture_gizmo_transform_edits(world: &mut World) {
if let Some((primary, old_primary, group)) = finished_edit {
let Some(new_primary) = world.get::<Transform>(primary).copied() else {
for (entity, old) in group {
if let Some(mut transform) = world.get_mut::<Transform>(entity) {
*transform = old;
}
}
set_transform_operator_status(
world,
OperatorPhase::Canceled,
"Transform target disappeared; surviving previews restored",
);
return;
};
let undo_depth = world.resource::<EditorHistory>().undo_depth();
if group.len() <= 1 {
set_transform_with_history(world, primary, old_primary, new_primary);
return;
} else {
let changes = transform_group_changes(old_primary, new_primary, group);
set_transform_group_with_history(world, changes);
}
let changes = transform_group_changes(old_primary, new_primary, group);
set_transform_group_with_history(world, changes);
if world.resource::<EditorHistory>().undo_depth() > undo_depth {
set_transform_operator_status(
world,
OperatorPhase::Committed,
"Transform gizmo edit committed",
);
} else {
set_transform_operator_status(
world,
OperatorPhase::Canceled,
"Transform gizmo edit made no changes",
);
}
}
}
fn set_transform_operator_status(world: &mut World, phase: OperatorPhase, hint: impl Into<String>) {
if let Some(mut active) = world.get_resource_mut::<ActiveOperator>() {
active.status = Some(OperatorStatus {
id: "transform.gizmo".to_string(),
label: "Transform Gizmo".to_string(),
phase,
hint: hint.into(),
warnings: Vec::new(),
});
}
}
@@ -2804,7 +2926,7 @@ pub(crate) fn material_eq(a: &MaterialDesc, b: &MaterialDesc) -> bool {
mod tests {
use super::*;
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
use crate::operators::{ActiveOperator, OperatorPhase};
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq)]
#[reflect(Component, Default)]
@@ -3082,6 +3204,7 @@ mod tests {
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<TransformEditTracker>();
let first = world.spawn((LevelObject, Transform::default())).id();
let second = world
.spawn((
@@ -3093,30 +3216,19 @@ mod tests {
let committed = vec![Vec3::Z, Vec3::new(2.0, 0.0, 1.0)];
let harness = OperatorInvariantHarness::capture(&mut world);
set_transform_group_with_history(
&mut world,
[
(
first,
Transform::default(),
Transform::from_translation(committed[0]),
),
(
second,
Transform::from_translation(initial[1]),
Transform::from_translation(committed[1]),
),
world.resource_mut::<TransformEditTracker>().active = Some((
first,
Transform::default(),
vec![
(first, Transform::default()),
(second, Transform::from_translation(initial[1])),
],
);
world.resource_mut::<ActiveOperator>().status = Some(OperatorStatus {
id: "transform.gizmo".to_string(),
label: "Transform Gizmo".to_string(),
phase: OperatorPhase::Committed,
hint: "Committed multi-selection drag".to_string(),
warnings: Vec::new(),
});
));
*world.get_mut::<Transform>(first).unwrap() = Transform::from_translation(committed[0]);
capture_gizmo_transform_edits(&mut world);
harness.assert_committed(&mut world, 1, 0);
harness.assert_status(&world, "transform.gizmo", OperatorPhase::Committed);
assert_undo_redo_round_trip(&mut world, initial, committed, |world| {
[first, second]
.into_iter()
@@ -3125,6 +3237,63 @@ mod tests {
});
}
#[test]
fn no_op_transform_release_terminates_preview_without_history() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<TransformEditTracker>();
let transform = Transform::from_xyz(1.0, 2.0, 3.0);
let entity = world.spawn((LevelObject, transform)).id();
world.resource_mut::<TransformEditTracker>().active =
Some((entity, transform, vec![(entity, transform)]));
set_transform_operator_status(
&mut world,
OperatorPhase::Preview,
"Transform gizmo drag in progress",
);
let harness = OperatorInvariantHarness::capture(&mut world);
capture_gizmo_transform_edits(&mut world);
harness.assert_canceled(&mut world);
harness.assert_status(&world, "transform.gizmo", OperatorPhase::Canceled);
assert_eq!(world.get::<Transform>(entity), Some(&transform));
}
#[test]
fn missing_primary_transform_rolls_back_surviving_preview_targets() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<TransformEditTracker>();
let primary_old = Transform::from_xyz(1.0, 0.0, 0.0);
let survivor_old = Transform::from_xyz(2.0, 0.0, 0.0);
let primary = world.spawn((LevelObject, primary_old)).id();
let survivor = world.spawn((LevelObject, survivor_old)).id();
world.resource_mut::<TransformEditTracker>().active = Some((
primary,
primary_old,
vec![(primary, primary_old), (survivor, survivor_old)],
));
*world.get_mut::<Transform>(survivor).unwrap() = Transform::from_xyz(8.0, 0.0, 0.0);
world.despawn(primary);
set_transform_operator_status(
&mut world,
OperatorPhase::Preview,
"Transform gizmo drag in progress",
);
let harness = OperatorInvariantHarness::capture(&mut world);
capture_gizmo_transform_edits(&mut world);
harness.assert_canceled(&mut world);
harness.assert_status(&world, "transform.gizmo", OperatorPhase::Canceled);
assert_eq!(world.get::<Transform>(survivor), Some(&survivor_old));
}
#[test]
fn unpack_prefab_is_one_undoable_history_command() {
let mut world = World::new();
+15
View File
@@ -25,6 +25,7 @@ pub use play::state;
pub use project::collaboration;
pub use project::diagnostics_bundle;
pub use project::launcher;
pub use project::native_dialog;
pub use project::project_io;
pub use project::session;
pub use project::settings_ui;
@@ -37,10 +38,14 @@ pub use viewport::brush_edit;
pub use viewport::brush_tool;
pub use viewport::camera;
pub use viewport::gizmos;
pub use viewport::material_drop;
pub use viewport::physics_placement;
pub use viewport::render_view;
pub use viewport::rendering_diagnostics;
pub use viewport::selection;
pub use viewport::selection_outline;
pub use viewport::terrain_paint;
pub use viewport::terrain_sculpt;
pub use viewport::visualizers;
use bevy::app::PluginGroupBuilder;
@@ -62,10 +67,13 @@ use extensibility::ExtensibilityPlugin;
use gizmos::EditorGizmoPlugin;
use history::EditorHistoryPlugin;
use infra::EditorInfraPlugin;
use material_drop::MaterialDropPlugin;
use operators::OperatorPlugin;
use physics_placement::PhysicsPlacementPlugin;
use play::audio_preview::AudioPreviewPlugin;
use play::PlaySessionPlugin;
use project::collaboration::CollaborationPlugin;
use project::native_dialog::NativeDialogPlugin;
use project_io::ProjectIoPlugin;
use render_view::RenderViewPlugin;
use scene_io::SceneIoPlugin;
@@ -75,6 +83,8 @@ use selection_outline::SelectionOutlinePlugin;
use session::EditorSessionPlugin;
use settings_ui::SettingsUiPlugin;
use state::EditorStatePlugin;
use terrain_paint::TerrainPaintPlugin;
use terrain_sculpt::TerrainSculptPlugin;
use ui::EditorUiPlugin;
use viewport::ViewportPlugin;
use visualizers::EditorVisualizersPlugin;
@@ -88,6 +98,7 @@ impl PluginGroup for EditorPluginGroup {
let group = PluginGroupBuilder::start::<Self>()
.add(EditorInfraPlugin)
.add(ProjectIoPlugin)
.add(NativeDialogPlugin)
.add(scene_schema::SceneSchemaPlugin)
.add(net_editor::NetEditorPlugin)
.add(AssetDbPlugin)
@@ -104,9 +115,13 @@ impl PluginGroup for EditorPluginGroup {
.add(BrushCsgPlugin)
.add(BrushEditPlugin)
.add(BrushToolPlugin)
.add(TerrainSculptPlugin)
.add(TerrainPaintPlugin)
.add(EditorCameraPlugin)
.add(AudioPreviewPlugin)
.add(ActorIconsPlugin)
.add(MaterialDropPlugin)
.add(PhysicsPlacementPlugin)
.add(EditorSelectionPlugin)
.add(SelectionOutlinePlugin)
.add(EditorGizmoPlugin)
+97
View File
@@ -59,6 +59,12 @@ pub enum OperatorAvailability {
Disabled(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperatorAction {
Commit,
ContinuePreview,
}
pub trait EditorOperator {
fn id(&self) -> &str;
fn label(&self) -> &str;
@@ -221,6 +227,51 @@ pub fn run_immediate_operator(
run_operator(world, &mut operator)
}
/// Runs an editor command that may either complete immediately or hand ownership to a modal tool.
/// Modal starters retain the preview status installed by their production entry point.
pub fn run_operator_action(
world: &mut World,
id: &str,
label: &str,
availability: OperatorAvailability,
action: impl FnOnce(&mut World) -> Result<OperatorAction, String>,
) -> bool {
if let OperatorAvailability::Disabled(reason) = availability {
set_operator_status(
world,
OperatorStatus::new(id, label, OperatorPhase::Blocked, reason),
);
return false;
}
set_operator_status(
world,
OperatorStatus::new(id, label, OperatorPhase::Preview, "Starting"),
);
match action(world) {
Ok(OperatorAction::Commit) => {
set_operator_status(
world,
OperatorStatus::new(
id,
label,
OperatorPhase::Committed,
format!("Completed {label}"),
),
);
true
}
Ok(OperatorAction::ContinuePreview) => true,
Err(error) => {
set_operator_status(
world,
OperatorStatus::new(id, label, OperatorPhase::Canceled, error),
);
false
}
}
}
fn set_operator_status(world: &mut World, status: OperatorStatus) {
if let Some(mut active) = world.get_resource_mut::<ActiveOperator>() {
active.status = Some(status);
@@ -355,6 +406,52 @@ mod tests {
harness.assert_no_helpers::<PreviewHelper>(&mut world);
}
#[test]
fn preview_failure_runs_cancel_and_cleans_helpers() {
struct PreviewFailure(CounterOperator);
impl EditorOperator for PreviewFailure {
fn id(&self) -> &str {
self.0.id()
}
fn label(&self) -> &str {
self.0.label()
}
fn begin(&mut self, world: &mut World) -> Result<(), String> {
self.0.begin(world)
}
fn preview(&mut self, world: &mut World) -> Result<(), String> {
self.0.preview(world)?;
Err("preview failed".to_string())
}
fn commit(&mut self, _world: &mut World) -> Result<(), String> {
panic!("commit must not run after preview failure")
}
fn cancel(&mut self, world: &mut World) {
self.0.cancel(world);
}
}
let mut world = test_world();
let harness = OperatorInvariantHarness::capture(&mut world);
let mut operator = PreviewFailure(CounterOperator {
before: 0,
helper: None,
});
assert!(!run_operator(&mut world, &mut operator));
harness.assert_canceled(&mut world);
harness.assert_status(&world, "test.counter", OperatorPhase::Canceled);
harness.assert_no_helpers::<PreviewHelper>(&mut world);
assert_eq!(world.resource::<Counter>().0, 0);
}
#[test]
fn blocked_operator_never_begins_or_mutates_world() {
let mut world = test_world();
@@ -47,6 +47,12 @@ impl OperatorInvariantHarness {
world.resource::<SceneIo>().dirty,
"a committed authored mutation must mark the scene dirty"
);
} else {
assert_eq!(
world.resource::<SceneIo>().dirty,
self.dirty,
"a committed non-authoring operator must preserve the prior dirty state"
);
}
assert_eq!(
authored_count(world) as isize,
@@ -93,6 +99,39 @@ impl OperatorInvariantHarness {
);
}
pub(crate) fn assert_status(
&self,
world: &World,
expected_id: &str,
expected_phase: OperatorPhase,
) {
let status = world
.resource::<ActiveOperator>()
.status
.as_ref()
.expect("operator must retain an inspectable lifecycle status");
assert_eq!(status.id, expected_id, "operator reported the wrong id");
assert_eq!(
status.phase, expected_phase,
"operator reported the wrong phase"
);
}
pub(crate) fn assert_projection_unchanged<T>(
&self,
world: &mut World,
expected: T,
mut read: impl FnMut(&mut World) -> T,
) where
T: Debug + PartialEq,
{
assert_eq!(
read(world),
expected,
"operator changed authored state without a committed history transaction"
);
}
fn assert_phase(&self, world: &World, expected: OperatorPhase) {
let phase = world
.resource::<ActiveOperator>()
+51 -3
View File
@@ -1,9 +1,12 @@
use std::time::Duration;
use avian3d::prelude::{Physics, PhysicsTime};
use bevy::prelude::*;
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
use bevy_egui::PrimaryEguiContext;
use game::player::PlayerCamera;
use game::{GameInputEnabled, GameInputFocused, SimEnabled};
use protocol::PlayerInputIntent;
use protocol::{PlayerInputIntent, SIM_TICK_RATE_HZ};
use sim::{Crouching, Grounded, JumpState, Player, PlayerVelocity};
use crate::camera::EditorCamera;
@@ -195,6 +198,7 @@ pub(crate) fn sync_mode_resources_and_cameras(
mut step: ResMut<PlayStepOnce>,
mut input_enabled: ResMut<GameInputEnabled>,
mut sim_enabled: ResMut<SimEnabled>,
mut physics_time: ResMut<Time<Physics>>,
mut editor_cameras: Query<&mut Camera, With<EditorCamera>>,
mut player_cameras: Query<&mut Camera, (With<PlayerCamera>, Without<EditorCamera>)>,
mut egui_cameras: Query<
@@ -212,9 +216,11 @@ pub(crate) fn sync_mode_resources_and_cameras(
let ejected = playing && *possession == PlayPossession::Ejected;
let possessed = playing && *possession == PlayPossession::Possessed;
sim_enabled.0 = playing && (!paused.0 || step.0);
let stepping = step.0;
sim_enabled.0 = playing && (!paused.0 || stepping);
input_enabled.0 = possessed && !paused.0;
if step.0 {
sync_editor_physics_clock(&mut physics_time, playing, paused.0, stepping);
if stepping {
step.0 = false;
}
@@ -240,6 +246,22 @@ pub(crate) fn sync_mode_resources_and_cameras(
}
}
fn sync_editor_physics_clock(
physics_time: &mut Time<Physics>,
playing: bool,
paused: bool,
stepping: bool,
) {
if playing && !paused {
physics_time.unpause();
return;
}
physics_time.pause();
if playing && stepping {
physics_time.advance_by(Duration::from_secs_f64(1.0 / SIM_TICK_RATE_HZ as f64));
}
}
fn sync_play_input_focus(
mode: Res<State<EditorMode>>,
possession: Res<PlayPossession>,
@@ -414,3 +436,29 @@ pub fn toggle_play_possession_world(world: &mut World) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn editor_physics_clock_tracks_edit_play_pause_and_single_step() {
let mut time = Time::<Physics>::default();
sync_editor_physics_clock(&mut time, false, false, false);
assert!(time.is_paused());
sync_editor_physics_clock(&mut time, true, false, false);
assert!(!time.is_paused());
sync_editor_physics_clock(&mut time, true, true, false);
assert!(time.is_paused());
sync_editor_physics_clock(&mut time, true, true, true);
assert!(time.is_paused());
assert_eq!(
time.delta(),
Duration::from_secs_f64(1.0 / SIM_TICK_RATE_HZ as f64)
);
}
}
+28 -6
View File
@@ -15,6 +15,7 @@ use egui_phosphor_icons::icons;
use shared::PrefabInstance;
use crate::assets::EditorAssets;
use crate::native_dialog::NativeDialogBroker;
use crate::project_io::ProjectWorkspace;
use crate::scene::recovery::atomic_write_with_pre_rename;
use crate::scene_io::SceneIo;
@@ -880,13 +881,34 @@ fn resolve_conflict_reload(world: &mut World, conflict: &PendingFileConflict) {
}
fn resolve_conflict_save_as(world: &mut World, conflict: &PendingFileConflict) {
let directory = conflict.path.parent().unwrap_or_else(|| Path::new("."));
let conflict = conflict.clone();
let directory = conflict
.path
.parent()
.unwrap_or_else(|| Path::new("."))
.to_path_buf();
let file_name = conflict_copy_file_name(&conflict.path);
let Some(destination) = rfd::FileDialog::new()
.set_directory(directory)
.set_file_name(file_name)
.save_file()
else {
let request = world.resource::<NativeDialogBroker>().request(
move || {
rfd::FileDialog::new()
.set_directory(directory)
.set_file_name(file_name)
.save_file()
},
move |world, destination| finish_conflict_save_as(world, conflict, destination),
);
world.resource_mut::<SceneIo>().set_status(match request {
Ok(()) => "Choose a destination for the conflict copy".into(),
Err(error) => format!("Save As unavailable: {error}"),
});
}
fn finish_conflict_save_as(
world: &mut World,
conflict: PendingFileConflict,
destination: Option<PathBuf>,
) {
let Some(destination) = destination else {
world
.resource_mut::<SceneIo>()
.set_status("Save conflict copy cancelled");
+37 -5
View File
@@ -13,6 +13,7 @@ use settings::{
PROJECT_TEMPLATE_VERSION,
};
use crate::native_dialog::{NativeDialogBroker, NativeDialogPlugin};
use crate::project_io::UserPreferences;
use crate::scene::recovery::atomic_write;
use crate::ui::theme::{
@@ -91,6 +92,7 @@ pub fn run_project_launcher() {
..default()
}))
.add_plugins(EguiPlugin::default())
.add_plugins(NativeDialogPlugin)
.init_resource::<ProjectLauncherUi>()
.add_systems(Startup, spawn_project_launcher_camera)
.add_systems(EguiPrimaryContextPass, project_launcher_ui_system);
@@ -208,9 +210,24 @@ fn launcher_actions(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLau
egui::RichText::new("Select a root containing assets/project.ron").color(TEXT_DIM),
);
ui.add_space(8.0);
if ui.button("Browse Existing...").clicked() {
if let Some(root) = rfd::FileDialog::new().pick_folder() {
open_project_from_launcher(world, state, root);
let dialog_pending = world.resource::<NativeDialogBroker>().is_pending();
if ui
.add_enabled(!dialog_pending, egui::Button::new("Browse Existing..."))
.clicked()
{
let result = world.resource::<NativeDialogBroker>().request(
|| rfd::FileDialog::new().pick_folder(),
|world, root| {
let Some(root) = root else {
return;
};
world.resource_scope(|world, mut state: Mut<ProjectLauncherUi>| {
open_project_from_launcher(world, &mut state, root);
});
},
);
if let Err(error) = result {
state.status = Some(format!("Project browser unavailable: {error}"));
}
}
@@ -239,8 +256,23 @@ fn launcher_actions(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLau
)
.truncate(),
);
if ui.button("Choose Empty Folder...").clicked() {
state.sandbox_destination = rfd::FileDialog::new().pick_folder();
if ui
.add_enabled(!dialog_pending, egui::Button::new("Choose Empty Folder..."))
.clicked()
{
let result = world.resource::<NativeDialogBroker>().request(
|| rfd::FileDialog::new().pick_folder(),
|world, destination| {
if let Some(destination) = destination {
world
.resource_mut::<ProjectLauncherUi>()
.sandbox_destination = Some(destination);
}
},
);
if let Err(error) = result {
state.status = Some(format!("Folder browser unavailable: {error}"));
}
}
let can_create =
state.sandbox_destination.is_some() && !state.sandbox_name.trim().is_empty();
+1
View File
@@ -3,6 +3,7 @@
pub mod collaboration;
pub mod diagnostics_bundle;
pub mod launcher;
pub mod native_dialog;
pub mod project_io;
pub mod session;
pub mod settings_ui;
+171
View File
@@ -0,0 +1,171 @@
//! Non-blocking bridge between native dialogs and main-thread editor workflows.
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc, Mutex,
};
use bevy::prelude::*;
type MainThreadCompletion = Box<dyn FnOnce(&mut World) + Send + 'static>;
#[derive(Resource)]
pub struct NativeDialogBroker {
sender: Sender<MainThreadCompletion>,
receiver: Mutex<Receiver<MainThreadCompletion>>,
pending: Arc<AtomicUsize>,
}
impl Default for NativeDialogBroker {
fn default() -> Self {
let (sender, receiver) = mpsc::channel();
Self {
sender,
receiver: Mutex::new(receiver),
pending: Arc::new(AtomicUsize::new(0)),
}
}
}
impl NativeDialogBroker {
pub fn is_pending(&self) -> bool {
self.pending.load(Ordering::Acquire) > 0
}
pub fn request<T, D, C>(&self, dialog: D, completion: C) -> Result<(), &'static str>
where
T: Send + 'static,
D: FnOnce() -> T + Send + 'static,
C: FnOnce(&mut World, T) + Send + 'static,
{
if self
.pending
.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return Err("another native dialog is already open");
}
let sender = self.sender.clone();
let pending = Arc::clone(&self.pending);
std::thread::spawn(move || {
let result = dialog();
let callback: MainThreadCompletion = Box::new(move |world| completion(world, result));
if sender.send(callback).is_err() {
pending.store(0, Ordering::Release);
}
});
Ok(())
}
}
pub struct NativeDialogPlugin;
impl Plugin for NativeDialogPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<NativeDialogBroker>()
.add_systems(Update, drain_native_dialog_results);
}
}
fn drain_native_dialog_results(world: &mut World) {
let callbacks: Vec<_> = {
let broker = world.resource::<NativeDialogBroker>();
broker
.receiver
.lock()
.expect("native dialog receiver poisoned")
.try_iter()
.collect()
};
for callback in callbacks {
world
.resource::<NativeDialogBroker>()
.pending
.store(0, Ordering::Release);
callback(world);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Resource, Default)]
struct ResultValue(Option<u32>);
#[derive(Resource, Default)]
struct FrameCount(u32);
#[test]
fn request_is_exclusive_and_completion_runs_once() {
let mut app = App::new();
app.add_plugins(NativeDialogPlugin)
.init_resource::<ResultValue>();
app.world()
.resource::<NativeDialogBroker>()
.request(
|| 42,
|world, value| world.resource_mut::<ResultValue>().0 = Some(value),
)
.unwrap();
assert!(app
.world()
.resource::<NativeDialogBroker>()
.request(|| 7, |_, _| {})
.is_err());
for _ in 0..100 {
app.update();
if app.world().resource::<ResultValue>().0.is_some() {
break;
}
std::thread::yield_now();
}
assert_eq!(app.world().resource::<ResultValue>().0, Some(42));
app.update();
assert_eq!(app.world().resource::<ResultValue>().0, Some(42));
assert!(!app.world().resource::<NativeDialogBroker>().is_pending());
}
#[test]
fn blocked_dialog_worker_does_not_block_app_frames() {
let mut app = App::new();
app.add_plugins(NativeDialogPlugin)
.init_resource::<ResultValue>()
.init_resource::<FrameCount>()
.add_systems(Update, |mut frames: ResMut<FrameCount>| frames.0 += 1);
let (release_sender, release_receiver) = mpsc::channel();
app.world()
.resource::<NativeDialogBroker>()
.request(
move || {
release_receiver
.recv()
.expect("test release sender dropped")
},
|world, value| world.resource_mut::<ResultValue>().0 = Some(value),
)
.unwrap();
for _ in 0..8 {
app.update();
}
assert_eq!(app.world().resource::<FrameCount>().0, 8);
assert_eq!(app.world().resource::<ResultValue>().0, None);
assert!(app.world().resource::<NativeDialogBroker>().is_pending());
release_sender.send(73).unwrap();
for _ in 0..100 {
app.update();
if app.world().resource::<ResultValue>().0.is_some() {
break;
}
std::thread::yield_now();
}
assert_eq!(app.world().resource::<ResultValue>().0, Some(73));
assert!(app.world().resource::<FrameCount>().0 > 8);
assert!(!app.world().resource::<NativeDialogBroker>().is_pending());
}
}
+220 -125
View File
@@ -23,6 +23,7 @@ use shared::{
use crate::assets::{import_external_assets, EditorAssets, IMPORTABLE_ASSET_EXTENSIONS};
use crate::history::{clear_level_objects, snapshot_entity, EditorHistory};
use crate::native_dialog::NativeDialogBroker;
use crate::project::collaboration::{publish_authored_file, FileSnapshot, FileWriteIntent};
use crate::scene::recovery::{
default_state_root, discard_recovery_snapshots, latest_recovery_snapshot,
@@ -82,8 +83,6 @@ pub struct SceneIo {
pub request: Option<SceneIoRequest>,
pub status: String,
pub dirty: bool,
/// When set, the next I/O request needs unsaved-changes confirmation.
pub pending_request: Option<SceneIoRequest>,
/// Newest recovery snapshot that is newer than the active authored scene.
pub recovery_snapshot: Option<PathBuf>,
/// Bounded in-session audit trail for scene persistence and recovery operations.
@@ -119,7 +118,6 @@ impl Default for SceneIo {
request: None,
status: "Ready".to_string(),
dirty: false,
pending_request: None,
recovery_snapshot: None,
events: VecDeque::new(),
tabs: vec![SceneTab {
@@ -291,39 +289,15 @@ fn load_startup_scene(world: &mut World) {
}
fn process_scene_io_requests(world: &mut World) {
let request = {
let mut io = world.resource_mut::<SceneIo>();
if let Some(pending) = io.pending_request.take() {
pending
} else {
match io.request.take() {
Some(req) if io.has_unsaved_tabs() && needs_dirty_confirm(&req) => {
io.pending_request = Some(req);
return;
}
Some(req) => req,
None => return,
}
}
let Some(request) = world.resource_mut::<SceneIo>().request.take() else {
return;
};
if world.resource::<SceneIo>().has_unsaved_tabs() && needs_dirty_confirm(&request) {
match confirm_discard_or_save() {
DirtyConfirm::Save => {
let save_status = save_all_tabs(world);
if save_status.starts_with("Save failed") || save_status.ends_with("cancelled") {
world.resource_mut::<SceneIo>().set_status(save_status);
return;
}
}
DirtyConfirm::Discard => {}
DirtyConfirm::Cancel => {
world
.resource_mut::<SceneIo>()
.set_status("Operation cancelled");
return;
}
}
if matches!(request, SceneIoRequest::SwitchProject)
&& world.resource::<SceneIo>().has_unsaved_tabs()
{
request_switch_project_confirmation(world);
return;
}
let status = match request {
@@ -348,16 +322,6 @@ fn process_scene_io_requests(world: &mut World) {
world.resource_mut::<SceneIo>().set_status(status);
}
enum DirtyConfirm {
Save,
Discard,
Cancel,
}
fn needs_dirty_confirm(request: &SceneIoRequest) -> bool {
matches!(request, SceneIoRequest::SwitchProject)
}
fn switch_project(world: &mut World) -> String {
match crate::launcher::spawn_project_launcher_process() {
Ok(()) => {
@@ -368,19 +332,41 @@ fn switch_project(world: &mut World) -> String {
}
}
fn confirm_discard_or_save() -> DirtyConfirm {
use rfd::{MessageButtons, MessageDialog, MessageLevel};
match MessageDialog::new()
.set_title("Unsaved Changes")
.set_description("The scene has unsaved changes. Save before continuing?")
.set_level(MessageLevel::Warning)
.set_buttons(MessageButtons::YesNoCancel)
.show()
{
rfd::MessageDialogResult::Yes => DirtyConfirm::Save,
rfd::MessageDialogResult::No => DirtyConfirm::Discard,
_ => DirtyConfirm::Cancel,
}
fn request_switch_project_confirmation(world: &mut World) {
let result = world.resource::<NativeDialogBroker>().request(
|| {
rfd::MessageDialog::new()
.set_title("Unsaved Changes")
.set_description("The scene has unsaved changes. Save before continuing?")
.set_level(rfd::MessageLevel::Warning)
.set_buttons(rfd::MessageButtons::YesNoCancel)
.show()
},
|world, decision| match decision {
rfd::MessageDialogResult::Yes => {
let status = save_all_tabs(world);
if status == "Saved all modified scene tabs" {
let status = switch_project(world);
world.resource_mut::<SceneIo>().set_status(status);
} else {
world.resource_mut::<SceneIo>().set_status(format!(
"Project switch paused until every scene is saved: {status}"
));
}
}
rfd::MessageDialogResult::No => {
let status = switch_project(world);
world.resource_mut::<SceneIo>().set_status(status);
}
_ => world
.resource_mut::<SceneIo>()
.set_status("Project switch cancelled"),
},
);
world.resource_mut::<SceneIo>().set_status(match result {
Ok(()) => "Waiting for unsaved-scene confirmation".into(),
Err(error) => format!("Project switch unavailable: {error}"),
});
}
fn open_recent(world: &mut World, index: usize) -> String {
@@ -533,18 +519,14 @@ fn close_scene_tab(world: &mut World, index: usize) -> String {
}
if world.resource::<SceneIo>().dirty {
match confirm_close_scene() {
DirtyConfirm::Save => {
let status = save_active_or_prompt(world);
if status.starts_with("Save failed") || status.ends_with("cancelled") {
return status;
}
}
DirtyConfirm::Discard => {}
DirtyConfirm::Cancel => return "Close scene cancelled".to_string(),
}
request_close_scene_confirmation(world);
return "Waiting for close-scene confirmation".to_string();
}
finish_close_scene_tab(world)
}
fn finish_close_scene_tab(world: &mut World) -> String {
if world.resource::<SceneIo>().tabs.len() == 1 {
clear_scene_world(world);
world.insert_resource(SceneComposition {
@@ -618,18 +600,36 @@ fn reload_active_composition(world: &mut World) -> String {
"Reloaded active scene composition".to_string()
}
fn confirm_close_scene() -> DirtyConfirm {
use rfd::{MessageButtons, MessageDialog, MessageLevel};
match MessageDialog::new()
.set_title("Close Scene")
.set_description("This scene tab has unsaved changes. Save before closing it?")
.set_level(MessageLevel::Warning)
.set_buttons(MessageButtons::YesNoCancel)
.show()
{
rfd::MessageDialogResult::Yes => DirtyConfirm::Save,
rfd::MessageDialogResult::No => DirtyConfirm::Discard,
_ => DirtyConfirm::Cancel,
fn request_close_scene_confirmation(world: &mut World) {
let result = world.resource::<NativeDialogBroker>().request(
|| {
rfd::MessageDialog::new()
.set_title("Close Scene")
.set_description("This scene tab has unsaved changes. Save before closing it?")
.set_level(rfd::MessageLevel::Warning)
.set_buttons(rfd::MessageButtons::YesNoCancel)
.show()
},
|world, decision| {
let status = match decision {
rfd::MessageDialogResult::Yes => {
let save_status = save_active_or_prompt(world);
if save_status.starts_with("Saved ") {
finish_close_scene_tab(world)
} else {
format!("Close scene paused until it is saved: {save_status}")
}
}
rfd::MessageDialogResult::No => finish_close_scene_tab(world),
_ => "Close scene cancelled".to_string(),
};
world.resource_mut::<SceneIo>().set_status(status);
},
);
if let Err(error) = result {
world
.resource_mut::<SceneIo>()
.set_status(format!("Close scene unavailable: {error}"));
}
}
@@ -694,12 +694,31 @@ fn save_selection_as_prefab(world: &mut World) -> String {
return "Select level objects to save as prefab".to_string();
}
let Some(path) = rfd::FileDialog::new()
.set_directory("assets/prefabs")
.add_filter("Bevy prefab", &["scn.ron", "ron"])
.set_file_name("prefab.scn.ron")
.save_file()
else {
let request = world.resource::<NativeDialogBroker>().request(
|| {
rfd::FileDialog::new()
.set_directory("assets/prefabs")
.add_filter("Bevy prefab", &["scn.ron", "ron"])
.set_file_name("prefab.scn.ron")
.save_file()
},
move |world, path| {
let status = finish_save_selection_as_prefab(world, selection, path);
world.resource_mut::<SceneIo>().set_status(status);
},
);
match request {
Ok(()) => "Choose a destination for the prefab".to_string(),
Err(error) => format!("Save prefab unavailable: {error}"),
}
}
fn finish_save_selection_as_prefab(
world: &mut World,
selection: Vec<Entity>,
path: Option<PathBuf>,
) -> String {
let Some(path) = path else {
return "Save prefab cancelled".to_string();
};
let expected = match FileSnapshot::capture(&path) {
@@ -859,12 +878,27 @@ fn save_active_or_prompt(world: &mut World) -> String {
}
fn save_with_dialog(world: &mut World) -> String {
let Some(path) = rfd::FileDialog::new()
.set_directory("assets/levels")
.add_filter("Bevy scene", &["scn.ron", "ron"])
.set_file_name("editor_scene.scn.ron")
.save_file()
else {
let request = world.resource::<NativeDialogBroker>().request(
|| {
rfd::FileDialog::new()
.set_directory("assets/levels")
.add_filter("Bevy scene", &["scn.ron", "ron"])
.set_file_name("editor_scene.scn.ron")
.save_file()
},
|world, path| {
let status = finish_save_with_dialog(world, path);
world.resource_mut::<SceneIo>().set_status(status);
},
);
match request {
Ok(()) => "Choose a scene destination".to_string(),
Err(error) => format!("Save unavailable: {error}"),
}
}
fn finish_save_with_dialog(world: &mut World, path: Option<PathBuf>) -> String {
let Some(path) = path else {
return "Save cancelled".to_string();
};
let expected = match FileSnapshot::capture(&path) {
@@ -885,31 +919,51 @@ fn save_with_dialog(world: &mut World) -> String {
}
fn open_with_dialog(world: &mut World) -> String {
let Some(path) = rfd::FileDialog::new()
.set_directory("assets/levels")
.add_filter("Bevy scene", &["scn.ron", "ron"])
.pick_file()
else {
return "Open cancelled".to_string();
};
open_path(world, path)
let request = world.resource::<NativeDialogBroker>().request(
|| {
rfd::FileDialog::new()
.set_directory("assets/levels")
.add_filter("Bevy scene", &["scn.ron", "ron"])
.pick_file()
},
|world, path| {
let status = path.map_or_else(
|| "Open cancelled".to_string(),
|path| open_path(world, path),
);
world.resource_mut::<SceneIo>().set_status(status);
},
);
match request {
Ok(()) => "Choose a scene to open".to_string(),
Err(error) => format!("Open unavailable: {error}"),
}
}
fn import_with_dialog(world: &mut World) -> String {
let Some(paths) = rfd::FileDialog::new()
.add_filter("Editor assets", IMPORTABLE_ASSET_EXTENSIONS)
.pick_files()
else {
return "Import cancelled".to_string();
};
match import_external_assets(&paths) {
Ok(count) => {
world.resource_mut::<EditorAssets>().refresh();
format!("Imported {count} asset(s)")
}
Err(err) => format!("Import failed: {err}"),
let request = world.resource::<NativeDialogBroker>().request(
|| {
rfd::FileDialog::new()
.add_filter("Editor assets", IMPORTABLE_ASSET_EXTENSIONS)
.pick_files()
},
|world, paths| {
let status = match paths {
None => "Import cancelled".to_string(),
Some(paths) => match import_external_assets(&paths) {
Ok(count) => {
world.resource_mut::<EditorAssets>().refresh();
format!("Imported {count} asset(s)")
}
Err(err) => format!("Import failed: {err}"),
},
};
world.resource_mut::<SceneIo>().set_status(status);
},
);
match request {
Ok(()) => "Choose assets to import".to_string(),
Err(error) => format!("Import unavailable: {error}"),
}
}
@@ -921,14 +975,32 @@ fn export_selection_with_dialog(world: &mut World) -> String {
return "Selected entity is not an authored level object".to_string();
}
let Some(path) = rfd::FileDialog::new()
.set_directory("assets/levels")
.add_filter("Bevy prefab", &["scn.ron", "ron"])
.set_file_name("selection.scn.ron")
.save_file()
else {
let request = world.resource::<NativeDialogBroker>().request(
|| {
rfd::FileDialog::new()
.set_directory("assets/levels")
.add_filter("Bevy prefab", &["scn.ron", "ron"])
.set_file_name("selection.scn.ron")
.save_file()
},
move |world, path| {
let status = finish_export_selection(world, entity, path);
world.resource_mut::<SceneIo>().set_status(status);
},
);
match request {
Ok(()) => "Choose an export destination".to_string(),
Err(error) => format!("Export unavailable: {error}"),
}
}
fn finish_export_selection(world: &mut World, entity: Entity, path: Option<PathBuf>) -> String {
let Some(path) = path else {
return "Export cancelled".to_string();
};
if snapshot_entity(world, entity).is_none() {
return "Export failed: the initiating selection no longer exists".to_string();
}
let expected = match FileSnapshot::capture(&path) {
Ok(expected) => expected,
Err(error) => return format!("Export failed: {error}"),
@@ -1041,6 +1113,9 @@ fn format_actor_validation(err: ActorValidationError) -> String {
ActorValidationError::InvalidBrushGeometry(message) => {
format!("Save failed: invalid brush geometry: {message}")
}
ActorValidationError::InvalidTerrain(message) => {
format!("Save failed: invalid terrain: {message}")
}
ActorValidationError::StaticMeshMissingPrimitive => {
"Save failed: StaticMesh actor requires Primitive or StaticMeshRenderer with a mesh slot"
.into()
@@ -1607,12 +1682,32 @@ fn save_recovery_copy_with_dialog(world: &mut World) -> String {
|| "recovered_scene.scn.ron".to_string(),
|stem| format!("{stem}.recovered.scn.ron"),
);
let Some(destination) = rfd::FileDialog::new()
.set_directory(directory)
.add_filter("Bevy scene", &["scn.ron", "ron"])
.set_file_name(file_name)
.save_file()
else {
let directory = directory.to_path_buf();
let request = world.resource::<NativeDialogBroker>().request(
move || {
rfd::FileDialog::new()
.set_directory(directory)
.add_filter("Bevy scene", &["scn.ron", "ron"])
.set_file_name(file_name)
.save_file()
},
move |world, destination| {
let status = finish_save_recovery_copy(world, snapshot, destination);
world.resource_mut::<SceneIo>().set_status(status);
},
);
match request {
Ok(()) => "Choose a destination for the recovery copy".to_string(),
Err(error) => format!("Save recovery copy unavailable: {error}"),
}
}
fn finish_save_recovery_copy(
world: &mut World,
snapshot: PathBuf,
destination: Option<PathBuf>,
) -> String {
let Some(destination) = destination else {
return "Save recovery copy cancelled".to_string();
};
let expected = match FileSnapshot::capture(&destination) {
@@ -112,6 +112,7 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::Brush
| ActorKind::Terrain
| ActorKind::ImportedModel
| ActorKind::Light
| ActorKind::Empty
@@ -143,6 +144,7 @@ fn actor_icon(kind: ActorKind) -> egui_phosphor_icons::Icon {
ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::Brush
| ActorKind::Terrain
| ActorKind::ImportedModel => icons::CUBE,
ActorKind::Light => icons::LIGHTBULB,
ActorKind::PrefabAnchor => icons::PACKAGE,
+6 -2
View File
@@ -1855,7 +1855,7 @@ fn details_panel(world: &mut World, ui: &mut egui::Ui, selected_entities: &Selec
}
}
fn top_level_asset_details_panel(
pub(crate) fn top_level_asset_details_panel(
world: &mut World,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
@@ -2524,7 +2524,11 @@ fn save_material_draft(world: &mut World) {
}
}
fn create_material_instance_from_base(world: &mut World, base_path: &str, base_label: &str) {
pub(crate) fn create_material_instance_from_base(
world: &mut World,
base_path: &str,
base_label: &str,
) {
let base_reference = world
.get_resource_mut::<crate::asset_db::AssetRegistry>()
.ok_or_else(|| "Asset registry is unavailable".to_string())
@@ -373,6 +373,27 @@ impl Default for EditorComponentRegistry {
],
hydration_effect: "Hydrates into generated brush mesh children.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_TERRAIN,
type_name: "shared::components::TerrainDesc",
display_name: "Terrain",
category: EditorComponentCategory::Authoring,
addable: true,
removable: true,
reorderable: true,
hidden: false,
icon: icons::MOUNTAINS.as_str(),
description: "Creates chunked height-grid terrain with optional collision.",
search_terms: &["terrain", "landscape", "heightmap", "ground", "chunk"],
recommended: &[],
conflicts_with: &[
"shared::components::Primitive",
"shared::components::BrushDesc",
"shared::components::StaticMeshRenderer",
"shared::animation::SkinnedMeshRenderer",
],
hydration_effect: "Hydrates into generated render and collider chunks.",
},
EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_MATERIAL,
type_name: "shared::components::MaterialDesc",
+73
View File
@@ -15,6 +15,9 @@ use crate::project_io::ProjectWorkspace;
use crate::scene_io::{SceneIo, SceneIoEventSeverity};
use crate::selection::SelectedEntity;
use crate::ui::UiState;
use crate::viewport::collider_diagnostics::{
ColliderDiagnosticSeverity, ColliderDiagnosticsState, ColliderOverlayStatus,
};
#[derive(Resource, Default)]
pub struct DiagnosticsPanel {
@@ -138,6 +141,9 @@ pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
}
}
ui.separator();
collider_diagnostics_ui(world, ui);
ui.separator();
ui.horizontal(|ui| {
ui.strong("Support bundle");
@@ -193,6 +199,73 @@ pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
ui.small("BRP is enabled on the editor for external tooling.");
}
fn collider_diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
let Some(state) = world.get_resource::<ColliderDiagnosticsState>() else {
return;
};
let mut rows = state.entries.values().cloned().collect::<Vec<_>>();
rows.sort_by(|left, right| left.actor_name.cmp(&right.actor_name));
let valid = state.valid_actors;
let disabled = state.disabled_actors;
let warnings = state.warning_actors;
let errors = state.error_actors;
ui.horizontal_wrapped(|ui| {
ui.strong("Collider health");
ui.colored_label(
egui::Color32::from_rgb(125, 210, 145),
format!("{valid} ready"),
);
if disabled > 0 {
ui.colored_label(
egui::Color32::from_rgb(143, 151, 163),
format!("{disabled} disabled"),
);
}
if warnings > 0 {
ui.colored_label(
egui::Color32::from_rgb(242, 173, 72),
format!("{warnings} warning"),
);
}
if errors > 0 {
ui.colored_label(
egui::Color32::from_rgb(244, 91, 99),
format!("{errors} invalid"),
);
}
});
for row in rows.into_iter().filter(|row| {
matches!(
row.overlay_status,
ColliderOverlayStatus::Warning | ColliderOverlayStatus::Error
)
}) {
ui.horizontal_wrapped(|ui| {
let color = match row.overlay_status {
ColliderOverlayStatus::Error => egui::Color32::from_rgb(244, 91, 99),
_ => egui::Color32::from_rgb(242, 173, 72),
};
ui.colored_label(color, row.shape_label);
ui.label(&row.actor_name);
if ui.small_button("Select").clicked() {
world.resource_mut::<SelectedEntity>().0 = Some(row.entity);
world
.resource_mut::<UiState>()
.selected_entities
.select_replace(row.entity);
}
});
for diagnostic in &row.diagnostics {
if diagnostic.severity == ColliderDiagnosticSeverity::Info {
continue;
}
ui.small(format!("{}: {}", diagnostic.code, diagnostic.message));
}
}
}
pub fn brush_diagnostics_window(world: &mut World, ctx: &egui::Context, open: &mut bool) {
if !*open {
return;
+11 -5
View File
@@ -36,7 +36,10 @@ impl PanelNodes {
EditorTab::Viewport | EditorTab::GameView => self.main_view(),
EditorTab::Hierarchy => self.hierarchy(),
EditorTab::Inspector => self.inspector(),
EditorTab::AssetBrowser | EditorTab::Build | EditorTab::Toolbar => self.bottom(),
EditorTab::AssetBrowser
| EditorTab::MaterialLibrary
| EditorTab::Build
| EditorTab::Toolbar => self.bottom(),
}
}
@@ -51,20 +54,22 @@ impl PanelNodes {
EditorTab::Viewport | EditorTab::GameView => nodes.main_view = path.node.0,
EditorTab::Hierarchy => nodes.hierarchy = path.node.0,
EditorTab::Inspector => nodes.inspector = path.node.0,
EditorTab::AssetBrowser | EditorTab::Build | EditorTab::Toolbar => {
nodes.bottom = path.node.0
}
EditorTab::AssetBrowser
| EditorTab::MaterialLibrary
| EditorTab::Build
| EditorTab::Toolbar => nodes.bottom = path.node.0,
}
}
nodes
}
}
pub const PANEL_TABS: [EditorTab; 5] = [
pub const PANEL_TABS: [EditorTab; 6] = [
EditorTab::Viewport,
EditorTab::Hierarchy,
EditorTab::Inspector,
EditorTab::AssetBrowser,
EditorTab::MaterialLibrary,
EditorTab::Build,
];
@@ -74,6 +79,7 @@ pub fn tab_label(tab: &EditorTab) -> &'static str {
EditorTab::Hierarchy => "Hierarchy",
EditorTab::Inspector => "Inspector",
EditorTab::AssetBrowser => "Asset Browser",
EditorTab::MaterialLibrary => "Material Library",
EditorTab::Build => "Build",
EditorTab::Toolbar => "Toolbar (legacy)",
}
+13 -24
View File
@@ -11,7 +11,10 @@ use sim::Player;
use crate::assets::{snapshot_for_asset, EditorAsset, EditorAssetKind};
use crate::camera::EditorCamera;
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
use crate::history::{set_material_group_with_history, spawn_with_history, EditorEntitySnapshot};
use crate::history::{
set_light_group_with_history, set_material_group_with_history, spawn_with_history,
EditorEntitySnapshot,
};
use crate::play::default_player_spawn;
use crate::scene_io::SceneIo;
use crate::viewport::{recall_camera_bookmark, save_camera_bookmark, CameraBookmarks};
@@ -191,37 +194,23 @@ pub fn ensure_player_spawn_for_edit(world: &mut World) -> Entity {
/// Removes all authored [`LightDesc`] so project sun/ambient drive outdoor lighting.
pub fn reset_scene_lighting_to_project_defaults(world: &mut World) {
let mut query = world.query_filtered::<Entity, With<LevelObject>>();
let with_lights: Vec<Entity> = query
let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>();
let changes = query
.iter(world)
.filter(|entity| world.get::<LightDesc>(*entity).is_some())
.collect();
for entity in with_lights {
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.remove::<LightDesc>();
}
}
world
.resource_mut::<crate::scene_io::SceneIo>()
.mark_dirty();
.map(|(entity, _)| (entity, None))
.collect::<Vec<_>>();
set_light_group_with_history(world, changes, "Reset Scene Lighting");
}
/// Removes authored directional lights so [`ProjectSun`] drives outdoor lighting.
pub fn use_project_sun(world: &mut World) {
let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>();
let directionals: Vec<Entity> = query
let changes = query
.iter(world)
.filter(|(_, light)| matches!(light.kind, AuthoringLightKind::Directional))
.map(|(e, _)| e)
.collect();
for entity in directionals {
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.remove::<LightDesc>();
}
}
world
.resource_mut::<crate::scene_io::SceneIo>()
.mark_dirty();
.map(|(entity, _)| (entity, None))
.collect::<Vec<_>>();
set_light_group_with_history(world, changes, "Use Project Sun");
}
pub fn create_scene_sun_override_from_project_settings(world: &mut World) -> Entity {
+2
View File
@@ -205,6 +205,7 @@ fn actor_kind_sort_key(world: &World, entity: Entity) -> u8 {
.map(|kind| match kind {
ActorKind::Empty => 0,
ActorKind::Brush
| ActorKind::Terrain
| ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::ImportedModel => 1,
@@ -468,6 +469,7 @@ pub fn actor_kind_icon(kind: ActorKind) -> &'static str {
match kind {
ActorKind::Empty => icons::FOLDER.as_str(),
ActorKind::Brush => icons::CUBE.as_str(),
ActorKind::Terrain => icons::MOUNTAINS.as_str(),
ActorKind::StaticMesh => icons::CUBE.as_str(),
ActorKind::SkinnedMesh => icons::PERSON_SIMPLE_RUN.as_str(),
ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(),
+442 -15
View File
@@ -16,8 +16,8 @@ use shared::{
MaterialParameterValue, MaterialRef, MaterialShaderKind, NavigationArea, NavigationBounds,
NavigationLink, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn,
PostProcessVolumeDesc, PrefabInstance, Primitive, PrimitiveShape, ProjectSun, RigidBodyDesc,
SkinnedMeshRenderer, StaticMeshRenderer, StaticMeshRendererEntry, TeamSpawn, TriggerVolume,
WeaponSpawn, AUTHORING_DIRECTIONAL_LUX_MAX, AUTHORING_POINT_SPOT_LUMENS_MAX,
SkinnedMeshRenderer, StaticMeshRenderer, StaticMeshRendererEntry, TeamSpawn, TerrainDesc,
TriggerVolume, WeaponSpawn, AUTHORING_DIRECTIONAL_LUX_MAX, AUTHORING_POINT_SPOT_LUMENS_MAX,
COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_AUDIO_LISTENER_DESC,
COMPONENT_AUDIO_SOURCE_DESC, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
COMPONENT_LIGHT_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_NAVIGATION_AREA,
@@ -25,8 +25,8 @@ use shared::{
COMPONENT_OBJECTIVE_MARKER, COMPONENT_PHYSICS_BODY, COMPONENT_PLAYER_SPAWN,
COMPONENT_POST_PROCESS_VOLUME, COMPONENT_PREFAB_INSTANCE, COMPONENT_PRIMITIVE,
COMPONENT_PROJECT_SUN, COMPONENT_RIGID_BODY_DESC, COMPONENT_SKINNED_MESH_RENDERER,
COMPONENT_STATIC_MESH_RENDERER, COMPONENT_TEAM_SPAWN, COMPONENT_TRIGGER_VOLUME,
COMPONENT_WEAPON_SPAWN,
COMPONENT_STATIC_MESH_RENDERER, COMPONENT_TEAM_SPAWN, COMPONENT_TERRAIN_DESC,
COMPONENT_TRIGGER_VOLUME, COMPONENT_WEAPON_SPAWN,
};
use crate::history::{
@@ -44,6 +44,9 @@ use crate::ui::theme::{
};
use crate::ui::widgets::{icon_button_small, phosphor_icon, phosphor_icon_text};
use crate::viewport::brush_edit::{BrushElementKey, BrushElementSelection};
use crate::viewport::collider_diagnostics::{
diagnose_collider, ColliderDiagnosticSeverity, ColliderOverlayStatus,
};
use super::component_registry::{
EditorComponentCategory, EditorComponentDescriptor, EditorComponentRegistry,
@@ -1110,6 +1113,7 @@ fn draw_authoring_component_by_type(
COMPONENT_STATIC_MESH_RENDERER => static_mesh_renderer_ui(world, ui, entity),
COMPONENT_SKINNED_MESH_RENDERER => skinned_mesh_renderer_ui(world, ui, entity),
COMPONENT_BRUSH_DESC => brush_editor_ui(world, ui, entity),
COMPONENT_TERRAIN_DESC => terrain_editor_ui(world, ui, entity),
COMPONENT_PRIMITIVE => primitive_editor_ui(world, ui, entity),
COMPONENT_MATERIAL_DESC => material_editor_ui(world, ui, entity),
COMPONENT_LIGHT_DESC => light_editor_ui(world, ui, entity),
@@ -3494,6 +3498,325 @@ fn brush_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
}
}
fn terrain_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let material_candidates = brush_face_material_ref_candidates(world);
let dragging_selection = world
.get_resource::<EditorAssets>()
.and_then(|assets| assets.dragging_selection().cloned());
let material_drop_candidate = dragging_selection.as_ref().and_then(|selection| {
asset_ref_candidate_from_selection(world, selection, AssetRefCandidateKind::Material)
});
let Some(mut terrain) = world.get::<TerrainDesc>(entity).cloned() else {
return;
};
let original = terrain.clone();
let mut changed = false;
let mut requested_resolution = terrain.resolution;
let mut remove_layer = None;
let mut swap_layers = None;
let mut locate_layer = None;
let mut accepted_drop = false;
let card = component_card_context(
world,
entity,
ComponentCardOptions::removable(COMPONENT_TERRAIN_DESC, "Terrain", icons::MOUNTAINS),
);
let card_response = component_card(ui, &card, |ui| {
property_row(ui, "Grid", |ui| {
ui.horizontal(|ui| {
ui.add(
egui::DragValue::new(&mut requested_resolution)
.range(2..=1025)
.suffix(" samples"),
);
if ui
.add_enabled(
requested_resolution != terrain.resolution,
egui::Button::new("Resize Flat"),
)
.on_hover_text("Replaces the current height grid with a flat grid")
.clicked()
{
let replacement = TerrainDesc::flat(requested_resolution);
terrain.resolution = replacement.resolution;
terrain.heights = replacement.heights;
terrain.material_weights.clear();
terrain.chunk_quads = terrain.chunk_quads.min(terrain.resolution - 1).max(1);
changed = true;
}
});
});
property_row(ui, "Sample Spacing", |ui| {
changed |= ui
.add(
egui::DragValue::new(&mut terrain.sample_spacing)
.range(0.01..=1000.0)
.speed(0.1)
.suffix(" m"),
)
.changed();
});
property_row(ui, "Height Scale", |ui| {
changed |= ui
.add(
egui::DragValue::new(&mut terrain.height_scale)
.range(0.01..=10000.0)
.speed(0.1)
.suffix(" m"),
)
.changed();
});
property_row(ui, "Chunk Size", |ui| {
changed |= ui
.add(
egui::DragValue::new(&mut terrain.chunk_quads)
.range(1..=terrain.resolution.saturating_sub(1))
.suffix(" quads"),
)
.changed();
});
property_row(ui, "Collision", |ui| {
changed |= ui
.checkbox(&mut terrain.generate_colliders, "Generate")
.changed();
});
property_row(ui, "Shadows", |ui| {
ui.horizontal_wrapped(|ui| {
changed |= ui.checkbox(&mut terrain.cast_shadows, "Cast").changed();
changed |= ui
.checkbox(&mut terrain.receive_shadows, "Receive")
.changed();
});
});
ui.add_space(6.0);
ui.separator();
ui.horizontal(|ui| {
ui.label(egui::RichText::new("Material Layers").strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui
.add_enabled(
terrain.material_layers.len() < shared::TERRAIN_MATERIAL_LAYER_LIMIT,
egui::Button::new(phosphor_icon(icons::PLUS, 16.0)),
)
.on_hover_text("Add a terrain blend channel")
.clicked()
{
let material = if terrain.material_layers.is_empty() {
terrain.base_material.take()
} else {
None
};
terrain.material_layers.push(shared::TerrainMaterialLayer {
material,
..Default::default()
});
changed = true;
}
});
});
if terrain.material_layers.is_empty() {
ui.label(
egui::RichText::new(
terrain
.base_material
.as_ref()
.map(|material| format!("Legacy base: {}", material.label))
.unwrap_or_else(|| "No layers assigned; visible terrain fallback".into()),
)
.color(TEXT_DIM)
.small(),
);
}
for index in 0..terrain.material_layers.len() {
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.label(
egui::RichText::new(format!("Layer {}", index + 1))
.strong()
.color(if index == 0 {
SELECTION_BG_MUTED
} else {
TEXT_DIM
}),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if icon_button_small(ui, icons::TRASH, "Remove layer").clicked() {
remove_layer = Some(index);
}
if ui
.add_enabled(
index + 1 < terrain.material_layers.len(),
egui::Button::new(phosphor_icon(icons::ARROW_DOWN, 15.0)).frame(false),
)
.on_hover_text("Move layer down")
.clicked()
{
swap_layers = Some((index, index + 1));
}
if ui
.add_enabled(
index > 0,
egui::Button::new(phosphor_icon(icons::ARROW_UP, 15.0)).frame(false),
)
.on_hover_text("Move layer up")
.clicked()
{
swap_layers = Some((index, index - 1));
}
});
});
let response = asset_selector_row(
ui,
"Material",
icons::PALETTE,
terrain.material_layers[index].material.as_ref(),
None,
true,
&material_candidates,
material_drop_candidate.as_ref(),
);
if let Some(selected) = response.selected {
terrain.material_layers[index].material = Some(selected);
changed = true;
}
if response.clear {
terrain.material_layers[index].material = None;
changed = true;
}
if response.locate {
locate_layer = Some(index);
}
accepted_drop |= response.accepted_drop;
property_row(ui, "UV Tiling", |ui| {
changed |= ui
.add(
egui::DragValue::new(&mut terrain.material_layers[index].uv_scale)
.range(0.01..=1024.0)
.speed(0.1)
.suffix("×"),
)
.changed();
});
if !terrain.material_weights.is_empty() {
let covered = terrain
.material_weights
.iter()
.filter(|weights| weights[index] > 0)
.count();
ui.label(
egui::RichText::new(format!(
"{} / {} samples carry this layer",
covered,
terrain.material_weights.len()
))
.color(TEXT_DIM)
.small(),
);
}
}
match terrain.validate() {
Ok(()) => {
ui.label(
egui::RichText::new(format!(
"{} heights • {}×{} chunks",
terrain.heights.len(),
(terrain.resolution - 1).div_ceil(terrain.chunk_quads),
(terrain.resolution - 1).div_ceil(terrain.chunk_quads)
))
.color(super::theme::SUCCESS),
);
}
Err(error) => {
ui.label(egui::RichText::new(error).color(super::theme::ERROR));
}
}
});
apply_component_card_response(world, entity, card_response);
if let Some(index) = remove_layer {
remove_terrain_material_layer(&mut terrain, index);
changed = true;
}
if let Some((a, b)) = swap_layers {
terrain.material_layers.swap(a, b);
for weights in &mut terrain.material_weights {
weights.swap(a, b);
}
changed = true;
}
if let Some(index) = locate_layer {
locate_asset_ref(
world,
terrain
.material_layers
.get(index)
.and_then(|layer| layer.material.as_ref()),
&material_candidates,
);
}
if accepted_drop {
clear_asset_drag(world);
}
if changed && terrain != original {
let _ = reflected_component_transaction(
world,
entity,
"Edit Terrain",
shared::AUTHORING_COMPONENT_TERRAIN,
COMPONENT_TERRAIN_DESC,
move |world, entity| {
world.entity_mut(entity).insert(terrain);
Ok(())
},
);
}
}
fn remove_terrain_material_layer(terrain: &mut TerrainDesc, index: usize) {
if index >= terrain.material_layers.len() {
return;
}
terrain.material_layers.remove(index);
if terrain.material_layers.is_empty() {
terrain.material_weights.clear();
return;
}
for weights in &mut terrain.material_weights {
for channel in index..3 {
weights[channel] = weights[channel + 1];
}
weights[3] = 0;
normalize_terrain_weights(weights, terrain.material_layers.len());
}
}
fn normalize_terrain_weights(weights: &mut [u8; 4], layer_count: usize) {
for weight in weights.iter_mut().skip(layer_count) {
*weight = 0;
}
let sum: u16 = weights
.iter()
.take(layer_count)
.copied()
.map(u16::from)
.sum();
if sum == 0 {
*weights = [255, 0, 0, 0];
return;
}
let source = *weights;
let mut assigned = 0_u16;
for index in 0..layer_count {
weights[index] = ((u16::from(source[index]) * 255) / sum) as u8;
assigned += u16::from(weights[index]);
}
let largest = (0..layer_count)
.max_by_key(|index| source[*index])
.unwrap_or(0);
weights[largest] = weights[largest].saturating_add((255 - assigned) as u8);
}
fn brush_validation_ui(ui: &mut egui::Ui, brush: &BrushDesc) {
let report = validate_brush(brush);
if report.diagnostics.is_empty() {
@@ -3893,6 +4216,7 @@ fn rigid_body_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
fn collider_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let mesh_candidates = static_mesh_asset_ref_candidates(world, AssetRefCandidateKind::Mesh);
let diagnostic_entry = diagnose_collider(world, entity);
let Some(mut collider) = world.get::<ColliderDesc>(entity).cloned() else {
return;
};
@@ -3915,13 +4239,60 @@ fn collider_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
ComponentCardOptions::removable(COMPONENT_COLLIDER_DESC, "Collider", icons::SELECTION),
);
let card_response = component_card(ui, &card, |ui| {
if let Some(entry) = diagnostic_entry.as_ref() {
let (label, color) = match entry.overlay_status {
ColliderOverlayStatus::Valid => ("Ready", egui::Color32::from_rgb(112, 210, 144)),
ColliderOverlayStatus::Trigger => {
("Trigger", egui::Color32::from_rgb(86, 195, 235))
}
ColliderOverlayStatus::Disabled => {
("Disabled", egui::Color32::from_rgb(143, 151, 163))
}
ColliderOverlayStatus::Warning => {
("Warning", egui::Color32::from_rgb(242, 173, 72))
}
ColliderOverlayStatus::Error => ("Invalid", egui::Color32::from_rgb(244, 91, 99)),
};
ui.horizontal_wrapped(|ui| {
ui.colored_label(color, egui::RichText::new(label).strong());
ui.label(egui::RichText::new(entry.shape_label).color(TEXT_DIM));
if entry.runtime_ready {
ui.label(egui::RichText::new("Hydrated").color(TEXT_MUTED).small());
}
});
for diagnostic in &entry.diagnostics {
let color = match diagnostic.severity {
ColliderDiagnosticSeverity::Info => TEXT_MUTED,
ColliderDiagnosticSeverity::Warning => egui::Color32::from_rgb(242, 173, 72),
ColliderDiagnosticSeverity::Error => egui::Color32::from_rgb(244, 91, 99),
};
ui.label(
egui::RichText::new(&diagnostic.message)
.color(color)
.small(),
);
ui.label(
egui::RichText::new(&diagnostic.repair)
.color(TEXT_MUTED)
.small(),
);
}
if entry.highest_severity() == Some(ColliderDiagnosticSeverity::Error)
&& ui.small_button("Reset shape").clicked()
{
collider.shape = ColliderShapeDesc::default();
collider.enabled = true;
changed = true;
}
ui.add_space(2.0);
}
property_row(ui, "Mode", |ui| {
changed |= ui.checkbox(&mut collider.enabled, "Enabled").changed();
changed |= ui.checkbox(&mut collider.is_trigger, "Trigger").changed();
});
property_row(ui, "Shape", |ui| {
let mut shape_kind = collider_shape_kind(&collider.shape);
egui::ComboBox::from_id_salt("collider_shape_kind")
egui::ComboBox::from_id_salt(("collider_shape_kind", entity))
.selected_text(shape_kind)
.show_ui(ui, |ui| {
for label in ["Box", "Sphere", "Capsule", "Static Mesh"] {
@@ -3931,15 +4302,8 @@ fn collider_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
}
});
if shape_kind != collider_shape_kind(&collider.shape) {
collider.shape = match shape_kind {
"Sphere" => ColliderShapeDesc::Sphere { radius: 0.5 },
"Capsule" => ColliderShapeDesc::Capsule {
radius: 0.5,
height: 1.0,
},
"Static Mesh" => ColliderShapeDesc::static_mesh(renderer_meshes.clone()),
_ => ColliderShapeDesc::default(),
};
collider.shape =
convert_collider_shape(&collider.shape, shape_kind, renderer_meshes.clone());
changed = true;
}
});
@@ -4007,12 +4371,48 @@ fn collider_shape_kind(shape: &ColliderShapeDesc) -> &'static str {
}
}
fn convert_collider_shape(
previous: &ColliderShapeDesc,
shape_kind: &str,
renderer_meshes: Vec<EditorAssetRef>,
) -> ColliderShapeDesc {
let dimensions = match previous {
ColliderShapeDesc::Cuboid {
x_length,
y_length,
z_length,
} => Vec3::new(*x_length, *y_length, *z_length),
ColliderShapeDesc::Sphere { radius } => Vec3::splat(*radius * 2.0),
ColliderShapeDesc::Capsule { radius, height } => {
Vec3::new(*radius * 2.0, *height, *radius * 2.0)
}
ColliderShapeDesc::StaticMesh { .. } => Vec3::ONE,
}
.max(Vec3::splat(0.001));
match shape_kind {
"Sphere" => ColliderShapeDesc::Sphere {
radius: dimensions.max_element() * 0.5,
},
"Capsule" => ColliderShapeDesc::Capsule {
radius: dimensions.x.max(dimensions.z) * 0.5,
height: dimensions.y,
},
"Static Mesh" => ColliderShapeDesc::static_mesh(renderer_meshes),
_ => ColliderShapeDesc::Cuboid {
x_length: dimensions.x,
y_length: dimensions.y,
z_length: dimensions.z,
},
}
}
fn dimension_drag(ui: &mut egui::Ui, label: &str, value: &mut f32) -> bool {
property_row(ui, label, |ui| {
ui.add_sized(
[fit_width(ui, 72.0, 120.0), 20.0],
egui::DragValue::new(value)
.range(0.0..=10_000.0)
.range(0.001..=10_000.0)
.speed(0.05)
.min_decimals(2)
.max_decimals(3),
@@ -4519,3 +4919,30 @@ fn option_string_ui(ui: &mut egui::Ui, label: &str, value: &mut Option<String>)
};
changed
}
#[cfg(test)]
mod collider_inspector_tests {
use super::*;
use crate::history::{apply_command_undo, EditorHistory};
#[test]
fn shape_switch_preserves_dimensions_and_is_one_undoable_edit() {
let mut world = World::new();
world.init_resource::<EditorHistory>();
let original = ColliderDesc::static_cuboid(Vec3::new(2.0, 4.0, 6.0));
let entity = world.spawn((LevelObject, original.clone())).id();
let sphere = ColliderDesc {
shape: convert_collider_shape(&original.shape, "Sphere", Vec::new()),
..original.clone()
};
assert_eq!(sphere.shape, ColliderShapeDesc::Sphere { radius: 3.0 });
set_collider_with_history(&mut world, entity, sphere.clone());
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
assert_eq!(world.get::<ColliderDesc>(entity), Some(&sphere));
apply_command_undo(&mut world);
assert_eq!(world.get::<ColliderDesc>(entity), Some(&original));
}
}
+5 -2
View File
@@ -32,8 +32,11 @@ pub fn default_dock_layout() -> DockLayoutSnapshot {
tree.split_right(NodeIndex::root(), 0.76, vec![EditorTab::Inspector]);
let [main_view_node, hierarchy_node] =
tree.split_left(main_view_node, 0.2, vec![EditorTab::Hierarchy]);
let [main_view_node, bottom_node] =
tree.split_below(main_view_node, 0.88, vec![EditorTab::AssetBrowser]);
let [main_view_node, bottom_node] = tree.split_below(
main_view_node,
0.88,
vec![EditorTab::AssetBrowser, EditorTab::MaterialLibrary],
);
let panel_nodes = PanelNodes {
main_view: main_view_node.0,
File diff suppressed because it is too large. Load diff
+20
View File
@@ -13,6 +13,7 @@ pub mod hierarchy_ops;
pub mod hierarchy_state;
pub(crate) mod inspector;
mod layout;
mod material_library;
mod menu;
pub(crate) mod navigation_inspector;
mod play_controls;
@@ -75,6 +76,9 @@ pub struct UiState {
last_mode_tab: Option<EditorMode>,
}
#[derive(Resource, Default)]
struct DockTabRequest(Option<EditorTab>);
pub fn egui_captures_keyboard(ctx: &egui::Context) -> bool {
ctx.egui_wants_keyboard_input()
}
@@ -187,6 +191,10 @@ impl UiState {
.show_inside(root_ui, &mut viewer);
});
if let Some(tab) = world.resource_mut::<DockTabRequest>().0.take() {
dock_tabs::open_and_focus_tab(&mut self.dock_state, tab, &self.panel_nodes);
}
self.panel_nodes = PanelNodes::discover(&self.dock_state, self.panel_nodes);
mark_layout_dirty_if_changed(
@@ -283,6 +291,7 @@ pub enum EditorTab {
Inspector,
Toolbar,
AssetBrowser,
MaterialLibrary,
Build,
}
@@ -298,6 +307,9 @@ impl Plugin for EditorUiPlugin {
.init_resource::<component_registry::EditorComponentRegistry>()
.init_resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
.init_resource::<asset_browser::AssetBrowserUiState>()
.init_resource::<material_library::MaterialLibraryState>()
.init_resource::<material_library::MaterialLibraryCatalog>()
.init_resource::<DockTabRequest>()
.init_resource::<inspector::InspectorClipboard>()
.init_resource::<inspector::InspectorPanelState>()
.init_resource::<animation_inspector::AnimationInspectorState>()
@@ -315,6 +327,10 @@ impl Plugin for EditorUiPlugin {
apply_ui_state_from_prefs
.after(crate::project_io::load_user_preferences_on_startup),
)
.add_systems(
EguiPrimaryContextPass,
material_library::refresh_material_library_catalog.before(show_ui_system),
)
.add_systems(EguiPrimaryContextPass, show_ui_system)
.add_systems(
Update,
@@ -421,6 +437,9 @@ impl egui_dock::TabViewer for TabViewer<'_> {
EditorTab::AssetBrowser => {
asset_browser::asset_browser_ui(self.world, ui, self.selected_entities);
}
EditorTab::MaterialLibrary => {
material_library::material_library_ui(self.world, ui, self.selected_entities);
}
EditorTab::Build => build::build_ui(self.world, ui),
}
}
@@ -432,6 +451,7 @@ impl egui_dock::TabViewer for TabViewer<'_> {
EditorTab::Inspector => (icons::SLIDERS, "Inspector"),
EditorTab::Toolbar => (icons::WRENCH, "Toolbar"),
EditorTab::AssetBrowser => (icons::FOLDER, "Asset Browser"),
EditorTab::MaterialLibrary => (icons::PALETTE, "Material Library"),
EditorTab::Build => (icons::HAMMER, "Build"),
};
tab_title(icon, label)
+47 -24
View File
@@ -8,6 +8,7 @@ use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
use egui_phosphor_icons::icons;
use shared::{SceneComposition, SubsceneReference};
use crate::native_dialog::NativeDialogBroker;
use crate::scene_io::{ComposedSceneMember, SceneIo, SceneIoRequest};
use crate::selection::SelectedEntity;
@@ -195,19 +196,47 @@ fn composition_menu(
ui.separator();
if ui
.add_enabled(editing, egui::Button::new("Add Subscene..."))
.add_enabled(
editing && !world.resource::<NativeDialogBroker>().is_pending(),
egui::Button::new("Add Subscene..."),
)
.clicked()
{
match choose_subscene(world, &composition) {
Ok(Some(reference)) => {
composition.subscenes.push(reference);
changed = true;
}
Ok(None) => {}
Err(error) => world
.resource_mut::<SceneIo>()
.set_status(format!("Add subscene failed: {error}")),
}
let project_root =
PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
let directory = project_root.join("assets/levels");
let result = world.resource::<NativeDialogBroker>().request(
move || {
rfd::FileDialog::new()
.set_directory(directory)
.add_filter("Bevy scene", &["scn.ron", "ron"])
.pick_file()
},
move |world, path| {
let Some(path) = path else {
world
.resource_mut::<SceneIo>()
.set_status("Add subscene cancelled");
return;
};
let current = world.resource::<SceneComposition>().clone();
match validate_subscene_choice(&project_root, &current, path) {
Ok(reference) => {
let mut updated = current;
updated.subscenes.push(reference);
crate::history::set_scene_composition_with_history(world, updated);
world.resource_mut::<SceneIo>().set_status("Subscene added");
}
Err(error) => world
.resource_mut::<SceneIo>()
.set_status(format!("Add subscene failed: {error}")),
}
},
);
world.resource_mut::<SceneIo>().set_status(match result {
Ok(()) => "Choose a scene to compose".into(),
Err(error) => format!("Add subscene unavailable: {error}"),
});
}
if changed {
@@ -218,20 +247,14 @@ fn composition_menu(
}
}
fn choose_subscene(
world: &World,
fn validate_subscene_choice(
project_root: &Path,
composition: &SceneComposition,
) -> Result<Option<SubsceneReference>, String> {
let project_root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root)
path: PathBuf,
) -> Result<SubsceneReference, String> {
let project_root = project_root
.canonicalize()
.map_err(|error| format!("could not resolve project root: {error}"))?;
let Some(path) = rfd::FileDialog::new()
.set_directory(project_root.join("assets/levels"))
.add_filter("Bevy scene", &["scn.ron", "ron"])
.pick_file()
else {
return Ok(None);
};
let path = path
.canonicalize()
.map_err(|error| format!("could not resolve {}: {error}", path.display()))?;
@@ -251,12 +274,12 @@ fn choose_subscene(
{
return Err(format!("{relative} is already composed"));
}
Ok(Some(SubsceneReference {
Ok(SubsceneReference {
id: uuid::Uuid::new_v4().to_string(),
path: relative,
visible: true,
locked: true,
}))
})
}
fn focus_subscene(world: &mut World, selected: &mut SelectedEntities, reference_id: &str) {
+554 -70
View File
@@ -7,22 +7,28 @@ use egui_phosphor_icons::icons;
use transform_gizmo_bevy::prelude::GizmoOptions;
use crate::assets::operators::{
apply_material_operator, apply_texture_operator, assign_animation_clip_operator,
assign_audio_clip_operator, place_asset_operator, place_subasset_operator,
assign_animation_clip_operator, assign_audio_clip_operator, place_asset_operator,
place_subasset_operator,
};
use crate::assets::thumbnails::kind_icon;
use crate::assets::{AssetSelection, AssetSubAssetKind, EditorAssets};
use crate::camera::EditorCamera;
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
use crate::render_target::ViewportRenderTarget;
use crate::selection::{ViewportClick, ViewportPickStack};
use crate::selection::{SelectedEntity, ViewportClick, ViewportPickStack};
use crate::state::PlayPossession;
use crate::viewport::actor_icons::ActorIconSettings;
use crate::viewport::brush_edit::{BrushEditMode, BrushElementSelection};
use crate::viewport::brush_tool::{BrushToolPhase, BrushToolState};
use crate::viewport::physics_placement::{
begin_physics_placement, request_physics_placement, PhysicsPlacementPhase,
PhysicsPlacementRequest, PhysicsPlacementState,
};
use crate::viewport::terrain_paint::{TerrainPaintMode, TerrainPaintState};
use crate::viewport::terrain_sculpt::{TerrainSculptMode, TerrainSculptState};
use crate::viewport::{
snap_translation, viewport_ground_position, EditorViewportMode, ViewportDisplayMode,
ViewportSettings,
material_drop::is_surface_asset_selection, snap_translation, viewport_ground_position,
EditorViewportMode, MaterialDropState, ViewportDisplayMode, ViewportSettings,
};
use super::helpers::{
@@ -30,7 +36,8 @@ use super::helpers::{
};
use super::theme::{
overlay_chip_frame, viewport_toolbar_frame, ACCENT, ACCENT_HOVER, AXIS_X, AXIS_Y, AXIS_Z,
BORDER, BORDER_STRONG, ELEVATED_BG, SELECTION, SUCCESS, TEXT, TEXT_DIM, TEXT_MUTED, WARNING,
BORDER, BORDER_STRONG, ELEVATED_BG, ERROR, SELECTION, SUCCESS, TEXT, TEXT_DIM, TEXT_MUTED,
WARNING,
};
use super::widgets::{
icon_button_small, panel_toolbar_row, phosphor_icon, tool_button, tool_button_accent,
@@ -40,6 +47,7 @@ use super::widgets::{
pub struct ViewportUiState {
pub options_open: bool,
pub shortcuts_open: bool,
pub toolbar_rect: Option<egui::Rect>,
}
const VIEWPORT_TOOLTIP: &str = "RMB + WASD/QE: fly | MMB: pan | Scroll: dolly\nW/E/R: gizmo | X: world/local | F: focus | G: game view | Ctrl+G: grid\nTab: cycle overlapping picks | Play/Pause/Stop: main toolbar (F5 / F6)";
@@ -69,9 +77,17 @@ pub fn viewport_tab_ui(
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
let response = ui.allocate_rect(rect, egui::Sense::HOVER);
*viewport_pointer_pos = response
.interact_pointer_pos()
.or_else(|| response.hover_pos())
// A drag source owns egui's interaction response, so `Response::hover_pos()`
// is intentionally empty while an asset is dragged over the viewport. The
// global pointer position remains available and is the correct input for
// drag previews and exact surface targeting.
*viewport_pointer_pos = ui
.input(|input| {
input
.pointer
.interact_pos()
.or_else(|| input.pointer.hover_pos())
})
.filter(|pos| rect.contains(*pos));
*pointer_in_viewport = viewport_pointer_pos.is_some();
@@ -134,9 +150,12 @@ pub fn viewport_tab_ui(
return;
}
scene_view_overlay_toolbar(world, ui.ctx(), rect);
scene_view_overlay_toolbar(world, ui.ctx(), rect, selected_entities);
scene_view_selection_hud(world, ui.ctx(), rect, selected_entities);
scene_view_brush_draw_hints(world, ui.ctx(), rect);
scene_view_terrain_sculpt_hints(world, ui.ctx(), rect);
scene_view_terrain_paint_hints(world, ui.ctx(), rect);
scene_view_physics_placement_hud(world, ui.ctx(), rect);
scene_view_render_badge(world, ui.ctx(), rect);
scene_view_brush_mode_badge(world, ui.ctx(), rect);
scene_view_volume_hud(world, ui.ctx(), rect);
@@ -181,16 +200,54 @@ fn scene_view_render_badge(world: &World, ctx: &egui::Context, scene_rect: egui:
});
if mode == EditorViewportMode::Collider {
let health =
world.get_resource::<crate::viewport::collider_diagnostics::ColliderDiagnosticsState>();
let selected_entry = world
.get_resource::<SelectedEntity>()
.and_then(|selected| selected.0)
.and_then(|entity| health.and_then(|health| health.entry(entity)));
egui::Area::new(egui::Id::new("scene_view_collider_warning"))
.fixed_pos(scene_rect.left_bottom() + egui::vec2(8.0, -28.0))
.interactable(false)
.show(ctx, |ui| {
overlay_chip_frame().show(ui, |ui| {
ui.label(
egui::RichText::new("Collider view / meshes hidden")
.color(WARNING)
ui.horizontal_wrapped(|ui| {
ui.label(
egui::RichText::new("Collider View")
.color(WARNING)
.strong()
.small(),
);
if let Some(health) = health {
ui.label(
egui::RichText::new(format!(
"{} ready {} disabled {} warning {} invalid",
health.valid_actors,
health.disabled_actors,
health.warning_actors,
health.error_actors
))
.color(TEXT_MUTED)
.small(),
);
}
});
if let Some(entry) = selected_entry {
ui.label(
egui::RichText::new(format!(
"{} / {} / {}",
entry.actor_name,
entry.shape_label,
if entry.runtime_ready {
"hydrated"
} else {
"not hydrated"
}
))
.color(SELECTION)
.small(),
);
);
}
});
});
}
@@ -295,6 +352,94 @@ fn scene_view_brush_draw_hints(world: &World, ctx: &egui::Context, scene_rect: e
});
}
fn scene_view_terrain_sculpt_hints(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
let Some(tool) = world.get_resource::<TerrainSculptState>() else {
return;
};
if !tool.active {
return;
}
egui::Area::new(egui::Id::new("scene_view_terrain_sculpt_hints"))
.fixed_pos(scene_rect.left_top() + egui::vec2(8.0, 52.0))
.interactable(false)
.show(ctx, |ui| {
overlay_chip_frame().show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(
egui::RichText::new(format!("Terrain {}", tool.mode.label()))
.color(SELECTION)
.strong(),
);
ui.label(
egui::RichText::new(format!("R {:.1}m", tool.radius))
.color(TEXT_DIM)
.monospace()
.small(),
);
ui.label(
egui::RichText::new(format!("S {:.2}m", tool.strength))
.color(SUCCESS)
.monospace()
.small(),
);
});
ui.add_space(4.0);
ui.horizontal_wrapped(|ui| {
key_hint(ui, "LMB Drag", "Sculpt");
key_hint(ui, "Esc", "Cancel stroke / close");
key_hint(ui, "RMB", "Cancel stroke / close");
key_hint(ui, "Ctrl+Z", "Undo stroke");
});
});
});
}
fn scene_view_terrain_paint_hints(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
let Some(tool) = world.get_resource::<TerrainPaintState>() else {
return;
};
if !tool.active {
return;
}
egui::Area::new(egui::Id::new("scene_view_terrain_paint_hints"))
.fixed_pos(scene_rect.left_top() + egui::vec2(8.0, 52.0))
.interactable(false)
.show(ctx, |ui| {
overlay_chip_frame().show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(
egui::RichText::new(format!(
"Terrain {} • Layer {}",
tool.mode.label(),
tool.active_layer + 1
))
.color(SELECTION)
.strong(),
);
ui.label(
egui::RichText::new(format!("R {:.1}m", tool.radius))
.color(TEXT_DIM)
.monospace()
.small(),
);
ui.label(
egui::RichText::new(format!("S {:.0}%", tool.strength * 100.0))
.color(SUCCESS)
.monospace()
.small(),
);
});
ui.add_space(4.0);
ui.horizontal_wrapped(|ui| {
key_hint(ui, "LMB Drag", tool.mode.label());
key_hint(ui, "Esc", "Cancel stroke / close");
key_hint(ui, "RMB", "Cancel stroke / close");
key_hint(ui, "Ctrl+Z", "Undo stroke");
});
});
});
}
fn key_hint(ui: &mut egui::Ui, key: &str, label: &str) {
ui.horizontal(|ui| {
ui.label(
@@ -480,11 +625,38 @@ fn scene_view_volume_hud(world: &World, ctx: &egui::Context, scene_rect: egui::R
});
}
fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect: egui::Rect) {
fn scene_view_overlay_toolbar(
world: &mut World,
ctx: &egui::Context,
scene_rect: egui::Rect,
selected_entities: &SelectedEntities,
) {
let mut options_open = world.resource::<ViewportUiState>().options_open;
let mut shortcuts_open = world.resource::<ViewportUiState>().shortcuts_open;
let terrain_selected = world
.resource::<crate::selection::SelectedEntity>()
.0
.filter(|entity| world.get::<shared::TerrainDesc>(*entity).is_some());
let terrain_layer_labels = terrain_selected
.and_then(|entity| world.get::<shared::TerrainDesc>(entity))
.map(|terrain| {
terrain
.material_layers
.iter()
.enumerate()
.map(|(index, layer)| {
layer
.material
.as_ref()
.map(|material| material.label.clone())
.filter(|label| !label.trim().is_empty())
.unwrap_or_else(|| format!("Layer {}", index + 1))
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
egui::Area::new(egui::Id::new("scene_view_toolbar"))
let toolbar_response = egui::Area::new(egui::Id::new("scene_view_toolbar"))
.fixed_pos(scene_rect.left_top() + egui::vec2(6.0, 6.0))
.interactable(true)
.show(ctx, |ui| {
@@ -613,6 +785,224 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
}
}
let placement_active = world.resource::<PhysicsPlacementState>().active();
ui.separator();
if placement_active {
let phase = world.resource::<PhysicsPlacementState>().phase;
ui.label(
egui::RichText::new(phase.label())
.color(match phase {
PhysicsPlacementPhase::Settled => SUCCESS,
PhysicsPlacementPhase::TimedOut => WARNING,
_ => SELECTION,
})
.strong()
.small(),
);
if icon_button_small(
ui,
icons::CHECK,
"Commit physics placement (Enter when settled)",
)
.clicked()
{
request_physics_placement(world, PhysicsPlacementRequest::Commit);
}
if icon_button_small(ui, icons::X, "Cancel physics placement (Esc)")
.clicked()
{
request_physics_placement(world, PhysicsPlacementRequest::Cancel);
}
} else {
let selected = selected_entities.iter().collect::<Vec<_>>();
let can_start = !selected.is_empty();
let clicked = ui
.add_enabled(
can_start,
egui::Button::new(phosphor_icon(icons::HAND_ARROW_DOWN, 16.0)),
)
.on_hover_text(if can_start {
"Release selected props into physics"
} else {
"Select one or more props to place with physics"
})
.clicked();
if clicked && begin_physics_placement(world, selected).is_ok() {
world.resource_mut::<TerrainSculptState>().stop();
world.resource_mut::<TerrainPaintState>().stop();
world.resource_mut::<BrushToolState>().cancel();
world.resource_mut::<ViewportClick>().0 = None;
}
}
let sculpt_active = world.resource::<TerrainSculptState>().active;
let paint_active = world.resource::<TerrainPaintState>().active;
if terrain_selected.is_some() || sculpt_active || paint_active {
ui.separator();
let stroking = world.resource::<TerrainSculptState>().is_stroking();
let sculpt_button_clicked = tool_button_accent(
ui,
icons::MOUNTAINS,
sculpt_active,
if sculpt_active {
"Close terrain sculpt tool"
} else {
"Sculpt selected terrain"
},
)
.clicked();
if sculpt_button_clicked {
world.resource_mut::<ViewportClick>().0 = None;
}
if sculpt_button_clicked && !stroking {
let state = &mut *world.resource_mut::<TerrainSculptState>();
if state.active {
state.stop();
} else if let Some(entity) = terrain_selected {
state.start(entity);
}
let active = state.active;
if active {
world.resource_mut::<TerrainPaintState>().stop();
world.resource_mut::<BrushToolState>().cancel();
world
.resource_mut::<crate::operators::ActiveOperator>()
.status = Some(crate::operators::OperatorStatus {
id: "terrain.sculpt".to_string(),
label: "Terrain Sculpt".to_string(),
phase: crate::operators::OperatorPhase::Preview,
hint: "LMB drag sculpts; Esc or RMB cancels".to_string(),
warnings: Vec::new(),
});
}
}
if sculpt_active {
let mut mode = world.resource::<TerrainSculptState>().mode;
for candidate in [
TerrainSculptMode::Raise,
TerrainSculptMode::Lower,
TerrainSculptMode::Flatten,
TerrainSculptMode::Smooth,
TerrainSculptMode::Noise,
] {
ui.selectable_value(&mut mode, candidate, candidate.label())
.on_hover_text(format!("{} terrain", candidate.label()));
}
let mut radius = world.resource::<TerrainSculptState>().radius;
let mut strength = world.resource::<TerrainSculptState>().strength;
ui.add(
egui::DragValue::new(&mut radius)
.range(0.25..=128.0)
.speed(0.1)
.prefix("R ")
.suffix(" m"),
)
.on_hover_text("Brush radius");
ui.add(
egui::DragValue::new(&mut strength)
.range(0.01..=20.0)
.speed(0.05)
.prefix("S ")
.suffix(" m"),
)
.on_hover_text("Height strength per dab");
let mut state = world.resource_mut::<TerrainSculptState>();
state.mode = mode;
state.radius = radius;
state.strength = strength;
state.clamp_settings();
}
let paint_stroking = world.resource::<TerrainPaintState>().is_stroking();
let can_paint = terrain_layer_labels.len() >= 2 || paint_active;
let paint_button_clicked = ui
.add_enabled(
can_paint,
egui::Button::new(phosphor_icon(icons::PAINT_BRUSH, 16.0))
.selected(paint_active),
)
.on_hover_text(if can_paint {
if paint_active {
"Close terrain material paint tool"
} else {
"Paint selected terrain material layers"
}
} else {
"Assign at least two terrain material layers first"
})
.clicked();
if paint_button_clicked {
world.resource_mut::<ViewportClick>().0 = None;
}
if paint_button_clicked && !paint_stroking {
let layer_count = terrain_layer_labels.len();
let state = &mut *world.resource_mut::<TerrainPaintState>();
if state.active {
state.stop();
} else if let Some(entity) = terrain_selected {
state.start(entity, layer_count);
}
let active = state.active;
if active {
world.resource_mut::<TerrainSculptState>().stop();
world.resource_mut::<BrushToolState>().cancel();
world
.resource_mut::<crate::operators::ActiveOperator>()
.status = Some(crate::operators::OperatorStatus {
id: "terrain.paint".into(),
label: "Terrain Paint".into(),
phase: crate::operators::OperatorPhase::Preview,
hint: "LMB drag paints weights; Esc or RMB cancels".into(),
warnings: Vec::new(),
});
}
}
if paint_active {
let mut mode = world.resource::<TerrainPaintState>().mode;
ui.selectable_value(&mut mode, TerrainPaintMode::Paint, "Paint")
.on_hover_text("Increase the selected layer weight");
ui.selectable_value(&mut mode, TerrainPaintMode::Erase, "Erase")
.on_hover_text("Reduce the selected layer weight");
let mut active_layer =
world.resource::<TerrainPaintState>().active_layer;
egui::ComboBox::from_id_salt("terrain_paint_layer")
.selected_text(
terrain_layer_labels
.get(active_layer)
.cloned()
.unwrap_or_else(|| "Layer".into()),
)
.show_ui(ui, |ui| {
for (index, label) in terrain_layer_labels.iter().enumerate() {
ui.selectable_value(&mut active_layer, index, label);
}
});
let mut radius = world.resource::<TerrainPaintState>().radius;
let mut strength = world.resource::<TerrainPaintState>().strength;
ui.add(
egui::DragValue::new(&mut radius)
.range(0.25..=128.0)
.speed(0.1)
.prefix("R ")
.suffix(" m"),
)
.on_hover_text("Brush radius");
ui.add(
egui::DragValue::new(&mut strength)
.range(0.01..=1.0)
.speed(0.02)
.prefix("S "),
)
.on_hover_text("Weight strength per dab");
let mut state = world.resource_mut::<TerrainPaintState>();
state.mode = mode;
state.active_layer = active_layer;
state.radius = radius;
state.strength = strength;
state.clamp_settings();
}
}
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
if tool_button(
ui,
@@ -640,6 +1030,13 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
});
});
let toolbar_clicked = toolbar_response.response.contains_pointer()
&& ctx.input(|input| input.pointer.button_clicked(egui::PointerButton::Primary));
if toolbar_clicked {
world.resource_mut::<ViewportClick>().0 = None;
}
world.resource_mut::<ViewportUiState>().toolbar_rect = Some(toolbar_response.response.rect);
if options_open {
scene_options_popover(world, ctx, scene_rect, &mut options_open);
}
@@ -651,6 +1048,66 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
world.resource_mut::<ViewportUiState>().shortcuts_open = shortcuts_open;
}
fn scene_view_physics_placement_hud(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
let state = world.resource::<PhysicsPlacementState>();
if !state.active() {
let Some(error) = state.last_error.as_deref() else {
return;
};
egui::Area::new(egui::Id::new("scene_view_physics_placement_error"))
.fixed_pos(scene_rect.left_top() + egui::vec2(8.0, 52.0))
.interactable(false)
.show(ctx, |ui| {
overlay_chip_frame().show(ui, |ui| {
ui.label(
egui::RichText::new("Physics placement unavailable")
.color(ERROR)
.strong(),
);
for line in error.lines().take(4) {
ui.label(egui::RichText::new(line).color(TEXT_DIM).small());
}
});
});
return;
}
egui::Area::new(egui::Id::new("scene_view_physics_placement_hud"))
.fixed_pos(scene_rect.left_top() + egui::vec2(8.0, 52.0))
.interactable(false)
.show(ctx, |ui| {
overlay_chip_frame().show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(phosphor_icon(icons::HAND_ARROW_DOWN, 16.0).color(SELECTION));
ui.label(
egui::RichText::new(format!("Physics Placement / {}", state.phase.label()))
.color(match state.phase {
PhysicsPlacementPhase::Settled => SUCCESS,
PhysicsPlacementPhase::TimedOut => WARNING,
_ => SELECTION,
})
.strong(),
);
ui.label(
egui::RichText::new(format!(
"{} props / {:.1}s",
state.selected_count,
state.simulated_seconds()
))
.color(TEXT_DIM)
.monospace()
.small(),
);
});
ui.add_space(4.0);
ui.horizontal_wrapped(|ui| {
key_hint(ui, "Esc", "Cancel");
key_hint(ui, "Enter", "Commit when settled");
});
});
});
}
fn scene_options_popover(
world: &mut World,
ctx: &egui::Context,
@@ -820,11 +1277,44 @@ fn viewport_asset_drop_ui(
.resource::<EditorAssets>()
.dragging_selection()
.cloned();
let drag_descriptor = drag_selection
let surface_drag = drag_selection
.as_ref()
.is_some_and(|selection| is_surface_asset_selection(world, selection));
let mut drag_descriptor = drag_selection
.as_ref()
.and_then(|selection| asset_drag_descriptor(world, selection, selected));
let over_viewport = pointer_pos.is_some_and(|pos| viewport_rect.contains(pos));
let surface_feedback = surface_drag
.then(|| world.get_resource::<MaterialDropState>())
.flatten()
.and_then(MaterialDropState::feedback)
.cloned();
if surface_drag && over_viewport {
if let Some((_, _, action)) = drag_descriptor.as_mut() {
*action = surface_feedback
.as_ref()
.map(|feedback| feedback.action.clone())
.unwrap_or_else(|| "Finding an assignable surface".into());
}
}
let drop_valid = (surface_drag && over_viewport)
.then(|| surface_feedback.as_ref().map(|feedback| feedback.valid))
.flatten();
let highlight_color = match drop_valid {
Some(true) => SUCCESS,
Some(false) => ERROR,
None => ACCENT_HOVER,
};
let drag_visual_state = if !over_viewport {
AssetDragVisualState::Outside
} else {
match drop_valid {
Some(true) => AssetDragVisualState::Valid,
Some(false) => AssetDragVisualState::Invalid,
None => AssetDragVisualState::Targeted,
}
};
if let (Some(pointer), Some((icon, label, action))) = (pointer_pos, drag_descriptor.as_ref()) {
draw_asset_drag_preview(
ui,
@@ -833,7 +1323,7 @@ fn viewport_asset_drop_ui(
*icon,
label,
action,
over_viewport,
drag_visual_state,
);
}
@@ -841,7 +1331,7 @@ fn viewport_asset_drop_ui(
ui.painter().rect_stroke(
viewport_rect.shrink(2.0),
0.0,
egui::Stroke::new(2.0, ACCENT_HOVER),
egui::Stroke::new(2.0, highlight_color),
egui::StrokeKind::Inside,
);
}
@@ -851,6 +1341,11 @@ fn viewport_asset_drop_ui(
return;
}
if surface_drag && over_viewport {
// The Last-schedule surface-drop session owns exact hit resolution and commit.
return;
}
if !pointer_pos.is_some_and(|pos| viewport_rect.contains(pos)) {
world.resource_mut::<EditorAssets>().clear_drag();
return;
@@ -903,26 +1398,6 @@ fn viewport_asset_drop_ui(
return;
}
if let AssetSelection::SubAsset {
kind: AssetSubAssetKind::Texture,
source_path: Some(path),
label,
..
} = &selection
{
let asset = crate::assets::EditorAsset {
label: label.clone(),
path: Some(path.clone()),
folder_path: std::path::Path::new(path)
.parent()
.map(|parent| parent.to_string_lossy().replace('\\', "/"))
.unwrap_or_else(|| crate::assets::ASSETS_ROOT.to_string()),
kind: crate::assets::EditorAssetKind::Texture,
};
apply_texture_operator(world, asset, selected);
return;
}
let asset = {
let assets = world.resource::<EditorAssets>();
assets.asset_for_selection(&selection).cloned()
@@ -943,18 +1418,6 @@ fn viewport_asset_drop_ui(
}
return;
}
match asset.kind {
crate::assets::EditorAssetKind::Texture => {
apply_texture_operator(world, asset, selected);
return;
}
crate::assets::EditorAssetKind::Material => {
apply_material_operator(world, asset, selected);
return;
}
_ => {}
}
place_asset_operator(world, asset, placement);
}
@@ -996,11 +1459,11 @@ fn asset_drag_descriptor(
AssetSelection::SubAsset {
kind: AssetSubAssetKind::Texture,
..
} if !selected.is_empty() => "Apply texture to selection",
} => "Drop onto a primitive or brush face",
AssetSelection::SubAsset {
kind: AssetSubAssetKind::Material,
..
} if !selected.is_empty() => "Apply material to selection",
} => "Drop onto an exact renderer slot",
AssetSelection::SubAsset {
kind: AssetSubAssetKind::Skeleton,
..
@@ -1020,12 +1483,8 @@ fn asset_drag_descriptor(
..
} => "Create animated actor",
_ => match asset.kind {
crate::assets::EditorAssetKind::Texture if !selected.is_empty() => {
"Apply texture to selection"
}
crate::assets::EditorAssetKind::Material if !selected.is_empty() => {
"Apply material to selection"
}
crate::assets::EditorAssetKind::Texture => "Drop onto a primitive or brush face",
crate::assets::EditorAssetKind::Material => "Drop onto a renderable surface",
crate::assets::EditorAssetKind::AudioClip
if selected
.as_slice()
@@ -1041,6 +1500,29 @@ fn asset_drag_descriptor(
Some((icon, label, action.to_string()))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AssetDragVisualState {
Outside,
Targeted,
Valid,
Invalid,
}
impl AssetDragVisualState {
fn over_viewport(self) -> bool {
self != Self::Outside
}
fn color(self) -> egui::Color32 {
match self {
Self::Outside => TEXT_DIM,
Self::Targeted => ACCENT_HOVER,
Self::Valid => SUCCESS,
Self::Invalid => ERROR,
}
}
}
fn draw_asset_drag_preview(
ui: &egui::Ui,
viewport_rect: egui::Rect,
@@ -1048,39 +1530,41 @@ fn draw_asset_drag_preview(
icon: egui_phosphor_icons::Icon,
label: &str,
action: &str,
over_viewport: bool,
visual_state: AssetDragVisualState,
) {
let over_viewport = visual_state.over_viewport();
let highlight_color = visual_state.color();
if over_viewport {
let painter = ui.painter();
painter.circle_filled(pointer, 3.0, ACCENT_HOVER);
painter.circle_stroke(pointer, 11.0, egui::Stroke::new(1.5, ACCENT_HOVER));
painter.circle_filled(pointer, 3.0, highlight_color);
painter.circle_stroke(pointer, 11.0, egui::Stroke::new(1.5, highlight_color));
painter.line_segment(
[
pointer - egui::vec2(17.0, 0.0),
pointer - egui::vec2(7.0, 0.0),
],
egui::Stroke::new(1.5, ACCENT_HOVER),
egui::Stroke::new(1.5, highlight_color),
);
painter.line_segment(
[
pointer + egui::vec2(7.0, 0.0),
pointer + egui::vec2(17.0, 0.0),
],
egui::Stroke::new(1.5, ACCENT_HOVER),
egui::Stroke::new(1.5, highlight_color),
);
painter.line_segment(
[
pointer - egui::vec2(0.0, 17.0),
pointer - egui::vec2(0.0, 7.0),
],
egui::Stroke::new(1.5, ACCENT_HOVER),
egui::Stroke::new(1.5, highlight_color),
);
painter.line_segment(
[
pointer + egui::vec2(0.0, 7.0),
pointer + egui::vec2(0.0, 17.0),
],
egui::Stroke::new(1.5, ACCENT_HOVER),
egui::Stroke::new(1.5, highlight_color),
);
}
@@ -1101,7 +1585,7 @@ fn draw_asset_drag_preview(
ui.set_width(228.0);
ui.horizontal(|ui| {
ui.label(phosphor_icon(icon, 20.0).color(if over_viewport {
ACCENT_HOVER
highlight_color
} else {
TEXT_DIM
}));
@@ -1116,7 +1600,7 @@ fn draw_asset_drag_preview(
})
.size(11.0)
.color(if over_viewport {
ACCENT_HOVER
highlight_color
} else {
TEXT_MUTED
}),
@@ -1152,9 +1636,9 @@ fn draw_asset_drag_preview(
),
] {
ui.painter()
.line_segment([a, a + b], egui::Stroke::new(3.0, ACCENT_HOVER));
.line_segment([a, a + b], egui::Stroke::new(3.0, highlight_color));
ui.painter()
.line_segment([a, a + c], egui::Stroke::new(3.0, ACCENT_HOVER));
.line_segment([a, a + c], egui::Stroke::new(3.0, highlight_color));
}
}
}
@@ -631,6 +631,10 @@ fn icon_for_actor_components(components: ActorIconComponents) -> ActorIconSpec {
image: ActorIconImage::Mesh,
category: ActorIconCategory::Mesh,
},
ActorKind::Terrain => ActorIconSpec {
image: ActorIconImage::Mesh,
category: ActorIconCategory::Mesh,
},
ActorKind::StaticMesh => {
if components.has_primitive || components.has_static_mesh_renderer {
ActorIconSpec {
+54 -30
View File
@@ -4,7 +4,7 @@ use bevy::math::Affine3A;
use bevy::prelude::*;
use shared::{
brush_math::{validate_brush, BrushDiagnosticSeverity},
BrushDesc, LevelObject,
BrushDesc,
};
use crate::history::apply_brush_csg_with_history;
@@ -64,24 +64,27 @@ pub fn selected_brush_count(world: &World) -> usize {
.resource::<UiState>()
.selected_entities
.iter()
.filter(|entity| world.get::<BrushDesc>(*entity).is_some())
.filter(|entity| {
world.get::<BrushDesc>(*entity).is_some()
&& crate::ui::selection_ops::is_mutable_level_object(world, *entity)
})
.count()
}
pub fn intersect_selected_brushes(world: &mut World) {
run_bounds_csg(world, BrushCsgOp::Intersect);
pub fn intersect_selected_brushes(world: &mut World) -> Result<(), String> {
run_bounds_csg(world, BrushCsgOp::Intersect)
}
pub fn merge_selected_brushes(world: &mut World) {
run_bounds_csg(world, BrushCsgOp::Merge);
pub fn merge_selected_brushes(world: &mut World) -> Result<(), String> {
run_bounds_csg(world, BrushCsgOp::Merge)
}
pub fn subtract_selected_brushes(world: &mut World) {
run_bounds_csg(world, BrushCsgOp::Subtract);
pub fn subtract_selected_brushes(world: &mut World) -> Result<(), String> {
run_bounds_csg(world, BrushCsgOp::Subtract)
}
#[derive(Resource, Default, Debug, Clone)]
struct BrushCsgPreview {
pub(crate) struct BrushCsgPreview {
pending: Option<PendingBrushCsg>,
}
@@ -99,18 +102,18 @@ enum BrushCsgOp {
Subtract,
}
fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
fn run_bounds_csg(world: &mut World, op: BrushCsgOp) -> Result<(), String> {
let selected: Vec<Entity> = world
.resource::<UiState>()
.selected_entities
.iter()
.filter(|entity| {
world.get::<LevelObject>(*entity).is_some() && world.get::<BrushDesc>(*entity).is_some()
world.get::<BrushDesc>(*entity).is_some()
&& crate::ui::selection_ops::is_mutable_level_object(world, *entity)
})
.collect();
if selected.len() < 2 {
set_status(world, "Select at least two brushes for CSG");
return;
return csg_failure(world, "Select at least two editable brushes for CSG");
}
for entity in &selected {
let Some(brush) = world.get::<BrushDesc>(*entity) else {
@@ -118,20 +121,18 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
};
let validation = validate_brush(brush);
if !validation.is_valid() {
set_status(
return csg_failure(
world,
format!(
"CSG failed: selected brush is invalid: {}",
first_brush_error(&validation)
),
);
return;
}
}
let Some(primary_bounds) = brush_world_bounds(world, selected[0]) else {
set_status(world, "Primary brush has no valid bounds");
return;
return csg_failure(world, "Primary brush has no valid bounds");
};
let result = match op {
@@ -147,8 +148,7 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
continue;
};
let Some(intersection) = result.intersection(bounds) else {
set_status(world, "Brush intersect failed: no overlap");
return;
return csg_failure(world, "Brush intersect failed: no overlap");
};
result = intersection;
}
@@ -156,16 +156,13 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
}
BrushCsgOp::Subtract => {
let Some(cutter_bounds) = brush_world_bounds(world, selected[1]) else {
set_status(world, "Subtract failed: cutter brush has no valid bounds");
return;
return csg_failure(world, "Subtract failed: cutter brush has no valid bounds");
};
let Some(overlap) = primary_bounds.intersection(cutter_bounds) else {
set_status(world, "Subtract failed: brushes do not overlap");
return;
return csg_failure(world, "Subtract failed: brushes do not overlap");
};
let Some(result) = largest_remaining_slab(primary_bounds, overlap) else {
set_status(world, "Subtract failed: result would be empty");
return;
return csg_failure(world, "Subtract failed: result would be empty");
};
result
}
@@ -175,14 +172,13 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
let new_brush = BrushDesc::cuboid(size);
let validation = validate_brush(&new_brush);
if !validation.is_valid() {
set_status(
return csg_failure(
world,
format!(
"CSG failed: result is invalid: {}",
first_brush_error(&validation)
),
);
return;
}
world.resource_mut::<BrushCsgPreview>().pending = Some(PendingBrushCsg {
@@ -197,6 +193,13 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
};
set_status(world, hint);
set_csg_operator_status(world, OperatorPhase::Preview, hint);
Ok(())
}
fn csg_failure(world: &mut World, message: impl Into<String>) -> Result<(), String> {
let message = message.into();
set_status(world, message.clone());
Err(message)
}
fn brush_csg_preview_input(world: &mut World) {
@@ -253,6 +256,22 @@ fn commit_csg_preview(world: &mut World, pending: PendingBrushCsg) {
);
return;
}
if pending
.selected
.iter()
.any(|entity| !crate::ui::selection_ops::is_mutable_level_object(world, *entity))
{
set_status(
world,
"Brush CSG commit blocked: selected content is no longer editable",
);
set_csg_operator_status(
world,
OperatorPhase::Blocked,
"Commit blocked: selected content is no longer editable",
);
return;
}
let new_brush = BrushDesc::cuboid(pending.result.size());
let to_delete: Vec<_> = if matches!(pending.op, BrushCsgOp::Merge | BrushCsgOp::Intersect) {
pending
@@ -265,7 +284,11 @@ fn commit_csg_preview(world: &mut World, pending: PendingBrushCsg) {
} else {
Vec::new()
};
apply_bounds_result(world, primary, pending.result, new_brush, &to_delete);
if !apply_bounds_result(world, primary, pending.result, new_brush, &to_delete) {
set_status(world, "Brush CSG commit made no changes");
set_csg_operator_status(world, OperatorPhase::Canceled, "No changes");
return;
}
let hint = match pending.op {
BrushCsgOp::Intersect => "Brush intersect committed",
BrushCsgOp::Merge => "Brush convex merge committed",
@@ -332,14 +355,14 @@ fn apply_bounds_result(
bounds: BrushBounds,
new_brush: BrushDesc,
delete_entities: &[Entity],
) {
) -> bool {
let center = bounds.center();
let old_transform = world.get::<Transform>(entity).copied().unwrap_or_default();
let mut new_transform = old_transform;
new_transform.translation = center;
new_transform.rotation = Quat::IDENTITY;
new_transform.scale = Vec3::ONE;
apply_brush_csg_with_history(world, entity, new_transform, new_brush, delete_entities);
apply_brush_csg_with_history(world, entity, new_transform, new_brush, delete_entities)
}
fn brush_world_bounds(world: &World, entity: Entity) -> Option<BrushBounds> {
@@ -426,6 +449,7 @@ mod tests {
use crate::history::{EditorCommand, EditorHistory};
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
use crate::selection::SelectedEntity;
use shared::LevelObject;
fn bounds(min: Vec3, max: Vec3) -> BrushBounds {
BrushBounds { min, max }
+62
View File
@@ -1047,6 +1047,17 @@ fn pick_face(
best
}
pub(crate) fn pick_brush_face_id(
brush: &BrushDesc,
transform: &GlobalTransform,
ray: Ray3d,
) -> Option<(ComponentInstanceId, f32)> {
let (BrushElementKey::Face { face }, distance) = pick_face(brush, transform, ray)? else {
return None;
};
Some((face, distance))
}
fn world_vertices(face: &BrushFaceDesc, transform: &GlobalTransform) -> Vec<Vec3> {
face.vertices
.iter()
@@ -1297,4 +1308,55 @@ mod tests {
assert!(state.old_brush.is_none());
assert!(!state.changed);
}
#[test]
fn brush_element_release_uses_production_finalizer_and_round_trips() {
let mut app = App::new();
app.init_resource::<ActiveOperator>()
.init_resource::<EditorHistory>()
.init_resource::<SceneIo>()
.init_resource::<BrushEditMode>()
.init_resource::<BrushElementSelection>()
.init_resource::<BrushElementGizmoState>()
.add_systems(Update, apply_brush_element_gizmo);
let original = BrushDesc::cuboid(Vec3::ONE);
let preview = BrushDesc::cuboid(Vec3::new(1.5, 1.0, 1.0));
let brush_entity = app
.world_mut()
.spawn((LevelObject, preview.clone(), GlobalTransform::default()))
.id();
let helper = app
.world_mut()
.spawn((
BrushElementGizmo,
Transform::default(),
GizmoTarget::default(),
))
.id();
*app.world_mut().resource_mut::<BrushEditMode>() = BrushEditMode::Vertex;
*app.world_mut().resource_mut::<BrushElementSelection>() = BrushElementSelection {
brush: Some(brush_entity),
elements: vec![BrushElementKey::Vertex {
face: original.faces[0].id.clone(),
index: 0,
}],
};
*app.world_mut().resource_mut::<BrushElementGizmoState>() = BrushElementGizmoState {
entity: Some(helper),
brush: Some(brush_entity),
old_brush: Some(original.clone()),
old_gizmo: Some(Transform::default()),
last_gizmo: Some(Transform::from_translation(Vec3::X * 0.25)),
changed: true,
};
let harness = OperatorInvariantHarness::capture(app.world_mut());
app.update();
harness.assert_committed(app.world_mut(), 1, 0);
harness.assert_status(app.world(), "brush.edit_mode", OperatorPhase::Committed);
assert_undo_redo_round_trip(app.world_mut(), original, preview, |world| {
world.get::<BrushDesc>(brush_entity).unwrap().clone()
});
}
}
@@ -0,0 +1,428 @@
//! Shared authored/runtime collider diagnostics for editor workflows.
use std::collections::HashMap;
use avian3d::prelude::{Collider, RigidBody};
use bevy::prelude::*;
use shared::{
authoring_component_active, AuthoringComponentStates, ColliderDesc, ColliderShapeDesc,
InspectorOrder, LevelObject, PhysicsBody, RigidBodyDesc, COMPONENT_COLLIDER_DESC,
COMPONENT_PHYSICS_BODY, COMPONENT_RIGID_BODY_DESC,
};
use crate::assets::asset_db::{find_asset_by_id, AssetRegistry};
use crate::ui::selection_ops::entity_name;
/// Collider dimensions beyond this world-space extent are usually accidental in a meter-scale
/// project and can severely degrade broad-phase performance.
pub const OVERSIZED_COLLIDER_EXTENT: f32 = 1_000.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ColliderDiagnosticSeverity {
Info,
Warning,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColliderDiagnostic {
pub code: &'static str,
pub severity: ColliderDiagnosticSeverity,
pub message: String,
pub repair: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColliderOverlayStatus {
Valid,
Trigger,
Disabled,
Warning,
Error,
}
#[derive(Debug, Clone)]
pub struct ColliderDiagnosticEntry {
pub entity: Entity,
pub actor_name: String,
pub shape_label: &'static str,
pub runtime_ready: bool,
pub diagnostics: Vec<ColliderDiagnostic>,
pub overlay_status: ColliderOverlayStatus,
}
impl ColliderDiagnosticEntry {
pub fn highest_severity(&self) -> Option<ColliderDiagnosticSeverity> {
self.diagnostics
.iter()
.map(|diagnostic| diagnostic.severity)
.max()
}
pub fn blocking_messages(&self) -> impl Iterator<Item = &str> {
self.diagnostics
.iter()
.filter(|diagnostic| diagnostic.severity == ColliderDiagnosticSeverity::Error)
.map(|diagnostic| diagnostic.message.as_str())
}
}
#[derive(Resource, Debug, Default)]
pub struct ColliderDiagnosticsState {
pub entries: HashMap<Entity, ColliderDiagnosticEntry>,
pub valid_actors: usize,
pub disabled_actors: usize,
pub warning_actors: usize,
pub error_actors: usize,
}
impl ColliderDiagnosticsState {
pub fn entry(&self, entity: Entity) -> Option<&ColliderDiagnosticEntry> {
self.entries.get(&entity)
}
}
pub fn refresh_collider_diagnostics(world: &mut World) {
let entities = world
.iter_entities()
.filter(|entity| entity.contains::<LevelObject>())
.map(|entity| entity.id())
.collect::<Vec<_>>();
let mut state = ColliderDiagnosticsState::default();
for entity in entities {
let Some(entry) = diagnose_collider(world, entity) else {
continue;
};
match entry.overlay_status {
ColliderOverlayStatus::Error => state.error_actors += 1,
ColliderOverlayStatus::Warning => state.warning_actors += 1,
ColliderOverlayStatus::Disabled => state.disabled_actors += 1,
_ => state.valid_actors += 1,
}
state.entries.insert(entity, entry);
}
world.insert_resource(state);
}
pub fn diagnose_collider(world: &World, entity: Entity) -> Option<ColliderDiagnosticEntry> {
let states = world.get::<AuthoringComponentStates>(entity);
let order = world.get::<InspectorOrder>(entity);
let rigid_body_active = world.get::<RigidBodyDesc>(entity).is_some()
&& authoring_component_active(states, order, COMPONENT_RIGID_BODY_DESC);
let legacy_active = world.get::<PhysicsBody>(entity).is_some()
&& authoring_component_active(states, order, COMPONENT_PHYSICS_BODY);
let collider = world.get::<ColliderDesc>(entity);
let collider_active =
collider.is_some() && authoring_component_active(states, order, COMPONENT_COLLIDER_DESC);
if !rigid_body_active && !legacy_active && collider.is_none() {
return None;
}
let mut diagnostics = Vec::new();
if rigid_body_active && !legacy_active && !collider_active {
diagnostics.push(ColliderDiagnostic {
code: "collider.missing",
severity: ColliderDiagnosticSeverity::Error,
message: "Rigid body has no active Collider component.".into(),
repair: "Add or enable a Collider component on this actor.".into(),
});
}
let mut shape_label = if legacy_active { "Legacy" } else { "Missing" };
let mut enabled = legacy_active;
let mut trigger = false;
let mut authoring_valid = true;
if let Some(collider) = collider {
shape_label = collider_shape_label(&collider.shape);
enabled = collider_active && collider.enabled;
trigger = collider.is_trigger;
if !collider_active {
diagnostics.push(ColliderDiagnostic {
code: "collider.inactive",
severity: ColliderDiagnosticSeverity::Info,
message: "Collider component is inactive.".into(),
repair: "Enable the component when this actor should participate in collision."
.into(),
});
} else if !collider.enabled {
diagnostics.push(ColliderDiagnostic {
code: "collider.disabled",
severity: ColliderDiagnosticSeverity::Info,
message: "Collider is disabled.".into(),
repair: "Enable the collider when collision is required.".into(),
});
} else {
let shape_diagnostics = validate_shape(world, entity, &collider.shape);
authoring_valid = shape_diagnostics
.iter()
.all(|diagnostic| diagnostic.severity != ColliderDiagnosticSeverity::Error);
diagnostics.extend(shape_diagnostics);
}
}
let runtime_ready = has_runtime_collider(world, entity);
if enabled && authoring_valid && !runtime_ready {
diagnostics.push(ColliderDiagnostic {
code: "collider.runtime_stale",
severity: ColliderDiagnosticSeverity::Warning,
message: "Authored collider has not hydrated into a runtime shape.".into(),
repair: "Check mesh cooking and asset references, then refresh the scene.".into(),
});
}
let highest = diagnostics
.iter()
.map(|diagnostic| diagnostic.severity)
.max();
let overlay_status = match highest {
Some(ColliderDiagnosticSeverity::Error) => ColliderOverlayStatus::Error,
Some(ColliderDiagnosticSeverity::Warning) => ColliderOverlayStatus::Warning,
_ if !enabled => ColliderOverlayStatus::Disabled,
_ if trigger => ColliderOverlayStatus::Trigger,
_ => ColliderOverlayStatus::Valid,
};
Some(ColliderDiagnosticEntry {
entity,
actor_name: entity_name(world, entity),
shape_label,
runtime_ready,
diagnostics,
overlay_status,
})
}
pub fn physics_placement_prerequisite_problems(world: &World, entity: Entity) -> Vec<String> {
let name = entity_name(world, entity);
let states = world.get::<AuthoringComponentStates>(entity);
let order = world.get::<InspectorOrder>(entity);
let split_body = world.get::<RigidBodyDesc>(entity).is_some()
&& authoring_component_active(states, order, COMPONENT_RIGID_BODY_DESC);
let legacy = world.get::<PhysicsBody>(entity).is_some()
&& authoring_component_active(states, order, COMPONENT_PHYSICS_BODY);
let collider = world.get::<ColliderDesc>(entity).filter(|collider| {
collider.enabled
&& !collider.is_trigger
&& authoring_component_active(states, order, COMPONENT_COLLIDER_DESC)
});
let mut problems = Vec::new();
if !split_body && !legacy {
problems.push(format!("{name}: add and enable a Rigid Body component"));
}
if collider.is_none() && !legacy {
problems.push(format!(
"{name}: add and enable a non-trigger Collider component"
));
}
if let Some(entry) = diagnose_collider(world, entity) {
problems.extend(
entry
.diagnostics
.iter()
.filter(|diagnostic| {
diagnostic.severity == ColliderDiagnosticSeverity::Error
&& diagnostic.code != "collider.missing"
})
.map(|diagnostic| format!("{name}: {}", diagnostic.message)),
);
}
if world.get::<RigidBody>(entity).is_none() {
problems.push(format!("{name}: rigid body has not hydrated yet"));
}
if !has_runtime_collider(world, entity) {
problems.push(format!(
"{name}: collider has not hydrated or finished cooking"
));
}
problems.sort();
problems.dedup();
problems
}
pub fn has_runtime_collider(world: &World, root: Entity) -> bool {
let mut pending = vec![root];
while let Some(entity) = pending.pop() {
if world.get::<Collider>(entity).is_some() {
return true;
}
if let Some(children) = world.get::<Children>(entity) {
pending.extend(children.iter());
}
}
false
}
pub fn collider_shape_label(shape: &ColliderShapeDesc) -> &'static str {
match shape {
ColliderShapeDesc::Cuboid { .. } => "Box",
ColliderShapeDesc::Sphere { .. } => "Sphere",
ColliderShapeDesc::Capsule { .. } => "Capsule",
ColliderShapeDesc::StaticMesh { .. } => "Static Mesh",
}
}
fn validate_shape(
world: &World,
entity: Entity,
shape: &ColliderShapeDesc,
) -> Vec<ColliderDiagnostic> {
let mut diagnostics = Vec::new();
let dimensions = match shape {
ColliderShapeDesc::Cuboid {
x_length,
y_length,
z_length,
} => Some(Vec3::new(*x_length, *y_length, *z_length)),
ColliderShapeDesc::Sphere { radius } => Some(Vec3::splat(*radius * 2.0)),
ColliderShapeDesc::Capsule { radius, height } => {
Some(Vec3::new(*radius * 2.0, *height, *radius * 2.0))
}
ColliderShapeDesc::StaticMesh { meshes, .. } => {
if meshes.is_empty() {
diagnostics.push(ColliderDiagnostic {
code: "collider.mesh_missing",
severity: ColliderDiagnosticSeverity::Error,
message: "Static mesh collider has no mesh sources.".into(),
repair: "Choose a mesh source or use the actor renderer meshes.".into(),
});
}
for mesh in meshes {
if !mesh.is_resolved() {
diagnostics.push(ColliderDiagnostic {
code: "collider.mesh_invalid_ref",
severity: ColliderDiagnosticSeverity::Error,
message: format!(
"Static mesh source `{}` has no stable asset or sub-asset ID.",
mesh.label
),
repair: "Choose a valid mesh from the asset browser.".into(),
});
} else if world
.get_resource::<AssetRegistry>()
.is_some_and(|registry| find_asset_by_id(registry, &mesh.asset_id).is_none())
{
diagnostics.push(ColliderDiagnostic {
code: "collider.mesh_stale_ref",
severity: ColliderDiagnosticSeverity::Error,
message: format!(
"Static mesh source `{}` no longer exists in the asset registry.",
mesh.label
),
repair: "Relink the collider to an existing mesh asset.".into(),
});
}
}
None
}
};
if let Some(dimensions) = dimensions {
if !dimensions.is_finite() || dimensions.min_element() <= 0.0 {
diagnostics.push(ColliderDiagnostic {
code: "collider.invalid_dimensions",
severity: ColliderDiagnosticSeverity::Error,
message: "Collider dimensions must be positive finite values.".into(),
repair: "Reset the shape or enter valid dimensions.".into(),
});
} else {
let scale = world
.get::<GlobalTransform>(entity)
.map(|global| global.to_scale_rotation_translation().0.abs())
.unwrap_or(Vec3::ONE);
let world_extent = (dimensions * scale).max_element();
if world_extent > OVERSIZED_COLLIDER_EXTENT {
diagnostics.push(ColliderDiagnostic {
code: "collider.oversized",
severity: ColliderDiagnosticSeverity::Warning,
message: format!(
"Collider spans {world_extent:.1} m in world space (recommended maximum: {OVERSIZED_COLLIDER_EXTENT:.0} m)."
),
repair: "Reduce collider dimensions or actor scale; split large collision into smaller actors."
.into(),
});
}
}
}
diagnostics
}
#[cfg(test)]
mod tests {
use super::*;
use shared::AuthoringRigidBody;
#[test]
fn reports_missing_invalid_oversized_and_stale_runtime_colliders() {
let mut world = World::new();
let missing = world
.spawn((LevelObject, RigidBodyDesc::default(), Transform::default()))
.id();
let invalid = world
.spawn((
LevelObject,
ColliderDesc {
enabled: true,
is_trigger: false,
shape: ColliderShapeDesc::Sphere { radius: 0.0 },
},
Transform::default(),
))
.id();
let oversized = world
.spawn((
LevelObject,
ColliderDesc::static_cuboid(Vec3::splat(2.0)),
Transform::from_scale(Vec3::splat(600.0)),
GlobalTransform::from(Transform::from_scale(Vec3::splat(600.0))),
))
.id();
let missing = diagnose_collider(&world, missing).unwrap();
assert!(missing
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == "collider.missing"));
let invalid = diagnose_collider(&world, invalid).unwrap();
assert!(invalid
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == "collider.invalid_dimensions"));
let oversized = diagnose_collider(&world, oversized).unwrap();
assert!(oversized
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == "collider.oversized"));
assert!(oversized
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == "collider.runtime_stale"));
}
#[test]
fn hydrated_trigger_has_trigger_overlay_status() {
let mut world = World::new();
let entity = world
.spawn((
LevelObject,
RigidBodyDesc {
body: AuthoringRigidBody::Static,
},
ColliderDesc {
enabled: true,
is_trigger: true,
shape: ColliderShapeDesc::Sphere { radius: 1.0 },
},
Collider::sphere(1.0),
Transform::default(),
))
.id();
let entry = diagnose_collider(&world, entity).unwrap();
assert_eq!(entry.overlay_status, ColliderOverlayStatus::Trigger);
assert!(entry.runtime_ready);
}
}
File diff suppressed because it is too large. Load diff
+9
View File
@@ -5,12 +5,17 @@ pub mod brush_csg;
pub mod brush_edit;
pub mod brush_tool;
pub mod camera;
pub mod collider_diagnostics;
pub mod gizmos;
pub mod material_drop;
mod panel;
pub mod physics_placement;
pub mod render_view;
pub mod rendering_diagnostics;
pub mod selection;
pub mod selection_outline;
pub mod terrain_paint;
pub mod terrain_sculpt;
pub mod viewport_mode;
pub mod visualizers;
@@ -21,5 +26,9 @@ pub use brush_csg::{
};
pub use brush_edit::{BrushEditMode, BrushEditPlugin, BrushElementSelection};
pub use brush_tool::{BrushToolPlugin, BrushToolState};
pub use material_drop::{MaterialDropFeedback, MaterialDropPlugin, MaterialDropState};
pub use panel::*;
pub use physics_placement::{PhysicsPlacementPlugin, PhysicsPlacementState};
pub use terrain_paint::{TerrainPaintMode, TerrainPaintPlugin, TerrainPaintState};
pub use terrain_sculpt::{TerrainSculptMode, TerrainSculptPlugin, TerrainSculptState};
pub use viewport_mode::EditorViewportMode;
@@ -0,0 +1,697 @@
//! Transactional gravity placement using the editor's hydrated Avian world.
use std::collections::HashSet;
use std::time::Duration;
use avian3d::prelude::*;
use bevy::prelude::*;
use crate::history::{set_transform_group_with_history, EditorHistory};
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
use crate::state::EditorMode;
use crate::ui::selection_ops::{entity_name, is_mutable_level_object};
use crate::viewport::collider_diagnostics::physics_placement_prerequisite_problems;
const STEP_HZ: f64 = 120.0;
const STEPS_PER_FRAME: usize = 4;
const SETTLE_LINEAR_SPEED: f32 = 0.04;
const SETTLE_ANGULAR_SPEED: f32 = 0.04;
const SETTLE_STEPS: u32 = 30;
const MAX_STEPS: u32 = 1_200;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PhysicsPlacementPhase {
#[default]
Inactive,
Dropping,
Settled,
TimedOut,
}
impl PhysicsPlacementPhase {
pub fn label(self) -> &'static str {
match self {
Self::Inactive => "Inactive",
Self::Dropping => "Simulating",
Self::Settled => "Settled",
Self::TimedOut => "Preview stopped",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PhysicsPlacementRequest {
#[default]
None,
Commit,
Cancel,
}
#[derive(Component, Debug, Clone, Copy, Default)]
pub struct PhysicsPlacementPreview;
#[derive(Resource, Debug, Default)]
pub struct PhysicsPlacementState {
pub phase: PhysicsPlacementPhase,
pub request: PhysicsPlacementRequest,
pub last_error: Option<String>,
pub selected_count: usize,
pub simulated_steps: u32,
session: Option<PlacementSession>,
}
impl PhysicsPlacementState {
pub fn active(&self) -> bool {
self.session.is_some()
}
pub fn simulated_seconds(&self) -> f32 {
self.simulated_steps as f32 / STEP_HZ as f32
}
}
#[derive(Debug)]
struct PlacementSession {
selected: Vec<BodySnapshot>,
frozen: Vec<BodySnapshot>,
stable_steps: u32,
}
#[derive(Debug, Clone)]
struct BodySnapshot {
entity: Entity,
transform: Transform,
position: Option<Position>,
rotation: Option<Rotation>,
rigid_body: RigidBody,
linear_velocity: Option<LinearVelocity>,
angular_velocity: Option<AngularVelocity>,
gravity_scale: Option<GravityScale>,
sleeping: bool,
sleeping_disabled: bool,
rigid_body_disabled: bool,
}
impl BodySnapshot {
fn capture(world: &World, entity: Entity) -> Result<Self, String> {
Ok(Self {
entity,
transform: world
.get::<Transform>(entity)
.copied()
.ok_or_else(|| format!("{} has no Transform", entity_name(world, entity)))?,
position: world.get::<Position>(entity).copied(),
rotation: world.get::<Rotation>(entity).copied(),
rigid_body: world.get::<RigidBody>(entity).copied().ok_or_else(|| {
format!("{} has no hydrated rigid body", entity_name(world, entity))
})?,
linear_velocity: world.get::<LinearVelocity>(entity).copied(),
angular_velocity: world.get::<AngularVelocity>(entity).copied(),
gravity_scale: world.get::<GravityScale>(entity).copied(),
sleeping: world.get::<Sleeping>(entity).is_some(),
sleeping_disabled: world.get::<SleepingDisabled>(entity).is_some(),
rigid_body_disabled: world.get::<RigidBodyDisabled>(entity).is_some(),
})
}
}
pub struct PhysicsPlacementPlugin;
impl Plugin for PhysicsPlacementPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<PhysicsPlacementState>()
.add_systems(PostStartup, pause_physics_for_editor)
.add_systems(PostUpdate, tick_physics_placement)
.add_systems(OnExit(EditorMode::Editing), cancel_physics_placement);
}
}
fn pause_physics_for_editor(mut physics_time: ResMut<Time<Physics>>) {
physics_time.pause();
}
pub fn begin_physics_placement(
world: &mut World,
selected: impl IntoIterator<Item = Entity>,
) -> Result<(), String> {
if *world.resource::<State<EditorMode>>().get() != EditorMode::Editing {
return placement_error(world, "Physics placement is available only in Edit mode");
}
if world.resource::<PhysicsPlacementState>().active() {
return placement_error(world, "A physics placement preview is already active");
}
let mut unique = HashSet::new();
let selected = selected
.into_iter()
.filter(|entity| unique.insert(*entity))
.collect::<Vec<_>>();
validate_selection(world, &selected)?;
let selected_set = selected.iter().copied().collect::<HashSet<_>>();
let selected_snapshots = selected
.iter()
.map(|entity| BodySnapshot::capture(world, *entity))
.collect::<Result<Vec<_>, _>>()?;
let movable = world
.query::<(Entity, &RigidBody)>()
.iter(world)
.filter_map(|(entity, body)| {
(!selected_set.contains(&entity) && *body != RigidBody::Static).then_some(entity)
})
.collect::<Vec<_>>();
let frozen_snapshots = movable
.iter()
.map(|entity| BodySnapshot::capture(world, *entity))
.collect::<Result<Vec<_>, _>>()?;
for snapshot in &frozen_snapshots {
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
entity.insert(RigidBody::Static);
}
}
for snapshot in &selected_snapshots {
let global = world
.get::<GlobalTransform>(snapshot.entity)
.copied()
.unwrap_or_else(|| GlobalTransform::from(snapshot.transform));
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
entity.insert((
RigidBody::Dynamic,
LinearVelocity::ZERO,
AngularVelocity::ZERO,
GravityScale(1.0),
Position(global.translation()),
Rotation(global.rotation()),
PhysicsPlacementPreview,
));
entity.remove::<Sleeping>();
entity.remove::<RigidBodyDisabled>();
}
}
let selected_count = selected_snapshots.len();
let mut state = world.resource_mut::<PhysicsPlacementState>();
state.phase = PhysicsPlacementPhase::Dropping;
state.request = PhysicsPlacementRequest::None;
state.last_error = None;
state.selected_count = selected_count;
state.simulated_steps = 0;
state.session = Some(PlacementSession {
selected: selected_snapshots,
frozen: frozen_snapshots,
stable_steps: 0,
});
set_operator_status(
world,
OperatorPhase::Preview,
format!("Dropping {selected_count} selected prop(s)"),
Vec::new(),
);
Ok(())
}
pub fn request_physics_placement(world: &mut World, request: PhysicsPlacementRequest) {
if world.resource::<PhysicsPlacementState>().active() {
world.resource_mut::<PhysicsPlacementState>().request = request;
}
}
pub fn cancel_physics_placement(world: &mut World) {
finish_physics_placement(world, false);
}
pub fn commit_physics_placement(world: &mut World) {
finish_physics_placement(world, true);
}
fn finish_physics_placement(world: &mut World, commit: bool) {
let Some(mut state) = world.remove_resource::<PhysicsPlacementState>() else {
return;
};
let Some(session) = state.session.take() else {
world.insert_resource(state);
return;
};
let final_transforms = session
.selected
.iter()
.filter_map(|snapshot| {
world
.get::<Transform>(snapshot.entity)
.copied()
.map(|transform| (snapshot.entity, transform))
})
.collect::<Vec<_>>();
for snapshot in &session.frozen {
restore_snapshot(world, snapshot, true);
}
for snapshot in &session.selected {
restore_snapshot(world, snapshot, !commit);
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
entity.remove::<PhysicsPlacementPreview>();
}
}
let undo_depth = world.resource::<EditorHistory>().undo_depth();
if commit {
let changes = session.selected.iter().filter_map(|snapshot| {
final_transforms
.iter()
.find(|(entity, _)| *entity == snapshot.entity)
.map(|(_, new)| (snapshot.entity, snapshot.transform, *new))
});
set_transform_group_with_history(world, changes);
}
let committed = commit && world.resource::<EditorHistory>().undo_depth() > undo_depth;
state.phase = PhysicsPlacementPhase::Inactive;
state.request = PhysicsPlacementRequest::None;
state.selected_count = 0;
state.simulated_steps = 0;
state.last_error = None;
world.insert_resource(state);
let (phase, hint) = if committed {
(OperatorPhase::Committed, "Physics placement committed")
} else if commit {
(OperatorPhase::Canceled, "Physics placement made no changes")
} else {
(OperatorPhase::Canceled, "Physics placement canceled")
};
set_operator_status(world, phase, hint.to_string(), Vec::new());
}
fn tick_physics_placement(world: &mut World) {
let escape = world
.get_resource::<ButtonInput<KeyCode>>()
.is_some_and(|keys| keys.just_pressed(KeyCode::Escape));
let enter = world
.get_resource::<ButtonInput<KeyCode>>()
.is_some_and(|keys| keys.just_pressed(KeyCode::Enter));
let request = world.resource::<PhysicsPlacementState>().request;
let settled = matches!(
world.resource::<PhysicsPlacementState>().phase,
PhysicsPlacementPhase::Settled | PhysicsPlacementPhase::TimedOut
);
if escape || request == PhysicsPlacementRequest::Cancel {
cancel_physics_placement(world);
return;
}
if request == PhysicsPlacementRequest::Commit || (enter && settled) {
commit_physics_placement(world);
return;
}
if world.resource::<PhysicsPlacementState>().phase != PhysicsPlacementPhase::Dropping {
return;
}
for _ in 0..STEPS_PER_FRAME {
world
.resource_mut::<Time<Physics>>()
.advance_by(Duration::from_secs_f64(1.0 / STEP_HZ));
world.run_schedule(FixedPostUpdate);
}
let Some(mut state) = world.remove_resource::<PhysicsPlacementState>() else {
return;
};
state.simulated_steps = state.simulated_steps.saturating_add(STEPS_PER_FRAME as u32);
let Some(session) = state.session.as_mut() else {
world.insert_resource(state);
return;
};
let at_rest = session.selected.iter().all(|snapshot| {
let linear = world
.get::<LinearVelocity>(snapshot.entity)
.map_or(0.0, |velocity| velocity.length());
let angular = world
.get::<AngularVelocity>(snapshot.entity)
.map_or(0.0, |velocity| velocity.length());
(linear <= SETTLE_LINEAR_SPEED && angular <= SETTLE_ANGULAR_SPEED)
|| world.get::<Sleeping>(snapshot.entity).is_some()
});
session.stable_steps = if at_rest {
session.stable_steps.saturating_add(STEPS_PER_FRAME as u32)
} else {
0
};
let mut status = None;
if session.stable_steps >= SETTLE_STEPS {
state.phase = PhysicsPlacementPhase::Settled;
status = Some((
OperatorPhase::Preview,
"Placement settled; commit or cancel".to_string(),
Vec::new(),
));
} else if state.simulated_steps >= MAX_STEPS {
state.phase = PhysicsPlacementPhase::TimedOut;
status = Some((
OperatorPhase::Preview,
"Placement reached its 10 second preview limit".to_string(),
vec!["Bodies are still moving; commit the current pose or cancel".to_string()],
));
}
world.insert_resource(state);
if let Some((phase, hint, warnings)) = status {
set_operator_status(world, phase, hint, warnings);
}
}
fn validate_selection(world: &mut World, selected: &[Entity]) -> Result<(), String> {
if selected.is_empty() {
return placement_error(world, "Select at least one prop to place with physics");
}
let mut problems = Vec::new();
for entity in selected {
let name = entity_name(world, *entity);
if !is_mutable_level_object(world, *entity) {
problems.push(format!(
"{name}: selection is locked, linked, or not a level object"
));
continue;
}
problems.extend(physics_placement_prerequisite_problems(world, *entity));
}
if problems.is_empty() {
Ok(())
} else {
placement_error(world, problems.join("\n"))
}
}
fn restore_snapshot(world: &mut World, snapshot: &BodySnapshot, restore_pose: bool) {
let Ok(mut entity) = world.get_entity_mut(snapshot.entity) else {
return;
};
entity.insert(snapshot.rigid_body);
restore_optional(&mut entity, snapshot.linear_velocity);
restore_optional(&mut entity, snapshot.angular_velocity);
restore_optional(&mut entity, snapshot.gravity_scale);
restore_marker::<Sleeping>(&mut entity, snapshot.sleeping);
restore_marker::<SleepingDisabled>(&mut entity, snapshot.sleeping_disabled);
restore_marker::<RigidBodyDisabled>(&mut entity, snapshot.rigid_body_disabled);
if restore_pose {
entity.insert(snapshot.transform);
restore_optional(&mut entity, snapshot.position);
restore_optional(&mut entity, snapshot.rotation);
}
}
fn restore_optional<T: Component + Clone>(entity: &mut EntityWorldMut<'_>, value: Option<T>) {
if let Some(value) = value {
entity.insert(value);
} else {
entity.remove::<T>();
}
}
fn restore_marker<T: Component + Default>(entity: &mut EntityWorldMut<'_>, present: bool) {
if present {
entity.insert(T::default());
} else {
entity.remove::<T>();
}
}
fn placement_error<T>(world: &mut World, message: impl Into<String>) -> Result<T, String> {
let message = message.into();
world.resource_mut::<PhysicsPlacementState>().last_error = Some(message.clone());
set_operator_status(
world,
OperatorPhase::Blocked,
"Physics placement could not start".to_string(),
message.lines().map(str::to_string).collect(),
);
Err(message)
}
fn set_operator_status(
world: &mut World,
phase: OperatorPhase,
hint: String,
warnings: Vec<String>,
) {
if let Some(mut operator) = world.get_resource_mut::<ActiveOperator>() {
operator.status = Some(OperatorStatus {
id: "physics.placement".to_string(),
label: "Physics Placement".to_string(),
phase,
hint,
warnings,
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::history::EditorHistory;
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
use crate::scene_io::SceneIo;
use bevy::asset::{AssetApp, AssetPlugin};
use bevy::state::app::StatesPlugin;
use shared::{ColliderDesc, LevelObject, RigidBodyDesc};
fn app_with_physics() -> App {
let mut app = App::new();
app.add_plugins((
MinimalPlugins,
AssetPlugin::default(),
StatesPlugin,
TransformPlugin,
PhysicsPlugins::default(),
))
.init_asset::<Mesh>()
.init_state::<EditorMode>()
.init_resource::<PhysicsPlacementState>()
.init_resource::<EditorHistory>()
.init_resource::<ActiveOperator>()
.init_resource::<SceneIo>();
app.finish();
app.cleanup();
app.update();
app.world_mut().resource_mut::<Time<Physics>>().pause();
app
}
fn spawn_placeable(world: &mut World, name: &str, transform: Transform) -> Entity {
world
.spawn((
Name::new(name.to_string()),
LevelObject,
RigidBodyDesc::default(),
ColliderDesc::default(),
RigidBody::Static,
Collider::cuboid(1.0, 1.0, 1.0),
transform,
))
.id()
}
#[test]
fn reports_missing_authoring_prerequisites_without_starting() {
let mut app = app_with_physics();
let entity = app
.world_mut()
.spawn((Name::new("No Physics"), LevelObject, Transform::default()))
.id();
let harness = OperatorInvariantHarness::capture(app.world_mut());
let error = begin_physics_placement(app.world_mut(), [entity]).unwrap_err();
assert!(error.contains("add and enable a Rigid Body"));
assert!(error.contains("add and enable a non-trigger Collider"));
assert!(!app.world().resource::<PhysicsPlacementState>().active());
harness.assert_blocked(app.world_mut());
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Blocked);
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
}
#[test]
fn cancel_restores_selected_and_unrelated_motion_state_exactly() {
let mut app = app_with_physics();
let selected = spawn_placeable(
app.world_mut(),
"Selected",
Transform::from_xyz(1.0, 4.0, 2.0),
);
app.world_mut().entity_mut(selected).insert((
RigidBody::Kinematic,
LinearVelocity(Vec3::new(1.0, 2.0, 3.0)),
AngularVelocity(Vec3::new(0.1, 0.2, 0.3)),
GravityScale(0.25),
SleepingDisabled,
));
let unrelated = app
.world_mut()
.spawn((
RigidBody::Dynamic,
Collider::sphere(0.5),
LinearVelocity(Vec3::X * 3.0),
Transform::from_xyz(8.0, 2.0, 0.0),
))
.id();
app.update();
let harness = OperatorInvariantHarness::capture(app.world_mut());
begin_physics_placement(app.world_mut(), [selected]).unwrap();
assert_eq!(
app.world().get::<RigidBody>(selected),
Some(&RigidBody::Dynamic)
);
assert_eq!(
app.world().get::<RigidBody>(unrelated),
Some(&RigidBody::Static)
);
for _ in 0..10 {
tick_physics_placement(app.world_mut());
}
assert!(
app.world()
.get::<Transform>(selected)
.unwrap()
.translation
.y
< 4.0
);
cancel_physics_placement(app.world_mut());
assert_eq!(
app.world().get::<Transform>(selected).unwrap().translation,
Vec3::new(1.0, 4.0, 2.0)
);
assert_eq!(
app.world().get::<RigidBody>(selected),
Some(&RigidBody::Kinematic)
);
assert_eq!(
app.world().get::<LinearVelocity>(selected),
Some(&LinearVelocity(Vec3::new(1.0, 2.0, 3.0)))
);
assert_eq!(
app.world().get::<GravityScale>(selected),
Some(&GravityScale(0.25))
);
assert!(app.world().get::<SleepingDisabled>(selected).is_some());
assert_eq!(
app.world().get::<RigidBody>(unrelated),
Some(&RigidBody::Dynamic)
);
assert_eq!(
app.world().get::<LinearVelocity>(unrelated),
Some(&LinearVelocity(Vec3::X * 3.0))
);
assert_eq!(app.world().resource::<EditorHistory>().undo_depth(), 0);
harness.assert_canceled(app.world_mut());
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Canceled);
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
}
#[test]
fn real_physics_drop_commits_once_and_undo_restores_start_transform() {
let mut app = app_with_physics();
app.world_mut().spawn((
RigidBody::Static,
Collider::cuboid(20.0, 0.5, 20.0),
Transform::from_xyz(0.0, -0.25, 0.0),
));
let start = Transform::from_xyz(0.0, 4.0, 0.0);
let prop = spawn_placeable(app.world_mut(), "Drop Prop", start);
app.update();
let harness = OperatorInvariantHarness::capture(app.world_mut());
begin_physics_placement(app.world_mut(), [prop]).unwrap();
for _ in 0..400 {
tick_physics_placement(app.world_mut());
if app.world().resource::<PhysicsPlacementState>().phase
== PhysicsPlacementPhase::Settled
{
break;
}
}
assert_eq!(
app.world().resource::<PhysicsPlacementState>().phase,
PhysicsPlacementPhase::Settled
);
let settled = *app.world().get::<Transform>(prop).unwrap();
assert!(settled.translation.y < 1.0, "{settled:?}");
commit_physics_placement(app.world_mut());
harness.assert_committed(app.world_mut(), 1, 0);
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Committed);
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
assert_eq!(
app.world().resource::<EditorHistory>().status,
"Undo: Move Selection"
);
assert_eq!(app.world().get::<RigidBody>(prop), Some(&RigidBody::Static));
assert_eq!(*app.world().get::<Transform>(prop).unwrap(), settled);
assert_undo_redo_round_trip(app.world_mut(), start, settled, |world| {
*world.get::<Transform>(prop).unwrap()
});
}
#[test]
fn no_op_commit_terminates_without_dirtying_or_history() {
let mut app = app_with_physics();
let start = Transform::from_xyz(0.0, 4.0, 0.0);
let prop = spawn_placeable(app.world_mut(), "Static Prop", start);
app.update();
let harness = OperatorInvariantHarness::capture(app.world_mut());
begin_physics_placement(app.world_mut(), [prop]).unwrap();
commit_physics_placement(app.world_mut());
harness.assert_canceled(app.world_mut());
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Canceled);
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
assert_eq!(*app.world().get::<Transform>(prop).unwrap(), start);
assert_eq!(app.world().get::<RigidBody>(prop), Some(&RigidBody::Static));
}
#[test]
fn multi_select_commit_is_one_transaction_and_cleans_every_preview_helper() {
let mut app = app_with_physics();
let starts = [
Transform::from_xyz(-1.0, 4.0, 0.0),
Transform::from_xyz(1.0, 6.0, 0.0),
];
let first = spawn_placeable(app.world_mut(), "First", starts[0]);
let second = spawn_placeable(app.world_mut(), "Second", starts[1]);
app.update();
let harness = OperatorInvariantHarness::capture(app.world_mut());
begin_physics_placement(app.world_mut(), [first, second, first]).unwrap();
assert_eq!(
app.world()
.resource::<PhysicsPlacementState>()
.selected_count,
2,
"duplicate selections must collapse to one placement snapshot"
);
let committed = [
Transform::from_xyz(-1.0, 0.5, 0.0),
Transform::from_xyz(1.0, 0.5, 0.0),
];
app.world_mut().entity_mut(first).insert(committed[0]);
app.world_mut().entity_mut(second).insert(committed[1]);
commit_physics_placement(app.world_mut());
harness.assert_committed(app.world_mut(), 1, 0);
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Committed);
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
assert_undo_redo_round_trip(app.world_mut(), starts, committed, |world| {
[
*world.get::<Transform>(first).unwrap(),
*world.get::<Transform>(second).unwrap(),
]
});
}
}
+115 -1
View File
@@ -14,6 +14,7 @@ use crate::ui::helpers::ensure_player_spawn_for_edit;
use crate::ui::hierarchy_ops::is_entity_locked;
use crate::ui::hierarchy_state::HierarchyPanelState;
use crate::ui::UiState;
use crate::ui::ViewportUiState;
use crate::viewport::actor_icons::ActorIconProxy;
use crate::viewport::brush_edit::{BrushEditMode, BrushElementGizmo};
use crate::viewport::brush_tool::BrushToolState;
@@ -21,7 +22,11 @@ use crate::viewport::ViewportDisplayMode;
use crate::visualizers::EditorVisualizerProxy;
use bevy_egui::egui;
use crate::viewport::material_drop::{MaterialDropSet, MaterialDropState};
use crate::viewport::physics_placement::PhysicsPlacementState;
use crate::viewport::scene_view_ray;
use crate::viewport::terrain_paint::TerrainPaintState;
use crate::viewport::terrain_sculpt::TerrainSculptState;
#[derive(Resource, Default, Debug, Clone, Copy)]
pub struct SelectedEntity(pub Option<Entity>);
@@ -47,6 +52,11 @@ struct PickTargetQueries<'w, 's> {
icon_proxies: Query<'w, 's, &'static ActorIconProxy>,
parents: Query<'w, 's, &'static ChildOf>,
editor_only: Query<'w, 's, (), With<EditorOnly>>,
material_drop: Option<Res<'w, MaterialDropState>>,
terrain_sculpt: Res<'w, TerrainSculptState>,
terrain_paint: Res<'w, TerrainPaintState>,
physics_placement: Option<Res<'w, PhysicsPlacementState>>,
viewport_ui: Res<'w, ViewportUiState>,
}
impl Plugin for EditorSelectionPlugin {
@@ -68,6 +78,7 @@ impl Plugin for EditorSelectionPlugin {
Last,
(handle_pick_events, cycle_overlapping_viewport_pick)
.chain()
.after(MaterialDropSet)
.run_if(scene_tools_active),
);
}
@@ -110,6 +121,35 @@ fn handle_pick_events(
gizmo_targets: Query<&GizmoTarget>,
hierarchy: Option<Res<HierarchyPanelState>>,
) -> Result {
if ui_state.viewport_pointer_pos.is_some_and(|pointer| {
pick_targets
.viewport_ui
.toolbar_rect
.is_some_and(|rect| rect.contains(pointer))
}) {
viewport_click.0 = None;
for _ in click_events.read() {}
return Ok(());
}
if pick_targets.terrain_sculpt.active
|| pick_targets.terrain_paint.active
|| pick_targets
.physics_placement
.as_deref()
.is_some_and(PhysicsPlacementState::active)
{
viewport_click.0 = None;
for _ in click_events.read() {}
return Ok(());
}
if pick_targets
.material_drop
.as_deref()
.is_some_and(MaterialDropState::captures_viewport_input)
{
viewport_click.0 = None;
return Ok(());
}
if ui_state.pointer_in_viewport
&& !buttons.any_pressed([MouseButton::Right, MouseButton::Middle])
&& keys.just_pressed(KeyCode::Escape)
@@ -209,6 +249,10 @@ fn handle_pick_events(
Ok(())
}
#[expect(
clippy::too_many_arguments,
reason = "selection cycling reads independent viewport input ownership resources"
)]
fn cycle_overlapping_viewport_pick(
mut ui_state: ResMut<UiState>,
mut selected: ResMut<SelectedEntity>,
@@ -216,7 +260,19 @@ fn cycle_overlapping_viewport_pick(
keys: Res<ButtonInput<KeyCode>>,
buttons: Res<ButtonInput<MouseButton>>,
display: Res<ViewportDisplayMode>,
material_drop: Option<Res<MaterialDropState>>,
terrain_sculpt: Res<TerrainSculptState>,
terrain_paint: Res<TerrainPaintState>,
) -> Result {
if terrain_sculpt.active || terrain_paint.active {
return Ok(());
}
if material_drop
.as_deref()
.is_some_and(MaterialDropState::captures_viewport_input)
{
return Ok(());
}
if display.clean_game_view {
return Ok(());
}
@@ -397,13 +453,23 @@ fn sync_gizmo_targets(
hierarchy: Option<Res<HierarchyPanelState>>,
display: Res<ViewportDisplayMode>,
brush_mode: Res<BrushEditMode>,
terrain_sculpt: Res<TerrainSculptState>,
terrain_paint: Res<TerrainPaintState>,
physics_placement: Option<Res<PhysicsPlacementState>>,
) {
ui_state
.selected_entities
.retain(|entity| transforms.contains(entity) && !editor_only.contains(entity));
selected.0 = ui_state.selected_entities.as_slice().first().copied();
if display.clean_game_view || brush_mode.is_element_mode() {
if display.clean_game_view
|| brush_mode.is_element_mode()
|| terrain_sculpt.active
|| terrain_paint.active
|| physics_placement
.as_deref()
.is_some_and(PhysicsPlacementState::active)
{
for (entity, brush_element_gizmo) in &targets {
if brush_element_gizmo.is_none() {
commands.entity(entity).remove::<GizmoTarget>();
@@ -456,6 +522,8 @@ mod tests {
.init_resource::<SelectedEntity>()
.init_resource::<ViewportDisplayMode>()
.init_resource::<BrushEditMode>()
.init_resource::<TerrainSculptState>()
.init_resource::<TerrainPaintState>()
.add_systems(Update, sync_gizmo_targets);
app.update();
@@ -470,4 +538,50 @@ mod tests {
assert!(app.world().get::<GizmoTarget>(first).is_some());
assert!(app.world().get::<GizmoTarget>(second).is_none());
}
#[test]
fn terrain_sculpt_owns_pointer_without_transform_gizmo() {
let mut app = App::new();
let terrain = app
.world_mut()
.spawn((LevelObject, Transform::default(), GizmoTarget::default()))
.id();
let mut ui_state = UiState::default_layout();
ui_state.selected_entities.select_replace(terrain);
let mut sculpt = TerrainSculptState::default();
sculpt.start(terrain);
app.insert_resource(ui_state)
.insert_resource(sculpt)
.init_resource::<SelectedEntity>()
.init_resource::<ViewportDisplayMode>()
.init_resource::<BrushEditMode>()
.init_resource::<TerrainPaintState>()
.add_systems(Update, sync_gizmo_targets);
app.update();
assert!(app.world().get::<GizmoTarget>(terrain).is_none());
}
#[test]
fn terrain_paint_owns_pointer_without_transform_gizmo() {
let mut app = App::new();
let terrain = app
.world_mut()
.spawn((LevelObject, Transform::default(), GizmoTarget::default()))
.id();
let mut ui_state = UiState::default_layout();
ui_state.selected_entities.select_replace(terrain);
let mut paint = TerrainPaintState::default();
paint.start(terrain, 2);
app.insert_resource(ui_state)
.insert_resource(paint)
.init_resource::<SelectedEntity>()
.init_resource::<ViewportDisplayMode>()
.init_resource::<BrushEditMode>()
.init_resource::<TerrainSculptState>()
.add_systems(Update, sync_gizmo_targets);
app.update();
assert!(app.world().get::<GizmoTarget>(terrain).is_none());
}
}
+795
View File
@@ -0,0 +1,795 @@
//! Modal terrain material-weight painting with exact cancel and grouped history.
use bevy::prelude::*;
use bevy_egui::EguiContexts;
use shared::{TerrainDesc, AUTHORING_COMPONENT_TERRAIN, COMPONENT_TERRAIN_DESC};
use super::terrain_sculpt::{active_scene_ray, smooth_falloff, terrain_ray_hit, TerrainHit};
use crate::camera::EditorCamera;
use crate::history::{reflected_component_transaction, EditorHistory};
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
use crate::scene_io::SceneIo;
use crate::selection::{SelectedEntity, ViewportClick};
use crate::state::scene_tools_active;
use crate::ui::UiState;
use crate::viewport::ViewportDisplayMode;
const MIN_RADIUS: f32 = 0.25;
const MAX_RADIUS: f32 = 128.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TerrainPaintMode {
#[default]
Paint,
Erase,
}
impl TerrainPaintMode {
pub fn label(self) -> &'static str {
match self {
Self::Paint => "Paint",
Self::Erase => "Erase",
}
}
}
#[derive(Debug, Clone)]
struct TerrainPaintStroke {
entity: Entity,
original: TerrainDesc,
last_local: Vec3,
}
#[derive(Resource, Debug, Clone)]
pub struct TerrainPaintState {
pub active: bool,
pub mode: TerrainPaintMode,
pub active_layer: usize,
pub radius: f32,
pub strength: f32,
hover: Option<TerrainHit>,
stroke: Option<TerrainPaintStroke>,
target: Option<Entity>,
}
impl Default for TerrainPaintState {
fn default() -> Self {
Self {
active: false,
mode: TerrainPaintMode::Paint,
active_layer: 1,
radius: 4.0,
strength: 0.35,
hover: None,
stroke: None,
target: None,
}
}
}
impl TerrainPaintState {
pub fn start(&mut self, target: Entity, layer_count: usize) {
self.active = true;
self.target = Some(target);
self.active_layer = self.active_layer.min(layer_count.saturating_sub(1));
}
pub fn stop(&mut self) {
self.active = false;
self.hover = None;
self.target = None;
}
pub fn is_stroking(&self) -> bool {
self.stroke.is_some()
}
pub fn clamp_settings(&mut self) {
self.radius = self.radius.clamp(MIN_RADIUS, MAX_RADIUS);
self.strength = self.strength.clamp(0.01, 1.0);
}
}
pub struct TerrainPaintPlugin;
impl Plugin for TerrainPaintPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<TerrainPaintState>().add_systems(
Update,
(terrain_paint_input, draw_terrain_paint_preview)
.chain()
.run_if(scene_tools_active),
);
}
}
#[allow(clippy::too_many_arguments)]
fn terrain_paint_input(
mut commands: Commands,
mut state: ResMut<TerrainPaintState>,
mut selected: ResMut<SelectedEntity>,
keys: Res<ButtonInput<KeyCode>>,
buttons: Res<ButtonInput<MouseButton>>,
mut contexts: EguiContexts,
ui_state: Res<UiState>,
display: Res<ViewportDisplayMode>,
cameras: Query<(&Camera, &GlobalTransform), With<EditorCamera>>,
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
mut viewport_click: ResMut<ViewportClick>,
mut scene_io: ResMut<SceneIo>,
mut active_operator: ResMut<ActiveOperator>,
) -> Result {
if !state.active {
return Ok(());
}
viewport_click.0 = None;
state.clamp_settings();
let Some(entity) = state.target.or(selected.0) else {
stop_tool_with_rollback(
&mut state,
&mut terrains,
&mut scene_io,
&mut active_operator,
OperatorPhase::Blocked,
"Terrain paint stopped: target is unavailable",
"Target unavailable",
);
return Ok(());
};
if selected.0 != Some(entity) {
selected.0 = Some(entity);
}
if display.clean_game_view {
stop_tool_with_rollback(
&mut state,
&mut terrains,
&mut scene_io,
&mut active_operator,
OperatorPhase::Canceled,
"Terrain paint stopped for clean game view",
"Clean game view enabled; weights restored",
);
return Ok(());
}
let ctx = contexts.ctx_mut()?;
let cancel_requested =
keys.just_pressed(KeyCode::Escape) || buttons.just_pressed(MouseButton::Right);
if cancel_requested {
if state.is_stroking() {
cancel_active_stroke(
&mut state,
&mut terrains,
&mut scene_io,
&mut active_operator,
);
} else {
state.stop();
scene_io.status = "Terrain paint tool closed".into();
set_status(&mut active_operator, OperatorPhase::Canceled, "Tool closed");
}
return Ok(());
}
let Ok((global, mut terrain)) = terrains.get_mut(entity) else {
stop_tool_with_rollback(
&mut state,
&mut terrains,
&mut scene_io,
&mut active_operator,
OperatorPhase::Blocked,
"Terrain paint stopped: target no longer exists",
"Target no longer exists",
);
return Ok(());
};
let layer_count = terrain.material_layers.len();
if layer_count == 0 {
if let Some(stroke) = state.stroke.take() {
*terrain = stroke.original;
}
state.stop();
scene_io.status = "Add a terrain material layer before painting".into();
set_status(
&mut active_operator,
OperatorPhase::Blocked,
"Add a material layer before painting",
);
return Ok(());
}
state.active_layer = state.active_layer.min(layer_count - 1);
state.hover = ui_state
.viewport_pointer_pos
.and_then(|pointer| active_scene_ray(&cameras, pointer, ui_state.viewport_rect))
.and_then(|ray| terrain_ray_hit(entity, &terrain, global, ray));
if buttons.just_pressed(MouseButton::Left) && !ctx.egui_wants_pointer_input() {
if let Some(hit) = state.hover.filter(|hit| hit.entity == entity) {
let original = terrain.clone();
terrain.ensure_material_weights();
apply_weight_dab(
&mut terrain,
hit.local,
state.radius,
state.strength,
state.active_layer,
state.mode,
);
state.stroke = Some(TerrainPaintStroke {
entity,
original,
last_local: hit.local,
});
set_status(
&mut active_operator,
OperatorPhase::Preview,
format!(
"{} layer {} in progress",
state.mode.label(),
state.active_layer + 1
),
);
}
} else if buttons.pressed(MouseButton::Left) {
let radius = state.radius;
let strength = state.strength;
let layer = state.active_layer;
let mode = state.mode;
if let (Some(hit), Some(stroke)) = (state.hover, state.stroke.as_mut()) {
if hit.entity == stroke.entity {
let step = (radius * 0.2).max(terrain.sample_spacing * 0.25);
let delta = hit.local - stroke.last_local;
let distance = Vec2::new(delta.x, delta.z).length();
if distance >= step {
let count = (distance / step).floor() as usize;
for index in 1..=count {
let point = stroke.last_local + delta * (index as f32 / count as f32);
apply_weight_dab(&mut terrain, point, radius, strength, layer, mode);
}
stroke.last_local = hit.local;
}
}
}
}
if buttons.just_released(MouseButton::Left) {
if let Some(stroke) = state.stroke.take() {
let final_terrain = terrain.clone();
let mode = state.mode;
commands.queue(move |world: &mut World| {
finish_paint_stroke(world, stroke, final_terrain, mode);
});
}
}
Ok(())
}
fn commit_paint_stroke(
world: &mut World,
stroke: TerrainPaintStroke,
final_terrain: TerrainDesc,
) -> Result<(), String> {
let original = stroke.original;
if let Ok(mut actor) = world.get_entity_mut(stroke.entity) {
actor.insert(original.clone());
}
let result = reflected_component_transaction(
world,
stroke.entity,
"Paint Terrain Material",
AUTHORING_COMPONENT_TERRAIN,
COMPONENT_TERRAIN_DESC,
move |world, entity| {
world.entity_mut(entity).insert(final_terrain);
Ok(())
},
);
if result.is_err() {
if let Ok(mut actor) = world.get_entity_mut(stroke.entity) {
actor.insert(original);
}
}
result
}
fn finish_paint_stroke(
world: &mut World,
stroke: TerrainPaintStroke,
final_terrain: TerrainDesc,
mode: TerrainPaintMode,
) {
let undo_depth = world.resource::<EditorHistory>().undo_depth();
match commit_paint_stroke(world, stroke, final_terrain) {
Ok(()) if world.resource::<EditorHistory>().undo_depth() > undo_depth => {
world.resource_mut::<SceneIo>().status =
format!("{} terrain material weights committed", mode.label());
set_status(
&mut world.resource_mut::<ActiveOperator>(),
OperatorPhase::Committed,
format!("{} weights; Ctrl+Z to undo", mode.label()),
);
}
Ok(()) => {
world.resource_mut::<SceneIo>().status =
format!("{} terrain stroke made no changes", mode.label());
set_status(
&mut world.resource_mut::<ActiveOperator>(),
OperatorPhase::Canceled,
format!("{} stroke made no changes", mode.label()),
);
}
Err(error) => {
world.resource_mut::<SceneIo>().status =
format!("Terrain paint commit failed: {error}");
set_status(
&mut world.resource_mut::<ActiveOperator>(),
OperatorPhase::Blocked,
format!("Commit failed: {error}"),
);
}
}
}
fn cancel_active_stroke(
state: &mut TerrainPaintState,
terrains: &mut Query<(&GlobalTransform, &mut TerrainDesc)>,
scene_io: &mut SceneIo,
active_operator: &mut ActiveOperator,
) {
cancel_stroke(state, terrains);
scene_io.status = "Terrain paint stroke canceled".into();
set_status(active_operator, OperatorPhase::Canceled, "Weights restored");
}
fn stop_tool_with_rollback(
state: &mut TerrainPaintState,
terrains: &mut Query<(&GlobalTransform, &mut TerrainDesc)>,
scene_io: &mut SceneIo,
active_operator: &mut ActiveOperator,
phase: OperatorPhase,
message: &str,
hint: &str,
) {
cancel_stroke(state, terrains);
state.stop();
scene_io.status = message.to_string();
set_status(active_operator, phase, hint);
}
fn cancel_stroke(
state: &mut TerrainPaintState,
terrains: &mut Query<(&GlobalTransform, &mut TerrainDesc)>,
) {
let Some(stroke) = state.stroke.take() else {
return;
};
if let Ok((_, mut terrain)) = terrains.get_mut(stroke.entity) {
*terrain = stroke.original;
}
}
fn set_status(active: &mut ActiveOperator, phase: OperatorPhase, hint: impl Into<String>) {
active.status = Some(OperatorStatus {
id: "terrain.paint".into(),
label: "Terrain Paint".into(),
phase,
hint: hint.into(),
warnings: Vec::new(),
});
}
fn apply_weight_dab(
terrain: &mut TerrainDesc,
center: Vec3,
radius: f32,
strength: f32,
active_layer: usize,
mode: TerrainPaintMode,
) {
terrain.ensure_material_weights();
let layer_count = terrain.material_layers.len().clamp(1, 4);
if active_layer >= layer_count {
return;
}
let radius = radius.max(MIN_RADIUS);
let half_extent = (terrain.resolution - 1) as f32 * terrain.sample_spacing * 0.5;
for z in 0..terrain.resolution {
for x in 0..terrain.resolution {
let sample = Vec2::new(
x as f32 * terrain.sample_spacing - half_extent,
z as f32 * terrain.sample_spacing - half_extent,
);
let distance = sample.distance(Vec2::new(center.x, center.z));
if distance > radius {
continue;
}
let amount = strength.clamp(0.0, 1.0) * smooth_falloff(distance / radius);
let index = (z * terrain.resolution + x) as usize;
terrain.material_weights[index] = adjust_weights(
terrain.material_weights[index],
active_layer,
layer_count,
amount,
mode,
);
}
}
}
fn adjust_weights(
weights: [u8; 4],
active_layer: usize,
layer_count: usize,
amount: f32,
mode: TerrainPaintMode,
) -> [u8; 4] {
let mut values = weights.map(|value| f32::from(value) / 255.0);
for value in values.iter_mut().skip(layer_count) {
*value = 0.0;
}
let current = values[active_layer];
let target = match mode {
TerrainPaintMode::Paint => current + (1.0 - current) * amount,
TerrainPaintMode::Erase => current * (1.0 - amount),
};
let other_sum: f32 = values
.iter()
.take(layer_count)
.enumerate()
.filter(|(index, _)| *index != active_layer)
.map(|(_, value)| *value)
.sum();
if other_sum <= f32::EPSILON {
if layer_count == 1 {
values[active_layer] = 1.0;
} else {
values.fill(0.0);
values[active_layer] = target;
let fallback = if active_layer == 0 { 1 } else { 0 };
values[fallback] = 1.0 - target;
}
} else {
let scale = (1.0 - target) / other_sum;
for (index, value) in values.iter_mut().take(layer_count).enumerate() {
if index != active_layer {
*value *= scale;
}
}
values[active_layer] = target;
}
quantize_weights(values, layer_count)
}
fn quantize_weights(values: [f32; 4], layer_count: usize) -> [u8; 4] {
let mut result = [0_u8; 4];
let mut fractions = [(0_usize, 0.0_f32); 4];
let mut assigned = 0_u16;
for index in 0..layer_count {
let scaled = values[index].clamp(0.0, 1.0) * 255.0;
let floor = scaled.floor() as u8;
result[index] = floor;
assigned += u16::from(floor);
fractions[index] = (index, scaled - f32::from(floor));
}
fractions[..layer_count].sort_by(|a, b| b.1.total_cmp(&a.1));
for offset in 0..usize::from(255_u16 - assigned) {
result[fractions[offset % layer_count].0] += 1;
}
result
}
fn draw_terrain_paint_preview(state: Res<TerrainPaintState>, mut gizmos: Gizmos) {
if !state.active {
return;
}
let Some(hit) = state.hover else {
return;
};
let color = match state.mode {
TerrainPaintMode::Paint => Color::srgba(0.22, 0.78, 1.0, 0.95),
TerrainPaintMode::Erase => Color::srgba(1.0, 0.64, 0.22, 0.95),
};
let rotation = hit.world_rotation * Quat::from_rotation_x(std::f32::consts::FRAC_PI_2);
gizmos
.circle(
Isometry3d::new(hit.world + Vec3::Y * 0.035, rotation),
state.radius,
color,
)
.resolution(48);
gizmos.sphere(
Isometry3d::from_translation(hit.world + Vec3::Y * 0.04),
0.06,
color,
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::history::EditorHistory;
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
use shared::{ActorKind, LevelObject};
#[test]
fn paint_and_erase_keep_weights_exactly_normalized() {
let painted = adjust_weights([255, 0, 0, 0], 1, 2, 0.5, TerrainPaintMode::Paint);
assert_eq!(painted.iter().copied().map(u16::from).sum::<u16>(), 255);
assert!(painted[1] > 0);
let erased = adjust_weights(painted, 1, 2, 1.0, TerrainPaintMode::Erase);
assert_eq!(erased, [255, 0, 0, 0]);
}
#[test]
fn dab_only_changes_samples_inside_footprint() {
let mut terrain = TerrainDesc::flat(5);
terrain.material_layers = vec![Default::default(), Default::default()];
apply_weight_dab(
&mut terrain,
Vec3::ZERO,
1.1,
1.0,
1,
TerrainPaintMode::Paint,
);
assert!(terrain.material_weights[12][1] > 0);
assert_eq!(terrain.material_weights[0], [255, 0, 0, 0]);
assert!(terrain.validate().is_ok());
}
#[test]
fn many_dabs_commit_as_one_undoable_paint_stroke() {
let mut app = App::new();
app.register_type::<ActorKind>()
.register_type::<TerrainDesc>()
.register_type::<shared::TerrainMaterialLayer>()
.register_type::<shared::EditorAssetRef>();
let world = app.world_mut();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<TerrainPaintState>();
let mut original = TerrainDesc::flat(9);
original.material_layers = vec![Default::default(), Default::default()];
let entity = world
.spawn((LevelObject, ActorKind::Terrain, original.clone()))
.id();
let mut final_terrain = original.clone();
for x in [-2.0, 0.0, 2.0] {
apply_weight_dab(
&mut final_terrain,
Vec3::new(x, 0.0, 0.0),
2.5,
0.5,
1,
TerrainPaintMode::Paint,
);
}
world.entity_mut(entity).insert(final_terrain.clone());
let stroke = TerrainPaintStroke {
entity,
original: original.clone(),
last_local: Vec3::ZERO,
};
{
let mut state = world.resource_mut::<TerrainPaintState>();
state.start(entity, 2);
state.stroke = Some(stroke);
}
let stroke = world
.resource_mut::<TerrainPaintState>()
.stroke
.take()
.unwrap();
let harness = OperatorInvariantHarness::capture(world);
finish_paint_stroke(
world,
stroke,
final_terrain.clone(),
TerrainPaintMode::Paint,
);
harness.assert_committed(world, 1, 0);
harness.assert_status(world, "terrain.paint", OperatorPhase::Committed);
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
let state = world.resource::<TerrainPaintState>();
assert!(state.active);
assert_eq!(state.target, Some(entity));
assert!(!state.is_stroking());
assert_undo_redo_round_trip(world, original, final_terrain, |world| {
world.get::<TerrainDesc>(entity).unwrap().clone()
});
}
#[test]
fn no_op_paint_release_terminates_without_dirtying_or_history() {
let mut app = App::new();
app.register_type::<ActorKind>()
.register_type::<TerrainDesc>()
.register_type::<shared::TerrainMaterialLayer>()
.register_type::<shared::EditorAssetRef>();
let world = app.world_mut();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let mut original = TerrainDesc::flat(5);
original.material_layers = vec![Default::default(), Default::default()];
original.ensure_material_weights();
let entity = world
.spawn((LevelObject, ActorKind::Terrain, original.clone()))
.id();
let harness = OperatorInvariantHarness::capture(world);
finish_paint_stroke(
world,
TerrainPaintStroke {
entity,
original: original.clone(),
last_local: Vec3::ZERO,
},
original.clone(),
TerrainPaintMode::Erase,
);
harness.assert_canceled(world);
harness.assert_status(world, "terrain.paint", OperatorPhase::Canceled);
assert_eq!(world.get::<TerrainDesc>(entity), Some(&original));
}
#[test]
fn commit_failure_restores_preview_and_reports_blocked_without_history() {
let mut app = App::new();
let world = app.world_mut();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let mut original = TerrainDesc::flat(5);
original.material_layers = vec![Default::default(), Default::default()];
let mut preview = original.clone();
apply_weight_dab(
&mut preview,
Vec3::ZERO,
3.0,
0.8,
1,
TerrainPaintMode::Paint,
);
let entity = world
.spawn((LevelObject, ActorKind::Terrain, preview.clone()))
.id();
let mut hierarchy = crate::ui::hierarchy_state::HierarchyPanelState::default();
hierarchy.locked.insert(entity);
world.insert_resource(hierarchy);
let harness = OperatorInvariantHarness::capture(world);
finish_paint_stroke(
world,
TerrainPaintStroke {
entity,
original: original.clone(),
last_local: Vec3::ZERO,
},
preview,
TerrainPaintMode::Paint,
);
harness.assert_blocked(world);
harness.assert_status(world, "terrain.paint", OperatorPhase::Blocked);
assert_eq!(world.get::<TerrainDesc>(entity), Some(&original));
assert!(world
.resource::<SceneIo>()
.status
.starts_with("Terrain paint commit failed:"));
}
#[test]
fn cancel_restores_implicit_pre_stroke_weights() {
fn cancel_once(
mut state: ResMut<TerrainPaintState>,
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
mut scene_io: ResMut<SceneIo>,
mut active_operator: ResMut<ActiveOperator>,
) {
cancel_active_stroke(
&mut state,
&mut terrains,
&mut scene_io,
&mut active_operator,
);
}
let mut app = App::new();
app.init_resource::<ActiveOperator>()
.init_resource::<EditorHistory>()
.init_resource::<SceneIo>();
let mut original = TerrainDesc::flat(5);
original.material_layers = vec![Default::default(), Default::default()];
let mut preview = original.clone();
apply_weight_dab(
&mut preview,
Vec3::ZERO,
3.0,
0.8,
1,
TerrainPaintMode::Paint,
);
let entity = app
.world_mut()
.spawn((LevelObject, GlobalTransform::default(), preview))
.id();
let mut state = TerrainPaintState::default();
state.start(entity, 2);
state.stroke = Some(TerrainPaintStroke {
entity,
original: original.clone(),
last_local: Vec3::ZERO,
});
app.insert_resource(state).add_systems(Update, cancel_once);
let harness = OperatorInvariantHarness::capture(app.world_mut());
app.update();
harness.assert_canceled(app.world_mut());
harness.assert_status(app.world(), "terrain.paint", OperatorPhase::Canceled);
assert_eq!(app.world().get::<TerrainDesc>(entity), Some(&original));
let state = app.world().resource::<TerrainPaintState>();
assert!(state.active);
assert_eq!(state.target, Some(entity));
assert!(!state.is_stroking());
}
#[test]
fn clean_view_interruption_restores_weights_and_terminates_tool() {
fn interrupt_once(
mut state: ResMut<TerrainPaintState>,
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
mut scene_io: ResMut<SceneIo>,
mut active_operator: ResMut<ActiveOperator>,
) {
stop_tool_with_rollback(
&mut state,
&mut terrains,
&mut scene_io,
&mut active_operator,
OperatorPhase::Canceled,
"Terrain paint stopped for clean game view",
"Clean game view enabled; weights restored",
);
}
let mut app = App::new();
app.init_resource::<ActiveOperator>()
.init_resource::<EditorHistory>()
.init_resource::<SceneIo>();
let mut original = TerrainDesc::flat(5);
original.material_layers = vec![Default::default(), Default::default()];
let mut preview = original.clone();
apply_weight_dab(
&mut preview,
Vec3::ZERO,
3.0,
0.8,
1,
TerrainPaintMode::Paint,
);
let entity = app
.world_mut()
.spawn((LevelObject, GlobalTransform::default(), preview))
.id();
let mut state = TerrainPaintState::default();
state.start(entity, 2);
state.stroke = Some(TerrainPaintStroke {
entity,
original: original.clone(),
last_local: Vec3::ZERO,
});
app.insert_resource(state)
.add_systems(Update, interrupt_once);
let harness = OperatorInvariantHarness::capture(app.world_mut());
app.update();
harness.assert_canceled(app.world_mut());
harness.assert_status(app.world(), "terrain.paint", OperatorPhase::Canceled);
assert_eq!(app.world().get::<TerrainDesc>(entity), Some(&original));
assert!(!app.world().resource::<TerrainPaintState>().active);
}
}
File diff suppressed because it is too large. Load diff
+194 -61
View File
@@ -1,14 +1,16 @@
//! Editor-side scene visualizers for authoring/runtime entities that have no mesh.
use avian3d::prelude::ColliderConstructor;
use std::f32::consts::FRAC_PI_2;
use avian3d::prelude::{ColliderAabb, ColliderConstructor};
use bevy::ecs::system::SystemParam;
use bevy::prelude::*;
use shared::{
AudioListenerDesc, AudioSourceDesc, AuthoringLightKind, ColliderDesc, ColliderShapeDesc,
LevelObject, LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink,
NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc,
PrefabRef, ProjectSun, RaytracingExcluded, SkinnedMeshRenderer, TeamSpawn, TriggerVolume,
WeaponSpawn,
PrefabRef, ProjectSun, RaytracingExcluded, RigidBodyDesc, SkinnedMeshRenderer, TeamSpawn,
TriggerVolume, WeaponSpawn,
};
use sim::tuning::{EYE_OFFSET_STAND, PLAYER_LENGTH, PLAYER_RADIUS};
use sim::{Player, PlayerCamera};
@@ -16,6 +18,10 @@ use sim::{Player, PlayerCamera};
use crate::infra::EditorOnly;
use crate::selection::SelectedEntity;
use crate::state::{scene_tools_active, EditorMode, PlayPossession};
use crate::viewport::collider_diagnostics::{
refresh_collider_diagnostics, ColliderDiagnosticEntry, ColliderDiagnosticsState,
ColliderOverlayStatus,
};
use crate::viewport::{EditorViewportMode, ViewportDisplayMode};
#[derive(Resource, Debug, Clone)]
@@ -102,7 +108,7 @@ struct VisualizerTargetQueries<'w, 's> {
Entity,
(
With<LevelObject>,
Or<(With<PhysicsBody>, With<ColliderDesc>)>,
Or<(With<PhysicsBody>, With<ColliderDesc>, With<RigidBodyDesc>)>,
),
>,
lights: Query<'w, 's, Entity, (With<LevelObject>, With<LightDesc>)>,
@@ -127,7 +133,15 @@ pub struct EditorVisualizersPlugin;
impl Plugin for EditorVisualizersPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<EditorVisualizationSettings>()
.init_resource::<ColliderDiagnosticsState>()
.add_systems(Startup, init_visualizer_proxy_assets)
.add_systems(
Update,
refresh_collider_diagnostics
.before(sync_visualizer_proxies)
.before(draw_visualizers)
.before(draw_split_collider_visualizers),
)
.add_systems(Update, sync_visualizer_proxies)
.add_systems(
Update,
@@ -135,6 +149,7 @@ impl Plugin for EditorVisualizersPlugin {
draw_visualizers,
draw_audio_visualizers,
draw_split_collider_visualizers,
draw_missing_collider_visualizers,
draw_post_process_volume_gizmos,
draw_navigation_visualizers,
)
@@ -145,6 +160,52 @@ impl Plugin for EditorVisualizersPlugin {
}
}
fn draw_missing_collider_visualizers(
viewport_mode: Res<EditorViewportMode>,
settings: Res<EditorVisualizationSettings>,
diagnostics: Res<ColliderDiagnosticsState>,
selected: Res<SelectedEntity>,
mut gizmos: Gizmos,
missing: Query<
(Entity, &GlobalTransform),
(
With<LevelObject>,
With<RigidBodyDesc>,
Without<ColliderDesc>,
Without<PhysicsBody>,
),
>,
) {
let collider_mode = *viewport_mode == EditorViewportMode::Collider;
if !(collider_mode || settings.enabled && settings.show_colliders) {
return;
}
for (entity, global) in &missing {
let color = collider_overlay_color(
diagnostics.entry(entity),
selected.0 == Some(entity),
collider_mode,
);
let center = global.translation();
let radius = if selected.0 == Some(entity) {
0.48
} else {
0.34
};
draw_box(
&mut gizmos,
center,
global.rotation(),
Vec3::splat(radius),
color,
);
for axis in [Vec3::X, Vec3::Y, Vec3::Z] {
let direction = global.rotation() * axis * radius * 1.35;
gizmos.line(center - direction, center + direction, color);
}
}
}
fn draw_navigation_visualizers(
state: Res<crate::ui::navigation_inspector::NavigationEditorState>,
mut gizmos: Gizmos,
@@ -556,17 +617,7 @@ fn draw_visualizers(
if settings.show_colliders || collider_mode {
for (entity, body, global) in &colliders {
let color = if selected.0 == Some(entity) {
if collider_mode {
Color::srgba(0.65, 1.0, 0.55, 1.0)
} else {
Color::srgba(0.55, 1.0, 0.45, 0.95)
}
} else if collider_mode {
Color::srgba(0.35, 1.0, 0.45, 0.9)
} else {
Color::srgba(0.25, 0.9, 0.35, 0.55)
};
let color = collider_overlay_color(None, selected.0 == Some(entity), collider_mode);
draw_collider(&mut gizmos, global, &body.collider, color);
}
}
@@ -679,11 +730,18 @@ fn draw_visualizers(
}
}
#[expect(
clippy::too_many_arguments,
reason = "collider overlays combine authoring, runtime bounds, selection, and viewport state"
)]
fn draw_split_collider_visualizers(
viewport_mode: Res<EditorViewportMode>,
settings: Res<EditorVisualizationSettings>,
diagnostics: Res<ColliderDiagnosticsState>,
selected: Res<SelectedEntity>,
mut gizmos: Gizmos,
children: Query<&Children>,
runtime_aabbs: Query<&ColliderAabb>,
colliders: Query<
(Entity, &ColliderDesc, &GlobalTransform),
(With<LevelObject>, Without<PhysicsBody>),
@@ -697,17 +755,80 @@ fn draw_split_collider_visualizers(
return;
}
for (entity, collider, global) in &colliders {
let color = if selected.0 == Some(entity) {
Color::srgba(0.65, 1.0, 0.55, 1.0)
} else if collider_mode {
Color::srgba(0.35, 1.0, 0.45, 0.9)
} else {
Color::srgba(0.25, 0.9, 0.35, 0.55)
};
draw_collider_desc(&mut gizmos, global, collider, color);
let color = collider_overlay_color(
diagnostics.entry(entity),
selected.0 == Some(entity),
collider_mode,
);
let drew_runtime_mesh = matches!(collider.shape, ColliderShapeDesc::StaticMesh { .. })
&& draw_runtime_collider_bounds(&mut gizmos, entity, &children, &runtime_aabbs, color);
if !drew_runtime_mesh {
draw_collider_desc(&mut gizmos, global, collider, color);
}
}
}
fn collider_overlay_color(
entry: Option<&ColliderDiagnosticEntry>,
selected: bool,
collider_mode: bool,
) -> Color {
let status = entry
.map(|entry| entry.overlay_status)
.unwrap_or(ColliderOverlayStatus::Valid);
let (rgb, base_alpha): (Vec3, f32) = match status {
ColliderOverlayStatus::Valid => (Vec3::new(0.25, 0.92, 0.43), 0.72),
ColliderOverlayStatus::Trigger => (Vec3::new(0.18, 0.82, 1.0), 0.78),
ColliderOverlayStatus::Disabled => (Vec3::new(0.52, 0.56, 0.62), 0.42),
ColliderOverlayStatus::Warning => (Vec3::new(1.0, 0.68, 0.18), 0.9),
ColliderOverlayStatus::Error => (Vec3::new(1.0, 0.24, 0.3), 0.96),
};
let alpha = if selected {
1.0
} else if collider_mode {
base_alpha.max(0.82)
} else {
base_alpha * 0.72
};
let rgb = if selected {
rgb.lerp(Vec3::ONE, 0.18)
} else {
rgb
};
Color::srgba(rgb.x, rgb.y, rgb.z, alpha)
}
fn draw_runtime_collider_bounds(
gizmos: &mut Gizmos,
root: Entity,
children: &Query<&Children>,
aabbs: &Query<&ColliderAabb>,
color: Color,
) -> bool {
let mut pending = vec![root];
let mut drew = false;
while let Some(entity) = pending.pop() {
if let Ok(aabb) = aabbs.get(entity) {
let min = aabb.min;
let max = aabb.max;
if min.is_finite() && max.is_finite() && min.cmplt(max).all() {
draw_box(
gizmos,
(min + max) * 0.5,
Quat::IDENTITY,
(max - min) * 0.5,
color,
);
drew = true;
}
}
if let Ok(entity_children) = children.get(entity) {
pending.extend(entity_children.iter());
}
}
drew
}
fn draw_post_process_volume_gizmos(
viewport_mode: Res<EditorViewportMode>,
settings: Res<EditorVisualizationSettings>,
@@ -741,6 +862,8 @@ fn draw_collider(
collider: &ColliderConstructor,
color: Color,
) {
let (scale, rotation, translation) = global.to_scale_rotation_translation();
let scale = scale.abs();
match collider {
ColliderConstructor::Cuboid {
x_length,
@@ -748,27 +871,21 @@ fn draw_collider(
z_length,
} => draw_box(
gizmos,
global.translation(),
global.rotation(),
Vec3::new(*x_length, *y_length, *z_length) * 0.5,
translation,
rotation,
Vec3::new(*x_length, *y_length, *z_length) * scale * 0.5,
color,
),
ColliderConstructor::Sphere { radius } => {
gizmos
.sphere(
Isometry3d::new(global.translation(), global.rotation()),
*radius,
color,
)
.resolution(24);
draw_ellipsoid(gizmos, translation, rotation, scale * *radius, color);
}
ColliderConstructor::Capsule { radius, height } => {
draw_capsule(
gizmos,
global.translation(),
global.rotation(),
*radius,
*height,
translation,
rotation,
*radius * scale.x.max(scale.z),
*height * scale.y,
color,
);
}
@@ -790,9 +907,8 @@ fn draw_collider_desc(
collider: &ColliderDesc,
color: Color,
) {
if !collider.enabled {
return;
}
let (scale, rotation, translation) = global.to_scale_rotation_translation();
let scale = scale.abs();
match &collider.shape {
ColliderShapeDesc::Cuboid {
x_length,
@@ -800,42 +916,59 @@ fn draw_collider_desc(
z_length,
} => draw_box(
gizmos,
global.translation(),
global.rotation(),
Vec3::new(*x_length, *y_length, *z_length) * 0.5,
translation,
rotation,
Vec3::new(*x_length, *y_length, *z_length) * scale * 0.5,
color,
),
ColliderShapeDesc::Sphere { radius } => {
gizmos
.sphere(
Isometry3d::new(global.translation(), global.rotation()),
*radius,
color,
)
.resolution(24);
draw_ellipsoid(gizmos, translation, rotation, scale * *radius, color);
}
ColliderShapeDesc::Capsule { radius, height } => {
draw_capsule(
gizmos,
global.translation(),
global.rotation(),
*radius,
*height,
translation,
rotation,
*radius * scale.x.max(scale.z),
*height * scale.y,
color,
);
}
ColliderShapeDesc::StaticMesh { .. } => {
gizmos
.sphere(
Isometry3d::new(global.translation(), global.rotation()),
0.35,
color,
)
.resolution(16);
draw_box(gizmos, translation, rotation, Vec3::splat(0.24), color);
gizmos.line(
translation - rotation * Vec3::splat(0.34),
translation + rotation * Vec3::splat(0.34),
color,
);
}
}
}
fn draw_ellipsoid(gizmos: &mut Gizmos, center: Vec3, rotation: Quat, radii: Vec3, color: Color) {
gizmos
.ellipse(
Isometry3d::new(center, rotation),
Vec2::new(radii.x, radii.z),
color,
)
.resolution(32);
gizmos
.ellipse(
Isometry3d::new(center, rotation * Quat::from_rotation_x(FRAC_PI_2)),
Vec2::new(radii.x, radii.y),
color,
)
.resolution(32);
gizmos
.ellipse(
Isometry3d::new(center, rotation * Quat::from_rotation_z(FRAC_PI_2)),
Vec2::new(radii.y, radii.z),
color,
)
.resolution(32);
}
fn draw_light(
gizmos: &mut Gizmos,
global: &GlobalTransform,
+1 -1
View File
@@ -94,7 +94,7 @@ mod hot {
ActiveCameraRenderProfile, ProjectRenderCamera, ProjectSettings, RenderingCapabilities,
SimTuning,
};
use shared::{InspectorOrder, LevelObject, LightDesc, ProjectSun};
use shared::{AuthoringComponentStates, InspectorOrder, LevelObject, LightDesc, ProjectSun};
use sim::{
CameraSensitivity, Crouching, GameInputEnabled, GameInputFocused, Grounded, JumpState,
Player, PlayerCamera, PlayerVelocity, PlayerYawSensitivity,
+1
View File
@@ -175,6 +175,7 @@ fn actor_kind_ron(kind: ActorKind) -> &'static str {
match kind {
ActorKind::Empty => "Empty",
ActorKind::Brush => "Brush",
ActorKind::Terrain => "Terrain",
ActorKind::StaticMesh => "StaticMesh",
ActorKind::SkinnedMesh => "SkinnedMesh",
ActorKind::ImportedModel => "ImportedModel",
+18 -1
View File
@@ -11,7 +11,7 @@ use crate::{
ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, LevelObject,
LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink, NavigationObstacle,
ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TerrainDesc, TriggerVolume, WeaponSpawn,
AUDIO_CLIP_SUB_ASSET_ID,
};
@@ -31,6 +31,9 @@ pub fn infer_actor_kind(entity: EntityRef<'_>) -> Option<ActorKind> {
if entity.get::<BrushDesc>().is_some() {
return Some(ActorKind::Brush);
}
if entity.get::<TerrainDesc>().is_some() {
return Some(ActorKind::Terrain);
}
if entity.get::<Primitive>().is_some() || entity.get::<StaticMeshRenderer>().is_some() {
return Some(ActorKind::StaticMesh);
}
@@ -84,6 +87,7 @@ pub enum ActorValidationError {
BrushHasLight,
BrushHasModelRef,
InvalidBrushGeometry(String),
InvalidTerrain(String),
StaticMeshMissingPrimitive,
StaticMeshHasLight,
StaticMeshHasModelRef,
@@ -166,6 +170,7 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
}
let geometry_source_count = usize::from(entity.get::<Primitive>().is_some())
+ usize::from(entity.get::<BrushDesc>().is_some())
+ usize::from(entity.get::<TerrainDesc>().is_some())
+ usize::from(entity.get::<StaticMeshRenderer>().is_some())
+ usize::from(entity.get::<SkinnedMeshRenderer>().is_some())
+ usize::from(entity.get::<ModelRef>().is_some());
@@ -186,6 +191,11 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
return Err(ActorValidationError::InvalidBrushGeometry(message));
}
}
if let Some(terrain) = entity.get::<TerrainDesc>() {
terrain
.validate()
.map_err(ActorValidationError::InvalidTerrain)?;
}
if let Some(renderer) = entity.get::<SkinnedMeshRenderer>() {
if renderer.path.trim().is_empty() {
return Err(ActorValidationError::SkinnedMeshInvalidRenderer);
@@ -218,6 +228,13 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
}
let _ = brush;
}
ActorKind::Terrain => {
if entity.get::<TerrainDesc>().is_none() {
return Err(ActorValidationError::InvalidTerrain(
"terrain actor is missing TerrainDesc".into(),
));
}
}
ActorKind::StaticMesh => {
let has_static_mesh_renderer = entity
.get::<StaticMeshRenderer>()
+226
View File
@@ -290,6 +290,7 @@ pub fn inspector_component_active(order: Option<&InspectorOrder>, type_name: &st
// Rust type paths remain serialization details and may change during refactors.
pub const AUTHORING_COMPONENT_PRIMITIVE: &str = "render.primitive";
pub const AUTHORING_COMPONENT_BRUSH: &str = "render.brush";
pub const AUTHORING_COMPONENT_TERRAIN: &str = "render.terrain";
pub const AUTHORING_COMPONENT_STATIC_MESH_RENDERER: &str = "render.static_mesh_renderer";
pub const AUTHORING_COMPONENT_SKINNED_MESH_RENDERER: &str = "render.skinned_mesh_renderer";
pub const AUTHORING_COMPONENT_MATERIAL: &str = "render.material";
@@ -318,6 +319,7 @@ pub fn authoring_component_id(key: &str) -> Option<&'static str> {
match key {
AUTHORING_COMPONENT_PRIMITIVE | COMPONENT_PRIMITIVE => Some(AUTHORING_COMPONENT_PRIMITIVE),
AUTHORING_COMPONENT_BRUSH | COMPONENT_BRUSH_DESC => Some(AUTHORING_COMPONENT_BRUSH),
AUTHORING_COMPONENT_TERRAIN | COMPONENT_TERRAIN_DESC => Some(AUTHORING_COMPONENT_TERRAIN),
AUTHORING_COMPONENT_STATIC_MESH_RENDERER | COMPONENT_STATIC_MESH_RENDERER => {
Some(AUTHORING_COMPONENT_STATIC_MESH_RENDERER)
}
@@ -386,6 +388,7 @@ pub fn authoring_component_key(key: &str) -> &str {
pub const COMPONENT_PRIMITIVE: &str = "shared::components::Primitive";
pub const COMPONENT_BRUSH_DESC: &str = "shared::components::BrushDesc";
pub const COMPONENT_TERRAIN_DESC: &str = "shared::components::TerrainDesc";
pub const COMPONENT_STATIC_MESH_RENDERER: &str = "shared::components::StaticMeshRenderer";
pub const COMPONENT_MATERIAL_DESC: &str = "shared::components::MaterialDesc";
pub const COMPONENT_MATERIAL_OVERRIDE: &str = "shared::components::MaterialOverride";
@@ -852,6 +855,228 @@ impl BrushDesc {
}
}
pub const TERRAIN_SCHEMA_VERSION: u32 = 1;
pub const TERRAIN_MATERIAL_LAYER_LIMIT: usize = 4;
fn default_terrain_layer_uv_scale() -> f32 {
8.0
}
/// One shared project material assigned to a terrain blend channel.
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct TerrainMaterialLayer {
#[serde(default)]
pub material: Option<EditorAssetRef>,
#[serde(default = "default_terrain_layer_uv_scale")]
pub uv_scale: f32,
}
impl Default for TerrainMaterialLayer {
fn default() -> Self {
Self {
material: None,
uv_scale: default_terrain_layer_uv_scale(),
}
}
}
/// Persistent height-grid terrain authoring data. Hydration partitions the grid into generated
/// render/collider chunks; saved scenes retain only this descriptor.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct TerrainDesc {
#[serde(default = "default_terrain_schema_version")]
pub schema_version: u32,
#[serde(default = "default_terrain_resolution")]
pub resolution: u32,
#[serde(default = "default_terrain_heights")]
pub heights: Vec<f32>,
#[serde(default = "default_terrain_sample_spacing")]
pub sample_spacing: f32,
#[serde(default = "default_terrain_height_scale")]
pub height_scale: f32,
#[serde(default = "default_terrain_chunk_quads")]
pub chunk_quads: u32,
#[serde(default)]
pub base_material: Option<EditorAssetRef>,
/// Up to four project Material/Material Instance assignments. Empty retains the legacy
/// `base_material` path and an empty weight map means 100% channel zero.
#[serde(default)]
pub material_layers: Vec<TerrainMaterialLayer>,
/// RGBA8 weights per height sample. Channels correspond to `material_layers`.
#[serde(default)]
pub material_weights: Vec<[u8; TERRAIN_MATERIAL_LAYER_LIMIT]>,
#[serde(default = "default_true")]
pub generate_colliders: bool,
#[serde(default = "default_true")]
pub cast_shadows: bool,
#[serde(default = "default_true")]
pub receive_shadows: bool,
}
impl Default for TerrainDesc {
fn default() -> Self {
Self {
schema_version: TERRAIN_SCHEMA_VERSION,
resolution: default_terrain_resolution(),
heights: default_terrain_heights(),
sample_spacing: default_terrain_sample_spacing(),
height_scale: default_terrain_height_scale(),
chunk_quads: default_terrain_chunk_quads(),
base_material: None,
material_layers: Vec::new(),
material_weights: Vec::new(),
generate_colliders: true,
cast_shadows: true,
receive_shadows: true,
}
}
}
impl TerrainDesc {
pub fn flat(resolution: u32) -> Self {
let resolution = resolution.max(2);
Self {
resolution,
heights: vec![0.0; resolution as usize * resolution as usize],
chunk_quads: (resolution - 1).min(default_terrain_chunk_quads()),
..Default::default()
}
}
pub fn validate(&self) -> Result<(), String> {
if self.schema_version != TERRAIN_SCHEMA_VERSION {
return Err(format!(
"terrain schema {} is unsupported; expected {}",
self.schema_version, TERRAIN_SCHEMA_VERSION
));
}
if !(2..=1025).contains(&self.resolution) {
return Err("terrain resolution must be between 2 and 1025 samples".into());
}
let expected = self.resolution as usize * self.resolution as usize;
if self.heights.len() != expected {
return Err(format!(
"terrain resolution {} requires {expected} height samples, found {}",
self.resolution,
self.heights.len()
));
}
if self.heights.iter().any(|height| !height.is_finite()) {
return Err("terrain height samples must all be finite".into());
}
if self.material_layers.len() > TERRAIN_MATERIAL_LAYER_LIMIT {
return Err(format!(
"terrain supports at most {TERRAIN_MATERIAL_LAYER_LIMIT} material layers"
));
}
for (index, layer) in self.material_layers.iter().enumerate() {
if !layer.uv_scale.is_finite() || layer.uv_scale <= 0.0 {
return Err(format!(
"terrain material layer {} UV scale must be finite and positive",
index + 1
));
}
}
if !self.material_weights.is_empty() {
if self.material_weights.len() != expected {
return Err(format!(
"terrain resolution {} requires {expected} material weights, found {}",
self.resolution,
self.material_weights.len()
));
}
if self
.material_weights
.iter()
.any(|weights| weights.iter().copied().map(u16::from).sum::<u16>() != 255)
{
return Err("terrain material weights must sum to 255 at every sample".into());
}
let active_channels = self.material_layers.len().max(1);
if self.material_weights.iter().any(|weights| {
weights
.iter()
.skip(active_channels)
.any(|weight| *weight != 0)
}) {
return Err("terrain material weights use an unassigned layer channel".into());
}
}
if !self.sample_spacing.is_finite() || self.sample_spacing <= 0.0 {
return Err("terrain sample spacing must be finite and positive".into());
}
if !self.height_scale.is_finite() || self.height_scale <= 0.0 {
return Err("terrain height scale must be finite and positive".into());
}
if self.chunk_quads == 0 || self.chunk_quads > self.resolution - 1 {
return Err(format!(
"terrain chunk size must be between 1 and {} quads",
self.resolution - 1
));
}
Ok(())
}
/// Material channels used by hydration, including the legacy base-material fallback.
pub fn effective_material_layers(&self) -> Vec<TerrainMaterialLayer> {
if !self.material_layers.is_empty() {
return self.material_layers.clone();
}
self.base_material
.clone()
.map(|material| TerrainMaterialLayer {
material: Some(material),
..Default::default()
})
.into_iter()
.collect()
}
/// Material weights for one sample, normalized for vertex transport.
pub fn normalized_material_weights(&self, sample_index: usize) -> [f32; 4] {
let weights = self
.material_weights
.get(sample_index)
.copied()
.unwrap_or([255, 0, 0, 0]);
weights.map(|weight| f32::from(weight) / 255.0)
}
/// Materializes the implicit channel-zero map before an editor paint operation.
pub fn ensure_material_weights(&mut self) {
let expected = self.resolution as usize * self.resolution as usize;
if self.material_weights.len() != expected {
self.material_weights = vec![[255, 0, 0, 0]; expected];
}
}
}
fn default_terrain_schema_version() -> u32 {
TERRAIN_SCHEMA_VERSION
}
fn default_terrain_resolution() -> u32 {
33
}
fn default_terrain_heights() -> Vec<f32> {
vec![0.0; default_terrain_resolution() as usize * default_terrain_resolution() as usize]
}
fn default_terrain_sample_spacing() -> f32 {
1.0
}
fn default_terrain_height_scale() -> f32 {
10.0
}
fn default_terrain_chunk_quads() -> u32 {
16
}
impl Default for BrushDesc {
fn default() -> Self {
Self::cuboid(Vec3::ONE)
@@ -1392,6 +1617,7 @@ impl Default for EditorVisibility {
pub enum ActorKind {
Empty,
Brush,
Terrain,
StaticMesh,
SkinnedMesh,
ImportedModel,
+3 -4
View File
@@ -11,8 +11,7 @@ use bevy::prelude::*;
use crate::{
asset_server_path, authoring_component_active, brush_math::validate_brush,
AuthoringComponentStates, BrushDesc, BrushFaceDesc, ColliderDesc, InspectorOrder, LevelObject,
MaterialAsset, MaterialDesc, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
COMPONENT_MATERIAL_DESC,
MaterialDesc, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
};
use super::materials::material_from_desc;
@@ -214,8 +213,8 @@ fn brush_group_material(
texture_path: Option<&str>,
) -> StandardMaterial {
let mut material = material_path
.and_then(|path| MaterialAsset::load_from_path(path).ok())
.map(|asset| material_from_desc(asset_server, &asset.material))
.and_then(|path| crate::load_resolved_material_from_path(path).ok())
.map(|(desc, _)| material_from_desc(asset_server, &desc))
.or_else(|| parent_material.map(|material| material_from_desc(asset_server, material)))
.unwrap_or_else(default_brush_material);
if let Some(texture_path) = texture_path {
+19 -2
View File
@@ -10,6 +10,7 @@ mod primitives;
mod skinned_meshes;
mod static_meshes;
pub mod strip;
mod terrain;
mod visibility;
pub use lights::cascade_config_from_rendering;
@@ -37,6 +38,8 @@ use static_meshes::{
hydrate_static_mesh_renderers, spawn_static_mesh_parts, HydratedStaticMeshPart,
StaticMeshArtifactCache,
};
pub use terrain::HydratedTerrainChunk;
use terrain::{cleanup_removed_terrain, hydrate_terrain};
use visibility::{
ensure_level_object_visibility_hierarchy, init_editor_visibility_on_spawn,
sync_editor_visibility, visibility_from_editor,
@@ -52,17 +55,28 @@ use crate::{
/// Registers hydration systems in deterministic order.
pub struct HydrationPlugin;
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum HydrationSet {
Visibility,
Content,
}
impl Plugin for HydrationPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<StaticMeshArtifactCache>()
.add_observer(tag_hydrated_prefab_members)
.add_observer(mark_skinned_materials_ready)
.add_observer(crate::prefab_overrides::apply_prefab_overrides_on_ready)
.configure_sets(
Update,
(HydrationSet::Visibility, HydrationSet::Content).chain(),
)
.add_systems(
Update,
(
hydrate_primitives,
hydrate_brushes,
hydrate_terrain,
hydrate_materials,
hydrate_lights,
reconcile_missing_runtime_lights,
@@ -73,8 +87,10 @@ impl Plugin for HydrationPlugin {
hydrate_models,
hydrate_prefabs,
hydrate_physics,
cleanup_removed_terrain,
)
.chain(),
.chain()
.in_set(HydrationSet::Content),
)
.add_systems(
Update,
@@ -83,7 +99,8 @@ impl Plugin for HydrationPlugin {
sync_editor_visibility,
init_editor_visibility_on_spawn,
)
.chain(),
.chain()
.in_set(HydrationSet::Visibility),
);
}
}
+4 -20
View File
@@ -10,10 +10,9 @@ use std::collections::{HashMap, HashSet};
use crate::{
asset_server_path, authoring_component_active, standard_material_asset_path,
AuthoringComponentStates, ColliderDesc, ColliderShapeDesc, EditorAssetRef,
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, MaterialAlphaMode, MaterialAsset,
MaterialDesc, MaterialInstanceAsset, MaterialOverride, MaterialRef, StaticMeshRenderer,
StaticMeshRendererEntry, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
COMPONENT_STATIC_MESH_RENDERER,
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, MaterialAlphaMode, MaterialDesc,
MaterialOverride, MaterialRef, StaticMeshRenderer, StaticMeshRendererEntry,
COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_STATIC_MESH_RENDERER,
};
use super::materials::material_from_desc;
@@ -457,22 +456,7 @@ fn resolve_shared_material(
return Some(handle.clone());
}
let path = reference.0.source_path.as_deref()?;
let desc_and_state = MaterialAsset::load_from_path(path)
.map(|asset| (asset.material, asset.render_state))
.or_else(|_| {
let instance = MaterialInstanceAsset::load_from_path(path)?;
let base_path = instance.base.0.source_path.as_deref().ok_or_else(|| {
format!(
"material instance {} has no loadable base path",
instance.label
)
})?;
let base = MaterialAsset::load_from_path(base_path)?;
let mut desc = base.material;
instance.apply_to(&mut desc);
Ok::<_, String>((desc, base.render_state))
})
.ok()?;
let desc_and_state = crate::load_resolved_material_from_path(path).ok()?;
let mut material = material_from_desc(asset_server, &desc_and_state.0);
material.alpha_mode = match desc_and_state.1.alpha_mode {
MaterialAlphaMode::Opaque => AlphaMode::Opaque,
+372
View File
@@ -0,0 +1,372 @@
//! Chunked render and collider hydration for authored height-grid terrain.
use avian3d::prelude::ColliderConstructor;
use bevy::asset::RenderAssetUsages;
use bevy::light::{NotShadowCaster, NotShadowReceiver};
use bevy::mesh::{Indices, PrimitiveTopology};
use bevy::prelude::*;
use crate::{
authoring_component_active, load_resolved_material_from_path, AuthoringComponentStates,
HydratedTerrainMaterialBinding, InspectorOrder, LevelObject, RaytracingExcluded, TerrainDesc,
COMPONENT_TERRAIN_DESC,
};
use super::materials::material_from_desc;
#[derive(Component, Reflect, Debug, Clone, Copy, PartialEq, Eq)]
#[reflect(Component, Default, Debug)]
pub struct HydratedTerrainChunk {
pub owner: Entity,
pub chunk_x: u32,
pub chunk_z: u32,
}
impl Default for HydratedTerrainChunk {
fn default() -> Self {
Self {
owner: Entity::PLACEHOLDER,
chunk_x: 0,
chunk_z: 0,
}
}
}
#[allow(clippy::type_complexity)]
pub fn hydrate_terrain(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
terrains: Query<
(
Entity,
&TerrainDesc,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
With<LevelObject>,
Or<(
Added<TerrainDesc>,
Changed<TerrainDesc>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
>,
children: Query<&Children>,
chunks: Query<(), With<HydratedTerrainChunk>>,
) {
for (entity, terrain, states, order) in &terrains {
despawn_terrain_chunks(&mut commands, entity, &children, &chunks);
if authoring_component_active(states, order, COMPONENT_TERRAIN_DESC) {
spawn_terrain_chunks(
&mut commands,
&asset_server,
&mut meshes,
&mut materials,
entity,
terrain,
);
}
}
}
pub fn cleanup_removed_terrain(
mut commands: Commands,
mut removed: RemovedComponents<TerrainDesc>,
children: Query<&Children>,
chunks: Query<(), With<HydratedTerrainChunk>>,
) {
for entity in removed.read() {
despawn_terrain_chunks(&mut commands, entity, &children, &chunks);
}
}
pub fn spawn_terrain_chunks(
commands: &mut Commands,
asset_server: &AssetServer,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
owner: Entity,
terrain: &TerrainDesc,
) {
if let Err(error) = terrain.validate() {
warn!("Terrain hydration skipped invalid actor {owner:?}: {error}");
return;
}
let effective_layers = terrain.effective_material_layers();
let material = effective_layers
.first()
.and_then(|layer| layer.material.as_ref())
.and_then(|reference| reference.source_path.as_deref())
.and_then(|path| match load_resolved_material_from_path(path) {
Ok((desc, _)) => Some(material_from_desc(asset_server, &desc)),
Err(error) => {
warn!("Terrain {owner:?} material could not resolve: {error}");
None
}
})
.unwrap_or_else(|| StandardMaterial {
base_color: Color::srgb(0.24, 0.29, 0.25),
perceptual_roughness: 0.92,
..default()
});
let material = materials.add(material);
let quad_count = terrain.resolution - 1;
let chunks_per_axis = quad_count.div_ceil(terrain.chunk_quads);
for chunk_z in 0..chunks_per_axis {
for chunk_x in 0..chunks_per_axis {
let start_x = chunk_x * terrain.chunk_quads;
let start_z = chunk_z * terrain.chunk_quads;
let end_x = (start_x + terrain.chunk_quads).min(quad_count);
let end_z = (start_z + terrain.chunk_quads).min(quad_count);
let Some(mesh) = terrain_chunk_mesh(terrain, start_x, start_z, end_x, end_z) else {
continue;
};
let mesh = meshes.add(mesh);
let mut chunk = commands.spawn((
HydratedTerrainChunk {
owner,
chunk_x,
chunk_z,
},
Name::new(format!("Terrain Chunk {chunk_x},{chunk_z}")),
Mesh3d(mesh),
MeshMaterial3d(material.clone()),
HydratedTerrainMaterialBinding {
owner,
layers: terrain.effective_material_layers(),
},
Transform::default(),
Visibility::Visible,
RaytracingExcluded,
ChildOf(owner),
));
if terrain.generate_colliders {
chunk.insert(ColliderConstructor::TrimeshFromMesh);
}
if !terrain.cast_shadows {
chunk.insert(NotShadowCaster);
}
if !terrain.receive_shadows {
chunk.insert(NotShadowReceiver);
}
}
}
}
fn despawn_terrain_chunks(
commands: &mut Commands,
entity: Entity,
children: &Query<&Children>,
chunks: &Query<(), With<HydratedTerrainChunk>>,
) {
let Ok(children) = children.get(entity) else {
return;
};
for child in children.iter() {
if chunks.get(child).is_ok() {
commands.entity(child).despawn();
}
}
}
pub fn terrain_chunk_mesh(
terrain: &TerrainDesc,
start_x: u32,
start_z: u32,
end_x: u32,
end_z: u32,
) -> Option<Mesh> {
if start_x >= end_x
|| start_z >= end_z
|| end_x >= terrain.resolution
|| end_z >= terrain.resolution
{
return None;
}
let width = end_x - start_x + 1;
let depth = end_z - start_z + 1;
let mut positions = Vec::with_capacity((width * depth) as usize);
let mut normals = Vec::with_capacity((width * depth) as usize);
let mut uvs = Vec::with_capacity((width * depth) as usize);
let mut colors = Vec::with_capacity((width * depth) as usize);
let quad_count = (terrain.resolution - 1) as f32;
let half_extent = quad_count * terrain.sample_spacing * 0.5;
let sample = |x: u32, z: u32| {
terrain.heights[(z * terrain.resolution + x) as usize] * terrain.height_scale
};
for z in start_z..=end_z {
for x in start_x..=end_x {
let left = sample(x.saturating_sub(1), z);
let right = sample((x + 1).min(terrain.resolution - 1), z);
let down = sample(x, z.saturating_sub(1));
let up = sample(x, (z + 1).min(terrain.resolution - 1));
let normal = Vec3::new(left - right, 2.0 * terrain.sample_spacing, down - up)
.normalize_or_zero();
positions.push([
x as f32 * terrain.sample_spacing - half_extent,
sample(x, z),
z as f32 * terrain.sample_spacing - half_extent,
]);
normals.push(normal.to_array());
uvs.push([x as f32 / quad_count, z as f32 / quad_count]);
colors.push(terrain.normalized_material_weights((z * terrain.resolution + x) as usize));
}
}
let mut indices = Vec::with_capacity(((width - 1) * (depth - 1) * 6) as usize);
for z in 0..depth - 1 {
for x in 0..width - 1 {
let a = z * width + x;
let b = a + 1;
let c = a + width;
let d = c + 1;
indices.extend_from_slice(&[a, c, b, b, c, d]);
}
}
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, colors);
mesh.insert_indices(Indices::U32(indices));
if let Err(error) = mesh.generate_tangents() {
warn!("Terrain chunk tangent generation failed: {error:?}");
}
Some(mesh)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ActorKind;
#[test]
fn chunk_mesh_has_expected_topology() {
let terrain = TerrainDesc::flat(5);
let mesh = terrain_chunk_mesh(&terrain, 0, 0, 4, 4).unwrap();
assert_eq!(mesh.count_vertices(), 25);
assert_eq!(mesh.indices().unwrap().len(), 96);
}
#[test]
fn descriptor_rejects_mismatched_and_non_finite_heights() {
let mut terrain = TerrainDesc::flat(3);
terrain.heights.pop();
assert!(terrain.validate().unwrap_err().contains("requires 9"));
terrain.heights.push(f32::NAN);
assert!(terrain.validate().unwrap_err().contains("finite"));
}
#[test]
fn descriptor_round_trips_through_ron() {
let mut terrain = TerrainDesc::flat(5);
terrain.heights[12] = 0.75;
terrain.sample_spacing = 2.0;
terrain.material_layers = vec![
crate::TerrainMaterialLayer {
material: Some(crate::EditorAssetRef::new(
"ground",
"material:source",
"Ground",
)),
uv_scale: 6.0,
},
crate::TerrainMaterialLayer {
material: Some(crate::EditorAssetRef::new(
"rock",
"material:source",
"Rock",
)),
uv_scale: 12.0,
},
];
terrain.ensure_material_weights();
terrain.material_weights[12] = [64, 191, 0, 0];
let text = ron::to_string(&terrain).unwrap();
let restored: TerrainDesc = ron::from_str(&text).unwrap();
assert_eq!(restored, terrain);
assert!(restored.validate().is_ok());
}
#[test]
fn chunk_mesh_transports_normalized_material_weights_as_vertex_colors() {
let mut terrain = TerrainDesc::flat(3);
terrain.ensure_material_weights();
terrain.material_weights[4] = [64, 191, 0, 0];
let mesh = terrain_chunk_mesh(&terrain, 0, 0, 2, 2).unwrap();
let Some(bevy::mesh::VertexAttributeValues::Float32x4(colors)) =
mesh.attribute(Mesh::ATTRIBUTE_COLOR)
else {
panic!("terrain chunks should carry RGBA layer weights");
};
assert_eq!(colors.len(), 9);
assert!((colors[4][0] - 64.0 / 255.0).abs() < 0.0001);
assert!((colors[4][1] - 191.0 / 255.0).abs() < 0.0001);
}
#[test]
fn descriptor_rejects_non_normalized_material_weights() {
let mut terrain = TerrainDesc::flat(3);
terrain.material_weights = vec![[128, 128, 0, 0]; 9];
assert!(terrain.validate().unwrap_err().contains("sum to 255"));
terrain.material_weights = vec![[127, 0, 128, 0]; 9];
assert!(terrain
.validate()
.unwrap_err()
.contains("unassigned layer channel"));
}
#[test]
fn hydration_generates_runtime_only_chunks_and_cleans_up() {
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()))
.init_asset::<Mesh>()
.init_asset::<StandardMaterial>()
.add_systems(Update, (hydrate_terrain, cleanup_removed_terrain).chain());
let owner = app
.world_mut()
.spawn((
LevelObject,
ActorKind::Terrain,
TerrainDesc {
resolution: 5,
heights: vec![0.0; 25],
chunk_quads: 2,
..Default::default()
},
Transform::default(),
))
.id();
app.update();
app.update();
let children = app.world().get::<Children>(owner).unwrap();
assert_eq!(children.len(), 4);
for child in children.iter() {
assert!(app.world().get::<HydratedTerrainChunk>(child).is_some());
assert!(app.world().get::<LevelObject>(child).is_none());
assert!(app.world().get::<Mesh3d>(child).is_some());
assert!(app.world().get::<ColliderConstructor>(child).is_some());
}
app.world_mut().entity_mut(owner).remove::<TerrainDesc>();
app.update();
app.update();
assert!(app
.world()
.get::<Children>(owner)
.is_none_or(Children::is_empty));
}
}
+7 -4
View File
@@ -22,12 +22,13 @@ pub use components::*;
pub use hydration::{
cascade_config_from_rendering, flush_level_object_hydration, material_from_desc,
strip_hydrated, strip_hydrated_entity, HydratedModelRoot, HydratedPrefabMember,
HydratedPrefabReady, HydratedSkinnedMeshRoot, HydrationPlugin, PrefabHydrationBlocked,
HydratedPrefabReady, HydratedSkinnedMeshRoot, HydratedTerrainChunk, HydrationPlugin,
PrefabHydrationBlocked,
};
pub use material_asset::{
MaterialAlphaMode, MaterialAsset, MaterialInstanceAsset, MaterialRenderState,
ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset, MATERIAL_ASSET_SCHEMA_VERSION,
MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
load_resolved_material_from_path, MaterialAlphaMode, MaterialAsset, MaterialInstanceAsset,
MaterialRenderState, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,
MATERIAL_ASSET_SCHEMA_VERSION, MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
};
pub use navigation::*;
pub use post_process_effect_asset::{PostProcessEffectAsset, PostProcessEffectKind};
@@ -112,6 +113,8 @@ impl Plugin for SharedTypesPlugin {
.register_type::<Primitive>()
.register_type::<PrimitiveShape>()
.register_type::<BrushDesc>()
.register_type::<TerrainDesc>()
.register_type::<TerrainMaterialLayer>()
.register_type::<BrushKind>()
.register_type::<BrushPlaneDesc>()
.register_type::<BrushFaceDesc>()
+89
View File
@@ -79,6 +79,33 @@ impl MaterialAsset {
}
}
/// Loads a project Material or direct-base Material Instance into one effective descriptor.
///
/// The returned descriptor retains the selected asset path so primitive/brush authoring can locate
/// the shared source while renderer slots continue to preserve their stable [`MaterialRef`].
pub fn load_resolved_material_from_path(
catalog_path: &str,
) -> Result<(MaterialDesc, MaterialRenderState), String> {
if let Ok(asset) = MaterialAsset::load_from_path(catalog_path) {
let mut material = asset.material;
material.material_asset_path = Some(catalog_path.to_string());
return Ok((material, asset.render_state));
}
let instance = MaterialInstanceAsset::load_from_path(catalog_path)?;
let base_path = instance.base.0.source_path.as_deref().ok_or_else(|| {
format!(
"material instance {} has no loadable base path",
instance.label
)
})?;
let base = MaterialAsset::load_from_path(base_path)?;
let mut material = base.material;
instance.apply_to(&mut material);
material.material_asset_path = Some(catalog_path.to_string());
Ok((material, base.render_state))
}
/// Explicit reusable overrides over one project Material asset.
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MaterialInstanceAsset {
@@ -270,4 +297,66 @@ mod tests {
.iter()
.any(|value| value.name == "edge_width"));
}
#[test]
fn resolved_material_instance_applies_sparse_overrides_and_keeps_instance_path() {
let root = std::env::temp_dir().join(format!(
"blacksite-resolved-material-instance-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let base_path = root.join("base.ron");
let instance_path = root.join("instance.ron");
std::fs::create_dir_all(&root).unwrap();
let base = MaterialAsset {
schema_version: MATERIAL_ASSET_SCHEMA_VERSION,
label: "Base".into(),
shader: None,
shader_ref: None,
render_state: MaterialRenderState {
double_sided: true,
..Default::default()
},
material: MaterialDesc {
roughness: 0.8,
..Default::default()
},
};
std::fs::write(
&base_path,
ron::ser::to_string_pretty(&base, ron::ser::PrettyConfig::default()).unwrap(),
)
.unwrap();
let instance = MaterialInstanceAsset {
schema_version: MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "Instance".into(),
base: MaterialRef::new(
EditorAssetRef::new("base", "material:source", "Base")
.with_source_path(base_path.to_string_lossy().into_owned()),
),
parameters: vec![MaterialParameter {
name: "roughness".into(),
value: crate::MaterialParameterValue::Float(0.25),
}],
textures: Vec::new(),
};
std::fs::write(
&instance_path,
ron::ser::to_string_pretty(&instance, ron::ser::PrettyConfig::default()).unwrap(),
)
.unwrap();
let (resolved, state) =
load_resolved_material_from_path(instance_path.to_str().unwrap()).unwrap();
assert_eq!(resolved.roughness, 0.25);
assert_eq!(
resolved.material_asset_path.as_deref(),
instance_path.to_str()
);
assert!(state.double_sided);
std::fs::remove_dir_all(root).unwrap();
}
}
+21 -1
View File
@@ -3,7 +3,10 @@
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{ComponentInstanceId, EditorAssetRef, MaterialParameter, MaterialTextureBinding};
use crate::{
ComponentInstanceId, EditorAssetRef, MaterialParameter, MaterialTextureBinding,
TerrainMaterialLayer,
};
/// A stable reference to a project material, material instance, or imported material subasset.
///
@@ -112,6 +115,23 @@ pub struct HydratedRendererMaterialBinding {
pub effective_material: Option<MaterialRef>,
}
/// Runtime ownership marker consumed by the project terrain-layer renderer.
#[derive(Component, Reflect, Debug, Clone, PartialEq)]
#[reflect(Component, Default, Debug, PartialEq)]
pub struct HydratedTerrainMaterialBinding {
pub owner: Entity,
pub layers: Vec<TerrainMaterialLayer>,
}
impl Default for HydratedTerrainMaterialBinding {
fn default() -> Self {
Self {
owner: Entity::PLACEHOLDER,
layers: Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
+16 -1
View File
@@ -52,13 +52,17 @@ Immutable-style log of significant decisions. Add a new numbered ADR when changi
| [0035](adr/0035-shared-material-assets-and-renderer-slots.md) | Shared Material/Material Instance assets, stable renderer slots, and runtime-only property blocks |
| [0036](adr/0036-surface-abi-and-solari-parity.md) | Constrained Surface ABI v1, raster/Solari evaluator parity, and deformed-geometry boundary |
| [0037](adr/0037-collaborative-authored-file-safety.md) | Exact authored-file revisions, observational Git status, and optional ownership providers |
| [0038](adr/0038-non-blocking-native-dialog-broker.md) | Worker-owned native waits with one-shot main-thread workflow completion |
| [0039](adr/0039-inline-height-grid-terrain-foundation.md) | Inline authored height grids with deterministic runtime-only chunk hydration |
| [0040](adr/0040-terrain-material-layer-weights.md) | Four-channel terrain material layers, compact normalized weights, and raster transport |
| [0041](adr/0041-transactional-editor-physics-placement.md) | Paused editor physics ownership and transactional gravity placement |
## Editor framework
| Document | Purpose |
|----------|---------|
| [editor/release-notes.md](editor/release-notes.md) | Editor framework 1.0 baseline |
| [editor/evaluations/](editor/evaluations/) | Horizon gate sign-offs (R1–R6) |
| [editor/evaluations/](editor/evaluations/) | Acceptance records, screenshots, and Gitea evidence-publishing policy |
| [editor/architecture.md](editor/architecture.md) | Viewport / PIE / settings data flow |
| [editor/visual-language.md](editor/visual-language.md) | Editor chrome, viewport, selection, gizmo, and visualizer language |
| [editor/roadmap.md](editor/roadmap.md) | Phased editor roadmap and status |
@@ -77,8 +81,17 @@ Immutable-style log of significant decisions. Add a new numbered ADR when changi
| [editor/extensibility.md](editor/extensibility.md) | Static authoring component registration, lifecycle, composition, and history contract |
| [editor/material-system.md](editor/material-system.md) | Shared material assets and instances, renderer-slot assignment, Surface evaluators, migration, and diagnostics |
| [editor/collaborative-file-safety.md](editor/collaborative-file-safety.md) | Guarded authored writes, compact Git/read-only status, conflict recovery, and ownership providers |
| [editor/native-dialogs.md](editor/native-dialogs.md) | Non-blocking native dialog acquisition and main-thread result application |
| [editor/terrain.md](editor/terrain.md) | Terrain schema, inspector workflow, chunk hydration, collision, and follow-on boundaries |
| [editor/physics-placement.md](editor/physics-placement.md) | Transactional gravity placement, diagnostics, isolation, and undo workflow |
| [editor/collider-authoring.md](editor/collider-authoring.md) | Collider shape authoring, hydration diagnostics, semantic overlays, and placement prerequisites |
| [editor/evaluations/material-renderer-foundation/](editor/evaluations/material-renderer-foundation/) | Live screenshots and acceptance results for the renderer/material/component foundation |
| [editor/evaluations/terrain-sculpt-tools/](editor/evaluations/terrain-sculpt-tools/) | Live screenshot and acceptance results for modal terrain sculpt tools |
| [editor/evaluations/terrain-material-layers/](editor/evaluations/terrain-material-layers/) | Live screenshot and acceptance results for terrain material assignment, blending, painting, and history |
| [editor/evaluations/physics-placement/](editor/evaluations/physics-placement/) | Live screenshot and acceptance results for physics settling, cancel, commit, undo, and redo |
| [editor/evaluations/collider-diagnostics/](editor/evaluations/collider-diagnostics/) | Live screenshot and acceptance results for collider overlays, diagnostics, shape history, and placement preflight |
| [editor/evaluations/navigation-authoring/](editor/evaluations/navigation-authoring/) | Live screenshots and acceptance results for navigation authoring and runtime parity |
| [editor/evaluations/operator-invariants/](editor/evaluations/operator-invariants/) | Source acceptance results for production operator lifecycle, rollback, cleanup, and undo/redo invariants |
| [editor/evaluations/production-readiness/](editor/evaluations/production-readiness/) | Current versioned production gate, evidence matrix, candidate commands, soak protocol, and independent sign-off requirements |
## Working plans (not canonical long-term)
@@ -101,6 +114,8 @@ Detailed milestone and feature plans live in [`.cursor/plans/`](../.cursor/plans
| `source_control_collaboration_safety_*.plan.md` | Exact authored-file guards, observational Git status, conflict recovery, and provider contract |
| `production_readiness_acceptance_*.plan.md` | Release-candidate evidence matrix, blocker sequence, clean-checkout checks, soak, budgets, and independent sign-off |
| `material_library_and_targeted_drop_*.plan.md` | Dedicated Material Library, exact viewport slot/primitive/brush targeting, hover preview, cancel, and grouped history |
| `terrain_material_layers_*.plan.md` | Terrain shared-material layers, normalized weights, blended hydration, and modal painting |
| `operator_invariants_completion_*.plan.md` | Production operator dispatch, interruption, rollback, cleanup, and undo/redo acceptance |
## Crate responsibilities (quick reference)
@@ -55,6 +55,8 @@ from its draw or skeleton representation.
user decision to reassign or discard.
- Legacy primitive/actor `MaterialDesc` paths remain compatibility paths until their consumers move
to renderer slots; new mesh-renderer work uses shared references.
- Runtime property blocks have no editor promotion workflow yet.
- `MaterialPropertyBlocks` currently define the runtime-only schema and persistence exclusion, but
renderer application and the editor promote-to-instance transaction are not implemented. Gitea
#53 owns that complete workflow; callers must not treat the component as visibly applied yet.
- Material graph authoring, nested instances, blended/transmissive materials, and a generalized
per-renderer property-block inspector are outside this decision.
@@ -0,0 +1,40 @@
# ADR 0038: Non-Blocking Native Dialog Broker
## Status
Accepted
## Context
Blacksite opens native file, folder, Save As, and confirmation dialogs from editor workflows. Calling
the synchronous `rfd` API inside a Bevy/egui system stops window event processing until the dialog
returns. On Wayland compositors this can trigger an application-not-responding prompt even though
the native dialog is operating normally.
Path selection precedes stateful main-thread work such as scene serialization, imports, history
changes, prefab relinking, collaborative revision checks, and project activation. Moving those
operations to arbitrary worker threads would violate ECS ownership and weaken existing guards.
## Decision
The editor owns one `NativeDialogBroker` resource. A workflow submits native dialog construction and
a typed completion callback. The broker runs only the blocking native dialog wait on a worker thread,
then queues the result. An exclusive Bevy system drains the queue and invokes each completion exactly
once with `&mut World`.
Only one native dialog may be active. Additional requests fail immediately with explicit status.
Cancellation is delivered as the dialog API's empty or cancel result and remains non-mutating.
Initiating workflows capture stable entity IDs or paths and revalidate them before applying a result.
Native confirmation dialogs use the same broker. A requested close or project switch proceeds only
after the confirmation result and any required save have completed; an incomplete asynchronous save
pauses the transition rather than discarding content.
## Consequences
- Blacksite continues rendering and answering compositor pings while native dialogs are open.
- Project and ECS mutations remain on the Bevy main thread with their existing history, validation,
and collaborative file-revision boundaries.
- Workflows split dialog acquisition from result application and handle stale initiating state.
- The one-dialog policy is intentionally global across the editor and Project Browser.
- A future platform-specific async backend can replace the worker without changing completions.
@@ -0,0 +1,38 @@
# ADR 0039: Inline Height-Grid Terrain Foundation
## Status
Accepted
## Context
Terrain sculpting, material painting, physics placement, recovery, and prefab workflows need one
stable owner for height data. Generated meshes and colliders cannot be authoritative because they
are runtime artifacts, while introducing an external binary heightmap before editing semantics exist
would add file-move, revision, import, and multi-document transaction complexity prematurely.
## Decision
`TerrainDesc` schema v1 stores a bounded square grid of normalized finite `f32` heights directly in
the authored scene component. It also stores sample spacing, height scale, chunk quad size, an
optional shared base Material/Material Instance reference, collider generation, and shadow flags.
Hydration deterministically partitions grid quads into generated children. Boundary samples are
duplicated between neighboring render chunks so each chunk has complete normals and independent
triangle geometry. Chunk meshes/colliders are never `LevelObject` entities and are therefore absent
from saved scenes, recovery documents, prefabs, and history snapshots.
Resolution changes are explicit destructive flat-grid replacements in the foundation inspector.
Sculpt tools mutate the existing grid through grouped history transactions. A future external
heightmap representation requires an explicit schema migration and authored-file ownership ADR; it
must not silently rewrite an inline terrain during normal load.
## Consequences
- Scene, prefab, undo, recovery, collaboration, and validation use one exact terrain document.
- V1 grids are bounded to 1025×1025 samples to prevent accidental unbounded scene payloads.
- Large production terrains may eventually need tiled external storage and streaming.
- Foundation chunks remain raster-only in Solari until terrain layer materials have an exact Surface
evaluator in `#24`; explicit exclusion is preferred to a black or mismatched ray-traced proxy.
- Layer weights and sculpt strokes extend this descriptor contract in `#23`/`#24`; generated chunks
remain disposable regardless of the editing representation.
@@ -0,0 +1,36 @@
# ADR 0040: Terrain Material Layers And Weight Transport
## Status
Accepted
## Context
Terrain needs multiple shared project materials, editable weight painting, deterministic persistence,
and raster behavior that remains consistent between the editor and game. Duplicating full material
descriptors into scenes would break the shared Material/Material Instance contract. Storing floating
point weights would also create avoidable scene churn and normalization drift.
## Decision
`TerrainDesc` stores at most four `TerrainMaterialLayer` entries referencing shared assets and one
RGBA8 weight tuple per height sample. Every explicit tuple sums to 255; an absent weight array means
full channel-zero coverage for backward compatibility. Generated terrain chunks transport normalized
weights through `Mesh::ATTRIBUTE_COLOR`.
`shared` owns persistence, validation, chunk generation, and a runtime-only terrain material binding.
`blacksite_surface` owns the terrain-specific `ExtendedMaterial` and blends each resolved layer's
albedo, tangent-space normal, metallic, and roughness inputs. Invalid or unavailable references leave
the existing visible terrain fallback in place and emit diagnostics. Terrain remains excluded from
Solari geometry until a matching ray-tracing evaluator exists.
Editor paint strokes materialize the implicit default map only when needed. Each pointer stroke is a
single reflected `TerrainDesc` transaction; cancel restores the exact original descriptor.
## Consequences
- Four channels give fixed shader bindings, compact deterministic scenes, and simple normalization.
- Adding more than four simultaneous layers requires a deliberate schema and renderer revision.
- Weight resolution follows the height grid; independent high-resolution splat maps remain future work.
- Terrain raster rendering gains project-material texture parity while Solari terrain parity remains an
explicit later milestone rather than using a semantically different proxy.
@@ -0,0 +1,44 @@
# ADR 0041: Transactional Editor Physics Placement
## Status
Accepted
## Context
The editor and game share one Bevy world and one Avian physics instance. Authored rigid
bodies are hydrated in Edit mode so collider visualization and queries remain available,
but advancing the shared simulation while editing mutates scene transforms outside history.
A physics-placement tool must use the real runtime colliders while preventing unrelated
dynamic bodies, PIE state, or authored physics settings from changing.
Running a second physics world would duplicate hydration, imported-mesh collider cooking,
and hierarchy mapping. Advancing the existing world without isolation would make placement
dependent on every other movable body in the scene and would violate cancel safety.
## Decision
The editor owns Avian's `Time<Physics>` clock:
- normal Edit mode and paused Play mode keep physics paused;
- active Play mode unpauses physics;
- paused Play single-step advances the physics clock by one fixed tick;
- the placement tool advances bounded 120 Hz steps while Edit mode remains paused.
Physics placement is a transactional preview in the shared world. It snapshots the selected
bodies' local transforms and runtime motion components, temporarily makes them dynamic, and
temporarily makes every other movable rigid body static. Static bodies and all colliders stay
in the same world, preserving production collision fidelity. Commit restores every temporary
runtime override and writes only the final local transforms through one grouped history
command. Cancel restores the full snapshot and writes no history.
## Consequences
- Edit mode no longer permits authored dynamic bodies to drift outside undo history.
- Placement uses the exact hydrated collider geometry used by PIE and the standalone game.
- Kinematic and dynamic non-selected bodies behave as fixed collision surfaces during the
preview; simulating interacting piles is deliberately outside this tool's contract.
- A placement session cannot cross the Edit/Play boundary and is cancelled on mode exit.
- Future editor physics previews should reuse this clock ownership and transactional-session
model instead of introducing independent ad hoc simulation loops.
+22 -3
View File
@@ -24,8 +24,22 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
| [extensibility.md](extensibility.md) | Static authoring component lifecycle registration, stable IDs, composition, and generic history |
| [material-system.md](material-system.md) | Shared Material/Material Instance assets, static/skinned renderer slots, Surface ABI, Solari scope, and migration |
| [collaborative-file-safety.md](collaborative-file-safety.md) | Exact authored-file revisions, Git/read-only status, conflict recovery, and optional ownership providers |
| [native-dialogs.md](native-dialogs.md) | Non-blocking file/folder/confirmation acquisition and main-thread result application |
| [terrain.md](terrain.md) | Inline height-grid terrain, chunk hydration, collision, inspector workflow, and fixtures |
| [physics-placement.md](physics-placement.md) | Transactional gravity placement, prerequisites, isolation, commit/cancel, and undo |
| [collider-authoring.md](collider-authoring.md) | Collider shape editing, shared health diagnostics, overlays, hydration status, and placement reuse |
| [evaluations/](evaluations/) | Acceptance evidence records and native Gitea attachment publishing policy |
| [evaluations/material-renderer-foundation/](evaluations/material-renderer-foundation/) | Live screenshots and verification record for the renderer/material/component foundation |
| [evaluations/material-library-targeted-drop/](evaluations/material-library-targeted-drop/) | Live screenshot and verification record for the docked Material Library and exact reversible surface drops |
| [evaluations/collaborative-file-safety/](evaluations/collaborative-file-safety/) | Live screenshot and verification record for source-control status and guarded external-change recovery |
| [evaluations/native-dialog-responsiveness/](evaluations/native-dialog-responsiveness/) | Live native-Wayland screenshot and verification record for non-blocking picker responsiveness |
| [evaluations/terrain-foundation/](evaluations/terrain-foundation/) | Live screenshot and verification record for height-grid terrain schema and chunk hydration |
| [evaluations/terrain-sculpt-tools/](evaluations/terrain-sculpt-tools/) | Live screenshot and verification record for modal sculpt controls, footprint, and stroke history |
| [evaluations/terrain-material-layers/](evaluations/terrain-material-layers/) | Live screenshot and verification record for blended layers, assignment, painting, and history |
| [evaluations/physics-placement/](evaluations/physics-placement/) | Live screenshot and verification record for multi-prop settling, cancel, commit, undo, and redo |
| [evaluations/collider-diagnostics/](evaluations/collider-diagnostics/) | Live screenshot and verification record for semantic collider overlays, health linking, shape switching, and placement reuse |
| [evaluations/navigation-authoring/](evaluations/navigation-authoring/) | Live screenshots and verification record for navigation authoring and runtime parity |
| [evaluations/operator-invariants/](evaluations/operator-invariants/) | Source acceptance record for production operator lifecycle, rollback, cleanup, and undo/redo invariants |
| [evaluations/production-readiness/](evaluations/production-readiness/) | Current #50 release-candidate matrix and required clean-checkout, soak, performance, limitation, and independent-signoff evidence |
## Subsystems (code → doc)
@@ -34,18 +48,22 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
|-------------|----------------|-----|
| `lib.rs` / `EditorPluginGroup` | Ordered plugin bundle, lib/bin split | ADR 0008, architecture.md |
| `shared::components::BrushDesc` / `shared::hydration::brushes` | Persisted brush authoring data and generated runtime mesh hydration | brushes.md, ADR 0021 |
| `shared::components::TerrainDesc` / `shared::hydration::terrain` / `blacksite_surface` | Persisted height/layer grids, generated chunks, and raster blending | terrain.md, ADR 0039, ADR 0040 |
| `viewport/physics_placement.rs` / `play/state.rs` | Paused Edit physics and transactional gravity placement | physics-placement.md, ADR 0041 |
| `viewport/collider_diagnostics.rs` / `viewport/visualizers.rs` / `ui/inspector.rs` | Shared collider health, semantic overlays, and undoable shape authoring | collider-authoring.md |
| `scene/` | Level I/O, tabs, composition materialization, schema, viewport render-target setup | architecture.md, multi-scene-composition.md, ADR 0026 |
| `viewport/` | Camera, selection, gizmos, render views | architecture.md |
| `play/` | PIE session, editor mode state | architecture.md |
| `play/audio_preview.rs` / `game::audio` | Non-dirty editor audition and authored runtime playback/bus adapter | audio-authoring.md, ADR 0030 |
| `assets/animation.rs` / `ui/animation_inspector.rs` / `game::animation` | Generated animation manifests, controller authoring/preview, and runtime state adapter | animation-authoring.md, ADR 0031 |
| `ui/navigation_inspector.rs` / `scene::navigation` / `game::navigation` | Navigation authoring, deterministic bake artifacts, viewport preview, and runtime path queries | navigation-authoring.md, ADR 0032 |
| `assets/materials.rs` / `shared::renderer_material` / `shared::hydration::{static_meshes,skinned_meshes}` | Shared material discovery, stable renderer slots, and draw binding | material-system.md, ADR 0035 |
| `assets/materials.rs` / `ui/material_library.rs` / `viewport/material_drop.rs` / `shared::renderer_material` | Shared material discovery, docked catalog/usage UI, exact reversible surface drops, stable renderer slots, and draw binding | material-system.md, ADR 0035 |
| `blacksite_surface` / `game_hot::rendering::solari` / `third_party/bevy_solari` | Surface ABI packing, raster composition, Solari evaluator dispatch, and deformation eligibility | material-system.md, rendering.md, ADR 0036 |
| `assets/` | Catalog, asset DB, static mesh artifacts, `thumbnails/`, `materials.rs`, prefab overrides v2 | this file (below), prefab-authoring.md, ADR 0017, ADR 0027 |
| `shared::prefab_overrides` | Versioned stable override schema and editor-independent runtime application | prefab-authoring.md, ADR 0027 |
| `project/` | Workspace, settings UI, user prefs, support diagnostics | roadmap Phase 1 |
| `project/collaboration.rs` | Guarded authored writes, asynchronous Git status, and optional ownership providers | collaborative-file-safety.md, ADR 0037 |
| `project/native_dialog.rs` | One-at-a-time native dialog worker and one-shot main-thread completions | native-dialogs.md, ADR 0038 |
| `project/session.rs` | Versioned XDG session document, clean marker, and safe resume | session-recovery.md, ADR 0024 |
| `project/diagnostics_bundle.rs` | Privacy-bounded transactional support report export | session-recovery.md, ADR 0024 |
| `project/launcher.rs` | Strict project inspection, CLI activation, recent filtering, and sandbox scaffolding | project-launcher.md, ADR 0025 |
@@ -68,14 +86,15 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
- **Unified viewport** uses one render-to-texture target for both the editor fly camera and the possessed player camera so HDR/atmosphere is not broken by sub-viewport cropping.
- **PIE:** F8 possess/eject while sim runs; **F6** pauses/resumes simulation in Play; project settings drive shared rendering for the active viewport camera.
- **Asset browser** mirrors the on-disk `assets/` directory with project tree, breadcrumb, search/filter/sort, grid/list views, texture/model/material thumbnails, a details pane, and context-aware row/menu actions; narrow docks prioritize content, keep the root panel fixed, switch list view to a compact single-column layout, and hide tree/details panes when they would crowd the content area. The footer stays pinned while only the project tree, asset content, and details panels scroll. **Built-ins** holds spawnable primitives and lights. **Materials** folder scans `assets/materials/*.ron`, renders material thumbnails on a sphere using `MaterialDesc`, and exposes shader-schema-driven parameters/textures in the details editor; **Shaders** holds shader schema RON files. **Audio** accepts Bevy-supported Ogg/Vorbis and Speex (`.ogg`, `.oga`, `.spx`), WAV, MP3, and FLAC clips under `assets/audio/`, with a dedicated filter, waveform icon, format/file details, and stable registry-backed references that retain a runtime source path. glTF/GLB/FBX rows can expand into a shelf of normalized embedded mesh, material, and texture subassets with independent generated thumbnails. Mesh subassets can be selected, dragged into the viewport, or placed from details/context menus; material subassets render source-material spheres; texture subassets can be applied to the selected actor. Model import settings are staged with **Apply** / **Revert**, asset context menus can regenerate thumbnails, material asset details edit shared `MaterialAsset` fields, and file asset deletion moves sources/generated artifacts into `assets/.trash/`. Before thumbnail loading, glTF sources preflight local external buffers/images and show a stable non-retryable failure state when a dependency is missing instead of repeatedly invoking the asset loader.
- **Material Library** is a dockable bottom-panel catalog for cross-folder Material and direct-base Material Instance authoring. It provides search, type and scene-usage filters, grid/list thumbnails, dependency health, usage counts, creation, guarded details editing, and first-class drag sources. Viewport drops resolve an exact renderer slot, primitive, or brush face under the pointer, preview transiently, reject incompatible/read-only targets explicitly, restore on target change/cancel, and commit one typed undo step on release.
- **Static/skinned renderer split** — model drag/drop uses normalized artifacts under `assets/meshes/generated/`. Unrigged, non-animated sources create `ActorKind::StaticMesh + StaticMeshRenderer`; skin-bound or animated sources create `ActorKind::SkinnedMesh + SkinnedMeshRenderer` and preserve the imported hierarchy. Static slots never contain marked skinned primitives or geometry from animated sources. `SceneInstance` placement keeps `ImportedModel + ModelRef` for generic full-source scenes. See [ADR 0033](../adr/0033-dedicated-skinned-mesh-renderer.md).
- **Animation authoring** — glTF/GLB imports generate UUID-keyed rig/clip manifests and expandable skeleton/clip shelves. Clip drag creates a skinned actor or adds one exact-signature-compatible state to a selected skinned actor through typed history. `AnimationControllerDesc` exposes named states, ranges, loop/speed, default/crossfade, and non-dirty runtime-backed preview; project validation resolves the same stable refs and blocks animated/skinned FBX with conversion guidance. Production acceptance completed in Gitea #46. See [animation-authoring.md](animation-authoring.md) and [ADR 0031](../adr/0031-animation-authoring-runtime-contract.md).
- **Navigation authoring** — bounds, obstacles, areas, and links use typed history and viewport visualizers. Rerecast produces a versioned fingerprinted artifact; Polyanya powers both editor path preview and the game-owned runtime API. The existing horizontal toolbar path button creates or bakes bounds, while Scene > Navigation exposes the complete workflow. See [navigation-authoring.md](navigation-authoring.md) and [ADR 0032](../adr/0032-versioned-navigation-bake-and-runtime-query.md).
- **Brush authoring** — `ActorKind::Brush + BrushDesc` stores persisted convex blockout faces, validates authored geometry in the inspector and Window → Brush Diagnostics, and hydrates active valid brushes into generated mesh children. See [brushes.md](brushes.md).
- **Draw Brush** — `B`, toolbar pencil, or command `brush.draw` enters a floor-polygon draw mode. LMB places snapped points, Backspace removes the last point, Enter locks the outline for height editing, mouse up/down adjusts height, and Enter/LMB creates additive prism brushes through history. Esc/right-click cancels. Simple concave outlines decompose into convex brush parts; self-intersections remain blocked.
- **Brush edit modes** — with a brush selected, `1`/`2`/`3`/`4` enter vertex, edge, face, and clip element modes. Element modes show brush handles in the viewport, own LMB picking, support Shift multi-select, show a mode badge, and Esc returns to object mode. Vertex/edge/face selections use the standard `W`/`E`/`R` gizmo at the element pivot and commit undoable `SetBrush` edits. Clip previews a bounds-based half-brush and commits with Enter; command-palette intersect, convex merge, and subtract operations use the same preview/commit lifecycle for conservative cuboid/prism blockout.
- **Collider split** — imported mesh collision lives in a separate `ColliderDesc::StaticMesh` plus optional `RigidBodyDesc`; renderer slots own only render visibility, shadows, mesh, and material references.
- **Material assets and renderer slots** — Material and direct-base Material Instance documents are shared assets. `StaticMeshRenderer` and `SkinnedMeshRenderer` each own stable material slots with imported source defaults and explicit shared assignments; Clear returns to the source default, while reimported missing slots retain overrides as orphans instead of matching by name. Runtime-only property blocks never mutate or persist into the shared asset. Custom Surface evaluators use the same constrained ABI for raster and Solari-eligible non-deformed geometry; skinned/morph geometry is deliberately excluded from Solari until deformed BLAS updates exist. See [material-system.md](material-system.md), [ADR 0035](../adr/0035-shared-material-assets-and-renderer-slots.md), and [ADR 0036](../adr/0036-surface-abi-and-solari-parity.md).
- **Collider split and health** — imported mesh collision lives in a separate `ColliderDesc::StaticMesh` plus optional `RigidBodyDesc`; renderer slots own only render visibility, shadows, mesh, and material references. Inspector, viewport, Diagnostics, and physics placement share one authored/runtime health result; see [collider-authoring.md](collider-authoring.md).
- **Material assets and renderer slots** — Material and direct-base Material Instance documents are shared assets. `StaticMeshRenderer` and `SkinnedMeshRenderer` each own stable material slots with imported source defaults and explicit shared assignments; Clear returns to the source default, while reimported missing slots retain overrides as orphans instead of matching by name. The property-block schema is runtime-only and persistence-excluded, while renderer application/promotion remains #53. Custom Surface evaluators use the same constrained ABI for raster and Solari-eligible non-deformed geometry; skinned/morph geometry is deliberately excluded from Solari until #54 adds deformed BLAS updates. See [material-system.md](material-system.md), [ADR 0035](../adr/0035-shared-material-assets-and-renderer-slots.md), and [ADR 0036](../adr/0036-surface-abi-and-solari-parity.md).
- **Prefab authoring** — shared `PrefabOverrides` targets generated actors by nested anchor chain plus stable `ActorId`, and applies reflected property/component plus same-layer structural operations in editor and game hydration. The editor supports scoped Revert and transactional **Apply to source** with three-way conflict checks, exact-file undo guards, and recoverable changed/broken/conflict states. `HydratedPrefabMember` keeps generated content out of owner serialization; linked-root saves retain local structure as variants. **Unpack Layer** preserves nested links, while **Convert to Local** recursively removes them. See [prefab-authoring.md](prefab-authoring.md) and [ADR 0027](../adr/0027-stable-prefab-ownership-and-variants.md).
- **Visual language** uses a near-black industrial shell, a compact Blacksite identity mark, restrained amber actions/primary selection, cyan secondary selection, semantic status colors, stable grouped controls, and shared elevated viewport chips. Primary/secondary selection roles remain consistent across hierarchy rows, viewport x-ray shells/corner brackets, the selection HUD, and transform interactions. See [visual-language.md](visual-language.md).
- **Hierarchy** shows authored objects plus useful runtime context (`Player`, `PlayerCamera`, Project Sun). Ordinary runtime rows remain read-only; generated prefab rows expose override-aware inspection and same-layer remove/reparent actions while rejecting cross-instance/layer and composition-boundary drops. Locks prevent selection, gizmos, drag participation, structural targets, and mutating context actions. Authored reparenting preserves world placement and records parent/local-transform/manual-order changes as one undoable command.
+19 -7
View File
@@ -24,6 +24,7 @@ Native-only dependencies (`rfd`, BRP HTTP) stay in `editor`. `settings`, `shared
| `ProjectSettingsPlugin` | Load `assets/project.ron`, emit changes, sync `SimTuning` |
| `ProjectIoPlugin` | User prefs, workspace metadata, window title inputs |
| `EditorStatePlugin` | `EditorMode` (Edit/Play), `PlayPossession`, camera/input gating |
| `PhysicsPlacementPlugin` | Paused Edit physics plus isolated transactional gravity placement |
| `ViewportPlugin` | Grid, focus, bookmarks, snap settings |
| `EditorCameraPlugin` | Fly camera; FX applied via `render_view` + `viewport_camera` sync |
| `ActorIconsPlugin` | Selectable actor root billboard icons |
@@ -181,11 +182,19 @@ stateDiagram-v2
|----------|---------|-------------------|-----------------|
| `SimEnabled` | false | true | true |
| `GameInputEnabled` | false | true | false |
| `Time<Physics>` | paused | running | running |
| Editor camera active | true | false | true |
| Player camera active | false | true | false |
On play enter/exit the editor snapshots **player sim state only** (transform, velocity, jump timers). Authored scene entities are not rolled back so in-play edits persist when stopping PIE.
Paused Play also pauses `Time<Physics>`; **F7** advances that clock by exactly one 64 Hz sim tick.
Edit mode keeps the clock paused. `viewport/physics_placement.rs` may advance bounded 120 Hz
preview steps while selected bodies are temporarily dynamic and every other movable body is
temporarily static. Commit records only final local transforms through grouped history; cancel and
the Edit-to-Play boundary restore the complete runtime snapshot. See
[physics-placement.md](physics-placement.md) and [ADR 0041](../adr/0041-transactional-editor-physics-placement.md).
## Scene authoring flow
1. User edits entities with `LevelObject` + reflectable components from `shared`.
@@ -236,13 +245,16 @@ On play enter/exit the editor snapshots **player sim state only** (transform, ve
Structural edits (spawn, delete, transform, rename) go through `EditorHistory` command objects in `history.rs`.
User-facing actions route through the operator lifecycle in `operators.rs`: begin, preview,
commit, cancel, disabled reason, and status text. The first bridge wraps command-palette and queued
editor commands as immediate operators, while existing `EditorHistory` commands remain the undo
payload. Asset placement, mesh-subasset placement, texture apply, and material apply actions now
use immediate operators from `assets::operators`; texture/material changes across a selection use
one `SetMaterialGroup` command. Draw Brush, brush CSG, clip, and element gizmo paths publish the
same preview/commit/cancel phases. `operators/test_harness.rs` verifies authored deltas, dirty
state, helper cleanup, undo grouping, and undo/redo restoration; see
commit, cancel, disabled reason, stable ID, and status text. Registered commands return typed
`OperatorAction::Commit` or `OperatorAction::ContinuePreview`, so immediate commands finish while
Draw Brush and CSG retain modal Preview ownership; validation failures terminate instead of leaving
stale status. Existing `EditorHistory` commands remain the undo payload. Group Selection is one
atomic command that remaps its transient group identity on every redo without reparenting unrelated
siblings. Lighting reset and Project Sun changes use one grouped light command. Asset placement,
assignment, exact material drops, brush tools, terrain strokes, physics placement, and the real
transform tracker all publish terminal lifecycle state. `operators/test_harness.rs` verifies semantic
projections, dirty-state preservation, stable IDs, helper cleanup, undo grouping, repeated undo/redo,
and automatic interruption rollback; see
[operator-regression-testing.md](operator-regression-testing.md).
PIE stop restores player simulation state only; authored `LevelObject` edits made during PIE remain in the scene.
+4
View File
@@ -56,3 +56,7 @@ empty provider registry performs no calls and adds no UI.
The architectural policy is recorded in
[ADR 0037](../adr/0037-collaborative-authored-file-safety.md).
Live editor acceptance, including external-change detection, metadata comparison, cancel/reload
invariants, and source-control status, is recorded in the
[collaborative file-safety evaluation](evaluations/collaborative-file-safety/).
+55
View File
@@ -0,0 +1,55 @@
# Collider Authoring And Diagnostics
`ColliderDesc` is the saved collision shape. `RigidBodyDesc` independently controls authored body
motion, while Avian `Collider` and `RigidBody` components are hydrated runtime state. Collider
health compares both sides of that boundary so editor tools do not treat authored-but-unavailable
collision as ready.
## Inspector Workflow
The Collider component card reports its shape, health, and hydration state. Box, sphere, capsule,
and static mesh shapes can be switched from the Shape menu. Primitive conversions retain the
previous shape's useful extents; each completed switch uses `SetCollider` history and is one undo
operation. Invalid shapes expose a reset action. Static mesh sources can be selected or replaced
with the actor's renderer meshes.
Dimensions are clamped to positive values in normal inspector editing. Project validation still
rejects hand-edited or migrated non-finite/zero dimensions and empty mesh source lists.
## Viewport Contract
Collider view hides render meshes and emphasizes authored collision using semantic status colors:
| Color | State |
|-------|-------|
| Green | Valid hydrated solid collider |
| Cyan | Valid hydrated trigger |
| Gray | Disabled or inactive collider |
| Amber | Stale hydration or oversized collider |
| Red | Missing or invalid collider |
Box, sphere/ellipsoid, and capsule wireframes include actor world scale. Static mesh collision uses
the cooked runtime collider bounds when available. A rigid body with no collider receives a red
spatial marker, so missing collision remains discoverable with meshes hidden. The lower-left HUD
summarizes scene health and identifies the selected collider's shape and hydration state.
## Diagnostics
The shared health service reports:
- missing/inactive/disabled collider authoring;
- non-positive or non-finite primitive dimensions;
- empty, unresolved, or registry-stale static mesh references;
- valid authoring that has not produced a runtime collider;
- primitive colliders exceeding 1,000 meters on any world-space axis.
The 1,000-meter warning is conservative rather than a save blocker. Large worlds should split
collision into spatially bounded actors to keep broad-phase behavior predictable. Diagnostics can
select the affected actor; static mesh fields retain their asset-browser locate action.
Physics Placement consumes the same errors plus its stricter non-trigger and hydrated rigid-body
requirements. See [physics-placement.md](physics-placement.md).
`assets/levels/collider_diagnostics_showcase.scn.ron` contains valid box, scaled sphere, capsule,
trigger, disabled, and missing-collider states for visual acceptance. Invalid, oversized, and stale
asset cases live in unit fixtures so the committed project remains release-valid.
+3 -1
View File
@@ -10,6 +10,7 @@ Living checklist for the production editor program ([ADR 0012](../adr/0012-zero-
| Monolithic `hydrate_authoring_entities` | Done | `crates/shared/src/hydration/*` modules |
| Optional / inferred `ActorKind` as long-term save path | Done | Schema v2 + migration; save validates |
| Hydrated components in committed `.scn.ron` | CI | `scene::validate_scene_authoring_only` + `repo_editor_scene_has_no_hydrated_components` |
| Production mutation without commit/cancel/failure/undo invariants | Done | Shared operator harness plus typed history projections cover palette, asset, brush, terrain, physics, grouping, lighting, material-drop, and transform paths; see [evaluation](evaluations/operator-invariants/) |
| Dual FBX thumbnail ad-hoc path (parallel to unified pipeline) | Partial | Phase 5 `assets/thumbnails/` refactor |
| `failed_keys` thumbnail cache without retry API | Partial | `asset_thumbnails.rs`; Phase 5 `ThumbnailState` |
@@ -21,7 +22,7 @@ Living checklist for the production editor program ([ADR 0012](../adr/0012-zero-
| P1 | `ActorKind` required; `validate_actor` on save |
| P2 | No runtime components in default inspector |
| P3 | `HierarchySiblingIndex`; no undefined sibling order |
| P6 | `ActorInspectorSection` registry; command palette commands; BRP authoring policy |
| P6 | `ActorInspectorSection` registry; typed immediate/modal command dispatch; BRP authoring policy; production mutation invariants |
| P7 | ADRs 0009–0012 indexed; CI `shared` + `scene` + `editor` checks |
## Manual verification (release)
@@ -29,3 +30,4 @@ Living checklist for the production editor program ([ADR 0012](../adr/0012-zero-
- [ ] R1–R6 rendering/inspector scenarios ([roadmap.md](roadmap.md))
- [ ] Save/load roundtrip: hierarchy, lights, materials unchanged
- [ ] PIE 60s stop: project lighting profile unchanged unless scene overrides edited
- [ ] Rerun the [operator invariant matrix](operator-regression-testing.md) from the nominated release-candidate commit
+15
View File
@@ -0,0 +1,15 @@
# Editor Evaluation Evidence
Each subdirectory keeps the canonical, versioned acceptance record for an editor feature. Screenshots
remain in the repository beside that record and are intentionally stored through Git LFS.
## Publishing To Gitea
Do not embed a repository `/raw/branch/...` or `/raw/commit/...` PNG URL in an issue or pull-request
comment. Gitea can serve the LFS pointer document at that URL, which renders as text instead of an
image. Upload the PNG to the relevant issue as a native attachment and use the returned
`/attachments/<uuid>` URL for the Markdown image. Keep the repository evaluation link next to the
attachment so the evidence remains traceable to its committed source.
Native attachments are presentation copies. The committed evaluation directory remains the source of
truth and should retain the original image and verification notes.
@@ -0,0 +1,39 @@
# Collaborative File Safety Evaluation
Date: 2026-07-12
Branch: `codex/collaboration-live-acceptance`
Implementation commits: `5a82a9e`, `f2ad88f`
This record captures live acceptance for source-control status and guarded authored-file writes.
The permanent workflow and recovery contract live in the
[collaborative file-safety guide](../../collaborative-file-safety.md).
## Live Editor Evidence
The image below is a native Wayland capture from the debug editor. A disposable untracked scene
was loaded, changed locally, and then changed independently on disk before Save.
![External-change guard showing loaded and current revision metadata while the dirty untracked scene remains open](external-change-metadata.png)
The bottom status strip reports the active scene as `UNTRACKED`. The guarded save left the disk
revision unchanged and opened recovery choices with the exact loaded/current revision, byte count,
modified time, and permissions.
## Acceptance Results
| Area | Result | Evidence |
|------|--------|----------|
| Source-control status | Pass | Active disposable scene reported `UNTRACKED` without disrupting the editor workflow |
| External-change guard | Pass | Save detected the changed disk revision and did not overwrite it |
| Metadata comparison | Pass | Loaded/current revision, byte count, modified time, and permissions were displayed |
| Cancel invariants | Pass | Cancel preserved the dirty local scene and made no filesystem change |
| Invalid reload | Pass | Malformed external RON failed safely, kept the recovery dialog open, and reported the error |
| Valid reload | Pass | Reload replaced the local draft, removed its duplicate actor, cleared dirty/history state, and adopted the disk revision |
| Repository hygiene | Pass | Disposable scene and importer registry churn were removed after acceptance |
| Packaged acceptance | Deferred | Explicitly deferred by project-owner direction; no packaged result is claimed here |
## Automated Verification
The implementation commits were already covered on integrated `main` by the workspace formatting,
check, strict Clippy, test, level-validation, and navigation-artifact suites. This evidence-only
change was additionally checked with `git diff --check`.
@@ -0,0 +1,24 @@
# Collider Diagnostics Acceptance
Issue: Gitea #26 (`BS-JD-305`)
## Evidence
![Collider viewport, selected trigger inspector, and scene health panel](collider-diagnostics-live.png)
The native Wayland editor loaded `assets/levels/collider_diagnostics_showcase.scn.ron` and entered
Collider view. The captured frame shows shape overlays with meshes hidden, the scene health HUD,
the selectable Diagnostics window, and the selected trigger's hydrated status in the inspector.
## Live Results
- Box, scaled sphere/ellipsoid, and capsule overlays matched authored transforms and dimensions.
- Green ready, cyan trigger, gray disabled, and red missing states were visually distinct.
- The HUD reported `4 ready / 1 disabled / 0 warning / 1 invalid` and followed selection.
- The Diagnostics panel linked the missing finding back to its actor.
- Switching the valid box to sphere preserved useful extents and produced `Undo: Set Collider`;
undo restored the box.
- Physics Placement rejected the missing-collider actor with the shared collider-health messages.
- Scene switching and editor shutdown completed without a panic or runtime validation error.
Packaged verification remains deferred by current project instruction.
@@ -0,0 +1,47 @@
# Material Library And Targeted Drop Evaluation
Date: 2026-07-12
Branch: `codex/material-library-targeted-drop`
Implementation commit: `02247f0`
This record captures live acceptance for the docked Material Library and exact viewport
Material/Texture assignment workflow. The permanent user workflow lives in the
[material-system guide](../../material-system.md), and the implementation plan is
[material_library_and_targeted_drop_2026-07-12.plan.md](../../../../.cursor/plans/material_library_and_targeted_drop_2026-07-12.plan.md).
## Live Editor Evidence
The image below is a native Wayland capture from the debug editor. The assignment was previewed,
committed once, undone, previewed again, and canceled with Escape; the authored scene was not saved.
![Material Instance preview on the exact Ground surface with the docked Material Library and green target feedback](material-instance-surface-preview.png)
The Material Library resolves `surface_tint_instance` through its base Material and sparse
overrides. While the pointer is over the viewport, the green card names `Ground / Surface`, the
inspector reflects the transient material, and the scene-usage section identifies the exact actor
and surface. The preview does not push history or dirty the scene.
## Acceptance Results
| Area | Result | Evidence |
|------|--------|----------|
| Catalog workflow | Pass | Window menu entry, persisted bottom dock, search, Material/Instance/Used/Unused filters, grid/list views, resolved instance thumbnail, and details selection |
| Exact targeting | Pass | Primitive preview resolves one actor surface; automated coverage resolves one stable renderer slot and one stable brush face |
| Feedback | Pass | Neutral acquisition changes to green valid actor/surface feedback; invalid payload and read-only paths are covered by focused tests |
| Preview lifecycle | Pass | Live material and usage update without a history entry; Escape restores the exact prior material |
| Commit lifecycle | Pass | Release creates one typed history/operator entry; undo restores the prior surface |
| Startup hygiene | Pass | Relaunching the authored showcase after visibility-order correction produced no Bevy hierarchy warnings |
| Packaged acceptance | Deferred | Explicitly deferred by project-owner direction; no packaged result is claimed here |
## Automated Verification
| Command/suite | Result |
|---------------|--------|
| `cargo fmt --all -- --check` | Pass |
| `cargo check --workspace --all-targets` | Pass |
| `cargo clippy --workspace --all-targets -- -D warnings` | Pass |
| `cargo test --workspace` | Pass |
| Editor strict Clippy with `dev` and `hot-reload` features | Pass |
| `cargo validate-levels --project .` | 59 dependencies, 5 non-blocking findings, 0 blocking errors |
| `cargo bake-navigation --project . --check` | 1 deterministic artifact current |
| `git diff --check` | Pass |
@@ -65,7 +65,7 @@ Additional captures:
| Dedicated static/skinned ownership | Pass | Separate authored/hydrated renderer types; rigged/animated manifests are rejected by static hydration |
| Pose lifecycle | Pass | Explicit stable default clip; transform and morph-weight baseline restore on stop, controller removal, preview reset, and PIE exit |
| Renderer material slots | Pass | Stable named IDs, imported fallback, explicit assignment, orphan retention, and in-place material patching |
| Material assets/instances | Pass | Versioned shared assets, direct-base sparse instances, transient property blocks, Apply/Revert/Create Instance |
| Material assets/instances | Pass | Versioned shared assets, direct-base sparse instances, Apply/Revert/Create Instance; property-block runtime application/promotion is isolated in #53 |
| Texture parameters | Pass | Project-wide picker includes imported texture subassets; base/schema/stored/instance slots share browse, drop, reject, and clear behavior |
| Component lifecycle | Pass | Stable registry IDs, reflected transactions/history, persistence allowlist, independent active state, and compatible composition |
| Surface raster/Solari semantics | Pass for eligible geometry | Shared ABI packing, evaluator, textures, normal/emissive/unlit values, and cutout predicate |
@@ -92,5 +92,6 @@ Additional captures:
Bevy 0.19's maintained Solari path does not expose dynamic post-morph/post-skin vertex buffers and
BLAS updates. Skinned and morph-deformed actors therefore remain visible in raster but are omitted
from ray tracing with an actionable diagnostic. This is safer than tracing a stale bind-pose ghost;
dynamic deformed BLAS support remains future work and the corresponding Gitea acceptance item stays
open.
dynamic deformed BLAS support is the independently scoped Gitea #54. Runtime property-block
application and promotion are independently scoped in #53; this foundation record does not claim
either follow-up.
@@ -0,0 +1,42 @@
# Native Dialog Responsiveness Evaluation
Date: 2026-07-12
Branch: `codex/non-blocking-native-dialogs`
Implementation commits: `d038cf3` and the closing commit for Gitea #52
This record captures live acceptance for the non-blocking native-dialog broker. The permanent
workflow contract lives in the [native-dialog guide](../../native-dialogs.md).
## Live Editor Evidence
The native KDE portal Open dialog below was launched through the production `SceneIoRequest::Open`
path in a native Wayland debug editor and held open for 12 seconds.
![Native KDE Open dialog over the still-rendered Blacksite editor](native-open-dialog.png)
During the hold, Hyprland continued to report Blacksite as mapped, visible, input-capable, and native
Wayland. No application-not-responding client appeared. Cancel closed the picker without changing the
active scene, and the editor then stopped cleanly.
## Acceptance Results
| Area | Result | Evidence |
|------|--------|----------|
| Frame responsiveness | Pass | A blocked-dialog regression test advances eight Bevy frames before releasing the worker; live editor remained compositor-responsive during the 12-second picker hold |
| Shared coverage | Pass | Every `rfd::FileDialog` and `rfd::MessageDialog` construction is inside a `NativeDialogBroker::request` worker closure |
| Request exclusivity | Pass | Focused test rejects a second request while one is pending and permits work after one-shot completion |
| Cancellation | Pass | Live Open cancellation preserved the active scene; workflow callbacks retain explicit non-mutating cancel branches |
| Main-thread application | Pass | Paths/results cross the broker, while scene, asset, history, registry, project, and collaboration work remains in `&mut World` completions |
| Stale initiating state | Pass | Prefab/export completions reject missing initiating entities; composition validates against current state after selection |
| Packaged acceptance | Deferred | Explicitly deferred by project-owner direction; no packaged result is claimed here |
## Automated Verification
| Command/suite | Result |
|---------------|--------|
| `cargo fmt --all -- --check` | Pass |
| `cargo check --workspace --all-targets` | Pass |
| `cargo clippy --workspace --all-targets -- -D warnings` | Pass |
| `cargo test --workspace` | Pass |
| Focused native-dialog lifecycle and frame-progress tests | 2 passed |
| `git diff --check` | Pass |
@@ -0,0 +1,45 @@
# Operator Invariants Evaluation
Date: 2026-07-12
Gitea issue:
[`#33`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/33)
This acceptance record covers the source-level production operator contract. It does not nominate a
release candidate or replace the clean-checkout rerun required by production-readiness gate G3.
## Accepted Coverage
- Registered commands distinguish immediate completion from modal Preview ownership; validation
failures terminate with their stable command ID.
- Group Selection is one history transaction and preserves unrelated hierarchy rows through repeated
undo/redo even though the transient group entity is respawned.
- Reset Lighting and Project Sun changes are grouped, undoable light transactions.
- Asset/sub-asset placement; material/texture/audio/animation assignment; and exact viewport material
drops cover commit, block/failure, cancel where applicable, and semantic undo/redo projections.
- Draw Brush, CSG, clip, and element-gizmo paths exercise production modal finalizers and helper
cleanup.
- Terrain sculpt/paint cover multi-dab commit, failure rollback, cancel, clean-view interruption, and
resource cleanup.
- Physics placement covers prerequisite block, exact cancel, real settle commit, multi-selection
grouping, helper cleanup, undo, and redo.
- The transform tracker covers continuous multi-target grouping and no-op release termination.
## Verification
The publication worktree passed:
- `cargo test -p editor --lib --no-fail-fast`: 245 passed, 0 failed.
- `cargo clippy -p editor --lib --tests -- -D warnings`.
- `cargo fmt --all -- --check`.
- `cargo test --workspace --all-targets --no-fail-fast`.
- `cargo clippy --workspace --all-targets -- -D warnings`.
- `cargo validate-levels --project .`: 62 dependencies, 5 expected non-blocking findings, 0 blocking
errors.
The Gitea closure comment records these results with the exact publication commit.
No screenshot is required for this ticket: the accepted surface is lifecycle, rollback, cleanup, and
history behavior exercised through headless production entry points. Live command/status checks add
confidence but are not substituted for semantic assertions. Packaged-runtime testing remains
deferred by project-owner request.
@@ -0,0 +1,28 @@
# Physics Placement Evaluation
Date: 2026-07-12
![Three selected props settled on the committed placement floor](physics-placement-settled.png)
The native Wayland editor is shown with the committed
`assets/levels/physics_placement_showcase.scn.ron` fixture. Placement Prop A, B, and C were
multi-selected and released from three different heights through the hand/down-arrow action in the
existing horizontal viewport toolbar.
## Acceptance
- All three props used the hydrated Avian cuboid colliders and settled on Placement Floor after
1.5 simulated seconds.
- During preview the HUD reported selection count, simulated time, and Settled state; transform
gizmos and viewport picking did not compete with the modal tool.
- Escape restored every starting transform and left history empty.
- A second run committed with Enter as exactly one `Undo: Move Selection` entry.
- Ctrl+Z restored all three elevated starting transforms; Ctrl+Y restored the settled transforms.
- Opening the fixture immediately after the terrain showcase no longer panicked on a stale
generated terrain-material binding; the scene-switch regression is covered in
`blacksite_surface`.
- The runtime log contained no physics-placement, scene-load, render-pipeline, or GPU validation
error after the stale-binding fix.
Packaged-runtime tests remain intentionally deferred by project-owner request.
@@ -1,6 +1,6 @@
# Production-Readiness Acceptance Matrix
**Matrix version:** 0.1
**Matrix version:** 0.2
**Last audit:** 2026-07-12
@@ -30,20 +30,20 @@ another commit, a dirty worktree, or an older package do not transfer to the can
| ID | Requirement | State | Current evidence and gap |
|----|-------------|-------|--------------------------|
| G1 | Project create/open/resume, scene authoring, autosave/recovery, hierarchy, prefab, and asset integrity pass | Partial | Project/recovery/session/multi-scene/prefab implementations are documented in [project launcher](../../project-launcher.md), [session recovery](../../session-recovery.md), [multi-scene composition](../../multi-scene-composition.md), and [prefab authoring](../../prefab-authoring.md). Candidate-specific end-to-end reruns and the open asset-integrity work remain. |
| G2 | Brush, material, terrain, physics placement, animation, audio, navigation, PIE, and build/package samples pass | Fail | Animation, audio, navigation, and build foundations are implemented. Material/drag-drop tickets `#16`, `#18`, and `#51` remain open; terrain `#22`-`#24` and physics placement `#25` are not complete; brush acceptance `#37` remains open. Packaged testing is owner-deferred. |
| G3 | Undo/redo/cancel invariants and helper cleanup cover every production mutation path | Partial | The reusable harness and current tool coverage are documented in [operator regression testing](../../operator-regression-testing.md). Gitea `#33` remains open for terrain-stroke and physics-settle fixtures after those tools exist. |
| G1 | Project create/open/resume, scene authoring, autosave/recovery, hierarchy, prefab, and asset integrity pass | Partial | Project/recovery/session/multi-scene/prefab implementations are documented in [project launcher](../../project-launcher.md), [session recovery](../../session-recovery.md), [multi-scene composition](../../multi-scene-composition.md), and [prefab authoring](../../prefab-authoring.md). Collaborative file safety `#49` and non-blocking native dialogs `#52` passed live acceptance. Candidate-specific end-to-end reruns remain. |
| G2 | Brush, material, terrain, physics placement, animation, audio, navigation, PIE, and build/package samples pass | Fail | Animation, audio, navigation, renderer/material foundation `#51`, Material Library, targeted material drops, terrain `#22`-`#24`, physics placement `#25`, and build foundations are implemented with source/live fixtures. Brush acceptance `#37` remains incomplete. Packaged testing is owner-deferred. |
| G3 | Undo/redo/cancel invariants and helper cleanup cover every production mutation path | Partial | Source implementation and focused evidence are complete in [operator regression testing](../../operator-regression-testing.md) and the [operator-invariants evaluation](../operator-invariants/); Gitea `#33` is ready to close. A clean, exact-candidate rerun is still required for `Pass`. |
| G4 | Representative project completes an eight-hour soak without unbounded memory/target growth or unrecoverable failure | Missing | No candidate soak log, resource timeline, failure ledger, or target-growth measurement exists. |
| G5 | Cold start, scene open/save, asset refresh, common manipulation, and package-build budgets are documented and measured | Missing | Gitea `#34` is open; no ratified budgets or candidate measurement record exists. |
| G6 | Headless content validation and CI are green from a clean checkout | Missing | [CI configuration](../../../../.github/workflows/ci.yml) exists and local source/headless checks have passed during feature work, but no clean-checkout candidate run is linked. The current Gitea server does not expose an Actions run endpoint for this repository. |
| G7 | First-hour UX and recovery QA are signed off by someone other than the implementer | External | No independent sign-off exists. Gitea `#36` remains open; historical H1-H6 implementation-pass notes do not count. |
| G8 | Known limitations have severity/workaround and no P0 blocker remains | Fail | Limitations are distributed across feature docs rather than one candidate ledger. Open P0 work includes `#16`, `#18`, `#32`, `#33`, `#35`, and `#51`; `#50` cannot close while a gate-relevant P0 remains. |
| G8 | Known limitations have severity/workaround and no P0 blocker remains | Fail | Limitations are distributed across feature docs rather than one candidate ledger. The remaining open P0 implementation blocker is `#32`; `#50` cannot close while it remains. Operator invariants `#33`, renderer foundation `#51`, roadmap audit `#35`, Material Library `#16`, targeted drops `#18`, collaborative safety `#49`, and dialog responsiveness `#52` are complete. Property-block application `#53` is P1; dynamic deformed Solari geometry `#54` is a documented P2 limitation with Forward/raster fallback. |
## Deliverables
| ID | Deliverable | State | Evidence or next action |
|----|-------------|-------|-------------------------|
| D1 | Versioned acceptance matrix under `docs/editor/evaluations/` | Pass | This file, version 0.1. |
| D1 | Versioned acceptance matrix under `docs/editor/evaluations/` | Pass | This file, version 0.2. |
| D2 | Release-candidate representative project and reproducible validation commands | Missing | Expand the committed project/regression pack through `#32`, including terrain and physics-placement samples, then nominate an exact commit. |
| D3 | Signed milestone comment linking evidence, limitations, and exact commit | Missing | Post only after G1-G8 pass; no candidate exists yet. |
@@ -56,15 +56,17 @@ another commit, a dirty worktree, or an older package do not transfer to the can
| Hierarchy parenting and prefab structure | Implemented | Not rerun |
| Multi-scene composition | Implemented | Not rerun |
| Brush blockout/edit/CSG | Implemented foundation; `#37` open | Not signed off |
| Material catalog and assignment | Partial; `#16`, `#18`, `#51` open | Blocked |
| Terrain authoring | `#22`-`#24` open | Blocked |
| Physics placement | `#25` open | Blocked |
| Material catalog and assignment | Renderer/material foundation `#51`, Material Library, and exact targeted drops accepted; optional property-block promotion is `#53` | Not rerun as one candidate |
| Terrain authoring | `#22`-`#24` source/live acceptance complete; M3 closed | Pass; packaged-runtime acceptance owner-deferred |
| Physics placement | `#25` source/live acceptance complete | Pass; packaged-runtime acceptance owner-deferred |
| Collider authoring and diagnostics | `#26` source/live acceptance complete | Pass; packaged-runtime acceptance owner-deferred |
| Animation | Implemented | Not rerun |
| Audio | Implemented | Not rerun |
| Navigation | Implemented | Not rerun |
| PIE | Implemented | Not rerun |
| Build/package/runtime | Implemented foundation | Deferred by owner |
| Collaborative file safety | Local source/headless acceptance; `#49` open | Awaiting publication and live visual QA |
| Collaborative file safety | Implemented; `#49` closed with live external-change acceptance | Not rerun as one candidate |
| Native file/folder dialogs | Implemented; `#52` closed with live 12-second compositor-responsiveness hold | Not rerun as one candidate |
## Candidate Validation Commands
@@ -0,0 +1,42 @@
# Terrain Foundation Evaluation
Date: 2026-07-12
Branch: `codex/terrain-foundation`
Gitea issue: `#22`
This record captures acceptance for the persistent height-grid terrain schema and deterministic
runtime chunk hydration. The permanent workflow lives in the [terrain guide](../../terrain.md).
## Live Editor Evidence
The native Wayland debug editor loaded the committed
`assets/levels/terrain_authoring_showcase.scn.ron` fixture. The screenshot uses Forward rendering to
isolate mesh/material/light correctness while foundation terrain remains explicitly excluded from
Solari until exact terrain layer/Surface parity lands in `#24`.
![Asymmetric shared-material terrain hill generated from four runtime chunks](terrain-showcase-forward.png)
The 5×5 authored grid renders as the expected asymmetric hill, resolves the committed shared
Material Instance, and is split into four 2×2-quad chunks with generated trimesh colliders. The
authored scene contains no `HydratedTerrainChunk`, `Mesh3d`, or collider-constructor components.
## Acceptance Results
| Area | Result | Evidence |
|------|--------|----------|
| Schema and serialization | Pass | Versioned bounded descriptor, exact height count, finite-value and scale/chunk validation, RON round-trip test |
| Chunk hydration | Pass | Deterministic four-chunk runtime fixture; topology test verifies 25 vertices and 96 indices for a 4×4-quad mesh |
| Runtime-only ownership | Pass | Hydration test verifies children have mesh/collider/owner markers but no `LevelObject`, then verifies removal cleanup |
| Actor/editor integration | Pass | First-class Terrain kind, registry descriptor, hierarchy/viewport icon, reflected Add Component and inspector transaction path |
| Material behavior | Pass with boundary | Shared Material/Instance source resolves for raster; missing source uses visible fallback; Solari submission is explicitly excluded pending `#24` |
| Project validation | Pass | 60 level dependencies, existing 5 non-blocking findings, 0 blocking errors |
| Packaged acceptance | Deferred | Explicitly deferred by project-owner direction; no packaged result is claimed here |
## Automated Verification
| Command/suite | Result |
|---------------|--------|
| Focused terrain descriptor/topology/hydration tests | 4 passed |
| Editor component registry reflection contract | Pass |
| `cargo check --workspace --all-targets` | Pass |
| `cargo validate-levels --project .` | 60 dependencies, 5 findings, 0 blockers |
@@ -0,0 +1,36 @@
# Terrain Material Layers Acceptance
## Evidence
![Terrain layer paint stroke](terrain-material-paint-stroke.png)
The native Wayland editor is shown with the deterministic terrain showcase selected, two shared
material layers visible in the Inspector, Paint active in the existing horizontal viewport toolbar,
and the cyan terrain-following brush footprint over the blended PBR surface.
## Live Acceptance
- `Concrete` and `Surface Tint` blend continuously across all four generated chunks.
- Layer assignment, clear, reorder, remove, UV tiling, and per-layer sample coverage are visible in
the Terrain card without nesting a second panel.
- Paint and Erase share the existing horizontal toolbar with layer, radius, and strength controls.
- A Paint drag changed layer-two coverage from 13/25 to 16/25 samples and produced exactly one
`Undo: Paint Terrain Material` history entry.
- Ctrl+Z restored 13/25 samples; Ctrl+Y restored 16/25 samples.
- The cyan footprint followed the actual sampled terrain surface and the transform gizmo remained
absent while Paint owned viewport input.
- Forward PBR and the project `blacksite_surface` terrain extension compiled without GPU pipeline
errors. The invalid deferred-only prepass override found during QA was removed from both project
material extensions.
## Automated Coverage
- Terrain layer/weight RON round-trip and structural validation.
- RGBA8 normalization rejection and normalized vertex-color transport.
- Paint/Erase normalization and brush-footprint isolation.
- Multi-dab single-transaction undo/redo.
- Exact restoration of an implicit pre-stroke weight map on cancel.
Packaged build tests remain intentionally skipped per current project direction. Source workspace
format/check/clippy/tests, project validation, navigation bake validation, and diff hygiene are the
required gate for this ticket.
@@ -0,0 +1,31 @@
# Terrain Sculpt Tools Acceptance
Issue: Gitea `#23`
Scope: native Wayland debug editor; packaged acceptance remains deferred by project-owner direction.
## Live Evidence
![Raise stroke with terrain-following footprint and horizontal sculpt controls](terrain-sculpt-raise-stroke.png)
The committed terrain showcase was selected in Forward rendering. Enabling the mountains tool kept
the actor selected, removed the transform gizmo, expanded Raise/Lower/Flatten/Smooth/Noise plus
radius/strength controls inside the existing horizontal viewport toolbar, and displayed the modal
cancel/undo hints. A dragged Raise stroke visibly changed the generated terrain while the footprint
tracked the sampled surface. Release produced exactly `Undo: Raise Terrain`; no transform `Move`
history entry was created.
Escape/right-click restoration, deterministic brush math, exact vertical-ray sampling, multi-dab
stroke grouping, and sculpt-time gizmo exclusion are covered by focused tests. The live pass also
exposed and corrected toolbar click-through into raw mesh picking before this evidence was captured.
## Source Verification
- `cargo fmt --all -- --check`
- `cargo check -p editor --all-targets`
- `cargo clippy -p editor --all-targets -- -D warnings`
- six focused terrain-sculpt/input-ownership tests
- `git diff --check`
The canonical fixture remains `assets/levels/terrain_authoring_showcase.scn.ron`; no QA-only scene or
project setting is retained.
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more