Compare commits

..
Author SHA1 Message Date
Rbanh 7e99243a78 Record deterministic asset acceptance
CI / Format, lint, test, build (push) Waiting to run
2026-07-13 12:09:19 -04:00
Rbanh cbd380a941 Stabilize asset registry publication order 2026-07-13 11:46:51 -04:00
Rbanh e1b2f86a49 Make imported asset fingerprints deterministic 2026-07-13 11:23:06 -04:00
Rbanh a048233fce Record guarded shutdown and scoped UI acceptance
CI / Format, lint, test, build (push) Waiting to run
2026-07-13 10:23:56 -04:00
Rbanh 9e23ae731f Fix scoped editor UI action state 2026-07-13 06:39:30 -04:00
Rbanh 4b33f32357 Guard editor shutdown and track clean savepoints 2026-07-13 05:12:43 -04:00
Rbanh 62b538999d Record sample pack native acceptance
CI / Format, lint, test, build (push) Waiting to run
2026-07-13 04:18:56 -04:00
Rbanh d52cc2e3b7 Fix sample hydration rendering regressions 2026-07-13 03:07:31 -04:00
Rbanh 06010c5922 Add editor sample regression pack 2026-07-13 01:52:58 -04:00
Rbanh c55f34780f Fix live operator UI regressions
CI / Format, lint, test, build (push) Waiting to run
2026-07-13 00:43:10 -04:00
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
Rbanh f2ad88fd03 Define production readiness acceptance gate 2026-07-12 11:29:17 -04:00
Rbanh 5a82a9ee29 Add collaborative authored-file safety 2026-07-12 11:27:57 -04:00
172 changed files with 21522 additions and 1373 deletions

No files matched your search

+1
View File
@@ -7,6 +7,7 @@ rustflags = ["-C", "link-arg=-fuse-ld=mold"]
[alias] [alias]
clean-target = "run -p xtask --bin clean-target --" clean-target = "run -p xtask --bin clean-target --"
validate-levels = "run -p xtask --features validate-levels --bin validate-levels --" validate-levels = "run -p xtask --features validate-levels --bin validate-levels --"
validate-samples = "run -p xtask --features validate-samples --bin validate-samples --"
bake-navigation = "run -p xtask --features validate-levels --bin bake-navigation --" bake-navigation = "run -p xtask --features validate-levels --bin bake-navigation --"
package-project = "run -p xtask --features validate-levels --bin package-project --" package-project = "run -p xtask --features validate-levels --bin package-project --"
upgrade-project = "run -p xtask --features validate-levels --bin upgrade-project --" upgrade-project = "run -p xtask --features validate-levels --bin upgrade-project --"
@@ -21,9 +21,23 @@ performance, soak, regression, and first-hour workflows must pass against a repr
`#43`; M6 implementation is complete. `#43`; M6 implementation is complete.
4. Completed: authoritative content validation `#45` and the validation-gated packaging/Build 4. Completed: authoritative content validation `#45` and the validation-gated packaging/Build
workflow `#44`. workflow `#44`.
5. Completed: audio source/listener/bus authoring and spatial preview passed production acceptance 5. Completed: audio `#47`, animation `#46`, and navigation `#48` passed production acceptance.
in `#47`. Next: animation `#46`, navigation `#48`, source-control safety `#49`, then readiness Source-control safety `#49` has complete implementation and source/headless acceptance; live
gate `#50`. visual acceptance remains before the readiness gate `#50`.
## Implemented Slice - Collaborative Authored-File Safety
- Exact BLAKE3 baselines for scene tabs, staged Material/Material Instance documents, and Project
Settings.
- One guarded atomic publication path for scene save/export, prefab source Apply/history, and
editable materials, including missing-file and immediate pre-rename race protection.
- Non-destructive background Git porcelain scanning with optional off-thread ownership providers;
Git/provider absence is quiet.
- Compact active-scene and selected-asset state plus Reload, metadata comparison, Save As, and
Cancel conflict recovery. No force-overwrite action exists.
- Focused race, read-only, provider-lock, parser, non-repository, modal-render, scene, and material
tests pass. Live debug-editor visual acceptance remains pending for a desktop-capable QA session;
packaged acceptance remains owner-deferred.
## M6 - Reliability, Recovery, And Project Workflow ## M6 - Reliability, Recovery, And Project Workflow
@@ -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.
@@ -0,0 +1,38 @@
# Deterministic Imported-Asset Fingerprints
**Status:** Complete at `cbd380a9413411667a83f74b66c5a2feda5e1af7`; see
[`docs/editor/evaluations/deterministic-asset-fingerprints/`](../../docs/editor/evaluations/deterministic-asset-fingerprints/).
## Scope
Implement Gitea #56 so imported-source identity is content-addressed and editor/validator runs do
not rewrite project artifacts because checkout timestamps or serialization whitespace changed.
## Contract
- Persist one shared fingerprint for imported model, texture, and audio sources: byte length plus a
BLAKE3 digest of the exact source bytes.
- Do not persist or compare source mtimes as semantic identity. Legacy timestamp fields remain
readable but are ignored.
- Static-mesh and animation manifests use the same content identity as the asset registry.
- Preserve stable registry UUIDs across metadata-only drift and uniquely identifiable source moves.
- Before writing a registry or generated manifest, compare the parsed semantic document; preserve
the existing bytes when the result is equivalent.
- Project validators stay read-only and validate both length and digest, including same-size edits.
## Implementation
1. Add the shared fingerprint type and migrate animation/static-mesh contracts.
2. Persist fingerprints for model, texture, and audio registry records and generalize move recovery.
3. Make registry and manifest publication semantic and byte-preserving.
4. Extend static-mesh and registry validation plus focused migration/read-only tests.
5. Update ADRs, asset-pipeline docs, CI clean-worktree assertion, and committed generated artifacts.
## Verification
- Focused editor and scene tests for mtime-only drift, same-size changes, legacy manifests,
byte-preserving equivalent refresh, imported source kinds, and read-only validation.
- Formatting, diff check, clippy, and workspace all-target tests.
- Native editor startup and asset refresh with before/after Git status and source timestamp drift.
- `cargo validate-levels --project .` and `cargo validate-samples --project .`, followed by a clean
worktree assertion. Packaged-runtime tests remain deferred by owner direction.
@@ -0,0 +1,66 @@
# Editor Sample Regression Pack
Date: 2026-07-13
Issue: BS-JD-501 / Gitea #32
Milestone: M5 - Regression, docs, and first-hour UX
## Goal
Ship a deterministic five-scene editor regression pack that is easy to open from the editor and
that fails headless validation when its catalog, authored data, or referenced assets drift. The pack
must cover Brush, Material, Terrain, Physics Placement, and Rendering workflows.
## Decisions
- `assets/samples/editor_samples.ron` is the conventional, versioned pack manifest. This remains a
QA/editor convention and does not extend `ProjectSettings`.
- The manifest is parsed and validated in the `scene` crate. Editor UI and headless tooling consume
that one representation.
- Every entry has a stable ID, label, area, project-relative `.scn.ron` path, summary, and nonempty
operator checks. Manifest order is menu and report order.
- Exactly one entry for each required area is release-gated. Scene paths must remain regular files
inside `assets/levels/`; traversal, absolute paths, symlink escapes, duplicates, and future schemas
are blocking.
- Existing accepted terrain, physics-placement, and rendering fixtures remain canonical entries.
Add dedicated brush and material scenes under `assets/levels/samples/` and strengthen weak visual
anchors in the existing fixtures instead of duplicating them.
- `cargo validate-samples --project .` combines pack-specific structure/feature checks with the
authoritative `validate_project` report. It verifies stable actor IDs, required area components,
authoring-only scene documents, and referenced content.
- Terrain descriptors and their shared material layers become first-class project-validation input.
Actor-owned invalid descriptors or missing material references are blocking findings.
- `File > Open Sample` is backed by a cached project catalog and opens through normal scene-tab I/O.
Invalid or unavailable catalogs produce a disabled, actionable row rather than a panic.
- CI hydrates Git LFS before content validation and runs both validation commands. Packaged-runtime
tests remain deferred by project-owner request.
## Implementation
1. Add the manifest schema, deterministic report, safe path resolver, and sample feature checks to
`scene::sample_pack`, with malformed/missing/duplicate/path-escape fixture tests.
2. Add typed `TerrainDesc` validation and base/layer material dependency collection to authoritative
project validation, including owner-attributed tests.
3. Add the `validate-samples` xtask binary, Cargo alias, JSON mode, stable console summary, and CI
steps. Enable LFS hydration at checkout and verify hydrated objects.
4. Add the five-entry manifest, `brush_blockout.scn.ron`, and `material_lab.scn.ron`. Give every
sample actor a stable `ActorId`; add visible rendering anchors and distinct physics shapes where
the current fixtures are ambiguous.
5. Load the catalog after project startup, render `File > Open Sample` in manifest order, and route a
selected stable ID through scene I/O. Add unknown-entry and deterministic-row tests.
6. Add a no-GPU typed-deserialization test over every manifest scene so unknown Bevy component
registrations fail before native QA.
7. Document pack contracts, per-scene checks, release commands, and the editor workflow. Update ADR
0028, the root README checklist/controls, editor/docs indexes, feature guides, roadmap status,
debt audit, and production-readiness evidence.
8. Run source gates, open all five samples through the native menu, exercise one representative tool
interaction per area, inspect logs, and attach representative native issue images when useful.
## Acceptance
- Five manifest entries cover all required areas and open through `File > Open Sample`.
- Every entry type-deserializes and has stable actor IDs plus its required authored feature.
- `validate-levels` reports terrain material dependencies and has no blocking findings.
- `validate-samples` is deterministic, CI-backed, and exits nonzero for pack or project blockers.
- Native viewport captures are nonblank, correctly framed, and free of missing-reference, hydration,
render, or operator errors.
- Documentation gives contributors a single release-use workflow and explains every sample check.
@@ -0,0 +1,62 @@
# Guarded Shutdown And History Savepoints
Date: 2026-07-13
Issue: BS-PR-709 / Gitea #55
Milestone: M7 - Production Readiness
## Goal
Route every editor-exit surface through one non-blocking dirty-document decision and make scene
dirtiness follow the authored undo timeline. Closing the native window, choosing File > Quit, and
requesting an editor exit programmatically must never silently discard dirty scene tabs.
## Decisions
- The editor disables Bevy's automatic close-and-exit systems and owns primary-window close
requests. A guarded-shutdown resource is the single authority that may emit `AppExit`.
- The final dirty-state recheck and `AppExit` authorization run in a dedicated schedule after
Bevy's `Last`; session clean-marker persistence runs after that finalizer.
- Native window close, File > Quit, and internal editor quit requests enqueue the same shutdown
intent. Repeated requests while confirmation or Save As is pending are coalesced.
- Clean sessions exit immediately. Dirty sessions use the shared `NativeDialogBroker` and a single
Save All / Discard / Cancel decision. Cancel preserves all tabs and live editor state; Discard
exits without rewriting authored files; Save All exits only after every dirty tab is saved.
- Untitled tabs and other asynchronous Save As work keep shutdown pending until their dialog result
is applied on the main thread. Cancellation or any failed write returns the editor to an idle,
dirty, recoverable state and does not emit `AppExit`.
- Each scene tab retains a canonical authored-content checkpoint established only by a successful
load or save. The checkpoint is keyed by stable actor identity, canonical component order, stable
parent identity, and scene composition rather than transient Bevy entity numbers.
- Push marks the active document dirty. Undo and redo serialize the authoritative authored
projection and compare it with that tab's checkpoint, so saving at nonzero history depth,
returning to that point, branching, tab switches, and direct non-history mutations remain exact.
## Implementation
1. Add per-tab canonical clean checkpoints to scene I/O and reconcile `SceneIo::dirty` after push,
undo, redo, save, load, and document switches without persisting Entity-ID-based history stacks.
2. Add focused history tests for undo-to-clean, redo-away-from-clean, save at nonzero depth,
branching before/after the clean point, and tab isolation.
3. Add a guarded-shutdown plugin/resource that intercepts `WindowCloseRequested`, accepts menu and
programmatic requests, coordinates non-blocking confirmation/save completion, and emits the only
final `AppExit` for the full editor.
4. Make Save All report complete, pending, cancelled, or failed explicitly. Resume pending shutdown
after untitled Save As completion and preserve the originating tab plus dirty state on failure.
5. Add File > Quit and route Switch Project's exit half through the same guard without spawning a
replacement process until the dirty-document decision succeeds.
6. Update ADR 0023, native-dialog/session-recovery documentation, editor architecture guidance,
root README controls/checklist, and production-readiness evidence.
7. Run formatting, strict Clippy, workspace tests, and focused headless state-machine tests. Keep
packaged tests deferred by project-owner direction.
8. Launch the exact editor commit under Hyprland. Exercise Cancel, Discard, Save All, clean close,
File > Quit, and the compositor close button; verify the editor remains responsive during native
dialogs, no state is lost on cancel/failure, and no process or warning remains after exit.
## Acceptance
- Native close, File > Quit, and programmatic editor exit share one guarded implementation.
- One or many dirty tabs cannot be lost without explicit Discard; failed or cancelled saves do not
exit and preserve the session.
- Undoing exactly to the saved state clears the dirty marker; redo or a divergent edit restores it.
- Saving at nonzero history depth establishes a new clean point without deleting useful history.
- Headless state-machine tests and exact-commit native Linux QA pass with clean logs.
@@ -0,0 +1,94 @@
# Material Library And Targeted Viewport Drop
Working implementation plan for Gitea issues
[`#16`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/16) and
[`#18`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/18).
The shared Material/Material Instance and stable renderer-slot foundation from `#51` is already
present; this slice completes the production-facing catalog and drag/drop workflow.
## Status
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.
## Resolved Gaps
- 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
1. Add a dockable `Material Library` panel, opened from Window and placed in the existing bottom dock
without adding another permanent toolbar.
2. Present project Materials and Material Instances with search, Material/Instance filter, thumbnail
grid/list modes, base/dependency health, and source-control status.
3. Add a scene-usage section that counts renderer-slot, primitive, and brush-face references and can
select/locate users. Do not revive ambiguous hidden scene-local material clones.
4. Reuse the existing guarded Material/Instance drafts for Apply, Revert, Create Instance, and
texture-parameter editing. Shared-file edits remain explicit; scene assignment changes use
history.
5. Material and Instance cells are first-class drag sources and preserve the current pointer-following
visual identity.
## Targeted Drop Contract
Introduce a frame-updated `ViewportAssetDropTarget` resolved by the existing mesh-picking path:
- A hydrated static/skinned draw maps through `HydratedRendererMaterialBinding` to the authored actor
and exact stable slot ID.
- A primitive maps to its authored actor-level `MaterialDesc`.
- A brush performs authored face intersection and identifies the stable face ID.
- An authored but unsupported target remains a visible invalid target with a specific reason.
- Empty space remains placement-only for placeable assets and invalid for Material/Texture payloads.
Payload matrix:
| Payload | Renderer slot | Primitive | Brush face |
|---------|---------------|-----------|------------|
| Material / Material Instance | Assign exact hit slot; one-slot actors may assign directly | Replace actor material reference/values | Replace the hit face material reference |
| Texture | Reject with guidance to create/edit a Material Instance | Set base-color texture | Set hit-face base-color texture/material binding |
An explicit `Apply All Slots` command remains available from the renderer inspector/library usage
menu; a viewport hit never silently broadens from one slot to all slots.
## Preview, Commit, And Cancel
1. Start a persistent drop-preview session when a supported Material/Texture payload enters the
viewport. Snapshot only the target's affected authored state.
2. Apply a transient visual preview without pushing history or marking the scene dirty.
3. When the pointer changes target, restore the previous snapshot before previewing the new target.
4. On release, restore the transient state first, then commit exactly one typed history/operator
transaction to the identified slot, primitive, or face.
5. On Escape, drag cancellation, leaving the viewport, invalid target, or missing source, restore the
exact snapshot and remove every preview/helper marker.
6. The drag card and target outline name the payload, actor, slot/face, action, and invalid reason.
## Verification
- 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.
@@ -0,0 +1,38 @@
# Production-Readiness Acceptance Gate
Working plan for Gitea issue
[`#50`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/50).
This gate is broader than the M7 feature list: it proves the complete daily authoring, content,
recovery, performance, and release workflow against one exact release-candidate commit.
## Status
Audit in progress. The versioned acceptance matrix exists, but no release candidate is nominated and
the gate is not signed off. Packaged/release testing remains explicitly deferred until the project
owner requests it again.
## Sequence
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. 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.
6. Run the eight-hour soak and measured performance protocol, consolidate limitations by severity
and workaround, and obtain independent first-hour/recovery sign-off.
7. Post the signed Gitea milestone comment linking the exact commit and immutable evidence. Close
`#50` only when every required row passes and no P0 blocker remains.
## Gate Rules
- Feature presence is not acceptance evidence.
- A local dirty worktree is not a release candidate.
- Results from another commit or an old package do not transfer to the candidate.
- Deferred, missing, partial, and implementer-only evidence are not passes.
- Every failure records an owner ticket or a concrete rerun condition.
@@ -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,58 @@
# Source-Control Status And Collaborative File Safety
Working implementation plan for Gitea issue
[`#49`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/49).
This is the final M7 implementation slice before the production-readiness acceptance gate.
## Status
Implementation, focused source tests, full editor tests, strict editor clippy, and headless checks
are complete. Live debug-editor visual acceptance remains pending for a desktop-capable QA session.
Packaged/release acceptance is explicitly deferred until the project owner requests another
packaged pass.
## Outcome
External edits cannot be silently overwritten by the editor, common Git/read-only/ownership states
are visible without dominating the shell, and projects without Git or an ownership provider behave
normally.
## Implementation Sequence
1. Add exact file revisions, comparison metadata, guarded atomic replacement, and deterministic
pre-rename race coverage.
2. Capture baselines for scene tabs, material/material-instance drafts, and Project Settings;
protect prefab source Apply and exact-file undo/redo with the same guard.
3. Add a non-destructive asynchronous Git scanner and optional ownership-provider registry.
4. Add compact active-scene and selected-asset status plus a recovery modal with reload, compare
metadata, save-as, and cancel.
5. Cover missing/present/read-only/external-change races, porcelain parsing, provider absence, and
document-specific conflict recovery with focused source tests.
6. Run format, strict affected-crate clippy, source tests, headless validation, and live debug-editor
QA. Do not run packaged tests until requested by the project owner.
## Acceptance Gates
- A loaded authored file changed by another process is never replaced by Save, Apply to source, or
prefab source history.
- File creation is also conditional: a file that appears after a save-as baseline is captured is
not overwritten.
- Conflict and read-only UI identifies the path and recovery choices without a force-overwrite
escape hatch.
- Active-scene and selected-asset Git status remain compact and explain themselves on hover.
- Git absence, a non-repository project, and an empty provider registry are quiet normal states.
- Git commands are read-only and never alter index, worktree, commits, branches, or locks.
- Provider state can block an authored write without coupling core editor code to a vendor.
- Source tests simulate a writer changing the target immediately before rename and prove the old or
external content survives.
## Deliberate Boundaries
- Generated registries, imports, thumbnails, navigation bakes, recovery snapshots, and packages are
regenerative/system-owned and do not open authored-file recovery UI.
- V1 compares metadata rather than rendering a text diff; external diff-tool integration is future
work.
- V1 observes ownership/locks. Acquiring, releasing, or stealing locks belongs in a provider-specific
follow-up.
- Git status is project-local and advisory. The content revision guard remains authoritative even
when Git is absent or stale.
@@ -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.
+13
View File
@@ -17,6 +17,11 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
lfs: true
- name: Verify Git LFS checkout
run: git lfs fsck
- name: Install Linux dependencies - name: Install Linux dependencies
run: | run: |
@@ -55,6 +60,14 @@ jobs:
- name: Validate level scenes - name: Validate level scenes
run: cargo validate-levels run: cargo validate-levels
- name: Validate editor sample pack
run: cargo validate-samples
- name: Assert validation leaves checkout clean
run: |
git diff --exit-code
test -z "$(git ls-files --others --exclude-standard)"
- name: Clippy launch feature matrix - name: Clippy launch feature matrix
run: cargo clippy -p editor -p game --bins --features dev,hot-reload -- -D warnings run: cargo clippy -p editor -p game --bins --features dev,hot-reload -- -D warnings
+53 -7
View File
@@ -27,6 +27,7 @@ cargo clippy --workspace --all-targets -- -D warnings
cargo clippy -p editor -p game --bins --features dev,hot-reload -- -D warnings cargo clippy -p editor -p game --bins --features dev,hot-reload -- -D warnings
cargo test --workspace cargo test --workspace
cargo validate-levels cargo validate-levels
cargo validate-samples
cargo bake-navigation --project . --check cargo bake-navigation --project . --check
# Validate one artifact without opening a game window # Validate one artifact without opening a game window
cargo run -p game -- --validate-navigation assets/navigation/generated/navigation_showcase_humanoid.nav.ron cargo run -p game -- --validate-navigation assets/navigation/generated/navigation_showcase_humanoid.nav.ron
@@ -56,8 +57,9 @@ cargo run -p editor --bin project_launcher --features dev
``` ```
The installed **Blacksite Editor** desktop entry also exposes **Open Project Browser** from its The installed **Blacksite Editor** desktop entry also exposes **Open Project Browser** from its
desktop action menu. In the editor, **File > Switch Project...** performs a clean shutdown and desktop action menu. In the editor, **File > Switch Project...** uses the guarded Save All / Discard /
opens the same browser; choosing a project starts a fresh editor process with that root. Cancel shutdown path before opening the same browser; choosing a project starts a fresh editor
process with that root.
### Hot reload (gameplay iteration) ### Hot reload (gameplay iteration)
@@ -135,7 +137,7 @@ deep-stale variants.
| Click empty viewport / `Esc` | Deselect | | Click empty viewport / `Esc` | Deselect |
| `Delete` / `Backspace` | Delete selection | | `Delete` / `Backspace` | Delete selection |
| `Ctrl+D` | Duplicate selection | | `Ctrl+D` | Duplicate selection |
| `Ctrl+Z` / `Ctrl+Shift+Z` / `Ctrl+Y` | Undo / redo | | `Ctrl+Z` / `Ctrl+Shift+Z` / `Ctrl+Y` | Undo / redo; returning exactly to the last loaded or saved authored state clears that scene tab's dirty marker |
| `F2` in Hierarchy | Rename selection | | `F2` in Hierarchy | Rename selection |
| `W` / `E` / `R` | Translate / rotate / scale gizmo; multi-selection uses one grouped gizmo and undo step | | `W` / `E` / `R` | Translate / rotate / scale gizmo; multi-selection uses one grouped gizmo and undo step |
| `X` | Toggle world/local gizmo orientation | | `X` | Toggle world/local gizmo orientation |
@@ -144,6 +146,7 @@ deep-stale variants.
| Brush selected: `1` / `2` / `3` / `4` | Vertex / edge / face / clip edit modes | | 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 | | 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) | | 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 | | 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 | | `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 | | Viewport selection/orientation HUD | Identify the primary selection, multi-selection count, overlapping-pick position, camera axes, shading mode, and active render path |
@@ -152,6 +155,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 | | 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 | | 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/` | | 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 | | 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 | | `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 | | `F7` | While paused in Play: advance one sim tick |
@@ -160,11 +166,18 @@ deep-stale variants.
| Drag actor between rows / onto Scene Root (Hierarchy, Manual sort) | Reorder siblings / unparent to the root | | 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 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 | | 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, **Open Sample** for the five-area regression pack, recovery restore/keep-copy/discard when available, Import Assets, Export Selection, Save Selection As Prefab (including linked-root variants), Recent Scenes, Switch Project, and Quit |
| Window close / **File > Quit** | Clean sessions exit immediately; dirty scene tabs use one non-blocking **Save All / Discard / Cancel** decision, and cancel or failed saves keep the editor open |
| 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 | | 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** | | 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 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 | 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 | | 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 | | Edit → Project Settings… | Edit `assets/project.ron` rendering, audio buses, physics, and input |
@@ -261,6 +274,13 @@ Viewport shortcut keys require the pointer to be in the viewport and are suspend
without changing the scene. without changing the scene.
- Runtime-only handles/colliders are not serialized directly, keeping scenes stable and portable. - Runtime-only handles/colliders are not serialized directly, keeping scenes stable and portable.
- Editor-only cameras and helper roots are filtered from selection, hierarchy, and scene save. - Editor-only cameras and helper roots are filtered from selection, hierarchy, and scene save.
- Loaded scenes, prefab source Apply/history, Materials, Material Instances, and Project Settings
retain exact BLAKE3 disk revisions. Save verifies the revision again immediately before atomic
replacement; an external edit, create race, read-only target, or provider lock leaves the
existing file untouched and opens the collaborative recovery dialog. Git status is observational
and optional. See the
[collaborative file-safety guide](docs/editor/collaborative-file-safety.md) and
[ADR 0037](docs/adr/0037-collaborative-authored-file-safety.md).
- **PIE restores player sim only** (transform, velocity, jump state) when you stop Play; authored - **PIE restores player sim only** (transform, velocity, jump state) when you stop Play; authored
`LevelObject` edits made during PIE **remain** in the scene (the level may show as dirty). `LevelObject` edits made during PIE **remain** in the scene (the level may show as dirty).
- Play mode swaps the unified viewport between the player camera (possessed) and editor fly camera - Play mode swaps the unified viewport between the player camera (possessed) and editor fly camera
@@ -323,6 +343,16 @@ identity, project and active-scene paths, dirty flags, aggregate validation coun
state, and the bounded Scene I/O log. It excludes scene and asset contents, environment values, state, and the bounded Scene I/O log. It excludes scene and asset contents, environment values,
host/user identity, credentials, access tokens, and modal tool state. host/user identity, credentials, access tokens, and modal tool state.
### External file changes and read-only assets
The active scene status strip and selected asset header show compact Git/read-only/ownership state
when available. If Save or Apply detects a different disk revision, Blacksite leaves that revision
untouched and opens **Authored File Not Saved**. Use **Compare Metadata** to inspect both revisions,
**Save As** to preserve the editor copy elsewhere, **Reload** to take the disk version, or **Cancel**
to keep the local draft unsaved. Git and ownership providers are optional; the status scanner never
stages, commits, resets, checks out, restores, or discards files. See
[collaborative-file-safety.md](docs/editor/collaborative-file-safety.md).
## Cursor / VSCode Setup ## Cursor / VSCode Setup
The `.vscode/` folder is preconfigured: The `.vscode/` folder is preconfigured:
@@ -346,6 +376,8 @@ The `.vscode/` folder is preconfigured:
- [ADR 0016: Unified Rendering Contract](docs/adr/0016-unified-rendering-contract.md) - [ADR 0016: Unified Rendering Contract](docs/adr/0016-unified-rendering-contract.md)
- [ADR 0017: Normalized Static Mesh Assets](docs/adr/0017-normalized-static-mesh-assets.md) - [ADR 0017: Normalized Static Mesh Assets](docs/adr/0017-normalized-static-mesh-assets.md)
- [ADR 0034: Registry-driven Authoring Components](docs/adr/0034-registry-driven-authoring-components.md) - [ADR 0034: Registry-driven Authoring Components](docs/adr/0034-registry-driven-authoring-components.md)
- [ADR 0037: Collaborative Authored-File Safety](docs/adr/0037-collaborative-authored-file-safety.md)
- [ADR 0043: Content-Addressed Import Fingerprints](docs/adr/0043-content-addressed-import-fingerprints.md)
## Project Layout ## Project Layout
@@ -375,6 +407,14 @@ crates/
- [x] Filtered hierarchy, inspector, viewport, toolbar, asset browser, and status panels - [x] Filtered hierarchy, inspector, viewport, toolbar, asset browser, and status panels
- [x] Delete, duplicate, rename, and structural/material undo-redo - [x] Delete, duplicate, rename, and structural/material undo-redo
- [x] Native Bevy scene New/Open/Save/Save As with dirty title tracking - [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] Guarded native/menu/programmatic editor shutdown with asynchronous multi-tab Save All / Discard / Cancel and canonical per-tab clean checkpoints for exact undo/redo dirtiness ([ADR 0042](docs/adr/0042-guarded-editor-shutdown-and-document-savepoints.md), [Gitea #55](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/55))
- [x] Scoped egui action safety for toolbar/navigation spawns, Inspector state, cross-panel selection/tab requests, diagnostics selection, and full-slice selection precedence ([evaluation](docs/editor/evaluations/scoped-ui-actions/), [Gitea #57](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/57))
- [x] Asset import, static mesh/prefab placement, texture assignment, and selection export - [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] PIE player-only snapshot/restore (authored `LevelObject` edits persist on stop)
- [x] Unified viewport render-to-texture target + Play session bootstrap - [x] Unified viewport render-to-texture target + Play session bootstrap
@@ -383,16 +423,21 @@ crates/
- [x] Cursor/VSCode workspace tasks + launch configs - [x] Cursor/VSCode workspace tasks + launch configs
- [x] Opaque Wayland window launch defaults + SDR/HDR runtime toggle - [x] Opaque Wayland window launch defaults + SDR/HDR runtime toggle
- [x] CI workflow for format, check, clippy, tests, and binary builds - [x] CI workflow for format, check, clippy, tests, and binary builds
- [x] Deterministic five-area editor sample regression pack with stable actor IDs, **File > Open Sample**, typed scene checks, headless validation, and committed brush/material/terrain/physics/rendering fixtures ([sample guide](docs/editor/sample-regression-pack.md), [Gitea #32](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/32))
- [x] ADRs for roadmap architecture and Bevy migration policy - [x] ADRs for roadmap architecture and Bevy migration policy
- [x] Determinism harness: same inputs over same ticks produce the same state summary/hash - [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] 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] Stable asset registry with UUIDs + import settings in asset browser details
- [x] Deterministic imported-source fingerprints for models, textures, and audio; BLAKE3-backed
static/animation manifests; byte-preserving equivalent refresh; and read-only validator checkout
assertions ([ADR 0043](docs/adr/0043-content-addressed-import-fingerprints.md), [evaluation](docs/editor/evaluations/deterministic-asset-fingerprints/), [Gitea #56](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/56))
- [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 - [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
- [x] Audio clip catalog/import foundation for Ogg, WAV, MP3, and FLAC with dedicated filtering, file details, and stable runtime-resolvable asset references - [x] Audio clip catalog/import foundation for Ogg, WAV, MP3, and FLAC with dedicated filtering, file details, and stable runtime-resolvable asset references
- [x] Audio source/listener authoring, non-dirty spatial audition, viewport icons/range gizmos, stable buses, PIE/runtime parity, device diagnostics, and shared release validation ([ADR 0030](docs/adr/0030-audio-authoring-and-bus-schema.md); production acceptance completed in [Gitea #47](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/47)) - [x] Audio source/listener authoring, non-dirty spatial audition, viewport icons/range gizmos, stable buses, PIE/runtime parity, device diagnostics, and shared release validation ([ADR 0030](docs/adr/0030-audio-authoring-and-bus-schema.md); production acceptance completed in [Gitea #47](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/47))
- [x] glTF/GLB skeletal animation manifests, stable controller states, non-dirty preview, PIE/runtime hydration, and exact-signature compatibility validation ([ADR 0031](docs/adr/0031-animation-authoring-runtime-contract.md); production acceptance completed in [Gitea #46](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/46)) - [x] glTF/GLB skeletal animation manifests, stable controller states, non-dirty preview, PIE/runtime hydration, and exact-signature compatibility validation ([ADR 0031](docs/adr/0031-animation-authoring-runtime-contract.md); production acceptance completed in [Gitea #46](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/46))
- [x] Navigation bounds/obstacles/areas/links, persisted validation samples, composed-source resolution, deterministic stale-checked bake artifacts, viewport path preview, headless bake, and shared game/runtime query API ([ADR 0032](docs/adr/0032-versioned-navigation-bake-and-runtime-query.md); [evaluation](docs/editor/evaluations/navigation-authoring/); [Gitea #48](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/48)) - [x] Navigation bounds/obstacles/areas/links, persisted validation samples, composed-source resolution, deterministic stale-checked bake artifacts, viewport path preview, headless bake, and shared game/runtime query API ([ADR 0032](docs/adr/0032-versioned-navigation-bake-and-runtime-query.md); [evaluation](docs/editor/evaluations/navigation-authoring/); [Gitea #48](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/48))
- [x] Exact authored-file revision guards for scenes, prefab source Apply/history, Materials, Material Instances, and Project Settings; compact observational Git/read-only/ownership state; and explicit Reload/Compare Metadata/Save As/Cancel recovery without force overwrite ([ADR 0037](docs/adr/0037-collaborative-authored-file-safety.md), [collaboration guide](docs/editor/collaborative-file-safety.md), [Gitea #49](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/49))
- [x] Prefab instances (`PrefabInstance`) + save-as-prefab + unpack - [x] Prefab instances (`PrefabInstance`) + save-as-prefab + unpack
- [x] Independent dirty-tab close confirmation and all-tab save guard when switching projects - [x] Independent dirty-tab close confirmation and all-tab save guard when switching projects
- [x] Transactional scene writes + bounded user-local recovery snapshots ([ADR 0023](docs/adr/0023-transactional-scene-persistence-and-recovery.md)) - [x] Transactional scene writes + bounded user-local recovery snapshots ([ADR 0023](docs/adr/0023-transactional-scene-persistence-and-recovery.md))
@@ -412,7 +457,8 @@ crates/
- [x] Editor lib/bin split + `EditorPluginGroup`; game EditorPlugin dogfood panel - [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] 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] 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 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] 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)) - [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))
@@ -455,7 +501,7 @@ crates/
**Unpack Layer** preserves nested links; **Convert to Local** recursively removes them. Current **Unpack Layer** preserves nested links; **Convert to Local** recursively removes them. Current
authoring UI coverage and production-acceptance gaps are tracked in authoring UI coverage and production-acceptance gaps are tracked in
[prefab-authoring.md](docs/editor/prefab-authoring.md). [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. - 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, - 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. material graphs, lighting profiles) can be added without changing the scene format foundation.
+526 -386
View File
@@ -1,346 +1,4 @@
[ [
(
id: ("c0a7d10e-53c1-4de0-b0dc-34a66f44ba77"),
path: "assets/audio/editor_audition_tone.ogg",
label: "editor_audition_tone",
kind_tag: "AudioClip",
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: ("fe40db93-181f-4c79-86e6-26bd97464c4b"),
path: "assets/audio/Puzzle Lobby.mp3",
label: "Puzzle Lobby",
kind_tag: "AudioClip",
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: ("31963299-d4c1-45dc-8f67-2f469ca1ad6d"),
path: "assets/post_fx/chromatic_aberration.ron",
label: "chromatic_aberration",
kind_tag: "PostProcessEffect",
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: ("e14a9bc3-9a4e-47b0-901f-b31c004e1836"),
path: "assets/post_fx/vignette.ron",
label: "vignette",
kind_tag: "PostProcessEffect",
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: ("b98ef565-3500-49e7-9935-f685fa9b2594"),
path: "assets/models/painted_wooden_chair_02_2k.fbx",
label: "painted_wooden_chair_02_2k",
kind_tag: "Model",
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: StaticAsset,
hierarchy_mode: SingleActor,
material_policy: SourceMaterials,
static_mesh_manifest_path: Some("assets/meshes/generated/b98ef565-3500-49e7-9935-f685fa9b2594.static_mesh.ron"),
animation_manifest_path: Some("assets/animations/generated/b98ef565-3500-49e7-9935-f685fa9b2594.animation.ron"),
default_animation_clip_id: None,
),
dependencies: [],
),
(
id: ("113f74df-e39c-41d4-9b5b-e48efe541f7f"),
path: "assets/models/RobotExpressive.glb",
label: "RobotExpressive",
kind_tag: "Model",
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: SceneInstance,
hierarchy_mode: SourceHierarchy,
material_policy: SourceMaterials,
static_mesh_manifest_path: Some("assets/meshes/generated/113f74df-e39c-41d4-9b5b-e48efe541f7f.static_mesh.ron"),
animation_manifest_path: Some("assets/animations/generated/113f74df-e39c-41d4-9b5b-e48efe541f7f.animation.ron"),
default_animation_clip_id: Some("animation:clip:8:standing"),
),
dependencies: [],
),
(
id: ("3f63f359-45eb-4cb2-8970-71921cbd7bd0"),
path: "assets/models/robot_expressive.glb",
label: "robot_expressive",
kind_tag: "Model",
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: StaticAsset,
hierarchy_mode: SingleActor,
material_policy: SourceMaterials,
static_mesh_manifest_path: Some("assets/meshes/generated/3f63f359-45eb-4cb2-8970-71921cbd7bd0.static_mesh.ron"),
animation_manifest_path: Some("assets/animations/generated/3f63f359-45eb-4cb2-8970-71921cbd7bd0.animation.ron"),
default_animation_clip_id: Some("animation:clip:8:standing"),
),
dependencies: [],
),
(
id: ("c4abe41c-ac88-4aec-8168-27e8a7c90583"),
path: "assets/textures/metal_stool_01_nor_gl_2k.jpg",
label: "metal_stool_01_nor_gl_2k",
kind_tag: "Texture",
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: ("0496e62e-1837-4940-a9c9-b2b4ffe9ed90"),
path: "assets/textures/metal_stool_01_arm_2k.jpg",
label: "metal_stool_01_arm_2k",
kind_tag: "Texture",
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: ("bddaa4d4-5097-42bf-8d51-dd9a3580442a"),
path: "assets/textures/metal_stool_01_diff_2k.jpg",
label: "metal_stool_01_diff_2k",
kind_tag: "Texture",
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: ("61802b85-fda9-4aff-94d9-fe5f0860c516"),
path: "assets/levels/rendering_showcase.scn.ron",
label: "rendering_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",
label: "navigation_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: ("48bcef13-e6a6-4260-bb1b-c29787bd8c70"),
path: "assets/levels/editor_scene 3.scn.ron",
label: "editor_scene 3.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",
label: "audio_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: ("5a2307d0-48e5-40d3-a5c9-527c0cfd30f4"),
path: "assets/levels/editor_scene.scn.ron",
label: "editor_scene.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",
label: "editor_scene 2.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: ("c14f6240-5654-4e80-9edb-2b4c44cf8d61"),
path: "assets/prefabs/example_variant.scn.ron",
label: "example_variant.scn",
kind_tag: "Prefab",
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: ("682191d6-59cd-46a1-9560-6cf7bc1583b2"),
path: "assets/prefabs/example_nested.scn.ron",
label: "example_nested.scn",
kind_tag: "Prefab",
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: ("862530b2-8111-4ebb-9078-29723c002e08"),
path: "assets/prefabs/example_base.scn.ron",
label: "example_base.scn",
kind_tag: "Prefab",
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: ("04a4e00e-4732-43db-8e99-9cd99b94667b"), id: ("04a4e00e-4732-43db-8e99-9cd99b94667b"),
path: "assets/animations/generated/113f74df-e39c-41d4-9b5b-e48efe541f7f.animation.ron", path: "assets/animations/generated/113f74df-e39c-41d4-9b5b-e48efe541f7f.animation.ron",
@@ -396,10 +54,14 @@
dependencies: [], dependencies: [],
), ),
( (
id: ("802471df-8295-4997-80e2-db4191850fc9"), id: ("fe40db93-181f-4c79-86e6-26bd97464c4b"),
path: "assets/rendering_profiles/outdoor_haze.ron", path: "assets/audio/Puzzle Lobby.mp3",
label: "outdoor_haze", label: "Puzzle Lobby",
kind_tag: "RenderingProfile", kind_tag: "AudioClip",
source_fingerprint: Some((
byte_len: 1680820,
content_hash: "3b5a401dbaccfdbda540c60070ce259fb506d7da548f45008eb2b3fa720b4b57",
)),
import_settings: ( import_settings: (
scale: 1.0, scale: 1.0,
generate_collider: true, generate_collider: true,
@@ -414,10 +76,14 @@
dependencies: [], dependencies: [],
), ),
( (
id: ("2c4a9866-17b5-4797-9a8f-726b2ffacdb9"), id: ("c0a7d10e-53c1-4de0-b0dc-34a66f44ba77"),
path: "assets/rendering_profiles/cave_dark.ron", path: "assets/audio/editor_audition_tone.ogg",
label: "cave_dark", label: "editor_audition_tone",
kind_tag: "RenderingProfile", kind_tag: "AudioClip",
source_fingerprint: Some((
byte_len: 4450,
content_hash: "8ef56184ab5b5cd135e45df152f8a95737023420947f3d08c9b3e3605e55a349",
)),
import_settings: ( import_settings: (
scale: 1.0, scale: 1.0,
generate_collider: true, generate_collider: true,
@@ -432,9 +98,243 @@
dependencies: [], dependencies: [],
), ),
( (
id: ("264e2010-0693-4d74-8440-99373c2cedb3"), id: ("9213efe6-12c7-45a8-8b64-9e1699f76ba3"),
path: "assets/navigation/generated/navigation_showcase_humanoid.nav.ron", path: "assets/build_profiles/development.ron",
label: "navigation_showcase_humanoid.nav", label: "development",
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: ("64fea29e-c123-4987-92dc-ca25f4dc7dea"),
path: "assets/build_profiles/qa.ron",
label: "qa",
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: ("de76f1c9-f05d-48d3-bb69-6b7ce05f29d8"),
path: "assets/build_profiles/release.ron",
label: "release",
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",
label: "audio_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: ("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: ("dc13ce01-c7ce-43c5-974c-0e659ae49ab9"),
path: "assets/levels/editor_scene 2.scn.ron",
label: "editor_scene 2.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: ("48bcef13-e6a6-4260-bb1b-c29787bd8c70"),
path: "assets/levels/editor_scene 3.scn.ron",
label: "editor_scene 3.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: ("5a2307d0-48e5-40d3-a5c9-527c0cfd30f4"),
path: "assets/levels/editor_scene.scn.ron",
label: "editor_scene.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",
label: "navigation_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: ("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: ("61802b85-fda9-4aff-94d9-fe5f0860c516"),
path: "assets/levels/rendering_showcase.scn.ron",
label: "rendering_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: ("bca13177-afa9-4691-9b40-288059c7a57e"),
path: "assets/levels/samples/brush_blockout.scn.ron",
label: "brush_blockout.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: ("607864bf-fa77-4f9e-acc9-2c0906d34163"),
path: "assets/levels/samples/material_lab.scn.ron",
label: "material_lab.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: ("1b25d451-7b54-41d6-af00-d2e6950f502d"),
path: "assets/levels/terrain_authoring_showcase.scn.ron",
label: "terrain_authoring_showcase.scn",
kind_tag: "Level", kind_tag: "Level",
import_settings: ( import_settings: (
scale: 1.0, scale: 1.0,
@@ -467,24 +367,6 @@
), ),
dependencies: [], dependencies: [],
), ),
(
id: ("cc2769da-c9a5-4cb3-866a-cc81d0688ee2"),
path: "assets/materials/surface_tint_instance.ron",
label: "surface_tint_instance",
kind_tag: "Material",
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: ("4f684592-50b1-47e4-888c-8ba537e4c29d"), id: ("4f684592-50b1-47e4-888c-8ba537e4c29d"),
path: "assets/materials/emissive_panel.ron", path: "assets/materials/emissive_panel.ron",
@@ -522,9 +404,93 @@
dependencies: [], dependencies: [],
), ),
( (
id: ("64fea29e-c123-4987-92dc-ca25f4dc7dea"), id: ("cc2769da-c9a5-4cb3-866a-cc81d0688ee2"),
path: "assets/build_profiles/qa.ron", path: "assets/materials/surface_tint_instance.ron",
label: "qa", label: "surface_tint_instance",
kind_tag: "Material",
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: ("113f74df-e39c-41d4-9b5b-e48efe541f7f"),
path: "assets/models/RobotExpressive.glb",
label: "RobotExpressive",
kind_tag: "Model",
source_fingerprint: Some((
byte_len: 463988,
content_hash: "5869cb813e6a6093eda7af2824a9c13a582750e0443e88ce7c991a1f83415521",
)),
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: SceneInstance,
hierarchy_mode: SourceHierarchy,
material_policy: SourceMaterials,
static_mesh_manifest_path: Some("assets/meshes/generated/113f74df-e39c-41d4-9b5b-e48efe541f7f.static_mesh.ron"),
animation_manifest_path: Some("assets/animations/generated/113f74df-e39c-41d4-9b5b-e48efe541f7f.animation.ron"),
default_animation_clip_id: Some("animation:clip:8:standing"),
),
dependencies: [],
),
(
id: ("b98ef565-3500-49e7-9935-f685fa9b2594"),
path: "assets/models/painted_wooden_chair_02_2k.fbx",
label: "painted_wooden_chair_02_2k",
kind_tag: "Model",
source_fingerprint: Some((
byte_len: 59964,
content_hash: "b12973a62dcb44589e380ea833eade726ae98a86c81084c842ee3801866d6a46",
)),
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: StaticAsset,
hierarchy_mode: SingleActor,
material_policy: SourceMaterials,
static_mesh_manifest_path: Some("assets/meshes/generated/b98ef565-3500-49e7-9935-f685fa9b2594.static_mesh.ron"),
animation_manifest_path: Some("assets/animations/generated/b98ef565-3500-49e7-9935-f685fa9b2594.animation.ron"),
default_animation_clip_id: None,
),
dependencies: [],
),
(
id: ("3f63f359-45eb-4cb2-8970-71921cbd7bd0"),
path: "assets/models/robot_expressive.glb",
label: "robot_expressive",
kind_tag: "Model",
source_fingerprint: Some((
byte_len: 463988,
content_hash: "5869cb813e6a6093eda7af2824a9c13a582750e0443e88ce7c991a1f83415521",
)),
import_settings: (
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: StaticAsset,
hierarchy_mode: SingleActor,
material_policy: SourceMaterials,
static_mesh_manifest_path: Some("assets/meshes/generated/3f63f359-45eb-4cb2-8970-71921cbd7bd0.static_mesh.ron"),
animation_manifest_path: Some("assets/animations/generated/3f63f359-45eb-4cb2-8970-71921cbd7bd0.animation.ron"),
default_animation_clip_id: Some("animation:clip:8:standing"),
),
dependencies: [],
),
(
id: ("264e2010-0693-4d74-8440-99373c2cedb3"),
path: "assets/navigation/generated/navigation_showcase_humanoid.nav.ron",
label: "navigation_showcase_humanoid.nav",
kind_tag: "Level", kind_tag: "Level",
import_settings: ( import_settings: (
scale: 1.0, scale: 1.0,
@@ -540,10 +506,10 @@
dependencies: [], dependencies: [],
), ),
( (
id: ("9213efe6-12c7-45a8-8b64-9e1699f76ba3"), id: ("31963299-d4c1-45dc-8f67-2f469ca1ad6d"),
path: "assets/build_profiles/development.ron", path: "assets/post_fx/chromatic_aberration.ron",
label: "development", label: "chromatic_aberration",
kind_tag: "Level", kind_tag: "PostProcessEffect",
import_settings: ( import_settings: (
scale: 1.0, scale: 1.0,
generate_collider: true, generate_collider: true,
@@ -558,10 +524,10 @@
dependencies: [], dependencies: [],
), ),
( (
id: ("de76f1c9-f05d-48d3-bb69-6b7ce05f29d8"), id: ("e14a9bc3-9a4e-47b0-901f-b31c004e1836"),
path: "assets/build_profiles/release.ron", path: "assets/post_fx/vignette.ron",
label: "release", label: "vignette",
kind_tag: "Level", kind_tag: "PostProcessEffect",
import_settings: ( import_settings: (
scale: 1.0, scale: 1.0,
generate_collider: true, generate_collider: true,
@@ -576,10 +542,100 @@
dependencies: [], dependencies: [],
), ),
( (
id: ("7b143cfb-a9e9-45d4-8f01-cfaa66fa9811"), id: ("862530b2-8111-4ebb-9078-29723c002e08"),
path: "assets/shaders/unlit.shader.ron", path: "assets/prefabs/example_base.scn.ron",
label: "unlit.shader", label: "example_base.scn",
kind_tag: "ShaderSchema", kind_tag: "Prefab",
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: ("682191d6-59cd-46a1-9560-6cf7bc1583b2"),
path: "assets/prefabs/example_nested.scn.ron",
label: "example_nested.scn",
kind_tag: "Prefab",
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: ("c14f6240-5654-4e80-9edb-2b4c44cf8d61"),
path: "assets/prefabs/example_variant.scn.ron",
label: "example_variant.scn",
kind_tag: "Prefab",
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: ("2c4a9866-17b5-4797-9a8f-726b2ffacdb9"),
path: "assets/rendering_profiles/cave_dark.ron",
label: "cave_dark",
kind_tag: "RenderingProfile",
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: ("802471df-8295-4997-80e2-db4191850fc9"),
path: "assets/rendering_profiles/outdoor_haze.ron",
label: "outdoor_haze",
kind_tag: "RenderingProfile",
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: ("e42185de-cda2-4a9e-9df0-df67ccd86123"),
path: "assets/samples/editor_samples.ron",
label: "editor_samples",
kind_tag: "Level",
import_settings: ( import_settings: (
scale: 1.0, scale: 1.0,
generate_collider: true, generate_collider: true,
@@ -629,4 +685,88 @@
), ),
dependencies: [], dependencies: [],
), ),
(
id: ("7b143cfb-a9e9-45d4-8f01-cfaa66fa9811"),
path: "assets/shaders/unlit.shader.ron",
label: "unlit.shader",
kind_tag: "ShaderSchema",
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: ("0496e62e-1837-4940-a9c9-b2b4ffe9ed90"),
path: "assets/textures/metal_stool_01_arm_2k.jpg",
label: "metal_stool_01_arm_2k",
kind_tag: "Texture",
source_fingerprint: Some((
byte_len: 3152060,
content_hash: "31b2249ed7b50d3a021312a1e299167897513710ee8ded75c5c5e56aad592e10",
)),
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: ("bddaa4d4-5097-42bf-8d51-dd9a3580442a"),
path: "assets/textures/metal_stool_01_diff_2k.jpg",
label: "metal_stool_01_diff_2k",
kind_tag: "Texture",
source_fingerprint: Some((
byte_len: 2603921,
content_hash: "e0b9dee5b09f1968e7c6ea82eb9a157d303c25d0600913b8b9c809adf50b73c8",
)),
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: ("c4abe41c-ac88-4aec-8168-27e8a7c90583"),
path: "assets/textures/metal_stool_01_nor_gl_2k.jpg",
label: "metal_stool_01_nor_gl_2k",
kind_tag: "Texture",
source_fingerprint: Some((
byte_len: 2779150,
content_hash: "8c0aa4cf4270c9bf7217fba40b2b48878972ee59cff851cb8dfa57a90f4f373b",
)),
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: [],
),
] ]
@@ -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 Cuboid",
"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 Sphere",
"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: Sphere, size: (1.6, 1.6, 1.6)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true,
is_trigger: false,
shape: Sphere(radius: 0.8),
),
}),
4: (components: {
"bevy_ecs::name::Name": "Placement Capsule",
"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: (0.9, 1.8, 0.9)),
"shared::components::RigidBodyDesc": (body: Static),
"shared::components::ColliderDesc": (
enabled: true,
is_trigger: false,
shape: Capsule(radius: 0.45, height: 1.8),
),
}),
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,
),
}),
})
+181 -8
View File
@@ -1,14 +1,160 @@
(schema_version: 4,resources: { (schema_version: 4, resources: {}, entities: {
}, 1: (components: {
entities: { "bevy_ecs::name::Name": "Rendering Lab Floor",
4294968001: (components: { "bevy_transform::components::transform::Transform": (
translation: (1.0, -0.25, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("rendering-showcase-floor"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (0),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Box, size: (38.0, 0.5, 12.0)),
"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: [],
),
}),
2: (components: {
"bevy_ecs::name::Name": "Vignette Anchor",
"bevy_transform::components::transform::Transform": (
translation: (-12.0, 1.2, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("rendering-showcase-vignette-anchor"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (1),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Sphere, size: (2.4, 2.4, 2.4)),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.82, g: 0.18, b: 0.2, a: 1.0),
metallic: 0.08,
roughness: 0.38,
emissive_color: (r: 1.0, g: 0.2, b: 0.2, 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: [],
),
}),
3: (components: {
"bevy_ecs::name::Name": "Fog Anchor",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 1.4, 0.0),
rotation: (0.0, 0.258819, 0.0, 0.9659258),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("rendering-showcase-fog-anchor"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (2),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Box, size: (2.8, 2.8, 2.8)),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.1, g: 0.58, b: 0.72, a: 1.0),
metallic: 0.15,
roughness: 0.35,
emissive_color: (r: 0.1, g: 0.58, b: 0.72, 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: [],
),
}),
4: (components: {
"bevy_ecs::name::Name": "Exposure Anchor",
"bevy_transform::components::transform::Transform": (
translation: (14.0, 1.3, 0.0),
rotation: (0.0, -0.1736482, 0.0, 0.9848078),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("rendering-showcase-exposure-anchor"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (3),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Box, size: (3.0, 2.6, 3.0)),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.92, g: 0.62, b: 0.12, a: 1.0),
metallic: 0.12,
roughness: 0.32,
emissive_color: (r: 1.0, g: 0.65, b: 0.12, 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: [],
),
}),
5: (components: {
"bevy_ecs::name::Name": "Emissive Comparison Panel",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 2.6, -4.8),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("rendering-showcase-emissive-panel"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (4),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Box, size: (26.0, 1.2, 0.25)),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.15, g: 0.22, b: 0.28, a: 1.0),
metallic: 0.0,
roughness: 0.35,
emissive_color: (r: 0.55, g: 0.85, b: 1.0, a: 1.0),
emissive_intensity: 2500.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: Some("assets/materials/emissive_panel.ron"),
parameters: [],
textures: [],
),
}),
6: (components: {
"bevy_ecs::name::Name": "Fog Volume", "bevy_ecs::name::Name": "Fog Volume",
"bevy_transform::components::transform::Transform": ( "bevy_transform::components::transform::Transform": (
translation: (0.0, 2.0, 0.0), translation: (0.0, 2.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0), rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0), scale: (1.0, 1.0, 1.0),
), ),
"shared::components::ActorId": ("rendering-showcase-fog-volume"),
"shared::components::ActorKind": PostProcessVolume, "shared::components::ActorKind": PostProcessVolume,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (5),
"shared::components::LevelObject": (), "shared::components::LevelObject": (),
"shared::components::PostProcessVolumeDesc": ( "shared::components::PostProcessVolumeDesc": (
half_extents: (6.0, 3.0, 6.0), half_extents: (6.0, 3.0, 6.0),
@@ -23,14 +169,17 @@
label: Some("Foggy courtyard"), label: Some("Foggy courtyard"),
), ),
}), }),
4294968002: (components: { 7: (components: {
"bevy_ecs::name::Name": "Dark Exposure Volume", "bevy_ecs::name::Name": "Dark Exposure Volume",
"bevy_transform::components::transform::Transform": ( "bevy_transform::components::transform::Transform": (
translation: (14.0, 2.0, 0.0), translation: (14.0, 2.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0), rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0), scale: (1.0, 1.0, 1.0),
), ),
"shared::components::ActorId": ("rendering-showcase-exposure-volume"),
"shared::components::ActorKind": PostProcessVolume, "shared::components::ActorKind": PostProcessVolume,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (6),
"shared::components::LevelObject": (), "shared::components::LevelObject": (),
"shared::components::PostProcessVolumeDesc": ( "shared::components::PostProcessVolumeDesc": (
half_extents: (4.0, 2.5, 4.0), half_extents: (4.0, 2.5, 4.0),
@@ -45,14 +194,17 @@
label: Some("Cave mouth"), label: Some("Cave mouth"),
), ),
}), }),
4294968003: (components: { 8: (components: {
"bevy_ecs::name::Name": "Vignette FX Volume", "bevy_ecs::name::Name": "Vignette FX Volume",
"bevy_transform::components::transform::Transform": ( "bevy_transform::components::transform::Transform": (
translation: (-12.0, 2.0, 0.0), translation: (-12.0, 2.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0), rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0), scale: (1.0, 1.0, 1.0),
), ),
"shared::components::ActorId": ("rendering-showcase-vignette-volume"),
"shared::components::ActorKind": PostProcessVolume, "shared::components::ActorKind": PostProcessVolume,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (7),
"shared::components::LevelObject": (), "shared::components::LevelObject": (),
"shared::components::PostProcessVolumeDesc": ( "shared::components::PostProcessVolumeDesc": (
half_extents: (5.0, 2.0, 5.0), half_extents: (5.0, 2.0, 5.0),
@@ -64,5 +216,26 @@
label: Some("Vignette demo"), label: Some("Vignette demo"),
), ),
}), }),
}, 9: (components: {
) "bevy_ecs::name::Name": "Rendering Lab Sun",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 10.0, 5.0),
rotation: (-0.3826834, 0.0, 0.0, 0.9238795),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("rendering-showcase-sun"),
"shared::components::ActorKind": Light,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (8),
"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,332 @@
(schema_version: 4, resources: {}, entities: {
1: (components: {
"bevy_ecs::name::Name": "Foundation Brush",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 0.5, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("sample-brush-foundation"),
"shared::components::ActorKind": Brush,
"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.55, g: 0.54, b: 0.52, a: 1.0),
metallic: 0.0,
roughness: 0.85,
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: Some("assets/materials/concrete.ron"),
parameters: [],
textures: [],
),
"shared::components::BrushDesc": (
kind: Additive,
faces: [
(
id: ("face:+x"),
plane: (normal: (1.0, 0.0, 0.0), distance: 5.0),
vertices: [(5.0, -0.5, -4.0), (5.0, 0.5, -4.0), (5.0, 0.5, 4.0), (5.0, -0.5, 4.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-x"),
plane: (normal: (-1.0, 0.0, 0.0), distance: 5.0),
vertices: [(-5.0, -0.5, 4.0), (-5.0, 0.5, 4.0), (-5.0, 0.5, -4.0), (-5.0, -0.5, -4.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:+y"),
plane: (normal: (0.0, 1.0, 0.0), distance: 0.5),
vertices: [(-5.0, 0.5, -4.0), (-5.0, 0.5, 4.0), (5.0, 0.5, 4.0), (5.0, 0.5, -4.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-y"),
plane: (normal: (0.0, -1.0, 0.0), distance: 0.5),
vertices: [(-5.0, -0.5, 4.0), (-5.0, -0.5, -4.0), (5.0, -0.5, -4.0), (5.0, -0.5, 4.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:+z"),
plane: (normal: (0.0, 0.0, 1.0), distance: 4.0),
vertices: [(5.0, -0.5, 4.0), (5.0, 0.5, 4.0), (-5.0, 0.5, 4.0), (-5.0, -0.5, 4.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-z"),
plane: (normal: (0.0, 0.0, -1.0), distance: 4.0),
vertices: [(-5.0, -0.5, -4.0), (-5.0, 0.5, -4.0), (5.0, 0.5, -4.0), (5.0, -0.5, -4.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
],
cast_shadows: true,
receive_shadows: true,
),
}),
2: (components: {
"bevy_ecs::name::Name": "Material Face Tower",
"bevy_transform::components::transform::Transform": (
translation: (-2.5, 3.0, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("sample-brush-material-tower"),
"shared::components::ActorKind": Brush,
"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.55, g: 0.54, b: 0.52, a: 1.0),
metallic: 0.0,
roughness: 0.85,
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: Some("assets/materials/concrete.ron"),
parameters: [],
textures: [],
),
"shared::components::BrushDesc": (
kind: Additive,
faces: [
(
id: ("face:+x"),
plane: (normal: (1.0, 0.0, 0.0), distance: 1.25),
vertices: [(1.25, -2.0, -1.25), (1.25, 2.0, -1.25), (1.25, 2.0, 1.25), (1.25, -2.0, 1.25)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-x"),
plane: (normal: (-1.0, 0.0, 0.0), distance: 1.25),
vertices: [(-1.25, -2.0, 1.25), (-1.25, 2.0, 1.25), (-1.25, 2.0, -1.25), (-1.25, -2.0, -1.25)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:+y"),
plane: (normal: (0.0, 1.0, 0.0), distance: 2.0),
vertices: [(-1.25, 2.0, -1.25), (-1.25, 2.0, 1.25), (1.25, 2.0, 1.25), (1.25, 2.0, -1.25)],
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"),
)),
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-y"),
plane: (normal: (0.0, -1.0, 0.0), distance: 2.0),
vertices: [(-1.25, -2.0, 1.25), (-1.25, -2.0, -1.25), (1.25, -2.0, -1.25), (1.25, -2.0, 1.25)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:+z"),
plane: (normal: (0.0, 0.0, 1.0), distance: 1.25),
vertices: [(1.25, -2.0, 1.25), (1.25, 2.0, 1.25), (-1.25, 2.0, 1.25), (-1.25, -2.0, 1.25)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-z"),
plane: (normal: (0.0, 0.0, -1.0), distance: 1.25),
vertices: [(-1.25, -2.0, -1.25), (-1.25, 2.0, -1.25), (1.25, 2.0, -1.25), (1.25, -2.0, -1.25)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
],
cast_shadows: true,
receive_shadows: true,
),
}),
3: (components: {
"bevy_ecs::name::Name": "Subtractive Marker",
"bevy_transform::components::transform::Transform": (
translation: (2.5, 2.0, 0.0),
rotation: (0.0, 0.258819, 0.0, 0.9659258),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("sample-brush-subtractive-marker"),
"shared::components::ActorKind": Brush,
"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.72, g: 0.14, b: 0.16, a: 1.0),
metallic: 0.05,
roughness: 0.4,
emissive_color: (r: 1.0, g: 0.25, b: 0.2, 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::BrushDesc": (
kind: SubtractiveMarker,
faces: [
(
id: ("face:+x"),
plane: (normal: (1.0, 0.0, 0.0), distance: 1.0),
vertices: [(1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (1.0, 1.0, 1.0), (1.0, -1.0, 1.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-x"),
plane: (normal: (-1.0, 0.0, 0.0), distance: 1.0),
vertices: [(-1.0, -1.0, 1.0), (-1.0, 1.0, 1.0), (-1.0, 1.0, -1.0), (-1.0, -1.0, -1.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:+y"),
plane: (normal: (0.0, 1.0, 0.0), distance: 1.0),
vertices: [(-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, -1.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-y"),
plane: (normal: (0.0, -1.0, 0.0), distance: 1.0),
vertices: [(-1.0, -1.0, 1.0), (-1.0, -1.0, -1.0), (1.0, -1.0, -1.0), (1.0, -1.0, 1.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:+z"),
plane: (normal: (0.0, 0.0, 1.0), distance: 1.0),
vertices: [(1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (-1.0, 1.0, 1.0), (-1.0, -1.0, 1.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
(
id: ("face:-z"),
plane: (normal: (0.0, 0.0, -1.0), distance: 1.0),
vertices: [(-1.0, -1.0, -1.0), (-1.0, 1.0, -1.0), (1.0, 1.0, -1.0), (1.0, -1.0, -1.0)],
material: None,
texture: None,
uv_offset: (0.0, 0.0),
uv_scale: (1.0, 1.0),
uv_rotation: 0.0,
smoothing_group: 0,
),
],
cast_shadows: true,
receive_shadows: true,
),
}),
4: (components: {
"bevy_ecs::name::Name": "Brush Lab 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": ("sample-brush-sun"),
"shared::components::ActorKind": Light,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (3),
"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,
),
}),
})
+189
View File
@@ -0,0 +1,189 @@
(schema_version: 4, resources: {}, entities: {
1: (components: {
"bevy_ecs::name::Name": "Material Lab Floor",
"bevy_transform::components::transform::Transform": (
translation: (0.0, -0.2, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("sample-material-floor"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (0),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Box, size: (14.0, 0.4, 8.0)),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.55, g: 0.54, b: 0.52, a: 1.0),
metallic: 0.0,
roughness: 0.85,
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: Some("assets/materials/concrete.ron"),
parameters: [],
textures: [],
),
}),
2: (components: {
"bevy_ecs::name::Name": "Concrete Reference",
"bevy_transform::components::transform::Transform": (
translation: (-4.0, 1.0, 0.0),
rotation: (0.0, 0.2164396, 0.0, 0.976296),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("sample-material-concrete"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (1),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Box, size: (2.0, 2.0, 2.0)),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.55, g: 0.54, b: 0.52, a: 1.0),
metallic: 0.0,
roughness: 0.85,
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: Some("assets/materials/concrete.ron"),
parameters: [],
textures: [],
),
}),
3: (components: {
"bevy_ecs::name::Name": "Custom Surface Reference",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 1.2, 0.0),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("sample-material-custom-surface"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (2),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Sphere, size: (2.4, 2.4, 2.4)),
"shared::components::MaterialDesc": (
shader: (
kind: Custom,
schema_path: Some("assets/shaders/surface_tint.shader.ron"),
shader_path: Some("assets/shaders/surface_tint.wgsl"),
),
base_color: (r: 0.12, g: 0.42, b: 0.95, a: 1.0),
metallic: 0.15,
roughness: 0.28,
emissive_color: (r: 0.02, g: 0.08, b: 0.25, a: 1.0),
emissive_intensity: 3.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: Some("assets/materials/surface_tint.ron"),
parameters: [
(name: "tint", value: Color((r: 0.12, g: 0.42, b: 0.95, a: 1.0))),
(name: "roughness", value: Float(0.28)),
(name: "metallic", value: Float(0.15)),
(name: "emissive", value: Color((r: 0.02, g: 0.08, b: 0.25, a: 1.0))),
(name: "emissive_intensity", value: Float(3.0)),
],
textures: [],
),
}),
4: (components: {
"bevy_ecs::name::Name": "Material Instance Reference",
"bevy_transform::components::transform::Transform": (
translation: (4.0, 1.0, 0.0),
rotation: (0.0, -0.1305262, 0.0, 0.9914449),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("sample-material-instance"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (3),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Box, size: (2.6, 2.0, 2.6)),
"shared::components::MaterialDesc": (
shader: (
kind: Custom,
schema_path: Some("assets/shaders/surface_tint.shader.ron"),
shader_path: Some("assets/shaders/surface_tint.wgsl"),
),
base_color: (r: 0.12, g: 0.42, b: 0.95, a: 1.0),
metallic: 0.15,
roughness: 0.28,
emissive_color: (r: 0.02, g: 0.08, b: 0.25, a: 1.0),
emissive_intensity: 3.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: Some("assets/materials/surface_tint_instance.ron"),
parameters: [
(name: "tint", value: Color((r: 0.12, g: 0.42, b: 0.95, a: 1.0))),
(name: "roughness", value: Float(0.28)),
(name: "metallic", value: Float(0.15)),
(name: "emissive", value: Color((r: 0.02, g: 0.08, b: 0.25, a: 1.0))),
(name: "emissive_intensity", value: Float(3.0)),
],
textures: [],
),
}),
5: (components: {
"bevy_ecs::name::Name": "Emissive Reference Panel",
"bevy_transform::components::transform::Transform": (
translation: (0.0, 2.3, -3.6),
rotation: (0.0, 0.0, 0.0, 1.0),
scale: (1.0, 1.0, 1.0),
),
"shared::components::ActorId": ("sample-material-emissive-panel"),
"shared::components::ActorKind": StaticMesh,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (4),
"shared::components::LevelObject": (),
"shared::components::Primitive": (shape: Box, size: (9.0, 3.0, 0.25)),
"shared::components::MaterialDesc": (
shader: (kind: StandardLit, schema_path: None, shader_path: None),
base_color: (r: 0.15, g: 0.22, b: 0.28, a: 1.0),
metallic: 0.0,
roughness: 0.35,
emissive_color: (r: 0.55, g: 0.85, b: 1.0, a: 1.0),
emissive_intensity: 2500.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: Some("assets/materials/emissive_panel.ron"),
parameters: [],
textures: [],
),
}),
6: (components: {
"bevy_ecs::name::Name": "Material Lab 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": ("sample-material-sun"),
"shared::components::ActorKind": Light,
"shared::components::EditorVisibility": (visible: true),
"shared::components::HierarchySiblingIndex": (5),
"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,
),
}),
})
@@ -1,5 +1,5 @@
( (
schema_version: 3, schema_version: 4,
asset_id: "113f74df-e39c-41d4-9b5b-e48efe541f7f", asset_id: "113f74df-e39c-41d4-9b5b-e48efe541f7f",
label: "RobotExpressive", label: "RobotExpressive",
source: ( source: (
@@ -7,7 +7,7 @@
format: "glb", format: "glb",
fingerprint: ( fingerprint: (
byte_len: 463988, byte_len: 463988,
modified_unix_secs: 1783799272, content_hash: "5869cb813e6a6093eda7af2824a9c13a582750e0443e88ce7c991a1f83415521",
), ),
dependencies: [], dependencies: [],
), ),
@@ -1,5 +1,5 @@
( (
schema_version: 3, schema_version: 4,
asset_id: "3f63f359-45eb-4cb2-8970-71921cbd7bd0", asset_id: "3f63f359-45eb-4cb2-8970-71921cbd7bd0",
label: "robot_expressive", label: "robot_expressive",
source: ( source: (
@@ -7,7 +7,7 @@
format: "glb", format: "glb",
fingerprint: ( fingerprint: (
byte_len: 463988, byte_len: 463988,
modified_unix_secs: 1783750957, content_hash: "5869cb813e6a6093eda7af2824a9c13a582750e0443e88ce7c991a1f83415521",
), ),
dependencies: [], dependencies: [],
), ),
@@ -1,5 +1,5 @@
( (
schema_version: 3, schema_version: 4,
asset_id: "b98ef565-3500-49e7-9935-f685fa9b2594", asset_id: "b98ef565-3500-49e7-9935-f685fa9b2594",
label: "painted_wooden_chair_02_2k", label: "painted_wooden_chair_02_2k",
source: ( source: (
@@ -7,7 +7,7 @@
format: "fbx", format: "fbx",
fingerprint: ( fingerprint: (
byte_len: 59964, byte_len: 59964,
modified_unix_secs: 1780713434, content_hash: "b12973a62dcb44589e380ea833eade726ae98a86c81084c842ee3801866d6a46",
), ),
dependencies: [], dependencies: [],
), ),
+65
View File
@@ -0,0 +1,65 @@
(
schema_version: 1,
samples: [
(
id: "brush-blockout",
label: "Brush Blockout",
area: Brush,
scene: "assets/levels/samples/brush_blockout.scn.ron",
summary: "Convex additive brushes, a subtractive marker, and a shared face material for brush editing and CSG regression checks.",
checks: [
"valid authored BrushDesc geometry",
"shared brush-face material resolution",
"object, face, clip, and CSG selection targets",
],
),
(
id: "material-lab",
label: "Material Lab",
area: Material,
scene: "assets/levels/samples/material_lab.scn.ron",
summary: "A compact look-development stage for shared materials, material instances, custom surfaces, and emissive output.",
checks: [
"Material and Material Instance dependency resolution",
"standard, custom, and emissive surface hydration",
"primitive material assignment and targeted drops",
],
),
(
id: "terrain-authoring",
label: "Terrain Authoring",
area: Terrain,
scene: "assets/levels/terrain_authoring_showcase.scn.ron",
summary: "A deterministic height grid with shared material layers, normalized paint weights, chunks, and collision.",
checks: [
"TerrainDesc schema and normalized layer weights",
"shared terrain material dependency resolution",
"sculpt, paint, chunk, and collider hydration",
],
),
(
id: "physics-placement",
label: "Physics Placement",
area: PhysicsPlacement,
scene: "assets/levels/physics_placement_showcase.scn.ron",
summary: "Three visually distinct collider cases above a static floor for transactional multi-object settling.",
checks: [
"cuboid, sphere, and capsule collider diversity",
"multi-selection settle and grouped history",
"static floor collision and cancel restoration",
],
),
(
id: "rendering-lab",
label: "Rendering Lab",
area: Rendering,
scene: "assets/levels/rendering_showcase.scn.ron",
summary: "Visible comparison anchors for fog, exposure, rendering profiles, fullscreen effects, and emissive lighting.",
checks: [
"stable post-process volume ownership",
"rendering profile and fullscreen effect dependency resolution",
"visible fog, exposure, vignette, and emissive comparison anchors",
],
),
],
)
+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
}
+347 -14
View File
@@ -6,6 +6,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::fs; use std::fs;
use bevy::material::OpaqueRendererMethod;
use bevy::mesh::MeshVertexBufferLayoutRef; use bevy::mesh::MeshVertexBufferLayoutRef;
use bevy::pbr::{ use bevy::pbr::{
ExtendedMaterial, MaterialExtension, MaterialExtensionKey, MaterialExtensionPipeline, ExtendedMaterial, MaterialExtension, MaterialExtensionKey, MaterialExtensionPipeline,
@@ -17,15 +18,92 @@ use bevy::render::render_resource::{
}; };
use bevy::shader::{Shader, ShaderRef}; use bevy::shader::{Shader, ShaderRef};
use shared::{ use shared::{
asset_server_path, material_from_desc, HydratedRendererMaterialBinding, MaterialAsset, asset_server_path, material_from_desc, HydratedRendererMaterialBinding,
MaterialInstanceAsset, MaterialParameterValue, MaterialRef, ShaderPropertyType, HydratedTerrainMaterialBinding, MaterialAsset, MaterialDesc, MaterialInstanceAsset,
ShaderSchemaAsset, MATERIAL_INSTANCE_SCHEMA_VERSION, MaterialParameterValue, MaterialRef, ShaderPropertyType, ShaderSchemaAsset,
TerrainMaterialLayer, MATERIAL_INSTANCE_SCHEMA_VERSION, TERRAIN_MATERIAL_LAYER_LIMIT,
}; };
pub const SURFACE_ABI_VERSION: u32 = 1; pub const SURFACE_ABI_VERSION: u32 = 1;
pub const SURFACE_PARAMETER_LANES: usize = 16; pub const SURFACE_PARAMETER_LANES: usize = 16;
pub const SURFACE_TEXTURE_SLOTS: usize = 8; pub const SURFACE_TEXTURE_SLOTS: usize = 8;
pub const DEFAULT_SURFACE_SHADER_PATH: &str = "shaders/blacksite_surface.wgsl"; 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)] #[derive(ShaderType, Reflect, Debug, Clone, Copy, PartialEq)]
pub struct SurfaceUniform { pub struct SurfaceUniform {
@@ -121,10 +199,6 @@ impl MaterialExtension for SurfaceExtension {
DEFAULT_SURFACE_SHADER_PATH.into() DEFAULT_SURFACE_SHADER_PATH.into()
} }
fn prepass_fragment_shader() -> ShaderRef {
DEFAULT_SURFACE_SHADER_PATH.into()
}
fn specialize( fn specialize(
_pipeline: &MaterialExtensionPipeline, _pipeline: &MaterialExtensionPipeline,
descriptor: &mut RenderPipelineDescriptor, descriptor: &mut RenderPipelineDescriptor,
@@ -179,10 +253,194 @@ pub struct SurfaceMaterialPlugin;
impl Plugin for SurfaceMaterialPlugin { impl Plugin for SurfaceMaterialPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_plugins(MaterialPlugin::<SurfaceMaterial>::default()) app.add_plugins(MaterialPlugin::<SurfaceMaterial>::default())
.add_plugins(MaterialPlugin::<TerrainLayerMaterial>::default())
.init_resource::<SurfaceMaterialCache>() .init_resource::<SurfaceMaterialCache>()
.init_resource::<TerrainLayerMaterialCache>()
.init_resource::<SurfaceDiagnostics>() .init_resource::<SurfaceDiagnostics>()
.init_resource::<SurfaceEvaluatorRegistry>() .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,
// Terrain is intentionally absent from the Solari acceleration structure until its
// ray-tracing evaluator exists, so keep the layer blend in the raster forward pass.
opaque_render_method: OpaqueRendererMethod::Forward,
..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 +484,8 @@ fn sync_surface_material_bindings(
{ {
commands commands
.entity(entity) .entity(entity)
.remove::<MeshMaterial3d<SurfaceMaterial>>() .try_remove::<MeshMaterial3d<SurfaceMaterial>>()
.insert(MeshMaterial3d(handle)); .try_insert(MeshMaterial3d(handle));
} }
} }
continue; continue;
@@ -297,8 +555,8 @@ fn sync_surface_material_bindings(
{ {
commands commands
.entity(entity) .entity(entity)
.remove::<MeshMaterial3d<SurfaceMaterial>>() .try_remove::<MeshMaterial3d<SurfaceMaterial>>()
.insert(MeshMaterial3d(handle)); .try_insert(MeshMaterial3d(handle));
} }
continue; continue;
} }
@@ -322,8 +580,8 @@ fn sync_surface_material_bindings(
if surface_handle.is_none_or(|current| current.0 != handle) { if surface_handle.is_none_or(|current| current.0 != handle) {
commands commands
.entity(entity) .entity(entity)
.remove::<MeshMaterial3d<StandardMaterial>>() .try_remove::<MeshMaterial3d<StandardMaterial>>()
.insert(MeshMaterial3d(handle)); .try_insert(MeshMaterial3d(handle));
} }
} }
} }
@@ -714,6 +972,21 @@ pub fn compose_surface_shader(evaluator: &str) -> String {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; 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] #[test]
fn rejects_resource_bindings_and_missing_entry() { fn rejects_resource_bindings_and_missing_entry() {
@@ -759,4 +1032,64 @@ mod tests {
assert_eq!(SURFACE_TEXTURE_SLOTS, 8); assert_eq!(SURFACE_TEXTURE_SLOTS, 8);
assert_eq!(std::mem::size_of::<SurfaceUniform>(), 400); 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_eq!(
material.base.opaque_render_method,
OpaqueRendererMethod::Forward
);
assert_ne!(
material.extension.uniform.base_colors[0],
material.extension.uniform.base_colors[1]
);
}
} }
+32 -24
View File
@@ -3,7 +3,6 @@
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::fs; use std::fs;
use std::path::Path; use std::path::Path;
use std::time::UNIX_EPOCH;
use serde::Deserialize; use serde::Deserialize;
use shared::{ use shared::{
@@ -14,6 +13,7 @@ use shared::{
}; };
use crate::asset_db::AssetRecord; use crate::asset_db::AssetRecord;
use crate::assets::fingerprint::write_pretty_ron_if_changed;
pub fn animation_manifest_path(asset_id: &str) -> String { pub fn animation_manifest_path(asset_id: &str) -> String {
format!("{ANIMATION_ARTIFACT_DIR}/{asset_id}.animation.ron") format!("{ANIMATION_ARTIFACT_DIR}/{asset_id}.animation.ron")
@@ -32,15 +32,9 @@ pub fn refresh_animation_artifact(record: &mut AssetRecord) -> Result<AnimationM
record.dependencies.sort(); record.dependencies.sort();
record.dependencies.dedup(); record.dependencies.dedup();
let text = ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()) if write_pretty_ron_if_changed(&path, &manifest)
.map_err(|error| format!("could not serialize animation manifest: {error}"))?; .map_err(|error| format!("could not publish animation manifest {path}: {error}"))?
if let Some(parent) = Path::new(&path).parent() { {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
if fs::read_to_string(&path).ok().as_deref() != Some(text.as_str()) {
fs::write(&path, text)
.map_err(|error| format!("could not write animation manifest {path}: {error}"))?;
bevy::log::info!( bevy::log::info!(
"Animation manifest refreshed: source={} artifact={} skeletons={} clips={} runtime_supported={}", "Animation manifest refreshed: source={} artifact={} skeletons={} clips={} runtime_supported={}",
record.path, record.path,
@@ -63,7 +57,7 @@ pub fn load_animation_manifest(path: &str) -> Result<AnimationManifest, String>
pub fn build_animation_manifest(record: &AssetRecord) -> Result<AnimationManifest, String> { pub fn build_animation_manifest(record: &AssetRecord) -> Result<AnimationManifest, String> {
let bytes = fs::read(&record.path) let bytes = fs::read(&record.path)
.map_err(|error| format!("could not read {}: {error}", record.path))?; .map_err(|error| format!("could not read {}: {error}", record.path))?;
let fingerprint = source_fingerprint(&record.path, &bytes)?; let fingerprint = source_fingerprint(&bytes);
let format = source_format(&record.path)?; let format = source_format(&record.path)?;
match format.as_str() { match format.as_str() {
"gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, &bytes), "gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, &bytes),
@@ -582,19 +576,8 @@ fn fbx_matrix_bytes(matrix: &ufbx::Matrix) -> Vec<u8> {
.collect() .collect()
} }
fn source_fingerprint(path: &str, bytes: &[u8]) -> Result<AnimationSourceFingerprint, String> { fn source_fingerprint(bytes: &[u8]) -> AnimationSourceFingerprint {
let metadata = fs::metadata(path).map_err(|error| format!("could not stat {path}: {error}"))?; AnimationSourceFingerprint::from_bytes(bytes)
let modified_unix_secs = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map(|duration| duration.as_secs())
.unwrap_or_default();
Ok(AnimationSourceFingerprint {
byte_len: metadata.len(),
modified_unix_secs,
content_hash: blake3::hash(bytes).to_hex().to_string(),
})
} }
fn source_format(path: &str) -> Result<String, String> { fn source_format(path: &str) -> Result<String, String> {
@@ -626,6 +609,7 @@ mod tests {
path: path.to_string_lossy().replace('\\', "/"), path: path.to_string_lossy().replace('\\', "/"),
label: "Animated Hero".into(), label: "Animated Hero".into(),
kind_tag: "Model".into(), kind_tag: "Model".into(),
source_fingerprint: None,
import_settings: ImportSettings::default(), import_settings: ImportSettings::default(),
dependencies: Vec::new(), dependencies: Vec::new(),
} }
@@ -754,6 +738,30 @@ mod tests {
fs::remove_dir_all(root).unwrap(); fs::remove_dir_all(root).unwrap();
} }
#[test]
fn legacy_mtime_metadata_does_not_rewrite_equivalent_animation_manifest() {
let root =
std::env::temp_dir().join(format!("blacksite-animation-legacy-{}", Uuid::new_v4()));
let path = write_animated_gltf(&root);
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
let canonical =
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap();
let marker = format!("byte_len: {},", manifest.source.fingerprint.byte_len);
let legacy = canonical.replacen(
&marker,
&format!("{marker}\n modified_unix_secs: 123456,"),
1,
);
assert_ne!(legacy, canonical);
let artifact = root.join("legacy.animation.ron");
fs::write(&artifact, &legacy).unwrap();
assert!(!write_pretty_ron_if_changed(&artifact, &manifest).unwrap());
assert_eq!(fs::read_to_string(&artifact).unwrap(), legacy);
fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn explicit_default_clip_is_stable_and_stale_ids_are_diagnostic() { fn explicit_default_clip_is_stable_and_stale_ids_are_diagnostic() {
let root = let root =
+177 -34
View File
@@ -2,9 +2,12 @@
use bevy::prelude::*; use bevy::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use shared::AssetSourceFingerprint;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use uuid::Uuid; use uuid::Uuid;
use crate::assets::fingerprint::{fingerprint_file, write_pretty_ron_if_changed};
/// Stable asset identity for dependency tracking and prefab references. /// Stable asset identity for dependency tracking and prefab references.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct AssetId(pub Uuid); pub struct AssetId(pub Uuid);
@@ -93,6 +96,8 @@ pub struct AssetRecord {
pub path: String, pub path: String,
pub label: String, pub label: String,
pub kind_tag: String, pub kind_tag: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_fingerprint: Option<AssetSourceFingerprint>,
#[serde(default)] #[serde(default)]
pub import_settings: ImportSettings, pub import_settings: ImportSettings,
#[serde(default)] #[serde(default)]
@@ -122,9 +127,10 @@ fn sync_registry_from_browser(
return; return;
} }
let mut existing: HashMap<String, AssetRecord> = registry let previous_records = std::mem::take(&mut registry.records);
.records let mut existing: HashMap<String, AssetRecord> = previous_records
.drain(..) .iter()
.cloned()
.map(|record| (record.path.clone(), record)) .map(|record| (record.path.clone(), record))
.collect(); .collect();
let current_paths = assets let current_paths = assets
@@ -146,12 +152,30 @@ fn sync_registry_from_browser(
seen_paths.insert(path.clone(), ()); seen_paths.insert(path.clone(), ());
let kind_tag = format!("{:?}", asset.kind); let kind_tag = format!("{:?}", asset.kind);
let source_fingerprint = if imported_source_kind(&kind_tag) {
match fingerprint_file(&path) {
Ok(fingerprint) => Some(fingerprint),
Err(error) => {
warn!("Imported source fingerprint failed for {path}: {error}");
None
}
}
} else {
None
};
let mut record = if let Some(mut prior) = existing.remove(&path).or_else(|| { let mut record = if let Some(mut prior) = existing.remove(&path).or_else(|| {
take_uniquely_moved_model_record(&mut existing, &current_paths, &path, &kind_tag) source_fingerprint.as_ref().and_then(|fingerprint| {
take_uniquely_moved_import_record(
&mut existing,
&current_paths,
&kind_tag,
fingerprint,
)
})
}) { }) {
if prior.path != path { if prior.path != path {
info!( info!(
"Asset registry preserved model identity {} across move {} -> {}", "Asset registry preserved imported source identity {} across move {} -> {}",
prior.id.as_string(), prior.id.as_string(),
prior.path, prior.path,
path path
@@ -159,18 +183,26 @@ fn sync_registry_from_browser(
prior.path = path.clone(); prior.path = path.clone();
} }
prior.label = asset.label.clone(); prior.label = asset.label.clone();
prior.kind_tag = kind_tag; prior.kind_tag = kind_tag.clone();
prior prior
} else { } else {
AssetRecord { AssetRecord {
id: AssetId::new(), id: AssetId::new(),
path: path.clone(), path: path.clone(),
label: asset.label.clone(), label: asset.label.clone(),
kind_tag, kind_tag: kind_tag.clone(),
source_fingerprint: None,
import_settings: ImportSettings::default(), import_settings: ImportSettings::default(),
dependencies: Vec::new(), dependencies: Vec::new(),
} }
}; };
if imported_source_kind(&kind_tag) {
if let Some(source_fingerprint) = source_fingerprint {
record.source_fingerprint = Some(source_fingerprint);
}
} else {
record.source_fingerprint = None;
}
if record.kind_tag == "Model" { if record.kind_tag == "Model" {
if let Err(error) = super::refresh_model_artifacts(&mut record) { if let Err(error) = super::refresh_model_artifacts(&mut record) {
warn!( warn!(
@@ -183,7 +215,8 @@ fn sync_registry_from_browser(
next_records.push(record); next_records.push(record);
} }
let changed = registry.records != next_records; sort_registry_records(&mut next_records);
let changed = previous_records != next_records;
registry.records = next_records; registry.records = next_records;
if changed { if changed {
registry.index_dirty = true; registry.index_dirty = true;
@@ -198,26 +231,32 @@ fn sync_registry_from_browser(
} }
} }
fn take_uniquely_moved_model_record( fn imported_source_kind(kind_tag: &str) -> bool {
matches!(kind_tag, "Model" | "Texture" | "AudioClip")
}
fn sort_registry_records(records: &mut [AssetRecord]) {
records.sort_by(|left, right| left.path.cmp(&right.path));
}
fn take_uniquely_moved_import_record(
existing: &mut HashMap<String, AssetRecord>, existing: &mut HashMap<String, AssetRecord>,
current_paths: &HashSet<String>, current_paths: &HashSet<String>,
new_path: &str,
kind_tag: &str, kind_tag: &str,
fingerprint: &AssetSourceFingerprint,
) -> Option<AssetRecord> { ) -> Option<AssetRecord> {
if kind_tag != "Model" { if !imported_source_kind(kind_tag) {
return None; return None;
} }
let bytes = std::fs::read(new_path).ok()?;
let content_hash = blake3::hash(&bytes).to_hex().to_string();
let candidates = existing let candidates = existing
.iter() .iter()
.filter_map(|(old_path, record)| { .filter_map(|(old_path, record)| {
if current_paths.contains(old_path) || record.kind_tag != "Model" { if current_paths.contains(old_path) || record.kind_tag != kind_tag {
return None; return None;
} }
let manifest_path = record.import_settings.animation_manifest_path.as_deref()?; recorded_source_fingerprint(record)
let manifest = super::animation::load_animation_manifest(manifest_path).ok()?; .is_some_and(|prior| prior == *fingerprint)
(manifest.source.fingerprint.content_hash == content_hash).then(|| old_path.clone()) .then(|| old_path.clone())
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if candidates.len() != 1 { if candidates.len() != 1 {
@@ -226,6 +265,15 @@ fn take_uniquely_moved_model_record(
existing.remove(&candidates[0]) existing.remove(&candidates[0])
} }
fn recorded_source_fingerprint(record: &AssetRecord) -> Option<AssetSourceFingerprint> {
record.source_fingerprint.clone().or_else(|| {
let manifest_path = record.import_settings.animation_manifest_path.as_deref()?;
super::animation::load_animation_manifest(manifest_path)
.ok()
.map(|manifest| manifest.source.fingerprint)
})
}
pub fn find_asset_by_path(registry: &AssetRegistry, path: &str) -> Option<AssetRecord> { pub fn find_asset_by_path(registry: &AssetRegistry, path: &str) -> Option<AssetRecord> {
registry registry
.records .records
@@ -262,11 +310,16 @@ pub fn ensure_asset_record(
if let Some(record) = find_asset_by_path(registry, &path) { if let Some(record) = find_asset_by_path(registry, &path) {
return Ok(record); return Ok(record);
} }
let kind_tag = kind_tag.into();
let source_fingerprint = imported_source_kind(&kind_tag)
.then(|| fingerprint_file(&path).ok())
.flatten();
let record = AssetRecord { let record = AssetRecord {
id: AssetId::new(), id: AssetId::new(),
path, path,
label: label.into(), label: label.into(),
kind_tag: kind_tag.into(), kind_tag,
source_fingerprint,
import_settings: ImportSettings::default(), import_settings: ImportSettings::default(),
dependencies: Vec::new(), dependencies: Vec::new(),
}; };
@@ -292,6 +345,9 @@ pub fn update_import_settings(
else { else {
return false; return false;
}; };
if record.import_settings == settings {
return false;
}
record.import_settings = settings; record.import_settings = settings;
registry.index_dirty = true; registry.index_dirty = true;
true true
@@ -302,13 +358,7 @@ pub fn registry_index_path() -> &'static str {
} }
pub fn save_registry(registry: &AssetRegistry) -> Result<(), String> { pub fn save_registry(registry: &AssetRegistry) -> Result<(), String> {
let path = registry_index_path(); write_pretty_ron_if_changed(registry_index_path(), &registry.records).map(|_| ())
if let Some(parent) = std::path::Path::new(path).parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let text = ron::ser::to_string_pretty(&registry.records, ron::ser::PrettyConfig::default())
.map_err(|e| e.to_string())?;
std::fs::write(path, text).map_err(|e| e.to_string())
} }
pub fn load_registry() -> AssetRegistry { pub fn load_registry() -> AssetRegistry {
@@ -333,6 +383,101 @@ mod tests {
ANIMATION_MANIFEST_SCHEMA_VERSION, ANIMATION_MANIFEST_SCHEMA_VERSION,
}; };
#[test]
fn imported_source_policy_covers_model_texture_and_audio_only() {
for kind in ["Model", "Texture", "AudioClip"] {
assert!(imported_source_kind(kind), "missing imported kind {kind}");
}
for kind in ["Material", "Level", "Prefab", "PostProcessEffect"] {
assert!(
!imported_source_kind(kind),
"authored kind {kind} was hashed"
);
}
}
#[test]
fn registry_publication_order_is_stable_across_discovery_orders() {
let records = [
("assets/textures/z.png", "Texture"),
("assets/audio/a.ogg", "AudioClip"),
("assets/models/m.glb", "Model"),
]
.into_iter()
.map(|(path, kind_tag)| AssetRecord {
id: AssetId::new(),
path: path.into(),
label: path.into(),
kind_tag: kind_tag.into(),
source_fingerprint: None,
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
})
.collect::<Vec<_>>();
let mut forward = records.clone();
let mut reverse = records.into_iter().rev().collect::<Vec<_>>();
sort_registry_records(&mut forward);
sort_registry_records(&mut reverse);
assert_eq!(forward, reverse);
assert_eq!(
forward
.iter()
.map(|record| record.path.as_str())
.collect::<Vec<_>>(),
[
"assets/audio/a.ogg",
"assets/models/m.glb",
"assets/textures/z.png",
]
);
}
#[test]
fn legacy_registry_record_loads_without_forcing_a_new_identity() {
let source = r#"(
id: ("00000000-0000-0000-0000-000000000000"),
path: "assets/textures/legacy.png",
label: "Legacy",
kind_tag: "Texture",
)"#;
let record: AssetRecord = ron::from_str(source).unwrap();
assert_eq!(record.id, AssetId(Uuid::nil()));
assert!(record.source_fingerprint.is_none());
assert_eq!(record.import_settings, ImportSettings::default());
}
#[test]
fn content_match_preserves_every_imported_source_kind_across_move() {
let fingerprint = AssetSourceFingerprint::from_bytes(b"stable imported bytes");
for kind in ["Model", "Texture", "AudioClip"] {
let record = AssetRecord {
id: AssetId::new(),
path: format!("assets/old/{kind}"),
label: kind.into(),
kind_tag: kind.into(),
source_fingerprint: Some(fingerprint.clone()),
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
};
let expected_id = record.id.clone();
let mut existing = HashMap::from([(record.path.clone(), record)]);
let moved = take_uniquely_moved_import_record(
&mut existing,
&HashSet::new(),
kind,
&fingerprint,
)
.expect("unique content identity should preserve the record");
assert_eq!(moved.id, expected_id);
assert!(existing.is_empty());
}
}
fn moved_model_fixture(bytes: &[u8]) -> (std::path::PathBuf, std::path::PathBuf, AssetRecord) { fn moved_model_fixture(bytes: &[u8]) -> (std::path::PathBuf, std::path::PathBuf, AssetRecord) {
let key = Uuid::new_v4(); let key = Uuid::new_v4();
let source_path = std::env::temp_dir().join(format!("blacksite-moved-model-{key}.glb")); let source_path = std::env::temp_dir().join(format!("blacksite-moved-model-{key}.glb"));
@@ -351,7 +496,6 @@ mod tests {
format: "glb".into(), format: "glb".into(),
fingerprint: AnimationSourceFingerprint { fingerprint: AnimationSourceFingerprint {
byte_len: bytes.len() as u64, byte_len: bytes.len() as u64,
modified_unix_secs: 0,
content_hash: blake3::hash(bytes).to_hex().to_string(), content_hash: blake3::hash(bytes).to_hex().to_string(),
}, },
dependencies: Vec::new(), dependencies: Vec::new(),
@@ -371,6 +515,7 @@ mod tests {
path: old_path, path: old_path,
label: "Moved Model".into(), label: "Moved Model".into(),
kind_tag: "Model".into(), kind_tag: "Model".into(),
source_fingerprint: None,
import_settings: ImportSettings { import_settings: ImportSettings {
animation_manifest_path: Some(manifest_path.to_string_lossy().into_owned()), animation_manifest_path: Some(manifest_path.to_string_lossy().into_owned()),
..Default::default() ..Default::default()
@@ -385,12 +530,13 @@ mod tests {
let (source_path, manifest_path, record) = moved_model_fixture(b"stable model bytes"); let (source_path, manifest_path, record) = moved_model_fixture(b"stable model bytes");
let expected_id = record.id.clone(); let expected_id = record.id.clone();
let mut existing = HashMap::from([(record.path.clone(), record)]); let mut existing = HashMap::from([(record.path.clone(), record)]);
let fingerprint = fingerprint_file(&source_path).unwrap();
let moved = take_uniquely_moved_model_record( let moved = take_uniquely_moved_import_record(
&mut existing, &mut existing,
&HashSet::new(), &HashSet::new(),
&source_path.to_string_lossy(),
"Model", "Model",
&fingerprint,
) )
.expect("unique moved model should retain its registry record"); .expect("unique moved model should retain its registry record");
@@ -406,13 +552,10 @@ mod tests {
let old_path = record.path.clone(); let old_path = record.path.clone();
let mut existing = HashMap::from([(old_path.clone(), record)]); let mut existing = HashMap::from([(old_path.clone(), record)]);
let current_paths = HashSet::from([old_path]); let current_paths = HashSet::from([old_path]);
let fingerprint = fingerprint_file(&source_path).unwrap();
let moved = take_uniquely_moved_model_record( let moved =
&mut existing, take_uniquely_moved_import_record(&mut existing, &current_paths, "Model", &fingerprint);
&current_paths,
&source_path.to_string_lossy(),
"Model",
);
assert!(moved.is_none()); assert!(moved.is_none());
assert_eq!(existing.len(), 1); assert_eq!(existing.len(), 1);
+2 -1
View File
@@ -1548,6 +1548,7 @@ mod tests {
path: asset.path.clone().unwrap(), path: asset.path.clone().unwrap(),
label: asset.label.clone(), label: asset.label.clone(),
kind_tag: "AudioClip".into(), kind_tag: "AudioClip".into(),
source_fingerprint: None,
import_settings: Default::default(), import_settings: Default::default(),
dependencies: Vec::new(), dependencies: Vec::new(),
}], }],
@@ -1630,7 +1631,6 @@ mod tests {
format: "glb".into(), format: "glb".into(),
fingerprint: shared::AnimationSourceFingerprint { fingerprint: shared::AnimationSourceFingerprint {
byte_len: 1, byte_len: 1,
modified_unix_secs: 0,
content_hash: "fixture".into(), content_hash: "fixture".into(),
}, },
dependencies: Vec::new(), dependencies: Vec::new(),
@@ -1663,6 +1663,7 @@ mod tests {
path: "assets/models/robot.glb".into(), path: "assets/models/robot.glb".into(),
label: "Robot".into(), label: "Robot".into(),
kind_tag: "Model".into(), kind_tag: "Model".into(),
source_fingerprint: None,
import_settings: crate::asset_db::ImportSettings { import_settings: crate::asset_db::ImportSettings {
animation_manifest_path: Some(manifest_path.to_string_lossy().into_owned()), animation_manifest_path: Some(manifest_path.to_string_lossy().into_owned()),
default_animation_clip_id: Some(clip_id.clone()), default_animation_clip_id: Some(clip_id.clone()),
+114
View File
@@ -0,0 +1,114 @@
use std::fs;
use std::path::Path;
use serde::de::DeserializeOwned;
use serde::Serialize;
use shared::AssetSourceFingerprint;
pub(crate) fn fingerprint_file(path: impl AsRef<Path>) -> Result<AssetSourceFingerprint, String> {
let path = path.as_ref();
let bytes = fs::read(path)
.map_err(|error| format!("could not read imported source {}: {error}", path.display()))?;
Ok(AssetSourceFingerprint::from_bytes(&bytes))
}
/// Writes canonical pretty RON only when the parsed document changes semantically.
///
/// Equivalent existing bytes, including custom formatting and final-newline policy, stay intact.
pub(crate) fn write_pretty_ron_if_changed<T>(
path: impl AsRef<Path>,
value: &T,
) -> Result<bool, String>
where
T: DeserializeOwned + PartialEq + Serialize,
{
let path = path.as_ref();
if fs::read_to_string(path)
.ok()
.and_then(|text| ron::from_str::<T>(&text).ok())
.is_some_and(|existing| existing == *value)
{
return Ok(false);
}
let text = ron::ser::to_string_pretty(value, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize RON: {error}"))?;
if fs::read(path).ok().as_deref() == Some(text.as_bytes()) {
return Ok(false);
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::write(path, text)
.map_err(|error| format!("could not write {}: {error}", path.display()))?;
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
use std::fs::{File, FileTimes};
use std::time::{Duration, SystemTime};
use uuid::Uuid;
#[derive(Debug, Deserialize, PartialEq, Serialize)]
struct Fixture {
count: u32,
label: String,
}
fn fixture_path(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!(
"blacksite-fingerprint-{name}-{}.ron",
Uuid::new_v4()
))
}
#[test]
fn metadata_only_drift_does_not_change_content_identity() {
let path = fixture_path("mtime");
fs::write(&path, b"stable source bytes").unwrap();
let before = fingerprint_file(&path).unwrap();
File::options()
.write(true)
.open(&path)
.unwrap()
.set_times(
FileTimes::new().set_modified(SystemTime::now() + Duration::from_secs(86_400)),
)
.unwrap();
assert_eq!(fingerprint_file(&path).unwrap(), before);
fs::remove_file(path).unwrap();
}
#[test]
fn same_size_byte_change_updates_content_identity() {
let path = fixture_path("same-size");
fs::write(&path, b"source-a").unwrap();
let before = fingerprint_file(&path).unwrap();
fs::write(&path, b"source-b").unwrap();
let after = fingerprint_file(&path).unwrap();
assert_eq!(before.byte_len, after.byte_len);
assert_ne!(before.content_hash, after.content_hash);
fs::remove_file(path).unwrap();
}
#[test]
fn equivalent_ron_preserves_exact_existing_bytes() {
let path = fixture_path("semantic");
let existing = b"( label: \"stable\", count: 7, )\n\n";
fs::write(&path, existing).unwrap();
let value = Fixture {
count: 7,
label: "stable".into(),
};
assert!(!write_pretty_ron_if_changed(&path, &value).unwrap());
assert_eq!(fs::read(&path).unwrap(), existing);
fs::remove_file(path).unwrap();
}
}
+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> { pub fn material_desc_from_asset(catalog_path: &str) -> Result<MaterialDesc, String> {
let asset = load_material_asset(catalog_path)?; shared::load_resolved_material_from_path(catalog_path).map(|(desc, _)| desc)
let mut desc = asset.material;
desc.material_asset_path = Some(catalog_path.to_string());
Ok(desc)
} }
pub fn apply_material_asset_to_selection( pub fn apply_material_asset_to_selection(
@@ -110,7 +107,7 @@ pub fn apply_material_asset_to_selection(
Ok(()) 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 { for part in &mut renderer.slots {
if part.material_slot_id.0.trim().is_empty() { if part.material_slot_id.0.trim().is_empty() {
part.material_slot_id = if part.id.0.trim().is_empty() { part.material_slot_id = if part.id.0.trim().is_empty() {
+3 -2
View File
@@ -3,6 +3,7 @@
pub mod animation; pub mod animation;
pub mod asset_db; pub mod asset_db;
mod catalog; mod catalog;
mod fingerprint;
mod import; mod import;
pub mod materials; pub mod materials;
pub mod operators; pub mod operators;
@@ -13,8 +14,8 @@ pub mod thumbnails;
pub use catalog::*; pub use catalog::*;
pub use thumbnails::{ pub use thumbnails::{
draw_asset_cell_with, gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon, draw_asset_cell_with, gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon,
prefetch_folder_thumbnails, AssetThumbnailCache, ThumbnailCacheSnapshot, ThumbnailState, prefetch_asset_thumbnails, prefetch_folder_thumbnails, AssetThumbnailCache,
ThumbnailStudio, ThumbnailsPlugin, ThumbnailCacheSnapshot, ThumbnailState, ThumbnailStudio, ThumbnailsPlugin,
}; };
/// Refreshes both generated contracts derived from one imported model source. /// Refreshes both generated contracts derived from one imported model source.
+138 -1
View File
@@ -228,7 +228,6 @@ mod tests {
format: "glb".into(), format: "glb".into(),
fingerprint: AnimationSourceFingerprint { fingerprint: AnimationSourceFingerprint {
byte_len: 1, byte_len: 1,
modified_unix_secs: 0,
content_hash: "fixture".into(), content_hash: "fixture".into(),
}, },
dependencies: Vec::new(), dependencies: Vec::new(),
@@ -265,6 +264,7 @@ mod tests {
path: model_path.clone(), path: model_path.clone(),
label: "Operator Fixture".into(), label: "Operator Fixture".into(),
kind_tag: "Model".into(), kind_tag: "Model".into(),
source_fingerprint: None,
import_settings: ImportSettings { import_settings: ImportSettings {
animation_manifest_path: Some(path.to_string_lossy().into_owned()), animation_manifest_path: Some(path.to_string_lossy().into_owned()),
..Default::default() ..Default::default()
@@ -352,6 +352,7 @@ mod tests {
path: path.clone(), path: path.clone(),
label: "Impact".into(), label: "Impact".into(),
kind_tag: "AudioClip".into(), kind_tag: "AudioClip".into(),
source_fingerprint: None,
import_settings: Default::default(), import_settings: Default::default(),
dependencies: Vec::new(), dependencies: Vec::new(),
}], }],
@@ -469,6 +470,87 @@ 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(),
source_fingerprint: None,
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] #[test]
fn missing_subasset_commit_cancels_without_side_effects() { fn missing_subasset_commit_cancels_without_side_effects() {
let mut world = World::new(); let mut world = World::new();
@@ -533,4 +615,59 @@ mod tests {
harness.assert_blocked(&mut world); 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);
}
} }
+94 -4
View File
@@ -22,6 +22,7 @@ use crate::asset_db::{ensure_asset_record, AssetRegistry};
use crate::history::{ use crate::history::{
capture_prefab_edit_state, record_prefab_edit_state, record_prefab_source_apply, capture_prefab_edit_state, record_prefab_edit_state, record_prefab_source_apply,
}; };
use crate::native_dialog::NativeDialogBroker;
use crate::ui::inspector::{ use crate::ui::inspector::{
apply_component_card_response, component_card, component_card_context, property_row, apply_component_card_response, component_card, component_card_context, property_row,
ComponentCardOptions, ComponentCardOptions,
@@ -751,13 +752,44 @@ fn relink_prefab_source(world: &mut World, entity: Entity) {
else { else {
return; return;
}; };
let Some(path) = rfd::FileDialog::new() let directory = project_root.join("assets/prefabs");
.set_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"]) .add_filter("Bevy prefab", &["scn.ron", "ron"])
.pick_file() .pick_file()
else { },
move |world, path| {
let Some(path) = path else {
world
.resource_mut::<crate::scene_io::SceneIo>()
.set_status("Prefab relink cancelled");
return; 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 { let Ok(path) = path.canonicalize() else {
return; return;
}; };
@@ -1248,6 +1280,10 @@ fn apply_prefab_scope_to_source(
return; return;
} }
}; };
let before_snapshot = crate::collaboration::FileSnapshot::from_loaded_bytes(
&source_path,
before_source.as_bytes(),
);
let mut document = match SceneDocument::from_ron_text(&before_source) { let mut document = match SceneDocument::from_ron_text(&before_source) {
Ok(document) => document, Ok(document) => document,
Err(error) => { Err(error) => {
@@ -1361,7 +1397,13 @@ fn apply_prefab_scope_to_source(
} }
let after_source = document.to_ron_text()?; let after_source = document.to_ron_text()?;
scene::validate_prefab_graph_text(&after_source, &source_path, &project_root)?; scene::validate_prefab_graph_text(&after_source, &source_path, &project_root)?;
crate::scene::recovery::atomic_write(&source_path, after_source.as_bytes())?; crate::collaboration::publish_authored_file(
world,
&source_path,
after_source.as_bytes(),
&before_snapshot,
crate::collaboration::FileWriteIntent::PrefabSource { instance_root },
)?;
Ok::<_, String>(after_source) Ok::<_, String>(after_source)
})(); })();
let after_source = match apply_result { let after_source = match apply_result {
@@ -2607,6 +2649,22 @@ fn retry_prefab_source(world: &mut World, entity: Entity) {
"Prefab source queued for reload".into(); "Prefab source queued for reload".into();
} }
pub(crate) fn reload_prefab_source_after_file_conflict(
world: &mut World,
instance_root: Entity,
) -> Result<String, String> {
if world.get::<PrefabInstance>(instance_root).is_none() {
return Err("the prefab instance no longer exists".into());
}
retry_prefab_source(world, instance_root);
let status = world.resource::<crate::scene_io::SceneIo>().status.clone();
if status.starts_with("Prefab retry failed") {
Err(status)
} else {
Ok(status)
}
}
pub fn prefab_member_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) { pub fn prefab_member_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let Some((instance_root, target)) = prefab_member_override_target(world, entity) else { let Some((instance_root, target)) = prefab_member_override_target(world, entity) else {
ui.label(egui::RichText::new("Prefab target unavailable").color(ERROR)); ui.label(egui::RichText::new("Prefab target unavailable").color(ERROR));
@@ -3258,6 +3316,38 @@ mod tests {
assert_eq!(read_overrides(&instance), PrefabOverrides::default()); assert_eq!(read_overrides(&instance), PrefabOverrides::default());
} }
#[test]
fn collaboration_reload_restarts_prefab_hydration_without_dropping_overrides() {
let root = std::env::temp_dir().join(format!(
"blacksite-prefab-collaboration-reload-{}",
uuid::Uuid::new_v4()
));
let source_path = root.join("assets/prefabs/base.scn.ron");
std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
std::fs::write(&source_path, prefab_source("mesh", None)).unwrap();
let mut world = prefab_test_world(&root);
let mut instance = PrefabInstance::new("base", "assets/prefabs/base.scn.ron");
instance.overrides_ron = encode_prefab_overrides(&PrefabOverrides {
source_revision: Some("previous".into()),
..Default::default()
})
.unwrap();
let instance_root = world.spawn((instance.clone(), HydratedPrefabReady)).id();
let status = reload_prefab_source_after_file_conflict(&mut world, instance_root).unwrap();
assert_eq!(status, "Prefab source queued for reload");
assert_eq!(
world
.get::<PrefabInstance>(instance_root)
.map(|current| &current.overrides_ron),
Some(&instance.overrides_ron)
);
assert!(world.get::<HydratedPrefabReady>(instance_root).is_none());
assert!(world.get::<PrefabRef>(instance_root).is_some());
std::fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn nested_unpack_fold_is_transactional_when_a_later_link_is_invalid() { fn nested_unpack_fold_is_transactional_when_a_later_link_is_invalid() {
let mut world = World::new(); let mut world = World::new();
+61 -35
View File
@@ -2,7 +2,6 @@
use std::fs; use std::fs;
use std::path::Path; use std::path::Path;
use std::time::UNIX_EPOCH;
use bevy::gltf::GltfAssetLabel; use bevy::gltf::GltfAssetLabel;
use bevy::prelude::*; use bevy::prelude::*;
@@ -15,11 +14,13 @@ use crate::asset_db::{
AssetRecord, ImportSettings, MaterialImportPolicy, ModelHierarchyMode, ModelPlacementMode, AssetRecord, ImportSettings, MaterialImportPolicy, ModelHierarchyMode, ModelPlacementMode,
}; };
use shared::{ use shared::{
ComponentInstanceId, EditorAssetRef, MaterialRef, RendererMaterialSet, RendererMaterialSlot, AssetSourceFingerprint, ComponentInstanceId, EditorAssetRef, MaterialRef, RendererMaterialSet,
StaticMeshRenderer, StaticMeshRendererEntry, RendererMaterialSlot, StaticMeshRenderer, StaticMeshRendererEntry,
}; };
pub const STATIC_MESH_MANIFEST_SCHEMA: u32 = 3; use crate::assets::fingerprint::{fingerprint_file, write_pretty_ron_if_changed};
pub const STATIC_MESH_MANIFEST_SCHEMA: u32 = 4;
pub const STATIC_MESH_ARTIFACT_DIR: &str = "assets/meshes/generated"; pub const STATIC_MESH_ARTIFACT_DIR: &str = "assets/meshes/generated";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -42,11 +43,7 @@ pub struct StaticMeshSource {
pub dependencies: Vec<String>, pub dependencies: Vec<String>,
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub type StaticMeshSourceFingerprint = AssetSourceFingerprint;
pub struct StaticMeshSourceFingerprint {
pub byte_len: u64,
pub modified_unix_secs: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshImportSnapshot { pub struct StaticMeshImportSnapshot {
@@ -134,16 +131,9 @@ pub fn refresh_static_mesh_artifact(
manifest.source.dependencies.dedup(); manifest.source.dependencies.dedup();
record.dependencies = manifest.source.dependencies.clone(); record.dependencies = manifest.source.dependencies.clone();
let text = ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()) if write_pretty_ron_if_changed(&path, &manifest)
.map_err(|err| format!("could not serialize static mesh manifest: {err}"))?; .map_err(|error| format!("could not publish static mesh manifest {path}: {error}"))?
if let Some(parent) = Path::new(&path).parent() { {
fs::create_dir_all(parent)
.map_err(|err| format!("could not create {}: {err}", parent.display()))?;
}
let should_write = fs::read_to_string(&path).ok().as_deref() != Some(text.as_str());
if should_write {
fs::write(&path, text)
.map_err(|err| format!("could not write static mesh manifest {path}: {err}"))?;
info!( info!(
"Static mesh manifest refreshed: source={} artifact={} parts={}", "Static mesh manifest refreshed: source={} artifact={} parts={}",
record.path, record.path,
@@ -287,7 +277,7 @@ fn part_effective_material_id(part: &StaticMeshPart) -> Option<String> {
fn build_static_mesh_manifest(record: &AssetRecord) -> Result<StaticMeshManifest, String> { fn build_static_mesh_manifest(record: &AssetRecord) -> Result<StaticMeshManifest, String> {
let format = source_format(&record.path)?; let format = source_format(&record.path)?;
let fingerprint = source_fingerprint(&record.path)?; let fingerprint = fingerprint_file(&record.path)?;
let import = StaticMeshImportSnapshot { let import = StaticMeshImportSnapshot {
scale: record.import_settings.scale, scale: record.import_settings.scale,
generate_collider: record.import_settings.generate_collider, generate_collider: record.import_settings.generate_collider,
@@ -631,20 +621,6 @@ fn source_format(path: &str) -> Result<String, String> {
.ok_or_else(|| format!("asset path `{path}` has no extension")) .ok_or_else(|| format!("asset path `{path}` has no extension"))
} }
fn source_fingerprint(path: &str) -> Result<StaticMeshSourceFingerprint, String> {
let metadata = fs::metadata(path).map_err(|err| format!("could not stat {path}: {err}"))?;
let modified_unix_secs = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map(|duration| duration.as_secs())
.unwrap_or_default();
Ok(StaticMeshSourceFingerprint {
byte_len: metadata.len(),
modified_unix_secs,
})
}
fn resolve_dependency(source_path: &str, uri: &str) -> String { fn resolve_dependency(source_path: &str, uri: &str) -> String {
if uri.starts_with("data:") || uri.contains("://") { if uri.starts_with("data:") || uri.contains("://") {
return uri.to_string(); return uri.to_string();
@@ -672,7 +648,7 @@ mod tests {
format: "glb".into(), format: "glb".into(),
fingerprint: StaticMeshSourceFingerprint { fingerprint: StaticMeshSourceFingerprint {
byte_len: 42, byte_len: 42,
modified_unix_secs: 10, content_hash: "a".repeat(64),
}, },
dependencies: Vec::new(), dependencies: Vec::new(),
}, },
@@ -741,6 +717,55 @@ mod tests {
); );
} }
#[test]
fn schema_v3_manifest_without_hash_migrates_to_content_fingerprint() {
let root = std::env::temp_dir().join(format!(
"blacksite-static-mesh-legacy-{}",
uuid::Uuid::new_v4()
));
fs::create_dir_all(&root).unwrap();
let path = root.join("legacy.static_mesh.ron");
let expected = test_manifest();
let canonical =
ron::ser::to_string_pretty(&expected, ron::ser::PrettyConfig::default()).unwrap();
let legacy = canonical
.replacen("schema_version: 4", "schema_version: 3", 1)
.lines()
.filter(|line| !line.contains("content_hash:"))
.collect::<Vec<_>>()
.join("\n");
fs::write(&path, legacy).unwrap();
assert!(write_pretty_ron_if_changed(&path, &expected).unwrap());
assert_eq!(
load_static_mesh_manifest(&path.to_string_lossy()).unwrap(),
expected
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn equivalent_static_manifest_preserves_existing_formatting_and_newline() {
let root = std::env::temp_dir().join(format!(
"blacksite-static-mesh-semantic-{}",
uuid::Uuid::new_v4()
));
fs::create_dir_all(&root).unwrap();
let path = root.join("stable.static_mesh.ron");
let manifest = test_manifest();
let exact = format!(
"{}\n\n",
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap()
);
fs::write(&path, &exact).unwrap();
assert!(!write_pretty_ron_if_changed(&path, &manifest).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), exact);
fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn renderer_from_manifest_can_ignore_source_materials() { fn renderer_from_manifest_can_ignore_source_materials() {
let manifest = test_manifest(); let manifest = test_manifest();
@@ -785,6 +810,7 @@ mod tests {
path, path,
label: "Robot Expressive".into(), label: "Robot Expressive".into(),
kind_tag: "Model".into(), kind_tag: "Model".into(),
source_fingerprint: None,
import_settings: ImportSettings::default(), import_settings: ImportSettings::default(),
dependencies: Vec::new(), dependencies: Vec::new(),
}; };
+41 -4
View File
@@ -188,18 +188,24 @@ impl AssetThumbnailCache {
{ {
return; return;
} }
let material = match shared::MaterialAsset::load_from_path(&path) { let material = match shared::load_resolved_material_from_path(&path) {
Ok(asset) => asset, Ok((material, _)) => material,
Err(error) => { Err(error) => {
self.mark_studio_failed(&key, &error, true); self.mark_studio_failed(&key, &error, true);
return; 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( if studio.enqueue_source(
key.clone(), key.clone(),
ThumbnailJobSource::MaterialAsset { ThumbnailJobSource::MaterialAsset {
label: material.label.clone(), label,
material: Box::new(material.material), material: Box::new(material),
}, },
) { ) {
self.studio_pending.insert(key); 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()); .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) { pub fn invalidate_on_catalog_refresh(world: &mut World) {
world.resource_mut::<AssetThumbnailCache>().invalidate_all(); world.resource_mut::<AssetThumbnailCache>().invalidate_all();
if !world.contains_resource::<ThumbnailStudio>() { if !world.contains_resource::<ThumbnailStudio>() {
+3 -2
View File
@@ -8,8 +8,9 @@ mod sources;
mod studio; mod studio;
pub use cache::{ pub use cache::{
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_folder_thumbnails, draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_asset_thumbnails,
AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot, ThumbnailState, prefetch_folder_thumbnails, AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot,
ThumbnailState,
}; };
pub use job::{ThumbnailJob, ThumbnailJobSource}; pub use job::{ThumbnailJob, ThumbnailJobSource};
pub use sources::{ pub use sources::{
+340 -41
View File
@@ -4,7 +4,7 @@ use bevy::prelude::*;
use bevy_egui::{egui, EguiContexts, EguiPrimaryContextPass}; use bevy_egui::{egui, EguiContexts, EguiPrimaryContextPass};
use crate::history::group_selection_with_history; 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::state::{EditorMode, PlayPossession};
use crate::ui::helpers::{ use crate::ui::helpers::{
reset_scene_lighting_to_project_defaults, toggle_play_mode, toggle_play_paused, 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> { fn disabled_reason(&self, _world: &World) -> Option<String> {
None None
} }
fn execute(&self, world: &mut World); fn execute(&self, world: &mut World) -> Result<OperatorAction, String>;
} }
#[derive(Resource, Default)] #[derive(Resource, Default)]
@@ -70,17 +70,20 @@ impl EditorCommandRegistry {
.map(|cmd| (cmd.label().to_string(), cmd.disabled_reason(world))) .map(|cmd| (cmd.label().to_string(), cmd.disabled_reason(world)))
} }
pub fn run(&self, world: &mut World, name: &str) -> bool { pub fn run(&self, world: &mut World, name: &str) -> Option<Result<OperatorAction, String>> {
if let Some(command) = self.commands.iter().find(|cmd| cmd.name() == name) { self.commands
command.execute(world); .iter()
true .find(|command| command.name() == name)
} else { .map(|command| command.execute(world))
false
}
} }
} }
/// Custom inspector body for level objects (game crates register via [`register_actor_inspector_section`]). /// Custom inspector body for level objects (game crates register via
/// [`register_actor_inspector_section`]). Synchronous [`Self::ui`] callbacks run while
/// [`UiState`] is scoped out of `World`; implementations must not request that resource. Keep
/// extension-owned transient state in independently registered resources, use
/// [`crate::ui::request_ui_selection`] and [`crate::ui::request_editor_tab`] for host UI changes,
/// or defer other cross-panel work through extension-owned commands or events.
pub trait ActorInspectorSection: Send + Sync { pub trait ActorInspectorSection: Send + Sync {
fn id(&self) -> &str; fn id(&self) -> &str;
fn title(&self) -> &str; fn title(&self) -> &str;
@@ -191,6 +194,10 @@ pub fn register_editor_plugin(app: &mut App, plugin: Box<dyn EditorPlugin>) {
} }
fn register_builtin_commands(mut registry: ResMut<EditorCommandRegistry>) { 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(TogglePlayCommand));
registry.register(Box::new(TogglePlayPausedCommand)); registry.register(Box::new(TogglePlayPausedCommand));
registry.register(Box::new(TogglePossessionCommand)); registry.register(Box::new(TogglePossessionCommand));
@@ -235,7 +242,7 @@ fn dispatch_editor_command(world: &mut World, name: &str) {
let name_for_commit = name.to_string(); let name_for_commit = name.to_string();
let name_for_status = name.to_string(); let name_for_status = name.to_string();
let label_for_commit = label.clone(); let label_for_commit = label.clone();
run_immediate_operator( run_operator_action(
world, world,
&name_for_status, &name_for_status,
&label, &label,
@@ -244,14 +251,10 @@ fn dispatch_editor_command(world: &mut World, name: &str) {
None => OperatorAvailability::Ready, None => OperatorAvailability::Ready,
}, },
move |world| { 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) registry.run(world, &name_for_commit)
}); });
if ran { result.unwrap_or_else(|| Err(format!("Unknown editor command: {name_for_commit}")))
Ok(())
} else {
Err(format!("Unknown editor command: {name_for_commit}"))
}
}, },
); );
@@ -269,8 +272,9 @@ impl EditorCommand for TogglePlayCommand {
"Toggle Play / Edit" "Toggle Play / Edit"
} }
fn execute(&self, world: &mut World) { fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
toggle_play_mode(world); toggle_play_mode(world);
Ok(OperatorAction::Commit)
} }
} }
@@ -290,8 +294,9 @@ impl EditorCommand for TogglePlayPausedCommand {
.then(|| "Enter Play mode before pausing the simulation".to_string()) .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); toggle_play_paused(world);
Ok(OperatorAction::Commit)
} }
} }
@@ -311,12 +316,13 @@ impl EditorCommand for TogglePossessionCommand {
.then(|| "Enter Play mode before toggling possession".to_string()) .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>() { let next = match *world.resource::<PlayPossession>() {
PlayPossession::Possessed => PlayPossession::Ejected, PlayPossession::Possessed => PlayPossession::Ejected,
PlayPossession::Ejected => PlayPossession::Possessed, PlayPossession::Ejected => PlayPossession::Possessed,
}; };
*world.resource_mut::<PlayPossession>() = next; *world.resource_mut::<PlayPossession>() = next;
Ok(OperatorAction::Commit)
} }
} }
@@ -331,8 +337,9 @@ impl EditorCommand for ResetLightingCommand {
"Reset Scene Lighting" "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); reset_scene_lighting_to_project_defaults(world);
Ok(OperatorAction::Commit)
} }
} }
@@ -347,13 +354,23 @@ impl EditorCommand for GroupSelectionCommand {
"Group Selection" "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 let selected: Vec<Entity> = world
.resource::<UiState>() .resource::<UiState>()
.selected_entities .selected_entities
.iter() .iter()
.collect(); .collect();
group_selection_with_history(world, &selected); group_selection_with_history(world, &selected);
Ok(OperatorAction::Commit)
} }
} }
@@ -368,8 +385,9 @@ impl EditorCommand for FocusSelectionCommand {
"Focus Selection" "Focus Selection"
} }
fn execute(&self, world: &mut World) { fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
focus_editor_camera_on_selection(world); focus_editor_camera_on_selection(world);
Ok(OperatorAction::Commit)
} }
} }
@@ -384,8 +402,9 @@ impl EditorCommand for ResetSelectionTransformCommand {
"Reset Selection Transform" "Reset Selection Transform"
} }
fn execute(&self, world: &mut World) { fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
reset_selected_transforms(world); reset_selected_transforms(world);
Ok(OperatorAction::Commit)
} }
} }
@@ -405,8 +424,9 @@ impl EditorCommand for DrawBrushCommand {
.then(|| "Enter Edit mode before drawing brushes".to_string()) .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); start_draw_brush_tool(world);
Ok(OperatorAction::ContinuePreview)
} }
} }
@@ -425,8 +445,9 @@ impl EditorCommand for IntersectBrushesCommand {
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string()) (selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
} }
fn execute(&self, world: &mut World) { fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
intersect_selected_brushes(world); intersect_selected_brushes(world)?;
Ok(OperatorAction::ContinuePreview)
} }
} }
@@ -445,8 +466,9 @@ impl EditorCommand for MergeBrushesCommand {
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string()) (selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
} }
fn execute(&self, world: &mut World) { fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
merge_selected_brushes(world); merge_selected_brushes(world)?;
Ok(OperatorAction::ContinuePreview)
} }
} }
@@ -465,8 +487,9 @@ impl EditorCommand for SubtractBrushesCommand {
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string()) (selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
} }
fn execute(&self, world: &mut World) { fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
subtract_selected_brushes(world); subtract_selected_brushes(world)?;
Ok(OperatorAction::ContinuePreview)
} }
} }
@@ -481,8 +504,9 @@ impl EditorCommand for CreatePostProcessVolumeCommand {
"Create Post-process Volume" "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); crate::rendering_diagnostics::spawn_post_process_volume_at_camera(world);
Ok(OperatorAction::Commit)
} }
} }
@@ -497,9 +521,10 @@ impl EditorCommand for FocusActiveVolumesCommand {
"Focus Active Post-process Volumes" "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); crate::rendering_diagnostics::select_volumes_at_camera(world);
focus_editor_camera_on_selection(world); focus_editor_camera_on_selection(world);
Ok(OperatorAction::Commit)
} }
} }
@@ -514,8 +539,9 @@ impl EditorCommand for SelectVolumesAtCameraCommand {
"Select Volumes at Camera" "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); crate::rendering_diagnostics::select_volumes_at_camera(world);
Ok(OperatorAction::Commit)
} }
} }
@@ -542,6 +568,7 @@ fn command_palette_ui(
} }
let mut open = palette.open; let mut open = palette.open;
let mut dismiss_requested = false;
let palette_width = (ctx.content_rect().width() - 32.0).clamp(320.0, 520.0); let palette_width = (ctx.content_rect().width() - 32.0).clamp(320.0, 520.0);
egui::Window::new("Command Palette") egui::Window::new("Command Palette")
.open(&mut open) .open(&mut open)
@@ -590,13 +617,11 @@ fn command_palette_ui(
if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
if let Some(entry) = filtered_entries.get(palette.selected_index) { if let Some(entry) = filtered_entries.get(palette.selected_index) {
palette.pending_run = Some(entry.name.clone()); palette.pending_run = Some(entry.name.clone());
palette.open = false; dismiss_requested = true;
ui.close();
} }
} }
if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
palette.open = false; dismiss_requested = true;
ui.close();
} }
ui.separator(); ui.separator();
@@ -618,17 +643,20 @@ fn command_palette_ui(
if response.clicked() { if response.clicked() {
palette.selected_index = index; palette.selected_index = index;
palette.pending_run = Some(entry.name.clone()); palette.pending_run = Some(entry.name.clone());
palette.open = false; dismiss_requested = true;
ui.close();
} }
} }
}); });
}); });
palette.open = open; palette.open = resolve_palette_open(open, dismiss_requested);
Ok(()) Ok(())
} }
fn resolve_palette_open(window_open: bool, dismiss_requested: bool) -> bool {
window_open && !dismiss_requested
}
fn filtered_command_entries( fn filtered_command_entries(
registry: &EditorCommandRegistry, registry: &EditorCommandRegistry,
filter: &str, filter: &str,
@@ -671,6 +699,53 @@ fn command_palette_row(entry: &EditorCommandEntry) -> egui::WidgetText {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; 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] #[test]
fn command_filter_matches_human_label_and_stable_id() { fn command_filter_matches_human_label_and_stable_id() {
@@ -697,4 +772,228 @@ mod tests {
assert_eq!(entries[0].name, "play.toggle"); assert_eq!(entries[0].name, "play.toggle");
assert_eq!(entries[1].name, "scene.reset_lighting"); assert_eq!(entries[1].name, "scene.reset_lighting");
} }
#[test]
fn command_palette_dismissal_wins_over_stale_window_open_state() {
assert!(!resolve_palette_open(true, true));
assert!(!resolve_palette_open(false, false));
assert!(resolve_palette_open(true, false));
}
#[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")));
assert_group_has_visibility_hierarchy(&mut world);
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_group_has_visibility_hierarchy(&mut world);
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());
}
fn assert_group_has_visibility_hierarchy(world: &mut World) {
let group = world
.query::<(Entity, &Name)>()
.iter(world)
.find_map(|(entity, name)| (name.as_str() == "Group").then_some(entity))
.expect("group command should spawn the group actor");
assert!(world.get::<Visibility>(group).is_some());
assert!(world.get::<InheritedVisibility>(group).is_some());
assert!(world.get::<ViewVisibility>(group).is_some());
}
#[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)] #[derive(Debug, Clone)]
pub enum EditorCommand { pub enum EditorCommand {
GroupSelection {
snapshot: EditorEntitySnapshot,
group: Option<Entity>,
changes: Vec<SiblingChange>,
},
Spawn { Spawn {
snapshot: EditorEntitySnapshot, snapshot: EditorEntitySnapshot,
entity: Option<Entity>, entity: Option<Entity>,
@@ -152,6 +157,12 @@ pub enum EditorCommand {
old: Option<LightDesc>, old: Option<LightDesc>,
new: LightDesc, new: LightDesc,
}, },
SetLightGroup {
entities: Vec<Entity>,
olds: Vec<Option<LightDesc>>,
news: Vec<Option<LightDesc>>,
label: &'static str,
},
SetAnimationController { SetAnimationController {
entity: Entity, entity: Entity,
old: Option<AnimationControllerDesc>, old: Option<AnimationControllerDesc>,
@@ -293,6 +304,7 @@ pub enum EditorCommand {
impl EditorCommand { impl EditorCommand {
pub fn label(&self) -> &'static str { pub fn label(&self) -> &'static str {
match self { match self {
EditorCommand::GroupSelection { .. } => "Group Selection",
EditorCommand::Spawn { .. } => "Spawn", EditorCommand::Spawn { .. } => "Spawn",
EditorCommand::SpawnMany { .. } => "Spawn Brushes", EditorCommand::SpawnMany { .. } => "Spawn Brushes",
EditorCommand::Despawn { .. } => "Delete", EditorCommand::Despawn { .. } => "Delete",
@@ -303,6 +315,7 @@ impl EditorCommand {
EditorCommand::SetMaterialGroup { .. } => "Apply Material to Selection", EditorCommand::SetMaterialGroup { .. } => "Apply Material to Selection",
EditorCommand::SetMaterialOverride { .. } => "Set Material Override", EditorCommand::SetMaterialOverride { .. } => "Set Material Override",
EditorCommand::SetLight { .. } => "Set Light", EditorCommand::SetLight { .. } => "Set Light",
EditorCommand::SetLightGroup { label, .. } => label,
EditorCommand::SetAnimationController { .. } => "Set Animation Controller", EditorCommand::SetAnimationController { .. } => "Set Animation Controller",
EditorCommand::SetAudioSource { .. } => "Set Audio Source", EditorCommand::SetAudioSource { .. } => "Set Audio Source",
EditorCommand::SetAudioListener { .. } => "Set Audio Listener", EditorCommand::SetAudioListener { .. } => "Set Audio Listener",
+271 -78
View File
@@ -17,8 +17,8 @@ use shared::{
TriggerVolume, WeaponSpawn, TriggerVolume, WeaponSpawn,
}; };
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
use crate::scene_io::{SceneIo, SceneIoRequest}; use crate::scene_io::{SceneIo, SceneIoRequest};
use crate::selection::SelectedEntity;
use crate::state::scene_tools_active; use crate::state::scene_tools_active;
use crate::ui::hierarchy_ops::{ use crate::ui::hierarchy_ops::{
apply_sibling_change, apply_sibling_change_new, hierarchy_drop_violation, next_sibling_index, apply_sibling_change, apply_sibling_change_new, hierarchy_drop_violation, next_sibling_index,
@@ -197,7 +197,20 @@ fn spawn_snapshot_with_parent(
snapshot: &EditorEntitySnapshot, snapshot: &EditorEntitySnapshot,
parent: Option<Entity>, parent: Option<Entity>,
) -> Entity { ) -> Entity {
let mut entity_mut = world.spawn((LevelObject, snapshot.actor_kind, snapshot.transform)); let visibility = if snapshot.editor_visibility.visible {
Visibility::Visible
} else {
Visibility::Hidden
};
let mut entity_mut = world.spawn((
LevelObject,
snapshot.actor_kind,
snapshot.transform,
snapshot.editor_visibility,
visibility,
InheritedVisibility::default(),
ViewVisibility::default(),
));
entity_mut.insert( entity_mut.insert(
snapshot snapshot
.actor_id .actor_id
@@ -290,7 +303,6 @@ fn spawn_snapshot_with_parent(
entity_mut.insert(link.clone()); entity_mut.insert(link.clone());
} }
entity_mut.insert(HierarchySiblingIndex(snapshot.hierarchy_sibling_index)); entity_mut.insert(HierarchySiblingIndex(snapshot.hierarchy_sibling_index));
entity_mut.insert(snapshot.editor_visibility);
if let Some(order) = &snapshot.inspector_order { if let Some(order) = &snapshot.inspector_order {
entity_mut.insert(order.clone()); entity_mut.insert(order.clone());
} }
@@ -560,6 +572,40 @@ pub fn set_light_with_history(world: &mut World, entity: Entity, new: LightDesc)
push_history(world, EditorCommand::SetLight { entity, old, new }); 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) { pub fn set_audio_source_with_history(world: &mut World, entity: Entity, new: AudioSourceDesc) {
if !is_mutable_level_object(world, entity) { if !is_mutable_level_object(world, entity) {
return; return;
@@ -752,9 +798,13 @@ pub fn apply_brush_csg_with_history(
new_transform: Transform, new_transform: Transform,
new_brush: BrushDesc, new_brush: BrushDesc,
delete_entities: &[Entity], delete_entities: &[Entity],
) { ) -> bool {
if !is_level_object(world, primary) { if !is_mutable_level_object(world, primary)
return; || 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_transform = world.get::<Transform>(primary).copied().unwrap_or_default();
let old_brush = world.get::<BrushDesc>(primary).cloned(); let old_brush = world.get::<BrushDesc>(primary).cloned();
@@ -769,7 +819,7 @@ pub fn apply_brush_csg_with_history(
&& old_brush.as_ref() == Some(&new_brush) && old_brush.as_ref() == Some(&new_brush)
&& deleted.is_empty() && deleted.is_empty()
{ {
return; return false;
} }
if let Ok(mut entity_mut) = world.get_entity_mut(primary) { if let Ok(mut entity_mut) = world.get_entity_mut(primary) {
entity_mut.insert(new_transform); entity_mut.insert(new_transform);
@@ -790,6 +840,7 @@ pub fn apply_brush_csg_with_history(
}, },
); );
select_one(world, primary); select_one(world, primary);
true
} }
pub fn set_static_mesh_renderer_with_history( pub fn set_static_mesh_renderer_with_history(
@@ -943,14 +994,16 @@ pub fn group_selection_with_history(world: &mut World, entities: &[Entity]) {
children: Vec::new(), children: Vec::new(),
}; };
let group = spawn_snapshot(world, &snapshot); let group = spawn_snapshot(world, &snapshot);
let changes = reorder_entities_under_parent(world, &entities, Some(group), i32::MAX);
push_history( push_history(
world, world,
EditorCommand::Spawn { EditorCommand::GroupSelection {
snapshot, 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) { pub fn create_empty_child_with_history(world: &mut World, parent: Entity) {
@@ -1415,17 +1468,14 @@ pub fn apply_reflected_component(
let reflected = TypedReflectDeserializer::new(registration, &type_registry) let reflected = TypedReflectDeserializer::new(registration, &type_registry)
.deserialize(&mut deserializer) .deserialize(&mut deserializer)
.map_err(|error| error.to_string())?; .map_err(|error| error.to_string())?;
let exists = reflect_component.reflect(world.entity(entity)).is_some(); // Reflected `apply` merges list fields and cannot restore a shorter snapshot.
if exists { // Inserting the captured concrete component replaces the value atomically.
reflect_component.apply(world.entity_mut(entity), reflected.as_ref());
} else {
reflect_component.insert( reflect_component.insert(
&mut world.entity_mut(entity), &mut world.entity_mut(entity),
reflected.as_ref(), reflected.as_ref(),
&type_registry, &type_registry,
); );
} }
}
None => reflect_component.remove(&mut world.entity_mut(entity)), None => reflect_component.remove(&mut world.entity_mut(entity)),
} }
Ok(()) Ok(())
@@ -1451,16 +1501,11 @@ pub fn apply_reflected_default(
.data::<ReflectDefault>() .data::<ReflectDefault>()
.ok_or_else(|| format!("component `{type_path}` has no reflected Default"))? .ok_or_else(|| format!("component `{type_path}` has no reflected Default"))?
.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( reflect_component.insert(
&mut world.entity_mut(entity), &mut world.entity_mut(entity),
default.as_ref(), default.as_ref(),
&type_registry, &type_registry,
); );
}
Ok(()) Ok(())
}) })
} }
@@ -1570,7 +1615,7 @@ pub fn set_scene_composition_with_history(world: &mut World, new: SceneCompositi
pub fn apply_command_undo(world: &mut World) { pub fn apply_command_undo(world: &mut World) {
let candidate = world.resource::<EditorHistory>().undo_stack.last().cloned(); let candidate = world.resource::<EditorHistory>().undo_stack.last().cloned();
if let Some(candidate) = candidate { if let Some(candidate) = candidate {
if let Err(error) = prepare_prefab_source_history(&candidate, true) { if let Err(error) = prepare_prefab_source_history(world, &candidate, true) {
world.resource_mut::<EditorHistory>().status = format!("Undo blocked: {error}"); world.resource_mut::<EditorHistory>().status = format!("Undo blocked: {error}");
world world
.resource_mut::<SceneIo>() .resource_mut::<SceneIo>()
@@ -1585,13 +1630,13 @@ pub fn apply_command_undo(world: &mut World) {
undo_command(world, &mut command); undo_command(world, &mut command);
world.resource_mut::<EditorHistory>().push_redo(command); world.resource_mut::<EditorHistory>().push_redo(command);
world.resource_mut::<EditorHistory>().set_redo_status(label); world.resource_mut::<EditorHistory>().set_redo_status(label);
mark_dirty(world); crate::scene_io::reconcile_active_dirty_with_checkpoint(world);
} }
pub fn apply_command_redo(world: &mut World) { pub fn apply_command_redo(world: &mut World) {
let candidate = world.resource::<EditorHistory>().redo_stack.last().cloned(); let candidate = world.resource::<EditorHistory>().redo_stack.last().cloned();
if let Some(candidate) = candidate { if let Some(candidate) = candidate {
if let Err(error) = prepare_prefab_source_history(&candidate, false) { if let Err(error) = prepare_prefab_source_history(world, &candidate, false) {
world.resource_mut::<EditorHistory>().status = format!("Redo blocked: {error}"); world.resource_mut::<EditorHistory>().status = format!("Redo blocked: {error}");
world world
.resource_mut::<SceneIo>() .resource_mut::<SceneIo>()
@@ -1606,11 +1651,16 @@ pub fn apply_command_redo(world: &mut World) {
redo_command(world, &mut command); redo_command(world, &mut command);
world.resource_mut::<EditorHistory>().push_undo(command); world.resource_mut::<EditorHistory>().push_undo(command);
world.resource_mut::<EditorHistory>().set_undo_status(label); world.resource_mut::<EditorHistory>().set_undo_status(label);
mark_dirty(world); crate::scene_io::reconcile_active_dirty_with_checkpoint(world);
} }
fn prepare_prefab_source_history(command: &EditorCommand, undo: bool) -> Result<(), String> { fn prepare_prefab_source_history(
world: &mut World,
command: &EditorCommand,
undo: bool,
) -> Result<(), String> {
let EditorCommand::ApplyPrefabToSource { let EditorCommand::ApplyPrefabToSource {
entity,
source_path, source_path,
before_source, before_source,
after_source, after_source,
@@ -1624,19 +1674,29 @@ fn prepare_prefab_source_history(command: &EditorCommand, undo: bool) -> Result<
} else { } else {
(before_source, after_source) (before_source, after_source)
}; };
let current = std::fs::read_to_string(source_path) let expected =
.map_err(|error| format!("could not read {}: {error}", source_path.display()))?; crate::collaboration::FileSnapshot::from_loaded_bytes(source_path, expected.as_bytes());
if &current != expected { crate::collaboration::publish_authored_file(
return Err(format!( world,
"{} changed outside this history command", source_path,
source_path.display() replacement.as_bytes(),
)); &expected,
} crate::collaboration::FileWriteIntent::PrefabSourceHistory {
crate::scene::recovery::atomic_write(source_path, replacement.as_bytes()) instance_root: *entity,
},
)
.map(|_| ())
} }
fn undo_command(world: &mut World, command: &mut EditorCommand) { fn undo_command(world: &mut World, command: &mut EditorCommand) {
match command { 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, .. } => { EditorCommand::Spawn { entity, .. } => {
despawn_entity(world, entity.take()); despawn_entity(world, entity.take());
clear_selection(world); clear_selection(world);
@@ -1682,6 +1742,11 @@ fn undo_command(world: &mut World, command: &mut EditorCommand) {
EditorCommand::SetLight { entity, old, .. } => { EditorCommand::SetLight { entity, old, .. } => {
apply_light(world, *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, .. } => { EditorCommand::SetAnimationController { entity, old, .. } => {
apply_animation_controller(world, *entity, old); apply_animation_controller(world, *entity, old);
} }
@@ -1818,6 +1883,25 @@ fn undo_command(world: &mut World, command: &mut EditorCommand) {
fn redo_command(world: &mut World, command: &mut EditorCommand) { fn redo_command(world: &mut World, command: &mut EditorCommand) {
match command { 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 } => { EditorCommand::Spawn { snapshot, entity } => {
let spawned = spawn_snapshot(world, snapshot); let spawned = spawn_snapshot(world, snapshot);
*entity = Some(spawned); *entity = Some(spawned);
@@ -1881,6 +1965,11 @@ fn redo_command(world: &mut World, command: &mut EditorCommand) {
entity_mut.insert(new.clone()); 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, .. } => { EditorCommand::SetAnimationController { entity, new, .. } => {
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) { if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
entity_mut.insert(new.clone()); entity_mut.insert(new.clone());
@@ -2614,16 +2703,22 @@ fn capture_gizmo_transform_edits(world: &mut World) {
let start_group = let start_group =
active.map(|(entity, transform)| selected_transforms(world, &selection, entity, transform)); active.map(|(entity, transform)| selected_transforms(world, &selection, entity, transform));
let mut started_edit = false;
let (finished_edit, live_edit) = { let (finished_edit, live_edit) = {
let mut tracker = world.resource_mut::<TransformEditTracker>(); let mut tracker = world.resource_mut::<TransformEditTracker>();
if tracker.active.is_none() { if tracker.active.is_none() {
if let (Some((entity, transform)), Some(group)) = (active, start_group) { if let (Some((entity, transform)), Some(group)) = (active, start_group) {
tracker.active = Some((entity, transform, group)); tracker.active = Some((entity, transform, group));
return; started_edit = true;
} }
} }
if started_edit {
(None, None)
} else {
match tracker.active.take() { match tracker.active.take() {
Some((primary, old, group)) if active.is_none() => (Some((primary, old, group)), None), Some((primary, old, group)) if active.is_none() => {
(Some((primary, old, group)), None)
}
Some(state) if active.is_some() => { Some(state) if active.is_some() => {
let live = Some(state.clone()); let live = Some(state.clone());
tracker.active = Some(state); tracker.active = Some(state);
@@ -2631,8 +2726,18 @@ fn capture_gizmo_transform_edits(world: &mut World) {
} }
_ => (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 { if let Some((primary, old_primary, group)) = live_edit {
let Some(new_primary) = world.get::<Transform>(primary).copied() else { let Some(new_primary) = world.get::<Transform>(primary).copied() else {
return; return;
@@ -2645,15 +2750,51 @@ fn capture_gizmo_transform_edits(world: &mut World) {
if let Some((primary, old_primary, group)) = finished_edit { if let Some((primary, old_primary, group)) = finished_edit {
let Some(new_primary) = world.get::<Transform>(primary).copied() else { 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; return;
}; };
let undo_depth = world.resource::<EditorHistory>().undo_depth();
if group.len() <= 1 { if group.len() <= 1 {
set_transform_with_history(world, primary, old_primary, new_primary); set_transform_with_history(world, primary, old_primary, new_primary);
return; } else {
}
let changes = transform_group_changes(old_primary, new_primary, group); let changes = transform_group_changes(old_primary, new_primary, group);
set_transform_group_with_history(world, changes); 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(),
});
}
} }
fn transform_group_changes( fn transform_group_changes(
@@ -2730,32 +2871,15 @@ fn despawn_entity(world: &mut World, entity: Option<Entity>) {
} }
fn select_one(world: &mut World, entity: Entity) { fn select_one(world: &mut World, entity: Entity) {
if let Some(mut ui_state) = world.get_resource_mut::<UiState>() { crate::ui::request_ui_selection(world, &[entity]);
ui_state.selected_entities.clear();
ui_state.selected_entities.select_replace(entity);
}
world.resource_mut::<SelectedEntity>().0 = Some(entity);
} }
fn select_many(world: &mut World, entities: &[Entity]) { fn select_many(world: &mut World, entities: &[Entity]) {
if let Some(mut ui_state) = world.get_resource_mut::<UiState>() { crate::ui::request_ui_selection(world, entities);
ui_state.selected_entities.clear();
for (index, entity) in entities.iter().enumerate() {
if index == 0 {
ui_state.selected_entities.select_replace(*entity);
} else {
ui_state.selected_entities.select_maybe_add(*entity, true);
}
}
}
world.resource_mut::<SelectedEntity>().0 = entities.first().copied();
} }
pub fn clear_selection(world: &mut World) { pub fn clear_selection(world: &mut World) {
if let Some(mut ui_state) = world.get_resource_mut::<UiState>() { crate::ui::request_ui_selection(world, &[]);
ui_state.selected_entities.clear();
}
world.resource_mut::<SelectedEntity>().0 = None;
} }
pub fn is_level_object(world: &World, entity: Entity) -> bool { pub fn is_level_object(world: &World, entity: Entity) -> bool {
@@ -2796,7 +2920,29 @@ pub(crate) fn material_eq(a: &MaterialDesc, b: &MaterialDesc) -> bool {
mod tests { mod tests {
use super::*; use super::*;
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness}; use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus}; use crate::operators::{ActiveOperator, OperatorPhase};
use crate::selection::SelectedEntity;
use crate::ui::PendingUiSelection;
#[test]
fn history_select_many_queues_exact_selection_while_ui_state_is_scoped_out() {
let first = Entity::from_bits(1);
let second = Entity::from_bits(2);
let mut world = World::new();
world.init_resource::<SelectedEntity>();
world.init_resource::<PendingUiSelection>();
world.insert_resource(UiState::default_layout());
world.resource_scope::<UiState, _>(|world, _ui_state| {
assert!(!world.contains_resource::<UiState>());
select_many(world, &[first, second]);
assert_eq!(
world.resource::<PendingUiSelection>().0.as_deref(),
Some([first, second].as_slice())
);
assert_eq!(world.resource::<SelectedEntity>().0, Some(first));
});
}
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq)] #[derive(Component, Reflect, Default, Debug, Clone, PartialEq)]
#[reflect(Component, Default)] #[reflect(Component, Default)]
@@ -3074,6 +3220,7 @@ mod tests {
world.init_resource::<ActiveOperator>(); world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>(); world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>(); world.init_resource::<SceneIo>();
world.init_resource::<TransformEditTracker>();
let first = world.spawn((LevelObject, Transform::default())).id(); let first = world.spawn((LevelObject, Transform::default())).id();
let second = world let second = world
.spawn(( .spawn((
@@ -3085,30 +3232,19 @@ mod tests {
let committed = vec![Vec3::Z, Vec3::new(2.0, 0.0, 1.0)]; let committed = vec![Vec3::Z, Vec3::new(2.0, 0.0, 1.0)];
let harness = OperatorInvariantHarness::capture(&mut world); let harness = OperatorInvariantHarness::capture(&mut world);
set_transform_group_with_history( world.resource_mut::<TransformEditTracker>().active = Some((
&mut world,
[
(
first, first,
Transform::default(), Transform::default(),
Transform::from_translation(committed[0]), vec![
), (first, Transform::default()),
( (second, Transform::from_translation(initial[1])),
second,
Transform::from_translation(initial[1]),
Transform::from_translation(committed[1]),
),
], ],
); ));
world.resource_mut::<ActiveOperator>().status = Some(OperatorStatus { *world.get_mut::<Transform>(first).unwrap() = Transform::from_translation(committed[0]);
id: "transform.gizmo".to_string(), capture_gizmo_transform_edits(&mut world);
label: "Transform Gizmo".to_string(),
phase: OperatorPhase::Committed,
hint: "Committed multi-selection drag".to_string(),
warnings: Vec::new(),
});
harness.assert_committed(&mut world, 1, 0); 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| { assert_undo_redo_round_trip(&mut world, initial, committed, |world| {
[first, second] [first, second]
.into_iter() .into_iter()
@@ -3117,6 +3253,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] #[test]
fn unpack_prefab_is_one_undoable_history_command() { fn unpack_prefab_is_one_undoable_history_command() {
let mut world = World::new(); let mut world = World::new();
+25 -1
View File
@@ -22,11 +22,15 @@ pub use ext::extensibility;
pub use ext::hot_reload; pub use ext::hot_reload;
pub use play::net_editor; pub use play::net_editor;
pub use play::state; pub use play::state;
pub use project::collaboration;
pub use project::diagnostics_bundle; pub use project::diagnostics_bundle;
pub use project::launcher; pub use project::launcher;
pub use project::native_dialog;
pub use project::project_io; pub use project::project_io;
pub use project::samples;
pub use project::session; pub use project::session;
pub use project::settings_ui; pub use project::settings_ui;
pub use project::shutdown;
pub use scene::scene_io; pub use scene::scene_io;
pub use scene::scene_schema; pub use scene::scene_schema;
pub use scene::scene_view; pub use scene::scene_view;
@@ -36,10 +40,14 @@ pub use viewport::brush_edit;
pub use viewport::brush_tool; pub use viewport::brush_tool;
pub use viewport::camera; pub use viewport::camera;
pub use viewport::gizmos; pub use viewport::gizmos;
pub use viewport::material_drop;
pub use viewport::physics_placement;
pub use viewport::render_view; pub use viewport::render_view;
pub use viewport::rendering_diagnostics; pub use viewport::rendering_diagnostics;
pub use viewport::selection; pub use viewport::selection;
pub use viewport::selection_outline; pub use viewport::selection_outline;
pub use viewport::terrain_paint;
pub use viewport::terrain_sculpt;
pub use viewport::visualizers; pub use viewport::visualizers;
use bevy::app::PluginGroupBuilder; use bevy::app::PluginGroupBuilder;
@@ -61,9 +69,15 @@ use extensibility::ExtensibilityPlugin;
use gizmos::EditorGizmoPlugin; use gizmos::EditorGizmoPlugin;
use history::EditorHistoryPlugin; use history::EditorHistoryPlugin;
use infra::EditorInfraPlugin; use infra::EditorInfraPlugin;
use material_drop::MaterialDropPlugin;
use operators::OperatorPlugin; use operators::OperatorPlugin;
use physics_placement::PhysicsPlacementPlugin;
use play::audio_preview::AudioPreviewPlugin; use play::audio_preview::AudioPreviewPlugin;
use play::PlaySessionPlugin; use play::PlaySessionPlugin;
use project::collaboration::CollaborationPlugin;
use project::native_dialog::NativeDialogPlugin;
use project::samples::SampleCatalogPlugin;
use project::shutdown::ShutdownPlugin;
use project_io::ProjectIoPlugin; use project_io::ProjectIoPlugin;
use render_view::RenderViewPlugin; use render_view::RenderViewPlugin;
use scene_io::SceneIoPlugin; use scene_io::SceneIoPlugin;
@@ -73,6 +87,8 @@ use selection_outline::SelectionOutlinePlugin;
use session::EditorSessionPlugin; use session::EditorSessionPlugin;
use settings_ui::SettingsUiPlugin; use settings_ui::SettingsUiPlugin;
use state::EditorStatePlugin; use state::EditorStatePlugin;
use terrain_paint::TerrainPaintPlugin;
use terrain_sculpt::TerrainSculptPlugin;
use ui::EditorUiPlugin; use ui::EditorUiPlugin;
use viewport::ViewportPlugin; use viewport::ViewportPlugin;
use visualizers::EditorVisualizersPlugin; use visualizers::EditorVisualizersPlugin;
@@ -86,6 +102,9 @@ impl PluginGroup for EditorPluginGroup {
let group = PluginGroupBuilder::start::<Self>() let group = PluginGroupBuilder::start::<Self>()
.add(EditorInfraPlugin) .add(EditorInfraPlugin)
.add(ProjectIoPlugin) .add(ProjectIoPlugin)
.add(SampleCatalogPlugin)
.add(NativeDialogPlugin)
.add(ShutdownPlugin)
.add(scene_schema::SceneSchemaPlugin) .add(scene_schema::SceneSchemaPlugin)
.add(net_editor::NetEditorPlugin) .add(net_editor::NetEditorPlugin)
.add(AssetDbPlugin) .add(AssetDbPlugin)
@@ -102,15 +121,20 @@ impl PluginGroup for EditorPluginGroup {
.add(BrushCsgPlugin) .add(BrushCsgPlugin)
.add(BrushEditPlugin) .add(BrushEditPlugin)
.add(BrushToolPlugin) .add(BrushToolPlugin)
.add(TerrainSculptPlugin)
.add(TerrainPaintPlugin)
.add(EditorCameraPlugin) .add(EditorCameraPlugin)
.add(AudioPreviewPlugin) .add(AudioPreviewPlugin)
.add(ActorIconsPlugin) .add(ActorIconsPlugin)
.add(MaterialDropPlugin)
.add(PhysicsPlacementPlugin)
.add(EditorSelectionPlugin) .add(EditorSelectionPlugin)
.add(SelectionOutlinePlugin) .add(SelectionOutlinePlugin)
.add(EditorGizmoPlugin) .add(EditorGizmoPlugin)
.add(EditorVisualizersPlugin) .add(EditorVisualizersPlugin)
.add(EditorHistoryPlugin) .add(EditorHistoryPlugin)
.add(SceneIoPlugin) .add(SceneIoPlugin)
.add(CollaborationPlugin)
.add(EditorUiPlugin) .add(EditorUiPlugin)
.add(EditorSessionPlugin) .add(EditorSessionPlugin)
.add(brp::BrpPlugin); .add(brp::BrpPlugin);
@@ -122,7 +146,7 @@ impl PluginGroup for EditorPluginGroup {
/// Shared Bevy app wiring for the in-process editor (game sim + egui shell). /// Shared Bevy app wiring for the in-process editor (game sim + egui shell).
pub fn configure_editor_app(app: &mut App) { pub fn configure_editor_app(app: &mut App) {
app.add_plugins(launch::default_plugins("Bevy FPS Editor")) app.add_plugins(launch::editor_plugins("Bevy FPS Editor"))
.insert_resource(GameInputEnabled(false)) .insert_resource(GameInputEnabled(false))
.insert_resource(GameInputFocused(false)) .insert_resource(GameInputFocused(false))
.insert_resource(SimEnabled(false)) .insert_resource(SimEnabled(false))
+97
View File
@@ -59,6 +59,12 @@ pub enum OperatorAvailability {
Disabled(String), Disabled(String),
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperatorAction {
Commit,
ContinuePreview,
}
pub trait EditorOperator { pub trait EditorOperator {
fn id(&self) -> &str; fn id(&self) -> &str;
fn label(&self) -> &str; fn label(&self) -> &str;
@@ -221,6 +227,51 @@ pub fn run_immediate_operator(
run_operator(world, &mut 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) { fn set_operator_status(world: &mut World, status: OperatorStatus) {
if let Some(mut active) = world.get_resource_mut::<ActiveOperator>() { if let Some(mut active) = world.get_resource_mut::<ActiveOperator>() {
active.status = Some(status); active.status = Some(status);
@@ -355,6 +406,52 @@ mod tests {
harness.assert_no_helpers::<PreviewHelper>(&mut world); 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] #[test]
fn blocked_operator_never_begins_or_mutates_world() { fn blocked_operator_never_begins_or_mutates_world() {
let mut world = test_world(); let mut world = test_world();
@@ -47,6 +47,12 @@ impl OperatorInvariantHarness {
world.resource::<SceneIo>().dirty, world.resource::<SceneIo>().dirty,
"a committed authored mutation must mark the scene 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!( assert_eq!(
authored_count(world) as isize, 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) { fn assert_phase(&self, world: &World, expected: OperatorPhase) {
let phase = world let phase = world
.resource::<ActiveOperator>() .resource::<ActiveOperator>()
+51 -3
View File
@@ -1,9 +1,12 @@
use std::time::Duration;
use avian3d::prelude::{Physics, PhysicsTime};
use bevy::prelude::*; use bevy::prelude::*;
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow}; use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
use bevy_egui::PrimaryEguiContext; use bevy_egui::PrimaryEguiContext;
use game::player::PlayerCamera; use game::player::PlayerCamera;
use game::{GameInputEnabled, GameInputFocused, SimEnabled}; use game::{GameInputEnabled, GameInputFocused, SimEnabled};
use protocol::PlayerInputIntent; use protocol::{PlayerInputIntent, SIM_TICK_RATE_HZ};
use sim::{Crouching, Grounded, JumpState, Player, PlayerVelocity}; use sim::{Crouching, Grounded, JumpState, Player, PlayerVelocity};
use crate::camera::EditorCamera; use crate::camera::EditorCamera;
@@ -195,6 +198,7 @@ pub(crate) fn sync_mode_resources_and_cameras(
mut step: ResMut<PlayStepOnce>, mut step: ResMut<PlayStepOnce>,
mut input_enabled: ResMut<GameInputEnabled>, mut input_enabled: ResMut<GameInputEnabled>,
mut sim_enabled: ResMut<SimEnabled>, mut sim_enabled: ResMut<SimEnabled>,
mut physics_time: ResMut<Time<Physics>>,
mut editor_cameras: Query<&mut Camera, With<EditorCamera>>, mut editor_cameras: Query<&mut Camera, With<EditorCamera>>,
mut player_cameras: Query<&mut Camera, (With<PlayerCamera>, Without<EditorCamera>)>, mut player_cameras: Query<&mut Camera, (With<PlayerCamera>, Without<EditorCamera>)>,
mut egui_cameras: Query< mut egui_cameras: Query<
@@ -212,9 +216,11 @@ pub(crate) fn sync_mode_resources_and_cameras(
let ejected = playing && *possession == PlayPossession::Ejected; let ejected = playing && *possession == PlayPossession::Ejected;
let possessed = playing && *possession == PlayPossession::Possessed; 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; 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; 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( fn sync_play_input_focus(
mode: Res<State<EditorMode>>, mode: Res<State<EditorMode>>,
possession: Res<PlayPossession>, 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)
);
}
}
File diff suppressed because it is too large. Load diff
+37 -5
View File
@@ -13,6 +13,7 @@ use settings::{
PROJECT_TEMPLATE_VERSION, PROJECT_TEMPLATE_VERSION,
}; };
use crate::native_dialog::{NativeDialogBroker, NativeDialogPlugin};
use crate::project_io::UserPreferences; use crate::project_io::UserPreferences;
use crate::scene::recovery::atomic_write; use crate::scene::recovery::atomic_write;
use crate::ui::theme::{ use crate::ui::theme::{
@@ -91,6 +92,7 @@ pub fn run_project_launcher() {
..default() ..default()
})) }))
.add_plugins(EguiPlugin::default()) .add_plugins(EguiPlugin::default())
.add_plugins(NativeDialogPlugin)
.init_resource::<ProjectLauncherUi>() .init_resource::<ProjectLauncherUi>()
.add_systems(Startup, spawn_project_launcher_camera) .add_systems(Startup, spawn_project_launcher_camera)
.add_systems(EguiPrimaryContextPass, project_launcher_ui_system); .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), egui::RichText::new("Select a root containing assets/project.ron").color(TEXT_DIM),
); );
ui.add_space(8.0); ui.add_space(8.0);
if ui.button("Browse Existing...").clicked() { let dialog_pending = world.resource::<NativeDialogBroker>().is_pending();
if let Some(root) = rfd::FileDialog::new().pick_folder() { if ui
open_project_from_launcher(world, state, root); .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(), .truncate(),
); );
if ui.button("Choose Empty Folder...").clicked() { if ui
state.sandbox_destination = rfd::FileDialog::new().pick_folder(); .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 = let can_create =
state.sandbox_destination.is_some() && !state.sandbox_name.trim().is_empty(); state.sandbox_destination.is_some() && !state.sandbox_name.trim().is_empty();
+4
View File
@@ -1,7 +1,11 @@
//! Project workspace I/O, settings UI, and recent-level sync. //! Project workspace I/O, settings UI, and recent-level sync.
pub mod collaboration;
pub mod diagnostics_bundle; pub mod diagnostics_bundle;
pub mod launcher; pub mod launcher;
pub mod native_dialog;
pub mod project_io; pub mod project_io;
pub mod samples;
pub mod session; pub mod session;
pub mod settings_ui; pub mod settings_ui;
pub mod shutdown;
+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());
}
}
+208
View File
@@ -0,0 +1,208 @@
//! Cached project sample catalog used by editor scene-opening UI.
use std::path::{Path, PathBuf};
use bevy::prelude::*;
use scene::sample_pack::{
validate_editor_sample_pack, EditorSampleEntry, EDITOR_SAMPLE_MANIFEST_PATH,
};
use super::project_io::ProjectWorkspace;
const VALIDATION_HINT: &str = "Run `cargo validate-samples --project .` for details.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SampleCatalogEntry {
pub id: String,
pub label: String,
pub scene_path: PathBuf,
pub project_relative_scene: String,
pub summary: String,
pub checks: Vec<String>,
}
impl SampleCatalogEntry {
pub fn hover_text(&self) -> String {
let mut lines = vec![self.summary.clone()];
if !self.checks.is_empty() {
lines.push(format!("Checks: {}", self.checks.join(", ")));
}
lines.push(self.project_relative_scene.clone());
lines.join("\n")
}
}
#[derive(Resource, Debug, Clone)]
pub struct SampleCatalog {
entries: Vec<SampleCatalogEntry>,
unavailable_reason: Option<String>,
}
impl Default for SampleCatalog {
fn default() -> Self {
Self::unavailable("Sample catalog is loading")
}
}
impl SampleCatalog {
pub fn entries(&self) -> &[SampleCatalogEntry] {
&self.entries
}
pub fn entry(&self, stable_id: &str) -> Option<&SampleCatalogEntry> {
self.unavailable_reason
.is_none()
.then(|| self.entries.iter().find(|entry| entry.id == stable_id))
.flatten()
}
pub fn unavailable_reason(&self) -> Option<&str> {
self.unavailable_reason.as_deref()
}
#[cfg(test)]
pub(crate) fn available_entries(entries: Vec<SampleCatalogEntry>) -> Self {
Self {
entries,
unavailable_reason: None,
}
}
fn available(samples: Vec<EditorSampleEntry>) -> Self {
Self {
entries: samples.into_iter().map(catalog_entry).collect(),
unavailable_reason: None,
}
}
fn unavailable(reason: impl Into<String>) -> Self {
Self {
entries: Vec::new(),
unavailable_reason: Some(reason.into()),
}
}
}
fn catalog_entry(entry: EditorSampleEntry) -> SampleCatalogEntry {
SampleCatalogEntry {
id: entry.id,
label: entry.label,
scene_path: PathBuf::from(&entry.scene),
project_relative_scene: entry.scene,
summary: entry.summary,
checks: entry.checks,
}
}
fn load_catalog(project_root: &Path) -> SampleCatalog {
let validation = validate_editor_sample_pack(project_root);
if !validation.is_release_ready() {
let first_error = validation
.report
.findings
.iter()
.find(|finding| finding.severity == scene::ValidationSeverity::Error)
.map(|finding| finding.message.as_str())
.unwrap_or("sample pack validation failed");
return SampleCatalog::unavailable(format!(
"Sample manifest `{EDITOR_SAMPLE_MANIFEST_PATH}` is invalid: {first_error}\n{VALIDATION_HINT}"
));
}
if validation.samples.is_empty() {
return SampleCatalog::unavailable(format!(
"Sample manifest contains no scenes.\n{VALIDATION_HINT}"
));
}
SampleCatalog::available(validation.samples)
}
fn load_sample_catalog(world: &mut World) {
let project_root = PathBuf::from(&world.resource::<ProjectWorkspace>().root);
world.insert_resource(load_catalog(&project_root));
}
pub struct SampleCatalogPlugin;
impl Plugin for SampleCatalogPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<SampleCatalog>()
.add_systems(Startup, load_sample_catalog);
}
}
#[cfg(test)]
mod tests {
use super::*;
use scene::sample_pack::EditorSampleArea;
fn sample(id: &str, label: &str, scene: &str) -> EditorSampleEntry {
EditorSampleEntry {
id: id.into(),
label: label.into(),
area: EditorSampleArea::Brush,
scene: scene.into(),
summary: format!("Summary for {label}"),
checks: vec!["selection".into(), "undo".into()],
}
}
#[test]
fn available_catalog_preserves_manifest_order_and_resolves_paths() {
let catalog = SampleCatalog::available(vec![
sample(
"terrain",
"Terrain",
"assets/levels/samples/terrain.scn.ron",
),
sample("brush", "Brush", "assets/levels/samples/brush.scn.ron"),
]);
assert_eq!(
catalog
.entries()
.iter()
.map(|entry| entry.id.as_str())
.collect::<Vec<_>>(),
vec!["terrain", "brush"]
);
assert_eq!(
catalog.entry("brush").unwrap().scene_path,
PathBuf::from("assets/levels/samples/brush.scn.ron")
);
let hover = catalog.entry("brush").unwrap().hover_text();
assert!(hover.contains("Summary for Brush"));
assert!(hover.contains("Checks: selection, undo"));
assert!(hover.contains("assets/levels/samples/brush.scn.ron"));
}
#[test]
fn unavailable_catalog_never_resolves_entries() {
let catalog = SampleCatalog {
entries: vec![catalog_entry(sample(
"brush",
"Brush",
"assets/levels/samples/brush.scn.ron",
))],
unavailable_reason: Some("manifest invalid".into()),
};
assert!(catalog.entry("brush").is_none());
assert_eq!(catalog.unavailable_reason(), Some("manifest invalid"));
}
#[test]
fn missing_manifest_reports_repair_command() {
let root = std::env::temp_dir().join(format!(
"blacksite-missing-sample-catalog-{}",
uuid::Uuid::new_v4()
));
std::fs::create_dir_all(&root).unwrap();
let catalog = load_catalog(&root);
let reason = catalog.unavailable_reason().unwrap();
assert!(reason.contains(EDITOR_SAMPLE_MANIFEST_PATH));
assert!(reason.contains("cargo validate-samples --project ."));
std::fs::remove_dir_all(root).unwrap();
}
}
+8 -2
View File
@@ -11,6 +11,7 @@ use crate::project_io::{ProjectWorkspace, UserPreferences};
use crate::scene::recovery::{atomic_write, default_state_root}; use crate::scene::recovery::{atomic_write, default_state_root};
use crate::scene_io::{SceneIo, SceneIoRequest}; use crate::scene_io::{SceneIo, SceneIoRequest};
use crate::settings_ui::ProjectSettingsPanel; use crate::settings_ui::ProjectSettingsPanel;
use crate::shutdown::ShutdownCoordinator;
use crate::ui::{BrushDiagnosticsPanel, DiagnosticsPanel}; use crate::ui::{BrushDiagnosticsPanel, DiagnosticsPanel};
use crate::viewport::rendering_diagnostics::RenderingDiagnosticsPanel; use crate::viewport::rendering_diagnostics::RenderingDiagnosticsPanel;
use crate::viewport::CameraBookmarks; use crate::viewport::CameraBookmarks;
@@ -109,8 +110,8 @@ impl Plugin for EditorSessionPlugin {
.add_systems(Startup, initialize_session) .add_systems(Startup, initialize_session)
.add_systems(Update, persist_running_session) .add_systems(Update, persist_running_session)
.add_systems( .add_systems(
Last, crate::shutdown::EditorShutdownFinalize,
persist_clean_session_on_exit.after(bevy::window::ExitSystems), persist_clean_session_on_exit.after(crate::shutdown::finalize_authorized_shutdown),
); );
} }
} }
@@ -311,6 +312,7 @@ fn persist_running_session(world: &mut World) {
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn persist_clean_session_on_exit( fn persist_clean_session_on_exit(
mut exits: MessageReader<AppExit>, mut exits: MessageReader<AppExit>,
shutdown: Option<Res<ShutdownCoordinator>>,
scene_io: Res<SceneIo>, scene_io: Res<SceneIo>,
workspace: Res<ProjectWorkspace>, workspace: Res<ProjectWorkspace>,
prefs: Res<UserPreferences>, prefs: Res<UserPreferences>,
@@ -323,6 +325,10 @@ fn persist_clean_session_on_exit(
if exits.read().next().is_none() { if exits.read().next().is_none() {
return; return;
} }
if !shutdown.is_some_and(|shutdown| shutdown.authorized_exit_sent()) {
warn!("Ignoring an unauthorized AppExit for clean-session persistence");
return;
}
let Some(path) = session_path() else { let Some(path) = session_path() else {
return; return;
}; };
+184 -9
View File
@@ -1,18 +1,28 @@
//! Editor-only Project Settings panel (egui). Data lives in the `settings` crate. //! Editor-only Project Settings panel (egui). Data lives in the `settings` crate.
use std::path::Path;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_egui::egui; use bevy_egui::egui;
use game_hot::sync_project_sun_from_settings; use game_hot::sync_project_sun_from_settings;
use settings::{ use settings::{
load_project_settings_from_path, save_project_settings, sync_sim_tuning, ExposureMode, save_project_settings_to_string, sync_sim_tuning, ExposureMode, ProjectSettings,
ProjectSettings, ProjectSettingsChanged, ProjectSettingsIo, ProjectSettingsChanged, ProjectSettingsIo,
}; };
use crate::project::collaboration::{
file_status_indicator_ui, publish_authored_file, CollaborationState, FileSnapshot,
FileWriteIntent,
};
use crate::scene_io::SceneIo;
/// Whether the Project Settings window is visible (editor UI state only). /// Whether the Project Settings window is visible (editor UI state only).
#[derive(Resource, Debug, Default)] #[derive(Resource, Debug, Default)]
pub struct ProjectSettingsPanel { pub struct ProjectSettingsPanel {
pub open: bool, pub open: bool,
pub draft: Option<ProjectSettings>, pub draft: Option<ProjectSettings>,
disk_snapshot: Option<FileSnapshot>,
save_error: Option<String>,
} }
pub struct SettingsUiPlugin; pub struct SettingsUiPlugin;
@@ -39,11 +49,23 @@ pub fn project_settings_window(
) { ) {
if !panel.open { if !panel.open {
panel.draft = None; panel.draft = None;
panel.disk_snapshot = None;
panel.save_error = None;
return; return;
} }
if panel.draft.is_none() { if panel.draft.is_none() {
panel.draft = Some(world.resource::<ProjectSettings>().clone()); panel.draft = Some(world.resource::<ProjectSettings>().clone());
let io = world.resource::<ProjectSettingsIo>();
panel.disk_snapshot = Some(
io.loaded_source
.as_deref()
.map(|source| {
FileSnapshot::from_loaded_bytes(Path::new(&io.path), source.as_bytes())
})
.unwrap_or_else(FileSnapshot::missing),
);
panel.save_error = None;
} }
let mut open = panel.open; let mut open = panel.open;
@@ -51,17 +73,33 @@ pub fn project_settings_window(
.open(&mut open) .open(&mut open)
.default_width(420.0) .default_width(420.0)
.show(ctx, |ui| { .show(ctx, |ui| {
let Some(draft) = panel.draft.as_mut() else { let ProjectSettingsPanel {
draft: Some(draft),
disk_snapshot,
save_error,
..
} = panel
else {
return; return;
}; };
let io_path = world.resource::<ProjectSettingsIo>().path.clone(); let io_path = world.resource::<ProjectSettingsIo>().path.clone();
let mut io_dirty = world.resource::<ProjectSettingsIo>().dirty; let mut io_dirty = world.resource::<ProjectSettingsIo>().dirty;
draw_project_settings_form(world, ui, draft, &io_path, &mut io_dirty); draw_project_settings_form(
world,
ui,
draft,
&io_path,
&mut io_dirty,
disk_snapshot,
save_error,
);
world.resource_mut::<ProjectSettingsIo>().dirty = io_dirty; world.resource_mut::<ProjectSettingsIo>().dirty = io_dirty;
}); });
panel.open = open; panel.open = open;
if !open { if !open {
panel.draft = None; panel.draft = None;
panel.disk_snapshot = None;
panel.save_error = None;
} }
} }
@@ -71,12 +109,26 @@ fn draw_project_settings_form(
draft: &mut ProjectSettings, draft: &mut ProjectSettings,
io_path: &str, io_path: &str,
io_dirty: &mut bool, io_dirty: &mut bool,
disk_snapshot: &mut Option<FileSnapshot>,
save_error: &mut Option<String>,
) { ) {
let caps = world let caps = world
.get_resource::<settings::RenderingCapabilities>() .get_resource::<settings::RenderingCapabilities>()
.cloned() .cloned()
.unwrap_or_default(); .unwrap_or_default();
ui.horizontal_wrapped(|ui| {
ui.small(egui::RichText::new(io_path).monospace());
if let Some(state) = world.get_resource::<CollaborationState>() {
let status = state.file_status(Path::new(io_path));
let _ = file_status_indicator_ui(ui, &status, Path::new(io_path));
}
});
if let Some(error) = save_error.as_deref() {
ui.colored_label(crate::ui::theme::ERROR, error);
}
ui.separator();
ui.collapsing("Global Illumination", |ui| { ui.collapsing("Global Illumination", |ui| {
egui::ComboBox::from_label("GiMode") egui::ComboBox::from_label("GiMode")
.selected_text(format!("{:?}", draft.rendering.gi_mode)) .selected_text(format!("{:?}", draft.rendering.gi_mode))
@@ -335,25 +387,116 @@ fn draw_project_settings_form(
.clicked() .clicked()
{ {
commit_project_settings(world, draft); commit_project_settings(world, draft);
*io_dirty = true;
let settings = world.resource::<ProjectSettings>().clone(); let settings = world.resource::<ProjectSettings>().clone();
let Some(expected) = disk_snapshot.clone() else {
let error = "Project settings disk baseline is unavailable; reload before saving";
*save_error = Some(error.into());
world.resource_mut::<SceneIo>().set_status(error);
return;
};
match persist_project_settings(world, &settings, &expected) {
Ok((snapshot, source)) => {
let mut io = world.resource_mut::<ProjectSettingsIo>(); let mut io = world.resource_mut::<ProjectSettingsIo>();
if let Err(error) = save_project_settings(&settings, &mut io) { io.dirty = false;
warn!("Save project settings failed: {error}"); io.loaded_source = Some(source);
} else { *disk_snapshot = Some(snapshot);
*save_error = None;
*io_dirty = false; *io_dirty = false;
world
.resource_mut::<SceneIo>()
.set_status(format!("Saved project settings to {io_path}"));
}
Err(error) => {
warn!("Save project settings failed: {error}");
*save_error = Some(error.clone());
world
.resource_mut::<SceneIo>()
.set_status(format!("Save project settings failed: {error}"));
}
} }
} }
if ui.button("Revert from disk").clicked() { if ui.button("Revert from disk").clicked() {
*draft = load_project_settings_from_path(io_path); match read_project_settings_document(Path::new(io_path)) {
Ok((settings, source, snapshot)) => {
*draft = settings;
commit_project_settings(world, draft); commit_project_settings(world, draft);
world.resource_mut::<ProjectSettingsIo>().dirty = false; let mut io = world.resource_mut::<ProjectSettingsIo>();
io.dirty = false;
io.loaded_source = Some(source);
*disk_snapshot = Some(snapshot);
*save_error = None;
*io_dirty = false; *io_dirty = false;
} }
Err(error) => {
*save_error = Some(error.clone());
world
.resource_mut::<SceneIo>()
.set_status(format!("Revert project settings failed: {error}"));
}
}
}
if *io_dirty { if *io_dirty {
ui.label(egui::RichText::new("Unsaved changes").color(egui::Color32::YELLOW)); ui.label(egui::RichText::new("Unsaved changes").color(egui::Color32::YELLOW));
} }
} }
fn persist_project_settings(
world: &mut World,
settings: &ProjectSettings,
expected: &FileSnapshot,
) -> Result<(FileSnapshot, String), String> {
let path = world.resource::<ProjectSettingsIo>().path.clone();
let source = save_project_settings_to_string(settings).map_err(|error| error.to_string())?;
let snapshot = publish_authored_file(
world,
Path::new(&path),
source.as_bytes(),
expected,
FileWriteIntent::ProjectSettings,
)?;
Ok((snapshot, source))
}
fn read_project_settings_document(
path: &Path,
) -> Result<(ProjectSettings, String, FileSnapshot), String> {
let source = std::fs::read_to_string(path)
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
let settings: ProjectSettings = ron::from_str(&source)
.map_err(|error| format!("invalid project settings in {}: {error}", path.display()))?;
let snapshot = FileSnapshot::from_loaded_bytes(path, source.as_bytes());
Ok((settings, source, snapshot))
}
pub(crate) fn reload_project_settings_after_file_conflict(
world: &mut World,
path: &Path,
) -> Result<String, String> {
let active_path = world.resource::<ProjectSettingsIo>().path.clone();
if Path::new(&active_path) != path {
return Err("the project settings conflict no longer matches the active manifest".into());
}
let (settings, source, snapshot) = read_project_settings_document(path)?;
commit_project_settings(world, &settings);
{
let mut io = world.resource_mut::<ProjectSettingsIo>();
io.dirty = false;
io.loaded_source = Some(source);
}
{
let mut panel = world.resource_mut::<ProjectSettingsPanel>();
panel.draft = Some(settings);
panel.disk_snapshot = Some(snapshot);
panel.save_error = None;
}
Ok(format!("Reloaded project settings from {}", path.display()))
}
pub(crate) fn project_settings_conflict_copy_saved(world: &mut World) {
world.resource_mut::<ProjectSettingsPanel>().save_error = None;
}
fn commit_project_settings(world: &mut World, draft: &ProjectSettings) { fn commit_project_settings(world: &mut World, draft: &ProjectSettings) {
let previous = world.resource::<ProjectSettings>().rendering.gi_mode; let previous = world.resource::<ProjectSettings>().rendering.gi_mode;
*world.resource_mut::<ProjectSettings>() = draft.clone(); *world.resource_mut::<ProjectSettings>() = draft.clone();
@@ -406,3 +549,35 @@ fn apply_project_settings_changes(
// Full stack refresh runs next frame via `render_view::sync_project_render_view` // Full stack refresh runs next frame via `render_view::sync_project_render_view`
// when `ProjectSettings` changes. // when `ProjectSettings` changes.
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn project_settings_save_refuses_an_external_revision() {
let root = std::env::temp_dir().join(format!(
"blacksite-project-settings-external-write-{}",
uuid::Uuid::new_v4()
));
let path = root.join("assets/project.ron");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let loaded = save_project_settings_to_string(&ProjectSettings::default()).unwrap();
std::fs::write(&path, &loaded).unwrap();
let expected = FileSnapshot::from_loaded_bytes(&path, loaded.as_bytes());
let mut world = World::new();
world.insert_resource(ProjectSettingsIo {
path: path.to_string_lossy().into_owned(),
loaded_source: Some(loaded),
..Default::default()
});
world.insert_resource(SceneIo::default());
std::fs::write(&path, b"external").unwrap();
let result = persist_project_settings(&mut world, &ProjectSettings::default(), &expected);
assert!(result.unwrap_err().contains("changed outside Blacksite"));
assert_eq!(std::fs::read(&path).unwrap(), b"external");
std::fs::remove_dir_all(root).unwrap();
}
}
+752
View File
@@ -0,0 +1,752 @@
//! Guarded editor shutdown and the handoff to scene persistence.
use bevy::app::{AppExit, MainScheduleOrder};
use bevy::ecs::schedule::ScheduleLabel;
use bevy::prelude::*;
use bevy::window::{PrimaryWindow, WindowCloseRequested};
use crate::native_dialog::NativeDialogBroker;
use crate::scene_io::SceneIo;
const SAVE_ALL_LABEL: &str = "Save All";
const DISCARD_LABEL: &str = "Discard";
const CANCEL_LABEL: &str = "Cancel";
/// The user or editor surface that initiated a guarded shutdown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShutdownSource {
NativeWindow,
FileMenu,
Programmatic,
SwitchProject,
}
/// Observable state of the single editor shutdown flow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ShutdownIntent {
#[default]
Idle,
WaitingForBroker {
source: ShutdownSource,
},
Confirming {
source: ShutdownSource,
},
Saving {
source: ShutdownSource,
},
Authorized {
source: ShutdownSource,
require_clean_scenes: bool,
},
ExitSent {
source: ShutdownSource,
},
}
impl ShutdownIntent {
pub fn source(self) -> Option<ShutdownSource> {
match self {
Self::Idle => None,
Self::WaitingForBroker { source }
| Self::Confirming { source }
| Self::Saving { source }
| Self::Authorized { source, .. }
| Self::ExitSent { source } => Some(source),
}
}
}
/// Coordinates all editor exit requests so only an authorized flow emits [`AppExit`].
#[derive(Resource, Debug, Default)]
pub struct ShutdownCoordinator {
intent: ShutdownIntent,
coalesced_requests: u32,
last_blocker: Option<String>,
}
impl ShutdownCoordinator {
pub fn intent(&self) -> ShutdownIntent {
self.intent
}
pub fn coalesced_requests(&self) -> u32 {
self.coalesced_requests
}
pub fn last_blocker(&self) -> Option<&str> {
self.last_blocker.as_deref()
}
pub fn authorized_exit_sent(&self) -> bool {
matches!(self.intent, ShutdownIntent::ExitSent { .. })
}
/// Queue a shutdown if no shutdown flow is already active.
///
/// Repeated window, menu, or programmatic requests are coalesced until the
/// current flow is cancelled, fails to save, or sends the authorized exit.
pub fn request(&mut self, source: ShutdownSource) -> bool {
if self.intent != ShutdownIntent::Idle {
self.coalesced_requests = self.coalesced_requests.saturating_add(1);
return false;
}
self.intent = ShutdownIntent::WaitingForBroker { source };
self.coalesced_requests = 0;
self.last_blocker = None;
true
}
#[cfg(test)]
pub(crate) fn set_intent_for_test(&mut self, intent: ShutdownIntent) {
self.intent = intent;
}
}
/// Emitted once when the guarded dialog chooses `Save All`.
///
/// Scene persistence owns the actual save sequence and must finish it with
/// [`complete_shutdown_save`].
#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
pub struct ShutdownSaveAllRequested {
pub source: ShutdownSource,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShutdownSaveOutcome {
Saved,
Cancelled,
Failed(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShutdownDecision {
SaveAll,
Discard,
Cancel,
}
/// Runs after Bevy's `Last` schedule so no editor authoring system can mutate
/// a document after the final dirty-state check in the same frame.
#[derive(ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
pub struct EditorShutdownFinalize;
/// Queue a guarded shutdown from an exclusive-world UI or workflow callback.
pub fn request_editor_shutdown(world: &mut World, source: ShutdownSource) -> bool {
world
.get_resource_mut::<ShutdownCoordinator>()
.is_some_and(|mut coordinator| coordinator.request(source))
}
/// Queue a project-browser handoff through the same dirty-document guard as editor exit.
pub fn request_project_switch(world: &mut World) -> bool {
request_editor_shutdown(world, ShutdownSource::SwitchProject)
}
/// Resolve the dirty-scene confirmation through the shared coordinator.
pub fn resolve_shutdown_decision(world: &mut World, decision: ShutdownDecision) -> bool {
let (save_request, status) = {
let Some(mut coordinator) = world.get_resource_mut::<ShutdownCoordinator>() else {
return false;
};
let ShutdownIntent::Confirming { source } = coordinator.intent else {
return false;
};
match decision {
ShutdownDecision::SaveAll => {
coordinator.intent = ShutdownIntent::Saving { source };
(
Some(source),
Some("Saving all modified scene tabs before shutdown"),
)
}
ShutdownDecision::Discard => {
coordinator.intent = ShutdownIntent::Authorized {
source,
require_clean_scenes: false,
};
(None, None)
}
ShutdownDecision::Cancel => {
coordinator.intent = ShutdownIntent::Idle;
(
None,
Some("Shutdown cancelled; unsaved scene tabs retained"),
)
}
}
};
if let Some(status) = status {
if let Some(mut scene_io) = world.get_resource_mut::<SceneIo>() {
scene_io.set_status(status);
}
}
if let Some(source) = save_request {
world.write_message(ShutdownSaveAllRequested { source });
}
true
}
/// Finish the save-all handoff. A reported success is authorized only after
/// every scene tab is observably clean.
pub fn complete_shutdown_save(world: &mut World, outcome: ShutdownSaveOutcome) -> bool {
let scenes_are_clean = !scene_has_unsaved_changes(world);
let Some(mut coordinator) = world.get_resource_mut::<ShutdownCoordinator>() else {
return false;
};
let ShutdownIntent::Saving { source } = coordinator.intent else {
return false;
};
match outcome {
ShutdownSaveOutcome::Saved if scenes_are_clean => {
coordinator.intent = ShutdownIntent::Authorized {
source,
require_clean_scenes: true,
};
coordinator.last_blocker = None;
true
}
ShutdownSaveOutcome::Saved => {
coordinator.intent = ShutdownIntent::Idle;
coordinator.last_blocker =
Some("Save All completed while unsaved scene tabs remain".into());
false
}
ShutdownSaveOutcome::Cancelled => {
coordinator.intent = ShutdownIntent::Idle;
coordinator.last_blocker = None;
false
}
ShutdownSaveOutcome::Failed(error) => {
coordinator.intent = ShutdownIntent::Idle;
coordinator.last_blocker = Some(error);
false
}
}
}
pub struct ShutdownPlugin;
impl Plugin for ShutdownPlugin {
fn build(&self, app: &mut App) {
app.init_schedule(EditorShutdownFinalize);
app.world_mut()
.resource_mut::<MainScheduleOrder>()
.insert_after(Last, EditorShutdownFinalize);
app.init_resource::<ShutdownCoordinator>()
.add_message::<ShutdownSaveAllRequested>()
.add_systems(
Update,
(capture_native_close_requests, drive_shutdown).chain(),
)
.add_systems(EditorShutdownFinalize, finalize_authorized_shutdown);
}
}
fn capture_native_close_requests(
mut commands: Commands,
mut close_requests: MessageReader<WindowCloseRequested>,
primary_window: Query<Entity, With<PrimaryWindow>>,
mut coordinator: ResMut<ShutdownCoordinator>,
) {
let Ok(primary_window) = primary_window.single() else {
return;
};
for request in close_requests.read() {
if request.window == primary_window {
coordinator.request(ShutdownSource::NativeWindow);
} else {
commands.entity(request.window).despawn();
}
}
}
fn drive_shutdown(world: &mut World) {
let intent = world.resource::<ShutdownCoordinator>().intent;
match intent {
ShutdownIntent::Idle
| ShutdownIntent::Confirming { .. }
| ShutdownIntent::Saving { .. }
| ShutdownIntent::ExitSent { .. } => {}
ShutdownIntent::WaitingForBroker { source } => {
let unsaved_count = unsaved_scene_count(world);
if unsaved_count == 0 {
world.resource_mut::<ShutdownCoordinator>().intent = ShutdownIntent::Authorized {
source,
require_clean_scenes: true,
};
return;
}
if world.resource::<NativeDialogBroker>().is_pending() {
return;
}
let action = if source == ShutdownSource::SwitchProject {
"switching projects"
} else {
"quitting"
};
let description = if unsaved_count == 1 {
format!("One scene tab has unsaved changes. Save it before {action}?")
} else {
format!(
"{unsaved_count} scene tabs have unsaved changes. Save all before {action}?"
)
};
let title = if source == ShutdownSource::SwitchProject {
"Switch Project"
} else {
"Quit Blacksite Editor"
};
let request = world.resource::<NativeDialogBroker>().request(
move || {
rfd::MessageDialog::new()
.set_title(title)
.set_description(description)
.set_level(rfd::MessageLevel::Warning)
.set_buttons(rfd::MessageButtons::YesNoCancelCustom(
SAVE_ALL_LABEL.into(),
DISCARD_LABEL.into(),
CANCEL_LABEL.into(),
))
.show()
},
|world, result| {
resolve_shutdown_decision(world, decision_from_dialog(result));
},
);
if request.is_ok() {
world.resource_mut::<ShutdownCoordinator>().intent =
ShutdownIntent::Confirming { source };
}
}
ShutdownIntent::Authorized { .. } => {}
}
}
/// Final dirty-state recheck after editor UI and authoring schedules have completed.
pub(crate) fn finalize_authorized_shutdown(world: &mut World) {
let (source, require_clean_scenes) = {
let coordinator = world.resource::<ShutdownCoordinator>();
let ShutdownIntent::Authorized {
source,
require_clean_scenes,
} = coordinator.intent
else {
return;
};
(source, require_clean_scenes)
};
if require_clean_scenes && scene_has_unsaved_changes(world) {
world.resource_mut::<ShutdownCoordinator>().intent =
ShutdownIntent::WaitingForBroker { source };
return;
}
if source == ShutdownSource::SwitchProject {
if let Err(error) = crate::launcher::spawn_project_launcher_process() {
let message = format!("Switch project failed: {error}");
{
let mut coordinator = world.resource_mut::<ShutdownCoordinator>();
coordinator.intent = ShutdownIntent::Idle;
coordinator.last_blocker = Some(message.clone());
}
if let Some(mut scene_io) = world.get_resource_mut::<SceneIo>() {
scene_io.set_status(message);
}
return;
}
}
world.resource_mut::<ShutdownCoordinator>().intent = ShutdownIntent::ExitSent { source };
debug!(?source, "Editor shutdown authorized");
world.write_message(AppExit::Success);
}
fn scene_has_unsaved_changes(world: &World) -> bool {
world
.get_resource::<SceneIo>()
.is_some_and(SceneIo::has_unsaved_tabs)
}
fn unsaved_scene_count(world: &World) -> usize {
let Some(scene_io) = world.get_resource::<SceneIo>() else {
return 0;
};
let tab_count = scene_io.tabs.iter().filter(|tab| tab.dirty).count();
if scene_io.dirty
&& scene_io
.tabs
.get(scene_io.active_tab)
.is_none_or(|tab| !tab.dirty)
{
tab_count + 1
} else {
tab_count
}
}
fn decision_from_dialog(result: rfd::MessageDialogResult) -> ShutdownDecision {
match result {
rfd::MessageDialogResult::Custom(label) if label == SAVE_ALL_LABEL => {
ShutdownDecision::SaveAll
}
rfd::MessageDialogResult::Custom(label) if label == DISCARD_LABEL => {
ShutdownDecision::Discard
}
rfd::MessageDialogResult::Yes => ShutdownDecision::SaveAll,
rfd::MessageDialogResult::No => ShutdownDecision::Discard,
_ => ShutdownDecision::Cancel,
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use bevy::ecs::message::MessageCursor;
use super::*;
use crate::native_dialog::NativeDialogPlugin;
fn confirming_world() -> World {
let mut world = World::new();
world.init_resource::<Messages<ShutdownSaveAllRequested>>();
world.insert_resource(ShutdownCoordinator {
intent: ShutdownIntent::Confirming {
source: ShutdownSource::FileMenu,
},
..default()
});
world
}
#[test]
fn repeated_requests_are_coalesced_behind_the_first_source() {
let mut coordinator = ShutdownCoordinator::default();
assert!(coordinator.request(ShutdownSource::NativeWindow));
assert!(!coordinator.request(ShutdownSource::FileMenu));
assert_eq!(coordinator.coalesced_requests(), 1);
assert_eq!(
coordinator.intent(),
ShutdownIntent::WaitingForBroker {
source: ShutdownSource::NativeWindow
}
);
}
#[test]
fn cancel_returns_to_idle_and_discard_authorizes_exit() {
let mut cancel_world = confirming_world();
assert!(resolve_shutdown_decision(
&mut cancel_world,
ShutdownDecision::Cancel
));
assert_eq!(
cancel_world.resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::Idle
);
let mut discard_world = confirming_world();
assert!(resolve_shutdown_decision(
&mut discard_world,
ShutdownDecision::Discard
));
assert_eq!(
discard_world.resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::Authorized {
source: ShutdownSource::FileMenu,
require_clean_scenes: false,
}
);
}
#[test]
fn dirty_cancel_preserves_the_session_and_discard_emits_one_exit() {
let mut app = App::new();
app.add_message::<AppExit>()
.init_resource::<SceneIo>()
.init_resource::<ShutdownCoordinator>();
app.world_mut().resource_mut::<SceneIo>().mark_dirty();
app.world_mut()
.resource_mut::<ShutdownCoordinator>()
.set_intent_for_test(ShutdownIntent::Confirming {
source: ShutdownSource::Programmatic,
});
assert!(resolve_shutdown_decision(
app.world_mut(),
ShutdownDecision::Cancel
));
drive_shutdown(app.world_mut());
finalize_authorized_shutdown(app.world_mut());
assert_eq!(app.should_exit(), None);
assert!(app.world().resource::<SceneIo>().has_unsaved_tabs());
app.world_mut()
.resource_mut::<ShutdownCoordinator>()
.set_intent_for_test(ShutdownIntent::Confirming {
source: ShutdownSource::Programmatic,
});
assert!(resolve_shutdown_decision(
app.world_mut(),
ShutdownDecision::Discard
));
drive_shutdown(app.world_mut());
finalize_authorized_shutdown(app.world_mut());
assert_eq!(app.should_exit(), Some(AppExit::Success));
assert!(app.world().resource::<SceneIo>().has_unsaved_tabs());
assert!(app
.world()
.resource::<ShutdownCoordinator>()
.authorized_exit_sent());
}
#[test]
fn file_menu_and_programmatic_clean_exit_use_the_same_coordinator_path() {
for source in [ShutdownSource::FileMenu, ShutdownSource::Programmatic] {
let mut app = App::new();
app.add_message::<AppExit>()
.init_resource::<SceneIo>()
.init_resource::<ShutdownCoordinator>()
.init_resource::<NativeDialogBroker>();
assert!(request_editor_shutdown(app.world_mut(), source));
drive_shutdown(app.world_mut());
finalize_authorized_shutdown(app.world_mut());
assert_eq!(app.should_exit(), Some(AppExit::Success));
assert_eq!(
app.world().resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::ExitSent { source }
);
}
}
#[test]
fn save_all_emits_one_persistence_handoff() {
let mut world = confirming_world();
let mut cursor = MessageCursor::<ShutdownSaveAllRequested>::default();
assert!(resolve_shutdown_decision(
&mut world,
ShutdownDecision::SaveAll
));
assert!(!resolve_shutdown_decision(
&mut world,
ShutdownDecision::SaveAll
));
let messages = world.resource::<Messages<ShutdownSaveAllRequested>>();
let requests: Vec<_> = cursor.read(messages).copied().collect();
assert_eq!(
requests,
vec![ShutdownSaveAllRequested {
source: ShutdownSource::FileMenu
}]
);
}
#[test]
fn clean_native_close_emits_the_authorized_exit() {
let mut app = App::new();
app.add_message::<WindowCloseRequested>()
.add_plugins((NativeDialogPlugin, ShutdownPlugin))
.init_resource::<SceneIo>();
let window = app.world_mut().spawn(PrimaryWindow).id();
app.world_mut()
.write_message(WindowCloseRequested { window });
app.update();
assert_eq!(app.should_exit(), Some(AppExit::Success));
assert_eq!(
app.world().resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::ExitSent {
source: ShutdownSource::NativeWindow
}
);
}
#[test]
fn secondary_window_close_does_not_request_editor_shutdown() {
let mut app = App::new();
app.add_message::<WindowCloseRequested>()
.add_plugins((NativeDialogPlugin, ShutdownPlugin))
.init_resource::<SceneIo>();
app.world_mut().spawn(PrimaryWindow);
let secondary = app.world_mut().spawn_empty().id();
app.world_mut()
.write_message(WindowCloseRequested { window: secondary });
app.update();
assert_eq!(app.should_exit(), None);
assert_eq!(
app.world().resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::Idle
);
assert!(app.world().get_entity(secondary).is_err());
}
#[test]
fn occupied_dialog_broker_keeps_shutdown_waiting() {
let mut app = App::new();
app.add_message::<WindowCloseRequested>()
.add_plugins((NativeDialogPlugin, ShutdownPlugin))
.init_resource::<SceneIo>();
app.world_mut().resource_mut::<SceneIo>().mark_dirty();
let (release_sender, release_receiver) = mpsc::channel();
app.world()
.resource::<NativeDialogBroker>()
.request(
move || release_receiver.recv().expect("release sender dropped"),
|_, _: ()| {},
)
.unwrap();
assert!(request_editor_shutdown(
app.world_mut(),
ShutdownSource::Programmatic
));
app.update();
assert_eq!(
app.world().resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::WaitingForBroker {
source: ShutdownSource::Programmatic
}
);
release_sender.send(()).unwrap();
}
#[test]
fn successful_save_requires_every_scene_tab_to_be_clean() {
let mut world = World::new();
world.init_resource::<SceneIo>();
world.insert_resource(ShutdownCoordinator {
intent: ShutdownIntent::Saving {
source: ShutdownSource::Programmatic,
},
..default()
});
assert!(complete_shutdown_save(
&mut world,
ShutdownSaveOutcome::Saved
));
assert_eq!(
world.resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::Authorized {
source: ShutdownSource::Programmatic,
require_clean_scenes: true,
}
);
world.resource_mut::<SceneIo>().mark_dirty();
world.resource_mut::<ShutdownCoordinator>().intent = ShutdownIntent::Saving {
source: ShutdownSource::Programmatic,
};
assert!(!complete_shutdown_save(
&mut world,
ShutdownSaveOutcome::Saved
));
assert_eq!(
world.resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::Idle
);
assert!(world
.resource::<ShutdownCoordinator>()
.last_blocker()
.is_some());
}
#[test]
fn a_new_edit_after_save_reopens_the_guard_instead_of_exiting() {
let mut world = World::new();
world.init_resource::<Messages<AppExit>>();
world.init_resource::<SceneIo>();
world.insert_resource(ShutdownCoordinator {
intent: ShutdownIntent::Authorized {
source: ShutdownSource::Programmatic,
require_clean_scenes: true,
},
..default()
});
world.resource_mut::<SceneIo>().mark_dirty();
finalize_authorized_shutdown(&mut world);
assert_eq!(
world.resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::WaitingForBroker {
source: ShutdownSource::Programmatic
}
);
let messages = world.resource::<Messages<AppExit>>();
assert_eq!(
MessageCursor::<AppExit>::default().read(messages).count(),
0
);
}
#[test]
fn last_schedule_edit_is_seen_before_final_exit_authorization() {
let mut app = App::new();
app.add_message::<WindowCloseRequested>()
.add_plugins((NativeDialogPlugin, ShutdownPlugin))
.init_resource::<SceneIo>()
.add_systems(Last, |mut scene_io: ResMut<SceneIo>| {
scene_io.mark_dirty();
});
assert!(request_editor_shutdown(
app.world_mut(),
ShutdownSource::Programmatic
));
app.update();
assert_eq!(app.should_exit(), None);
assert!(app.world().resource::<SceneIo>().has_unsaved_tabs());
assert_eq!(
app.world().resource::<ShutdownCoordinator>().intent(),
ShutdownIntent::WaitingForBroker {
source: ShutdownSource::Programmatic
}
);
}
#[test]
fn custom_dialog_labels_map_to_shutdown_decisions() {
assert_eq!(
decision_from_dialog(rfd::MessageDialogResult::Custom(SAVE_ALL_LABEL.into())),
ShutdownDecision::SaveAll
);
assert_eq!(
decision_from_dialog(rfd::MessageDialogResult::Custom(DISCARD_LABEL.into())),
ShutdownDecision::Discard
);
assert_eq!(
decision_from_dialog(rfd::MessageDialogResult::Custom(CANCEL_LABEL.into())),
ShutdownDecision::Cancel
);
}
#[test]
fn only_the_final_coordinator_state_authorizes_clean_session_persistence() {
let mut coordinator = ShutdownCoordinator::default();
assert!(!coordinator.authorized_exit_sent());
coordinator.intent = ShutdownIntent::Authorized {
source: ShutdownSource::Programmatic,
require_clean_scenes: true,
};
assert!(!coordinator.authorized_exit_sent());
coordinator.intent = ShutdownIntent::ExitSent {
source: ShutdownSource::Programmatic,
};
assert!(coordinator.authorized_exit_sent());
}
}
+16 -10
View File
@@ -13,17 +13,20 @@ pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
atomic_write_with_pre_rename(path, bytes, || Ok(())) atomic_write_with_pre_rename(path, bytes, || Ok(()))
} }
fn atomic_write_with_pre_rename( pub(crate) fn atomic_write_with_pre_rename<E>(
path: &Path, path: &Path,
bytes: &[u8], bytes: &[u8],
before_rename: impl FnOnce() -> Result<(), String>, before_rename: impl FnOnce() -> Result<(), E>,
) -> Result<(), String> { ) -> Result<(), E>
where
E: From<String>,
{
let parent = path let parent = path
.parent() .parent()
.filter(|parent| !parent.as_os_str().is_empty()) .filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new(".")); .unwrap_or_else(|| Path::new("."));
fs::create_dir_all(parent) fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?; .map_err(|error| E::from(format!("could not create {}: {error}", parent.display())))?;
let file_name = path let file_name = path
.file_name() .file_name()
@@ -40,18 +43,21 @@ fn atomic_write_with_pre_rename(
.create_new(true) .create_new(true)
.write(true) .write(true)
.open(&temporary) .open(&temporary)
.map_err(|error| format!("could not create {}: {error}", temporary.display()))?; .map_err(|error| {
file.write_all(bytes) E::from(format!("could not create {}: {error}", temporary.display()))
.map_err(|error| format!("could not write {}: {error}", temporary.display()))?; })?;
file.write_all(bytes).map_err(|error| {
E::from(format!("could not write {}: {error}", temporary.display()))
})?;
file.sync_all() file.sync_all()
.map_err(|error| format!("could not sync {}: {error}", temporary.display()))?; .map_err(|error| E::from(format!("could not sync {}: {error}", temporary.display())))?;
before_rename()?; before_rename()?;
fs::rename(&temporary, path).map_err(|error| { fs::rename(&temporary, path).map_err(|error| {
format!( E::from(format!(
"could not replace {} with {}: {error}", "could not replace {} with {}: {error}",
path.display(), path.display(),
temporary.display() temporary.display()
) ))
})?; })?;
sync_parent_directory(parent); sync_parent_directory(parent);
Ok(()) Ok(())
File diff suppressed because it is too large. Load diff
@@ -112,6 +112,7 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
ActorKind::StaticMesh ActorKind::StaticMesh
| ActorKind::SkinnedMesh | ActorKind::SkinnedMesh
| ActorKind::Brush | ActorKind::Brush
| ActorKind::Terrain
| ActorKind::ImportedModel | ActorKind::ImportedModel
| ActorKind::Light | ActorKind::Light
| ActorKind::Empty | ActorKind::Empty
@@ -143,6 +144,7 @@ fn actor_icon(kind: ActorKind) -> egui_phosphor_icons::Icon {
ActorKind::StaticMesh ActorKind::StaticMesh
| ActorKind::SkinnedMesh | ActorKind::SkinnedMesh
| ActorKind::Brush | ActorKind::Brush
| ActorKind::Terrain
| ActorKind::ImportedModel => icons::CUBE, | ActorKind::ImportedModel => icons::CUBE,
ActorKind::Light => icons::LIGHTBULB, ActorKind::Light => icons::LIGHTBULB,
ActorKind::PrefabAnchor => icons::PACKAGE, ActorKind::PrefabAnchor => icons::PACKAGE,
@@ -884,7 +884,6 @@ mod tests {
format: "glb".into(), format: "glb".into(),
fingerprint: AnimationSourceFingerprint { fingerprint: AnimationSourceFingerprint {
byte_len: 42, byte_len: 42,
modified_unix_secs: 1,
content_hash: "hash".into(), content_hash: "hash".into(),
}, },
dependencies: Vec::new(), dependencies: Vec::new(),
+241 -16
View File
@@ -20,6 +20,10 @@ use crate::assets::{
AssetSelection, AssetSubAssetKind, EditorAsset, EditorAssetKind, EditorAssets, ASSETS_ROOT, AssetSelection, AssetSubAssetKind, EditorAsset, EditorAssetKind, EditorAssets, ASSETS_ROOT,
BUILTINS_FOLDER, BUILTINS_FOLDER,
}; };
use crate::project::collaboration::{
file_status_indicator_ui, publish_authored_file, CollaborationState, FileSnapshot,
FileWriteIntent,
};
use crate::scene_io::{SceneIo, SceneIoRequest}; use crate::scene_io::{SceneIo, SceneIoRequest};
use super::state::{ use super::state::{
@@ -1851,13 +1855,13 @@ 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, world: &mut World,
ui: &mut egui::Ui, ui: &mut egui::Ui,
selected_entities: &SelectedEntities, selected_entities: &SelectedEntities,
asset: &EditorAsset, asset: &EditorAsset,
) { ) {
asset_details_header(ui, asset); asset_details_header(world, ui, asset);
ui.add_space(8.0); ui.add_space(8.0);
detail_row(ui, "Path", asset.path.as_deref().unwrap_or("Built-in")); detail_row(ui, "Path", asset.path.as_deref().unwrap_or("Built-in"));
detail_row(ui, "Folder", asset.folder_path.as_str()); detail_row(ui, "Folder", asset.folder_path.as_str());
@@ -1946,7 +1950,7 @@ fn top_level_asset_details_panel(
asset_action_buttons(world, ui, selected_entities, asset); asset_action_buttons(world, ui, selected_entities, asset);
} }
fn asset_details_header(ui: &mut egui::Ui, asset: &EditorAsset) { fn asset_details_header(world: &World, ui: &mut egui::Ui, asset: &EditorAsset) {
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
ui.label( ui.label(
egui::RichText::new(kind_icon(&asset.kind).as_str()) egui::RichText::new(kind_icon(&asset.kind).as_str())
@@ -1959,6 +1963,13 @@ fn asset_details_header(ui: &mut egui::Ui, asset: &EditorAsset) {
ui.vertical(|ui| { ui.vertical(|ui| {
ui.strong(asset.label.as_str()); ui.strong(asset.label.as_str());
ui.small(egui::RichText::new(kind_label(&asset.kind)).color(TEXT_DIM)); ui.small(egui::RichText::new(kind_label(&asset.kind)).color(TEXT_DIM));
if let (Some(state), Some(path)) = (
world.get_resource::<CollaborationState>(),
asset.path.as_deref(),
) {
let status = state.file_status(Path::new(path));
let _ = file_status_indicator_ui(ui, &status, Path::new(path));
}
}); });
}); });
} }
@@ -2434,10 +2445,19 @@ fn ensure_material_draft(world: &mut World, path: &str, fallback_label: &str) {
if !needs_load { if !needs_load {
return; return;
} }
let draft = match MaterialAsset::load_from_path(path) { let loaded = fs::read_to_string(path)
Ok(asset) => MaterialAssetDraft { .map_err(|error| format!("could not read {path}: {error}"))
.and_then(|text| {
let snapshot = FileSnapshot::from_loaded_bytes(Path::new(path), text.as_bytes());
ron::from_str::<MaterialAsset>(&text)
.map(|asset| (asset, snapshot))
.map_err(|error| format!("invalid material RON in {path}: {error}"))
});
let draft = match loaded {
Ok((asset, disk_snapshot)) => MaterialAssetDraft {
path: path.to_string(), path: path.to_string(),
asset, asset,
disk_snapshot,
error: None, error: None,
}, },
Err(error) => MaterialAssetDraft { Err(error) => MaterialAssetDraft {
@@ -2450,6 +2470,8 @@ fn ensure_material_draft(world: &mut World, path: &str, fallback_label: &str) {
render_state: shared::MaterialRenderState::default(), render_state: shared::MaterialRenderState::default(),
material: MaterialDesc::default(), material: MaterialDesc::default(),
}, },
disk_snapshot: FileSnapshot::capture(Path::new(path))
.unwrap_or_else(|_| FileSnapshot::missing()),
error: Some(error), error: Some(error),
}, },
}; };
@@ -2467,17 +2489,23 @@ fn save_material_draft(world: &mut World) {
let result = ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default()) let result = ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize material {}: {error}", draft.path)) .map_err(|error| format!("could not serialize material {}: {error}", draft.path))
.and_then(|text| { .and_then(|text| {
fs::write(&draft.path, text) publish_authored_file(
.map_err(|error| format!("could not write material {}: {error}", draft.path)) world,
Path::new(&draft.path),
text.as_bytes(),
&draft.disk_snapshot,
FileWriteIntent::Material,
)
}); });
match result { match result {
Ok(()) => { Ok(disk_snapshot) => {
if let Some(current) = world if let Some(current) = world
.resource_mut::<AssetBrowserUiState>() .resource_mut::<AssetBrowserUiState>()
.material_draft .material_draft
.as_mut() .as_mut()
{ {
current.error = None; current.error = None;
current.disk_snapshot = disk_snapshot;
} }
world.resource_mut::<EditorAssets>().refresh(); world.resource_mut::<EditorAssets>().refresh();
invalidate_on_catalog_refresh(world); invalidate_on_catalog_refresh(world);
@@ -2496,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 let base_reference = world
.get_resource_mut::<crate::asset_db::AssetRegistry>() .get_resource_mut::<crate::asset_db::AssetRegistry>()
.ok_or_else(|| "Asset registry is unavailable".to_string()) .ok_or_else(|| "Asset registry is unavailable".to_string())
@@ -2556,8 +2588,13 @@ fn create_material_instance_from_base(world: &mut World, base_path: &str, base_l
let result = ron::ser::to_string_pretty(&instance, ron::ser::PrettyConfig::default()) let result = ron::ser::to_string_pretty(&instance, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize material instance: {error}")) .map_err(|error| format!("could not serialize material instance: {error}"))
.and_then(|text| { .and_then(|text| {
fs::write(&path, text) publish_authored_file(
.map_err(|error| format!("could not write {}: {error}", path.display())) world,
&path,
text.as_bytes(),
&FileSnapshot::missing(),
FileWriteIntent::MaterialInstance,
)
}); });
if let Err(error) = result { if let Err(error) = result {
world.resource_mut::<SceneIo>().status = error; world.resource_mut::<SceneIo>().status = error;
@@ -2845,10 +2882,19 @@ fn ensure_material_instance_draft(world: &mut World, path: &str, fallback_label:
if !needs_load { if !needs_load {
return; return;
} }
let draft = match MaterialInstanceAsset::load_from_path(path) { let loaded = fs::read_to_string(path)
Ok(asset) => MaterialInstanceAssetDraft { .map_err(|error| format!("could not read {path}: {error}"))
.and_then(|text| {
let snapshot = FileSnapshot::from_loaded_bytes(Path::new(path), text.as_bytes());
ron::from_str::<MaterialInstanceAsset>(&text)
.map(|asset| (asset, snapshot))
.map_err(|error| format!("invalid material-instance RON in {path}: {error}"))
});
let draft = match loaded {
Ok((asset, disk_snapshot)) => MaterialInstanceAssetDraft {
path: path.to_string(), path: path.to_string(),
asset, asset,
disk_snapshot,
error: None, error: None,
}, },
Err(error) => MaterialInstanceAssetDraft { Err(error) => MaterialInstanceAssetDraft {
@@ -2860,6 +2906,8 @@ fn ensure_material_instance_draft(world: &mut World, path: &str, fallback_label:
parameters: Vec::new(), parameters: Vec::new(),
textures: Vec::new(), textures: Vec::new(),
}, },
disk_snapshot: FileSnapshot::capture(Path::new(path))
.unwrap_or_else(|_| FileSnapshot::missing()),
error: Some(error), error: Some(error),
}, },
}; };
@@ -2884,18 +2932,24 @@ fn save_material_instance_draft(world: &mut World) {
ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default()) ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize material instance: {error}")) .map_err(|error| format!("could not serialize material instance: {error}"))
.and_then(|text| { .and_then(|text| {
fs::write(&draft.path, text) publish_authored_file(
.map_err(|error| format!("could not write {}: {error}", draft.path)) world,
Path::new(&draft.path),
text.as_bytes(),
&draft.disk_snapshot,
FileWriteIntent::MaterialInstance,
)
}) })
}; };
match result { match result {
Ok(()) => { Ok(disk_snapshot) => {
if let Some(current) = world if let Some(current) = world
.resource_mut::<AssetBrowserUiState>() .resource_mut::<AssetBrowserUiState>()
.material_instance_draft .material_instance_draft
.as_mut() .as_mut()
{ {
current.error = None; current.error = None;
current.disk_snapshot = disk_snapshot;
} }
world.resource_mut::<EditorAssets>().refresh(); world.resource_mut::<EditorAssets>().refresh();
invalidate_on_catalog_refresh(world); invalidate_on_catalog_refresh(world);
@@ -4380,10 +4434,181 @@ fn dedup_strings(values: &mut Vec<String>) {
values.retain(|value| seen.insert(value.clone())); values.retain(|value| seen.insert(value.clone()));
} }
pub(crate) fn validate_material_conflict_destination(
world: &World,
destination: &Path,
) -> Result<String, String> {
let root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
let root = root.canonicalize().unwrap_or(root);
let absolute = if destination.is_absolute() {
destination.to_path_buf()
} else {
root.join(destination)
};
let absolute = absolute
.parent()
.and_then(|parent| parent.canonicalize().ok())
.and_then(|parent| destination.file_name().map(|name| parent.join(name)))
.unwrap_or(absolute);
let relative = absolute.strip_prefix(&root).map_err(|_| {
format!(
"Material assets must stay inside {}",
root.join("assets").display()
)
})?;
if !relative.starts_with("assets") {
return Err(format!(
"Material assets must stay inside {}",
root.join("assets").display()
));
}
Ok(relative.to_string_lossy().replace('\\', "/"))
}
pub(crate) fn reload_material_after_file_conflict(
world: &mut World,
path: &Path,
intent: &FileWriteIntent,
) -> Result<String, String> {
let path = path.to_string_lossy();
{
let mut state = world.resource_mut::<AssetBrowserUiState>();
match intent {
FileWriteIntent::Material => {
if state
.material_draft
.as_ref()
.is_some_and(|draft| draft.path == path)
{
state.material_draft = None;
}
}
FileWriteIntent::MaterialInstance => {
if state
.material_instance_draft
.as_ref()
.is_some_and(|draft| draft.path == path)
{
state.material_instance_draft = None;
}
}
_ => return Err("the conflict is not an editable material document".into()),
}
}
world.resource_mut::<EditorAssets>().refresh();
invalidate_on_catalog_refresh(world);
Ok(format!("Reloaded {} from disk", path))
}
pub(crate) fn adopt_material_conflict_save_as(
world: &mut World,
original_path: &Path,
catalog_path: String,
disk_snapshot: FileSnapshot,
intent: &FileWriteIntent,
) -> Result<String, String> {
let original_path = original_path.to_string_lossy();
{
let mut state = world.resource_mut::<AssetBrowserUiState>();
match intent {
FileWriteIntent::Material => {
if let Some(draft) = state
.material_draft
.as_mut()
.filter(|draft| draft.path == original_path)
{
draft.path.clone_from(&catalog_path);
draft.disk_snapshot = disk_snapshot;
draft.error = None;
} else {
let asset = MaterialAsset::load_from_path(&catalog_path)?;
state.material_draft = Some(MaterialAssetDraft {
path: catalog_path.clone(),
asset,
disk_snapshot,
error: None,
});
}
}
FileWriteIntent::MaterialInstance => {
if let Some(draft) = state
.material_instance_draft
.as_mut()
.filter(|draft| draft.path == original_path)
{
draft.path.clone_from(&catalog_path);
draft.disk_snapshot = disk_snapshot;
draft.error = None;
} else {
let asset = MaterialInstanceAsset::load_from_path(&catalog_path)?;
state.material_instance_draft = Some(MaterialInstanceAssetDraft {
path: catalog_path.clone(),
asset,
disk_snapshot,
error: None,
});
}
}
_ => return Err("the conflict is not an editable material document".into()),
}
}
{
let mut assets = world.resource_mut::<EditorAssets>();
assets.refresh();
assets.select(AssetSelection::File(catalog_path.clone()));
}
invalidate_on_catalog_refresh(world);
Ok(format!("Saved material copy to {catalog_path}"))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn material_apply_refuses_an_external_revision() {
let root = std::env::temp_dir().join(format!(
"blacksite-material-external-write-{}",
uuid::Uuid::new_v4()
));
let path = root.join("assets/materials/test.ron");
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, b"loaded").unwrap();
let disk_snapshot = FileSnapshot::capture(&path).unwrap();
let draft = MaterialAssetDraft {
path: path.to_string_lossy().into_owned(),
asset: MaterialAsset {
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
label: "Test".into(),
shader: None,
shader_ref: None,
render_state: shared::MaterialRenderState::default(),
material: MaterialDesc::default(),
},
disk_snapshot,
error: None,
};
let state = AssetBrowserUiState {
material_draft: Some(draft),
..Default::default()
};
let mut world = World::new();
world.insert_resource(state);
world.insert_resource(SceneIo::default());
fs::write(&path, b"external").unwrap();
save_material_draft(&mut world);
assert_eq!(fs::read(&path).unwrap(), b"external");
assert!(world
.resource::<AssetBrowserUiState>()
.material_draft
.as_ref()
.and_then(|draft| draft.error.as_deref())
.is_some_and(|error| error.contains("changed outside Blacksite")));
fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn audio_filter_matches_only_audio_clips() { fn audio_filter_matches_only_audio_clips() {
let audio = EditorAsset { let audio = EditorAsset {
@@ -7,6 +7,7 @@ use shared::{MaterialAsset, MaterialInstanceAsset};
use crate::asset_db::ImportSettings; use crate::asset_db::ImportSettings;
use crate::assets::{AssetSelection, ASSETS_ROOT, BUILTINS_FOLDER}; use crate::assets::{AssetSelection, ASSETS_ROOT, BUILTINS_FOLDER};
use crate::project::collaboration::FileSnapshot;
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AssetBrowserView { pub(crate) enum AssetBrowserView {
@@ -69,6 +70,7 @@ pub(crate) struct ImportSettingsDraft {
pub(crate) struct MaterialAssetDraft { pub(crate) struct MaterialAssetDraft {
pub(crate) path: String, pub(crate) path: String,
pub(crate) asset: MaterialAsset, pub(crate) asset: MaterialAsset,
pub(crate) disk_snapshot: FileSnapshot,
pub(crate) error: Option<String>, pub(crate) error: Option<String>,
} }
@@ -76,6 +78,7 @@ pub(crate) struct MaterialAssetDraft {
pub(crate) struct MaterialInstanceAssetDraft { pub(crate) struct MaterialInstanceAssetDraft {
pub(crate) path: String, pub(crate) path: String,
pub(crate) asset: MaterialInstanceAsset, pub(crate) asset: MaterialInstanceAsset,
pub(crate) disk_snapshot: FileSnapshot,
pub(crate) error: Option<String>, pub(crate) error: Option<String>,
} }
@@ -47,6 +47,11 @@ pub struct EditorComponentRegistry {
inspectors: HashMap<&'static str, ComponentInspectorFn>, inspectors: HashMap<&'static str, ComponentInspectorFn>,
} }
/// Synchronous inspector callbacks run while [`crate::ui::UiState`] is scoped out of `World`.
/// They must not request that resource. Keep extension-owned transient state in independently
/// registered resources, use [`crate::ui::request_ui_selection`] and
/// [`crate::ui::request_editor_tab`] for host UI changes, or defer other cross-panel work through
/// extension-owned commands or events.
pub type ComponentInspectorFn = fn(&mut World, &mut egui::Ui, Entity); pub type ComponentInspectorFn = fn(&mut World, &mut egui::Ui, Entity);
impl EditorComponentRegistry { impl EditorComponentRegistry {
@@ -373,6 +378,27 @@ impl Default for EditorComponentRegistry {
], ],
hydration_effect: "Hydrates into generated brush mesh children.", 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 { EditorComponentDescriptor {
id: shared::AUTHORING_COMPONENT_MATERIAL, id: shared::AUTHORING_COMPONENT_MATERIAL,
type_name: "shared::components::MaterialDesc", type_name: "shared::components::MaterialDesc",
+109 -12
View File
@@ -13,8 +13,9 @@ use crate::history::set_brush_with_history;
use crate::history::EditorHistory; use crate::history::EditorHistory;
use crate::project_io::ProjectWorkspace; use crate::project_io::ProjectWorkspace;
use crate::scene_io::{SceneIo, SceneIoEventSeverity}; use crate::scene_io::{SceneIo, SceneIoEventSeverity};
use crate::selection::SelectedEntity; use crate::viewport::collider_diagnostics::{
use crate::ui::UiState; ColliderDiagnosticSeverity, ColliderDiagnosticsState, ColliderOverlayStatus,
};
#[derive(Resource, Default)] #[derive(Resource, Default)]
pub struct DiagnosticsPanel { pub struct DiagnosticsPanel {
@@ -120,11 +121,7 @@ pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
.iter(world) .iter(world)
.find_map(|(entity, id)| (id.0 == actor_id).then_some(entity)) .find_map(|(entity, id)| (id.0 == actor_id).then_some(entity))
{ {
world.resource_mut::<SelectedEntity>().0 = Some(entity); request_diagnostic_selection(world, entity);
world
.resource_mut::<UiState>()
.selected_entities
.select_replace(entity);
} }
} }
} }
@@ -138,6 +135,9 @@ pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
} }
} }
ui.separator();
collider_diagnostics_ui(world, ui);
ui.separator(); ui.separator();
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.strong("Support bundle"); ui.strong("Support bundle");
@@ -193,6 +193,69 @@ pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
ui.small("BRP is enabled on the editor for external tooling."); 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() {
request_diagnostic_selection(world, 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) { pub fn brush_diagnostics_window(world: &mut World, ctx: &egui::Context, open: &mut bool) {
if !*open { if !*open {
return; return;
@@ -231,11 +294,7 @@ fn brush_diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
ui.colored_label(color, row.status_label()); ui.colored_label(color, row.status_label());
ui.label(row.name.as_str()); ui.label(row.name.as_str());
if ui.button("Select").clicked() { if ui.button("Select").clicked() {
world.resource_mut::<SelectedEntity>().0 = Some(row.entity); request_diagnostic_selection(world, row.entity);
world
.resource_mut::<UiState>()
.selected_entities
.select_replace(row.entity);
} }
if ui if ui
.add_enabled(row.error_count > 0, egui::Button::new("Reset Cube")) .add_enabled(row.error_count > 0, egui::Button::new("Reset Cube"))
@@ -250,6 +309,10 @@ fn brush_diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
} }
} }
fn request_diagnostic_selection(world: &mut World, entity: Entity) {
crate::ui::request_ui_selection(world, &[entity]);
}
#[derive(Debug)] #[derive(Debug)]
struct BrushDiagnosticRow { struct BrushDiagnosticRow {
entity: Entity, entity: Entity,
@@ -324,3 +387,37 @@ pub fn diagnostics_window(world: &mut World, ctx: &egui::Context, open: &mut boo
diagnostics_ui(world, ui); diagnostics_ui(world, ui);
}); });
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::selection::SelectedEntity;
use crate::ui::{PendingUiSelection, UiState};
#[test]
fn diagnostic_selection_reconciles_while_ui_state_is_scoped_out() {
let before = Entity::from_bits(1);
let requested = Entity::from_bits(2);
let mut world = World::new();
world.init_resource::<SelectedEntity>();
world.init_resource::<PendingUiSelection>();
world.resource_mut::<SelectedEntity>().0 = Some(before);
let mut ui_state = UiState::default_layout();
ui_state.selected_entities.select_replace(before);
world.insert_resource(ui_state);
world.resource_scope::<UiState, _>(|world, mut ui_state| {
assert!(!world.contains_resource::<UiState>());
request_diagnostic_selection(world, requested);
let pending = world.resource_mut::<PendingUiSelection>().0.take();
super::super::reconcile_operator_selection(
&mut ui_state.selected_entities,
&[before],
world.resource::<SelectedEntity>().0,
pending.as_deref(),
);
assert_eq!(ui_state.selected_entities.as_slice(), &[requested]);
});
}
}
+11 -5
View File
@@ -36,7 +36,10 @@ impl PanelNodes {
EditorTab::Viewport | EditorTab::GameView => self.main_view(), EditorTab::Viewport | EditorTab::GameView => self.main_view(),
EditorTab::Hierarchy => self.hierarchy(), EditorTab::Hierarchy => self.hierarchy(),
EditorTab::Inspector => self.inspector(), 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::Viewport | EditorTab::GameView => nodes.main_view = path.node.0,
EditorTab::Hierarchy => nodes.hierarchy = path.node.0, EditorTab::Hierarchy => nodes.hierarchy = path.node.0,
EditorTab::Inspector => nodes.inspector = path.node.0, EditorTab::Inspector => nodes.inspector = path.node.0,
EditorTab::AssetBrowser | EditorTab::Build | EditorTab::Toolbar => { EditorTab::AssetBrowser
nodes.bottom = path.node.0 | EditorTab::MaterialLibrary
} | EditorTab::Build
| EditorTab::Toolbar => nodes.bottom = path.node.0,
} }
} }
nodes nodes
} }
} }
pub const PANEL_TABS: [EditorTab; 5] = [ pub const PANEL_TABS: [EditorTab; 6] = [
EditorTab::Viewport, EditorTab::Viewport,
EditorTab::Hierarchy, EditorTab::Hierarchy,
EditorTab::Inspector, EditorTab::Inspector,
EditorTab::AssetBrowser, EditorTab::AssetBrowser,
EditorTab::MaterialLibrary,
EditorTab::Build, EditorTab::Build,
]; ];
@@ -74,6 +79,7 @@ pub fn tab_label(tab: &EditorTab) -> &'static str {
EditorTab::Hierarchy => "Hierarchy", EditorTab::Hierarchy => "Hierarchy",
EditorTab::Inspector => "Inspector", EditorTab::Inspector => "Inspector",
EditorTab::AssetBrowser => "Asset Browser", EditorTab::AssetBrowser => "Asset Browser",
EditorTab::MaterialLibrary => "Material Library",
EditorTab::Build => "Build", EditorTab::Build => "Build",
EditorTab::Toolbar => "Toolbar (legacy)", 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::assets::{snapshot_for_asset, EditorAsset, EditorAssetKind};
use crate::camera::EditorCamera; use crate::camera::EditorCamera;
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace}; 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::play::default_player_spawn;
use crate::scene_io::SceneIo; use crate::scene_io::SceneIo;
use crate::viewport::{recall_camera_bookmark, save_camera_bookmark, CameraBookmarks}; 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. /// Removes all authored [`LightDesc`] so project sun/ambient drive outdoor lighting.
pub fn reset_scene_lighting_to_project_defaults(world: &mut World) { pub fn reset_scene_lighting_to_project_defaults(world: &mut World) {
let mut query = world.query_filtered::<Entity, With<LevelObject>>(); let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>();
let with_lights: Vec<Entity> = query let changes = query
.iter(world) .iter(world)
.filter(|entity| world.get::<LightDesc>(*entity).is_some()) .map(|(entity, _)| (entity, None))
.collect(); .collect::<Vec<_>>();
for entity in with_lights { set_light_group_with_history(world, changes, "Reset Scene Lighting");
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.remove::<LightDesc>();
}
}
world
.resource_mut::<crate::scene_io::SceneIo>()
.mark_dirty();
} }
/// Removes authored directional lights so [`ProjectSun`] drives outdoor lighting. /// Removes authored directional lights so [`ProjectSun`] drives outdoor lighting.
pub fn use_project_sun(world: &mut World) { pub fn use_project_sun(world: &mut World) {
let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>(); let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>();
let directionals: Vec<Entity> = query let changes = query
.iter(world) .iter(world)
.filter(|(_, light)| matches!(light.kind, AuthoringLightKind::Directional)) .filter(|(_, light)| matches!(light.kind, AuthoringLightKind::Directional))
.map(|(e, _)| e) .map(|(entity, _)| (entity, None))
.collect(); .collect::<Vec<_>>();
for entity in directionals { set_light_group_with_history(world, changes, "Use Project Sun");
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.remove::<LightDesc>();
}
}
world
.resource_mut::<crate::scene_io::SceneIo>()
.mark_dirty();
} }
pub fn create_scene_sun_override_from_project_settings(world: &mut World) -> Entity { 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 { .map(|kind| match kind {
ActorKind::Empty => 0, ActorKind::Empty => 0,
ActorKind::Brush ActorKind::Brush
| ActorKind::Terrain
| ActorKind::StaticMesh | ActorKind::StaticMesh
| ActorKind::SkinnedMesh | ActorKind::SkinnedMesh
| ActorKind::ImportedModel => 1, | ActorKind::ImportedModel => 1,
@@ -468,6 +469,7 @@ pub fn actor_kind_icon(kind: ActorKind) -> &'static str {
match kind { match kind {
ActorKind::Empty => icons::FOLDER.as_str(), ActorKind::Empty => icons::FOLDER.as_str(),
ActorKind::Brush => icons::CUBE.as_str(), ActorKind::Brush => icons::CUBE.as_str(),
ActorKind::Terrain => icons::MOUNTAINS.as_str(),
ActorKind::StaticMesh => icons::CUBE.as_str(), ActorKind::StaticMesh => icons::CUBE.as_str(),
ActorKind::SkinnedMesh => icons::PERSON_SIMPLE_RUN.as_str(), ActorKind::SkinnedMesh => icons::PERSON_SIMPLE_RUN.as_str(),
ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(), ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(),
+533 -55
View File
@@ -16,8 +16,8 @@ use shared::{
MaterialParameterValue, MaterialRef, MaterialShaderKind, NavigationArea, NavigationBounds, MaterialParameterValue, MaterialRef, MaterialShaderKind, NavigationArea, NavigationBounds,
NavigationLink, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn, NavigationLink, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn,
PostProcessVolumeDesc, PrefabInstance, Primitive, PrimitiveShape, ProjectSun, RigidBodyDesc, PostProcessVolumeDesc, PrefabInstance, Primitive, PrimitiveShape, ProjectSun, RigidBodyDesc,
SkinnedMeshRenderer, StaticMeshRenderer, StaticMeshRendererEntry, TeamSpawn, TriggerVolume, SkinnedMeshRenderer, StaticMeshRenderer, StaticMeshRendererEntry, TeamSpawn, TerrainDesc,
WeaponSpawn, AUTHORING_DIRECTIONAL_LUX_MAX, AUTHORING_POINT_SPOT_LUMENS_MAX, TriggerVolume, WeaponSpawn, AUTHORING_DIRECTIONAL_LUX_MAX, AUTHORING_POINT_SPOT_LUMENS_MAX,
COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_AUDIO_LISTENER_DESC, COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_AUDIO_LISTENER_DESC,
COMPONENT_AUDIO_SOURCE_DESC, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC, COMPONENT_AUDIO_SOURCE_DESC, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
COMPONENT_LIGHT_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_NAVIGATION_AREA, 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_OBJECTIVE_MARKER, COMPONENT_PHYSICS_BODY, COMPONENT_PLAYER_SPAWN,
COMPONENT_POST_PROCESS_VOLUME, COMPONENT_PREFAB_INSTANCE, COMPONENT_PRIMITIVE, COMPONENT_POST_PROCESS_VOLUME, COMPONENT_PREFAB_INSTANCE, COMPONENT_PRIMITIVE,
COMPONENT_PROJECT_SUN, COMPONENT_RIGID_BODY_DESC, COMPONENT_SKINNED_MESH_RENDERER, COMPONENT_PROJECT_SUN, COMPONENT_RIGID_BODY_DESC, COMPONENT_SKINNED_MESH_RENDERER,
COMPONENT_STATIC_MESH_RENDERER, COMPONENT_TEAM_SPAWN, COMPONENT_TRIGGER_VOLUME, COMPONENT_STATIC_MESH_RENDERER, COMPONENT_TEAM_SPAWN, COMPONENT_TERRAIN_DESC,
COMPONENT_WEAPON_SPAWN, COMPONENT_TRIGGER_VOLUME, COMPONENT_WEAPON_SPAWN,
}; };
use crate::history::{ use crate::history::{
@@ -37,20 +37,21 @@ use crate::history::{
set_primitive_with_history, set_rigid_body_with_history, set_static_mesh_renderer_with_history, set_primitive_with_history, set_rigid_body_with_history, set_static_mesh_renderer_with_history,
EditorEntitySnapshot, EditorEntitySnapshot,
}; };
use crate::selection::SelectedEntity;
use crate::ui::theme::{ use crate::ui::theme::{
panel_heading, BORDER, ELEVATED_BG, PANEL_BG_DARK, SELECTION_BG_MUTED, TEXT_DIM, TEXT_MUTED, panel_heading, BORDER, ELEVATED_BG, PANEL_BG_DARK, SELECTION_BG_MUTED, TEXT_DIM, TEXT_MUTED,
WIDGET_BG, WIDGET_BG,
}; };
use crate::ui::widgets::{icon_button_small, phosphor_icon, phosphor_icon_text}; use crate::ui::widgets::{icon_button_small, phosphor_icon, phosphor_icon_text};
use crate::viewport::brush_edit::{BrushElementKey, BrushElementSelection}; use crate::viewport::brush_edit::{BrushElementKey, BrushElementSelection};
use crate::viewport::collider_diagnostics::{
diagnose_collider, ColliderDiagnosticSeverity, ColliderOverlayStatus,
};
use super::component_registry::{ use super::component_registry::{
EditorComponentCategory, EditorComponentDescriptor, EditorComponentRegistry, EditorComponentCategory, EditorComponentDescriptor, EditorComponentRegistry,
}; };
use super::dock_tabs::open_and_focus_tab;
use super::helpers::create_scene_sun_override_from_project_settings; use super::helpers::create_scene_sun_override_from_project_settings;
use super::{EditorTab, UiState}; use super::EditorTab;
use crate::assets::asset_db::{find_asset_by_path, AssetRegistry}; use crate::assets::asset_db::{find_asset_by_path, AssetRegistry};
use crate::assets::static_mesh::{ use crate::assets::static_mesh::{
load_static_mesh_manifest, material_id_from_label, part_id_from_label, load_static_mesh_manifest, material_id_from_label, part_id_from_label,
@@ -132,6 +133,7 @@ pub(crate) struct InspectorPanelState {
add_component_scroll_selected: bool, add_component_scroll_selected: bool,
add_component_selected_index: usize, add_component_selected_index: usize,
add_component_target: Option<Entity>, add_component_target: Option<Entity>,
collapsed_components: HashSet<String>,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -273,13 +275,9 @@ pub(crate) fn component_card_context(
state_key, state_key,
); );
let collapsed = world let collapsed = world
.get_resource::<UiState>() .resource::<InspectorPanelState>()
.map(|state| { .collapsed_components
state .contains(&component_card_key(world, entity, options.type_name));
.inspector_collapsed_components
.contains(&component_card_key(world, entity, options.type_name))
})
.unwrap_or(false);
let pasteable = options.copyable let pasteable = options.copyable
&& world && world
.get_resource::<InspectorClipboard>() .get_resource::<InspectorClipboard>()
@@ -323,12 +321,11 @@ fn apply_component_card_response_for_type(
) { ) {
if let Some(collapsed) = response.collapsed { if let Some(collapsed) = response.collapsed {
let key = component_card_key(world, entity, type_name); let key = component_card_key(world, entity, type_name);
if let Some(mut ui_state) = world.get_resource_mut::<UiState>() { let mut panel_state = world.resource_mut::<InspectorPanelState>();
if collapsed { if collapsed {
ui_state.inspector_collapsed_components.insert(key); panel_state.collapsed_components.insert(key);
} else { } else {
ui_state.inspector_collapsed_components.remove(&key); panel_state.collapsed_components.remove(&key);
}
} }
} }
@@ -1110,6 +1107,7 @@ fn draw_authoring_component_by_type(
COMPONENT_STATIC_MESH_RENDERER => static_mesh_renderer_ui(world, ui, entity), COMPONENT_STATIC_MESH_RENDERER => static_mesh_renderer_ui(world, ui, entity),
COMPONENT_SKINNED_MESH_RENDERER => skinned_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_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_PRIMITIVE => primitive_editor_ui(world, ui, entity),
COMPONENT_MATERIAL_DESC => material_editor_ui(world, ui, entity), COMPONENT_MATERIAL_DESC => material_editor_ui(world, ui, entity),
COMPONENT_LIGHT_DESC => light_editor_ui(world, ui, entity), COMPONENT_LIGHT_DESC => light_editor_ui(world, ui, entity),
@@ -2358,18 +2356,15 @@ fn locate_asset_ref(
return; return;
}; };
reveal_asset_in_browser(world, &candidate.folder_path, &candidate.selection);
}
fn reveal_asset_in_browser(world: &mut World, folder_path: &str, selection: &AssetSelection) {
if let Some(mut assets) = world.get_resource_mut::<EditorAssets>() { if let Some(mut assets) = world.get_resource_mut::<EditorAssets>() {
assets.current_folder = candidate.folder_path.clone(); assets.current_folder = folder_path.to_string();
assets.select(candidate.selection.clone()); assets.select(selection.clone());
}
if let Some(mut ui_state) = world.get_resource_mut::<UiState>() {
let panel_nodes = ui_state.panel_nodes;
open_and_focus_tab(
&mut ui_state.dock_state,
EditorTab::AssetBrowser,
&panel_nodes,
);
} }
super::request_editor_tab(world, EditorTab::AssetBrowser);
} }
fn skinned_mesh_renderer_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) { fn skinned_mesh_renderer_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
@@ -3494,6 +3489,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) { fn brush_validation_ui(ui: &mut egui::Ui, brush: &BrushDesc) {
let report = validate_brush(brush); let report = validate_brush(brush);
if report.diagnostics.is_empty() { if report.diagnostics.is_empty() {
@@ -3893,6 +4207,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) { 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 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 { let Some(mut collider) = world.get::<ColliderDesc>(entity).cloned() else {
return; return;
}; };
@@ -3915,13 +4230,60 @@ fn collider_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
ComponentCardOptions::removable(COMPONENT_COLLIDER_DESC, "Collider", icons::SELECTION), ComponentCardOptions::removable(COMPONENT_COLLIDER_DESC, "Collider", icons::SELECTION),
); );
let card_response = component_card(ui, &card, |ui| { 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| { property_row(ui, "Mode", |ui| {
changed |= ui.checkbox(&mut collider.enabled, "Enabled").changed(); changed |= ui.checkbox(&mut collider.enabled, "Enabled").changed();
changed |= ui.checkbox(&mut collider.is_trigger, "Trigger").changed(); changed |= ui.checkbox(&mut collider.is_trigger, "Trigger").changed();
}); });
property_row(ui, "Shape", |ui| { property_row(ui, "Shape", |ui| {
let mut shape_kind = collider_shape_kind(&collider.shape); 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) .selected_text(shape_kind)
.show_ui(ui, |ui| { .show_ui(ui, |ui| {
for label in ["Box", "Sphere", "Capsule", "Static Mesh"] { for label in ["Box", "Sphere", "Capsule", "Static Mesh"] {
@@ -3931,15 +4293,8 @@ fn collider_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
} }
}); });
if shape_kind != collider_shape_kind(&collider.shape) { if shape_kind != collider_shape_kind(&collider.shape) {
collider.shape = match shape_kind { collider.shape =
"Sphere" => ColliderShapeDesc::Sphere { radius: 0.5 }, convert_collider_shape(&collider.shape, shape_kind, renderer_meshes.clone());
"Capsule" => ColliderShapeDesc::Capsule {
radius: 0.5,
height: 1.0,
},
"Static Mesh" => ColliderShapeDesc::static_mesh(renderer_meshes.clone()),
_ => ColliderShapeDesc::default(),
};
changed = true; changed = true;
} }
}); });
@@ -4007,12 +4362,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 { fn dimension_drag(ui: &mut egui::Ui, label: &str, value: &mut f32) -> bool {
property_row(ui, label, |ui| { property_row(ui, label, |ui| {
ui.add_sized( ui.add_sized(
[fit_width(ui, 72.0, 120.0), 20.0], [fit_width(ui, 72.0, 120.0), 20.0],
egui::DragValue::new(value) egui::DragValue::new(value)
.range(0.0..=10_000.0) .range(0.001..=10_000.0)
.speed(0.05) .speed(0.05)
.min_decimals(2) .min_decimals(2)
.max_decimals(3), .max_decimals(3),
@@ -4225,10 +4616,7 @@ pub fn project_sun_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
if create_override { if create_override {
let sun = create_scene_sun_override_from_project_settings(world); let sun = create_scene_sun_override_from_project_settings(world);
world.resource_mut::<SelectedEntity>().0 = Some(sun); crate::ui::request_ui_selection(world, &[sun]);
if let Some(mut ui_state) = world.get_resource_mut::<crate::ui::UiState>() {
ui_state.selected_entities.select_replace(sun);
}
} }
} }
@@ -4481,18 +4869,7 @@ fn locate_texture_asset(
return; return;
}; };
if let Some(mut assets) = world.get_resource_mut::<EditorAssets>() { reveal_asset_in_browser(world, &candidate.folder_path, &candidate.selection);
assets.current_folder = candidate.folder_path.clone();
assets.select(candidate.selection.clone());
}
if let Some(mut ui_state) = world.get_resource_mut::<UiState>() {
let panel_nodes = ui_state.panel_nodes;
open_and_focus_tab(
&mut ui_state.dock_state,
EditorTab::AssetBrowser,
&panel_nodes,
);
}
} }
fn option_string_ui(ui: &mut egui::Ui, label: &str, value: &mut Option<String>) -> bool { fn option_string_ui(ui: &mut egui::Ui, label: &str, value: &mut Option<String>) -> bool {
@@ -4519,3 +4896,104 @@ fn option_string_ui(ui: &mut egui::Ui, label: &str, value: &mut Option<String>)
}; };
changed changed
} }
#[cfg(test)]
mod collider_inspector_tests {
use super::*;
use crate::history::{apply_command_undo, EditorHistory};
use crate::ui::{DockTabRequest, UiState};
#[test]
fn component_collapse_persists_while_ui_state_is_scoped_out() {
let mut world = World::new();
world.init_resource::<EditorComponentRegistry>();
world.init_resource::<InspectorPanelState>();
let entity = world
.spawn((ActorId::new("collapsed-component"), Transform::IDENTITY))
.id();
world.insert_resource(UiState::default_layout());
world.resource_scope::<UiState, _>(|world, _ui_state| {
assert!(!world.contains_resource::<UiState>());
apply_component_card_response(
world,
entity,
ComponentCardResponse {
type_name: COMPONENT_TRANSFORM,
collapsed: Some(true),
..Default::default()
},
);
let context = component_card_context(
world,
entity,
ComponentCardOptions::fixed(COMPONENT_TRANSFORM, "Transform", icons::CUBE),
);
assert!(context.collapsed);
});
}
#[test]
fn locate_texture_requests_asset_browser_while_ui_state_is_scoped_out() {
let path = "assets/textures/scoped-locate.png";
let folder = "assets/textures";
let selection = AssetSelection::File(path.to_string());
let mut world = World::new();
world.insert_resource(EditorAssets {
folders: Vec::new(),
assets: vec![EditorAsset {
label: "Scoped Locate".into(),
path: Some(path.into()),
folder_path: folder.into(),
kind: EditorAssetKind::Texture,
}],
current_folder: crate::assets::ASSETS_ROOT.into(),
selected: None,
dragging: None,
status: String::new(),
});
world.init_resource::<DockTabRequest>();
world.insert_resource(UiState::default_layout());
let candidate = TextureAssetCandidate {
label: "Scoped Locate".into(),
path: path.into(),
folder_path: folder.into(),
selection: selection.clone(),
texture_id: None,
};
world.resource_scope::<UiState, _>(|world, _ui_state| {
assert!(!world.contains_resource::<UiState>());
locate_texture_asset(world, Some(path), &[candidate]);
});
let assets = world.resource::<EditorAssets>();
assert_eq!(assets.current_folder, folder);
assert_eq!(assets.selected.as_ref(), Some(&selection));
assert_eq!(
world.resource::<DockTabRequest>().0,
Some(EditorTab::AssetBrowser)
);
}
#[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]); tree.split_right(NodeIndex::root(), 0.76, vec![EditorTab::Inspector]);
let [main_view_node, hierarchy_node] = let [main_view_node, hierarchy_node] =
tree.split_left(main_view_node, 0.2, vec![EditorTab::Hierarchy]); tree.split_left(main_view_node, 0.2, vec![EditorTab::Hierarchy]);
let [main_view_node, bottom_node] = let [main_view_node, bottom_node] = tree.split_below(
tree.split_below(main_view_node, 0.88, vec![EditorTab::AssetBrowser]); main_view_node,
0.88,
vec![EditorTab::AssetBrowser, EditorTab::MaterialLibrary],
);
let panel_nodes = PanelNodes { let panel_nodes = PanelNodes {
main_view: main_view_node.0, main_view: main_view_node.0,
File diff suppressed because it is too large. Load diff
+88 -1
View File
@@ -6,8 +6,10 @@ use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
use egui_dock::DockState; use egui_dock::DockState;
use crate::history::{apply_command_redo, apply_command_undo, EditorHistory}; use crate::history::{apply_command_redo, apply_command_undo, EditorHistory};
use crate::project::samples::{SampleCatalog, SampleCatalogEntry};
use crate::scene_io::{SceneIo, SceneIoRequest}; use crate::scene_io::{SceneIo, SceneIoRequest};
use crate::settings_ui::{open_project_settings_panel, ProjectSettingsPanel}; use crate::settings_ui::{open_project_settings_panel, ProjectSettingsPanel};
use crate::shutdown::{request_editor_shutdown, ShutdownSource};
use crate::state::{EditorMode, PlayPaused}; use crate::state::{EditorMode, PlayPaused};
use super::diagnostics::{BrushDiagnosticsPanel, DiagnosticsPanel}; use super::diagnostics::{BrushDiagnosticsPanel, DiagnosticsPanel};
@@ -19,12 +21,26 @@ use super::layout::reset_and_save_layout;
use super::widgets::menu_item; use super::widgets::menu_item;
use super::EditorTab; use super::EditorTab;
#[derive(Debug, Clone, PartialEq, Eq)]
enum SampleMenuModel {
Available(Vec<SampleCatalogEntry>),
Unavailable(String),
}
fn sample_menu_model(catalog: &SampleCatalog) -> SampleMenuModel {
match catalog.unavailable_reason() {
Some(reason) => SampleMenuModel::Unavailable(reason.to_string()),
None => SampleMenuModel::Available(catalog.entries().to_vec()),
}
}
pub fn top_menu_bar( pub fn top_menu_bar(
world: &mut World, world: &mut World,
root_ui: &mut egui::Ui, root_ui: &mut egui::Ui,
selected: &SelectedEntities, selected: &SelectedEntities,
dock_state: &mut DockState<EditorTab>, dock_state: &mut DockState<EditorTab>,
panel_nodes: &mut PanelNodes, panel_nodes: &mut PanelNodes,
viewport_rect: egui::Rect,
) { ) {
egui::Panel::top("editor_menu_bar").show_inside(root_ui, |ui| { egui::Panel::top("editor_menu_bar").show_inside(root_ui, |ui| {
egui::MenuBar::new().ui(ui, |ui| { egui::MenuBar::new().ui(ui, |ui| {
@@ -37,6 +53,25 @@ pub fn top_menu_bar(
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Open); world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Open);
ui.close(); ui.close();
} }
let sample_menu = sample_menu_model(world.resource::<SampleCatalog>());
ui.menu_button("Open Sample", |ui| match sample_menu {
SampleMenuModel::Available(entries) => {
for entry in entries {
if menu_item(ui, &entry.label, None, true)
.on_hover_text(entry.hover_text())
.clicked()
{
world.resource_mut::<SceneIo>().request =
Some(SceneIoRequest::OpenSample(entry.id));
ui.close();
}
}
}
SampleMenuModel::Unavailable(reason) => {
menu_item(ui, "Sample pack unavailable", None, false)
.on_disabled_hover_text(reason);
}
});
if menu_item(ui, "Save", Some("Ctrl+S"), true).clicked() { if menu_item(ui, "Save", Some("Ctrl+S"), true).clicked() {
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Save); world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Save);
ui.close(); ui.close();
@@ -115,6 +150,11 @@ pub fn top_menu_bar(
} }
}); });
} }
ui.separator();
if menu_item(ui, "Quit", None, true).clicked() {
request_editor_shutdown(world, ShutdownSource::FileMenu);
ui.close();
}
}); });
ui.menu_button("Edit", |ui| { ui.menu_button("Edit", |ui| {
@@ -170,7 +210,7 @@ pub fn top_menu_bar(
("Create Link", NavigationActorType::Link), ("Create Link", NavigationActorType::Link),
] { ] {
if menu_item(ui, label, None, true).clicked() { if menu_item(ui, label, None, true).clicked() {
spawn_navigation_actor(world, actor_type); spawn_navigation_actor(world, actor_type, viewport_rect);
ui.close(); ui.close();
} }
} }
@@ -287,3 +327,50 @@ pub fn top_menu_bar(
}); });
}); });
} }
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
fn entry(id: &str, label: &str) -> SampleCatalogEntry {
SampleCatalogEntry {
id: id.into(),
label: label.into(),
scene_path: PathBuf::from(format!("assets/levels/samples/{id}.scn.ron")),
project_relative_scene: format!("assets/levels/samples/{id}.scn.ron"),
summary: format!("{label} summary"),
checks: vec![format!("{label} check")],
}
}
#[test]
fn sample_menu_preserves_catalog_order_and_hover_details() {
let catalog = SampleCatalog::available_entries(vec![
entry("material", "Material Lab"),
entry("terrain", "Terrain Sculpt"),
]);
let SampleMenuModel::Available(rows) = sample_menu_model(&catalog) else {
panic!("valid catalog must produce actionable menu rows");
};
assert_eq!(
rows.iter().map(|row| row.id.as_str()).collect::<Vec<_>>(),
vec!["material", "terrain"]
);
assert!(rows[0].hover_text().contains("Material Lab summary"));
assert!(rows[0].hover_text().contains("Material Lab check"));
}
#[test]
fn unavailable_catalog_produces_one_disabled_explanation() {
let catalog = SampleCatalog::default();
assert_eq!(
sample_menu_model(&catalog),
SampleMenuModel::Unavailable("Sample catalog is loading".into())
);
}
}
+157 -14
View File
@@ -13,6 +13,7 @@ pub mod hierarchy_ops;
pub mod hierarchy_state; pub mod hierarchy_state;
pub(crate) mod inspector; pub(crate) mod inspector;
mod layout; mod layout;
mod material_library;
mod menu; mod menu;
pub(crate) mod navigation_inspector; pub(crate) mod navigation_inspector;
mod play_controls; mod play_controls;
@@ -25,8 +26,6 @@ mod toolbar;
mod viewport_chrome; mod viewport_chrome;
mod widgets; mod widgets;
use std::collections::HashSet;
use bevy::prelude::*; use bevy::prelude::*;
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow}; use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
use bevy_egui::{egui, EguiContext, EguiPrimaryContextPass, PrimaryEguiContext}; use bevy_egui::{egui, EguiContext, EguiPrimaryContextPass, PrimaryEguiContext};
@@ -39,6 +38,10 @@ use crate::project_io::UserPreferences;
use crate::selection::SelectedEntity; use crate::selection::SelectedEntity;
use crate::state::EditorMode; use crate::state::EditorMode;
pub(crate) use asset_browser::{
adopt_material_conflict_save_as, reload_material_after_file_conflict,
validate_material_conflict_destination,
};
pub use build::BuildPanel; pub use build::BuildPanel;
pub use diagnostics::{BrushDiagnosticsPanel, DiagnosticsPanel}; pub use diagnostics::{BrushDiagnosticsPanel, DiagnosticsPanel};
pub use layout::LayoutSaveTimer; pub use layout::LayoutSaveTimer;
@@ -66,11 +69,63 @@ pub struct UiState {
pub selected_entities: SelectedEntities, pub selected_entities: SelectedEntities,
pub renaming_entity: Option<Entity>, pub renaming_entity: Option<Entity>,
pub rename_buffer: String, pub rename_buffer: String,
pub(crate) inspector_collapsed_components: HashSet<String>,
pub(crate) panel_nodes: PanelNodes, pub(crate) panel_nodes: PanelNodes,
last_mode_tab: Option<EditorMode>, last_mode_tab: Option<EditorMode>,
} }
#[derive(Resource, Default)]
struct DockTabRequest(Option<EditorTab>);
#[derive(Resource, Default, Debug)]
pub(crate) struct PendingUiSelection(pub(crate) Option<Vec<Entity>>);
fn replace_selected_entities(selected: &mut SelectedEntities, entities: &[Entity]) {
selected.clear();
for (index, entity) in entities.iter().enumerate() {
if index == 0 {
selected.select_replace(*entity);
} else {
selected.select_maybe_add(*entity, true);
}
}
}
/// Requests an editor selection change from synchronous UI or extension callbacks.
///
/// Returns `false` when the editor selection resources are not installed. A normally configured
/// editor provides them through [`crate::EditorPluginGroup`].
pub fn request_ui_selection(world: &mut World, entities: &[Entity]) -> bool {
{
let Some(mut selected) = world.get_resource_mut::<SelectedEntity>() else {
return false;
};
selected.0 = entities.first().copied();
}
if world.contains_resource::<UiState>() {
{
let mut ui_state = world.resource_mut::<UiState>();
replace_selected_entities(&mut ui_state.selected_entities, entities);
}
if let Some(mut pending) = world.get_resource_mut::<PendingUiSelection>() {
pending.0 = None;
}
} else if let Some(mut pending) = world.get_resource_mut::<PendingUiSelection>() {
pending.0 = Some(entities.to_vec());
}
true
}
/// Requests that an editor tab be opened and focused after the current synchronous UI pass.
///
/// Returns `false` when [`EditorUiPlugin`] is not installed.
pub fn request_editor_tab(world: &mut World, tab: EditorTab) -> bool {
let Some(mut request) = world.get_resource_mut::<DockTabRequest>() else {
return false;
};
request.0 = Some(tab);
true
}
pub fn egui_captures_keyboard(ctx: &egui::Context) -> bool { pub fn egui_captures_keyboard(ctx: &egui::Context) -> bool {
ctx.egui_wants_keyboard_input() ctx.egui_wants_keyboard_input()
} }
@@ -118,7 +173,6 @@ impl UiState {
selected_entities: SelectedEntities::default(), selected_entities: SelectedEntities::default(),
renaming_entity: None, renaming_entity: None,
rename_buffer: String::new(), rename_buffer: String::new(),
inspector_collapsed_components: HashSet::new(),
panel_nodes, panel_nodes,
last_mode_tab: None, last_mode_tab: None,
} }
@@ -130,7 +184,7 @@ impl UiState {
)] )]
fn ui(&mut self, world: &mut World, ctx: &mut egui::Context, dt: f32) { fn ui(&mut self, world: &mut World, ctx: &mut egui::Context, dt: f32) {
apply_editor_theme(ctx); apply_editor_theme(ctx);
let selected_before_ui = world.resource::<SelectedEntity>().0; let selected_before_ui: Vec<Entity> = self.selected_entities.iter().collect();
let mode = *world.resource::<State<EditorMode>>().get(); let mode = *world.resource::<State<EditorMode>>().get();
if self.last_mode_tab != Some(mode) { if self.last_mode_tab != Some(mode) {
@@ -161,9 +215,15 @@ impl UiState {
&self.selected_entities, &self.selected_entities,
&mut self.dock_state, &mut self.dock_state,
&mut self.panel_nodes, &mut self.panel_nodes,
self.viewport_rect,
); );
editor_toolbar_panel(world, root_ui, &mut self.selected_entities); editor_toolbar_panel(
world,
root_ui,
&mut self.selected_entities,
self.viewport_rect,
);
status_bar_ui(world, root_ui, &self.selected_entities, mode); status_bar_ui(world, root_ui, &self.selected_entities, mode);
let mut viewer = TabViewer { let mut viewer = TabViewer {
@@ -183,6 +243,10 @@ impl UiState {
.show_inside(root_ui, &mut viewer); .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); self.panel_nodes = PanelNodes::discover(&self.dock_state, self.panel_nodes);
mark_layout_dirty_if_changed( mark_layout_dirty_if_changed(
@@ -215,15 +279,19 @@ impl UiState {
project_settings_window(world, ctx, &mut panel); project_settings_window(world, ctx, &mut panel);
}); });
crate::collaboration::file_conflict_modal(world, ctx);
if ctx.input(|input| input.key_pressed(egui::Key::F1)) { if ctx.input(|input| input.key_pressed(egui::Key::F1)) {
world.resource_mut::<ViewportUiState>().shortcuts_open = true; world.resource_mut::<ViewportUiState>().shortcuts_open = true;
} }
let pending_selection = world.resource_mut::<PendingUiSelection>().0.take();
let requested_selection = world.resource::<SelectedEntity>().0; let requested_selection = world.resource::<SelectedEntity>().0;
reconcile_operator_selection( reconcile_operator_selection(
&mut self.selected_entities, &mut self.selected_entities,
selected_before_ui, &selected_before_ui,
requested_selection, requested_selection,
pending_selection.as_deref(),
); );
let selected = self.selected_entities.as_slice().first().copied(); let selected = self.selected_entities.as_slice().first().copied();
world.resource_mut::<SelectedEntity>().0 = selected; world.resource_mut::<SelectedEntity>().0 = selected;
@@ -232,16 +300,24 @@ impl UiState {
fn reconcile_operator_selection( fn reconcile_operator_selection(
selected_entities: &mut SelectedEntities, selected_entities: &mut SelectedEntities,
selected_before_ui: Option<Entity>, selected_before_ui: &[Entity],
requested_selection: Option<Entity>, requested_selection: Option<Entity>,
pending_selection: Option<&[Entity]>,
) { ) {
let selected_after_ui = selected_entities.as_slice().first().copied(); if selected_entities.as_slice() != selected_before_ui {
if requested_selection == selected_before_ui || selected_after_ui != selected_before_ui { return;
}
if let Some(entities) = pending_selection {
replace_selected_entities(selected_entities, entities);
return;
}
if requested_selection == selected_before_ui.first().copied() {
return; return;
} }
selected_entities.clear();
if let Some(entity) = requested_selection { if let Some(entity) = requested_selection {
selected_entities.select_replace(entity); replace_selected_entities(selected_entities, &[entity]);
} else {
selected_entities.clear();
} }
} }
@@ -277,6 +353,7 @@ pub enum EditorTab {
Inspector, Inspector,
Toolbar, Toolbar,
AssetBrowser, AssetBrowser,
MaterialLibrary,
Build, Build,
} }
@@ -292,6 +369,10 @@ impl Plugin for EditorUiPlugin {
.init_resource::<component_registry::EditorComponentRegistry>() .init_resource::<component_registry::EditorComponentRegistry>()
.init_resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>() .init_resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
.init_resource::<asset_browser::AssetBrowserUiState>() .init_resource::<asset_browser::AssetBrowserUiState>()
.init_resource::<material_library::MaterialLibraryState>()
.init_resource::<material_library::MaterialLibraryCatalog>()
.init_resource::<DockTabRequest>()
.init_resource::<PendingUiSelection>()
.init_resource::<inspector::InspectorClipboard>() .init_resource::<inspector::InspectorClipboard>()
.init_resource::<inspector::InspectorPanelState>() .init_resource::<inspector::InspectorPanelState>()
.init_resource::<animation_inspector::AnimationInspectorState>() .init_resource::<animation_inspector::AnimationInspectorState>()
@@ -309,6 +390,10 @@ impl Plugin for EditorUiPlugin {
apply_ui_state_from_prefs apply_ui_state_from_prefs
.after(crate::project_io::load_user_preferences_on_startup), .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(EguiPrimaryContextPass, show_ui_system)
.add_systems( .add_systems(
Update, Update,
@@ -415,6 +500,9 @@ impl egui_dock::TabViewer for TabViewer<'_> {
EditorTab::AssetBrowser => { EditorTab::AssetBrowser => {
asset_browser::asset_browser_ui(self.world, ui, self.selected_entities); 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), EditorTab::Build => build::build_ui(self.world, ui),
} }
} }
@@ -426,6 +514,7 @@ impl egui_dock::TabViewer for TabViewer<'_> {
EditorTab::Inspector => (icons::SLIDERS, "Inspector"), EditorTab::Inspector => (icons::SLIDERS, "Inspector"),
EditorTab::Toolbar => (icons::WRENCH, "Toolbar"), EditorTab::Toolbar => (icons::WRENCH, "Toolbar"),
EditorTab::AssetBrowser => (icons::FOLDER, "Asset Browser"), EditorTab::AssetBrowser => (icons::FOLDER, "Asset Browser"),
EditorTab::MaterialLibrary => (icons::PALETTE, "Material Library"),
EditorTab::Build => (icons::HAMMER, "Build"), EditorTab::Build => (icons::HAMMER, "Build"),
}; };
tab_title(icon, label) tab_title(icon, label)
@@ -450,7 +539,7 @@ mod tests {
let mut selected = SelectedEntities::default(); let mut selected = SelectedEntities::default();
selected.select_replace(before); selected.select_replace(before);
reconcile_operator_selection(&mut selected, Some(before), Some(spawned)); reconcile_operator_selection(&mut selected, &[before], Some(spawned), None);
assert_eq!(selected.as_slice(), &[spawned]); assert_eq!(selected.as_slice(), &[spawned]);
} }
@@ -463,8 +552,62 @@ mod tests {
let mut selected = SelectedEntities::default(); let mut selected = SelectedEntities::default();
selected.select_replace(clicked); selected.select_replace(clicked);
reconcile_operator_selection(&mut selected, Some(before), Some(requested)); reconcile_operator_selection(
&mut selected,
&[before],
Some(requested),
Some(&[requested, Entity::from_bits(4)]),
);
assert_eq!(selected.as_slice(), &[clicked]); assert_eq!(selected.as_slice(), &[clicked]);
} }
#[test]
fn direct_ui_secondary_selection_change_beats_pending_operator_selection() {
let a = Entity::from_bits(1);
let b = Entity::from_bits(2);
let c = Entity::from_bits(3);
let d = Entity::from_bits(4);
let e = Entity::from_bits(5);
let mut selected = SelectedEntities::default();
selected.select_replace(a);
selected.select_maybe_add(c, true);
reconcile_operator_selection(&mut selected, &[a, b], Some(d), Some(&[d, e]));
assert_eq!(selected.as_slice(), &[a, c]);
}
#[test]
fn menu_scope_multi_selection_request_preserves_all_entities() {
let before = Entity::from_bits(1);
let first_duplicate = Entity::from_bits(2);
let second_duplicate = Entity::from_bits(3);
let mut world = World::new();
world.init_resource::<SelectedEntity>();
world.init_resource::<PendingUiSelection>();
world.resource_mut::<SelectedEntity>().0 = Some(before);
let mut ui_state = UiState::default_layout();
ui_state.selected_entities.select_replace(before);
world.insert_resource(ui_state);
world.resource_scope::<UiState, _>(|world, mut ui_state| {
assert!(!world.contains_resource::<UiState>());
request_ui_selection(world, &[first_duplicate, second_duplicate]);
let pending = world.resource_mut::<PendingUiSelection>().0.take();
reconcile_operator_selection(
&mut ui_state.selected_entities,
&[before],
world.resource::<SelectedEntity>().0,
pending.as_deref(),
);
assert_eq!(
ui_state.selected_entities.as_slice(),
&[first_duplicate, second_duplicate]
);
});
}
} }
+50 -3
View File
@@ -858,10 +858,16 @@ pub enum NavigationActorType {
Link, Link,
} }
pub fn spawn_navigation_actor(world: &mut World, actor_type: NavigationActorType) -> Entity { pub fn spawn_navigation_actor(
let rect = world.resource::<crate::ui::UiState>().viewport_rect; world: &mut World,
actor_type: NavigationActorType,
viewport_rect: egui::Rect,
) -> Entity {
let settings = world.resource::<ViewportSettings>().clone(); let settings = world.resource::<ViewportSettings>().clone();
let translation = snap_translation(editor_spawn_ground_position(world, rect), &settings); let translation = snap_translation(
editor_spawn_ground_position(world, viewport_rect),
&settings,
);
let (name, bounds, obstacle, area, link) = match actor_type { let (name, bounds, obstacle, area, link) = match actor_type {
NavigationActorType::Bounds => ( NavigationActorType::Bounds => (
"Navigation Bounds", "Navigation Bounds",
@@ -1019,8 +1025,49 @@ pub fn sync_navigation_state(world: &mut World) {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::history::EditorHistory;
use crate::scene_io::SceneIo;
use crate::selection::SelectedEntity; use crate::selection::SelectedEntity;
use crate::ui::{PendingUiSelection, UiState};
use scene::navigation::NavigationGeometryInput; use scene::navigation::NavigationGeometryInput;
use shared::{ActorKind, LevelObject};
#[test]
fn navigation_spawn_works_while_ui_state_is_scoped_out_of_world() {
let mut world = World::new();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<SelectedEntity>();
world.init_resource::<PendingUiSelection>();
world.init_resource::<ViewportSettings>();
let mut ui_state = UiState::default_layout();
ui_state.viewport_rect =
egui::Rect::from_min_size(egui::pos2(100.0, 80.0), egui::vec2(1280.0, 720.0));
world.insert_resource(ui_state);
let entity = world.resource_scope::<UiState, _>(|world, mut ui_state| {
assert!(!world.contains_resource::<UiState>());
let entity =
spawn_navigation_actor(world, NavigationActorType::Bounds, ui_state.viewport_rect);
let pending = world.resource_mut::<PendingUiSelection>().0.take();
super::super::reconcile_operator_selection(
&mut ui_state.selected_entities,
&[],
world.resource::<SelectedEntity>().0,
pending.as_deref(),
);
assert_eq!(ui_state.selected_entities.as_slice(), &[entity]);
entity
});
assert!(world.contains_resource::<UiState>());
assert!(world.get::<LevelObject>(entity).is_some());
assert!(world.get::<NavigationBounds>(entity).is_some());
assert_eq!(world.get::<ActorKind>(entity), Some(&ActorKind::Navigation));
assert_eq!(world.resource::<SelectedEntity>().0, Some(entity));
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
}
#[test] #[test]
fn world_affine_uses_current_authored_parent_chain() { fn world_affine_uses_current_authored_parent_chain() {
+42 -19
View File
@@ -8,6 +8,7 @@ use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
use egui_phosphor_icons::icons; use egui_phosphor_icons::icons;
use shared::{SceneComposition, SubsceneReference}; use shared::{SceneComposition, SubsceneReference};
use crate::native_dialog::NativeDialogBroker;
use crate::scene_io::{ComposedSceneMember, SceneIo, SceneIoRequest}; use crate::scene_io::{ComposedSceneMember, SceneIo, SceneIoRequest};
use crate::selection::SelectedEntity; use crate::selection::SelectedEntity;
@@ -195,19 +196,47 @@ fn composition_menu(
ui.separator(); ui.separator();
if ui if ui
.add_enabled(editing, egui::Button::new("Add Subscene...")) .add_enabled(
editing && !world.resource::<NativeDialogBroker>().is_pending(),
egui::Button::new("Add Subscene..."),
)
.clicked() .clicked()
{ {
match choose_subscene(world, &composition) { let project_root =
Ok(Some(reference)) => { PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
composition.subscenes.push(reference); let directory = project_root.join("assets/levels");
changed = true; 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");
} }
Ok(None) => {}
Err(error) => world Err(error) => world
.resource_mut::<SceneIo>() .resource_mut::<SceneIo>()
.set_status(format!("Add subscene failed: {error}")), .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 { if changed {
@@ -218,20 +247,14 @@ fn composition_menu(
} }
} }
fn choose_subscene( fn validate_subscene_choice(
world: &World, project_root: &Path,
composition: &SceneComposition, composition: &SceneComposition,
) -> Result<Option<SubsceneReference>, String> { path: PathBuf,
let project_root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root) ) -> Result<SubsceneReference, String> {
let project_root = project_root
.canonicalize() .canonicalize()
.map_err(|error| format!("could not resolve project root: {error}"))?; .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 let path = path
.canonicalize() .canonicalize()
.map_err(|error| format!("could not resolve {}: {error}", path.display()))?; .map_err(|error| format!("could not resolve {}: {error}", path.display()))?;
@@ -251,12 +274,12 @@ fn choose_subscene(
{ {
return Err(format!("{relative} is already composed")); return Err(format!("{relative} is already composed"));
} }
Ok(Some(SubsceneReference { Ok(SubsceneReference {
id: uuid::Uuid::new_v4().to_string(), id: uuid::Uuid::new_v4().to_string(),
path: relative, path: relative,
visible: true, visible: true,
locked: true, locked: true,
})) })
} }
fn focus_subscene(world: &mut World, selected: &mut SelectedEntities, reference_id: &str) { fn focus_subscene(world: &mut World, selected: &mut SelectedEntities, reference_id: &str) {
+11
View File
@@ -7,6 +7,7 @@ use egui_phosphor_icons::icons;
use crate::history::EditorHistory; use crate::history::EditorHistory;
use crate::operators::ActiveOperator; use crate::operators::ActiveOperator;
use crate::project::collaboration::{file_status_indicator_ui, CollaborationState};
use crate::scene_io::SceneIo; use crate::scene_io::SceneIo;
use crate::state::{EditorMode, PlayPaused}; use crate::state::{EditorMode, PlayPaused};
@@ -47,6 +48,16 @@ pub fn status_bar_ui(
.on_hover_text(status); .on_hover_text(status);
}, },
|ui| { |ui| {
if let (Some(state), Some(path)) = (
world.get_resource::<CollaborationState>(),
world.resource::<SceneIo>().active_path.as_deref(),
) {
let status = state.file_status(path);
if status.indicator().is_some() {
let _ = file_status_indicator_ui(ui, &status, path);
ui.separator();
}
}
let (mode_icon, mode_label, mode_color) = match mode { let (mode_icon, mode_label, mode_color) = match mode {
EditorMode::Editing => (icons::PENCIL_SIMPLE, "EDIT", ACCENT), EditorMode::Editing => (icons::PENCIL_SIMPLE, "EDIT", ACCENT),
EditorMode::Playing => { EditorMode::Playing => {
+75 -15
View File
@@ -8,7 +8,6 @@ use egui_phosphor_icons::icons;
use crate::history::spawn_with_history; use crate::history::spawn_with_history;
use crate::scene_io::{SceneIo, SceneIoRequest}; use crate::scene_io::{SceneIo, SceneIoRequest};
use crate::state::{EditorMode, PlayPaused, PlayPossession}; use crate::state::{EditorMode, PlayPaused, PlayPossession};
use crate::ui::UiState;
use crate::viewport::brush_tool::start_draw_brush_tool; use crate::viewport::brush_tool::start_draw_brush_tool;
use crate::viewport::{editor_spawn_ground_position, snap_translation, ViewportSettings}; use crate::viewport::{editor_spawn_ground_position, snap_translation, ViewportSettings};
use shared::PrimitiveShape; use shared::PrimitiveShape;
@@ -30,15 +29,21 @@ pub fn editor_toolbar_panel(
world: &mut World, world: &mut World,
root_ui: &mut egui::Ui, root_ui: &mut egui::Ui,
selected: &mut SelectedEntities, selected: &mut SelectedEntities,
viewport_rect: egui::Rect,
) { ) {
egui::Panel::top("editor_toolbar") egui::Panel::top("editor_toolbar")
.exact_size(TOOLBAR_HEIGHT) .exact_size(TOOLBAR_HEIGHT)
.show_inside(root_ui, |ui| { .show_inside(root_ui, |ui| {
toolbar_ui(world, ui, selected); toolbar_ui(world, ui, selected, viewport_rect);
}); });
} }
pub fn toolbar_ui(world: &mut World, ui: &mut egui::Ui, selected: &mut SelectedEntities) { pub fn toolbar_ui(
world: &mut World,
ui: &mut egui::Ui,
selected: &mut SelectedEntities,
viewport_rect: egui::Rect,
) {
let (toolbar_rect, _) = ui.allocate_exact_size( let (toolbar_rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_width(), TOOLBAR_HEIGHT - 2.0), egui::vec2(ui.available_width(), TOOLBAR_HEIGHT - 2.0),
egui::Sense::hover(), egui::Sense::hover(),
@@ -65,7 +70,7 @@ pub fn toolbar_ui(world: &mut World, ui: &mut egui::Ui, selected: &mut SelectedE
.layout(egui::Layout::left_to_right(egui::Align::Center)), .layout(egui::Layout::left_to_right(egui::Align::Center)),
); );
left_ui.spacing_mut().item_spacing.x = 6.0; left_ui.spacing_mut().item_spacing.x = 6.0;
left_toolbar(world, &mut left_ui); left_toolbar(world, &mut left_ui, viewport_rect);
let mut transport_ui = ui.new_child( let mut transport_ui = ui.new_child(
egui::UiBuilder::new() egui::UiBuilder::new()
@@ -100,7 +105,7 @@ pub fn toolbar_ui(world: &mut World, ui: &mut egui::Ui, selected: &mut SelectedE
); );
} }
fn left_toolbar(world: &mut World, ui: &mut egui::Ui) { fn left_toolbar(world: &mut World, ui: &mut egui::Ui, viewport_rect: egui::Rect) {
brand_mark_frame().show(ui, |ui| { brand_mark_frame().show(ui, |ui| {
ui.set_min_width(118.0); ui.set_min_width(118.0);
ui.set_min_height(30.0); ui.set_min_height(30.0);
@@ -126,16 +131,16 @@ fn left_toolbar(world: &mut World, ui: &mut egui::Ui) {
toolbar_group_frame().show(ui, |ui| { toolbar_group_frame().show(ui, |ui| {
panel_toolbar_row(ui, |ui| { panel_toolbar_row(ui, |ui| {
if icon_button(ui, icons::CUBE, "Spawn cube").clicked() { if icon_button(ui, icons::CUBE, "Spawn cube").clicked() {
spawn_primitive_at_camera(world, PrimitiveShape::Box, "Cube"); spawn_primitive_at_camera(world, PrimitiveShape::Box, "Cube", viewport_rect);
} }
if icon_button(ui, icons::MOUNTAINS, "Spawn ramp").clicked() { if icon_button(ui, icons::MOUNTAINS, "Spawn ramp").clicked() {
spawn_primitive_at_camera(world, PrimitiveShape::Ramp, "Ramp"); spawn_primitive_at_camera(world, PrimitiveShape::Ramp, "Ramp", viewport_rect);
} }
if icon_button(ui, icons::SPHERE, "Spawn sphere").clicked() { if icon_button(ui, icons::SPHERE, "Spawn sphere").clicked() {
spawn_primitive_at_camera(world, PrimitiveShape::Sphere, "Sphere"); spawn_primitive_at_camera(world, PrimitiveShape::Sphere, "Sphere", viewport_rect);
} }
if icon_button(ui, icons::LIGHTBULB, "Spawn point light").clicked() { if icon_button(ui, icons::LIGHTBULB, "Spawn point light").clicked() {
let pos = camera_ground_spawn(world); let pos = camera_ground_spawn(world, viewport_rect);
spawn_with_history(world, light_snapshot("Point Light", pos)); spawn_with_history(world, light_snapshot("Point Light", pos));
} }
if icon_button(ui, icons::PENCIL_SIMPLE_LINE, "Draw brush (B)").clicked() { if icon_button(ui, icons::PENCIL_SIMPLE_LINE, "Draw brush (B)").clicked() {
@@ -157,6 +162,7 @@ fn left_toolbar(world: &mut World, ui: &mut egui::Ui) {
super::navigation_inspector::spawn_navigation_actor( super::navigation_inspector::spawn_navigation_actor(
world, world,
super::navigation_inspector::NavigationActorType::Bounds, super::navigation_inspector::NavigationActorType::Bounds,
viewport_rect,
); );
} }
} }
@@ -232,14 +238,68 @@ fn transport_controls(world: &mut World, ui: &mut egui::Ui) {
} }
} }
fn camera_ground_spawn(world: &mut World) -> Vec3 { fn camera_ground_spawn(world: &mut World, viewport_rect: egui::Rect) -> Vec3 {
let rect = world.resource::<UiState>().viewport_rect;
let settings = world.resource::<ViewportSettings>().clone(); let settings = world.resource::<ViewportSettings>().clone();
let pos = editor_spawn_ground_position(world, rect); let pos = editor_spawn_ground_position(world, viewport_rect);
snap_translation(pos, &settings) snap_translation(pos, &settings)
} }
fn spawn_primitive_at_camera(world: &mut World, shape: PrimitiveShape, name: &str) { fn spawn_primitive_at_camera(
let pos = camera_ground_spawn(world); world: &mut World,
spawn_with_history(world, primitive_snapshot(name, shape, pos)); shape: PrimitiveShape,
name: &str,
viewport_rect: egui::Rect,
) -> Entity {
let pos = camera_ground_spawn(world, viewport_rect);
spawn_with_history(world, primitive_snapshot(name, shape, pos))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::history::EditorHistory;
use crate::scene_io::SceneIo;
use crate::selection::SelectedEntity;
use crate::ui::{PendingUiSelection, UiState};
use shared::{LevelObject, Primitive};
#[test]
fn primitive_spawn_works_while_ui_state_is_scoped_out_of_world() {
let mut world = World::new();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<SelectedEntity>();
world.init_resource::<PendingUiSelection>();
world.init_resource::<ViewportSettings>();
let mut ui_state = UiState::default_layout();
ui_state.viewport_rect =
egui::Rect::from_min_size(egui::pos2(100.0, 80.0), egui::vec2(1280.0, 720.0));
world.insert_resource(ui_state);
let entity = world.resource_scope::<UiState, _>(|world, mut ui_state| {
assert!(!world.contains_resource::<UiState>());
let entity = spawn_primitive_at_camera(
world,
PrimitiveShape::Box,
"Cube",
ui_state.viewport_rect,
);
let pending = world.resource_mut::<PendingUiSelection>().0.take();
super::super::reconcile_operator_selection(
&mut ui_state.selected_entities,
&[],
world.resource::<SelectedEntity>().0,
pending.as_deref(),
);
assert_eq!(ui_state.selected_entities.as_slice(), &[entity]);
entity
});
assert!(world.contains_resource::<UiState>());
assert!(world.get::<LevelObject>(entity).is_some());
assert!(world.get::<Primitive>(entity).is_some());
assert_eq!(world.resource::<SelectedEntity>().0, Some(entity));
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
}
} }
+551 -67
View File
@@ -7,22 +7,28 @@ use egui_phosphor_icons::icons;
use transform_gizmo_bevy::prelude::GizmoOptions; use transform_gizmo_bevy::prelude::GizmoOptions;
use crate::assets::operators::{ use crate::assets::operators::{
apply_material_operator, apply_texture_operator, assign_animation_clip_operator, assign_animation_clip_operator, assign_audio_clip_operator, place_asset_operator,
assign_audio_clip_operator, place_asset_operator, place_subasset_operator, place_subasset_operator,
}; };
use crate::assets::thumbnails::kind_icon; use crate::assets::thumbnails::kind_icon;
use crate::assets::{AssetSelection, AssetSubAssetKind, EditorAssets}; use crate::assets::{AssetSelection, AssetSubAssetKind, EditorAssets};
use crate::camera::EditorCamera; use crate::camera::EditorCamera;
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace}; use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
use crate::render_target::ViewportRenderTarget; use crate::render_target::ViewportRenderTarget;
use crate::selection::{ViewportClick, ViewportPickStack}; use crate::selection::{SelectedEntity, ViewportClick, ViewportPickStack};
use crate::state::PlayPossession; use crate::state::PlayPossession;
use crate::viewport::actor_icons::ActorIconSettings; use crate::viewport::actor_icons::ActorIconSettings;
use crate::viewport::brush_edit::{BrushEditMode, BrushElementSelection}; use crate::viewport::brush_edit::{BrushEditMode, BrushElementSelection};
use crate::viewport::brush_tool::{BrushToolPhase, BrushToolState}; 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::{ use crate::viewport::{
snap_translation, viewport_ground_position, EditorViewportMode, ViewportDisplayMode, material_drop::is_surface_asset_selection, snap_translation, viewport_ground_position,
ViewportSettings, EditorViewportMode, MaterialDropState, ViewportDisplayMode, ViewportSettings,
}; };
use super::helpers::{ use super::helpers::{
@@ -30,7 +36,8 @@ use super::helpers::{
}; };
use super::theme::{ use super::theme::{
overlay_chip_frame, viewport_toolbar_frame, ACCENT, ACCENT_HOVER, AXIS_X, AXIS_Y, AXIS_Z, 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::{ use super::widgets::{
icon_button_small, panel_toolbar_row, phosphor_icon, tool_button, tool_button_accent, icon_button_small, panel_toolbar_row, phosphor_icon, tool_button, tool_button_accent,
@@ -40,6 +47,7 @@ use super::widgets::{
pub struct ViewportUiState { pub struct ViewportUiState {
pub options_open: bool, pub options_open: bool,
pub shortcuts_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)"; 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 clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
let response = ui.allocate_rect(rect, egui::Sense::HOVER); let response = ui.allocate_rect(rect, egui::Sense::HOVER);
*viewport_pointer_pos = response // A drag source owns egui's interaction response, so `Response::hover_pos()`
.interact_pointer_pos() // is intentionally empty while an asset is dragged over the viewport. The
.or_else(|| response.hover_pos()) // 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)); .filter(|pos| rect.contains(*pos));
*pointer_in_viewport = viewport_pointer_pos.is_some(); *pointer_in_viewport = viewport_pointer_pos.is_some();
@@ -134,9 +150,12 @@ pub fn viewport_tab_ui(
return; 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_selection_hud(world, ui.ctx(), rect, selected_entities);
scene_view_brush_draw_hints(world, ui.ctx(), rect); 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_render_badge(world, ui.ctx(), rect);
scene_view_brush_mode_badge(world, ui.ctx(), rect); scene_view_brush_mode_badge(world, ui.ctx(), rect);
scene_view_volume_hud(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 { 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")) egui::Area::new(egui::Id::new("scene_view_collider_warning"))
.fixed_pos(scene_rect.left_bottom() + egui::vec2(8.0, -28.0)) .fixed_pos(scene_rect.left_bottom() + egui::vec2(8.0, -28.0))
.interactable(false) .interactable(false)
.show(ctx, |ui| { .show(ctx, |ui| {
overlay_chip_frame().show(ui, |ui| { overlay_chip_frame().show(ui, |ui| {
ui.horizontal_wrapped(|ui| {
ui.label( ui.label(
egui::RichText::new("Collider view / meshes hidden") egui::RichText::new("Collider View")
.color(WARNING) .color(WARNING)
.strong()
.small(), .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) { fn key_hint(ui: &mut egui::Ui, key: &str, label: &str) {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label( 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 options_open = world.resource::<ViewportUiState>().options_open;
let mut shortcuts_open = world.resource::<ViewportUiState>().shortcuts_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)) .fixed_pos(scene_rect.left_top() + egui::vec2(6.0, 6.0))
.interactable(true) .interactable(true)
.show(ctx, |ui| { .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; let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
if tool_button( if tool_button(
ui, 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 { if options_open {
scene_options_popover(world, ctx, scene_rect, &mut 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; 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( fn scene_options_popover(
world: &mut World, world: &mut World,
ctx: &egui::Context, ctx: &egui::Context,
@@ -820,11 +1277,44 @@ fn viewport_asset_drop_ui(
.resource::<EditorAssets>() .resource::<EditorAssets>()
.dragging_selection() .dragging_selection()
.cloned(); .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() .as_ref()
.and_then(|selection| asset_drag_descriptor(world, selection, selected)); .and_then(|selection| asset_drag_descriptor(world, selection, selected));
let over_viewport = pointer_pos.is_some_and(|pos| viewport_rect.contains(pos)); 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()) { if let (Some(pointer), Some((icon, label, action))) = (pointer_pos, drag_descriptor.as_ref()) {
draw_asset_drag_preview( draw_asset_drag_preview(
ui, ui,
@@ -833,7 +1323,7 @@ fn viewport_asset_drop_ui(
*icon, *icon,
label, label,
action, action,
over_viewport, drag_visual_state,
); );
} }
@@ -841,7 +1331,7 @@ fn viewport_asset_drop_ui(
ui.painter().rect_stroke( ui.painter().rect_stroke(
viewport_rect.shrink(2.0), viewport_rect.shrink(2.0),
0.0, 0.0,
egui::Stroke::new(2.0, ACCENT_HOVER), egui::Stroke::new(2.0, highlight_color),
egui::StrokeKind::Inside, egui::StrokeKind::Inside,
); );
} }
@@ -851,6 +1341,11 @@ fn viewport_asset_drop_ui(
return; 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)) { if !pointer_pos.is_some_and(|pos| viewport_rect.contains(pos)) {
world.resource_mut::<EditorAssets>().clear_drag(); world.resource_mut::<EditorAssets>().clear_drag();
return; return;
@@ -903,26 +1398,6 @@ fn viewport_asset_drop_ui(
return; 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 asset = {
let assets = world.resource::<EditorAssets>(); let assets = world.resource::<EditorAssets>();
assets.asset_for_selection(&selection).cloned() assets.asset_for_selection(&selection).cloned()
@@ -943,18 +1418,6 @@ fn viewport_asset_drop_ui(
} }
return; 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); place_asset_operator(world, asset, placement);
} }
@@ -996,11 +1459,11 @@ fn asset_drag_descriptor(
AssetSelection::SubAsset { AssetSelection::SubAsset {
kind: AssetSubAssetKind::Texture, kind: AssetSubAssetKind::Texture,
.. ..
} if !selected.is_empty() => "Apply texture to selection", } => "Drop onto a primitive or brush face",
AssetSelection::SubAsset { AssetSelection::SubAsset {
kind: AssetSubAssetKind::Material, kind: AssetSubAssetKind::Material,
.. ..
} if !selected.is_empty() => "Apply material to selection", } => "Drop onto an exact renderer slot",
AssetSelection::SubAsset { AssetSelection::SubAsset {
kind: AssetSubAssetKind::Skeleton, kind: AssetSubAssetKind::Skeleton,
.. ..
@@ -1020,12 +1483,8 @@ fn asset_drag_descriptor(
.. ..
} => "Create animated actor", } => "Create animated actor",
_ => match asset.kind { _ => match asset.kind {
crate::assets::EditorAssetKind::Texture if !selected.is_empty() => { crate::assets::EditorAssetKind::Texture => "Drop onto a primitive or brush face",
"Apply texture to selection" crate::assets::EditorAssetKind::Material => "Drop onto a renderable surface",
}
crate::assets::EditorAssetKind::Material if !selected.is_empty() => {
"Apply material to selection"
}
crate::assets::EditorAssetKind::AudioClip crate::assets::EditorAssetKind::AudioClip
if selected if selected
.as_slice() .as_slice()
@@ -1041,6 +1500,29 @@ fn asset_drag_descriptor(
Some((icon, label, action.to_string())) 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( fn draw_asset_drag_preview(
ui: &egui::Ui, ui: &egui::Ui,
viewport_rect: egui::Rect, viewport_rect: egui::Rect,
@@ -1048,39 +1530,41 @@ fn draw_asset_drag_preview(
icon: egui_phosphor_icons::Icon, icon: egui_phosphor_icons::Icon,
label: &str, label: &str,
action: &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 { if over_viewport {
let painter = ui.painter(); let painter = ui.painter();
painter.circle_filled(pointer, 3.0, ACCENT_HOVER); painter.circle_filled(pointer, 3.0, highlight_color);
painter.circle_stroke(pointer, 11.0, egui::Stroke::new(1.5, ACCENT_HOVER)); painter.circle_stroke(pointer, 11.0, egui::Stroke::new(1.5, highlight_color));
painter.line_segment( painter.line_segment(
[ [
pointer - egui::vec2(17.0, 0.0), pointer - egui::vec2(17.0, 0.0),
pointer - egui::vec2(7.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( painter.line_segment(
[ [
pointer + egui::vec2(7.0, 0.0), pointer + egui::vec2(7.0, 0.0),
pointer + egui::vec2(17.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( painter.line_segment(
[ [
pointer - egui::vec2(0.0, 17.0), pointer - egui::vec2(0.0, 17.0),
pointer - egui::vec2(0.0, 7.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( painter.line_segment(
[ [
pointer + egui::vec2(0.0, 7.0), pointer + egui::vec2(0.0, 7.0),
pointer + egui::vec2(0.0, 17.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.set_width(228.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(phosphor_icon(icon, 20.0).color(if over_viewport { ui.label(phosphor_icon(icon, 20.0).color(if over_viewport {
ACCENT_HOVER highlight_color
} else { } else {
TEXT_DIM TEXT_DIM
})); }));
@@ -1116,7 +1600,7 @@ fn draw_asset_drag_preview(
}) })
.size(11.0) .size(11.0)
.color(if over_viewport { .color(if over_viewport {
ACCENT_HOVER highlight_color
} else { } else {
TEXT_MUTED TEXT_MUTED
}), }),
@@ -1152,9 +1636,9 @@ fn draw_asset_drag_preview(
), ),
] { ] {
ui.painter() 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() 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, image: ActorIconImage::Mesh,
category: ActorIconCategory::Mesh, category: ActorIconCategory::Mesh,
}, },
ActorKind::Terrain => ActorIconSpec {
image: ActorIconImage::Mesh,
category: ActorIconCategory::Mesh,
},
ActorKind::StaticMesh => { ActorKind::StaticMesh => {
if components.has_primitive || components.has_static_mesh_renderer { if components.has_primitive || components.has_static_mesh_renderer {
ActorIconSpec { ActorIconSpec {
+54 -30
View File
@@ -4,7 +4,7 @@ use bevy::math::Affine3A;
use bevy::prelude::*; use bevy::prelude::*;
use shared::{ use shared::{
brush_math::{validate_brush, BrushDiagnosticSeverity}, brush_math::{validate_brush, BrushDiagnosticSeverity},
BrushDesc, LevelObject, BrushDesc,
}; };
use crate::history::apply_brush_csg_with_history; use crate::history::apply_brush_csg_with_history;
@@ -64,24 +64,27 @@ pub fn selected_brush_count(world: &World) -> usize {
.resource::<UiState>() .resource::<UiState>()
.selected_entities .selected_entities
.iter() .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() .count()
} }
pub fn intersect_selected_brushes(world: &mut World) { pub fn intersect_selected_brushes(world: &mut World) -> Result<(), String> {
run_bounds_csg(world, BrushCsgOp::Intersect); run_bounds_csg(world, BrushCsgOp::Intersect)
} }
pub fn merge_selected_brushes(world: &mut World) { pub fn merge_selected_brushes(world: &mut World) -> Result<(), String> {
run_bounds_csg(world, BrushCsgOp::Merge); run_bounds_csg(world, BrushCsgOp::Merge)
} }
pub fn subtract_selected_brushes(world: &mut World) { pub fn subtract_selected_brushes(world: &mut World) -> Result<(), String> {
run_bounds_csg(world, BrushCsgOp::Subtract); run_bounds_csg(world, BrushCsgOp::Subtract)
} }
#[derive(Resource, Default, Debug, Clone)] #[derive(Resource, Default, Debug, Clone)]
struct BrushCsgPreview { pub(crate) struct BrushCsgPreview {
pending: Option<PendingBrushCsg>, pending: Option<PendingBrushCsg>,
} }
@@ -99,18 +102,18 @@ enum BrushCsgOp {
Subtract, 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 let selected: Vec<Entity> = world
.resource::<UiState>() .resource::<UiState>()
.selected_entities .selected_entities
.iter() .iter()
.filter(|entity| { .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(); .collect();
if selected.len() < 2 { if selected.len() < 2 {
set_status(world, "Select at least two brushes for CSG"); return csg_failure(world, "Select at least two editable brushes for CSG");
return;
} }
for entity in &selected { for entity in &selected {
let Some(brush) = world.get::<BrushDesc>(*entity) else { 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); let validation = validate_brush(brush);
if !validation.is_valid() { if !validation.is_valid() {
set_status( return csg_failure(
world, world,
format!( format!(
"CSG failed: selected brush is invalid: {}", "CSG failed: selected brush is invalid: {}",
first_brush_error(&validation) first_brush_error(&validation)
), ),
); );
return;
} }
} }
let Some(primary_bounds) = brush_world_bounds(world, selected[0]) else { let Some(primary_bounds) = brush_world_bounds(world, selected[0]) else {
set_status(world, "Primary brush has no valid bounds"); return csg_failure(world, "Primary brush has no valid bounds");
return;
}; };
let result = match op { let result = match op {
@@ -147,8 +148,7 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
continue; continue;
}; };
let Some(intersection) = result.intersection(bounds) else { let Some(intersection) = result.intersection(bounds) else {
set_status(world, "Brush intersect failed: no overlap"); return csg_failure(world, "Brush intersect failed: no overlap");
return;
}; };
result = intersection; result = intersection;
} }
@@ -156,16 +156,13 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
} }
BrushCsgOp::Subtract => { BrushCsgOp::Subtract => {
let Some(cutter_bounds) = brush_world_bounds(world, selected[1]) else { let Some(cutter_bounds) = brush_world_bounds(world, selected[1]) else {
set_status(world, "Subtract failed: cutter brush has no valid bounds"); return csg_failure(world, "Subtract failed: cutter brush has no valid bounds");
return;
}; };
let Some(overlap) = primary_bounds.intersection(cutter_bounds) else { let Some(overlap) = primary_bounds.intersection(cutter_bounds) else {
set_status(world, "Subtract failed: brushes do not overlap"); return csg_failure(world, "Subtract failed: brushes do not overlap");
return;
}; };
let Some(result) = largest_remaining_slab(primary_bounds, overlap) else { let Some(result) = largest_remaining_slab(primary_bounds, overlap) else {
set_status(world, "Subtract failed: result would be empty"); return csg_failure(world, "Subtract failed: result would be empty");
return;
}; };
result result
} }
@@ -175,14 +172,13 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
let new_brush = BrushDesc::cuboid(size); let new_brush = BrushDesc::cuboid(size);
let validation = validate_brush(&new_brush); let validation = validate_brush(&new_brush);
if !validation.is_valid() { if !validation.is_valid() {
set_status( return csg_failure(
world, world,
format!( format!(
"CSG failed: result is invalid: {}", "CSG failed: result is invalid: {}",
first_brush_error(&validation) first_brush_error(&validation)
), ),
); );
return;
} }
world.resource_mut::<BrushCsgPreview>().pending = Some(PendingBrushCsg { 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_status(world, hint);
set_csg_operator_status(world, OperatorPhase::Preview, 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) { fn brush_csg_preview_input(world: &mut World) {
@@ -253,6 +256,22 @@ fn commit_csg_preview(world: &mut World, pending: PendingBrushCsg) {
); );
return; 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 new_brush = BrushDesc::cuboid(pending.result.size());
let to_delete: Vec<_> = if matches!(pending.op, BrushCsgOp::Merge | BrushCsgOp::Intersect) { let to_delete: Vec<_> = if matches!(pending.op, BrushCsgOp::Merge | BrushCsgOp::Intersect) {
pending pending
@@ -265,7 +284,11 @@ fn commit_csg_preview(world: &mut World, pending: PendingBrushCsg) {
} else { } else {
Vec::new() 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 { let hint = match pending.op {
BrushCsgOp::Intersect => "Brush intersect committed", BrushCsgOp::Intersect => "Brush intersect committed",
BrushCsgOp::Merge => "Brush convex merge committed", BrushCsgOp::Merge => "Brush convex merge committed",
@@ -332,14 +355,14 @@ fn apply_bounds_result(
bounds: BrushBounds, bounds: BrushBounds,
new_brush: BrushDesc, new_brush: BrushDesc,
delete_entities: &[Entity], delete_entities: &[Entity],
) { ) -> bool {
let center = bounds.center(); let center = bounds.center();
let old_transform = world.get::<Transform>(entity).copied().unwrap_or_default(); let old_transform = world.get::<Transform>(entity).copied().unwrap_or_default();
let mut new_transform = old_transform; let mut new_transform = old_transform;
new_transform.translation = center; new_transform.translation = center;
new_transform.rotation = Quat::IDENTITY; new_transform.rotation = Quat::IDENTITY;
new_transform.scale = Vec3::ONE; 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> { fn brush_world_bounds(world: &World, entity: Entity) -> Option<BrushBounds> {
@@ -426,6 +449,7 @@ mod tests {
use crate::history::{EditorCommand, EditorHistory}; use crate::history::{EditorCommand, EditorHistory};
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness}; use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
use crate::selection::SelectedEntity; use crate::selection::SelectedEntity;
use shared::LevelObject;
fn bounds(min: Vec3, max: Vec3) -> BrushBounds { fn bounds(min: Vec3, max: Vec3) -> BrushBounds {
BrushBounds { min, max } BrushBounds { min, max }
+62
View File
@@ -1047,6 +1047,17 @@ fn pick_face(
best 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> { fn world_vertices(face: &BrushFaceDesc, transform: &GlobalTransform) -> Vec<Vec3> {
face.vertices face.vertices
.iter() .iter()
@@ -1297,4 +1308,55 @@ mod tests {
assert!(state.old_brush.is_none()); assert!(state.old_brush.is_none());
assert!(!state.changed); 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_edit;
pub mod brush_tool; pub mod brush_tool;
pub mod camera; pub mod camera;
pub mod collider_diagnostics;
pub mod gizmos; pub mod gizmos;
pub mod material_drop;
mod panel; mod panel;
pub mod physics_placement;
pub mod render_view; pub mod render_view;
pub mod rendering_diagnostics; pub mod rendering_diagnostics;
pub mod selection; pub mod selection;
pub mod selection_outline; pub mod selection_outline;
pub mod terrain_paint;
pub mod terrain_sculpt;
pub mod viewport_mode; pub mod viewport_mode;
pub mod visualizers; pub mod visualizers;
@@ -21,5 +26,9 @@ pub use brush_csg::{
}; };
pub use brush_edit::{BrushEditMode, BrushEditPlugin, BrushElementSelection}; pub use brush_edit::{BrushEditMode, BrushEditPlugin, BrushElementSelection};
pub use brush_tool::{BrushToolPlugin, BrushToolState}; pub use brush_tool::{BrushToolPlugin, BrushToolState};
pub use material_drop::{MaterialDropFeedback, MaterialDropPlugin, MaterialDropState};
pub use panel::*; 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; 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_ops::is_entity_locked;
use crate::ui::hierarchy_state::HierarchyPanelState; use crate::ui::hierarchy_state::HierarchyPanelState;
use crate::ui::UiState; use crate::ui::UiState;
use crate::ui::ViewportUiState;
use crate::viewport::actor_icons::ActorIconProxy; use crate::viewport::actor_icons::ActorIconProxy;
use crate::viewport::brush_edit::{BrushEditMode, BrushElementGizmo}; use crate::viewport::brush_edit::{BrushEditMode, BrushElementGizmo};
use crate::viewport::brush_tool::BrushToolState; use crate::viewport::brush_tool::BrushToolState;
@@ -21,7 +22,11 @@ use crate::viewport::ViewportDisplayMode;
use crate::visualizers::EditorVisualizerProxy; use crate::visualizers::EditorVisualizerProxy;
use bevy_egui::egui; 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::scene_view_ray;
use crate::viewport::terrain_paint::TerrainPaintState;
use crate::viewport::terrain_sculpt::TerrainSculptState;
#[derive(Resource, Default, Debug, Clone, Copy)] #[derive(Resource, Default, Debug, Clone, Copy)]
pub struct SelectedEntity(pub Option<Entity>); pub struct SelectedEntity(pub Option<Entity>);
@@ -47,6 +52,11 @@ struct PickTargetQueries<'w, 's> {
icon_proxies: Query<'w, 's, &'static ActorIconProxy>, icon_proxies: Query<'w, 's, &'static ActorIconProxy>,
parents: Query<'w, 's, &'static ChildOf>, parents: Query<'w, 's, &'static ChildOf>,
editor_only: Query<'w, 's, (), With<EditorOnly>>, 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 { impl Plugin for EditorSelectionPlugin {
@@ -68,6 +78,7 @@ impl Plugin for EditorSelectionPlugin {
Last, Last,
(handle_pick_events, cycle_overlapping_viewport_pick) (handle_pick_events, cycle_overlapping_viewport_pick)
.chain() .chain()
.after(MaterialDropSet)
.run_if(scene_tools_active), .run_if(scene_tools_active),
); );
} }
@@ -110,6 +121,35 @@ fn handle_pick_events(
gizmo_targets: Query<&GizmoTarget>, gizmo_targets: Query<&GizmoTarget>,
hierarchy: Option<Res<HierarchyPanelState>>, hierarchy: Option<Res<HierarchyPanelState>>,
) -> Result { ) -> 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 if ui_state.pointer_in_viewport
&& !buttons.any_pressed([MouseButton::Right, MouseButton::Middle]) && !buttons.any_pressed([MouseButton::Right, MouseButton::Middle])
&& keys.just_pressed(KeyCode::Escape) && keys.just_pressed(KeyCode::Escape)
@@ -209,6 +249,10 @@ fn handle_pick_events(
Ok(()) Ok(())
} }
#[expect(
clippy::too_many_arguments,
reason = "selection cycling reads independent viewport input ownership resources"
)]
fn cycle_overlapping_viewport_pick( fn cycle_overlapping_viewport_pick(
mut ui_state: ResMut<UiState>, mut ui_state: ResMut<UiState>,
mut selected: ResMut<SelectedEntity>, mut selected: ResMut<SelectedEntity>,
@@ -216,7 +260,19 @@ fn cycle_overlapping_viewport_pick(
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
buttons: Res<ButtonInput<MouseButton>>, buttons: Res<ButtonInput<MouseButton>>,
display: Res<ViewportDisplayMode>, display: Res<ViewportDisplayMode>,
material_drop: Option<Res<MaterialDropState>>,
terrain_sculpt: Res<TerrainSculptState>,
terrain_paint: Res<TerrainPaintState>,
) -> Result { ) -> 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 { if display.clean_game_view {
return Ok(()); return Ok(());
} }
@@ -397,13 +453,23 @@ fn sync_gizmo_targets(
hierarchy: Option<Res<HierarchyPanelState>>, hierarchy: Option<Res<HierarchyPanelState>>,
display: Res<ViewportDisplayMode>, display: Res<ViewportDisplayMode>,
brush_mode: Res<BrushEditMode>, brush_mode: Res<BrushEditMode>,
terrain_sculpt: Res<TerrainSculptState>,
terrain_paint: Res<TerrainPaintState>,
physics_placement: Option<Res<PhysicsPlacementState>>,
) { ) {
ui_state ui_state
.selected_entities .selected_entities
.retain(|entity| transforms.contains(entity) && !editor_only.contains(entity)); .retain(|entity| transforms.contains(entity) && !editor_only.contains(entity));
selected.0 = ui_state.selected_entities.as_slice().first().copied(); 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 { for (entity, brush_element_gizmo) in &targets {
if brush_element_gizmo.is_none() { if brush_element_gizmo.is_none() {
commands.entity(entity).remove::<GizmoTarget>(); commands.entity(entity).remove::<GizmoTarget>();
@@ -456,6 +522,8 @@ mod tests {
.init_resource::<SelectedEntity>() .init_resource::<SelectedEntity>()
.init_resource::<ViewportDisplayMode>() .init_resource::<ViewportDisplayMode>()
.init_resource::<BrushEditMode>() .init_resource::<BrushEditMode>()
.init_resource::<TerrainSculptState>()
.init_resource::<TerrainPaintState>()
.add_systems(Update, sync_gizmo_targets); .add_systems(Update, sync_gizmo_targets);
app.update(); app.update();
@@ -470,4 +538,50 @@ mod tests {
assert!(app.world().get::<GizmoTarget>(first).is_some()); assert!(app.world().get::<GizmoTarget>(first).is_some());
assert!(app.world().get::<GizmoTarget>(second).is_none()); 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
+192 -59
View File
@@ -1,14 +1,16 @@
//! Editor-side scene visualizers for authoring/runtime entities that have no mesh. //! 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::ecs::system::SystemParam;
use bevy::prelude::*; use bevy::prelude::*;
use shared::{ use shared::{
AudioListenerDesc, AudioSourceDesc, AuthoringLightKind, ColliderDesc, ColliderShapeDesc, AudioListenerDesc, AudioSourceDesc, AuthoringLightKind, ColliderDesc, ColliderShapeDesc,
LevelObject, LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink, LevelObject, LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink,
NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc,
PrefabRef, ProjectSun, RaytracingExcluded, SkinnedMeshRenderer, TeamSpawn, TriggerVolume, PrefabRef, ProjectSun, RaytracingExcluded, RigidBodyDesc, SkinnedMeshRenderer, TeamSpawn,
WeaponSpawn, TriggerVolume, WeaponSpawn,
}; };
use sim::tuning::{EYE_OFFSET_STAND, PLAYER_LENGTH, PLAYER_RADIUS}; use sim::tuning::{EYE_OFFSET_STAND, PLAYER_LENGTH, PLAYER_RADIUS};
use sim::{Player, PlayerCamera}; use sim::{Player, PlayerCamera};
@@ -16,6 +18,10 @@ use sim::{Player, PlayerCamera};
use crate::infra::EditorOnly; use crate::infra::EditorOnly;
use crate::selection::SelectedEntity; use crate::selection::SelectedEntity;
use crate::state::{scene_tools_active, EditorMode, PlayPossession}; use crate::state::{scene_tools_active, EditorMode, PlayPossession};
use crate::viewport::collider_diagnostics::{
refresh_collider_diagnostics, ColliderDiagnosticEntry, ColliderDiagnosticsState,
ColliderOverlayStatus,
};
use crate::viewport::{EditorViewportMode, ViewportDisplayMode}; use crate::viewport::{EditorViewportMode, ViewportDisplayMode};
#[derive(Resource, Debug, Clone)] #[derive(Resource, Debug, Clone)]
@@ -102,7 +108,7 @@ struct VisualizerTargetQueries<'w, 's> {
Entity, Entity,
( (
With<LevelObject>, With<LevelObject>,
Or<(With<PhysicsBody>, With<ColliderDesc>)>, Or<(With<PhysicsBody>, With<ColliderDesc>, With<RigidBodyDesc>)>,
), ),
>, >,
lights: Query<'w, 's, Entity, (With<LevelObject>, With<LightDesc>)>, lights: Query<'w, 's, Entity, (With<LevelObject>, With<LightDesc>)>,
@@ -127,7 +133,15 @@ pub struct EditorVisualizersPlugin;
impl Plugin for EditorVisualizersPlugin { impl Plugin for EditorVisualizersPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.init_resource::<EditorVisualizationSettings>() app.init_resource::<EditorVisualizationSettings>()
.init_resource::<ColliderDiagnosticsState>()
.add_systems(Startup, init_visualizer_proxy_assets) .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, sync_visualizer_proxies)
.add_systems( .add_systems(
Update, Update,
@@ -135,6 +149,7 @@ impl Plugin for EditorVisualizersPlugin {
draw_visualizers, draw_visualizers,
draw_audio_visualizers, draw_audio_visualizers,
draw_split_collider_visualizers, draw_split_collider_visualizers,
draw_missing_collider_visualizers,
draw_post_process_volume_gizmos, draw_post_process_volume_gizmos,
draw_navigation_visualizers, 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( fn draw_navigation_visualizers(
state: Res<crate::ui::navigation_inspector::NavigationEditorState>, state: Res<crate::ui::navigation_inspector::NavigationEditorState>,
mut gizmos: Gizmos, mut gizmos: Gizmos,
@@ -556,17 +617,7 @@ fn draw_visualizers(
if settings.show_colliders || collider_mode { if settings.show_colliders || collider_mode {
for (entity, body, global) in &colliders { for (entity, body, global) in &colliders {
let color = if selected.0 == Some(entity) { let color = collider_overlay_color(None, selected.0 == Some(entity), collider_mode);
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)
};
draw_collider(&mut gizmos, global, &body.collider, color); 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( fn draw_split_collider_visualizers(
viewport_mode: Res<EditorViewportMode>, viewport_mode: Res<EditorViewportMode>,
settings: Res<EditorVisualizationSettings>, settings: Res<EditorVisualizationSettings>,
diagnostics: Res<ColliderDiagnosticsState>,
selected: Res<SelectedEntity>, selected: Res<SelectedEntity>,
mut gizmos: Gizmos, mut gizmos: Gizmos,
children: Query<&Children>,
runtime_aabbs: Query<&ColliderAabb>,
colliders: Query< colliders: Query<
(Entity, &ColliderDesc, &GlobalTransform), (Entity, &ColliderDesc, &GlobalTransform),
(With<LevelObject>, Without<PhysicsBody>), (With<LevelObject>, Without<PhysicsBody>),
@@ -697,16 +755,79 @@ fn draw_split_collider_visualizers(
return; return;
} }
for (entity, collider, global) in &colliders { for (entity, collider, global) in &colliders {
let color = if selected.0 == Some(entity) { let color = collider_overlay_color(
Color::srgba(0.65, 1.0, 0.55, 1.0) diagnostics.entry(entity),
} else if collider_mode { selected.0 == Some(entity),
Color::srgba(0.35, 1.0, 0.45, 0.9) collider_mode,
} else { );
Color::srgba(0.25, 0.9, 0.35, 0.55) 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); 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( fn draw_post_process_volume_gizmos(
viewport_mode: Res<EditorViewportMode>, viewport_mode: Res<EditorViewportMode>,
@@ -741,6 +862,8 @@ fn draw_collider(
collider: &ColliderConstructor, collider: &ColliderConstructor,
color: Color, color: Color,
) { ) {
let (scale, rotation, translation) = global.to_scale_rotation_translation();
let scale = scale.abs();
match collider { match collider {
ColliderConstructor::Cuboid { ColliderConstructor::Cuboid {
x_length, x_length,
@@ -748,27 +871,21 @@ fn draw_collider(
z_length, z_length,
} => draw_box( } => draw_box(
gizmos, gizmos,
global.translation(), translation,
global.rotation(), rotation,
Vec3::new(*x_length, *y_length, *z_length) * 0.5, Vec3::new(*x_length, *y_length, *z_length) * scale * 0.5,
color, color,
), ),
ColliderConstructor::Sphere { radius } => { ColliderConstructor::Sphere { radius } => {
gizmos draw_ellipsoid(gizmos, translation, rotation, scale * *radius, color);
.sphere(
Isometry3d::new(global.translation(), global.rotation()),
*radius,
color,
)
.resolution(24);
} }
ColliderConstructor::Capsule { radius, height } => { ColliderConstructor::Capsule { radius, height } => {
draw_capsule( draw_capsule(
gizmos, gizmos,
global.translation(), translation,
global.rotation(), rotation,
*radius, *radius * scale.x.max(scale.z),
*height, *height * scale.y,
color, color,
); );
} }
@@ -790,9 +907,8 @@ fn draw_collider_desc(
collider: &ColliderDesc, collider: &ColliderDesc,
color: Color, color: Color,
) { ) {
if !collider.enabled { let (scale, rotation, translation) = global.to_scale_rotation_translation();
return; let scale = scale.abs();
}
match &collider.shape { match &collider.shape {
ColliderShapeDesc::Cuboid { ColliderShapeDesc::Cuboid {
x_length, x_length,
@@ -800,40 +916,57 @@ fn draw_collider_desc(
z_length, z_length,
} => draw_box( } => draw_box(
gizmos, gizmos,
global.translation(), translation,
global.rotation(), rotation,
Vec3::new(*x_length, *y_length, *z_length) * 0.5, Vec3::new(*x_length, *y_length, *z_length) * scale * 0.5,
color, color,
), ),
ColliderShapeDesc::Sphere { radius } => { ColliderShapeDesc::Sphere { radius } => {
gizmos draw_ellipsoid(gizmos, translation, rotation, scale * *radius, color);
.sphere(
Isometry3d::new(global.translation(), global.rotation()),
*radius,
color,
)
.resolution(24);
} }
ColliderShapeDesc::Capsule { radius, height } => { ColliderShapeDesc::Capsule { radius, height } => {
draw_capsule( draw_capsule(
gizmos, gizmos,
global.translation(), translation,
global.rotation(), rotation,
*radius, *radius * scale.x.max(scale.z),
*height, *height * scale.y,
color, color,
); );
} }
ColliderShapeDesc::StaticMesh { .. } => { ColliderShapeDesc::StaticMesh { .. } => {
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 gizmos
.sphere( .ellipse(
Isometry3d::new(global.translation(), global.rotation()), Isometry3d::new(center, rotation),
0.35, Vec2::new(radii.x, radii.z),
color, color,
) )
.resolution(16); .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( fn draw_light(
-1
View File
@@ -1267,7 +1267,6 @@ mod tests {
format: "glb".into(), format: "glb".into(),
fingerprint: AnimationSourceFingerprint { fingerprint: AnimationSourceFingerprint {
byte_len: 1, byte_len: 1,
modified_unix_secs: 0,
content_hash: "fixture".into(), content_hash: "fixture".into(),
}, },
dependencies: Vec::new(), dependencies: Vec::new(),
+33 -7
View File
@@ -6,7 +6,7 @@ use bevy::app::PluginGroupBuilder;
use bevy::asset::AssetPlugin; use bevy::asset::AssetPlugin;
use bevy::log::{LogPlugin, DEFAULT_FILTER}; use bevy::log::{LogPlugin, DEFAULT_FILTER};
use bevy::prelude::*; use bevy::prelude::*;
use bevy::window::{CompositeAlphaMode, PresentMode, WindowMode, WindowPlugin}; use bevy::window::{CompositeAlphaMode, ExitCondition, PresentMode, WindowMode, WindowPlugin};
/// Runtime switch for the HDR camera pass. /// Runtime switch for the HDR camera pass.
/// ///
@@ -40,6 +40,27 @@ fn find_assets_directory(start: Option<PathBuf>) -> Option<String> {
} }
pub fn default_plugins(title: impl Into<String>) -> PluginGroupBuilder { pub fn default_plugins(title: impl Into<String>) -> PluginGroupBuilder {
configured_plugins(WindowPlugin {
primary_window: Some(primary_window(title)),
..default()
})
}
/// Default plugins for the editor, whose shutdown coordinator owns window-close handling.
pub fn editor_plugins(title: impl Into<String>) -> PluginGroupBuilder {
configured_plugins(editor_window_plugin(title))
}
fn editor_window_plugin(title: impl Into<String>) -> WindowPlugin {
WindowPlugin {
primary_window: Some(primary_window(title)),
exit_condition: ExitCondition::DontExit,
close_when_requested: false,
..default()
}
}
fn configured_plugins(window_plugin: WindowPlugin) -> PluginGroupBuilder {
DefaultPlugins DefaultPlugins
.set(LogPlugin { .set(LogPlugin {
// Blacksite intentionally replaces Bevy's `.scn.ron` loader with a // Blacksite intentionally replaces Bevy's `.scn.ron` loader with a
@@ -48,10 +69,7 @@ pub fn default_plugins(title: impl Into<String>) -> PluginGroupBuilder {
filter: format!("{DEFAULT_FILTER}bevy_asset::server::loaders=error"), filter: format!("{DEFAULT_FILTER}bevy_asset::server::loaders=error"),
..default() ..default()
}) })
.set(WindowPlugin { .set(window_plugin)
primary_window: Some(primary_window(title)),
..default()
})
.set(AssetPlugin { .set(AssetPlugin {
file_path: resolve_assets_directory(), file_path: resolve_assets_directory(),
..default() ..default()
@@ -86,8 +104,8 @@ pub fn hdr_enabled_from_env() -> bool {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{primary_window, resolve_assets_directory}; use super::{editor_window_plugin, primary_window, resolve_assets_directory};
use bevy::window::CompositeAlphaMode; use bevy::window::{CompositeAlphaMode, ExitCondition};
#[test] #[test]
fn primary_window_is_opaque() { fn primary_window_is_opaque() {
@@ -97,6 +115,14 @@ mod tests {
assert_eq!(window.composite_alpha_mode, CompositeAlphaMode::Opaque); assert_eq!(window.composite_alpha_mode, CompositeAlphaMode::Opaque);
} }
#[test]
fn editor_window_defers_close_and_exit_to_the_editor() {
let plugin = editor_window_plugin("test");
assert!(!plugin.close_when_requested);
assert!(matches!(plugin.exit_condition, ExitCondition::DontExit));
}
#[test] #[test]
fn resolve_assets_directory_finds_workspace_assets() { fn resolve_assets_directory_finds_workspace_assets() {
let cwd = std::env::current_dir().expect("cwd"); let cwd = std::env::current_dir().expect("cwd");
+1 -1
View File
@@ -94,7 +94,7 @@ mod hot {
ActiveCameraRenderProfile, ProjectRenderCamera, ProjectSettings, RenderingCapabilities, ActiveCameraRenderProfile, ProjectRenderCamera, ProjectSettings, RenderingCapabilities,
SimTuning, SimTuning,
}; };
use shared::{InspectorOrder, LevelObject, LightDesc, ProjectSun}; use shared::{AuthoringComponentStates, InspectorOrder, LevelObject, LightDesc, ProjectSun};
use sim::{ use sim::{
CameraSensitivity, Crouching, GameInputEnabled, GameInputFocused, Grounded, JumpState, CameraSensitivity, Crouching, GameInputEnabled, GameInputFocused, Grounded, JumpState,
Player, PlayerCamera, PlayerVelocity, PlayerYawSensitivity, Player, PlayerCamera, PlayerVelocity, PlayerYawSensitivity,
+1
View File
@@ -9,6 +9,7 @@ mod migrate;
pub mod navigation; pub mod navigation;
mod prefab; mod prefab;
mod project_validation; mod project_validation;
pub mod sample_pack;
mod upgrade; mod upgrade;
use std::path::Path; use std::path::Path;
+1
View File
@@ -175,6 +175,7 @@ fn actor_kind_ron(kind: ActorKind) -> &'static str {
match kind { match kind {
ActorKind::Empty => "Empty", ActorKind::Empty => "Empty",
ActorKind::Brush => "Brush", ActorKind::Brush => "Brush",
ActorKind::Terrain => "Terrain",
ActorKind::StaticMesh => "StaticMesh", ActorKind::StaticMesh => "StaticMesh",
ActorKind::SkinnedMesh => "SkinnedMesh", ActorKind::SkinnedMesh => "SkinnedMesh",
ActorKind::ImportedModel => "ImportedModel", ActorKind::ImportedModel => "ImportedModel",
+457 -18
View File
@@ -9,12 +9,13 @@ use shared::{
animation_clip_source_index, animation_clip_sub_asset_id, animation_skeleton_source_index, animation_clip_source_index, animation_clip_sub_asset_id, animation_skeleton_source_index,
animation_skeleton_sub_asset_id, animation_skeleton_sub_asset_id,
brush_math::{validate_brush, BrushDiagnosticSeverity}, brush_math::{validate_brush, BrushDiagnosticSeverity},
AnimationControllerDesc, AnimationDiagnosticSeverity, AnimationManifest, AudioListenerDesc, AnimationControllerDesc, AnimationDiagnosticSeverity, AnimationManifest,
AudioSourceDesc, BrushDesc, ColliderDesc, ColliderShapeDesc, EditorAssetRef, MaterialAsset, AssetSourceFingerprint, AudioListenerDesc, AudioSourceDesc, BrushDesc, ColliderDesc,
MaterialDesc, MaterialInstanceAsset, MaterialOverride, ModelRef, PostProcessEffectAsset, ColliderShapeDesc, EditorAssetRef, MaterialAsset, MaterialDesc, MaterialInstanceAsset,
PostProcessVolumeDesc, PrefabInstance, PrefabRef, RendererMaterialSet, ShaderSchemaAsset, MaterialOverride, ModelRef, PostProcessEffectAsset, PostProcessVolumeDesc, PrefabInstance,
SkinnedMeshRenderer, StaticMeshRenderer, ANIMATION_MANIFEST_SCHEMA_VERSION, PrefabRef, RendererMaterialSet, ShaderSchemaAsset, SkinnedMeshRenderer, StaticMeshRenderer,
AUDIO_CLIP_SUB_ASSET_ID, COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_SKINNED_MESH_RENDERER, TerrainDesc, ANIMATION_MANIFEST_SCHEMA_VERSION, AUDIO_CLIP_SUB_ASSET_ID,
COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_SKINNED_MESH_RENDERER,
NAVIGATION_GENERATED_ARTIFACT_DIRECTORY, NAVIGATION_GENERATED_ARTIFACT_DIRECTORY,
}; };
@@ -25,6 +26,7 @@ const MATERIAL_DESC: &str = "shared::components::MaterialDesc";
const MATERIAL_OVERRIDE: &str = "shared::components::MaterialOverride"; const MATERIAL_OVERRIDE: &str = "shared::components::MaterialOverride";
const STATIC_MESH_RENDERER: &str = "shared::components::StaticMeshRenderer"; const STATIC_MESH_RENDERER: &str = "shared::components::StaticMeshRenderer";
const BRUSH_DESC: &str = "shared::components::BrushDesc"; const BRUSH_DESC: &str = "shared::components::BrushDesc";
const TERRAIN_DESC: &str = "shared::components::TerrainDesc";
const COLLIDER_DESC: &str = "shared::components::ColliderDesc"; const COLLIDER_DESC: &str = "shared::components::ColliderDesc";
const POST_PROCESS_VOLUME: &str = "shared::components::PostProcessVolumeDesc"; const POST_PROCESS_VOLUME: &str = "shared::components::PostProcessVolumeDesc";
const PREFAB_INSTANCE: &str = "shared::components::PrefabInstance"; const PREFAB_INSTANCE: &str = "shared::components::PrefabInstance";
@@ -321,6 +323,8 @@ struct RegistryAssetRecord {
path: String, path: String,
kind_tag: String, kind_tag: String,
#[serde(default)] #[serde(default)]
source_fingerprint: Option<AssetSourceFingerprint>,
#[serde(default)]
import_settings: RegistryImportSettings, import_settings: RegistryImportSettings,
#[serde(default)] #[serde(default)]
dependencies: Vec<String>, dependencies: Vec<String>,
@@ -481,10 +485,96 @@ fn validate_asset_registry(
repair: "Convert the clip to Ogg Vorbis, WAV, MP3, or FLAC and reimport it.".into(), repair: "Convert the clip to Ogg Vorbis, WAV, MP3, or FLAC and reimport it.".into(),
}); });
} }
if matches!(record.kind_tag.as_str(), "Model" | "Texture" | "AudioClip") {
validate_content_fingerprint(
project_root,
report,
"assets/.index/registry.ron",
&record.path,
record.source_fingerprint.as_ref(),
"registry.source_fingerprint_missing",
"registry.source_fingerprint_stale",
"registered imported source",
);
}
} }
animation_catalog animation_catalog
} }
#[allow(clippy::too_many_arguments)]
fn validate_content_fingerprint(
project_root: &Path,
report: &mut ProjectValidationReport,
owner_path: &str,
source_path: &str,
fingerprint: Option<&AssetSourceFingerprint>,
missing_code: &str,
stale_code: &str,
source_label: &str,
) {
let Some(fingerprint) = fingerprint.filter(|fingerprint| fingerprint.is_complete()) else {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: missing_code.into(),
source_path: owner_path.into(),
owner_actor_id: None,
reference: Some(source_path.into()),
message: format!("{source_label} has no complete BLAKE3 content fingerprint"),
repair: "Refresh the asset registry or reimport the source with this editor version."
.into(),
});
return;
};
let Some(path) = resolve_reference(project_root, source_path) else {
return;
};
let Ok(metadata) = std::fs::metadata(&path) else {
return;
};
if metadata.len() != fingerprint.byte_len {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: stale_code.into(),
source_path: owner_path.into(),
owner_actor_id: None,
reference: Some(source_path.into()),
message: format!(
"{source_label} size changed from {} to {} bytes",
fingerprint.byte_len,
metadata.len()
),
repair: "Refresh or reimport the changed source before validation or packaging.".into(),
});
return;
}
match blake3_file_hash(&path) {
Ok(content_hash) if content_hash != fingerprint.content_hash => {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: stale_code.into(),
source_path: owner_path.into(),
owner_actor_id: None,
reference: Some(source_path.into()),
message: format!(
"{source_label} content changed even though its byte length is unchanged"
),
repair: "Refresh or reimport the changed source before validation or packaging."
.into(),
});
}
Ok(_) => {}
Err(error) => report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: stale_code.into(),
source_path: owner_path.into(),
owner_actor_id: None,
reference: Some(source_path.into()),
message: format!("could not hash {source_label}: {error}"),
repair: "Restore readable source content and rerun validation.".into(),
}),
}
}
fn reference_is_runtime_package_asset(reference: &str) -> bool { fn reference_is_runtime_package_asset(reference: &str) -> bool {
let relative = Path::new(reference.split('#').next().unwrap_or(reference)); let relative = Path::new(reference.split('#').next().unwrap_or(reference));
if relative.is_absolute() if relative.is_absolute()
@@ -708,10 +798,12 @@ struct StaticMeshManifestView {
struct StaticMeshSourceView { struct StaticMeshSourceView {
path: String, path: String,
#[serde(default)] #[serde(default)]
fingerprint: AssetSourceFingerprint,
#[serde(default)]
dependencies: Vec<String>, dependencies: Vec<String>,
} }
const STATIC_MESH_MANIFEST_SCHEMA_VERSION: u32 = 3; const STATIC_MESH_MANIFEST_SCHEMA_VERSION: u32 = 4;
fn validate_static_mesh_manifests(project_root: &Path, report: &mut ProjectValidationReport) { fn validate_static_mesh_manifests(project_root: &Path, report: &mut ProjectValidationReport) {
for path in ron_files( for path in ron_files(
@@ -753,6 +845,16 @@ fn validate_static_mesh_manifests(project_root: &Path, report: &mut ProjectValid
"model", "model",
&manifest.source.path, &manifest.source.path,
); );
validate_content_fingerprint(
project_root,
report,
&source,
&manifest.source.path,
Some(&manifest.source.fingerprint),
"static_mesh.manifest_fingerprint_missing",
"static_mesh.manifest_stale",
"static mesh source",
);
for dependency in manifest.source.dependencies { for dependency in manifest.source.dependencies {
add_reference( add_reference(
project_root, project_root,
@@ -974,12 +1076,7 @@ fn validate_animation_manifest_contract(
} }
let fingerprint = &manifest.source.fingerprint; let fingerprint = &manifest.source.fingerprint;
let hash_is_present = fingerprint.content_hash.len() == 64 if fingerprint.byte_len == 0 || !fingerprint.is_complete() {
&& fingerprint
.content_hash
.bytes()
.all(|byte| byte.is_ascii_hexdigit());
if fingerprint.byte_len == 0 || fingerprint.modified_unix_secs == 0 || !hash_is_present {
report.findings.push(ProjectValidationFinding { report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error, severity: ValidationSeverity::Error,
code: "animation.manifest_fingerprint_missing".into(), code: "animation.manifest_fingerprint_missing".into(),
@@ -1905,6 +2002,53 @@ fn collect_component_references(
} }
} }
} }
TERRAIN_DESC => match ron::from_str::<TerrainDesc>(&component.ron) {
Ok(terrain) => {
if let Err(error) = terrain.validate() {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "terrain.invalid".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: None,
message: error,
repair: "Repair the terrain dimensions, samples, layers, and chunk settings in the Inspector."
.into(),
});
}
if let Some(material) = &terrain.base_material {
collect_terrain_material_ref(
project_root,
report,
source_path,
actor_id,
"TerrainDesc.base_material",
material,
);
}
for (index, layer) in terrain.material_layers.iter().enumerate() {
if let Some(material) = &layer.material {
collect_terrain_material_ref(
project_root,
report,
source_path,
actor_id,
&format!("TerrainDesc.material_layers[{index}].material"),
material,
);
}
}
}
Err(error) => report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "terrain.malformed".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: None,
message: format!("could not parse TerrainDesc: {error}"),
repair: "Remove and recreate the Terrain component with the current editor.".into(),
}),
},
COLLIDER_DESC => validate_collider( COLLIDER_DESC => validate_collider(
project_root, project_root,
report, report,
@@ -2736,6 +2880,64 @@ fn collect_material(
} }
} }
fn collect_terrain_material_ref(
project_root: &Path,
report: &mut ProjectValidationReport,
source_path: &str,
actor_id: Option<&str>,
property: &str,
reference: &EditorAssetRef,
) {
let Some(path) = reference
.source_path
.as_deref()
.filter(|path| !path.trim().is_empty())
else {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "terrain.material_ref_unresolved".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: Some(property.to_string()),
message: format!("{property} has no loadable project source path"),
repair:
"Assign an existing project Material or Material Instance in the Terrain inspector."
.into(),
});
return;
};
let path_value = Path::new(path);
if path_value.is_absolute()
|| path_value == Path::new("assets")
|| !path_value.starts_with("assets")
|| !path_value
.components()
.all(|component| matches!(component, Component::Normal(_)))
{
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "terrain.material_ref_invalid".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: Some(path.to_string()),
message: format!(
"{property} source path must be a normalized project-relative path below assets/"
),
repair: "Reassign the terrain layer from a project Material or Material Instance."
.into(),
});
return;
}
add_reference(
project_root,
report,
source_path,
actor_id,
"terrain_material",
path,
);
}
fn collect_asset_ref( fn collect_asset_ref(
project_root: &Path, project_root: &Path,
report: &mut ProjectValidationReport, report: &mut ProjectValidationReport,
@@ -2965,7 +3167,7 @@ mod tests {
} }
#[test] #[test]
fn static_mesh_manifest_schema_v3_is_current() { fn static_mesh_manifest_schema_v4_is_current() {
let root = fixture_root(); let root = fixture_root();
let source_path = "assets/models/static.glb"; let source_path = "assets/models/static.glb";
std::fs::create_dir_all(root.join("assets/models")).unwrap(); std::fs::create_dir_all(root.join("assets/models")).unwrap();
@@ -2975,7 +3177,8 @@ mod tests {
std::fs::write( std::fs::write(
artifact_dir.join("static-id.static_mesh.ron"), artifact_dir.join("static-id.static_mesh.ron"),
format!( format!(
"(schema_version:{STATIC_MESH_MANIFEST_SCHEMA_VERSION},asset_id:\"static-id\",source:(path:\"{source_path}\",dependencies:[]),warnings:[])" "(schema_version:{STATIC_MESH_MANIFEST_SCHEMA_VERSION},asset_id:\"static-id\",source:(path:\"{source_path}\",fingerprint:(byte_len:5,content_hash:\"{}\"),dependencies:[]),warnings:[])",
blake3::hash(b"model").to_hex()
), ),
) )
.unwrap(); .unwrap();
@@ -2989,6 +3192,70 @@ mod tests {
std::fs::remove_dir_all(root).unwrap(); std::fs::remove_dir_all(root).unwrap();
} }
#[test]
fn same_size_static_mesh_source_change_invalidates_content_hash() {
let root = fixture_root();
let source_path = "assets/models/static.glb";
std::fs::create_dir_all(root.join("assets/models")).unwrap();
std::fs::write(root.join(source_path), b"model").unwrap();
let fingerprint = AssetSourceFingerprint::from_bytes(b"model");
let artifact = root.join("assets/meshes/generated/static-id.static_mesh.ron");
std::fs::create_dir_all(artifact.parent().unwrap()).unwrap();
std::fs::write(
&artifact,
format!(
"(schema_version:{STATIC_MESH_MANIFEST_SCHEMA_VERSION},asset_id:\"static-id\",source:(path:\"{source_path}\",fingerprint:(byte_len:{},content_hash:\"{}\"),dependencies:[]),warnings:[])",
fingerprint.byte_len, fingerprint.content_hash
),
)
.unwrap();
std::fs::write(root.join(source_path), b"modem").unwrap();
let report = validate_project(&root);
let finding = report
.findings
.iter()
.find(|finding| finding.code == "static_mesh.manifest_stale")
.expect("same-size model edit must stale the static mesh manifest");
assert!(finding.message.contains("byte length is unchanged"));
assert!(finding.repair.contains("Refresh") || finding.repair.contains("reimport"));
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn registry_detects_same_size_changes_for_all_imported_source_kinds() {
for (kind, relative) in [
("Model", "assets/models/source.glb"),
("Texture", "assets/textures/source.png"),
("AudioClip", "assets/audio/source.ogg"),
] {
let root = fixture_root();
let path = root.join(relative);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"source-a").unwrap();
let fingerprint = AssetSourceFingerprint::from_bytes(b"source-a");
std::fs::write(
root.join("assets/.index/registry.ron"),
format!(
"[(id:(\"00000000-0000-0000-0000-000000000001\"),path:\"{relative}\",kind_tag:\"{kind}\",source_fingerprint:Some((byte_len:{},content_hash:\"{}\")),dependencies:[])]",
fingerprint.byte_len, fingerprint.content_hash
),
)
.unwrap();
std::fs::write(&path, b"source-b").unwrap();
let report = validate_project(&root);
assert!(report.findings.iter().any(|finding| {
finding.code == "registry.source_fingerprint_stale"
&& finding.reference.as_deref() == Some(relative)
&& finding.message.contains("byte length is unchanged")
}));
std::fs::remove_dir_all(root).unwrap();
}
}
fn write_manifest(root: &Path, version: u32) { fn write_manifest(root: &Path, version: u32) {
std::fs::write( std::fs::write(
root.join("assets/project.ron"), root.join("assets/project.ron"),
@@ -3022,7 +3289,6 @@ mod tests {
format: source_format.into(), format: source_format.into(),
fingerprint: AnimationSourceFingerprint { fingerprint: AnimationSourceFingerprint {
byte_len: 5, byte_len: 5,
modified_unix_secs: 1,
content_hash: blake3::hash(b"model").to_hex().to_string(), content_hash: blake3::hash(b"model").to_hex().to_string(),
}, },
dependencies: Vec::new(), dependencies: Vec::new(),
@@ -3082,10 +3348,12 @@ mod tests {
let manifest = animation_manifest_path let manifest = animation_manifest_path
.map(|path| format!("Some({path:?})")) .map(|path| format!("Some({path:?})"))
.unwrap_or_else(|| "None".into()); .unwrap_or_else(|| "None".into());
let fingerprint = AssetSourceFingerprint::from_bytes(b"model");
std::fs::write( std::fs::write(
root.join("assets/.index/registry.ron"), root.join("assets/.index/registry.ron"),
format!( format!(
"[(id:(\"{ANIMATION_ASSET_ID}\"),path:\"{source_path}\",kind_tag:\"Model\",import_settings:(static_mesh_manifest_path:None,animation_manifest_path:{manifest}),dependencies:[])]" "[(id:(\"{ANIMATION_ASSET_ID}\"),path:\"{source_path}\",kind_tag:\"Model\",source_fingerprint:Some((byte_len:{},content_hash:\"{}\")),import_settings:(static_mesh_manifest_path:None,animation_manifest_path:{manifest}),dependencies:[])]",
fingerprint.byte_len, fingerprint.content_hash
), ),
) )
.unwrap(); .unwrap();
@@ -3099,10 +3367,12 @@ mod tests {
let source = root.join(source_path); let source = root.join(source_path);
std::fs::create_dir_all(source.parent().unwrap()).unwrap(); std::fs::create_dir_all(source.parent().unwrap()).unwrap();
std::fs::write(source, b"model").unwrap(); std::fs::write(source, b"model").unwrap();
let fingerprint = AssetSourceFingerprint::from_bytes(b"model");
std::fs::write( std::fs::write(
root.join("assets/.index/registry.ron"), root.join("assets/.index/registry.ron"),
format!( format!(
"[(id:(\"{ANIMATION_ASSET_ID}\"),path:\"{source_path}\",kind_tag:\"Model\",import_settings:(static_mesh_manifest_path:None,animation_manifest_path:Some(\"{ANIMATION_MANIFEST_PATH}\"),default_animation_clip_id:Some(\"{default_clip_id}\")),dependencies:[])]" "[(id:(\"{ANIMATION_ASSET_ID}\"),path:\"{source_path}\",kind_tag:\"Model\",source_fingerprint:Some((byte_len:{},content_hash:\"{}\")),import_settings:(static_mesh_manifest_path:None,animation_manifest_path:Some(\"{ANIMATION_MANIFEST_PATH}\"),default_animation_clip_id:Some(\"{default_clip_id}\")),dependencies:[])]",
fingerprint.byte_len, fingerprint.content_hash
), ),
) )
.unwrap(); .unwrap();
@@ -3526,6 +3796,49 @@ mod tests {
std::fs::remove_dir_all(root).unwrap(); std::fs::remove_dir_all(root).unwrap();
} }
#[test]
fn project_validation_preserves_registry_and_generated_artifact_bytes() {
let root = fixture_root();
let source_path = "assets/models/hero.glb";
let manifest = animation_fixture_manifest(source_path, "glb", "rig-signature", true);
write_animation_source_and_registry(&root, source_path, Some(ANIMATION_MANIFEST_PATH));
write_animation_manifest(&root, &manifest);
write_animation_scene(&root, &animation_fixture_controller(&manifest));
let static_path = root.join("assets/meshes/generated/model-id.static_mesh.ron");
std::fs::create_dir_all(static_path.parent().unwrap()).unwrap();
std::fs::write(
&static_path,
format!(
"( schema_version: {STATIC_MESH_MANIFEST_SCHEMA_VERSION}, asset_id: \"model-id\", source: ( path: \"{source_path}\", fingerprint: ( byte_len: {}, content_hash: \"{}\", ), dependencies: [], ), warnings: [], )\n\n",
manifest.source.fingerprint.byte_len,
manifest.source.fingerprint.content_hash
),
)
.unwrap();
let paths = [
root.join("assets/.index/registry.ron"),
root.join(ANIMATION_MANIFEST_PATH),
static_path,
];
let before = paths
.iter()
.map(std::fs::read)
.collect::<Result<Vec<_>, _>>()
.unwrap();
let _ = validate_project(&root);
let _ = validate_project(&root);
let after = paths
.iter()
.map(std::fs::read)
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert_eq!(after, before);
std::fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn missing_animation_manifest_is_reported_globally_and_on_the_actor_property() { fn missing_animation_manifest_is_reported_globally_and_on_the_actor_property() {
let root = fixture_root(); let root = fixture_root();
@@ -3888,6 +4201,132 @@ mod tests {
std::fs::remove_dir_all(root).unwrap(); std::fs::remove_dir_all(root).unwrap();
} }
fn write_terrain_scene(root: &Path, terrain: &TerrainDesc) {
let terrain = ron::to_string(terrain).unwrap();
std::fs::write(
root.join("assets/levels/main.scn.ron"),
format!(
"(schema_version:4,resources:{{}},entities:{{1:(components:{{\"shared::components::ActorId\":(\"terrain-owner\"),\"{TERRAIN_DESC}\":{terrain},}})}})"
),
)
.unwrap();
}
#[test]
fn terrain_material_references_are_actor_owned_dependencies() {
let root = fixture_root();
let mut terrain = TerrainDesc::flat(3);
terrain.base_material = Some(
EditorAssetRef::new("base-id", "material:instance", "Base")
.with_source_path("assets/materials/base.ron"),
);
terrain.material_layers = vec![shared::TerrainMaterialLayer {
material: Some(
EditorAssetRef::new("layer-id", "material:source", "Layer")
.with_source_path("assets/materials/layer.ron"),
),
uv_scale: 4.0,
}];
write_terrain_scene(&root, &terrain);
let report = validate_project(&root);
let dependencies = report
.dependencies
.iter()
.filter(|dependency| dependency.kind == "terrain_material")
.collect::<Vec<_>>();
assert_eq!(dependencies.len(), 2, "{:?}", report.dependencies);
assert!(dependencies
.iter()
.all(|dependency| dependency.owner_actor_id.as_deref() == Some("terrain-owner")));
assert_eq!(
report
.findings
.iter()
.filter(|finding| finding.code == "asset.missing")
.count(),
2
);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn terrain_material_references_require_runtime_source_paths() {
let root = fixture_root();
let mut terrain = TerrainDesc::flat(3);
terrain.base_material = Some(
EditorAssetRef::new("empty-path-id", "material:source", "Empty")
.with_source_path(" "),
);
terrain.material_layers = vec![
shared::TerrainMaterialLayer {
material: Some(EditorAssetRef::new(
"source-less-id",
"material:source",
"Source-less",
)),
uv_scale: 4.0,
},
shared::TerrainMaterialLayer {
material: Some(
EditorAssetRef::new("missing-id", "material:source", "Missing")
.with_source_path("assets/materials/missing.ron"),
),
uv_scale: 8.0,
},
];
write_terrain_scene(&root, &terrain);
let report = validate_project(&root);
let unresolved = report
.findings
.iter()
.filter(|finding| finding.code == "terrain.material_ref_unresolved")
.collect::<Vec<_>>();
assert_eq!(unresolved.len(), 2, "{:?}", report.findings);
assert!(unresolved
.iter()
.all(|finding| finding.owner_actor_id.as_deref() == Some("terrain-owner")));
assert!(report.findings.iter().any(|finding| {
finding.code == "asset.missing"
&& finding.owner_actor_id.as_deref() == Some("terrain-owner")
&& finding.reference.as_deref() == Some("assets/materials/missing.ron")
}));
assert!(report.dependencies.iter().any(|dependency| {
dependency.kind == "terrain_material"
&& dependency.reference == "assets/materials/missing.ron"
}));
assert!(!report.dependencies.iter().any(|dependency| {
dependency.kind == "generated_manifest"
&& (dependency.reference.contains("empty-path-id")
|| dependency.reference.contains("source-less-id"))
}));
assert!(!report.is_release_ready());
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn invalid_terrain_descriptor_blocks_project_validation() {
let root = fixture_root();
let mut terrain = TerrainDesc::flat(3);
terrain.heights.pop();
write_terrain_scene(&root, &terrain);
let report = validate_project(&root);
let finding = report
.findings
.iter()
.find(|finding| finding.code == "terrain.invalid")
.expect("invalid terrain should block release validation");
assert_eq!(finding.owner_actor_id.as_deref(), Some("terrain-owner"));
assert!(finding.message.contains("requires 9 height samples"));
assert!(!report.is_release_ready());
std::fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn project_default_level_must_be_in_the_audited_levels_tree() { fn project_default_level_must_be_in_the_audited_levels_tree() {
let root = fixture_root(); let root = fixture_root();
File diff suppressed because it is too large. Load diff
+29 -3
View File
@@ -227,17 +227,22 @@ impl Default for InputSettings {
/// Loads settings from disk, falling back to defaults. /// Loads settings from disk, falling back to defaults.
pub fn load_project_settings_from_path(path: &str) -> ProjectSettings { pub fn load_project_settings_from_path(path: &str) -> ProjectSettings {
load_project_settings_with_source(path).0
}
/// Loads settings plus the exact source text used when the file was readable.
pub fn load_project_settings_with_source(path: &str) -> (ProjectSettings, Option<String>) {
match std::fs::read_to_string(path) { match std::fs::read_to_string(path) {
Ok(contents) => match ron::from_str(&contents) { Ok(contents) => match ron::from_str(&contents) {
Ok(settings) => settings, Ok(settings) => (settings, Some(contents)),
Err(error) => { Err(error) => {
warn!("Failed to parse {path}: {error}; using defaults"); warn!("Failed to parse {path}: {error}; using defaults");
ProjectSettings::default() (ProjectSettings::default(), Some(contents))
} }
}, },
Err(error) => { Err(error) => {
warn!("Could not read {path}: {error}; using defaults"); warn!("Could not read {path}: {error}; using defaults");
ProjectSettings::default() (ProjectSettings::default(), None)
} }
} }
} }
@@ -266,6 +271,27 @@ mod tests {
assert_eq!(parsed.rendering.gi_mode, settings.rendering.gi_mode); assert_eq!(parsed.rendering.gi_mode, settings.rendering.gi_mode);
} }
#[test]
fn settings_load_returns_the_exact_source_for_revision_guards() {
let root = std::env::temp_dir().join(format!(
"blacksite-settings-source-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let path = root.join("project.ron");
std::fs::create_dir_all(&root).unwrap();
let source = save_project_settings_to_string(&ProjectSettings::default()).unwrap();
std::fs::write(&path, &source).unwrap();
let (settings, loaded_source) = load_project_settings_with_source(path.to_str().unwrap());
assert_eq!(settings.name, ProjectSettings::default().name);
assert_eq!(loaded_source.as_deref(), Some(source.as_str()));
std::fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn legacy_manifest_defaults_project_identity_fields() { fn legacy_manifest_defaults_project_identity_fields() {
let legacy = r#"( let legacy = r#"(
+13 -5
View File
@@ -1,7 +1,7 @@
use bevy::prelude::*; use bevy::prelude::*;
use crate::{ use crate::{
load_project_settings_from_path, save_project_settings_to_string, PhysicsSettings, load_project_settings_with_source, save_project_settings_to_string, PhysicsSettings,
ProjectSettings, DEFAULT_PROJECT_PATH, ProjectSettings, DEFAULT_PROJECT_PATH,
}; };
@@ -56,6 +56,8 @@ impl SimTuning {
pub struct ProjectSettingsIo { pub struct ProjectSettingsIo {
pub path: String, pub path: String,
pub dirty: bool, pub dirty: bool,
/// Exact source loaded or last saved by this process; collaboration guards hash it.
pub loaded_source: Option<String>,
} }
impl Default for ProjectSettingsIo { impl Default for ProjectSettingsIo {
@@ -63,6 +65,7 @@ impl Default for ProjectSettingsIo {
Self { Self {
path: DEFAULT_PROJECT_PATH.into(), path: DEFAULT_PROJECT_PATH.into(),
dirty: false, dirty: false,
loaded_source: None,
} }
} }
} }
@@ -91,8 +94,9 @@ impl Plugin for ProjectSettingsPlugin {
} }
} }
fn load_settings(mut commands: Commands, io: Res<ProjectSettingsIo>) { fn load_settings(mut commands: Commands, mut io: ResMut<ProjectSettingsIo>) {
let settings = load_project_settings_from_path(&io.path); let (settings, source) = load_project_settings_with_source(&io.path);
io.loaded_source = source;
let tuning = SimTuning::from_physics(&settings.physics); let tuning = SimTuning::from_physics(&settings.physics);
commands.insert_resource(settings); commands.insert_resource(settings);
commands.insert_resource(tuning); commands.insert_resource(tuning);
@@ -103,13 +107,17 @@ pub fn sync_sim_tuning(settings: &ProjectSettings, mut tuning: ResMut<SimTuning>
*tuning = SimTuning::from_physics(&settings.physics); *tuning = SimTuning::from_physics(&settings.physics);
} }
/// Persists settings to the path in [`ProjectSettingsIo`]. /// Low-level unconditional persistence for non-editor callers.
///
/// The editor uses its guarded authored-file publication path instead so external revisions cannot
/// be overwritten.
pub fn save_project_settings( pub fn save_project_settings(
settings: &ProjectSettings, settings: &ProjectSettings,
io: &mut ProjectSettingsIo, io: &mut ProjectSettingsIo,
) -> Result<(), String> { ) -> Result<(), String> {
let text = save_project_settings_to_string(settings).map_err(|error| error.to_string())?; let text = save_project_settings_to_string(settings).map_err(|error| error.to_string())?;
std::fs::write(&io.path, text).map_err(|error| error.to_string())?; std::fs::write(&io.path, &text).map_err(|error| error.to_string())?;
io.loaded_source = Some(text);
io.dirty = false; io.dirty = false;
Ok(()) Ok(())
} }
+18 -1
View File
@@ -11,7 +11,7 @@ use crate::{
ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, LevelObject, ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, LevelObject,
LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink, NavigationObstacle, LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink, NavigationObstacle,
ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive, ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn, SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TerrainDesc, TriggerVolume, WeaponSpawn,
AUDIO_CLIP_SUB_ASSET_ID, AUDIO_CLIP_SUB_ASSET_ID,
}; };
@@ -31,6 +31,9 @@ pub fn infer_actor_kind(entity: EntityRef<'_>) -> Option<ActorKind> {
if entity.get::<BrushDesc>().is_some() { if entity.get::<BrushDesc>().is_some() {
return Some(ActorKind::Brush); 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() { if entity.get::<Primitive>().is_some() || entity.get::<StaticMeshRenderer>().is_some() {
return Some(ActorKind::StaticMesh); return Some(ActorKind::StaticMesh);
} }
@@ -84,6 +87,7 @@ pub enum ActorValidationError {
BrushHasLight, BrushHasLight,
BrushHasModelRef, BrushHasModelRef,
InvalidBrushGeometry(String), InvalidBrushGeometry(String),
InvalidTerrain(String),
StaticMeshMissingPrimitive, StaticMeshMissingPrimitive,
StaticMeshHasLight, StaticMeshHasLight,
StaticMeshHasModelRef, StaticMeshHasModelRef,
@@ -166,6 +170,7 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
} }
let geometry_source_count = usize::from(entity.get::<Primitive>().is_some()) let geometry_source_count = usize::from(entity.get::<Primitive>().is_some())
+ usize::from(entity.get::<BrushDesc>().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::<StaticMeshRenderer>().is_some())
+ usize::from(entity.get::<SkinnedMeshRenderer>().is_some()) + usize::from(entity.get::<SkinnedMeshRenderer>().is_some())
+ usize::from(entity.get::<ModelRef>().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)); 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 let Some(renderer) = entity.get::<SkinnedMeshRenderer>() {
if renderer.path.trim().is_empty() { if renderer.path.trim().is_empty() {
return Err(ActorValidationError::SkinnedMeshInvalidRenderer); return Err(ActorValidationError::SkinnedMeshInvalidRenderer);
@@ -218,6 +228,13 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
} }
let _ = brush; let _ = brush;
} }
ActorKind::Terrain => {
if entity.get::<TerrainDesc>().is_none() {
return Err(ActorValidationError::InvalidTerrain(
"terrain actor is missing TerrainDesc".into(),
));
}
}
ActorKind::StaticMesh => { ActorKind::StaticMesh => {
let has_static_mesh_renderer = entity let has_static_mesh_renderer = entity
.get::<StaticMeshRenderer>() .get::<StaticMeshRenderer>()
+2 -7
View File
@@ -266,13 +266,8 @@ pub struct AnimationManifestSource {
pub dependencies: Vec<String>, pub dependencies: Vec<String>,
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] /// Backward-compatible name for the shared imported-source fingerprint contract.
pub struct AnimationSourceFingerprint { pub type AnimationSourceFingerprint = crate::AssetSourceFingerprint;
pub byte_len: u64,
pub modified_unix_secs: u64,
/// BLAKE3 hash of the source file bytes.
pub content_hash: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnimationSkeletonRecord { pub struct AnimationSkeletonRecord {
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more