Compare commits
511 Commits
6c28f722a1
...
e31dfbc5cd
| Author | SHA1 | Date | |
|---|---|---|---|
| e31dfbc5cd | |||
| 2a924b5b36 | |||
| ec69f450df | |||
| 655f3d91a2 | |||
| 3d3020972b | |||
| 56bea13732 | |||
| 6f7c88c316 | |||
| f71039966d | |||
| 04e7c062ed | |||
| 22d97f0197 | |||
| 7676bddf62 | |||
| 04ffdbb4e6 | |||
| d8bd6c2c83 | |||
| 3e2bd13906 | |||
| a839530e60 | |||
| 0389d6535c | |||
| b2223ef606 | |||
| 7cb41ce3b5 | |||
| ad0bb16413 | |||
| c382ece672 | |||
| 0082dd4b52 | |||
| 72a204761f | |||
| 66fec4ca2d | |||
| 94fe6ca280 | |||
| 7ab407608e | |||
| f9da8a83fa | |||
| 0b2c2ab1bf | |||
| f67095bf05 | |||
| 3e59367d08 | |||
| 532c34117e | |||
| 7e866ec6b2 | |||
| 16a19b5e90 | |||
| 8302868e5f | |||
| 8548581699 | |||
| 774ff4a841 | |||
| f8a388b0f4 | |||
| 8e97fa3485 | |||
| e958c97fdb | |||
| a142a3f528 | |||
| fb10015fdf | |||
| 2c39553fdd | |||
| 797ef18c6a | |||
| 08e9f0978d | |||
| 3ce10dbed3 | |||
| 5f0cd09267 | |||
| b199fa1d60 | |||
| aeef4e898f | |||
| 69f4c8302a | |||
| 9093903287 | |||
| 9aff89a21e | |||
| 827d5c40e0 | |||
| c3a3820379 | |||
| bc31cd6b10 | |||
| c22c4b44d5 | |||
| 294955a0af | |||
| 0fc5e95a65 | |||
| 2a08b9b42e | |||
| 418086724e | |||
| e99a8ece66 | |||
| d9b6dcf85d | |||
| 00b556669d | |||
| 830b6abee0 | |||
| b9fb9cca48 | |||
| b850627295 | |||
| e04fc45477 | |||
| 6d6503eac3 | |||
| 297fdf7d1b | |||
| 3cabd0ff9b | |||
| c5d8bd00be | |||
| 77c1e1bb9c | |||
| d2dcb68f16 | |||
| 70ee2c5fcb | |||
| 9e76321ec6 | |||
| 645e454f62 | |||
| 54f62f0c10 | |||
| 3460b655e2 | |||
| fa173ba300 | |||
| 7a92b5ca93 | |||
| 6728a9db2f | |||
| 6bb996592d | |||
| 1060bb11dd | |||
| 6aacb11496 | |||
| 8b048fb09c | |||
| 930297a415 | |||
| 6ab4ae0b02 | |||
| 5d3d9c394d | |||
| 0bfa3613d5 | |||
| 7bb75973d9 | |||
| 376bb60e1b | |||
| ff938c5e93 | |||
| 1232128c84 | |||
| 73923baf5d | |||
| 0fd274d8ab | |||
| f69882764e | |||
| 89b30a507a | |||
| 991e414ae4 | |||
| b79ec90293 | |||
| b4f0c61a1e | |||
| f64eaa7350 | |||
| c19dae0df6 | |||
| cc9b200bae | |||
| 805fb9100f | |||
| 1da2eb3b1f | |||
| efbbd814a3 | |||
| 529e8f4da9 | |||
| 2e16851ac2 | |||
| c8fd1a6f94 | |||
| 39cce3952d | |||
| 1988abf055 | |||
| 4dfc3453fb | |||
| c2ac4b04f6 | |||
| 4974c7a89c | |||
| 7f5671051c | |||
| fdc582a494 | |||
| 6eef0142e2 | |||
| 4c4fde5aae | |||
| efad6ab92a | |||
| 1f8a112f0e | |||
| f30da7bc8a | |||
| 1e347c004e | |||
| 65bffc2ec8 | |||
| 561b64f1ba | |||
| 8210067daa | |||
| d7f580dfb5 | |||
| e462209dcd | |||
| d9c6455f9e | |||
| c0bc372277 | |||
| 3397be7b42 | |||
| 53d40ec039 | |||
| f22a64f97b | |||
| 3507e01e4a | |||
| 9fd09ae7ce | |||
| c752c7fa6d | |||
| 41917c30f7 | |||
| 6e4daccced | |||
| ac905d24fb | |||
| 9a22b462d4 | |||
| a2805c16fe | |||
| acf9a457c6 | |||
| 869432d989 | |||
| 484eaf8db9 | |||
| 9007681e0b | |||
| 70bcb35167 | |||
| 8a04101d68 | |||
| 762ed5d916 | |||
| 2dda25ae4b | |||
| ecff9053ab | |||
| 16a7b4e7e2 | |||
| 3fdbc002b6 | |||
| 6db8b82ed7 | |||
| bb6698caa0 | |||
| c89eb9db94 | |||
| 450ffc5299 | |||
| 30104e815b | |||
| 56cd968009 | |||
| d01a8bfefc | |||
| 8b01425464 | |||
| eefc57262b | |||
| 1c60dafbf8 | |||
| ca2f5b64aa | |||
| 7df881227a | |||
| cc8dd23768 | |||
| 27269c55d0 | |||
| 6a0ec57cf1 | |||
| 2b44ba38ca | |||
| 017e6959e4 | |||
| 8f92d34fca | |||
| b85b295c5a | |||
| 6b1b6a3437 | |||
| f63ce0fc11 | |||
| ba8f8235bf | |||
| 3d1dd3fe63 | |||
| d82e37861e | |||
| ae6becb14a | |||
| a66f57faff | |||
| 17709683bd | |||
| aba85766eb | |||
| 4ee909b911 | |||
| 9ff714af04 | |||
| 512d8e0269 | |||
| 86cfa78448 | |||
| 5c89a72dc8 | |||
| e0b1c31323 | |||
| 2dfa68822c | |||
| 6f07baf653 | |||
| 2bfec5b30b | |||
| 14b1de3a91 | |||
| e801c93a90 | |||
| ea8b8c4ba6 | |||
| c36c1c3394 | |||
| 6f1f2f20fb | |||
| f4fd54f285 | |||
| 8c844d08c9 | |||
| 21bf3b30a6 | |||
| d350a8839f | |||
| be81b73d11 | |||
| d8e60db880 | |||
| eab77f71ef | |||
| 7098687a99 | |||
| 9abbe7caf5 | |||
| 73a868ee33 | |||
| 3b38b1aee7 | |||
| 0af9837674 | |||
| 92e4c2eeaf | |||
| e6d9704b49 | |||
| 2d4fdfa427 | |||
| adb83e8a8f | |||
| 77d4b7fe08 | |||
| 7ce72c95c1 | |||
| c280c57619 | |||
| 809396619d | |||
| 3a0ad4b63b | |||
| f92f9e7222 | |||
| 7903090f90 | |||
| 0c2bca0331 | |||
| eda8a81448 | |||
| 84e3f4e0e5 | |||
| d32129edfc | |||
| a6f8e43c9f | |||
| fea1f32fc1 | |||
| 822105a215 | |||
| 39ee96f3e3 | |||
| 8fc2f7e9a4 | |||
| 52d2634324 | |||
| edd0b3e2a2 | |||
| 162b2495d8 | |||
| 879f34ec09 | |||
| d8cc3a1c46 | |||
| e88cd7e795 | |||
| 37e70a6b0b | |||
| 9d233de06a | |||
| 52f310e199 | |||
| 1ebc2f81d0 | |||
| fbde0094bf | |||
| e5a6da5a1e | |||
| 7e1e86abca | |||
| 9cb26f7562 | |||
| c48f630e25 | |||
| b562fe483b | |||
| bbfc17c66c | |||
| 31f170e2fa | |||
| 4810d8f3c2 | |||
| 8a36d888de | |||
| 2ff3f79f29 | |||
| 1e82418c53 | |||
| dd5482551e | |||
| c90c2ba5ad | |||
| 61cc96293d | |||
| 1b66de906e | |||
| 23ffb186e6 | |||
| d3566dec06 | |||
| f1191148ff | |||
| 8400dc30b5 | |||
| e659beb512 | |||
| 0a53bcdf6f | |||
| 4cf4642525 | |||
| bd0c30424e | |||
| b9e387464b | |||
| 8b0dd2951f | |||
| 3fcf9fc29c | |||
| f44050e2fe | |||
| d3c9361159 | |||
| 2eed4aca27 | |||
| c0efadeac7 | |||
| 9dfb3db3e7 | |||
| e68438083d | |||
| ed4f566d29 | |||
| fcc897b2f5 | |||
| 66fdcca4af | |||
| 138445a7de | |||
| 689e004d26 | |||
| a23bad5f87 | |||
| db4b907838 | |||
| db39f7253b | |||
| 11ef2c71db | |||
| 47753b4c14 | |||
| 7e610eaad4 | |||
| 13c600441f | |||
| a2ad50b3ea | |||
| eb3d08140f | |||
| d02159a253 | |||
| b54b3eb445 | |||
| 2e7de4b14c | |||
| 8dcca3487d | |||
| e230db744e | |||
| 464e7c5d86 | |||
| b23848ff55 | |||
| d46f836d4b | |||
| f5bb8b2627 | |||
| 149f550274 | |||
| 6cb7989a85 | |||
| 7c95b7e71e | |||
| 4bc45f3fa6 | |||
| c848001546 | |||
| 5718fd87fc | |||
| 18d2fffce2 | |||
| 5def502b4a | |||
| afea3647bb | |||
| 46ba6e56df | |||
| 6ada444b84 | |||
| 2176fcabd0 | |||
| 696d0a3fbe | |||
| 46984c8998 | |||
| 1fe0da2bb9 | |||
| 01bdb6525a | |||
| 9e4b7670a1 | |||
| 40c02757a6 | |||
| 32a611a71f | |||
| 697ad5cbca | |||
| 0c8a990176 | |||
| 5895f79264 | |||
| 0c84ccdd3c | |||
| 1a64fb81f3 | |||
| 3d7c0d75e4 | |||
| 1344c404d3 | |||
| 62c558bb27 | |||
| bea39f4526 | |||
| c1b6d984cb | |||
| 185cfe1aaa | |||
| db8965436d | |||
| 56305dc7cf | |||
| 8a0f97477f | |||
| e2ce5eab79 | |||
| aa82a0c01a | |||
| 4d4951aafa | |||
| cc0f2019eb | |||
| 5927304628 | |||
| d4d6711e65 | |||
| 2104ffa319 | |||
| 21ece68aff | |||
| 2f97a2173d | |||
| 064b138a8d | |||
| 238fe565dd | |||
| 0500b6cf2b | |||
| 4fd4da1e78 | |||
| b2438a85d2 | |||
| a71e94eec9 | |||
| 89344cc99f | |||
| 2682c290c1 | |||
| a3e658ab93 | |||
| 3bebd4116d | |||
| 63ab9afc9c | |||
| dbb886a9f1 | |||
| d87406f69e | |||
| aef964e958 | |||
| cc44ca1971 | |||
| d6023451d2 | |||
| 2ebe4bb8a1 | |||
| 0c5eeb64e4 | |||
| 43d4e26fac | |||
| 57098940e4 | |||
| 30de189cfa | |||
| 3dd75e3496 | |||
| 21e0ceccf9 | |||
| a1db92b7ff | |||
| c14ac433d9 | |||
| 572d448d1f | |||
| 8ee4a40485 | |||
| 22004d45e0 | |||
| 6bd7e5b769 | |||
| 394d99f20c | |||
| 24ad835ff7 | |||
| 34df9d7348 | |||
| 06117cad48 | |||
| 1eda6b2404 | |||
| 9507a69d9b | |||
| ef7eb5dfbe | |||
| d84d13fe75 | |||
| 8d4a0cbe81 | |||
| da9b08408a | |||
| 15313b0aab | |||
| ecd2bd7208 | |||
| c79173f058 | |||
| 7ba7d8a2e9 | |||
| 6a239b1504 | |||
| 28029202fa | |||
| 61b7be6219 | |||
| 329785ff91 | |||
| 3a48452c2a | |||
| cc48aaa7c7 | |||
| 75e118a287 | |||
| aed06fef01 | |||
| aa52d62098 | |||
| c73c9b5cc7 | |||
| ff4978edee | |||
| d12a4e68c8 | |||
| 0164cfe925 | |||
| ff86d5e49e | |||
| 8d1154c01b | |||
| bbfd2e0dc2 | |||
| fff366dea7 | |||
| 6864fea0ad | |||
| 3efd5e7310 | |||
| ad59846972 | |||
| 85abede15e | |||
| aced8c5dd4 | |||
| 6c9d305c67 | |||
| 15b17223c2 | |||
| 710b18b994 | |||
| d800b94184 | |||
| a875e45208 | |||
| 2a48089fae | |||
| 397bdff1e7 | |||
| fd6f783dbc | |||
| 9d3fa13b0c | |||
| 1630c84819 | |||
| 8ef565abc7 | |||
| e4ff5e8f8b | |||
| abfad5dfc7 | |||
| 2f1dbedf08 | |||
| 7e5ee352cc | |||
| b5fd4cc8ac | |||
| e2f6feace4 | |||
| 1ad076a73a | |||
| d191a61b15 | |||
| 6b0bb0fc52 | |||
| bb4435814b | |||
| fcd7886987 | |||
| e14f3b241c | |||
| 89c7aa3393 | |||
| cc66090ef1 | |||
| 62322050de | |||
| 113d899309 | |||
| 65e5f98b64 | |||
| 3270c3bb0f | |||
| 4dad2a7feb | |||
| b71f7adda2 | |||
| e3caeedcad | |||
| 856dd76669 | |||
| f1714a4c2a | |||
| 8366176e14 | |||
| a8f965cf0e | |||
| 783b63b3e5 | |||
| c310bb05c8 | |||
| 3b221cde66 | |||
| aaf5f9d646 | |||
| 53e71081f1 | |||
| 3881dc5e76 | |||
| a55872a878 | |||
| d0bfdd7187 | |||
| 3b11ea948a | |||
| 8662135892 | |||
| a2eb8ed1d4 | |||
| dafd22a0b3 | |||
| 4a3ba881eb | |||
| e50b88a995 | |||
| efb1a7be2e | |||
| 3430b8e73f | |||
| e559e4cad7 | |||
| c0ed844ae2 | |||
| b6af0f8d25 | |||
| e6f4672b3e | |||
| de4f66113a | |||
| 82ba38c106 | |||
| fdc42dce96 | |||
| 139744a53e | |||
| 8b7f382060 | |||
| 94cadc5f37 | |||
| 8c7a38a46d | |||
| 32660bd4b9 | |||
| 581aca0b44 | |||
| 3d56e92ed4 | |||
| f62383a91b | |||
| 009d1a41db | |||
| c62a6bcb39 | |||
| 53ab243437 | |||
| 0e1d637df2 | |||
| 5efc4c769c | |||
| cbf767290e | |||
| 2c3089e262 | |||
| 341383c61a | |||
| 2bc20c9f79 | |||
| fedbf85c40 | |||
| 712dbbd661 | |||
| ed0d2572cc | |||
| 5a44efe533 | |||
| 54c445b293 | |||
| aa7d742277 | |||
| b2cf951269 | |||
| e5c3099168 | |||
| 072f6a5eef | |||
| f79857cc70 | |||
| 300e04b6d1 | |||
| 6b60827c22 | |||
| 5ae467f103 | |||
| c61b416538 | |||
| 9eaf60f5e6 | |||
| 73efd566f4 | |||
| 8035b75220 | |||
| d4ef61abe3 | |||
| 927839243f | |||
| 07de28796a | |||
| 654672abf7 | |||
| d07304d6bc | |||
| f52af8865c | |||
| 4c5ce44726 | |||
| 36d8e29298 | |||
| e8b0078f0d | |||
| 40929981d0 | |||
| c7232a8a83 | |||
| fb05328e5b | |||
| aa17a1f4fa | |||
| c567f3f765 | |||
| e6f3c25c73 | |||
| 080e9b310e | |||
| a0c82d2734 | |||
| 687b58a487 | |||
| 4fcbb83dc6 | |||
| c0e24e6bde | |||
| 6675ac2d5e | |||
| 9dd8c0469e |
117
AGENTS.md
117
AGENTS.md
@@ -2,40 +2,45 @@
|
||||
|
||||
## Project identity
|
||||
|
||||
This repository contains a browser-based brush/solid editor for creating lightweight interactive 3D scenes, plus a built-in browser runner for playing those scenes.
|
||||
This repository contains a browser-based engine/editor for creating interactive 3D environments, with a built-in browser runner for immediate playtesting.
|
||||
|
||||
The product goal is:
|
||||
|
||||
- Hammer / TrenchBroom style spatial authoring
|
||||
- intuitive whiteboxing and scene assembly for interactive 3D spaces
|
||||
- modern browser delivery
|
||||
- glTF asset import, with optional later interchange export
|
||||
- fast edit -> run iteration
|
||||
- lightweight interactive runtime with spatial audio, navigation modes, and simple entity-driven logic
|
||||
|
||||
This is not a general-purpose DCC.
|
||||
This is not a full game engine.
|
||||
This is a focused authoring + runtime tool for browser-delivered 3D spaces.
|
||||
This is not an unlimited AAA engine platform.
|
||||
This is a focused engine/editor for browser-delivered interactive 3D environments.
|
||||
|
||||
---
|
||||
|
||||
## Product pillars
|
||||
|
||||
1. **Brushes are sacred**
|
||||
- Layout authoring must remain faster than Blender.
|
||||
- Brush editing is a first-class workflow, not a legacy compatibility mode.
|
||||
- The editor must feel immediate, precise, and grid-friendly.
|
||||
1. **Interactive environments come first**
|
||||
- The tool exists to build playable interactive 3D spaces for the web.
|
||||
- The editor and runner are one product, not separate concerns.
|
||||
- One-click edit -> run must remain central.
|
||||
|
||||
2. **Imported assets are first-class**
|
||||
2. **Whiteboxing is sacred**
|
||||
- Layout authoring must remain faster and more direct than using a general DCC for the same task.
|
||||
- Whiteboxing is a first-class workflow, not a temporary preproduction mode.
|
||||
- The editor must feel immediate and precise, with snapping available as a helper rather than a hard restriction.
|
||||
|
||||
3. **Imported assets are first-class**
|
||||
- glTF / GLB import must feel native.
|
||||
- Imported meshes, materials, textures, and animations must coexist cleanly with brush-authored worlds.
|
||||
- Imported assets complement brushes; they do not replace them.
|
||||
- Imported meshes, materials, textures, and animations must coexist cleanly with whitebox-authored worlds.
|
||||
- Imported assets complement whiteboxing; they do not replace it.
|
||||
|
||||
3. **The runner is built in**
|
||||
4. **The runner is built in**
|
||||
- Every meaningful authoring step should be testable in-browser.
|
||||
- Switching from edit mode to play mode should be nearly instant.
|
||||
- The runner is part of the product, not a demo app.
|
||||
|
||||
4. **Web-native sharing matters**
|
||||
5. **Web-native sharing matters**
|
||||
- Scenes should be easy to load, embed, preview, and eventually share by URL.
|
||||
- The browser is a target platform, not a secondary export target.
|
||||
|
||||
@@ -101,10 +106,9 @@ These defaults are intentionally fixed for the early slices unless a later slice
|
||||
- when binary assets arrive, they must survive reloads via embedded data or project-scoped packaged storage
|
||||
- never rely on ephemeral Blob URLs as the only persisted asset reference
|
||||
|
||||
### Early brush defaults
|
||||
### Current box-solid defaults
|
||||
|
||||
- Slice 1.1 box brushes are axis-aligned only
|
||||
- arbitrary brush rotation is explicitly deferred
|
||||
- early slices began with axis-aligned box brushes
|
||||
- canonical box face IDs are fixed and stable:
|
||||
- `posX`
|
||||
- `negX`
|
||||
@@ -113,22 +117,48 @@ These defaults are intentionally fixed for the early slices unless a later slice
|
||||
- `posZ`
|
||||
- `negZ`
|
||||
- `posY` is the top face and `negY` is the bottom face
|
||||
- future geometry slices may evolve these box-authored solids into freely transformable whitebox solids while preserving stable face identity where practical
|
||||
|
||||
### Whitebox geometry direction
|
||||
|
||||
- the product is moving from grid-bound brush thinking toward intuitive whitebox solids for level blocking
|
||||
- floating point position, rotation, and scale are allowed
|
||||
- the grid is a snap/reference aid, not a hard authoring law
|
||||
- whitebox boxes should support object, face, edge, and vertex interaction modes
|
||||
- non-planar quads are acceptable; rendering/build should triangulate them deterministically
|
||||
- whitebox solids do not need to stay convex
|
||||
- derived collision for whitebox solids should come from the solid-collider path, not from an assumption that all geometry is convex or axis-aligned
|
||||
|
||||
### Model placement
|
||||
|
||||
- placed imported models are **model instances**, not typed entities
|
||||
- keep model instances in a document collection separate from `entities`
|
||||
|
||||
### Imported model collision scope
|
||||
|
||||
- collision authoring for imported models belongs on `modelInstances`, not on asset records
|
||||
- the canonical source of truth is authored collision settings, not cooked collider bytes
|
||||
- generated collider data may be cached or rebuilt, but it is derived from:
|
||||
- imported model asset geometry
|
||||
- model instance transform
|
||||
- authored collision settings
|
||||
- for imported-model collider support beyond simple boxes, prefer integrating a real collision/query library such as Rapier over inventing custom broad-phase/narrow-phase code in-house
|
||||
- let the collision/query layer own broad-phase and narrow-phase pruning instead of re-implementing that manually in app code
|
||||
- do not turn this slice into a full physics sandbox or general rigidbody architecture rewrite unless the roadmap explicitly asks for that
|
||||
- near-term slices may adapt or replace the current handcrafted runner collision path where necessary so brush and imported-model colliders can participate in one coherent collision/query system
|
||||
|
||||
### Runtime interaction scope
|
||||
|
||||
- keep trigger/action/target links explicit and typed
|
||||
- do not activate actions for systems that do not exist yet
|
||||
- add sound and animation actions only when those runtime systems are implemented
|
||||
|
||||
### Early clipping scope
|
||||
### Whitebox editing scope
|
||||
|
||||
- until a dedicated convex-brush slice exists, clipping must be constrained to results representable by currently supported brush kinds
|
||||
- unsupported clip cases must fail clearly instead of inventing new hidden geometry rules
|
||||
- object, face, edge, and vertex editing should converge on one coherent transform-driven interaction model
|
||||
- `G / R / S` style modal transforms with axis constraints are a good fit for whiteboxing
|
||||
- clipping/extrusion/other topology tools should come after the whitebox-solid interaction model is coherent
|
||||
- unsupported geometry edits must fail clearly instead of inventing hidden topology rules
|
||||
|
||||
---
|
||||
|
||||
@@ -155,12 +185,16 @@ They are not v1 priorities.
|
||||
Use these terms consistently:
|
||||
|
||||
- **Document**: canonical editor state
|
||||
- **Brush**: author-authored solid/primitive in canonical brush form
|
||||
- **Face**: one editable surface of a brush
|
||||
- **Whitebox Solid**: author-authored blockout/level-shaping solid used for layout and gameplay space
|
||||
- **Box Solid**: the first whitebox solid shape; current code may still refer to this historically as a box brush
|
||||
- **Face**: one editable surface of a whitebox solid
|
||||
- **Edge**: one editable edge of a whitebox solid
|
||||
- **Vertex**: one editable point of a whitebox solid
|
||||
- **Material**: logical authoring material definition
|
||||
- **Texture**: image resource backing material channels
|
||||
- **Asset**: imported external resource, usually GLB/GLTF or audio and related media
|
||||
- **Model Instance**: placed scene instance of an imported asset
|
||||
- **Collider**: runtime collision representation derived from brushes or imported models
|
||||
- **Prefab**: reusable asset/entity package placeable in scenes
|
||||
- **Entity**: typed scene object with runtime/editor semantics
|
||||
- **Project Package**: portable editable bundle containing canonical scene JSON plus referenced assets
|
||||
@@ -168,7 +202,7 @@ Use these terms consistently:
|
||||
- **Runner**: browser runtime that loads and plays scenes
|
||||
- **Viewport**: editor rendering surface
|
||||
- **Command**: undoable state transition
|
||||
- **Tool**: editor interaction mode such as select, move, box-create, face-edit
|
||||
- **Tool**: editor interaction mode such as select, create, transform, or face-edit
|
||||
- **Build**: deterministic transformation from document -> runtime scene data
|
||||
- **Export**: downstream transformation to deployable or interchange deliverables such as runner packages or optional later GLB
|
||||
|
||||
@@ -193,7 +227,7 @@ When working in this repo:
|
||||
3. Preserve layering.
|
||||
- `document` owns canonical state.
|
||||
- `commands` apply valid state changes.
|
||||
- `geometry` owns derived brush and collider generation.
|
||||
- `geometry` owns derived solid and collider generation.
|
||||
- `viewport-three` renders editor state.
|
||||
- `runtime-three` plays runtime state.
|
||||
- `entities` owns typed non-brush scene objects.
|
||||
@@ -298,14 +332,16 @@ Maintain these layers:
|
||||
Do not let editor-only helpers leak into the canonical document.
|
||||
Do not store raw three.js objects inside canonical document state.
|
||||
|
||||
### Brush rules
|
||||
### Whitebox geometry rules
|
||||
|
||||
- brushes are not stored as triangle soup
|
||||
- whitebox solids are canonical authoring objects, not raw renderer state
|
||||
- face material assignments are per-face
|
||||
- UV transforms are canonical editor data
|
||||
- runtime mesh generation is derived data
|
||||
- render triangulation is derived data
|
||||
- collision generation is derived data
|
||||
- early boxes are axis-aligned and use fixed face IDs
|
||||
- non-planar quad faces are acceptable if the derived mesh triangulates them deterministically
|
||||
- whitebox solids do not need to remain convex
|
||||
- current box solids still use stable face IDs, even if later slices relax earlier axis-aligned constraints
|
||||
|
||||
### Entity rules
|
||||
|
||||
@@ -315,6 +351,21 @@ Do not store raw three.js objects inside canonical document state.
|
||||
- entity validation must happen at document/build boundaries
|
||||
- model instances remain separate from entities
|
||||
|
||||
### Imported model collision rules
|
||||
|
||||
- collision settings for imported models live on `modelInstances`
|
||||
- supported collision modes must be explicit and typed
|
||||
- generated collision geometry is derived data, not the canonical source document
|
||||
- collision debug visibility is editor/runtime UI state driven by authored settings, not a hidden renderer-only toggle
|
||||
- avoid implicit “always collide with render mesh” behavior
|
||||
- if broad-phase/narrow-phase pruning or non-box collider support is needed, prefer Rapier over ad hoc custom collision math
|
||||
- collision modes mean:
|
||||
- `none` = no collider
|
||||
- `terrain` = heightfield collider, static only
|
||||
- `static` = triangle mesh collider, fixed only
|
||||
- `dynamic` = convex decomposition into compound collider, dynamic/kinematic capable
|
||||
- `simple` = one cheap primitive or one convex hull
|
||||
|
||||
---
|
||||
|
||||
## Performance rules
|
||||
@@ -339,7 +390,7 @@ When optimizing:
|
||||
Expected hotspots:
|
||||
|
||||
- picking/raycasting
|
||||
- brush rebuilds / CSG
|
||||
- whitebox mesh rebuilds / solid triangulation
|
||||
- face highlighting
|
||||
- large texture browser lists
|
||||
- imported asset previews
|
||||
@@ -354,7 +405,7 @@ The editor should feel like a real authoring tool, not a tech demo.
|
||||
Prioritize:
|
||||
|
||||
- fast selection
|
||||
- robust snapping
|
||||
- trustworthy snapping when enabled
|
||||
- visible grid and transform feedback
|
||||
- obvious active tool state
|
||||
- low-friction material application
|
||||
@@ -423,7 +474,7 @@ Especially in early versions.
|
||||
|
||||
### Prefer constrained capabilities that feel good over flexible capabilities that feel vague
|
||||
Example:
|
||||
- better to have one excellent box-brush tool than five half-working primitive tools
|
||||
- better to have one excellent whitebox-solid editing flow than five half-working primitive tools
|
||||
|
||||
### Prefer immediate usability over speculative extensibility
|
||||
But preserve clean seams for future extensions.
|
||||
@@ -439,7 +490,7 @@ Do not:
|
||||
- add R3F because “we might want it later”
|
||||
- introduce ECS because “games use ECS”
|
||||
- over-generalize the entity system
|
||||
- replace canonical brush data with raw mesh editing
|
||||
- replace canonical whitebox data with hidden renderer-only mesh mutations
|
||||
- implement hidden magic behaviors without schema support
|
||||
- remove tests to get green CI
|
||||
- make visual changes without noting them in the slice summary
|
||||
@@ -503,9 +554,9 @@ The product should always trend toward:
|
||||
- authoring clarity
|
||||
- browser-native practicality
|
||||
- fast iteration
|
||||
- strong foundations for brushes, assets, entities, and runner behavior
|
||||
- strong foundations for whiteboxing, assets, entities, and runner behavior
|
||||
|
||||
If forced to choose, preserve the integrity of:
|
||||
1. the canonical document model
|
||||
2. the brush workflow
|
||||
2. the whiteboxing workflow
|
||||
3. the edit -> run loop
|
||||
|
||||
@@ -22,14 +22,14 @@ Core loop:
|
||||
|
||||
The product prioritizes:
|
||||
|
||||
- brush-first spatial authoring
|
||||
- intuitive whiteboxing / level blocking for interactive 3D environments
|
||||
- imported assets as first-class additions
|
||||
- typed entities and simple interactions
|
||||
- browser-native delivery
|
||||
|
||||
It is not:
|
||||
|
||||
- a full game engine
|
||||
- an unlimited general-purpose engine platform
|
||||
- a Blender replacement
|
||||
- a general CAD tool
|
||||
- an R3F showcase
|
||||
@@ -83,10 +83,9 @@ These are fixed for the early milestones unless a later slice explicitly changes
|
||||
- binary assets must survive reload via embedded or project-scoped persistent storage
|
||||
- never rely on Blob URLs as the only persisted asset reference
|
||||
|
||||
### Early box brushes
|
||||
### Current box-solid foundation
|
||||
|
||||
- first brush kind is an axis-aligned box
|
||||
- arbitrary brush rotation is deferred
|
||||
- early slices began with an axis-aligned box shape and stable face IDs
|
||||
- stable box face IDs are:
|
||||
- `posX`
|
||||
- `negX`
|
||||
@@ -96,6 +95,16 @@ These are fixed for the early milestones unless a later slice explicitly changes
|
||||
- `negZ`
|
||||
- `posY` is top and `negY` is bottom
|
||||
|
||||
### Whitebox direction
|
||||
|
||||
- move away from grid-bound brush thinking toward whitebox solids
|
||||
- allow floating point transforms
|
||||
- allow free object rotation
|
||||
- use the grid as optional snap/reference help, not as a hard restriction
|
||||
- unify object / face / edge / vertex editing around one transform-driven interaction model
|
||||
- non-planar quads are acceptable if triangulated deterministically in derived geometry
|
||||
- non-convex whitebox solids are acceptable if the solid mesh/collider pipeline can support them
|
||||
|
||||
### Early UV data
|
||||
|
||||
Per face, keep explicit UV transform values such as:
|
||||
@@ -113,6 +122,10 @@ Per face, keep explicit UV transform values such as:
|
||||
- imported assets live in the asset registry
|
||||
- placed imported models live in `modelInstances`
|
||||
- typed scene objects like `PlayerStart`, `TriggerVolume`, or lights live in `entities`
|
||||
- collision authoring for imported models belongs on `modelInstances`, not asset records
|
||||
- generated imported-model collider data should be derived from asset geometry + instance transform + authored settings
|
||||
- for imported-model collider types beyond simple boxes, prefer a Rapier-backed collision/query layer over extending the handcrafted collision code indefinitely
|
||||
- broad-phase and narrow-phase pruning should come from that collision/query layer, not custom app code
|
||||
|
||||
### Interaction scope
|
||||
|
||||
@@ -161,6 +174,7 @@ If a roadmap item is too large, split it into smaller vertical slices.
|
||||
- M1: axis-aligned box brushes, face materials/UVs, runner, first-room polish, world lighting basics
|
||||
- M2: typed entities, simple trigger/action/target interactions, click interactions
|
||||
- M3: GLB/GLTF import, local lights + skyboxes, animation, spatial audio
|
||||
- M4+: whitebox-solid interaction model, component editing, derived solid triangulation/collision
|
||||
|
||||
That ordering matters because:
|
||||
|
||||
|
||||
152
architecture.md
152
architecture.md
@@ -7,12 +7,12 @@ This project is a browser-based 3D scene authoring tool with a built-in runtime
|
||||
It has two primary modes:
|
||||
|
||||
1. **Editor mode**
|
||||
- author spatial scenes using brush primitives, entities, materials, and imported assets
|
||||
- author interactive 3D environments using whitebox solids, entities, materials, and imported assets
|
||||
|
||||
2. **Runner mode**
|
||||
- load and play those scenes in-browser using configurable navigation and interaction modes
|
||||
|
||||
The architecture is designed to preserve old-school level-editor ergonomics while staying web-native and maintainable.
|
||||
The architecture is designed to preserve intuitive level-authoring ergonomics while staying web-native and maintainable.
|
||||
|
||||
---
|
||||
|
||||
@@ -20,7 +20,7 @@ The architecture is designed to preserve old-school level-editor ergonomics whil
|
||||
|
||||
### Primary goals
|
||||
|
||||
- fast and precise brush-based scene authoring
|
||||
- fast and precise whitebox-based scene authoring
|
||||
- modern browser runtime delivery
|
||||
- native support for imported GLB/GLTF assets
|
||||
- robust material/texture workflows
|
||||
@@ -107,10 +107,10 @@ Do not introduce `/apps` + `/packages` or monorepo packaging until the current c
|
||||
- saved projects must keep binary assets via embedded data or project-packaged storage
|
||||
- never persist only ephemeral Blob URLs or runtime-only browser object references
|
||||
|
||||
### Early brush representation
|
||||
### Current box-solid foundation
|
||||
|
||||
The first supported brush kind is an axis-aligned box.
|
||||
Do not support arbitrary brush rotation in Slice 1.1.
|
||||
The first implemented shape was an axis-aligned box with stable face IDs.
|
||||
That is historical starting context, not the long-term geometry constraint.
|
||||
|
||||
Use stable face IDs:
|
||||
|
||||
@@ -142,6 +142,22 @@ interface BoxBrush {
|
||||
|
||||
`size` values should be positive and non-zero.
|
||||
|
||||
### Whitebox geometry direction
|
||||
|
||||
The product is moving away from grid-bound brush thinking toward intuitive whitebox solids for level blocking.
|
||||
|
||||
Directionally, this means:
|
||||
|
||||
- floating point transforms are allowed
|
||||
- free object rotation is allowed
|
||||
- the grid becomes a snap/reference aid, not a hard restriction
|
||||
- object, face, edge, and vertex editing should share one coherent transform-driven interaction model
|
||||
- non-planar quad faces are acceptable; derived rendering/build should triangulate them deterministically
|
||||
- solids do not need to remain convex
|
||||
- collision should come from the solid-collider pipeline rather than assumptions about convexity or axis alignment
|
||||
|
||||
Near-term implementation can keep existing `BoxBrush`/box-solid structures where useful, but future geometry slices should treat them as the first whitebox solid type rather than the entire long-term model.
|
||||
|
||||
### Early UV representation
|
||||
|
||||
Store actual UV transform values canonically per face.
|
||||
@@ -167,6 +183,21 @@ Placed imported models are not typed entities.
|
||||
- placed scene instances of those assets live in `modelInstances`
|
||||
- typed runtime/editor objects such as `PlayerStart` or `TriggerVolume` live in `entities`
|
||||
|
||||
### Imported model collision scope
|
||||
|
||||
Imported model collision should extend the current architecture, not replace it.
|
||||
|
||||
- authored collision settings belong on `modelInstances`
|
||||
- generated collider data is derived from:
|
||||
- imported model asset geometry
|
||||
- model instance transform
|
||||
- authored collision settings
|
||||
- do not make cooked/generated collider bytes the canonical source document by default
|
||||
- for non-box imported-model collider support and broad-phase/narrow-phase pruning, prefer integrating Rapier as a collision/query subsystem over inventing custom collision code in-house
|
||||
- broad-phase and narrow-phase pair pruning should be delegated to that collision/query layer rather than re-implemented manually in app code
|
||||
- do not turn this into a full general-purpose physics sandbox unless the product actually needs one
|
||||
- near-term slices may adapt or replace the current handcrafted runner collision path so brushes and imported models can participate in one coherent collision/query system
|
||||
|
||||
### Trigger/action/target scope
|
||||
|
||||
Keep interaction links explicit and typed.
|
||||
@@ -176,10 +207,16 @@ Only activate actions for systems that already exist.
|
||||
- sound actions should land with the audio slice
|
||||
- animation actions should land with the animation slice
|
||||
|
||||
### Clipping scope
|
||||
### Whitebox editing scope
|
||||
|
||||
Until a dedicated convex-brush slice exists, clipping must stay constrained to results representable by the currently supported brush kinds.
|
||||
If the first clip implementation only supports axis-aligned box brushes and principal-axis clip planes, that is acceptable.
|
||||
The geometry roadmap should prioritize:
|
||||
|
||||
- object transforms
|
||||
- component selection modes
|
||||
- face/edge/vertex editing
|
||||
- robust derived triangulation/collision for edited solids
|
||||
|
||||
before adding topology-changing tools such as clipping/extrusion in earnest.
|
||||
|
||||
---
|
||||
|
||||
@@ -200,7 +237,7 @@ Properties:
|
||||
|
||||
Contains:
|
||||
- world settings
|
||||
- brush definitions
|
||||
- whitebox solid definitions
|
||||
- face UV/material assignments
|
||||
- entity instances
|
||||
- model instances
|
||||
@@ -226,7 +263,7 @@ Contains:
|
||||
- selection outlines
|
||||
- gizmos
|
||||
- helper icons
|
||||
- grids
|
||||
- grids and snap guides
|
||||
- temporary tool feedback
|
||||
|
||||
### 3. Runtime representation
|
||||
@@ -344,6 +381,8 @@ interface SceneDocument {
|
||||
}
|
||||
```
|
||||
|
||||
Imported model collision settings should be represented canonically on the relevant `ModelInstance` records or a tightly related typed sub-structure, not as hidden renderer/runtime state.
|
||||
|
||||
`WorldSettings` is the correct home for:
|
||||
|
||||
- background mode and background color/gradient
|
||||
@@ -420,29 +459,27 @@ Contains:
|
||||
|
||||
This is one of the most critical modules.
|
||||
|
||||
### Canonical brush representation
|
||||
### Canonical whitebox representation
|
||||
|
||||
Brushes should not be stored as raw triangle meshes.
|
||||
Whitebox solids should not be stored as hidden renderer-only mesh state.
|
||||
|
||||
Preferred progression:
|
||||
|
||||
#### Early v1
|
||||
#### Current transition
|
||||
|
||||
Explicit parametric primitives with per-face data:
|
||||
|
||||
- box
|
||||
- wedge/ramp
|
||||
- cylinder prism
|
||||
- stairs
|
||||
- arch
|
||||
- box-based whitebox solids with stable face identity
|
||||
- object transforms plus component selection/editing
|
||||
- derived triangulation for rendering and collision
|
||||
|
||||
#### Later
|
||||
|
||||
Plane-based convex solids and clipping-based editing.
|
||||
- richer whitebox solid topology tools
|
||||
- clipping/extrusion/bevel-like operations if they fit the product cleanly
|
||||
- broader solid editing without turning the product into arbitrary mesh modeling
|
||||
|
||||
### Derived outputs
|
||||
|
||||
From brush data, generate:
|
||||
From canonical whitebox data, generate:
|
||||
|
||||
- editor mesh
|
||||
- pick mesh
|
||||
@@ -525,6 +562,14 @@ Responsibilities:
|
||||
- `AnimationSystem`
|
||||
- `RuntimeUIBridge`
|
||||
|
||||
### Collision strategy progression
|
||||
|
||||
Near-term runtime collision is intentionally narrower than a full game-engine physics stack.
|
||||
|
||||
- early runner slices use deterministic explicit collision data for navigation and authored interactions
|
||||
- imported model collision should first plug into that same runtime build/query path
|
||||
- only introduce a broader physics world when dynamic rigid bodies, richer contact response, or other product requirements make it necessary
|
||||
|
||||
### Navigation modes
|
||||
|
||||
Initial modes:
|
||||
@@ -697,6 +742,59 @@ There should be a clear distinction between:
|
||||
- model instance
|
||||
- prefab definition
|
||||
|
||||
### Imported model collision authoring
|
||||
|
||||
Imported models need an explicit authored collision path that coexists with brush collision.
|
||||
|
||||
Recommended authored settings shape:
|
||||
|
||||
```ts
|
||||
type ModelInstanceCollisionMode =
|
||||
| "none"
|
||||
| "terrain"
|
||||
| "static"
|
||||
| "dynamic"
|
||||
| "simple";
|
||||
|
||||
interface ModelInstanceCollisionSettings {
|
||||
mode: ModelInstanceCollisionMode;
|
||||
visible: boolean;
|
||||
simpleShape?: "box" | "sphere" | "capsule" | "convexHull";
|
||||
terrainResolution?: number;
|
||||
dynamicQuality?: "low" | "medium" | "high";
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- these settings are canonical authoring data
|
||||
- generated collider geometry is derived/cacheable data
|
||||
- collision generation is triggered by authored settings, not hidden import-time guesses
|
||||
- `modelInstances` remain separate from `entities`
|
||||
- collision debug rendering should be visually inspectable in editor and runner when enabled
|
||||
- preferred implementation path is:
|
||||
- Rapier 3D WASM provides the collision/query layer
|
||||
- Rapier owns broad-phase and narrow-phase pruning
|
||||
- the editor document owns authored collider settings
|
||||
- generated collider geometry/handles are derived runtime/cache data
|
||||
- collision modes should mean exactly:
|
||||
- `none` = no collider
|
||||
- `terrain` = heightfield collider, static only
|
||||
- `static` = triangle mesh collider, fixed only
|
||||
- `dynamic` = convex decomposition into compound collider, dynamic/kinematic capable
|
||||
- `simple` = one cheap primitive or one convex hull
|
||||
- initial support may be staged, but unsupported modes must fail clearly instead of silently degrading to random approximations
|
||||
|
||||
### Collision strategy progression
|
||||
|
||||
- early slices used handcrafted box-based player collision because only brush boxes existed
|
||||
- once imported-model colliders require terrain, trimesh, convex hull, or compound collision, the preferred next step is a Rapier-backed collision/query layer
|
||||
- this does not require a full gameplay physics sandbox in the same slice
|
||||
- a valid intermediate state is:
|
||||
- fixed/queryable colliders for brushes and imported models
|
||||
- existing first-person movement adapted to query against Rapier-backed colliders
|
||||
- dynamic collider generation represented canonically even if full rigidbody simulation lands later
|
||||
|
||||
---
|
||||
|
||||
## `serialization`
|
||||
@@ -905,11 +1003,19 @@ SceneDocument
|
||||
-> validate
|
||||
-> resolve assets/materials/entities/model instances
|
||||
-> build brush meshes
|
||||
-> build model-instance collider data
|
||||
-> build colliders
|
||||
-> build runtime entity graph
|
||||
-> assemble runtime scene package
|
||||
```
|
||||
|
||||
In the near-term architecture, `build colliders` may include a mix of:
|
||||
|
||||
- brush-derived colliders
|
||||
- imported-model-instance-derived colliders
|
||||
|
||||
without requiring a full general-purpose physics world.
|
||||
|
||||
### Project package build stages
|
||||
|
||||
```txt
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dimforge/rapier3d-compat": "^0.19.3",
|
||||
"postprocessing": "^6.39.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
|
||||
@@ -341,6 +341,46 @@ Do not:
|
||||
|
||||
---
|
||||
|
||||
## Slice Body 8B — Imported model collider authoring
|
||||
|
||||
```text
|
||||
Relevant docs to inspect after the common preamble:
|
||||
- architecture.md: model instances, assets, runtime build, collision scope
|
||||
- roadmap.md: Slice 3.1B
|
||||
- testing.md: serialization, geometry/runtime, collision coverage
|
||||
|
||||
Implement Slice 3.1B.
|
||||
|
||||
Requirements:
|
||||
- canonical collision settings on model instances
|
||||
- inspector selector for:
|
||||
- none
|
||||
- terrain
|
||||
- static
|
||||
- dynamic
|
||||
- simple
|
||||
- collision visibility/debug toggle
|
||||
- generated collider data derived from model asset geometry + model instance transform + authored settings
|
||||
- Rapier-backed collision/query integration for broad-phase/narrow-phase handling
|
||||
- runtime integration with the existing runner collision path
|
||||
- debug visualization for generated collision where enabled
|
||||
- explicit collider semantics:
|
||||
- none = no collider
|
||||
- terrain = heightfield collider, static only
|
||||
- static = triangle mesh collider, fixed only
|
||||
- dynamic = convex decomposition into compound collider, dynamic/kinematic capable
|
||||
- simple = one cheap primitive or one convex hull
|
||||
|
||||
Constraints:
|
||||
- do not merge model instances into entities
|
||||
- use Rapier instead of inventing custom broad-phase/narrow-phase code
|
||||
- do not rewrite the runner into a full gameplay-physics sandbox in this slice
|
||||
- keep authored settings canonical and generated collider data derived/cacheable
|
||||
- if terrain/dynamic support is partial, fail clearly and document it
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Slice Body 9 — Animation playback
|
||||
|
||||
```text
|
||||
|
||||
94
prompts.txt
94
prompts.txt
@@ -698,6 +698,100 @@ Please implement fully and report:
|
||||
|
||||
---
|
||||
|
||||
## Prompt 8B — Imported model collider authoring
|
||||
|
||||
```text
|
||||
You are implementing Slice 3.1B — Imported model collider authoring.
|
||||
|
||||
Read and follow:
|
||||
- AGENTS.md
|
||||
- CHAT_CONTEXT.md
|
||||
- architecture.md
|
||||
- roadmap.md
|
||||
- testing.md
|
||||
|
||||
Before coding:
|
||||
- Inspect the current repo and extend the existing implementation.
|
||||
- Build on the existing model asset / model instance path. Do not merge model instances into entities.
|
||||
- Integrate with the existing runtime scene build, but use Rapier 3D WASM as the collision/query layer for this slice instead of inventing custom broad-phase/narrow-phase logic.
|
||||
- Do not turn this slice into a full gameplay-physics sandbox or broad entity rigidbody rewrite.
|
||||
- If you change persisted schema, update versioning, migrations, and at least one compatibility test.
|
||||
|
||||
Current goal:
|
||||
Make imported model instances participate in collision by adding explicit authored collider settings, generated collider data, Rapier-backed collision/query integration, and runtime/debug support that fits the current codebase.
|
||||
|
||||
Requirements:
|
||||
- Add canonical collision settings to model instances.
|
||||
- Add an inspector UI for imported model instances with an explicit collision mode selector:
|
||||
- none
|
||||
- terrain
|
||||
- static
|
||||
- dynamic
|
||||
- simple
|
||||
- Add a collision visibility/debug toggle for model instances.
|
||||
- Generated collider data must be derived from:
|
||||
- imported model asset geometry
|
||||
- model instance transform
|
||||
- authored collision settings
|
||||
- Keep the authored settings canonical. Do not make cooked/generated collider bytes the source of truth in the document.
|
||||
- If you add caching, keep it explicit and derived.
|
||||
- Use Rapier 3D WASM for broad-phase/narrow-phase pruning and collision/query evaluation in this slice.
|
||||
|
||||
Collision-mode expectations:
|
||||
- `none`:
|
||||
- no collider
|
||||
- `terrain`:
|
||||
- heightfield collider
|
||||
- static only
|
||||
- if the source mesh cannot support the chosen terrain path cleanly, fail clearly with diagnostics instead of silently pretending it worked
|
||||
- `static`:
|
||||
- triangle mesh collider
|
||||
- fixed only
|
||||
- `dynamic`:
|
||||
- convex decomposition into a compound collider
|
||||
- dynamic/kinematic capable representation
|
||||
- this slice does not require a full general rigidbody gameplay system, but the generated representation must be explicit and correct
|
||||
- if actual runtime behavior is limited in this slice, document exactly what works now
|
||||
- `simple`:
|
||||
- one cheap primitive or one convex hull
|
||||
- keep the initial option set small and explicit if needed
|
||||
|
||||
Runtime/build requirements:
|
||||
- Extend runtime scene build so imported model colliders participate in one coherent Rapier-backed collision/query path together with brush-authored world collision.
|
||||
- Broad-phase and narrow-phase handling should come from Rapier, not app-specific custom collision pruning code.
|
||||
- Keep first-person traversal/collision working. It is acceptable to adapt the current player collision path to query against Rapier-backed colliders instead of the handwritten box-only collision path.
|
||||
- Add debug visualization for generated imported-model collision in editor and/or runner when the visibility toggle is enabled.
|
||||
- Keep the implementation understandable and explicit.
|
||||
|
||||
Important:
|
||||
- Do not build a giant general-purpose physics framework around Rapier in this slice.
|
||||
- Do not add arbitrary rigidbody components to every scene object just because Rapier is present.
|
||||
- Do not hide collider generation behind import-time magic; it should be driven by authored collision settings.
|
||||
- Do not treat the render mesh as automatically equal to the collision mesh in all modes.
|
||||
- Keep model-instance collision separate from brush collision and separate from typed entity schemas.
|
||||
|
||||
Testing expectations:
|
||||
- Round-trip tests for model-instance collision settings
|
||||
- Migration/compatibility test if schema changes
|
||||
- Validation/build tests for invalid or unsupported collision-mode assumptions
|
||||
- Geometry/runtime tests for generated collider outputs where practical
|
||||
- Runtime/domain tests proving the generated colliders participate in the actual Rapier-backed collision/query path
|
||||
- Runner/domain tests proving imported-model collision works together with existing brush/world collision
|
||||
- Browser/e2e or manual verification for collision debug visibility if practical
|
||||
|
||||
Please implement fully and report:
|
||||
- model-instance collision schema/settings
|
||||
- supported behavior for each collision mode
|
||||
- how generated collider data is represented and rebuilt/cached
|
||||
- how Rapier is integrated into the current runner collision/query architecture
|
||||
- how broad-phase/narrow-phase responsibilities are handled
|
||||
- how debug visibility works
|
||||
- tests added or updated
|
||||
- what limitations remain, especially for `terrain` and `dynamic`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Prompt 9 — Animation playback
|
||||
|
||||
```text
|
||||
|
||||
159
roadmap.md
159
roadmap.md
@@ -27,9 +27,9 @@ If a roadmap item is too large for one implementation pass, split it into smalle
|
||||
|
||||
## Product north star
|
||||
|
||||
A browser-based brush editor with a built-in runner, enabling users to quickly create and share lightweight interactive 3D spaces with:
|
||||
A browser-based engine/editor with a built-in runner, enabling users to quickly create and share lightweight interactive 3D spaces with:
|
||||
|
||||
- brush-authored layout
|
||||
- intuitive whiteboxing / level blocking
|
||||
- material/texture workflows
|
||||
- imported GLB/GLTF assets
|
||||
- spatial audio
|
||||
@@ -46,7 +46,7 @@ These are locked for the early milestones:
|
||||
- early repo shape is a single Vite app with domain folders under `src/`
|
||||
- canonical document state lives outside the React tree
|
||||
- the document is versioned from day one
|
||||
- early box brushes are axis-aligned only with fixed face IDs
|
||||
- early slices began with axis-aligned box brushes and fixed face IDs
|
||||
- placed imported models are `modelInstances`, not `entities`
|
||||
- local draft persistence plus explicit JSON import/export is acceptable early
|
||||
- once scenes depend on external binary assets, portable save/load must move to a project package containing canonical scene JSON plus bundled assets
|
||||
@@ -60,7 +60,7 @@ These are locked for the early milestones:
|
||||
Foundation and repo discipline
|
||||
|
||||
### Milestone 1
|
||||
First real room: brush layout + materials + play mode
|
||||
First real room: box-based layout + materials + play mode
|
||||
|
||||
### Milestone 2
|
||||
Entities and runtime interaction
|
||||
@@ -69,7 +69,7 @@ Entities and runtime interaction
|
||||
Imported models, lighting, animation, and audio
|
||||
|
||||
### Milestone 4
|
||||
Better brush editing and authoring ergonomics
|
||||
Whiteboxing and direct geometry editing
|
||||
|
||||
### Milestone 5
|
||||
Project portability, deployment, and quality improvements
|
||||
@@ -120,7 +120,7 @@ Create the minimum project skeleton that supports fast vertical slicing without
|
||||
|
||||
### Vision
|
||||
|
||||
The user can create a box brush, assign materials to faces, save the scene, reload it, and run around it.
|
||||
The user can create a box-based room, assign materials to faces, save the scene, reload it, and run around it.
|
||||
|
||||
This is the first proof that the product is real.
|
||||
|
||||
@@ -239,7 +239,7 @@ This is the first proof that the product is real.
|
||||
|
||||
### Vision
|
||||
|
||||
The user can place non-brush entities and author simple interactive scenes without scripting.
|
||||
The user can place non-whitebox entities and author simple interactive scenes without scripting.
|
||||
|
||||
### Slice 2.1 — Entity system foundation
|
||||
|
||||
@@ -342,6 +342,40 @@ The tool becomes more than brush-only by supporting imported assets, authored li
|
||||
|
||||
---
|
||||
|
||||
### Slice 3.1B — Imported model collider authoring
|
||||
|
||||
#### Deliverables
|
||||
|
||||
- canonical collision settings on model instances
|
||||
- explicit collision mode selector for:
|
||||
- none
|
||||
- terrain
|
||||
- static
|
||||
- dynamic
|
||||
- simple
|
||||
- collision visibility/debug toggle
|
||||
- generated collider data derived from imported model geometry plus authored settings
|
||||
- Rapier-backed collision/query integration for imported-model colliders and broad-phase/narrow-phase handling
|
||||
- runtime build support for imported-model colliders in the runner collision path
|
||||
- editor/runner debug visualization of generated collision where enabled
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- author can choose a collision mode per model instance in the inspector
|
||||
- imported models can participate in runner collision without hand-authored invisible geometry
|
||||
- collider modes mean exactly:
|
||||
- none = no collider
|
||||
- terrain = heightfield collider, static only
|
||||
- static = triangle mesh collider, fixed only
|
||||
- dynamic = convex decomposition into compound collider, dynamic/kinematic capable
|
||||
- simple = one cheap primitive or one convex hull
|
||||
- generated collision survives save/load through canonical settings and deterministic rebuild behavior
|
||||
- broad-phase and narrow-phase pruning are handled by Rapier instead of app-specific custom collision code
|
||||
- the slice does not require a full gameplay-physics sandbox
|
||||
- unsupported or partial modes fail clearly instead of silently pretending to work
|
||||
|
||||
---
|
||||
|
||||
### Slice 3.2 — Local lights and skyboxes
|
||||
|
||||
#### Deliverables
|
||||
@@ -396,64 +430,102 @@ The tool becomes more than brush-only by supporting imported assets, authored li
|
||||
|
||||
---
|
||||
|
||||
## Milestone 4 — Better brush ergonomics
|
||||
## Milestone 4 — Whiteboxing and direct geometry editing
|
||||
|
||||
### Vision
|
||||
|
||||
The editor starts feeling closer to the old-school map-editor joy.
|
||||
The editor stops feeling like a grid-bound brush tool and starts feeling like an intuitive web-native whiteboxing environment for interactive spaces.
|
||||
|
||||
These roadmap items may be delivered as multiple smaller implementation chats if that produces cleaner vertical slices.
|
||||
|
||||
### Slice 4.1 — More brush primitives
|
||||
### Slice 4.1 — Whitebox terminology and float-transform foundation
|
||||
|
||||
#### Deliverables
|
||||
|
||||
- wedge/ramp
|
||||
- cylinder prism
|
||||
- stairs
|
||||
- arch
|
||||
- shift the product/editor language from brush-first toward whitebox-solid authoring
|
||||
- allow floating point position/rotation/scale for box-based whitebox solids
|
||||
- free object rotation for whitebox boxes
|
||||
- grid snapping becomes optional/configurable rather than mandatory
|
||||
- save/load/runtime support for the new transform freedom
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- each new primitive is:
|
||||
- creatable
|
||||
- editable
|
||||
- save/load safe
|
||||
- renderable in runner
|
||||
- covered by geometry tests
|
||||
- user can place and rotate whitebox boxes freely without being forced back onto a coarse grid
|
||||
- transformed whitebox solids persist through save/load
|
||||
- editor and runner both reflect the same transform state
|
||||
|
||||
---
|
||||
|
||||
### Slice 4.2 — Brush clipping
|
||||
### Slice 4.2 — Whitebox component selection modes
|
||||
|
||||
#### Deliverables
|
||||
|
||||
- clip tool
|
||||
- split/keep side options
|
||||
- explicit object / face / edge / vertex selection modes
|
||||
- clear viewport feedback for the current component mode
|
||||
- default object-first selection behavior for transform workflows
|
||||
- coherent behavior in perspective and orthographic panes
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- the user can intentionally choose what level of a whitebox solid they are editing
|
||||
- component selection feels reliable and visible in single-view and quad-view layouts
|
||||
|
||||
---
|
||||
|
||||
### Slice 4.3 — Unified whitebox transforms
|
||||
|
||||
#### Deliverables
|
||||
|
||||
- unified transform workflow for object and component editing
|
||||
- `G / R / S` style modal transforms with `X / Y / Z` constraints
|
||||
- gizmo + keyboard parity where practical
|
||||
- move/rotate/scale support for whitebox objects
|
||||
- move/rotate/scale support for faces and edges where valid
|
||||
- move support for vertices in the first pass
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- whitebox editing feels direct rather than inspector-driven
|
||||
- transform previews, cancel, commit, and undo/redo are coherent
|
||||
- object and component transforms share one understandable interaction model
|
||||
|
||||
---
|
||||
|
||||
### Slice 4.4 — Whitebox mesh and collider derivation
|
||||
|
||||
#### Deliverables
|
||||
|
||||
- derived triangulation for edited whitebox solids
|
||||
- support for non-planar quad faces via deterministic internal triangulation
|
||||
- support for non-convex whitebox solids where the editing model permits them
|
||||
- collision generation through the solid collider path rather than axis-aligned-box assumptions
|
||||
- validation/diagnostics for invalid or unsupported edited solids
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- edited whitebox solids render and collide correctly in editor and runner
|
||||
- non-planar faces do not break the build path
|
||||
- unsupported geometry states fail clearly instead of silently corrupting the scene
|
||||
|
||||
---
|
||||
|
||||
### Slice 4.5 — Topology tools after transform foundations
|
||||
|
||||
#### Deliverables
|
||||
|
||||
- evaluate and add the first topology-changing tool only after the whitebox interaction model is coherent
|
||||
- possible candidates:
|
||||
- clip
|
||||
- extrude
|
||||
- bevel/chamfer-like edge operations
|
||||
- preview visualization
|
||||
- undo/redo support
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- clip operations are predictable and reversible
|
||||
- resulting brushes remain valid
|
||||
- unsupported clip cases fail clearly instead of silently producing ad hoc geometry
|
||||
|
||||
---
|
||||
|
||||
### Slice 4.3 — Better viewport layouts
|
||||
|
||||
#### Deliverables
|
||||
|
||||
- top/front/side orthographic views
|
||||
- optional split layout
|
||||
- improved transform workflows
|
||||
- configurable snapping
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- level-authoring speed materially improves
|
||||
- camera controls are documented and stable
|
||||
- the chosen topology tool feels consistent with the existing whitebox interaction model
|
||||
- resulting solids remain save/load safe and runner-safe
|
||||
- unsupported cases fail clearly instead of silently producing ad hoc geometry
|
||||
|
||||
---
|
||||
|
||||
@@ -562,7 +634,7 @@ These are only pursued after the earlier core loop feels solid.
|
||||
When schedule pressure forces tradeoffs, prefer work that strengthens:
|
||||
|
||||
1. edit -> save/load -> run loop
|
||||
2. brush ergonomics
|
||||
2. whiteboxing ergonomics
|
||||
3. material/texture speed
|
||||
4. typed entities and interactions
|
||||
5. imported asset support
|
||||
@@ -593,6 +665,7 @@ A slice is complete only when:
|
||||
- per-face UV persistence
|
||||
- picking accuracy
|
||||
- collision generation from brush data
|
||||
- collision generation from imported model data
|
||||
- imported asset/material compatibility
|
||||
- browser audio unlock behavior
|
||||
- input edge cases across browsers
|
||||
|
||||
2804
src/app/App.tsx
2804
src/app/App.tsx
File diff suppressed because it is too large
Load Diff
598
src/app/app.css
598
src/app/app.css
@@ -65,8 +65,8 @@ button:disabled {
|
||||
display: grid;
|
||||
grid-template-rows: auto minmax(0, 1fr) auto;
|
||||
height: 100vh;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
gap: 10px;
|
||||
padding: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -74,44 +74,80 @@ button:disabled {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 0 18px;
|
||||
gap: 12px;
|
||||
padding: 8px 14px;
|
||||
background: rgba(18, 22, 28, 0.88);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 18px;
|
||||
border-radius: 16px;
|
||||
box-shadow: var(--shadow-panel);
|
||||
backdrop-filter: blur(16px);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolbar__brand {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolbar__title {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.toolbar__subtitle {
|
||||
color: var(--color-muted);
|
||||
font-size: 0.74rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.toolbar__scene-name {
|
||||
flex: 1 1 320px;
|
||||
min-width: 220px;
|
||||
max-width: 520px;
|
||||
max-width: 460px;
|
||||
}
|
||||
|
||||
.toolbar__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolbar__group {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 14px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.toolbar__inline-field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 34px;
|
||||
padding: 0 4px 0 2px;
|
||||
}
|
||||
|
||||
.toolbar__inline-input {
|
||||
width: 76px;
|
||||
min-height: 34px;
|
||||
}
|
||||
|
||||
.toolbar__button {
|
||||
padding: 0.65rem 0.9rem;
|
||||
min-height: 34px;
|
||||
padding: 0.48rem 0.72rem;
|
||||
background: var(--color-surface-strong);
|
||||
color: var(--color-text);
|
||||
font-size: 0.84rem;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.toolbar__button:hover:not(:disabled) {
|
||||
@@ -124,6 +160,12 @@ button:disabled {
|
||||
color: var(--color-accent-strong);
|
||||
}
|
||||
|
||||
.toolbar__button--compact {
|
||||
min-height: 32px;
|
||||
padding: 0.4rem 0.62rem;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.toolbar__button--accent {
|
||||
background: var(--color-accent);
|
||||
color: #20140c;
|
||||
@@ -135,9 +177,9 @@ button:disabled {
|
||||
}
|
||||
|
||||
.toolbar__scene-name-input {
|
||||
height: 44px;
|
||||
padding: 0 14px;
|
||||
font-size: 1rem;
|
||||
height: 36px;
|
||||
padding: 0 12px;
|
||||
font-size: 0.92rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
@@ -357,13 +399,13 @@ button:disabled {
|
||||
.outliner-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.outliner-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.outliner-empty {
|
||||
@@ -399,6 +441,19 @@ button:disabled {
|
||||
border-color: rgba(207, 123, 66, 0.55);
|
||||
}
|
||||
|
||||
.outliner-item--compact {
|
||||
gap: 6px;
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.outliner-item__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.outliner-item__title {
|
||||
font-size: 0.88rem;
|
||||
font-weight: 700;
|
||||
@@ -426,11 +481,223 @@ button:disabled {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.outliner-item__editor {
|
||||
.outliner-item--compact .outliner-item__select {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.outliner-item--compact .outliner-item__title {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.outliner-item__rename {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
padding: 2px 6px;
|
||||
margin: -2px -6px;
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
background: rgba(7, 9, 13, 0.22);
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.outliner-item__rename:focus {
|
||||
outline: none;
|
||||
background: rgba(7, 9, 13, 0.38);
|
||||
border-color: rgba(207, 123, 66, 0.45);
|
||||
}
|
||||
|
||||
.outliner-item__delete {
|
||||
flex: 0 0 auto;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.82rem;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.outliner-item__delete:hover:not(:disabled) {
|
||||
color: var(--color-text);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border-color: rgba(255, 255, 255, 0.12);
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.asset-item--action {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.asset-item__content {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.asset-item--action .outliner-item__title {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.asset-item__plus {
|
||||
flex: 0 0 auto;
|
||||
color: var(--color-accent-strong);
|
||||
font-size: 1.1rem;
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.hierarchical-menu__backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 60;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.hierarchical-menu {
|
||||
position: fixed;
|
||||
width: min(320px, calc(100vw - 24px));
|
||||
max-height: min(72vh, 520px);
|
||||
padding: 10px;
|
||||
color: var(--color-text);
|
||||
background: rgba(17, 21, 28, 0.96);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 16px;
|
||||
box-shadow: var(--shadow-panel);
|
||||
backdrop-filter: blur(14px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.hierarchical-menu__title {
|
||||
margin-bottom: 8px;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.16em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.hierarchical-menu__list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.hierarchical-menu__group {
|
||||
overflow: hidden;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.hierarchical-menu__group[open] {
|
||||
border-color: rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
|
||||
.hierarchical-menu__group-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
list-style: none;
|
||||
cursor: pointer;
|
||||
color: var(--color-text);
|
||||
font-size: 0.86rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.hierarchical-menu__group-summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.hierarchical-menu__group-label {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.hierarchical-menu__group-chevron {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
flex: 0 0 auto;
|
||||
border-right: 2px solid currentColor;
|
||||
border-bottom: 2px solid currentColor;
|
||||
transform: rotate(-45deg);
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.hierarchical-menu__group[open] .hierarchical-menu__group-chevron {
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
|
||||
.hierarchical-menu__children {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 0 8px 8px 8px;
|
||||
}
|
||||
|
||||
.hierarchical-menu__action {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
color: var(--color-text);
|
||||
text-align: left;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid transparent;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.hierarchical-menu__action:hover:not(:disabled) {
|
||||
border-color: rgba(255, 255, 255, 0.14);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.hierarchical-menu__action:disabled {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.hierarchical-menu__action-label {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.hierarchical-menu__action-plus {
|
||||
flex: 0 0 auto;
|
||||
color: var(--color-accent-strong);
|
||||
font-size: 1rem;
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.hierarchical-menu__separator {
|
||||
height: 1px;
|
||||
margin: 4px 8px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.material-browser {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -532,7 +799,7 @@ button:disabled {
|
||||
|
||||
.viewport-region {
|
||||
display: grid;
|
||||
grid-template-rows: 42px minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
min-height: 0;
|
||||
background: rgba(20, 24, 31, 0.92);
|
||||
border: 1px solid var(--color-border);
|
||||
@@ -551,44 +818,175 @@ button:disabled {
|
||||
box-shadow: var(--shadow-panel);
|
||||
}
|
||||
|
||||
.viewport-region__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 18px;
|
||||
background: linear-gradient(90deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0) 100%);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
.viewport-region__panels {
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.viewport-region__title {
|
||||
font-size: 0.76rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.16em;
|
||||
.viewport-region__panels--single {
|
||||
display: flex;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.viewport-region__panels--quad {
|
||||
display: grid;
|
||||
grid-template-areas:
|
||||
"topLeft topRight"
|
||||
"bottomLeft bottomRight";
|
||||
grid-template-columns:
|
||||
minmax(0, calc(var(--viewport-quad-split-x, 0.5) * 100%))
|
||||
minmax(0, calc((1 - var(--viewport-quad-split-x, 0.5)) * 100%));
|
||||
grid-template-rows:
|
||||
minmax(0, calc(var(--viewport-quad-split-y, 0.5) * 100%))
|
||||
minmax(0, calc((1 - var(--viewport-quad-split-y, 0.5)) * 100%));
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.viewport-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
position: relative;
|
||||
background: rgba(11, 15, 20, 0.92);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 18px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.viewport-panel--single {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.viewport-panel--quad {
|
||||
min-height: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.viewport-panel--topLeft {
|
||||
grid-area: topLeft;
|
||||
}
|
||||
|
||||
.viewport-panel--topRight {
|
||||
grid-area: topRight;
|
||||
}
|
||||
|
||||
.viewport-panel--bottomLeft {
|
||||
grid-area: bottomLeft;
|
||||
}
|
||||
|
||||
.viewport-panel--bottomRight {
|
||||
grid-area: bottomRight;
|
||||
}
|
||||
|
||||
.viewport-panel__header {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border-bottom: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.viewport-panel--quad .viewport-panel__header {
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
}
|
||||
|
||||
.viewport-panel__meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.viewport-panel__title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.viewport-panel__title {
|
||||
font-size: 0.74rem;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.14em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.viewport-region__caption {
|
||||
color: var(--color-muted);
|
||||
font-size: 0.82rem;
|
||||
.viewport-panel__active-badge {
|
||||
padding: 0.18rem 0.42rem;
|
||||
color: #20140c;
|
||||
background: var(--color-accent-strong);
|
||||
border-radius: 999px;
|
||||
font-size: 0.64rem;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.viewport-panel__controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.viewport-panel__control-group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
padding: 4px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.viewport-panel__button {
|
||||
padding: 0.34rem 0.54rem;
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface-strong);
|
||||
font-size: 0.7rem;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.viewport-panel__button--active {
|
||||
background: var(--color-accent-soft);
|
||||
border-color: rgba(207, 123, 66, 0.55);
|
||||
color: var(--color-accent-strong);
|
||||
}
|
||||
|
||||
.viewport-canvas,
|
||||
.runner-canvas {
|
||||
position: relative;
|
||||
min-height: 420px;
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
background:
|
||||
radial-gradient(circle at top, rgba(130, 154, 188, 0.28) 0%, rgba(130, 154, 188, 0) 38%),
|
||||
linear-gradient(180deg, #55657c 0%, #2c3440 34%, #151920 100%);
|
||||
}
|
||||
|
||||
.viewport-canvas {
|
||||
display: flex;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.viewport-canvas--box-create {
|
||||
.viewport-canvas--create {
|
||||
cursor: copy;
|
||||
}
|
||||
|
||||
.viewport-canvas--authoring {
|
||||
background: #000000;
|
||||
}
|
||||
|
||||
.runner-canvas {
|
||||
flex: 1 1 auto;
|
||||
cursor: grab;
|
||||
@@ -603,34 +1001,119 @@ button:disabled {
|
||||
|
||||
.viewport-canvas__overlay {
|
||||
position: absolute;
|
||||
top: 18px;
|
||||
left: 18px;
|
||||
top: 10px;
|
||||
left: 10px;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-width: min(380px, calc(100% - 36px));
|
||||
padding: 12px 14px;
|
||||
gap: 6px;
|
||||
max-width: calc(100% - 20px);
|
||||
color: #f3e8da;
|
||||
background: rgba(8, 10, 14, 0.58);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 14px;
|
||||
backdrop-filter: blur(10px);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.viewport-canvas__overlay-badges {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.viewport-canvas__overlay-badge {
|
||||
padding: 0.28rem 0.5rem;
|
||||
color: var(--color-accent-strong);
|
||||
background: rgba(8, 10, 14, 0.62);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 999px;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
text-transform: uppercase;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.viewport-canvas__overlay-badge--view {
|
||||
color: #dbe5f4;
|
||||
}
|
||||
|
||||
.viewport-canvas__overlay-text,
|
||||
.viewport-canvas__overlay-preview {
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.45;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
padding: 0.38rem 0.62rem;
|
||||
color: #f3e8da;
|
||||
background: rgba(8, 10, 14, 0.62);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 999px;
|
||||
font-size: 0.76rem;
|
||||
line-height: 1.35;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.viewport-region__splitter {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.viewport-region__splitter::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
background: rgba(255, 255, 255, 0.16);
|
||||
opacity: 0;
|
||||
transition: opacity 120ms ease;
|
||||
}
|
||||
|
||||
.viewport-region__splitter:hover::before,
|
||||
.viewport-region__panels--resizing .viewport-region__splitter::before {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.viewport-region__splitter--vertical {
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: calc(var(--viewport-quad-split-x, 0.5) * 100%);
|
||||
width: 16px;
|
||||
transform: translateX(-50%);
|
||||
cursor: col-resize;
|
||||
}
|
||||
|
||||
.viewport-region__splitter--vertical::before {
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: calc(50% - 1px);
|
||||
width: 2px;
|
||||
}
|
||||
|
||||
.viewport-region__splitter--horizontal {
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(var(--viewport-quad-split-y, 0.5) * 100%);
|
||||
height: 16px;
|
||||
transform: translateY(-50%);
|
||||
cursor: row-resize;
|
||||
}
|
||||
|
||||
.viewport-region__splitter--horizontal::before {
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(50% - 1px);
|
||||
height: 2px;
|
||||
}
|
||||
|
||||
.viewport-region__splitter--center {
|
||||
top: calc(var(--viewport-quad-split-y, 0.5) * 100%);
|
||||
left: calc(var(--viewport-quad-split-x, 0.5) * 100%);
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
transform: translate(-50%, -50%);
|
||||
cursor: move;
|
||||
}
|
||||
|
||||
.viewport-region__splitter--center::before {
|
||||
inset: 5px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.28);
|
||||
border-radius: 999px;
|
||||
background: rgba(8, 10, 14, 0.72);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.viewport-canvas__fallback,
|
||||
@@ -647,7 +1130,7 @@ button:disabled {
|
||||
background: linear-gradient(180deg, rgba(8, 10, 14, 0.12) 0%, rgba(8, 10, 14, 0.58) 100%);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 18px;
|
||||
pointer-events: none;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.viewport-canvas__fallback-title,
|
||||
@@ -724,22 +1207,31 @@ button:disabled {
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
min-height: 44px;
|
||||
padding: 8px 16px;
|
||||
gap: 12px;
|
||||
min-height: 36px;
|
||||
padding: 6px 12px;
|
||||
background: rgba(18, 22, 28, 0.88);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 16px;
|
||||
border-radius: 14px;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.status-bar__item {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.status-bar__item--asset {
|
||||
flex: 1 1 420px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.status-bar__strong {
|
||||
color: var(--color-text);
|
||||
font-weight: 700;
|
||||
@@ -781,7 +1273,7 @@ button:disabled {
|
||||
.toolbar {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
padding: 16px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.workspace {
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
import { CommandHistory } from "../commands/command-history";
|
||||
import type { CommandContext, EditorCommand } from "../commands/command";
|
||||
import type { EditorSelection } from "../core/selection";
|
||||
import {
|
||||
areEditorSelectionsEqual,
|
||||
normalizeSelectionForWhiteboxSelectionMode,
|
||||
type EditorSelection
|
||||
} from "../core/selection";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import { type WhiteboxSelectionMode } from "../core/whitebox-selection-mode";
|
||||
import {
|
||||
areTransformSessionsEqual,
|
||||
cloneTransformSession,
|
||||
createInactiveTransformSession,
|
||||
type TransformAxis,
|
||||
type TransformSessionState
|
||||
} from "../core/transform-session";
|
||||
import { createEmptySceneDocument, type SceneDocument } from "../document/scene-document";
|
||||
import {
|
||||
DEFAULT_SCENE_DRAFT_STORAGE_KEY,
|
||||
@@ -12,11 +24,39 @@ import {
|
||||
saveSceneDocumentDraft
|
||||
} from "../serialization/local-draft-storage";
|
||||
import { parseSceneDocumentJson, serializeSceneDocument } from "../serialization/scene-document-json";
|
||||
import type { ViewportViewMode } from "../viewport-three/viewport-view-modes";
|
||||
import {
|
||||
areViewportToolPreviewsEqual,
|
||||
cloneViewportToolPreview,
|
||||
createDefaultViewportTransientState,
|
||||
isViewportToolPreviewCompatible,
|
||||
type ViewportToolPreview,
|
||||
type ViewportTransientState
|
||||
} from "../viewport-three/viewport-transient-state";
|
||||
import {
|
||||
areViewportPanelCameraStatesEqual,
|
||||
cloneViewportLayoutState,
|
||||
cloneViewportPanelCameraState,
|
||||
createDefaultViewportLayoutState,
|
||||
type ViewportDisplayMode,
|
||||
type ViewportLayoutState,
|
||||
type ViewportLayoutMode,
|
||||
type ViewportPanelId,
|
||||
type ViewportPanelState,
|
||||
type ViewportPanelCameraState,
|
||||
type ViewportQuadSplit
|
||||
} from "../viewport-three/viewport-layout";
|
||||
|
||||
export interface EditorStoreState {
|
||||
document: SceneDocument;
|
||||
selection: EditorSelection;
|
||||
whiteboxSelectionMode: WhiteboxSelectionMode;
|
||||
toolMode: ToolMode;
|
||||
viewportLayoutMode: ViewportLayoutMode;
|
||||
activeViewportPanelId: ViewportPanelId;
|
||||
viewportPanels: Record<ViewportPanelId, ViewportPanelState>;
|
||||
viewportQuadSplit: ViewportQuadSplit;
|
||||
viewportTransientState: ViewportTransientState;
|
||||
canUndo: boolean;
|
||||
canRedo: boolean;
|
||||
lastCommandLabel: string | null;
|
||||
@@ -25,6 +65,7 @@ export interface EditorStoreState {
|
||||
|
||||
interface EditorStoreOptions {
|
||||
initialDocument?: SceneDocument;
|
||||
initialViewportLayoutState?: ViewportLayoutState;
|
||||
storage?: KeyValueStorage | null;
|
||||
storageKey?: string;
|
||||
}
|
||||
@@ -37,7 +78,13 @@ export type EditorDraftLoadResult = LoadSceneDocumentDraftResult;
|
||||
export class EditorStore {
|
||||
private document: SceneDocument;
|
||||
private selection: EditorSelection = { kind: "none" };
|
||||
private whiteboxSelectionMode: WhiteboxSelectionMode = "object";
|
||||
private toolMode: ToolMode = "select";
|
||||
private viewportLayoutMode: ViewportLayoutMode;
|
||||
private activeViewportPanelId: ViewportPanelId;
|
||||
private viewportPanels: Record<ViewportPanelId, ViewportPanelState>;
|
||||
private viewportQuadSplit: ViewportQuadSplit;
|
||||
private viewportTransientState = createDefaultViewportTransientState();
|
||||
private previousEditingToolMode: Exclude<ToolMode, "play"> = "select";
|
||||
private readonly history = new CommandHistory();
|
||||
private readonly listeners = new Set<EditorStoreListener>();
|
||||
@@ -62,7 +109,13 @@ export class EditorStore {
|
||||
};
|
||||
|
||||
constructor(options: EditorStoreOptions = {}) {
|
||||
const initialViewportLayoutState = cloneViewportLayoutState(options.initialViewportLayoutState ?? createDefaultViewportLayoutState());
|
||||
|
||||
this.document = options.initialDocument ?? createEmptySceneDocument();
|
||||
this.viewportLayoutMode = initialViewportLayoutState.layoutMode;
|
||||
this.activeViewportPanelId = initialViewportLayoutState.activePanelId;
|
||||
this.viewportPanels = initialViewportLayoutState.panels;
|
||||
this.viewportQuadSplit = initialViewportLayoutState.viewportQuadSplit;
|
||||
this.storage = options.storage ?? null;
|
||||
this.storageKey = options.storageKey ?? DEFAULT_SCENE_DRAFT_STORAGE_KEY;
|
||||
this.snapshot = this.createSnapshot();
|
||||
@@ -88,9 +141,180 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
this.toolMode = toolMode;
|
||||
|
||||
if (!isViewportToolPreviewCompatible(toolMode, this.viewportTransientState.toolPreview)) {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
toolPreview: createDefaultViewportTransientState().toolPreview
|
||||
};
|
||||
}
|
||||
|
||||
if (toolMode !== "select" && this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportLayoutMode(viewportLayoutMode: ViewportLayoutMode) {
|
||||
if (this.viewportLayoutMode === viewportLayoutMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportLayoutMode = viewportLayoutMode;
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setActiveViewportPanel(panelId: ViewportPanelId) {
|
||||
if (this.activeViewportPanelId === panelId) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.activeViewportPanelId = panelId;
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportPanelViewMode(panelId: ViewportPanelId, viewMode: ViewportViewMode) {
|
||||
if (this.viewportPanels[panelId].viewMode === viewMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportPanels = {
|
||||
...this.viewportPanels,
|
||||
[panelId]: {
|
||||
...this.viewportPanels[panelId],
|
||||
viewMode
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportPanelDisplayMode(panelId: ViewportPanelId, displayMode: ViewportDisplayMode) {
|
||||
if (this.viewportPanels[panelId].displayMode === displayMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportPanels = {
|
||||
...this.viewportPanels,
|
||||
[panelId]: {
|
||||
...this.viewportPanels[panelId],
|
||||
displayMode
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportPanelCameraState(panelId: ViewportPanelId, cameraState: ViewportPanelCameraState) {
|
||||
if (areViewportPanelCameraStatesEqual(this.viewportPanels[panelId].cameraState, cameraState)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportPanels = {
|
||||
...this.viewportPanels,
|
||||
[panelId]: {
|
||||
...this.viewportPanels[panelId],
|
||||
cameraState: cloneViewportPanelCameraState(cameraState)
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportQuadSplit(viewportQuadSplit: ViewportQuadSplit) {
|
||||
if (this.viewportQuadSplit.x === viewportQuadSplit.x && this.viewportQuadSplit.y === viewportQuadSplit.y) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportQuadSplit = {
|
||||
x: viewportQuadSplit.x,
|
||||
y: viewportQuadSplit.y
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportToolPreview(toolPreview: ViewportToolPreview) {
|
||||
const nextToolPreview = cloneViewportToolPreview(toolPreview);
|
||||
|
||||
if (areViewportToolPreviewsEqual(this.viewportTransientState.toolPreview, nextToolPreview)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
toolPreview: nextToolPreview
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
clearViewportToolPreview(sourcePanelId?: ViewportPanelId) {
|
||||
const currentToolPreview = this.viewportTransientState.toolPreview;
|
||||
|
||||
if (currentToolPreview.kind === "none") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (sourcePanelId !== undefined && currentToolPreview.sourcePanelId !== sourcePanelId) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
toolPreview: createDefaultViewportTransientState().toolPreview
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setTransformSession(transformSession: TransformSessionState) {
|
||||
const nextTransformSession = cloneTransformSession(transformSession);
|
||||
|
||||
if (areTransformSessionsEqual(this.viewportTransientState.transformSession, nextTransformSession)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: nextTransformSession
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
clearTransformSession() {
|
||||
if (this.viewportTransientState.transformSession.kind === "none") {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setTransformAxisConstraint(axisConstraint: TransformAxis | null) {
|
||||
if (this.viewportTransientState.transformSession.kind !== "active") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.viewportTransientState.transformSession.axisConstraint === axisConstraint) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: {
|
||||
...(cloneTransformSession(this.viewportTransientState.transformSession) as Extract<TransformSessionState, { kind: "active" }>),
|
||||
axisConstraint
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportViewMode(viewportViewMode: ViewportViewMode) {
|
||||
this.setViewportPanelViewMode(this.activeViewportPanelId, viewportViewMode);
|
||||
}
|
||||
|
||||
enterPlayMode() {
|
||||
if (this.toolMode === "play") {
|
||||
return;
|
||||
@@ -98,6 +322,11 @@ export class EditorStore {
|
||||
|
||||
this.previousEditingToolMode = this.toolMode;
|
||||
this.toolMode = "play";
|
||||
|
||||
if (this.viewportTransientState.toolPreview.kind !== "none") {
|
||||
this.viewportTransientState = createDefaultViewportTransientState();
|
||||
}
|
||||
|
||||
this.emit();
|
||||
}
|
||||
|
||||
@@ -111,20 +340,65 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
setSelection(selection: EditorSelection) {
|
||||
if (this.viewportTransientState.transformSession.kind === "active" && !areEditorSelectionsEqual(this.selection, selection)) {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
|
||||
this.selection = selection;
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setWhiteboxSelectionMode(mode: WhiteboxSelectionMode) {
|
||||
if (this.whiteboxSelectionMode === mode) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
|
||||
this.whiteboxSelectionMode = mode;
|
||||
this.selection = normalizeSelectionForWhiteboxSelectionMode(this.selection, mode);
|
||||
this.emit();
|
||||
}
|
||||
|
||||
executeCommand(command: EditorCommand) {
|
||||
if (this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
|
||||
this.history.execute(command, this.commandContext);
|
||||
this.lastCommandLabel = command.label;
|
||||
this.emit();
|
||||
}
|
||||
|
||||
undo(): boolean {
|
||||
let clearedTransformSession = false;
|
||||
|
||||
if (this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
clearedTransformSession = true;
|
||||
}
|
||||
|
||||
const command = this.history.undo(this.commandContext);
|
||||
|
||||
if (command === null) {
|
||||
if (clearedTransformSession) {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -134,9 +408,23 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
redo(): boolean {
|
||||
let clearedTransformSession = false;
|
||||
|
||||
if (this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
clearedTransformSession = true;
|
||||
}
|
||||
|
||||
const command = this.history.redo(this.commandContext);
|
||||
|
||||
if (command === null) {
|
||||
if (clearedTransformSession) {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -148,8 +436,10 @@ export class EditorStore {
|
||||
replaceDocument(document: SceneDocument, resetHistory = true) {
|
||||
this.document = document;
|
||||
this.selection = { kind: "none" };
|
||||
this.whiteboxSelectionMode = "object";
|
||||
this.toolMode = "select";
|
||||
this.previousEditingToolMode = "select";
|
||||
this.viewportTransientState = createDefaultViewportTransientState();
|
||||
|
||||
if (resetHistory) {
|
||||
this.history.clear();
|
||||
@@ -167,7 +457,7 @@ export class EditorStore {
|
||||
};
|
||||
}
|
||||
|
||||
return saveSceneDocumentDraft(this.storage, this.document, this.storageKey);
|
||||
return saveSceneDocumentDraft(this.storage, this.document, this.createViewportLayoutState(), this.storageKey);
|
||||
}
|
||||
|
||||
loadDraft(): EditorDraftLoadResult {
|
||||
@@ -185,6 +475,12 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
this.replaceDocument(draftResult.document);
|
||||
|
||||
if (draftResult.viewportLayoutState !== null) {
|
||||
this.applyViewportLayoutState(draftResult.viewportLayoutState);
|
||||
this.emit();
|
||||
}
|
||||
|
||||
return draftResult;
|
||||
}
|
||||
|
||||
@@ -206,11 +502,35 @@ export class EditorStore {
|
||||
}
|
||||
}
|
||||
|
||||
private createViewportLayoutState(): ViewportLayoutState {
|
||||
return cloneViewportLayoutState({
|
||||
layoutMode: this.viewportLayoutMode,
|
||||
activePanelId: this.activeViewportPanelId,
|
||||
panels: this.viewportPanels,
|
||||
viewportQuadSplit: this.viewportQuadSplit
|
||||
});
|
||||
}
|
||||
|
||||
private applyViewportLayoutState(viewportLayoutState: ViewportLayoutState) {
|
||||
const nextViewportLayoutState = cloneViewportLayoutState(viewportLayoutState);
|
||||
|
||||
this.viewportLayoutMode = nextViewportLayoutState.layoutMode;
|
||||
this.activeViewportPanelId = nextViewportLayoutState.activePanelId;
|
||||
this.viewportPanels = nextViewportLayoutState.panels;
|
||||
this.viewportQuadSplit = nextViewportLayoutState.viewportQuadSplit;
|
||||
}
|
||||
|
||||
private createSnapshot(): EditorStoreState {
|
||||
return {
|
||||
document: this.document,
|
||||
selection: this.selection,
|
||||
whiteboxSelectionMode: this.whiteboxSelectionMode,
|
||||
toolMode: this.toolMode,
|
||||
viewportLayoutMode: this.viewportLayoutMode,
|
||||
activeViewportPanelId: this.activeViewportPanelId,
|
||||
viewportPanels: this.viewportPanels,
|
||||
viewportQuadSplit: this.viewportQuadSplit,
|
||||
viewportTransientState: this.viewportTransientState,
|
||||
canUndo: this.history.canUndo(),
|
||||
canRedo: this.history.canRedo(),
|
||||
lastCommandLabel: this.lastCommandLabel,
|
||||
|
||||
@@ -8,6 +8,9 @@ import type { ProjectAssetRecord } from "./project-assets";
|
||||
|
||||
const MODEL_PLACEHOLDER_COLOR = 0x89b6ff;
|
||||
const MODEL_SELECTION_COLOR = 0xf7d2aa;
|
||||
const MODEL_PREVIEW_SHELL_OPACITY = 0.5;
|
||||
|
||||
export type ModelInstanceRenderMode = "normal" | "wireframe";
|
||||
|
||||
interface ModelInstanceBounds {
|
||||
center: Vec3;
|
||||
@@ -59,6 +62,46 @@ function createWireframeBox(size: Vec3, color: number, opacity: number): Mesh {
|
||||
);
|
||||
}
|
||||
|
||||
function createWireframeMaterial(material: Material): MeshBasicMaterial {
|
||||
const source = material as Material & {
|
||||
color?: { getHex(): number };
|
||||
opacity?: number;
|
||||
transparent?: boolean;
|
||||
};
|
||||
const opacity = typeof source.opacity === "number" ? source.opacity : 1;
|
||||
|
||||
return new MeshBasicMaterial({
|
||||
color: source.color?.getHex() ?? MODEL_PLACEHOLDER_COLOR,
|
||||
wireframe: true,
|
||||
transparent: source.transparent === true || opacity < 1,
|
||||
opacity,
|
||||
depthWrite: false
|
||||
});
|
||||
}
|
||||
|
||||
function applyWireframeMaterialPresentation(group: Group) {
|
||||
group.traverse((object) => {
|
||||
const maybeMesh = object as Mesh & { isMesh?: boolean };
|
||||
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(maybeMesh.material)) {
|
||||
const originalMaterials = maybeMesh.material;
|
||||
maybeMesh.material = originalMaterials.map((material) => createWireframeMaterial(material));
|
||||
for (const material of originalMaterials) {
|
||||
material.dispose();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const originalMaterial = maybeMesh.material;
|
||||
maybeMesh.material = createWireframeMaterial(originalMaterial);
|
||||
originalMaterial.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
function disposeTexture(texture: Texture, seenTextures: Set<Texture>) {
|
||||
if (seenTextures.has(texture)) {
|
||||
return;
|
||||
@@ -116,7 +159,9 @@ export function createModelInstanceRenderGroup(
|
||||
modelInstance: ModelInstance,
|
||||
asset: ProjectAssetRecord | undefined,
|
||||
loadedAsset: LoadedModelAsset | undefined,
|
||||
selected = false
|
||||
selected = false,
|
||||
previewShellColor?: number,
|
||||
renderMode: ModelInstanceRenderMode = "normal"
|
||||
): Group {
|
||||
const bounds = getLocalModelBounds(asset);
|
||||
const group = new Group();
|
||||
@@ -132,14 +177,27 @@ export function createModelInstanceRenderGroup(
|
||||
group.userData.assetId = modelInstance.assetId;
|
||||
|
||||
if (loadedAsset !== undefined) {
|
||||
group.add(instantiateModelTemplate(loadedAsset.template));
|
||||
const instantiatedModel = instantiateModelTemplate(loadedAsset.template);
|
||||
|
||||
if (renderMode === "wireframe") {
|
||||
applyWireframeMaterialPresentation(instantiatedModel);
|
||||
}
|
||||
|
||||
group.add(instantiatedModel);
|
||||
} else {
|
||||
const placeholder = createWireframeBox(bounds.size, MODEL_PLACEHOLDER_COLOR, 0.28);
|
||||
const placeholder = createWireframeBox(bounds.size, previewShellColor ?? MODEL_PLACEHOLDER_COLOR, previewShellColor === undefined ? 0.28 : MODEL_PREVIEW_SHELL_OPACITY);
|
||||
placeholder.position.set(bounds.center.x, bounds.center.y, bounds.center.z);
|
||||
placeholder.userData.shadowIgnored = true;
|
||||
group.add(placeholder);
|
||||
}
|
||||
|
||||
if (loadedAsset !== undefined && previewShellColor !== undefined) {
|
||||
const previewShell = createWireframeBox(bounds.size, previewShellColor, MODEL_PREVIEW_SHELL_OPACITY);
|
||||
previewShell.position.set(bounds.center.x, bounds.center.y, bounds.center.z);
|
||||
previewShell.userData.shadowIgnored = true;
|
||||
group.add(previewShell);
|
||||
}
|
||||
|
||||
if (selected) {
|
||||
const selectionShell = createWireframeBox(bounds.size, MODEL_SELECTION_COLOR, 0.8);
|
||||
selectionShell.position.set(bounds.center.x, bounds.center.y, bounds.center.z);
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import type { ModelAssetRecord } from "./project-assets";
|
||||
|
||||
export const MODEL_INSTANCE_COLLISION_MODES = ["none", "terrain", "static", "dynamic", "simple"] as const;
|
||||
|
||||
export type ModelInstanceCollisionMode = (typeof MODEL_INSTANCE_COLLISION_MODES)[number];
|
||||
|
||||
export interface ModelInstanceCollisionSettings {
|
||||
mode: ModelInstanceCollisionMode;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
export interface ModelInstance {
|
||||
id: string;
|
||||
@@ -9,6 +19,7 @@ export interface ModelInstance {
|
||||
position: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
scale: Vec3;
|
||||
collision: ModelInstanceCollisionSettings;
|
||||
animationClipName?: string;
|
||||
animationAutoplay?: boolean;
|
||||
}
|
||||
@@ -31,6 +42,11 @@ export const DEFAULT_MODEL_INSTANCE_SCALE: Vec3 = {
|
||||
z: 1
|
||||
};
|
||||
|
||||
export const DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS: ModelInstanceCollisionSettings = {
|
||||
mode: "none",
|
||||
visible: false
|
||||
};
|
||||
|
||||
function cloneVec3(vector: Vec3): Vec3 {
|
||||
return {
|
||||
x: vector.x,
|
||||
@@ -43,6 +59,39 @@ function areVec3Equal(left: Vec3, right: Vec3): boolean {
|
||||
return left.x === right.x && left.y === right.y && left.z === right.z;
|
||||
}
|
||||
|
||||
export function isModelInstanceCollisionMode(value: unknown): value is ModelInstanceCollisionMode {
|
||||
return MODEL_INSTANCE_COLLISION_MODES.includes(value as ModelInstanceCollisionMode);
|
||||
}
|
||||
|
||||
export function createModelInstanceCollisionSettings(
|
||||
overrides: Partial<ModelInstanceCollisionSettings> = {}
|
||||
): ModelInstanceCollisionSettings {
|
||||
const mode = overrides.mode ?? DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS.mode;
|
||||
|
||||
if (!isModelInstanceCollisionMode(mode)) {
|
||||
throw new Error("Model instance collision mode must be a supported value.");
|
||||
}
|
||||
|
||||
const visible = overrides.visible ?? DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS.visible;
|
||||
|
||||
if (typeof visible !== "boolean") {
|
||||
throw new Error("Model instance collision visibility must be a boolean.");
|
||||
}
|
||||
|
||||
return {
|
||||
mode,
|
||||
visible
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneModelInstanceCollisionSettings(settings: ModelInstanceCollisionSettings): ModelInstanceCollisionSettings {
|
||||
return createModelInstanceCollisionSettings(settings);
|
||||
}
|
||||
|
||||
export function areModelInstanceCollisionSettingsEqual(left: ModelInstanceCollisionSettings, right: ModelInstanceCollisionSettings): boolean {
|
||||
return left.mode === right.mode && left.visible === right.visible;
|
||||
}
|
||||
|
||||
export function normalizeModelInstanceName(name: string | null | undefined): string | undefined {
|
||||
if (name === undefined || name === null) {
|
||||
return undefined;
|
||||
@@ -67,11 +116,15 @@ function assertPositiveFiniteVec3(vector: Vec3, label: string) {
|
||||
}
|
||||
|
||||
export function createModelInstance(
|
||||
overrides: Partial<Pick<ModelInstance, "id" | "name" | "position" | "rotationDegrees" | "scale" | "animationClipName" | "animationAutoplay">> & Pick<ModelInstance, "assetId">
|
||||
overrides: Partial<
|
||||
Pick<ModelInstance, "id" | "name" | "position" | "rotationDegrees" | "scale" | "collision" | "animationClipName" | "animationAutoplay">
|
||||
> &
|
||||
Pick<ModelInstance, "assetId">
|
||||
): ModelInstance {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_MODEL_INSTANCE_POSITION);
|
||||
const rotationDegrees = cloneVec3(overrides.rotationDegrees ?? DEFAULT_MODEL_INSTANCE_ROTATION_DEGREES);
|
||||
const scale = cloneVec3(overrides.scale ?? DEFAULT_MODEL_INSTANCE_SCALE);
|
||||
const collision = cloneModelInstanceCollisionSettings(overrides.collision ?? DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS);
|
||||
|
||||
if (overrides.assetId.trim().length === 0) {
|
||||
throw new Error("Model instance assetId must be a non-empty string.");
|
||||
@@ -89,11 +142,32 @@ export function createModelInstance(
|
||||
position,
|
||||
rotationDegrees,
|
||||
scale,
|
||||
collision,
|
||||
animationClipName: overrides.animationClipName,
|
||||
animationAutoplay: overrides.animationAutoplay
|
||||
};
|
||||
}
|
||||
|
||||
export function createModelInstancePlacementPosition(asset: ModelAssetRecord | undefined, anchor: Vec3 | null): Vec3 {
|
||||
const boundingBox = asset?.metadata.boundingBox;
|
||||
|
||||
if (anchor !== null) {
|
||||
const floorOffset = boundingBox === null || boundingBox === undefined ? 0 : -boundingBox.min.y;
|
||||
|
||||
return {
|
||||
x: anchor.x,
|
||||
y: anchor.y + floorOffset,
|
||||
z: anchor.z
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
x: DEFAULT_MODEL_INSTANCE_POSITION.x,
|
||||
y: boundingBox === null || boundingBox === undefined ? DEFAULT_MODEL_INSTANCE_POSITION.y : Math.max(DEFAULT_MODEL_INSTANCE_POSITION.y, -boundingBox.min.y),
|
||||
z: DEFAULT_MODEL_INSTANCE_POSITION.z
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneModelInstance(instance: ModelInstance): ModelInstance {
|
||||
return createModelInstance(instance);
|
||||
}
|
||||
@@ -107,6 +181,7 @@ export function areModelInstancesEqual(left: ModelInstance, right: ModelInstance
|
||||
areVec3Equal(left.position, right.position) &&
|
||||
areVec3Equal(left.rotationDegrees, right.rotationDegrees) &&
|
||||
areVec3Equal(left.scale, right.scale) &&
|
||||
areModelInstanceCollisionSettingsEqual(left.collision, right.collision) &&
|
||||
left.animationClipName === right.animationClipName &&
|
||||
left.animationAutoplay === right.animationAutoplay
|
||||
);
|
||||
@@ -134,4 +209,3 @@ export function getModelInstances(modelInstances: Record<string, ModelInstance>)
|
||||
export function getModelInstanceKindLabel(): string {
|
||||
return "Model Instance";
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { cloneEditorSelection, type EditorSelection } from "../core/selection";
|
||||
import { cloneFaceUvState, type BoxBrush, type BoxFaceId, type BrushFace } from "../document/brushes";
|
||||
import {
|
||||
cloneFaceUvState,
|
||||
type BoxBrush,
|
||||
type BoxEdgeId,
|
||||
type BoxFaceId,
|
||||
type BoxVertexId,
|
||||
type BrushFace
|
||||
} from "../document/brushes";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
|
||||
export function getBoxBrushOrThrow(document: SceneDocument, brushId: string): BoxBrush {
|
||||
@@ -31,6 +38,22 @@ export function setSingleBrushFaceSelection(brushId: string, faceId: BoxFaceId):
|
||||
};
|
||||
}
|
||||
|
||||
export function setSingleBrushEdgeSelection(brushId: string, edgeId: BoxEdgeId): EditorSelection {
|
||||
return {
|
||||
kind: "brushEdge",
|
||||
brushId,
|
||||
edgeId
|
||||
};
|
||||
}
|
||||
|
||||
export function setSingleBrushVertexSelection(brushId: string, vertexId: BoxVertexId): EditorSelection {
|
||||
return {
|
||||
kind: "brushVertex",
|
||||
brushId,
|
||||
vertexId
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneSelectionForCommand(selection: EditorSelection): EditorSelection {
|
||||
return cloneEditorSelection(selection);
|
||||
}
|
||||
|
||||
169
src/commands/commit-transform-session-command.ts
Normal file
169
src/commands/commit-transform-session-command.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
import { createMoveBoxBrushCommand } from "./move-box-brush-command";
|
||||
import { createResizeBoxBrushCommand } from "./resize-box-brush-command";
|
||||
import { createRotateBoxBrushCommand } from "./rotate-box-brush-command";
|
||||
import { createUpsertEntityCommand } from "./upsert-entity-command";
|
||||
import { createUpsertModelInstanceCommand } from "./upsert-model-instance-command";
|
||||
import type { EditorCommand } from "./command";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
import { createModelInstance } from "../assets/model-instances";
|
||||
import {
|
||||
createInteractableEntity,
|
||||
createPlayerStartEntity,
|
||||
createPointLightEntity,
|
||||
createSoundEmitterEntity,
|
||||
createSpotLightEntity,
|
||||
createTeleportTargetEntity,
|
||||
createTriggerVolumeEntity
|
||||
} from "../entities/entity-instances";
|
||||
import {
|
||||
getTransformOperationLabel,
|
||||
type ActiveTransformSession
|
||||
} from "../core/transform-session";
|
||||
|
||||
function createTransformCommandLabel(session: ActiveTransformSession): string {
|
||||
return `${getTransformOperationLabel(session.operation)} ${
|
||||
session.target.kind === "brush"
|
||||
? "whitebox box"
|
||||
: session.target.kind === "entity"
|
||||
? session.target.entityKind === "playerStart"
|
||||
? "player start"
|
||||
: session.target.entityKind === "pointLight"
|
||||
? "point light"
|
||||
: session.target.entityKind === "spotLight"
|
||||
? "spot light"
|
||||
: session.target.entityKind === "soundEmitter"
|
||||
? "sound emitter"
|
||||
: session.target.entityKind === "triggerVolume"
|
||||
? "trigger volume"
|
||||
: session.target.entityKind === "teleportTarget"
|
||||
? "teleport target"
|
||||
: "interactable"
|
||||
: "model instance"
|
||||
}`;
|
||||
}
|
||||
|
||||
export function createCommitTransformSessionCommand(document: SceneDocument, session: ActiveTransformSession): EditorCommand {
|
||||
switch (session.target.kind) {
|
||||
case "brush":
|
||||
if (session.preview.kind !== "brush") {
|
||||
throw new Error("Brush transform preview is invalid.");
|
||||
}
|
||||
|
||||
switch (session.operation) {
|
||||
case "translate":
|
||||
return createMoveBoxBrushCommand({
|
||||
brushId: session.target.brushId,
|
||||
center: session.preview.center,
|
||||
snapToGrid: false,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "rotate":
|
||||
return createRotateBoxBrushCommand({
|
||||
brushId: session.target.brushId,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "scale":
|
||||
return createResizeBoxBrushCommand({
|
||||
brushId: session.target.brushId,
|
||||
size: session.preview.size,
|
||||
snapToGrid: false,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
}
|
||||
case "modelInstance": {
|
||||
if (session.preview.kind !== "modelInstance") {
|
||||
throw new Error("Model instance transform preview is invalid.");
|
||||
}
|
||||
|
||||
const modelInstance = document.modelInstances[session.target.modelInstanceId];
|
||||
|
||||
if (modelInstance === undefined) {
|
||||
throw new Error(`Model instance ${session.target.modelInstanceId} does not exist.`);
|
||||
}
|
||||
|
||||
return createUpsertModelInstanceCommand({
|
||||
modelInstance: createModelInstance({
|
||||
...modelInstance,
|
||||
position: session.preview.position,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
scale: session.preview.scale
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
}
|
||||
case "entity": {
|
||||
if (session.preview.kind !== "entity") {
|
||||
throw new Error("Entity transform preview is invalid.");
|
||||
}
|
||||
|
||||
const entity = document.entities[session.target.entityId];
|
||||
|
||||
if (entity === undefined) {
|
||||
throw new Error(`Entity ${session.target.entityId} does not exist.`);
|
||||
}
|
||||
|
||||
switch (entity.kind) {
|
||||
case "pointLight":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createPointLightEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "spotLight":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createSpotLightEntity({
|
||||
...entity,
|
||||
position: session.preview.position,
|
||||
direction: session.preview.rotation.kind === "direction" ? session.preview.rotation.direction : entity.direction
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "playerStart":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createPlayerStartEntity({
|
||||
...entity,
|
||||
position: session.preview.position,
|
||||
yawDegrees: session.preview.rotation.kind === "yaw" ? session.preview.rotation.yawDegrees : entity.yawDegrees
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "soundEmitter":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createSoundEmitterEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "triggerVolume":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createTriggerVolumeEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "teleportTarget":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createTeleportTargetEntity({
|
||||
...entity,
|
||||
position: session.preview.position,
|
||||
yawDegrees: session.preview.rotation.kind === "yaw" ? session.preview.rotation.yawDegrees : entity.yawDegrees
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "interactable":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createInteractableEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,13 +12,21 @@ import type { EditorCommand } from "./command";
|
||||
interface CreateBoxBrushCommandOptions {
|
||||
center?: Vec3;
|
||||
size?: Vec3;
|
||||
snapToGrid?: boolean;
|
||||
gridSize?: number;
|
||||
}
|
||||
|
||||
export function createCreateBoxBrushCommand(options: CreateBoxBrushCommandOptions = {}): EditorCommand {
|
||||
const snapToGrid = options.snapToGrid ?? true;
|
||||
const brush = createBoxBrush({
|
||||
center: snapVec3ToGrid(options.center ?? DEFAULT_BOX_BRUSH_CENTER, options.gridSize ?? DEFAULT_GRID_SIZE),
|
||||
size: snapPositiveSizeToGrid(options.size ?? DEFAULT_BOX_BRUSH_SIZE, options.gridSize ?? DEFAULT_GRID_SIZE)
|
||||
center:
|
||||
snapToGrid === false
|
||||
? options.center ?? DEFAULT_BOX_BRUSH_CENTER
|
||||
: snapVec3ToGrid(options.center ?? DEFAULT_BOX_BRUSH_CENTER, options.gridSize ?? DEFAULT_GRID_SIZE),
|
||||
size:
|
||||
snapToGrid === false
|
||||
? options.size ?? DEFAULT_BOX_BRUSH_SIZE
|
||||
: snapPositiveSizeToGrid(options.size ?? DEFAULT_BOX_BRUSH_SIZE, options.gridSize ?? DEFAULT_GRID_SIZE)
|
||||
});
|
||||
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
|
||||
79
src/commands/delete-box-brush-command.ts
Normal file
79
src/commands/delete-box-brush-command.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import type { EditorSelection } from "../core/selection";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import { cloneBoxBrush, type BoxBrush } from "../document/brushes";
|
||||
|
||||
import { cloneSelectionForCommand, removeBrush } from "./brush-command-helpers";
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
function selectionIncludesBrush(selection: EditorSelection, brushId: string): boolean {
|
||||
return (
|
||||
(selection.kind === "brushes" && selection.ids.includes(brushId)) ||
|
||||
((selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") &&
|
||||
selection.brushId === brushId)
|
||||
);
|
||||
}
|
||||
|
||||
export function createDeleteBoxBrushCommand(brushId: string): EditorCommand {
|
||||
let previousBrush: BoxBrush | null = null;
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
let previousToolMode: ToolMode | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Delete box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentBrush = currentDocument.brushes[brushId];
|
||||
|
||||
if (currentBrush === undefined) {
|
||||
throw new Error(`Box brush ${brushId} does not exist.`);
|
||||
}
|
||||
|
||||
if (previousBrush === null) {
|
||||
previousBrush = cloneBoxBrush(currentBrush);
|
||||
}
|
||||
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
|
||||
context.setDocument(removeBrush(currentDocument, brushId));
|
||||
|
||||
if (selectionIncludesBrush(context.getSelection(), brushId)) {
|
||||
context.setSelection({
|
||||
kind: "none"
|
||||
});
|
||||
}
|
||||
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousBrush === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDocument = context.getDocument();
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
brushes: {
|
||||
...currentDocument.brushes,
|
||||
[previousBrush.id]: cloneBoxBrush(previousBrush)
|
||||
}
|
||||
});
|
||||
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
82
src/commands/delete-entity-command.ts
Normal file
82
src/commands/delete-entity-command.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEditorSelection, type EditorSelection } from "../core/selection";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import { cloneEntityInstance, type EntityInstance } from "../entities/entity-instances";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
function selectionIncludesEntity(selection: EditorSelection, entityId: string): boolean {
|
||||
return selection.kind === "entities" && selection.ids.includes(entityId);
|
||||
}
|
||||
|
||||
export function createDeleteEntityCommand(entityId: string): EditorCommand {
|
||||
let previousEntity: EntityInstance | null = null;
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
let previousToolMode: ToolMode | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Delete entity",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentEntity = currentDocument.entities[entityId];
|
||||
|
||||
if (currentEntity === undefined) {
|
||||
throw new Error(`Entity ${entityId} does not exist.`);
|
||||
}
|
||||
|
||||
if (previousEntity === null) {
|
||||
previousEntity = cloneEntityInstance(currentEntity);
|
||||
}
|
||||
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
|
||||
const nextEntities = {
|
||||
...currentDocument.entities
|
||||
};
|
||||
delete nextEntities[entityId];
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: nextEntities
|
||||
});
|
||||
|
||||
if (selectionIncludesEntity(context.getSelection(), entityId)) {
|
||||
context.setSelection({
|
||||
kind: "none"
|
||||
});
|
||||
}
|
||||
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousEntity === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDocument = context.getDocument();
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
[previousEntity.id]: cloneEntityInstance(previousEntity)
|
||||
}
|
||||
});
|
||||
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
82
src/commands/delete-model-instance-command.ts
Normal file
82
src/commands/delete-model-instance-command.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEditorSelection, type EditorSelection } from "../core/selection";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import { cloneModelInstance, type ModelInstance } from "../assets/model-instances";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
function selectionIncludesModelInstance(selection: EditorSelection, modelInstanceId: string): boolean {
|
||||
return selection.kind === "modelInstances" && selection.ids.includes(modelInstanceId);
|
||||
}
|
||||
|
||||
export function createDeleteModelInstanceCommand(modelInstanceId: string): EditorCommand {
|
||||
let previousModelInstance: ModelInstance | null = null;
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
let previousToolMode: ToolMode | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Delete model instance",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentModelInstance = currentDocument.modelInstances[modelInstanceId];
|
||||
|
||||
if (currentModelInstance === undefined) {
|
||||
throw new Error(`Model instance ${modelInstanceId} does not exist.`);
|
||||
}
|
||||
|
||||
if (previousModelInstance === null) {
|
||||
previousModelInstance = cloneModelInstance(currentModelInstance);
|
||||
}
|
||||
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
|
||||
const nextModelInstances = {
|
||||
...currentDocument.modelInstances
|
||||
};
|
||||
delete nextModelInstances[modelInstanceId];
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: nextModelInstances
|
||||
});
|
||||
|
||||
if (selectionIncludesModelInstance(context.getSelection(), modelInstanceId)) {
|
||||
context.setSelection({
|
||||
kind: "none"
|
||||
});
|
||||
}
|
||||
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousModelInstance === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDocument = context.getDocument();
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
[previousModelInstance.id]: cloneModelInstance(previousModelInstance)
|
||||
}
|
||||
});
|
||||
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -11,11 +11,14 @@ import type { EditorCommand } from "./command";
|
||||
interface MoveBoxBrushCommandOptions {
|
||||
brushId: string;
|
||||
center: Vec3;
|
||||
snapToGrid?: boolean;
|
||||
gridSize?: number;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function createMoveBoxBrushCommand(options: MoveBoxBrushCommandOptions): EditorCommand {
|
||||
const snappedCenter = snapVec3ToGrid(options.center, options.gridSize ?? DEFAULT_GRID_SIZE);
|
||||
const resolvedCenter =
|
||||
options.snapToGrid === false ? options.center : snapVec3ToGrid(options.center, options.gridSize ?? DEFAULT_GRID_SIZE);
|
||||
|
||||
let previousCenter: Vec3 | null = null;
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
@@ -23,7 +26,7 @@ export function createMoveBoxBrushCommand(options: MoveBoxBrushCommandOptions):
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Move box brush",
|
||||
label: options.label ?? "Move box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
@@ -46,7 +49,7 @@ export function createMoveBoxBrushCommand(options: MoveBoxBrushCommandOptions):
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
center: {
|
||||
...snappedCenter
|
||||
...resolvedCenter
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
@@ -11,11 +11,14 @@ import type { EditorCommand } from "./command";
|
||||
interface ResizeBoxBrushCommandOptions {
|
||||
brushId: string;
|
||||
size: Vec3;
|
||||
snapToGrid?: boolean;
|
||||
gridSize?: number;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOptions): EditorCommand {
|
||||
const snappedSize = snapPositiveSizeToGrid(options.size, options.gridSize ?? DEFAULT_GRID_SIZE);
|
||||
const resolvedSize =
|
||||
options.snapToGrid === false ? options.size : snapPositiveSizeToGrid(options.size, options.gridSize ?? DEFAULT_GRID_SIZE);
|
||||
|
||||
let previousSize: Vec3 | null = null;
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
@@ -23,7 +26,7 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Resize box brush",
|
||||
label: options.label ?? "Resize box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
@@ -46,7 +49,7 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
size: {
|
||||
...snappedSize
|
||||
...resolvedSize
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
79
src/commands/rotate-box-brush-command.ts
Normal file
79
src/commands/rotate-box-brush-command.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import type { EditorSelection } from "../core/selection";
|
||||
import type { Vec3 } from "../core/vector";
|
||||
|
||||
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushSelection } from "./brush-command-helpers";
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
interface RotateBoxBrushCommandOptions {
|
||||
brushId: string;
|
||||
rotationDegrees: Vec3;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function createRotateBoxBrushCommand(options: RotateBoxBrushCommandOptions): EditorCommand {
|
||||
let previousRotationDegrees: Vec3 | null = null;
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
let previousToolMode: ToolMode | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Rotate box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
|
||||
if (previousRotationDegrees === null) {
|
||||
previousRotationDegrees = {
|
||||
...brush.rotationDegrees
|
||||
};
|
||||
}
|
||||
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
|
||||
context.setDocument(
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
rotationDegrees: {
|
||||
...options.rotationDegrees
|
||||
}
|
||||
})
|
||||
);
|
||||
context.setSelection(setSingleBrushSelection(options.brushId));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousRotationDegrees === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
|
||||
context.setDocument(
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
rotationDegrees: {
|
||||
...previousRotationDegrees
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
61
src/commands/set-entity-name-command.ts
Normal file
61
src/commands/set-entity-name-command.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEntityInstance, normalizeEntityName } from "../entities/entity-instances";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
interface SetEntityNameCommandOptions {
|
||||
entityId: string;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
export function createSetEntityNameCommand(options: SetEntityNameCommandOptions): EditorCommand {
|
||||
const normalizedName = normalizeEntityName(options.name);
|
||||
let previousName: string | undefined;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: normalizedName === undefined ? "Clear entity name" : `Rename entity to ${normalizedName}`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const entity = currentDocument.entities[options.entityId];
|
||||
|
||||
if (entity === undefined) {
|
||||
throw new Error(`Entity ${options.entityId} does not exist.`);
|
||||
}
|
||||
|
||||
if (previousName === undefined) {
|
||||
previousName = entity.name;
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
[entity.id]: cloneEntityInstance({
|
||||
...entity,
|
||||
name: normalizedName
|
||||
})
|
||||
}
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const entity = currentDocument.entities[options.entityId];
|
||||
|
||||
if (entity === undefined) {
|
||||
throw new Error(`Entity ${options.entityId} does not exist.`);
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
[entity.id]: cloneEntityInstance({
|
||||
...entity,
|
||||
name: previousName
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
61
src/commands/set-model-instance-name-command.ts
Normal file
61
src/commands/set-model-instance-name-command.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneModelInstance, normalizeModelInstanceName } from "../assets/model-instances";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
interface SetModelInstanceNameCommandOptions {
|
||||
modelInstanceId: string;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
export function createSetModelInstanceNameCommand(options: SetModelInstanceNameCommandOptions): EditorCommand {
|
||||
const normalizedName = normalizeModelInstanceName(options.name);
|
||||
let previousName: string | undefined;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: normalizedName === undefined ? "Clear model instance name" : `Rename model instance to ${normalizedName}`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const modelInstance = currentDocument.modelInstances[options.modelInstanceId];
|
||||
|
||||
if (modelInstance === undefined) {
|
||||
throw new Error(`Model instance ${options.modelInstanceId} does not exist.`);
|
||||
}
|
||||
|
||||
if (previousName === undefined) {
|
||||
previousName = modelInstance.name;
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
[modelInstance.id]: cloneModelInstance({
|
||||
...modelInstance,
|
||||
name: normalizedName
|
||||
})
|
||||
}
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const modelInstance = currentDocument.modelInstances[options.modelInstanceId];
|
||||
|
||||
if (modelInstance === undefined) {
|
||||
throw new Error(`Model instance ${options.modelInstanceId} does not exist.`);
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
[modelInstance.id]: cloneModelInstance({
|
||||
...modelInstance,
|
||||
name: previousName
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import type { BoxFaceId } from "../document/brushes";
|
||||
import type { WhiteboxSelectionMode } from "./whitebox-selection-mode";
|
||||
import type { BoxEdgeId, BoxFaceId, BoxVertexId } from "../document/brushes";
|
||||
|
||||
export type EditorSelection =
|
||||
| { kind: "none" }
|
||||
| { kind: "brushes"; ids: string[] }
|
||||
| { kind: "brushFace"; brushId: string; faceId: BoxFaceId }
|
||||
| { kind: "brushEdge"; brushId: string; edgeId: BoxEdgeId }
|
||||
| { kind: "brushVertex"; brushId: string; vertexId: BoxVertexId }
|
||||
| { kind: "entities"; ids: string[] }
|
||||
| { kind: "modelInstances"; ids: string[] };
|
||||
|
||||
@@ -22,14 +25,51 @@ export function cloneEditorSelection(selection: EditorSelection): EditorSelectio
|
||||
};
|
||||
}
|
||||
|
||||
if (selection.kind === "brushEdge") {
|
||||
return {
|
||||
kind: "brushEdge",
|
||||
brushId: selection.brushId,
|
||||
edgeId: selection.edgeId
|
||||
};
|
||||
}
|
||||
|
||||
if (selection.kind === "brushVertex") {
|
||||
return {
|
||||
kind: "brushVertex",
|
||||
brushId: selection.brushId,
|
||||
vertexId: selection.vertexId
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: selection.kind,
|
||||
ids: [...selection.ids]
|
||||
};
|
||||
}
|
||||
|
||||
export function areEditorSelectionsEqual(left: EditorSelection, right: EditorSelection): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (left.kind) {
|
||||
case "none":
|
||||
return true;
|
||||
case "brushFace":
|
||||
return right.kind === "brushFace" && left.brushId === right.brushId && left.faceId === right.faceId;
|
||||
case "brushEdge":
|
||||
return right.kind === "brushEdge" && left.brushId === right.brushId && left.edgeId === right.edgeId;
|
||||
case "brushVertex":
|
||||
return right.kind === "brushVertex" && left.brushId === right.brushId && left.vertexId === right.vertexId;
|
||||
case "brushes":
|
||||
case "entities":
|
||||
case "modelInstances":
|
||||
return right.kind === left.kind && left.ids.length === right.ids.length && left.ids.every((id, index) => id === right.ids[index]);
|
||||
}
|
||||
}
|
||||
|
||||
export function getSingleSelectedBrushId(selection: EditorSelection): string | null {
|
||||
if (selection.kind === "brushFace") {
|
||||
if (selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") {
|
||||
return selection.brushId;
|
||||
}
|
||||
|
||||
@@ -48,6 +88,22 @@ export function getSelectedBrushFaceId(selection: EditorSelection): BoxFaceId |
|
||||
return selection.faceId;
|
||||
}
|
||||
|
||||
export function getSelectedBrushEdgeId(selection: EditorSelection): BoxEdgeId | null {
|
||||
if (selection.kind !== "brushEdge") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return selection.edgeId;
|
||||
}
|
||||
|
||||
export function getSelectedBrushVertexId(selection: EditorSelection): BoxVertexId | null {
|
||||
if (selection.kind !== "brushVertex") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return selection.vertexId;
|
||||
}
|
||||
|
||||
export function getSingleSelectedEntityId(selection: EditorSelection): string | null {
|
||||
if (selection.kind !== "entities" || selection.ids.length !== 1) {
|
||||
return null;
|
||||
@@ -67,7 +123,8 @@ export function getSingleSelectedModelInstanceId(selection: EditorSelection): st
|
||||
export function isBrushSelected(selection: EditorSelection, brushId: string): boolean {
|
||||
return (
|
||||
(selection.kind === "brushes" && selection.ids.includes(brushId)) ||
|
||||
(selection.kind === "brushFace" && selection.brushId === brushId)
|
||||
((selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") &&
|
||||
selection.brushId === brushId)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -75,6 +132,42 @@ export function isBrushFaceSelected(selection: EditorSelection, brushId: string,
|
||||
return selection.kind === "brushFace" && selection.brushId === brushId && selection.faceId === faceId;
|
||||
}
|
||||
|
||||
export function isBrushEdgeSelected(selection: EditorSelection, brushId: string, edgeId: BoxEdgeId): boolean {
|
||||
return selection.kind === "brushEdge" && selection.brushId === brushId && selection.edgeId === edgeId;
|
||||
}
|
||||
|
||||
export function isBrushVertexSelected(selection: EditorSelection, brushId: string, vertexId: BoxVertexId): boolean {
|
||||
return selection.kind === "brushVertex" && selection.brushId === brushId && selection.vertexId === vertexId;
|
||||
}
|
||||
|
||||
export function isModelInstanceSelected(selection: EditorSelection, modelInstanceId: string): boolean {
|
||||
return selection.kind === "modelInstances" && selection.ids.includes(modelInstanceId);
|
||||
}
|
||||
|
||||
export function normalizeSelectionForWhiteboxSelectionMode(selection: EditorSelection, mode: WhiteboxSelectionMode): EditorSelection {
|
||||
switch (selection.kind) {
|
||||
case "brushFace":
|
||||
return mode === "face"
|
||||
? selection
|
||||
: {
|
||||
kind: "brushes",
|
||||
ids: [selection.brushId]
|
||||
};
|
||||
case "brushEdge":
|
||||
return mode === "edge"
|
||||
? selection
|
||||
: {
|
||||
kind: "brushes",
|
||||
ids: [selection.brushId]
|
||||
};
|
||||
case "brushVertex":
|
||||
return mode === "vertex"
|
||||
? selection
|
||||
: {
|
||||
kind: "brushes",
|
||||
ids: [selection.brushId]
|
||||
};
|
||||
default:
|
||||
return selection;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
export type ToolMode = "select" | "box-create" | "play";
|
||||
export type ToolMode = "select" | "create" | "play";
|
||||
|
||||
585
src/core/transform-session.ts
Normal file
585
src/core/transform-session.ts
Normal file
@@ -0,0 +1,585 @@
|
||||
import { createOpaqueId } from "./ids";
|
||||
import type { EditorSelection } from "./selection";
|
||||
import type { WhiteboxSelectionMode } from "./whitebox-selection-mode";
|
||||
import type { Vec3 } from "./vector";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
import {
|
||||
cloneEntityInstance,
|
||||
getEntityKindLabel,
|
||||
type EntityInstance,
|
||||
type EntityKind
|
||||
} from "../entities/entity-instances";
|
||||
import { cloneModelInstance, getModelInstanceKindLabel } from "../assets/model-instances";
|
||||
import type { ViewportPanelId } from "../viewport-three/viewport-layout";
|
||||
|
||||
export type TransformOperation = "translate" | "rotate" | "scale";
|
||||
export type TransformAxis = "x" | "y" | "z";
|
||||
export type TransformSessionSource = "keyboard" | "gizmo" | "toolbar";
|
||||
|
||||
export interface YawEntityRotationState {
|
||||
kind: "yaw";
|
||||
yawDegrees: number;
|
||||
}
|
||||
|
||||
export interface DirectionEntityRotationState {
|
||||
kind: "direction";
|
||||
direction: Vec3;
|
||||
}
|
||||
|
||||
export interface NoEntityRotationState {
|
||||
kind: "none";
|
||||
}
|
||||
|
||||
export type EntityTransformRotationState = NoEntityRotationState | YawEntityRotationState | DirectionEntityRotationState;
|
||||
|
||||
export interface BrushTransformTarget {
|
||||
kind: "brush";
|
||||
brushId: string;
|
||||
initialCenter: Vec3;
|
||||
initialRotationDegrees: Vec3;
|
||||
initialSize: Vec3;
|
||||
}
|
||||
|
||||
export interface ModelInstanceTransformTarget {
|
||||
kind: "modelInstance";
|
||||
modelInstanceId: string;
|
||||
assetId: string;
|
||||
initialPosition: Vec3;
|
||||
initialRotationDegrees: Vec3;
|
||||
initialScale: Vec3;
|
||||
}
|
||||
|
||||
export interface EntityTransformTarget {
|
||||
kind: "entity";
|
||||
entityId: string;
|
||||
entityKind: EntityKind;
|
||||
initialPosition: Vec3;
|
||||
initialRotation: EntityTransformRotationState;
|
||||
}
|
||||
|
||||
export type TransformTarget = BrushTransformTarget | ModelInstanceTransformTarget | EntityTransformTarget;
|
||||
|
||||
export interface BrushTransformPreview {
|
||||
kind: "brush";
|
||||
center: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
size: Vec3;
|
||||
}
|
||||
|
||||
export interface ModelInstanceTransformPreview {
|
||||
kind: "modelInstance";
|
||||
position: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
scale: Vec3;
|
||||
}
|
||||
|
||||
export interface EntityTransformPreview {
|
||||
kind: "entity";
|
||||
position: Vec3;
|
||||
rotation: EntityTransformRotationState;
|
||||
}
|
||||
|
||||
export type TransformPreview = BrushTransformPreview | ModelInstanceTransformPreview | EntityTransformPreview;
|
||||
|
||||
export interface ActiveTransformSession {
|
||||
kind: "active";
|
||||
id: string;
|
||||
source: TransformSessionSource;
|
||||
sourcePanelId: ViewportPanelId;
|
||||
operation: TransformOperation;
|
||||
axisConstraint: TransformAxis | null;
|
||||
target: TransformTarget;
|
||||
preview: TransformPreview;
|
||||
}
|
||||
|
||||
export type TransformSessionState = ActiveTransformSession | { kind: "none" };
|
||||
|
||||
export interface TransformTargetResolution {
|
||||
target: TransformTarget | null;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
function cloneVec3(vector: Vec3): Vec3 {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
|
||||
function areVec3Equal(left: Vec3, right: Vec3): boolean {
|
||||
return left.x === right.x && left.y === right.y && left.z === right.z;
|
||||
}
|
||||
|
||||
function cloneEntityTransformRotationState(rotation: EntityTransformRotationState): EntityTransformRotationState {
|
||||
switch (rotation.kind) {
|
||||
case "none":
|
||||
return {
|
||||
kind: "none"
|
||||
};
|
||||
case "yaw":
|
||||
return {
|
||||
kind: "yaw",
|
||||
yawDegrees: rotation.yawDegrees
|
||||
};
|
||||
case "direction":
|
||||
return {
|
||||
kind: "direction",
|
||||
direction: cloneVec3(rotation.direction)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function areEntityTransformRotationsEqual(left: EntityTransformRotationState, right: EntityTransformRotationState): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (left.kind) {
|
||||
case "none":
|
||||
return true;
|
||||
case "yaw":
|
||||
return right.kind === "yaw" && left.yawDegrees === right.yawDegrees;
|
||||
case "direction":
|
||||
return right.kind === "direction" && areVec3Equal(left.direction, right.direction);
|
||||
}
|
||||
}
|
||||
|
||||
export function createInactiveTransformSession(): TransformSessionState {
|
||||
return {
|
||||
kind: "none"
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneTransformTarget(target: TransformTarget): TransformTarget {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
return {
|
||||
kind: "brush",
|
||||
brushId: target.brushId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
kind: "modelInstance",
|
||||
modelInstanceId: target.modelInstanceId,
|
||||
assetId: target.assetId,
|
||||
initialPosition: cloneVec3(target.initialPosition),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialScale: cloneVec3(target.initialScale)
|
||||
};
|
||||
case "entity":
|
||||
return {
|
||||
kind: "entity",
|
||||
entityId: target.entityId,
|
||||
entityKind: target.entityKind,
|
||||
initialPosition: cloneVec3(target.initialPosition),
|
||||
initialRotation: cloneEntityTransformRotationState(target.initialRotation)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function cloneTransformPreview(preview: TransformPreview): TransformPreview {
|
||||
switch (preview.kind) {
|
||||
case "brush":
|
||||
return {
|
||||
kind: "brush",
|
||||
center: cloneVec3(preview.center),
|
||||
rotationDegrees: cloneVec3(preview.rotationDegrees),
|
||||
size: cloneVec3(preview.size)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
kind: "modelInstance",
|
||||
position: cloneVec3(preview.position),
|
||||
rotationDegrees: cloneVec3(preview.rotationDegrees),
|
||||
scale: cloneVec3(preview.scale)
|
||||
};
|
||||
case "entity":
|
||||
return {
|
||||
kind: "entity",
|
||||
position: cloneVec3(preview.position),
|
||||
rotation: cloneEntityTransformRotationState(preview.rotation)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function cloneTransformSession(session: TransformSessionState): TransformSessionState {
|
||||
if (session.kind === "none") {
|
||||
return session;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "active",
|
||||
id: session.id,
|
||||
source: session.source,
|
||||
sourcePanelId: session.sourcePanelId,
|
||||
operation: session.operation,
|
||||
axisConstraint: session.axisConstraint,
|
||||
target: cloneTransformTarget(session.target),
|
||||
preview: cloneTransformPreview(session.preview)
|
||||
};
|
||||
}
|
||||
|
||||
export function areTransformSessionsEqual(left: TransformSessionState, right: TransformSessionState): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.kind === "none" || right.kind === "none") {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
left.id === right.id &&
|
||||
left.source === right.source &&
|
||||
left.sourcePanelId === right.sourcePanelId &&
|
||||
left.operation === right.operation &&
|
||||
left.axisConstraint === right.axisConstraint &&
|
||||
areTransformTargetsEqual(left.target, right.target) &&
|
||||
areTransformPreviewsEqual(left.preview, right.preview)
|
||||
);
|
||||
}
|
||||
|
||||
function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (left.kind) {
|
||||
case "brush":
|
||||
return (
|
||||
right.kind === "brush" &&
|
||||
left.brushId === right.brushId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize)
|
||||
);
|
||||
case "modelInstance":
|
||||
return (
|
||||
right.kind === "modelInstance" &&
|
||||
left.modelInstanceId === right.modelInstanceId &&
|
||||
left.assetId === right.assetId &&
|
||||
areVec3Equal(left.initialPosition, right.initialPosition) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(left.initialScale, right.initialScale)
|
||||
);
|
||||
case "entity":
|
||||
return (
|
||||
right.kind === "entity" &&
|
||||
left.entityId === right.entityId &&
|
||||
left.entityKind === right.entityKind &&
|
||||
areVec3Equal(left.initialPosition, right.initialPosition) &&
|
||||
areEntityTransformRotationsEqual(left.initialRotation, right.initialRotation)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function areTransformPreviewsEqual(left: TransformPreview, right: TransformPreview): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (left.kind) {
|
||||
case "brush":
|
||||
return (
|
||||
right.kind === "brush" &&
|
||||
areVec3Equal(left.center, right.center) &&
|
||||
areVec3Equal(left.rotationDegrees, right.rotationDegrees) &&
|
||||
areVec3Equal(left.size, right.size)
|
||||
);
|
||||
case "modelInstance":
|
||||
return (
|
||||
right.kind === "modelInstance" &&
|
||||
areVec3Equal(left.position, right.position) &&
|
||||
areVec3Equal(left.rotationDegrees, right.rotationDegrees) &&
|
||||
areVec3Equal(left.scale, right.scale)
|
||||
);
|
||||
case "entity":
|
||||
return right.kind === "entity" && areVec3Equal(left.position, right.position) && areEntityTransformRotationsEqual(left.rotation, right.rotation);
|
||||
}
|
||||
}
|
||||
|
||||
export function createTransformSession(options: {
|
||||
source: TransformSessionSource;
|
||||
sourcePanelId: ViewportPanelId;
|
||||
operation: TransformOperation;
|
||||
axisConstraint?: TransformAxis | null;
|
||||
target: TransformTarget;
|
||||
}): ActiveTransformSession {
|
||||
return {
|
||||
kind: "active",
|
||||
id: createOpaqueId("transform-session"),
|
||||
source: options.source,
|
||||
sourcePanelId: options.sourcePanelId,
|
||||
operation: options.operation,
|
||||
axisConstraint: options.axisConstraint ?? null,
|
||||
target: cloneTransformTarget(options.target),
|
||||
preview: createTransformPreviewFromTarget(options.target)
|
||||
};
|
||||
}
|
||||
|
||||
export function createTransformPreviewFromTarget(target: TransformTarget): TransformPreview {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
return {
|
||||
kind: "brush",
|
||||
center: cloneVec3(target.initialCenter),
|
||||
rotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
size: cloneVec3(target.initialSize)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
kind: "modelInstance",
|
||||
position: cloneVec3(target.initialPosition),
|
||||
rotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
scale: cloneVec3(target.initialScale)
|
||||
};
|
||||
case "entity":
|
||||
return {
|
||||
kind: "entity",
|
||||
position: cloneVec3(target.initialPosition),
|
||||
rotation: cloneEntityTransformRotationState(target.initialRotation)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function doesTransformSessionChangeTarget(session: ActiveTransformSession): boolean {
|
||||
switch (session.target.kind) {
|
||||
case "brush":
|
||||
return (
|
||||
session.preview.kind === "brush" &&
|
||||
(!areVec3Equal(session.preview.center, session.target.initialCenter) ||
|
||||
!areVec3Equal(session.preview.rotationDegrees, session.target.initialRotationDegrees) ||
|
||||
!areVec3Equal(session.preview.size, session.target.initialSize))
|
||||
);
|
||||
case "modelInstance":
|
||||
return (
|
||||
session.preview.kind === "modelInstance" &&
|
||||
(!areVec3Equal(session.preview.position, session.target.initialPosition) ||
|
||||
!areVec3Equal(session.preview.rotationDegrees, session.target.initialRotationDegrees) ||
|
||||
!areVec3Equal(session.preview.scale, session.target.initialScale))
|
||||
);
|
||||
case "entity":
|
||||
return (
|
||||
session.preview.kind === "entity" &&
|
||||
(!areVec3Equal(session.preview.position, session.target.initialPosition) ||
|
||||
!areEntityTransformRotationsEqual(session.preview.rotation, session.target.initialRotation))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function getTransformOperationLabel(operation: TransformOperation): string {
|
||||
switch (operation) {
|
||||
case "translate":
|
||||
return "Move";
|
||||
case "rotate":
|
||||
return "Rotate";
|
||||
case "scale":
|
||||
return "Scale";
|
||||
}
|
||||
}
|
||||
|
||||
export function getTransformAxisLabel(axis: TransformAxis): string {
|
||||
return axis.toUpperCase();
|
||||
}
|
||||
|
||||
export function getTransformTargetLabel(target: TransformTarget): string {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
return "Whitebox Box";
|
||||
case "modelInstance":
|
||||
return getModelInstanceKindLabel();
|
||||
case "entity":
|
||||
return getEntityKindLabel(target.entityKind);
|
||||
}
|
||||
}
|
||||
|
||||
export function getSupportedTransformOperations(target: TransformTarget): TransformOperation[] {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
return ["translate", "rotate", "scale"];
|
||||
case "modelInstance":
|
||||
return ["translate", "rotate", "scale"];
|
||||
case "entity":
|
||||
return target.initialRotation.kind === "none" ? ["translate"] : ["translate", "rotate"];
|
||||
}
|
||||
}
|
||||
|
||||
export function supportsTransformOperation(target: TransformTarget, operation: TransformOperation): boolean {
|
||||
return getSupportedTransformOperations(target).includes(operation);
|
||||
}
|
||||
|
||||
export function supportsTransformAxisConstraint(session: ActiveTransformSession, axis: TransformAxis): boolean {
|
||||
switch (session.operation) {
|
||||
case "translate":
|
||||
return true;
|
||||
case "scale":
|
||||
return session.target.kind === "modelInstance" || session.target.kind === "brush";
|
||||
case "rotate":
|
||||
if (session.target.kind === "entity" && session.target.initialRotation.kind === "yaw") {
|
||||
return axis === "y";
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEntityRotation(entity: EntityInstance): EntityTransformRotationState {
|
||||
switch (entity.kind) {
|
||||
case "playerStart":
|
||||
case "teleportTarget":
|
||||
return {
|
||||
kind: "yaw",
|
||||
yawDegrees: entity.yawDegrees
|
||||
};
|
||||
case "spotLight":
|
||||
return {
|
||||
kind: "direction",
|
||||
direction: cloneVec3(entity.direction)
|
||||
};
|
||||
case "pointLight":
|
||||
case "soundEmitter":
|
||||
case "triggerVolume":
|
||||
case "interactable":
|
||||
return {
|
||||
kind: "none"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function createBrushTransformTarget(document: SceneDocument, brushId: string): TransformTargetResolution {
|
||||
const brush = document.brushes[brushId];
|
||||
|
||||
if (brush === undefined || brush.kind !== "box") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a supported whitebox box before transforming it."
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
target: {
|
||||
kind: "brush",
|
||||
brushId: brush.id,
|
||||
initialCenter: cloneVec3(brush.center),
|
||||
initialRotationDegrees: cloneVec3(brush.rotationDegrees),
|
||||
initialSize: cloneVec3(brush.size)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
|
||||
function createEntityTransformTarget(document: SceneDocument, entityId: string): TransformTargetResolution {
|
||||
const entity = document.entities[entityId];
|
||||
|
||||
if (entity === undefined) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select an authored entity before transforming it."
|
||||
};
|
||||
}
|
||||
|
||||
const clonedEntity = cloneEntityInstance(entity);
|
||||
|
||||
return {
|
||||
target: {
|
||||
kind: "entity",
|
||||
entityId: clonedEntity.id,
|
||||
entityKind: clonedEntity.kind,
|
||||
initialPosition: cloneVec3(clonedEntity.position),
|
||||
initialRotation: resolveEntityRotation(clonedEntity)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
|
||||
function createModelInstanceTransformTarget(document: SceneDocument, modelInstanceId: string): TransformTargetResolution {
|
||||
const modelInstance = document.modelInstances[modelInstanceId];
|
||||
|
||||
if (modelInstance === undefined) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a model instance before transforming it."
|
||||
};
|
||||
}
|
||||
|
||||
const clonedModelInstance = cloneModelInstance(modelInstance);
|
||||
|
||||
return {
|
||||
target: {
|
||||
kind: "modelInstance",
|
||||
modelInstanceId: clonedModelInstance.id,
|
||||
assetId: clonedModelInstance.assetId,
|
||||
initialPosition: cloneVec3(clonedModelInstance.position),
|
||||
initialRotationDegrees: cloneVec3(clonedModelInstance.rotationDegrees),
|
||||
initialScale: cloneVec3(clonedModelInstance.scale)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveTransformTarget(
|
||||
document: SceneDocument,
|
||||
selection: EditorSelection,
|
||||
whiteboxSelectionMode: WhiteboxSelectionMode = "object"
|
||||
): TransformTargetResolution {
|
||||
switch (selection.kind) {
|
||||
case "none":
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single brush, entity, or model instance before transforming it."
|
||||
};
|
||||
case "brushFace":
|
||||
return {
|
||||
target: null,
|
||||
message: "Face selection is component-only in this slice. Switch to Object mode to transform the whole whitebox box."
|
||||
};
|
||||
case "brushEdge":
|
||||
return {
|
||||
target: null,
|
||||
message: "Edge transforms land in the next whitebox slice. Switch to Object mode to transform the whole whitebox box."
|
||||
};
|
||||
case "brushVertex":
|
||||
return {
|
||||
target: null,
|
||||
message: "Vertex transforms land in the next whitebox slice. Switch to Object mode to transform the whole whitebox box."
|
||||
};
|
||||
case "brushes":
|
||||
if (whiteboxSelectionMode !== "object") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Switch to Object mode to transform the whole whitebox box."
|
||||
};
|
||||
}
|
||||
|
||||
if (selection.ids.length !== 1) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single brush before transforming it."
|
||||
};
|
||||
}
|
||||
|
||||
return createBrushTransformTarget(document, selection.ids[0]);
|
||||
case "entities":
|
||||
if (selection.ids.length !== 1) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single entity before transforming it."
|
||||
};
|
||||
}
|
||||
|
||||
return createEntityTransformTarget(document, selection.ids[0]);
|
||||
case "modelInstances":
|
||||
if (selection.ids.length !== 1) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single model instance before transforming it."
|
||||
};
|
||||
}
|
||||
|
||||
return createModelInstanceTransformTarget(document, selection.ids[0]);
|
||||
}
|
||||
}
|
||||
33
src/core/whitebox-selection-feedback.ts
Normal file
33
src/core/whitebox-selection-feedback.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { EditorSelection } from "./selection";
|
||||
import {
|
||||
BOX_EDGE_LABELS,
|
||||
BOX_FACE_LABELS,
|
||||
BOX_VERTEX_LABELS
|
||||
} from "../document/brushes";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
|
||||
function getBrushDisplayLabel(document: SceneDocument, brushId: string): string {
|
||||
const brushes = Object.values(document.brushes);
|
||||
const brushIndex = brushes.findIndex((brush) => brush.id === brushId);
|
||||
|
||||
if (brushIndex === -1) {
|
||||
return "Whitebox Box";
|
||||
}
|
||||
|
||||
return brushes[brushIndex].name ?? `Whitebox Box ${brushIndex + 1}`;
|
||||
}
|
||||
|
||||
export function getWhiteboxSelectionFeedbackLabel(document: SceneDocument, selection: EditorSelection): string | null {
|
||||
switch (selection.kind) {
|
||||
case "brushes":
|
||||
return selection.ids.length === 1 ? `Solid · ${getBrushDisplayLabel(document, selection.ids[0])}` : null;
|
||||
case "brushFace":
|
||||
return `Face · ${BOX_FACE_LABELS[selection.faceId]} · ${getBrushDisplayLabel(document, selection.brushId)}`;
|
||||
case "brushEdge":
|
||||
return `Edge · ${BOX_EDGE_LABELS[selection.edgeId]} · ${getBrushDisplayLabel(document, selection.brushId)}`;
|
||||
case "brushVertex":
|
||||
return `Vertex · ${BOX_VERTEX_LABELS[selection.vertexId]} · ${getBrushDisplayLabel(document, selection.brushId)}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
14
src/core/whitebox-selection-mode.ts
Normal file
14
src/core/whitebox-selection-mode.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export const WHITEBOX_SELECTION_MODES = ["object", "face", "edge", "vertex"] as const;
|
||||
|
||||
export type WhiteboxSelectionMode = (typeof WHITEBOX_SELECTION_MODES)[number];
|
||||
|
||||
export const WHITEBOX_SELECTION_MODE_LABELS: Record<WhiteboxSelectionMode, string> = {
|
||||
object: "Object",
|
||||
face: "Face",
|
||||
edge: "Edge",
|
||||
vertex: "Vertex"
|
||||
};
|
||||
|
||||
export function getWhiteboxSelectionModeLabel(mode: WhiteboxSelectionMode): string {
|
||||
return WHITEBOX_SELECTION_MODE_LABELS[mode];
|
||||
}
|
||||
@@ -2,11 +2,72 @@ import { createOpaqueId } from "../core/ids";
|
||||
import type { Vec2, Vec3 } from "../core/vector";
|
||||
|
||||
export const BOX_FACE_IDS = ["posX", "negX", "posY", "negY", "posZ", "negZ"] as const;
|
||||
export const BOX_EDGE_IDS = [
|
||||
"edgeX_negY_negZ",
|
||||
"edgeX_posY_negZ",
|
||||
"edgeX_negY_posZ",
|
||||
"edgeX_posY_posZ",
|
||||
"edgeY_negX_negZ",
|
||||
"edgeY_posX_negZ",
|
||||
"edgeY_negX_posZ",
|
||||
"edgeY_posX_posZ",
|
||||
"edgeZ_negX_negY",
|
||||
"edgeZ_posX_negY",
|
||||
"edgeZ_negX_posY",
|
||||
"edgeZ_posX_posY"
|
||||
] as const;
|
||||
export const BOX_VERTEX_IDS = [
|
||||
"negX_negY_negZ",
|
||||
"posX_negY_negZ",
|
||||
"negX_posY_negZ",
|
||||
"posX_posY_negZ",
|
||||
"negX_negY_posZ",
|
||||
"posX_negY_posZ",
|
||||
"negX_posY_posZ",
|
||||
"posX_posY_posZ"
|
||||
] as const;
|
||||
export const FACE_UV_ROTATION_QUARTER_TURNS = [0, 1, 2, 3] as const;
|
||||
|
||||
export type BoxFaceId = (typeof BOX_FACE_IDS)[number];
|
||||
export type BoxEdgeId = (typeof BOX_EDGE_IDS)[number];
|
||||
export type BoxVertexId = (typeof BOX_VERTEX_IDS)[number];
|
||||
export type FaceUvRotationQuarterTurns = (typeof FACE_UV_ROTATION_QUARTER_TURNS)[number];
|
||||
|
||||
export const BOX_FACE_LABELS: Record<BoxFaceId, string> = {
|
||||
posX: "Right",
|
||||
negX: "Left",
|
||||
posY: "Top",
|
||||
negY: "Bottom",
|
||||
posZ: "Front",
|
||||
negZ: "Back"
|
||||
};
|
||||
|
||||
export const BOX_EDGE_LABELS: Record<BoxEdgeId, string> = {
|
||||
edgeX_negY_negZ: "X Edge (-Y, -Z)",
|
||||
edgeX_posY_negZ: "X Edge (+Y, -Z)",
|
||||
edgeX_negY_posZ: "X Edge (-Y, +Z)",
|
||||
edgeX_posY_posZ: "X Edge (+Y, +Z)",
|
||||
edgeY_negX_negZ: "Y Edge (-X, -Z)",
|
||||
edgeY_posX_negZ: "Y Edge (+X, -Z)",
|
||||
edgeY_negX_posZ: "Y Edge (-X, +Z)",
|
||||
edgeY_posX_posZ: "Y Edge (+X, +Z)",
|
||||
edgeZ_negX_negY: "Z Edge (-X, -Y)",
|
||||
edgeZ_posX_negY: "Z Edge (+X, -Y)",
|
||||
edgeZ_negX_posY: "Z Edge (-X, +Y)",
|
||||
edgeZ_posX_posY: "Z Edge (+X, +Y)"
|
||||
};
|
||||
|
||||
export const BOX_VERTEX_LABELS: Record<BoxVertexId, string> = {
|
||||
negX_negY_negZ: "Vertex (-X, -Y, -Z)",
|
||||
posX_negY_negZ: "Vertex (+X, -Y, -Z)",
|
||||
negX_posY_negZ: "Vertex (-X, +Y, -Z)",
|
||||
posX_posY_negZ: "Vertex (+X, +Y, -Z)",
|
||||
negX_negY_posZ: "Vertex (-X, -Y, +Z)",
|
||||
posX_negY_posZ: "Vertex (+X, -Y, +Z)",
|
||||
negX_posY_posZ: "Vertex (-X, +Y, +Z)",
|
||||
posX_posY_posZ: "Vertex (+X, +Y, +Z)"
|
||||
};
|
||||
|
||||
export interface FaceUvState {
|
||||
offset: Vec2;
|
||||
scale: Vec2;
|
||||
@@ -27,6 +88,7 @@ export interface BoxBrush {
|
||||
kind: "box";
|
||||
name?: string;
|
||||
center: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
size: Vec3;
|
||||
faces: BoxBrushFaces;
|
||||
layerId?: string;
|
||||
@@ -47,6 +109,12 @@ export const DEFAULT_BOX_BRUSH_SIZE: Vec3 = {
|
||||
z: 2
|
||||
};
|
||||
|
||||
export const DEFAULT_BOX_BRUSH_ROTATION_DEGREES: Vec3 = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
|
||||
export function normalizeBrushName(name: string | null | undefined): string | undefined {
|
||||
if (name === undefined || name === null) {
|
||||
return undefined;
|
||||
@@ -75,6 +143,14 @@ export function isBoxFaceId(value: unknown): value is BoxFaceId {
|
||||
return typeof value === "string" && BOX_FACE_IDS.some((faceId) => faceId === value);
|
||||
}
|
||||
|
||||
export function isBoxEdgeId(value: unknown): value is BoxEdgeId {
|
||||
return typeof value === "string" && BOX_EDGE_IDS.some((edgeId) => edgeId === value);
|
||||
}
|
||||
|
||||
export function isBoxVertexId(value: unknown): value is BoxVertexId {
|
||||
return typeof value === "string" && BOX_VERTEX_IDS.some((vertexId) => vertexId === value);
|
||||
}
|
||||
|
||||
export function isFaceUvRotationQuarterTurns(value: unknown): value is FaceUvRotationQuarterTurns {
|
||||
return typeof value === "number" && FACE_UV_ROTATION_QUARTER_TURNS.includes(value as FaceUvRotationQuarterTurns);
|
||||
}
|
||||
@@ -154,9 +230,10 @@ export function createDefaultBoxBrushFaces(): BoxBrushFaces {
|
||||
}
|
||||
|
||||
export function createBoxBrush(
|
||||
overrides: Partial<Pick<BoxBrush, "id" | "name" | "center" | "size" | "faces" | "layerId" | "groupId">> = {}
|
||||
overrides: Partial<Pick<BoxBrush, "id" | "name" | "center" | "rotationDegrees" | "size" | "faces" | "layerId" | "groupId">> = {}
|
||||
): BoxBrush {
|
||||
const center = cloneVec3(overrides.center ?? DEFAULT_BOX_BRUSH_CENTER);
|
||||
const rotationDegrees = cloneVec3(overrides.rotationDegrees ?? DEFAULT_BOX_BRUSH_ROTATION_DEGREES);
|
||||
const size = cloneVec3(overrides.size ?? DEFAULT_BOX_BRUSH_SIZE);
|
||||
|
||||
if (!hasPositiveBoxSize(size)) {
|
||||
@@ -168,6 +245,7 @@ export function createBoxBrush(
|
||||
kind: "box",
|
||||
name: normalizeBrushName(overrides.name),
|
||||
center,
|
||||
rotationDegrees,
|
||||
size,
|
||||
faces: overrides.faces === undefined ? createDefaultBoxBrushFaces() : cloneBoxBrushFaces(overrides.faces),
|
||||
layerId: overrides.layerId,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { createStarterMaterialRegistry, type MaterialDef, type MaterialPattern } from "../materials/starter-material-library";
|
||||
import {
|
||||
createModelInstanceCollisionSettings,
|
||||
createModelInstance,
|
||||
isModelInstanceCollisionMode,
|
||||
normalizeModelInstanceName,
|
||||
type ModelInstanceCollisionSettings,
|
||||
type ModelInstance
|
||||
} from "../assets/model-instances";
|
||||
import {
|
||||
@@ -13,13 +16,16 @@ import {
|
||||
type ProjectAssetRecord
|
||||
} from "../assets/project-assets";
|
||||
import {
|
||||
createPlayerStartColliderSettings,
|
||||
createInteractableEntity,
|
||||
normalizeEntityName,
|
||||
createPointLightEntity,
|
||||
createPlayerStartEntity,
|
||||
createSoundEmitterEntity,
|
||||
createSpotLightEntity,
|
||||
createTeleportTargetEntity,
|
||||
createTriggerVolumeEntity,
|
||||
isPlayerStartColliderMode,
|
||||
type EntityInstance
|
||||
} from "../entities/entity-instances";
|
||||
import {
|
||||
@@ -35,6 +41,7 @@ import {
|
||||
import {
|
||||
createBoxBrush,
|
||||
createDefaultFaceUvState,
|
||||
DEFAULT_BOX_BRUSH_ROTATION_DEGREES,
|
||||
isBoxFaceId,
|
||||
isFaceUvRotationQuarterTurns,
|
||||
normalizeBrushName,
|
||||
@@ -45,16 +52,20 @@ import {
|
||||
import {
|
||||
BOX_BRUSH_SCENE_DOCUMENT_VERSION,
|
||||
ANIMATION_PLAYBACK_SCENE_DOCUMENT_VERSION,
|
||||
ENTITY_NAMES_SCENE_DOCUMENT_VERSION,
|
||||
ENTITY_SYSTEM_FOUNDATION_SCENE_DOCUMENT_VERSION,
|
||||
FACE_MATERIALS_SCENE_DOCUMENT_VERSION,
|
||||
FIRST_ROOM_POLISH_SCENE_DOCUMENT_VERSION,
|
||||
FOUNDATION_SCENE_DOCUMENT_VERSION,
|
||||
IMPORTED_MODEL_COLLIDERS_SCENE_DOCUMENT_VERSION,
|
||||
LOCAL_LIGHTS_AND_SKYBOX_SCENE_DOCUMENT_VERSION,
|
||||
MODEL_ASSET_PIPELINE_SCENE_DOCUMENT_VERSION,
|
||||
PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION,
|
||||
RUNNER_V1_SCENE_DOCUMENT_VERSION,
|
||||
SPATIAL_AUDIO_SCENE_DOCUMENT_VERSION,
|
||||
SCENE_DOCUMENT_VERSION,
|
||||
TRIGGER_ACTION_TARGET_FOUNDATION_SCENE_DOCUMENT_VERSION,
|
||||
WHITEBOX_FLOAT_TRANSFORM_SCENE_DOCUMENT_VERSION,
|
||||
WORLD_ENVIRONMENT_SCENE_DOCUMENT_VERSION,
|
||||
type SceneDocument
|
||||
} from "./scene-document";
|
||||
@@ -334,6 +345,10 @@ function readOptionalBrushName(value: unknown, label: string): string | undefine
|
||||
return normalizeBrushName(expectOptionalString(value, label));
|
||||
}
|
||||
|
||||
function readOptionalEntityName(value: unknown, label: string): string | undefined {
|
||||
return normalizeEntityName(expectOptionalString(value, label));
|
||||
}
|
||||
|
||||
function expectEmptyCollection(value: unknown, label: string): Record<string, never> {
|
||||
if (!isRecord(value)) {
|
||||
throw new Error(`${label} must be a record.`);
|
||||
@@ -497,6 +512,50 @@ function readAssets(value: unknown): SceneDocument["assets"] {
|
||||
return assets;
|
||||
}
|
||||
|
||||
function readModelInstanceCollisionSettings(value: unknown, label: string): ModelInstanceCollisionSettings {
|
||||
if (value === undefined) {
|
||||
return createModelInstanceCollisionSettings();
|
||||
}
|
||||
|
||||
if (!isRecord(value)) {
|
||||
throw new Error(`${label} must be an object.`);
|
||||
}
|
||||
|
||||
const mode = readOptionalAllowedValue(value.mode, `${label}.mode`, "none", isModelInstanceCollisionMode);
|
||||
|
||||
return createModelInstanceCollisionSettings({
|
||||
mode,
|
||||
visible: readOptionalBoolean(value.visible, `${label}.visible`, false)
|
||||
});
|
||||
}
|
||||
|
||||
function readPlayerStartColliderSettings(value: unknown, label: string) {
|
||||
if (value === undefined) {
|
||||
return createPlayerStartColliderSettings();
|
||||
}
|
||||
|
||||
if (!isRecord(value)) {
|
||||
throw new Error(`${label} must be an object.`);
|
||||
}
|
||||
|
||||
const mode = readOptionalAllowedValue(
|
||||
value.mode,
|
||||
`${label}.mode`,
|
||||
"capsule",
|
||||
(candidate): candidate is "capsule" | "box" | "none" => typeof candidate === "string" && isPlayerStartColliderMode(candidate)
|
||||
);
|
||||
|
||||
return createPlayerStartColliderSettings({
|
||||
mode,
|
||||
eyeHeight: value.eyeHeight === undefined ? undefined : expectPositiveFiniteNumber(value.eyeHeight, `${label}.eyeHeight`),
|
||||
capsuleRadius:
|
||||
value.capsuleRadius === undefined ? undefined : expectPositiveFiniteNumber(value.capsuleRadius, `${label}.capsuleRadius`),
|
||||
capsuleHeight:
|
||||
value.capsuleHeight === undefined ? undefined : expectPositiveFiniteNumber(value.capsuleHeight, `${label}.capsuleHeight`),
|
||||
boxSize: value.boxSize === undefined ? undefined : readVec3(value.boxSize, `${label}.boxSize`)
|
||||
});
|
||||
}
|
||||
|
||||
function readModelInstance(value: unknown, label: string, assets: SceneDocument["assets"]): ModelInstance {
|
||||
if (!isRecord(value)) {
|
||||
throw new Error(`${label} must be an object.`);
|
||||
@@ -520,6 +579,7 @@ function readModelInstance(value: unknown, label: string, assets: SceneDocument[
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
rotationDegrees: readVec3(value.rotationDegrees, `${label}.rotationDegrees`),
|
||||
scale: readVec3(value.scale, `${label}.scale`),
|
||||
collision: readModelInstanceCollisionSettings(value.collision, `${label}.collision`),
|
||||
animationClipName: (() => {
|
||||
const raw = expectOptionalString(value.animationClipName, `${label}.animationClipName`);
|
||||
if (raw === undefined) return undefined;
|
||||
@@ -575,6 +635,18 @@ function readVec3(value: unknown, label: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function readOptionalVec3(value: unknown, label: string, fallback: { x: number; y: number; z: number }) {
|
||||
if (value === undefined) {
|
||||
return {
|
||||
x: fallback.x,
|
||||
y: fallback.y,
|
||||
z: fallback.z
|
||||
};
|
||||
}
|
||||
|
||||
return readVec3(value, label);
|
||||
}
|
||||
|
||||
function assertNonZeroVec3(vector: { x: number; y: number; z: number }, label: string) {
|
||||
if (vector.x === 0 && vector.y === 0 && vector.z === 0) {
|
||||
throw new Error(`${label} must not be the zero vector.`);
|
||||
@@ -732,6 +804,11 @@ function readBrushes(
|
||||
id: expectString(brushValue.id, `brushes.${brushId}.id`),
|
||||
name: readOptionalBrushName(brushValue.name, `brushes.${brushId}.name`),
|
||||
center,
|
||||
rotationDegrees: readOptionalVec3(
|
||||
brushValue.rotationDegrees,
|
||||
`brushes.${brushId}.rotationDegrees`,
|
||||
DEFAULT_BOX_BRUSH_ROTATION_DEGREES
|
||||
),
|
||||
size,
|
||||
faces: readBoxBrushFaces(brushValue.faces, `brushes.${brushId}.faces`, materials, allowMissingUvState),
|
||||
layerId: expectOptionalString(brushValue.layerId, `brushes.${brushId}.layerId`),
|
||||
@@ -818,6 +895,7 @@ function readPointLightEntity(value: unknown, label: string): EntityInstance {
|
||||
const kind = expectLiteralString(value.kind, "pointLight", `${label}.kind`);
|
||||
const entity = createPointLightEntity({
|
||||
id: expectString(value.id, `${label}.id`),
|
||||
name: readOptionalEntityName(value.name, `${label}.name`),
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
colorHex: expectHexColor(value.colorHex, `${label}.colorHex`),
|
||||
intensity: expectNonNegativeFiniteNumber(value.intensity, `${label}.intensity`),
|
||||
@@ -839,6 +917,7 @@ function readSpotLightEntity(value: unknown, label: string): EntityInstance {
|
||||
const kind = expectLiteralString(value.kind, "spotLight", `${label}.kind`);
|
||||
const entity = createSpotLightEntity({
|
||||
id: expectString(value.id, `${label}.id`),
|
||||
name: readOptionalEntityName(value.name, `${label}.name`),
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
direction: readVec3(value.direction, `${label}.direction`),
|
||||
colorHex: expectHexColor(value.colorHex, `${label}.colorHex`),
|
||||
@@ -862,8 +941,10 @@ function readPlayerStartEntity(value: unknown, label: string): EntityInstance {
|
||||
const kind = expectLiteralString(value.kind, "playerStart", `${label}.kind`);
|
||||
const entity = createPlayerStartEntity({
|
||||
id: expectString(value.id, `${label}.id`),
|
||||
name: readOptionalEntityName(value.name, `${label}.name`),
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
yawDegrees: expectFiniteNumber(value.yawDegrees, `${label}.yawDegrees`)
|
||||
yawDegrees: expectFiniteNumber(value.yawDegrees, `${label}.yawDegrees`),
|
||||
collider: readPlayerStartColliderSettings(value.collider, `${label}.collider`)
|
||||
});
|
||||
|
||||
if (entity.kind !== kind) {
|
||||
@@ -881,6 +962,7 @@ function readSoundEmitterEntity(value: unknown, label: string): EntityInstance {
|
||||
const kind = expectLiteralString(value.kind, "soundEmitter", `${label}.kind`);
|
||||
const entity = createSoundEmitterEntity({
|
||||
id: expectString(value.id, `${label}.id`),
|
||||
name: readOptionalEntityName(value.name, `${label}.name`),
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
audioAssetId:
|
||||
value.audioAssetId === undefined || value.audioAssetId === null
|
||||
@@ -909,6 +991,7 @@ function readLegacySoundEmitterEntity(value: unknown, label: string): EntityInst
|
||||
const radius = expectPositiveFiniteNumber(value.radius, `${label}.radius`);
|
||||
const entity = createSoundEmitterEntity({
|
||||
id: expectString(value.id, `${label}.id`),
|
||||
name: readOptionalEntityName(value.name, `${label}.name`),
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
refDistance: radius,
|
||||
maxDistance: radius,
|
||||
@@ -938,6 +1021,7 @@ function readTriggerVolumeEntity(value: unknown, label: string): EntityInstance
|
||||
|
||||
const entity = createTriggerVolumeEntity({
|
||||
id: expectString(value.id, `${label}.id`),
|
||||
name: readOptionalEntityName(value.name, `${label}.name`),
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
size,
|
||||
triggerOnEnter: expectBoolean(value.triggerOnEnter, `${label}.triggerOnEnter`),
|
||||
@@ -959,6 +1043,7 @@ function readTeleportTargetEntity(value: unknown, label: string): EntityInstance
|
||||
const kind = expectLiteralString(value.kind, "teleportTarget", `${label}.kind`);
|
||||
const entity = createTeleportTargetEntity({
|
||||
id: expectString(value.id, `${label}.id`),
|
||||
name: readOptionalEntityName(value.name, `${label}.name`),
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
yawDegrees: expectFiniteNumber(value.yawDegrees, `${label}.yawDegrees`)
|
||||
});
|
||||
@@ -978,6 +1063,7 @@ function readInteractableEntity(value: unknown, label: string): EntityInstance {
|
||||
const kind = expectLiteralString(value.kind, "interactable", `${label}.kind`);
|
||||
const entity = createInteractableEntity({
|
||||
id: expectString(value.id, `${label}.id`),
|
||||
name: readOptionalEntityName(value.name, `${label}.name`),
|
||||
position: readVec3(value.position, `${label}.position`),
|
||||
radius: expectPositiveFiniteNumber(value.radius, `${label}.radius`),
|
||||
prompt: expectString(value.prompt, `${label}.prompt`),
|
||||
@@ -1428,7 +1514,83 @@ export function migrateSceneDocument(source: unknown): SceneDocument {
|
||||
};
|
||||
}
|
||||
|
||||
if (source.version !== SCENE_DOCUMENT_VERSION) {
|
||||
// v16 -> v18: Player Start collider settings landed before whitebox box rotation.
|
||||
if (source.version === IMPORTED_MODEL_COLLIDERS_SCENE_DOCUMENT_VERSION) {
|
||||
const materials = readMaterialRegistry(source.materials, "materials");
|
||||
const assets = readAssets(source.assets);
|
||||
|
||||
return {
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
name: expectString(source.name, "name"),
|
||||
world: readWorldSettings(source.world),
|
||||
materials,
|
||||
textures: expectEmptyCollection(source.textures, "textures"),
|
||||
assets,
|
||||
brushes: readBrushes(source.brushes, materials, false),
|
||||
modelInstances: readModelInstances(source.modelInstances, assets),
|
||||
entities: readEntities(source.entities, { legacySoundEmitter: false }),
|
||||
interactionLinks: readInteractionLinks(source.interactionLinks)
|
||||
};
|
||||
}
|
||||
|
||||
// v17 -> v18: box-based whitebox solids gained authored object rotation.
|
||||
if (source.version === PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION) {
|
||||
const materials = readMaterialRegistry(source.materials, "materials");
|
||||
const assets = readAssets(source.assets);
|
||||
|
||||
return {
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
name: expectString(source.name, "name"),
|
||||
world: readWorldSettings(source.world),
|
||||
materials,
|
||||
textures: expectEmptyCollection(source.textures, "textures"),
|
||||
assets,
|
||||
brushes: readBrushes(source.brushes, materials, false),
|
||||
modelInstances: readModelInstances(source.modelInstances, assets),
|
||||
entities: readEntities(source.entities, { legacySoundEmitter: false }),
|
||||
interactionLinks: readInteractionLinks(source.interactionLinks)
|
||||
};
|
||||
}
|
||||
|
||||
// v15 -> v16: model instances gained authored collider settings.
|
||||
if (source.version === ENTITY_NAMES_SCENE_DOCUMENT_VERSION) {
|
||||
const materials = readMaterialRegistry(source.materials, "materials");
|
||||
const assets = readAssets(source.assets);
|
||||
|
||||
return {
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
name: expectString(source.name, "name"),
|
||||
world: readWorldSettings(source.world),
|
||||
materials,
|
||||
textures: expectEmptyCollection(source.textures, "textures"),
|
||||
assets,
|
||||
brushes: readBrushes(source.brushes, materials, false),
|
||||
modelInstances: readModelInstances(source.modelInstances, assets),
|
||||
entities: readEntities(source.entities, { legacySoundEmitter: false }),
|
||||
interactionLinks: readInteractionLinks(source.interactionLinks)
|
||||
};
|
||||
}
|
||||
|
||||
// v14 -> v15: entities gained an optional authored name field.
|
||||
if (source.version === 14) {
|
||||
const materials = readMaterialRegistry(source.materials, "materials");
|
||||
const assets = readAssets(source.assets);
|
||||
|
||||
return {
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
name: expectString(source.name, "name"),
|
||||
world: readWorldSettings(source.world),
|
||||
materials,
|
||||
textures: expectEmptyCollection(source.textures, "textures"),
|
||||
assets,
|
||||
brushes: readBrushes(source.brushes, materials, false),
|
||||
modelInstances: readModelInstances(source.modelInstances, assets),
|
||||
entities: readEntities(source.entities, { legacySoundEmitter: false }),
|
||||
interactionLinks: readInteractionLinks(source.interactionLinks)
|
||||
};
|
||||
}
|
||||
|
||||
if (source.version !== WHITEBOX_FLOAT_TRANSFORM_SCENE_DOCUMENT_VERSION) {
|
||||
throw new Error(`Unsupported scene document version: ${String(source.version)}.`);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,10 @@ import {
|
||||
type ProjectAssetRecord
|
||||
} from "../assets/project-assets";
|
||||
import type { ModelInstance } from "../assets/model-instances";
|
||||
import { isModelInstanceCollisionMode } from "../assets/model-instances";
|
||||
import {
|
||||
isPlayerStartColliderMode,
|
||||
getPlayerStartColliderHeight,
|
||||
type InteractableEntity,
|
||||
type PointLightEntity,
|
||||
type PlayerStartEntity,
|
||||
@@ -646,6 +649,28 @@ function validateModelInstance(modelInstance: ModelInstance, path: string, docum
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-instance-scale", "Model instance scales must remain finite and positive on every axis.", `${path}.scale`));
|
||||
}
|
||||
|
||||
if (!isModelInstanceCollisionMode(modelInstance.collision.mode)) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-model-instance-collision-mode",
|
||||
"Model instance collision mode must be one of none, terrain, static, dynamic, or simple.",
|
||||
`${path}.collision.mode`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!isBoolean(modelInstance.collision.visible)) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-model-instance-collision-visibility",
|
||||
"Model instance collision visibility must be a boolean.",
|
||||
`${path}.collision.visible`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const asset = document.assets[modelInstance.assetId];
|
||||
|
||||
if (asset === undefined) {
|
||||
@@ -667,6 +692,12 @@ function validateModelInstance(modelInstance: ModelInstance, path: string, docum
|
||||
}
|
||||
}
|
||||
|
||||
function validateEntityName(name: string | undefined, path: string, diagnostics: SceneDiagnostic[]) {
|
||||
if (name !== undefined && name.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-entity-name", "Entity names must be non-empty when authored.", `${path}.name`));
|
||||
}
|
||||
}
|
||||
|
||||
function validatePlayerStartEntity(entity: PlayerStartEntity, path: string, diagnostics: SceneDiagnostic[]) {
|
||||
if (!isFiniteVec3(entity.position)) {
|
||||
diagnostics.push(
|
||||
@@ -677,6 +708,90 @@ function validatePlayerStartEntity(entity: PlayerStartEntity, path: string, diag
|
||||
if (!isFiniteNumber(entity.yawDegrees)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-yaw", "Player Start yaw must remain a finite number.", `${path}.yawDegrees`));
|
||||
}
|
||||
|
||||
if (!isPlayerStartColliderMode(entity.collider.mode)) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-player-start-collider-mode",
|
||||
"Player Start collider mode must be capsule, box, or none.",
|
||||
`${path}.collider.mode`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!isFiniteNumber(entity.collider.eyeHeight) || entity.collider.eyeHeight <= 0) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-player-start-eye-height",
|
||||
"Player Start eye height must remain a finite number greater than zero.",
|
||||
`${path}.collider.eyeHeight`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!isFiniteNumber(entity.collider.capsuleRadius) || entity.collider.capsuleRadius <= 0) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-player-start-capsule-radius",
|
||||
"Player Start capsule radius must remain a finite number greater than zero.",
|
||||
`${path}.collider.capsuleRadius`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!isFiniteNumber(entity.collider.capsuleHeight) || entity.collider.capsuleHeight <= 0) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-player-start-capsule-height",
|
||||
"Player Start capsule height must remain a finite number greater than zero.",
|
||||
`${path}.collider.capsuleHeight`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
!isFiniteVec3(entity.collider.boxSize) ||
|
||||
entity.collider.boxSize.x <= 0 ||
|
||||
entity.collider.boxSize.y <= 0 ||
|
||||
entity.collider.boxSize.z <= 0
|
||||
) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-player-start-box-size",
|
||||
"Player Start box size must remain finite and positive on every axis.",
|
||||
`${path}.collider.boxSize`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (entity.collider.capsuleHeight < entity.collider.capsuleRadius * 2) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-player-start-capsule-proportions",
|
||||
"Player Start capsule height must be at least twice the capsule radius.",
|
||||
`${path}.collider.capsuleHeight`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const colliderHeight = getPlayerStartColliderHeight(entity.collider);
|
||||
|
||||
if (colliderHeight !== null && entity.collider.eyeHeight > colliderHeight) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-player-start-eye-height",
|
||||
"Player Start eye height must fit within the authored collider height.",
|
||||
`${path}.collider.eyeHeight`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function validateSoundEmitterAudioAsset(
|
||||
@@ -1153,6 +1268,23 @@ export function validateSceneDocument(document: SceneDocument): SceneDocumentVal
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-name", "Box brush names must be non-empty when authored.", `${path}.name`));
|
||||
}
|
||||
|
||||
if (!isFiniteVec3(brush.center)) {
|
||||
diagnostics.push(
|
||||
createDiagnostic("error", "invalid-box-center", "Box brush centers must remain finite on every axis.", `${path}.center`)
|
||||
);
|
||||
}
|
||||
|
||||
if (!isFiniteVec3(brush.rotationDegrees)) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
"invalid-box-rotation",
|
||||
"Box brush rotations must remain finite on every axis.",
|
||||
`${path}.rotationDegrees`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!isFiniteVec3(brush.size) || !hasPositiveBoxSize(brush.size)) {
|
||||
diagnostics.push(
|
||||
createDiagnostic("error", "invalid-box-size", "Box brush sizes must remain finite and positive on every axis.", `${path}.size`)
|
||||
@@ -1196,6 +1328,7 @@ export function validateSceneDocument(document: SceneDocument): SceneDocumentVal
|
||||
}
|
||||
|
||||
registerAuthoredId(entity.id, path, seenIds, diagnostics);
|
||||
validateEntityName(entity.name, path, diagnostics);
|
||||
|
||||
switch (entity.kind) {
|
||||
case "pointLight":
|
||||
|
||||
@@ -6,7 +6,11 @@ import type { InteractionLink } from "../interactions/interaction-links";
|
||||
import { cloneMaterialRegistry, createStarterMaterialRegistry, type MaterialDef } from "../materials/starter-material-library";
|
||||
import { createDefaultWorldSettings, type WorldSettings } from "./world-settings";
|
||||
|
||||
export const SCENE_DOCUMENT_VERSION = 14 as const;
|
||||
export const SCENE_DOCUMENT_VERSION = 18 as const;
|
||||
export const WHITEBOX_FLOAT_TRANSFORM_SCENE_DOCUMENT_VERSION = 18 as const;
|
||||
export const PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION = 17 as const;
|
||||
export const IMPORTED_MODEL_COLLIDERS_SCENE_DOCUMENT_VERSION = 16 as const;
|
||||
export const ENTITY_NAMES_SCENE_DOCUMENT_VERSION = 15 as const;
|
||||
export const SPATIAL_AUDIO_SCENE_DOCUMENT_VERSION = 13 as const;
|
||||
export const ANIMATION_PLAYBACK_SCENE_DOCUMENT_VERSION = 12 as const;
|
||||
export const LOCAL_LIGHTS_AND_SKYBOX_SCENE_DOCUMENT_VERSION = 10 as const;
|
||||
|
||||
@@ -2,19 +2,21 @@ import { createOpaqueId } from "../core/ids";
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import { isHexColorString } from "../document/world-settings";
|
||||
|
||||
export interface PointLightEntity {
|
||||
interface PositionedEntity {
|
||||
id: string;
|
||||
kind: "pointLight";
|
||||
name?: string;
|
||||
position: Vec3;
|
||||
}
|
||||
|
||||
export interface PointLightEntity extends PositionedEntity {
|
||||
kind: "pointLight";
|
||||
colorHex: string;
|
||||
intensity: number;
|
||||
distance: number;
|
||||
}
|
||||
|
||||
export interface SpotLightEntity {
|
||||
id: string;
|
||||
export interface SpotLightEntity extends PositionedEntity {
|
||||
kind: "spotLight";
|
||||
position: Vec3;
|
||||
direction: Vec3;
|
||||
colorHex: string;
|
||||
intensity: number;
|
||||
@@ -22,17 +24,25 @@ export interface SpotLightEntity {
|
||||
angleDegrees: number;
|
||||
}
|
||||
|
||||
export interface PlayerStartEntity {
|
||||
id: string;
|
||||
export interface PlayerStartEntity extends PositionedEntity {
|
||||
kind: "playerStart";
|
||||
position: Vec3;
|
||||
yawDegrees: number;
|
||||
collider: PlayerStartColliderSettings;
|
||||
}
|
||||
|
||||
export interface SoundEmitterEntity {
|
||||
id: string;
|
||||
export const PLAYER_START_COLLIDER_MODES = ["capsule", "box", "none"] as const;
|
||||
export type PlayerStartColliderMode = (typeof PLAYER_START_COLLIDER_MODES)[number];
|
||||
|
||||
export interface PlayerStartColliderSettings {
|
||||
mode: PlayerStartColliderMode;
|
||||
eyeHeight: number;
|
||||
capsuleRadius: number;
|
||||
capsuleHeight: number;
|
||||
boxSize: Vec3;
|
||||
}
|
||||
|
||||
export interface SoundEmitterEntity extends PositionedEntity {
|
||||
kind: "soundEmitter";
|
||||
position: Vec3;
|
||||
audioAssetId: string | null;
|
||||
volume: number;
|
||||
refDistance: number;
|
||||
@@ -41,26 +51,20 @@ export interface SoundEmitterEntity {
|
||||
loop: boolean;
|
||||
}
|
||||
|
||||
export interface TriggerVolumeEntity {
|
||||
id: string;
|
||||
export interface TriggerVolumeEntity extends PositionedEntity {
|
||||
kind: "triggerVolume";
|
||||
position: Vec3;
|
||||
size: Vec3;
|
||||
triggerOnEnter: boolean;
|
||||
triggerOnExit: boolean;
|
||||
}
|
||||
|
||||
export interface TeleportTargetEntity {
|
||||
id: string;
|
||||
export interface TeleportTargetEntity extends PositionedEntity {
|
||||
kind: "teleportTarget";
|
||||
position: Vec3;
|
||||
yawDegrees: number;
|
||||
}
|
||||
|
||||
export interface InteractableEntity {
|
||||
id: string;
|
||||
export interface InteractableEntity extends PositionedEntity {
|
||||
kind: "interactable";
|
||||
position: Vec3;
|
||||
radius: number;
|
||||
prompt: string;
|
||||
enabled: boolean;
|
||||
@@ -124,6 +128,15 @@ export const DEFAULT_ENTITY_POSITION: Vec3 = {
|
||||
|
||||
export const DEFAULT_PLAYER_START_POSITION = DEFAULT_ENTITY_POSITION;
|
||||
export const DEFAULT_PLAYER_START_YAW_DEGREES = 0;
|
||||
export const DEFAULT_PLAYER_START_COLLIDER_MODE: PlayerStartColliderMode = "capsule";
|
||||
export const DEFAULT_PLAYER_START_EYE_HEIGHT = 1.6;
|
||||
export const DEFAULT_PLAYER_START_CAPSULE_RADIUS = 0.3;
|
||||
export const DEFAULT_PLAYER_START_CAPSULE_HEIGHT = 1.8;
|
||||
export const DEFAULT_PLAYER_START_BOX_SIZE: Vec3 = {
|
||||
x: 0.6,
|
||||
y: 1.8,
|
||||
z: 0.6
|
||||
};
|
||||
export const DEFAULT_SOUND_EMITTER_AUDIO_ASSET_ID: string | null = null;
|
||||
export const DEFAULT_SOUND_EMITTER_VOLUME = 1;
|
||||
export const DEFAULT_SOUND_EMITTER_GAIN = DEFAULT_SOUND_EMITTER_VOLUME;
|
||||
@@ -195,6 +208,70 @@ function assertBoolean(value: boolean, label: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export function isPlayerStartColliderMode(value: string): value is PlayerStartColliderMode {
|
||||
return PLAYER_START_COLLIDER_MODES.includes(value as PlayerStartColliderMode);
|
||||
}
|
||||
|
||||
export function clonePlayerStartColliderSettings(settings: PlayerStartColliderSettings): PlayerStartColliderSettings {
|
||||
return {
|
||||
mode: settings.mode,
|
||||
eyeHeight: settings.eyeHeight,
|
||||
capsuleRadius: settings.capsuleRadius,
|
||||
capsuleHeight: settings.capsuleHeight,
|
||||
boxSize: cloneVec3(settings.boxSize)
|
||||
};
|
||||
}
|
||||
|
||||
export function getPlayerStartColliderHeight(settings: PlayerStartColliderSettings): number | null {
|
||||
switch (settings.mode) {
|
||||
case "capsule":
|
||||
return settings.capsuleHeight;
|
||||
case "box":
|
||||
return settings.boxSize.y;
|
||||
case "none":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function createPlayerStartColliderSettings(
|
||||
overrides: Partial<PlayerStartColliderSettings> = {}
|
||||
): PlayerStartColliderSettings {
|
||||
const mode = overrides.mode ?? DEFAULT_PLAYER_START_COLLIDER_MODE;
|
||||
const eyeHeight = overrides.eyeHeight ?? DEFAULT_PLAYER_START_EYE_HEIGHT;
|
||||
const capsuleRadius = overrides.capsuleRadius ?? DEFAULT_PLAYER_START_CAPSULE_RADIUS;
|
||||
const capsuleHeight = overrides.capsuleHeight ?? DEFAULT_PLAYER_START_CAPSULE_HEIGHT;
|
||||
const boxSize = cloneVec3(overrides.boxSize ?? DEFAULT_PLAYER_START_BOX_SIZE);
|
||||
|
||||
if (!isPlayerStartColliderMode(mode)) {
|
||||
throw new Error("Player Start collider mode must be capsule, box, or none.");
|
||||
}
|
||||
|
||||
assertPositiveFiniteNumber(eyeHeight, "Player Start eye height");
|
||||
assertPositiveFiniteNumber(capsuleRadius, "Player Start capsule radius");
|
||||
assertPositiveFiniteNumber(capsuleHeight, "Player Start capsule height");
|
||||
assertPositiveFiniteVec3(boxSize, "Player Start box size");
|
||||
|
||||
if (capsuleHeight < capsuleRadius * 2) {
|
||||
throw new Error("Player Start capsule height must be at least twice the capsule radius.");
|
||||
}
|
||||
|
||||
if (mode === "capsule" && eyeHeight > capsuleHeight) {
|
||||
throw new Error("Player Start eye height must be less than or equal to the capsule height.");
|
||||
}
|
||||
|
||||
if (mode === "box" && eyeHeight > boxSize.y) {
|
||||
throw new Error("Player Start eye height must be less than or equal to the box height.");
|
||||
}
|
||||
|
||||
return {
|
||||
mode,
|
||||
eyeHeight,
|
||||
capsuleRadius,
|
||||
capsuleHeight,
|
||||
boxSize
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSoundEmitterAudioAssetId(audioAssetId: string | null | undefined): string | null {
|
||||
if (audioAssetId === undefined || audioAssetId === null) {
|
||||
return null;
|
||||
@@ -209,6 +286,15 @@ function normalizeSoundEmitterAudioAssetId(audioAssetId: string | null | undefin
|
||||
return trimmedAudioAssetId;
|
||||
}
|
||||
|
||||
export function normalizeEntityName(name: string | null | undefined): string | undefined {
|
||||
if (name === undefined || name === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const trimmedName = name.trim();
|
||||
return trimmedName.length === 0 ? undefined : trimmedName;
|
||||
}
|
||||
|
||||
export function normalizeYawDegrees(yawDegrees: number): number {
|
||||
const normalizedYaw = yawDegrees % 360;
|
||||
return normalizedYaw < 0 ? normalizedYaw + 360 : normalizedYaw;
|
||||
@@ -225,7 +311,7 @@ export function normalizeInteractablePrompt(prompt: string): string {
|
||||
}
|
||||
|
||||
export function createPointLightEntity(
|
||||
overrides: Partial<Pick<PointLightEntity, "id" | "position" | "colorHex" | "intensity" | "distance">> = {}
|
||||
overrides: Partial<Pick<PointLightEntity, "id" | "name" | "position" | "colorHex" | "intensity" | "distance">> = {}
|
||||
): PointLightEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_POINT_LIGHT_POSITION);
|
||||
const colorHex = overrides.colorHex ?? DEFAULT_POINT_LIGHT_COLOR_HEX;
|
||||
@@ -240,6 +326,7 @@ export function createPointLightEntity(
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-point-light"),
|
||||
kind: "pointLight",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
colorHex,
|
||||
intensity,
|
||||
@@ -248,7 +335,7 @@ export function createPointLightEntity(
|
||||
}
|
||||
|
||||
export function createSpotLightEntity(
|
||||
overrides: Partial<Pick<SpotLightEntity, "id" | "position" | "direction" | "colorHex" | "intensity" | "distance" | "angleDegrees">> = {}
|
||||
overrides: Partial<Pick<SpotLightEntity, "id" | "name" | "position" | "direction" | "colorHex" | "intensity" | "distance" | "angleDegrees">> = {}
|
||||
): SpotLightEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_SPOT_LIGHT_POSITION);
|
||||
const direction = cloneVec3(overrides.direction ?? DEFAULT_SPOT_LIGHT_DIRECTION);
|
||||
@@ -271,6 +358,7 @@ export function createSpotLightEntity(
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-spot-light"),
|
||||
kind: "spotLight",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
direction,
|
||||
colorHex,
|
||||
@@ -281,10 +369,11 @@ export function createSpotLightEntity(
|
||||
}
|
||||
|
||||
export function createPlayerStartEntity(
|
||||
overrides: Partial<Pick<PlayerStartEntity, "id" | "position" | "yawDegrees">> = {}
|
||||
overrides: Partial<Pick<PlayerStartEntity, "id" | "name" | "position" | "yawDegrees" | "collider">> = {}
|
||||
): PlayerStartEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_PLAYER_START_POSITION);
|
||||
const yawDegrees = overrides.yawDegrees ?? DEFAULT_PLAYER_START_YAW_DEGREES;
|
||||
const collider = createPlayerStartColliderSettings(overrides.collider);
|
||||
|
||||
assertFiniteVec3(position, "Player Start position");
|
||||
|
||||
@@ -295,8 +384,10 @@ export function createPlayerStartEntity(
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-player-start"),
|
||||
kind: "playerStart",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
yawDegrees: normalizeYawDegrees(yawDegrees)
|
||||
yawDegrees: normalizeYawDegrees(yawDegrees),
|
||||
collider
|
||||
};
|
||||
}
|
||||
|
||||
@@ -304,7 +395,7 @@ export function createSoundEmitterEntity(
|
||||
overrides: Partial<
|
||||
Pick<
|
||||
SoundEmitterEntity,
|
||||
"id" | "position" | "audioAssetId" | "volume" | "refDistance" | "maxDistance" | "autoplay" | "loop"
|
||||
"id" | "name" | "position" | "audioAssetId" | "volume" | "refDistance" | "maxDistance" | "autoplay" | "loop"
|
||||
>
|
||||
> = {}
|
||||
): SoundEmitterEntity {
|
||||
@@ -331,6 +422,7 @@ export function createSoundEmitterEntity(
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-sound-emitter"),
|
||||
kind: "soundEmitter",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
audioAssetId,
|
||||
volume,
|
||||
@@ -342,7 +434,7 @@ export function createSoundEmitterEntity(
|
||||
}
|
||||
|
||||
export function createTriggerVolumeEntity(
|
||||
overrides: Partial<Pick<TriggerVolumeEntity, "id" | "position" | "size" | "triggerOnEnter" | "triggerOnExit">> = {}
|
||||
overrides: Partial<Pick<TriggerVolumeEntity, "id" | "name" | "position" | "size" | "triggerOnEnter" | "triggerOnExit">> = {}
|
||||
): TriggerVolumeEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const size = cloneVec3(overrides.size ?? DEFAULT_TRIGGER_VOLUME_SIZE);
|
||||
@@ -357,6 +449,7 @@ export function createTriggerVolumeEntity(
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-trigger-volume"),
|
||||
kind: "triggerVolume",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
size,
|
||||
triggerOnEnter,
|
||||
@@ -365,7 +458,7 @@ export function createTriggerVolumeEntity(
|
||||
}
|
||||
|
||||
export function createTeleportTargetEntity(
|
||||
overrides: Partial<Pick<TeleportTargetEntity, "id" | "position" | "yawDegrees">> = {}
|
||||
overrides: Partial<Pick<TeleportTargetEntity, "id" | "name" | "position" | "yawDegrees">> = {}
|
||||
): TeleportTargetEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const yawDegrees = overrides.yawDegrees ?? DEFAULT_TELEPORT_TARGET_YAW_DEGREES;
|
||||
@@ -379,13 +472,14 @@ export function createTeleportTargetEntity(
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-teleport-target"),
|
||||
kind: "teleportTarget",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
yawDegrees: normalizeYawDegrees(yawDegrees)
|
||||
};
|
||||
}
|
||||
|
||||
export function createInteractableEntity(
|
||||
overrides: Partial<Pick<InteractableEntity, "id" | "position" | "radius" | "prompt" | "enabled">> = {}
|
||||
overrides: Partial<Pick<InteractableEntity, "id" | "name" | "position" | "radius" | "prompt" | "enabled">> = {}
|
||||
): InteractableEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const radius = overrides.radius ?? DEFAULT_INTERACTABLE_RADIUS;
|
||||
@@ -399,6 +493,7 @@ export function createInteractableEntity(
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-interactable"),
|
||||
kind: "interactable",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
radius,
|
||||
prompt,
|
||||
@@ -509,7 +604,7 @@ export function cloneEntityRegistry(entities: Record<string, EntityInstance>): R
|
||||
}
|
||||
|
||||
export function areEntityInstancesEqual(left: EntityInstance, right: EntityInstance): boolean {
|
||||
if (left.kind !== right.kind || left.id !== right.id || !areVec3Equal(left.position, right.position)) {
|
||||
if (left.kind !== right.kind || left.id !== right.id || left.name !== right.name || !areVec3Equal(left.position, right.position)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -534,7 +629,14 @@ export function areEntityInstancesEqual(left: EntityInstance, right: EntityInsta
|
||||
}
|
||||
case "playerStart": {
|
||||
const typedRight = right as PlayerStartEntity;
|
||||
return left.yawDegrees === typedRight.yawDegrees;
|
||||
return (
|
||||
left.yawDegrees === typedRight.yawDegrees &&
|
||||
left.collider.mode === typedRight.collider.mode &&
|
||||
left.collider.eyeHeight === typedRight.collider.eyeHeight &&
|
||||
left.collider.capsuleRadius === typedRight.collider.capsuleRadius &&
|
||||
left.collider.capsuleHeight === typedRight.collider.capsuleHeight &&
|
||||
areVec3Equal(left.collider.boxSize, typedRight.collider.boxSize)
|
||||
);
|
||||
}
|
||||
case "soundEmitter": {
|
||||
const typedRight = right as SoundEmitterEntity;
|
||||
|
||||
@@ -30,6 +30,10 @@ export function getEntityDisplayLabel(
|
||||
entities: Record<string, EntityInstance>,
|
||||
assets?: Record<string, ProjectAssetRecord>
|
||||
): string {
|
||||
if (entity.name !== undefined) {
|
||||
return entity.name;
|
||||
}
|
||||
|
||||
const typedEntities = getSortedEntitiesByKind(entities, entity.kind);
|
||||
const entityIndex = typedEntities.findIndex((candidate) => candidate.id === entity.id);
|
||||
const baseLabel = getEntityKindLabel(entity.kind);
|
||||
|
||||
102
src/geometry/box-brush-components.ts
Normal file
102
src/geometry/box-brush-components.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { Euler, MathUtils, Vector3 } from "three";
|
||||
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import {
|
||||
type BoxBrush,
|
||||
type BoxEdgeId,
|
||||
type BoxVertexId
|
||||
} from "../document/brushes";
|
||||
import { getBoxBrushHalfSize } from "./box-brush";
|
||||
|
||||
type Sign = -1 | 1;
|
||||
|
||||
interface BoxVertexSigns {
|
||||
x: Sign;
|
||||
y: Sign;
|
||||
z: Sign;
|
||||
}
|
||||
|
||||
const BOX_VERTEX_SIGNS: Record<BoxVertexId, BoxVertexSigns> = {
|
||||
negX_negY_negZ: { x: -1, y: -1, z: -1 },
|
||||
posX_negY_negZ: { x: 1, y: -1, z: -1 },
|
||||
negX_posY_negZ: { x: -1, y: 1, z: -1 },
|
||||
posX_posY_negZ: { x: 1, y: 1, z: -1 },
|
||||
negX_negY_posZ: { x: -1, y: -1, z: 1 },
|
||||
posX_negY_posZ: { x: 1, y: -1, z: 1 },
|
||||
negX_posY_posZ: { x: -1, y: 1, z: 1 },
|
||||
posX_posY_posZ: { x: 1, y: 1, z: 1 }
|
||||
};
|
||||
|
||||
const BOX_EDGE_VERTEX_IDS: Record<BoxEdgeId, { start: BoxVertexId; end: BoxVertexId }> = {
|
||||
edgeX_negY_negZ: { start: "negX_negY_negZ", end: "posX_negY_negZ" },
|
||||
edgeX_posY_negZ: { start: "negX_posY_negZ", end: "posX_posY_negZ" },
|
||||
edgeX_negY_posZ: { start: "negX_negY_posZ", end: "posX_negY_posZ" },
|
||||
edgeX_posY_posZ: { start: "negX_posY_posZ", end: "posX_posY_posZ" },
|
||||
edgeY_negX_negZ: { start: "negX_negY_negZ", end: "negX_posY_negZ" },
|
||||
edgeY_posX_negZ: { start: "posX_negY_negZ", end: "posX_posY_negZ" },
|
||||
edgeY_negX_posZ: { start: "negX_negY_posZ", end: "negX_posY_posZ" },
|
||||
edgeY_posX_posZ: { start: "posX_negY_posZ", end: "posX_posY_posZ" },
|
||||
edgeZ_negX_negY: { start: "negX_negY_negZ", end: "negX_negY_posZ" },
|
||||
edgeZ_posX_negY: { start: "posX_negY_negZ", end: "posX_negY_posZ" },
|
||||
edgeZ_negX_posY: { start: "negX_posY_negZ", end: "negX_posY_posZ" },
|
||||
edgeZ_posX_posY: { start: "posX_posY_negZ", end: "posX_posY_posZ" }
|
||||
};
|
||||
|
||||
export interface BoxBrushEdgeWorldSegment {
|
||||
id: BoxEdgeId;
|
||||
start: Vec3;
|
||||
end: Vec3;
|
||||
center: Vec3;
|
||||
}
|
||||
|
||||
function createBrushRotationEuler(brush: BoxBrush): Euler {
|
||||
return new Euler(
|
||||
MathUtils.degToRad(brush.rotationDegrees.x),
|
||||
MathUtils.degToRad(brush.rotationDegrees.y),
|
||||
MathUtils.degToRad(brush.rotationDegrees.z),
|
||||
"XYZ"
|
||||
);
|
||||
}
|
||||
|
||||
export function transformBoxBrushLocalPointToWorld(brush: BoxBrush, localPoint: Vec3): Vec3 {
|
||||
const rotation = createBrushRotationEuler(brush);
|
||||
const rotatedOffset = new Vector3(localPoint.x, localPoint.y, localPoint.z).applyEuler(rotation);
|
||||
|
||||
return {
|
||||
x: brush.center.x + rotatedOffset.x,
|
||||
y: brush.center.y + rotatedOffset.y,
|
||||
z: brush.center.z + rotatedOffset.z
|
||||
};
|
||||
}
|
||||
|
||||
export function getBoxBrushVertexLocalPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
|
||||
const halfSize = getBoxBrushHalfSize(brush);
|
||||
const signs = BOX_VERTEX_SIGNS[vertexId];
|
||||
|
||||
return {
|
||||
x: signs.x * halfSize.x,
|
||||
y: signs.y * halfSize.y,
|
||||
z: signs.z * halfSize.z
|
||||
};
|
||||
}
|
||||
|
||||
export function getBoxBrushVertexWorldPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
|
||||
return transformBoxBrushLocalPointToWorld(brush, getBoxBrushVertexLocalPosition(brush, vertexId));
|
||||
}
|
||||
|
||||
export function getBoxBrushEdgeWorldSegment(brush: BoxBrush, edgeId: BoxEdgeId): BoxBrushEdgeWorldSegment {
|
||||
const vertexIds = BOX_EDGE_VERTEX_IDS[edgeId];
|
||||
const start = getBoxBrushVertexWorldPosition(brush, vertexIds.start);
|
||||
const end = getBoxBrushVertexWorldPosition(brush, vertexIds.end);
|
||||
|
||||
return {
|
||||
id: edgeId,
|
||||
start,
|
||||
end,
|
||||
center: {
|
||||
x: (start.x + end.x) * 0.5,
|
||||
y: (start.y + end.y) * 0.5,
|
||||
z: (start.z + end.z) * 0.5
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { Euler, MathUtils, Vector3 } from "three";
|
||||
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import type { BoxBrush } from "../document/brushes";
|
||||
|
||||
@@ -15,33 +17,52 @@ export function getBoxBrushHalfSize(brush: BoxBrush): Vec3 {
|
||||
}
|
||||
|
||||
export function getBoxBrushBounds(brush: BoxBrush): BoxBrushBounds {
|
||||
const halfSize = getBoxBrushHalfSize(brush);
|
||||
const corners = getBoxBrushCornerPositions(brush);
|
||||
const firstCorner = corners[0];
|
||||
const min = { ...firstCorner };
|
||||
const max = { ...firstCorner };
|
||||
|
||||
for (const corner of corners.slice(1)) {
|
||||
min.x = Math.min(min.x, corner.x);
|
||||
min.y = Math.min(min.y, corner.y);
|
||||
min.z = Math.min(min.z, corner.z);
|
||||
max.x = Math.max(max.x, corner.x);
|
||||
max.y = Math.max(max.y, corner.y);
|
||||
max.z = Math.max(max.z, corner.z);
|
||||
}
|
||||
|
||||
return {
|
||||
min: {
|
||||
x: brush.center.x - halfSize.x,
|
||||
y: brush.center.y - halfSize.y,
|
||||
z: brush.center.z - halfSize.z
|
||||
},
|
||||
max: {
|
||||
x: brush.center.x + halfSize.x,
|
||||
y: brush.center.y + halfSize.y,
|
||||
z: brush.center.z + halfSize.z
|
||||
}
|
||||
min,
|
||||
max
|
||||
};
|
||||
}
|
||||
|
||||
export function getBoxBrushCornerPositions(brush: BoxBrush): Vec3[] {
|
||||
const bounds = getBoxBrushBounds(brush);
|
||||
|
||||
return [
|
||||
{ x: bounds.min.x, y: bounds.min.y, z: bounds.min.z },
|
||||
{ x: bounds.max.x, y: bounds.min.y, z: bounds.min.z },
|
||||
{ x: bounds.min.x, y: bounds.max.y, z: bounds.min.z },
|
||||
{ x: bounds.max.x, y: bounds.max.y, z: bounds.min.z },
|
||||
{ x: bounds.min.x, y: bounds.min.y, z: bounds.max.z },
|
||||
{ x: bounds.max.x, y: bounds.min.y, z: bounds.max.z },
|
||||
{ x: bounds.min.x, y: bounds.max.y, z: bounds.max.z },
|
||||
{ x: bounds.max.x, y: bounds.max.y, z: bounds.max.z }
|
||||
const halfSize = getBoxBrushHalfSize(brush);
|
||||
const rotation = new Euler(
|
||||
MathUtils.degToRad(brush.rotationDegrees.x),
|
||||
MathUtils.degToRad(brush.rotationDegrees.y),
|
||||
MathUtils.degToRad(brush.rotationDegrees.z),
|
||||
"XYZ"
|
||||
);
|
||||
const offsets = [
|
||||
new Vector3(-halfSize.x, -halfSize.y, -halfSize.z),
|
||||
new Vector3(halfSize.x, -halfSize.y, -halfSize.z),
|
||||
new Vector3(-halfSize.x, halfSize.y, -halfSize.z),
|
||||
new Vector3(halfSize.x, halfSize.y, -halfSize.z),
|
||||
new Vector3(-halfSize.x, -halfSize.y, halfSize.z),
|
||||
new Vector3(halfSize.x, -halfSize.y, halfSize.z),
|
||||
new Vector3(-halfSize.x, halfSize.y, halfSize.z),
|
||||
new Vector3(halfSize.x, halfSize.y, halfSize.z)
|
||||
];
|
||||
|
||||
return offsets.map((offset) => {
|
||||
const rotatedOffset = offset.clone().applyEuler(rotation);
|
||||
|
||||
return {
|
||||
x: brush.center.x + rotatedOffset.x,
|
||||
y: brush.center.y + rotatedOffset.y,
|
||||
z: brush.center.z + rotatedOffset.z
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
165
src/geometry/model-instance-collider-debug-mesh.ts
Normal file
165
src/geometry/model-instance-collider-debug-mesh.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import {
|
||||
BoxGeometry,
|
||||
BufferGeometry,
|
||||
Float32BufferAttribute,
|
||||
Group,
|
||||
Mesh,
|
||||
MeshBasicMaterial,
|
||||
Vector3,
|
||||
type Material
|
||||
} from "three";
|
||||
import { ConvexGeometry } from "three/examples/jsm/geometries/ConvexGeometry.js";
|
||||
|
||||
import type {
|
||||
GeneratedModelBoxCollider,
|
||||
GeneratedModelCollider,
|
||||
GeneratedModelCompoundCollider,
|
||||
GeneratedModelHeightfieldCollider,
|
||||
GeneratedModelTriMeshCollider
|
||||
} from "./model-instance-collider-generation";
|
||||
|
||||
const DEBUG_COLLIDER_COLORS = {
|
||||
simple: 0x87d2ff,
|
||||
terrain: 0x7be7b4,
|
||||
static: 0xffc66d,
|
||||
dynamic: 0xff8b7a
|
||||
} as const;
|
||||
|
||||
function createWireframeMaterial(color: number): MeshBasicMaterial {
|
||||
return new MeshBasicMaterial({
|
||||
color,
|
||||
wireframe: true,
|
||||
transparent: true,
|
||||
opacity: 0.85,
|
||||
depthWrite: false,
|
||||
toneMapped: false
|
||||
});
|
||||
}
|
||||
|
||||
function markDebugMesh(mesh: Mesh) {
|
||||
mesh.userData.shadowIgnored = true;
|
||||
mesh.userData.nonPickable = true;
|
||||
mesh.renderOrder = 3_500;
|
||||
}
|
||||
|
||||
function createBoxColliderDebugMesh(collider: GeneratedModelBoxCollider): Mesh {
|
||||
const mesh = new Mesh(new BoxGeometry(collider.size.x, collider.size.y, collider.size.z), createWireframeMaterial(DEBUG_COLLIDER_COLORS.simple));
|
||||
mesh.position.set(collider.center.x, collider.center.y, collider.center.z);
|
||||
markDebugMesh(mesh);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
function createTriMeshColliderDebugMesh(collider: GeneratedModelTriMeshCollider): Mesh {
|
||||
const geometry = new BufferGeometry();
|
||||
|
||||
geometry.setAttribute("position", new Float32BufferAttribute(collider.vertices, 3));
|
||||
geometry.setIndex(Array.from(collider.indices));
|
||||
|
||||
const mesh = new Mesh(geometry, createWireframeMaterial(DEBUG_COLLIDER_COLORS.static));
|
||||
markDebugMesh(mesh);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
function createHeightfieldColliderDebugMesh(collider: GeneratedModelHeightfieldCollider): Mesh {
|
||||
const vertices: number[] = [];
|
||||
const indices: number[] = [];
|
||||
const width = collider.maxX - collider.minX;
|
||||
const depth = collider.maxZ - collider.minZ;
|
||||
|
||||
for (let zIndex = 0; zIndex < collider.cols; zIndex += 1) {
|
||||
const zLerp = collider.cols === 1 ? 0 : zIndex / (collider.cols - 1);
|
||||
const z = collider.minZ + depth * zLerp;
|
||||
|
||||
for (let xIndex = 0; xIndex < collider.rows; xIndex += 1) {
|
||||
const xLerp = collider.rows === 1 ? 0 : xIndex / (collider.rows - 1);
|
||||
const x = collider.minX + width * xLerp;
|
||||
const y = collider.heights[xIndex + zIndex * collider.rows];
|
||||
|
||||
vertices.push(x, y, z);
|
||||
}
|
||||
}
|
||||
|
||||
for (let zIndex = 0; zIndex < collider.cols - 1; zIndex += 1) {
|
||||
for (let xIndex = 0; xIndex < collider.rows - 1; xIndex += 1) {
|
||||
const topLeft = xIndex + zIndex * collider.rows;
|
||||
const topRight = topLeft + 1;
|
||||
const bottomLeft = topLeft + collider.rows;
|
||||
const bottomRight = bottomLeft + 1;
|
||||
|
||||
indices.push(topLeft, bottomLeft, bottomRight, topLeft, bottomRight, topRight);
|
||||
}
|
||||
}
|
||||
|
||||
const geometry = new BufferGeometry();
|
||||
|
||||
geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
|
||||
geometry.setIndex(indices);
|
||||
|
||||
const mesh = new Mesh(geometry, createWireframeMaterial(DEBUG_COLLIDER_COLORS.terrain));
|
||||
markDebugMesh(mesh);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
function createCompoundColliderDebugGroup(collider: GeneratedModelCompoundCollider): Group {
|
||||
const group = new Group();
|
||||
|
||||
for (const piece of collider.pieces) {
|
||||
const points: Vector3[] = [];
|
||||
|
||||
for (let index = 0; index < piece.points.length; index += 3) {
|
||||
points.push(new Vector3(piece.points[index], piece.points[index + 1], piece.points[index + 2]));
|
||||
}
|
||||
|
||||
const mesh = new Mesh(new ConvexGeometry(points), createWireframeMaterial(DEBUG_COLLIDER_COLORS.dynamic));
|
||||
markDebugMesh(mesh);
|
||||
group.add(mesh);
|
||||
}
|
||||
|
||||
return group;
|
||||
}
|
||||
|
||||
export function createModelColliderDebugGroup(collider: GeneratedModelCollider): Group {
|
||||
const group = new Group();
|
||||
|
||||
switch (collider.kind) {
|
||||
case "box":
|
||||
group.add(createBoxColliderDebugMesh(collider));
|
||||
break;
|
||||
case "trimesh":
|
||||
group.add(createTriMeshColliderDebugMesh(collider));
|
||||
break;
|
||||
case "heightfield":
|
||||
group.add(createHeightfieldColliderDebugMesh(collider));
|
||||
break;
|
||||
case "compound":
|
||||
group.add(createCompoundColliderDebugGroup(collider));
|
||||
break;
|
||||
}
|
||||
|
||||
group.userData.nonPickable = true;
|
||||
return group;
|
||||
}
|
||||
|
||||
function disposeMaterial(material: Material | Material[]) {
|
||||
if (Array.isArray(material)) {
|
||||
for (const item of material) {
|
||||
item.dispose();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
material.dispose();
|
||||
}
|
||||
|
||||
export function disposeModelColliderDebugGroup(group: Group) {
|
||||
group.traverse((object) => {
|
||||
const maybeMesh = object as Mesh & { isMesh?: boolean };
|
||||
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return;
|
||||
}
|
||||
|
||||
maybeMesh.geometry.dispose();
|
||||
disposeMaterial(maybeMesh.material);
|
||||
});
|
||||
}
|
||||
682
src/geometry/model-instance-collider-generation.ts
Normal file
682
src/geometry/model-instance-collider-generation.ts
Normal file
@@ -0,0 +1,682 @@
|
||||
import {
|
||||
Euler,
|
||||
Group,
|
||||
MathUtils,
|
||||
Matrix4,
|
||||
Mesh,
|
||||
Quaternion,
|
||||
Vector3,
|
||||
type BufferGeometry
|
||||
} from "three";
|
||||
|
||||
import type { LoadedModelAsset } from "../assets/gltf-model-import";
|
||||
import type { ModelInstance, ModelInstanceCollisionMode } from "../assets/model-instances";
|
||||
import type { ModelAssetRecord } from "../assets/project-assets";
|
||||
import type { Vec3 } from "../core/vector";
|
||||
|
||||
const TERRAIN_GRID_EPSILON = 1e-4;
|
||||
const DYNAMIC_TRIANGLE_TARGET = 48;
|
||||
const DYNAMIC_SPLIT_DEPTH_LIMIT = 3;
|
||||
|
||||
interface LocalTriangle {
|
||||
readonly a: Vector3;
|
||||
readonly b: Vector3;
|
||||
readonly c: Vector3;
|
||||
}
|
||||
|
||||
interface LocalTriangleCluster {
|
||||
readonly triangles: LocalTriangle[];
|
||||
}
|
||||
|
||||
export interface GeneratedColliderBounds {
|
||||
min: Vec3;
|
||||
max: Vec3;
|
||||
}
|
||||
|
||||
export interface GeneratedModelColliderTransform {
|
||||
position: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
scale: Vec3;
|
||||
}
|
||||
|
||||
interface GeneratedModelColliderBase {
|
||||
source: "modelInstance";
|
||||
instanceId: string;
|
||||
assetId: string;
|
||||
mode: ModelInstanceCollisionMode;
|
||||
visible: boolean;
|
||||
transform: GeneratedModelColliderTransform;
|
||||
localBounds: GeneratedColliderBounds;
|
||||
worldBounds: GeneratedColliderBounds;
|
||||
}
|
||||
|
||||
export interface GeneratedModelBoxCollider extends GeneratedModelColliderBase {
|
||||
kind: "box";
|
||||
center: Vec3;
|
||||
size: Vec3;
|
||||
}
|
||||
|
||||
export interface GeneratedModelTriMeshCollider extends GeneratedModelColliderBase {
|
||||
kind: "trimesh";
|
||||
vertices: Float32Array;
|
||||
indices: Uint32Array;
|
||||
triangleCount: number;
|
||||
}
|
||||
|
||||
export interface GeneratedModelHeightfieldCollider extends GeneratedModelColliderBase {
|
||||
kind: "heightfield";
|
||||
rows: number;
|
||||
cols: number;
|
||||
heights: Float32Array;
|
||||
minX: number;
|
||||
maxX: number;
|
||||
minZ: number;
|
||||
maxZ: number;
|
||||
}
|
||||
|
||||
export interface GeneratedModelCompoundColliderPiece {
|
||||
id: string;
|
||||
points: Float32Array;
|
||||
localBounds: GeneratedColliderBounds;
|
||||
}
|
||||
|
||||
export interface GeneratedModelCompoundCollider extends GeneratedModelColliderBase {
|
||||
kind: "compound";
|
||||
pieces: GeneratedModelCompoundColliderPiece[];
|
||||
decomposition: "spatial-bisect";
|
||||
runtimeBehavior: "fixedQueryOnly";
|
||||
}
|
||||
|
||||
export type GeneratedModelCollider =
|
||||
| GeneratedModelBoxCollider
|
||||
| GeneratedModelTriMeshCollider
|
||||
| GeneratedModelHeightfieldCollider
|
||||
| GeneratedModelCompoundCollider;
|
||||
|
||||
export class ModelColliderGenerationError extends Error {
|
||||
readonly code: string;
|
||||
|
||||
constructor(code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "ModelColliderGenerationError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
function cloneVec3(vector: Vec3): Vec3 {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
|
||||
function vector3ToVec3(vector: Vector3): Vec3 {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
|
||||
function createBounds(min: Vector3, max: Vector3): GeneratedColliderBounds {
|
||||
return {
|
||||
min: vector3ToVec3(min),
|
||||
max: vector3ToVec3(max)
|
||||
};
|
||||
}
|
||||
|
||||
function createModelTransform(modelInstance: ModelInstance): GeneratedModelColliderTransform {
|
||||
return {
|
||||
position: cloneVec3(modelInstance.position),
|
||||
rotationDegrees: cloneVec3(modelInstance.rotationDegrees),
|
||||
scale: cloneVec3(modelInstance.scale)
|
||||
};
|
||||
}
|
||||
|
||||
function createModelTransformMatrix(modelInstance: ModelInstance): Matrix4 {
|
||||
const rotation = new Euler(
|
||||
MathUtils.degToRad(modelInstance.rotationDegrees.x),
|
||||
MathUtils.degToRad(modelInstance.rotationDegrees.y),
|
||||
MathUtils.degToRad(modelInstance.rotationDegrees.z),
|
||||
"XYZ"
|
||||
);
|
||||
const quaternion = new Quaternion().setFromEuler(rotation);
|
||||
|
||||
return new Matrix4().compose(
|
||||
new Vector3(modelInstance.position.x, modelInstance.position.y, modelInstance.position.z),
|
||||
quaternion,
|
||||
new Vector3(modelInstance.scale.x, modelInstance.scale.y, modelInstance.scale.z)
|
||||
);
|
||||
}
|
||||
|
||||
function computeBoundsFromPoints(points: Iterable<Vector3>): GeneratedColliderBounds {
|
||||
const min = new Vector3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
|
||||
const max = new Vector3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
|
||||
let hasPoint = false;
|
||||
|
||||
for (const point of points) {
|
||||
hasPoint = true;
|
||||
min.min(point);
|
||||
max.max(point);
|
||||
}
|
||||
|
||||
if (!hasPoint) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", "The selected model does not contain any collision-capable geometry.");
|
||||
}
|
||||
|
||||
return createBounds(min, max);
|
||||
}
|
||||
|
||||
function computeBoundsFromFloat32Points(points: Float32Array): GeneratedColliderBounds {
|
||||
if (points.length < 3) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", "The selected model does not contain any collision-capable geometry.");
|
||||
}
|
||||
|
||||
const min = new Vector3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
|
||||
const max = new Vector3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
|
||||
|
||||
for (let index = 0; index < points.length; index += 3) {
|
||||
min.x = Math.min(min.x, points[index]);
|
||||
min.y = Math.min(min.y, points[index + 1]);
|
||||
min.z = Math.min(min.z, points[index + 2]);
|
||||
max.x = Math.max(max.x, points[index]);
|
||||
max.y = Math.max(max.y, points[index + 1]);
|
||||
max.z = Math.max(max.z, points[index + 2]);
|
||||
}
|
||||
|
||||
return createBounds(min, max);
|
||||
}
|
||||
|
||||
function computeWorldBoundsFromLocalBox(localBounds: GeneratedColliderBounds, modelMatrix: Matrix4): GeneratedColliderBounds {
|
||||
const min = localBounds.min;
|
||||
const max = localBounds.max;
|
||||
const corners = [
|
||||
new Vector3(min.x, min.y, min.z),
|
||||
new Vector3(min.x, min.y, max.z),
|
||||
new Vector3(min.x, max.y, min.z),
|
||||
new Vector3(min.x, max.y, max.z),
|
||||
new Vector3(max.x, min.y, min.z),
|
||||
new Vector3(max.x, min.y, max.z),
|
||||
new Vector3(max.x, max.y, min.z),
|
||||
new Vector3(max.x, max.y, max.z)
|
||||
];
|
||||
|
||||
return computeBoundsFromPoints(corners.map((corner) => corner.applyMatrix4(modelMatrix)));
|
||||
}
|
||||
|
||||
interface PositionLikeAttribute {
|
||||
getX(index: number): number;
|
||||
getY(index: number): number;
|
||||
getZ(index: number): number;
|
||||
}
|
||||
|
||||
function readIndexedVertex(position: PositionLikeAttribute, index: number, matrix: Matrix4): Vector3 {
|
||||
return new Vector3(position.getX(index), position.getY(index), position.getZ(index)).applyMatrix4(matrix);
|
||||
}
|
||||
|
||||
function getMeshGeometry(object: Group | Mesh): BufferGeometry | null {
|
||||
const maybeMesh = object as Mesh & { isMesh?: boolean };
|
||||
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return maybeMesh.geometry;
|
||||
}
|
||||
|
||||
function collectMeshTriangleClusters(template: Group): LocalTriangleCluster[] {
|
||||
template.updateMatrixWorld(true);
|
||||
const clusters: LocalTriangleCluster[] = [];
|
||||
|
||||
template.traverse((object) => {
|
||||
const geometry = getMeshGeometry(object as Group | Mesh);
|
||||
|
||||
if (geometry === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const position = geometry.getAttribute("position");
|
||||
|
||||
if (position === undefined || position.itemSize < 3 || position.count < 3) {
|
||||
return;
|
||||
}
|
||||
|
||||
const matrix = object.matrixWorld;
|
||||
const index = geometry.getIndex();
|
||||
const triangles: LocalTriangle[] = [];
|
||||
|
||||
if (index === null) {
|
||||
for (let vertexIndex = 0; vertexIndex <= position.count - 3; vertexIndex += 3) {
|
||||
triangles.push({
|
||||
a: readIndexedVertex(position, vertexIndex, matrix),
|
||||
b: readIndexedVertex(position, vertexIndex + 1, matrix),
|
||||
c: readIndexedVertex(position, vertexIndex + 2, matrix)
|
||||
});
|
||||
}
|
||||
} else {
|
||||
for (let triangleIndex = 0; triangleIndex <= index.count - 3; triangleIndex += 3) {
|
||||
triangles.push({
|
||||
a: readIndexedVertex(position, index.getX(triangleIndex), matrix),
|
||||
b: readIndexedVertex(position, index.getX(triangleIndex + 1), matrix),
|
||||
c: readIndexedVertex(position, index.getX(triangleIndex + 2), matrix)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (triangles.length > 0) {
|
||||
clusters.push({
|
||||
triangles
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return clusters;
|
||||
}
|
||||
|
||||
function flattenTriangleClusters(clusters: LocalTriangleCluster[]): LocalTriangle[] {
|
||||
return clusters.flatMap((cluster) => cluster.triangles);
|
||||
}
|
||||
|
||||
function buildTriMeshBuffers(triangles: LocalTriangle[]): { vertices: Float32Array; indices: Uint32Array } {
|
||||
const vertices = new Float32Array(triangles.length * 9);
|
||||
const indices = new Uint32Array(triangles.length * 3);
|
||||
let vertexOffset = 0;
|
||||
|
||||
for (let triangleIndex = 0; triangleIndex < triangles.length; triangleIndex += 1) {
|
||||
const triangle = triangles[triangleIndex];
|
||||
vertices[vertexOffset] = triangle.a.x;
|
||||
vertices[vertexOffset + 1] = triangle.a.y;
|
||||
vertices[vertexOffset + 2] = triangle.a.z;
|
||||
vertices[vertexOffset + 3] = triangle.b.x;
|
||||
vertices[vertexOffset + 4] = triangle.b.y;
|
||||
vertices[vertexOffset + 5] = triangle.b.z;
|
||||
vertices[vertexOffset + 6] = triangle.c.x;
|
||||
vertices[vertexOffset + 7] = triangle.c.y;
|
||||
vertices[vertexOffset + 8] = triangle.c.z;
|
||||
indices[triangleIndex * 3] = triangleIndex * 3;
|
||||
indices[triangleIndex * 3 + 1] = triangleIndex * 3 + 1;
|
||||
indices[triangleIndex * 3 + 2] = triangleIndex * 3 + 2;
|
||||
vertexOffset += 9;
|
||||
}
|
||||
|
||||
return {
|
||||
vertices,
|
||||
indices
|
||||
};
|
||||
}
|
||||
|
||||
function computeClusterCentroid(triangles: LocalTriangle[]): Vec3 {
|
||||
const centroid = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
let pointCount = 0;
|
||||
|
||||
for (const triangle of triangles) {
|
||||
centroid.x += triangle.a.x + triangle.b.x + triangle.c.x;
|
||||
centroid.y += triangle.a.y + triangle.b.y + triangle.c.y;
|
||||
centroid.z += triangle.a.z + triangle.b.z + triangle.c.z;
|
||||
pointCount += 3;
|
||||
}
|
||||
|
||||
return {
|
||||
x: centroid.x / pointCount,
|
||||
y: centroid.y / pointCount,
|
||||
z: centroid.z / pointCount
|
||||
};
|
||||
}
|
||||
|
||||
function getTriangleBounds(triangles: LocalTriangle[]): GeneratedColliderBounds {
|
||||
return computeBoundsFromPoints(triangles.flatMap((triangle) => [triangle.a, triangle.b, triangle.c]));
|
||||
}
|
||||
|
||||
type TriangleClusterSplit =
|
||||
| {
|
||||
kind: "leaf";
|
||||
triangles: LocalTriangle[];
|
||||
}
|
||||
| {
|
||||
kind: "split";
|
||||
left: LocalTriangle[];
|
||||
right: LocalTriangle[];
|
||||
};
|
||||
|
||||
function splitTriangleCluster(triangles: LocalTriangle[], depth: number): TriangleClusterSplit {
|
||||
if (triangles.length <= DYNAMIC_TRIANGLE_TARGET || depth >= DYNAMIC_SPLIT_DEPTH_LIMIT) {
|
||||
return {
|
||||
kind: "leaf",
|
||||
triangles
|
||||
};
|
||||
}
|
||||
|
||||
const bounds = getTriangleBounds(triangles);
|
||||
const size = {
|
||||
x: bounds.max.x - bounds.min.x,
|
||||
y: bounds.max.y - bounds.min.y,
|
||||
z: bounds.max.z - bounds.min.z
|
||||
};
|
||||
const splitAxis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";
|
||||
const sortedTriangles = [...triangles].sort((left, right) => computeClusterCentroid([left])[splitAxis] - computeClusterCentroid([right])[splitAxis]);
|
||||
const splitIndex = Math.floor(sortedTriangles.length * 0.5);
|
||||
|
||||
if (splitIndex <= 0 || splitIndex >= sortedTriangles.length) {
|
||||
return {
|
||||
kind: "leaf",
|
||||
triangles
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "split",
|
||||
left: sortedTriangles.slice(0, splitIndex),
|
||||
right: sortedTriangles.slice(splitIndex)
|
||||
};
|
||||
}
|
||||
|
||||
function collectConvexHullPointClouds(cluster: LocalTriangle[], depth = 0): Float32Array[] {
|
||||
const split = splitTriangleCluster(cluster, depth);
|
||||
|
||||
if (split.kind === "leaf") {
|
||||
return [dedupeTriangleClusterPoints(split.triangles)];
|
||||
}
|
||||
|
||||
return [...collectConvexHullPointClouds(split.left, depth + 1), ...collectConvexHullPointClouds(split.right, depth + 1)];
|
||||
}
|
||||
|
||||
function quantizeCoordinate(value: number): string {
|
||||
return (Math.round(value / TERRAIN_GRID_EPSILON) * TERRAIN_GRID_EPSILON).toFixed(4);
|
||||
}
|
||||
|
||||
function dedupeTriangleClusterPoints(triangles: LocalTriangle[]): Float32Array {
|
||||
const pointLookup = new Map<string, Vec3>();
|
||||
|
||||
for (const triangle of triangles) {
|
||||
for (const point of [triangle.a, triangle.b, triangle.c]) {
|
||||
const key = `${quantizeCoordinate(point.x)}:${quantizeCoordinate(point.y)}:${quantizeCoordinate(point.z)}`;
|
||||
|
||||
if (!pointLookup.has(key)) {
|
||||
pointLookup.set(key, {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
z: point.z
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (pointLookup.size < 4) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"unsupported-dynamic-model-collider",
|
||||
"Dynamic collision requires volumetric geometry that can form at least one convex hull."
|
||||
);
|
||||
}
|
||||
|
||||
return new Float32Array(
|
||||
Array.from(pointLookup.values()).flatMap((point) => [point.x, point.y, point.z])
|
||||
);
|
||||
}
|
||||
|
||||
function buildSimpleBoxCollider(modelInstance: ModelInstance, asset: ModelAssetRecord): GeneratedModelBoxCollider {
|
||||
const boundingBox = asset.metadata.boundingBox;
|
||||
|
||||
if (boundingBox === null) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"missing-model-collider-bounds",
|
||||
`Model instance ${modelInstance.id} cannot use simple collision because the asset does not have a measurable bounding box.`
|
||||
);
|
||||
}
|
||||
|
||||
const localBounds = createBounds(
|
||||
new Vector3(boundingBox.min.x, boundingBox.min.y, boundingBox.min.z),
|
||||
new Vector3(boundingBox.max.x, boundingBox.max.y, boundingBox.max.z)
|
||||
);
|
||||
|
||||
return {
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: modelInstance.assetId,
|
||||
mode: "simple",
|
||||
kind: "box",
|
||||
visible: modelInstance.collision.visible,
|
||||
transform: createModelTransform(modelInstance),
|
||||
center: {
|
||||
x: (boundingBox.min.x + boundingBox.max.x) * 0.5,
|
||||
y: (boundingBox.min.y + boundingBox.max.y) * 0.5,
|
||||
z: (boundingBox.min.z + boundingBox.max.z) * 0.5
|
||||
},
|
||||
size: cloneVec3(boundingBox.size),
|
||||
localBounds,
|
||||
worldBounds: computeWorldBoundsFromLocalBox(localBounds, createModelTransformMatrix(modelInstance))
|
||||
};
|
||||
}
|
||||
|
||||
function buildTriMeshCollider(modelInstance: ModelInstance, asset: ModelAssetRecord, loadedAsset: LoadedModelAsset | undefined): GeneratedModelTriMeshCollider {
|
||||
if (loadedAsset === undefined) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"missing-model-collider-geometry",
|
||||
`Model instance ${modelInstance.id} cannot build ${modelInstance.collision.mode} collision until asset geometry has loaded.`
|
||||
);
|
||||
}
|
||||
|
||||
const triangles = flattenTriangleClusters(collectMeshTriangleClusters(loadedAsset.template));
|
||||
|
||||
if (triangles.length === 0) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"missing-model-collider-geometry",
|
||||
`Model instance ${modelInstance.id} cannot use ${modelInstance.collision.mode} collision because the asset has no mesh triangles.`
|
||||
);
|
||||
}
|
||||
|
||||
const buffers = buildTriMeshBuffers(triangles);
|
||||
const localBounds = computeBoundsFromFloat32Points(buffers.vertices);
|
||||
|
||||
return {
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: asset.id,
|
||||
mode: "static",
|
||||
kind: "trimesh",
|
||||
visible: modelInstance.collision.visible,
|
||||
transform: createModelTransform(modelInstance),
|
||||
vertices: buffers.vertices,
|
||||
indices: buffers.indices,
|
||||
triangleCount: triangles.length,
|
||||
localBounds,
|
||||
worldBounds: computeWorldBoundsFromLocalBox(localBounds, createModelTransformMatrix(modelInstance))
|
||||
};
|
||||
}
|
||||
|
||||
function buildTerrainCollider(
|
||||
modelInstance: ModelInstance,
|
||||
asset: ModelAssetRecord,
|
||||
loadedAsset: LoadedModelAsset | undefined
|
||||
): GeneratedModelHeightfieldCollider {
|
||||
if (loadedAsset === undefined) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"missing-model-collider-geometry",
|
||||
`Model instance ${modelInstance.id} cannot build terrain collision until asset geometry has loaded.`
|
||||
);
|
||||
}
|
||||
|
||||
const triangles = flattenTriangleClusters(collectMeshTriangleClusters(loadedAsset.template));
|
||||
|
||||
if (triangles.length === 0) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"missing-model-collider-geometry",
|
||||
`Model instance ${modelInstance.id} cannot use terrain collision because the asset has no mesh triangles.`
|
||||
);
|
||||
}
|
||||
|
||||
const heightLookup = new Map<string, { x: number; y: number; z: number }>();
|
||||
const xValues = new Map<string, number>();
|
||||
const zValues = new Map<string, number>();
|
||||
|
||||
for (const triangle of triangles) {
|
||||
for (const point of [triangle.a, triangle.b, triangle.c]) {
|
||||
const xKey = quantizeCoordinate(point.x);
|
||||
const zKey = quantizeCoordinate(point.z);
|
||||
const key = `${xKey}:${zKey}`;
|
||||
const previousPoint = heightLookup.get(key);
|
||||
|
||||
if (previousPoint !== undefined && Math.abs(previousPoint.y - point.y) > TERRAIN_GRID_EPSILON) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"unsupported-terrain-model-collider",
|
||||
`Model instance ${modelInstance.id} cannot use terrain collision because the source mesh is not a single-valued heightfield over X/Z.`
|
||||
);
|
||||
}
|
||||
|
||||
heightLookup.set(key, {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
z: point.z
|
||||
});
|
||||
xValues.set(xKey, point.x);
|
||||
zValues.set(zKey, point.z);
|
||||
}
|
||||
}
|
||||
|
||||
const sortedX = Array.from(xValues.values()).sort((left, right) => left - right);
|
||||
const sortedZ = Array.from(zValues.values()).sort((left, right) => left - right);
|
||||
|
||||
if (sortedX.length < 2 || sortedZ.length < 2) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"unsupported-terrain-model-collider",
|
||||
`Model instance ${modelInstance.id} cannot use terrain collision because the source mesh does not form a regular X/Z grid.`
|
||||
);
|
||||
}
|
||||
|
||||
const expectedTriangleCount = (sortedX.length - 1) * (sortedZ.length - 1) * 2;
|
||||
|
||||
if (triangles.length !== expectedTriangleCount) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"unsupported-terrain-model-collider",
|
||||
`Model instance ${modelInstance.id} cannot use terrain collision because the source mesh is not a clean regular-grid terrain surface.`
|
||||
);
|
||||
}
|
||||
|
||||
const heights = new Float32Array(sortedX.length * sortedZ.length);
|
||||
|
||||
for (let zIndex = 0; zIndex < sortedZ.length; zIndex += 1) {
|
||||
for (let xIndex = 0; xIndex < sortedX.length; xIndex += 1) {
|
||||
const key = `${quantizeCoordinate(sortedX[xIndex])}:${quantizeCoordinate(sortedZ[zIndex])}`;
|
||||
const point = heightLookup.get(key);
|
||||
|
||||
if (point === undefined) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"unsupported-terrain-model-collider",
|
||||
`Model instance ${modelInstance.id} cannot use terrain collision because the source mesh is missing one or more regular-grid height samples.`
|
||||
);
|
||||
}
|
||||
|
||||
heights[xIndex + zIndex * sortedX.length] = point.y;
|
||||
}
|
||||
}
|
||||
|
||||
const localBounds = computeBoundsFromPoints(
|
||||
Array.from(heightLookup.values(), (point) => new Vector3(point.x, point.y, point.z))
|
||||
);
|
||||
|
||||
return {
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: asset.id,
|
||||
mode: "terrain",
|
||||
kind: "heightfield",
|
||||
visible: modelInstance.collision.visible,
|
||||
transform: createModelTransform(modelInstance),
|
||||
rows: sortedX.length,
|
||||
cols: sortedZ.length,
|
||||
heights,
|
||||
minX: sortedX[0],
|
||||
maxX: sortedX.at(-1) ?? sortedX[0],
|
||||
minZ: sortedZ[0],
|
||||
maxZ: sortedZ.at(-1) ?? sortedZ[0],
|
||||
localBounds,
|
||||
worldBounds: computeWorldBoundsFromLocalBox(localBounds, createModelTransformMatrix(modelInstance))
|
||||
};
|
||||
}
|
||||
|
||||
function buildDynamicCollider(
|
||||
modelInstance: ModelInstance,
|
||||
asset: ModelAssetRecord,
|
||||
loadedAsset: LoadedModelAsset | undefined
|
||||
): GeneratedModelCompoundCollider {
|
||||
if (loadedAsset === undefined) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"missing-model-collider-geometry",
|
||||
`Model instance ${modelInstance.id} cannot build dynamic collision until asset geometry has loaded.`
|
||||
);
|
||||
}
|
||||
|
||||
const triangleClusters = collectMeshTriangleClusters(loadedAsset.template);
|
||||
|
||||
if (triangleClusters.length === 0) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"missing-model-collider-geometry",
|
||||
`Model instance ${modelInstance.id} cannot use dynamic collision because the asset has no mesh triangles.`
|
||||
);
|
||||
}
|
||||
|
||||
const pieces = triangleClusters
|
||||
.flatMap((cluster) => collectConvexHullPointClouds(cluster.triangles))
|
||||
.map((points, index) => ({
|
||||
id: `${modelInstance.id}-piece-${index + 1}`,
|
||||
points,
|
||||
localBounds: computeBoundsFromFloat32Points(points)
|
||||
}));
|
||||
|
||||
if (pieces.length === 0) {
|
||||
throw new ModelColliderGenerationError(
|
||||
"unsupported-dynamic-model-collider",
|
||||
`Model instance ${modelInstance.id} could not derive any convex pieces for dynamic collision.`
|
||||
);
|
||||
}
|
||||
|
||||
const localBounds = computeBoundsFromPoints(
|
||||
pieces.flatMap((piece) => {
|
||||
const points: Vector3[] = [];
|
||||
|
||||
for (let pointIndex = 0; pointIndex < piece.points.length; pointIndex += 3) {
|
||||
points.push(new Vector3(piece.points[pointIndex], piece.points[pointIndex + 1], piece.points[pointIndex + 2]));
|
||||
}
|
||||
|
||||
return points;
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: asset.id,
|
||||
mode: "dynamic",
|
||||
kind: "compound",
|
||||
visible: modelInstance.collision.visible,
|
||||
transform: createModelTransform(modelInstance),
|
||||
pieces,
|
||||
decomposition: "spatial-bisect",
|
||||
runtimeBehavior: "fixedQueryOnly",
|
||||
localBounds,
|
||||
worldBounds: computeWorldBoundsFromLocalBox(localBounds, createModelTransformMatrix(modelInstance))
|
||||
};
|
||||
}
|
||||
|
||||
export function buildGeneratedModelCollider(
|
||||
modelInstance: ModelInstance,
|
||||
asset: ModelAssetRecord,
|
||||
loadedAsset?: LoadedModelAsset
|
||||
): GeneratedModelCollider | null {
|
||||
switch (modelInstance.collision.mode) {
|
||||
case "none":
|
||||
return null;
|
||||
case "simple":
|
||||
return buildSimpleBoxCollider(modelInstance, asset);
|
||||
case "static":
|
||||
return buildTriMeshCollider(modelInstance, asset, loadedAsset);
|
||||
case "terrain":
|
||||
return buildTerrainCollider(modelInstance, asset, loadedAsset);
|
||||
case "dynamic":
|
||||
return buildDynamicCollider(modelInstance, asset, loadedAsset);
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,15 @@ const storageAccess = getBrowserStorageAccess();
|
||||
const bootstrapResult = loadOrCreateSceneDocument(storageAccess.storage);
|
||||
const editorStore = createEditorStore({
|
||||
initialDocument: bootstrapResult.document,
|
||||
initialViewportLayoutState: bootstrapResult.viewportLayoutState ?? undefined,
|
||||
storage: storageAccess.storage
|
||||
});
|
||||
const initialStatusMessage = [storageAccess.diagnostic, bootstrapResult.diagnostic].filter(Boolean).join(" ") || undefined;
|
||||
|
||||
if (import.meta.env.DEV) {
|
||||
(window as Window & { __webeditor3dEditorStore?: typeof editorStore }).__webeditor3dEditorStore = editorStore;
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(rootElement).render(
|
||||
<React.StrictMode>
|
||||
<App store={editorStore} initialStatusMessage={initialStatusMessage} />
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Euler, Vector3 } from "three";
|
||||
|
||||
import type { Vec3 } from "../core/vector";
|
||||
|
||||
import { FIRST_PERSON_PLAYER_SHAPE, resolveFirstPersonMotion } from "./player-collision";
|
||||
import { getFirstPersonPlayerEyeHeight } from "./player-collision";
|
||||
import type { NavigationController, RuntimeControllerContext } from "./navigation-controller";
|
||||
|
||||
const LOOK_SENSITIVITY = 0.0022;
|
||||
@@ -14,10 +14,10 @@ function clampPitch(pitchRadians: number): number {
|
||||
return Math.max(-MAX_PITCH_RADIANS, Math.min(MAX_PITCH_RADIANS, pitchRadians));
|
||||
}
|
||||
|
||||
function toEyePosition(feetPosition: Vec3): Vec3 {
|
||||
function toEyePosition(feetPosition: Vec3, eyeHeight: number): Vec3 {
|
||||
return {
|
||||
x: feetPosition.x,
|
||||
y: feetPosition.y + FIRST_PERSON_PLAYER_SHAPE.eyeHeight,
|
||||
y: feetPosition.y + eyeHeight,
|
||||
z: feetPosition.z
|
||||
};
|
||||
}
|
||||
@@ -95,6 +95,7 @@ export class FirstPersonNavigationController implements NavigationController {
|
||||
return;
|
||||
}
|
||||
|
||||
const playerShape = this.context.getRuntimeScene().playerCollider;
|
||||
const inputX = (this.pressedKeys.has("KeyD") ? 1 : 0) - (this.pressedKeys.has("KeyA") ? 1 : 0);
|
||||
const inputZ = (this.pressedKeys.has("KeyW") ? 1 : 0) - (this.pressedKeys.has("KeyS") ? 1 : 0);
|
||||
const inputLength = Math.hypot(inputX, inputZ);
|
||||
@@ -102,31 +103,40 @@ export class FirstPersonNavigationController implements NavigationController {
|
||||
let horizontalX = 0;
|
||||
let horizontalZ = 0;
|
||||
|
||||
if (inputLength > 0) {
|
||||
const normalizedInputX = inputX / inputLength;
|
||||
const normalizedInputZ = inputZ / inputLength;
|
||||
const moveDistance = MOVE_SPEED * dt;
|
||||
if (inputLength > 0) {
|
||||
const normalizedInputX = inputX / inputLength;
|
||||
const normalizedInputZ = inputZ / inputLength;
|
||||
const moveDistance = MOVE_SPEED * dt;
|
||||
|
||||
this.forwardVector.set(Math.sin(this.yawRadians), 0, Math.cos(this.yawRadians));
|
||||
this.rightVector.set(-Math.cos(this.yawRadians), 0, Math.sin(this.yawRadians));
|
||||
this.forwardVector.set(Math.sin(this.yawRadians), 0, Math.cos(this.yawRadians));
|
||||
this.rightVector.set(-Math.cos(this.yawRadians), 0, Math.sin(this.yawRadians));
|
||||
|
||||
horizontalX = (this.forwardVector.x * normalizedInputZ + this.rightVector.x * normalizedInputX) * moveDistance;
|
||||
horizontalZ = (this.forwardVector.z * normalizedInputZ + this.rightVector.z * normalizedInputX) * moveDistance;
|
||||
}
|
||||
horizontalX = (this.forwardVector.x * normalizedInputZ + this.rightVector.x * normalizedInputX) * moveDistance;
|
||||
horizontalZ = (this.forwardVector.z * normalizedInputZ + this.rightVector.z * normalizedInputX) * moveDistance;
|
||||
}
|
||||
|
||||
this.verticalVelocity -= GRAVITY * dt;
|
||||
if (playerShape.mode === "none") {
|
||||
this.verticalVelocity = 0;
|
||||
} else {
|
||||
this.verticalVelocity -= GRAVITY * dt;
|
||||
}
|
||||
|
||||
const resolvedMotion = resolveFirstPersonMotion(
|
||||
const resolvedMotion = this.context.resolveFirstPersonMotion(
|
||||
this.feetPosition,
|
||||
{
|
||||
x: horizontalX,
|
||||
y: this.verticalVelocity * dt,
|
||||
y: playerShape.mode === "none" ? 0 : this.verticalVelocity * dt,
|
||||
z: horizontalZ
|
||||
},
|
||||
FIRST_PERSON_PLAYER_SHAPE,
|
||||
this.context.getRuntimeScene().colliders
|
||||
playerShape
|
||||
);
|
||||
|
||||
if (resolvedMotion === null) {
|
||||
this.updateCameraTransform();
|
||||
this.publishTelemetry();
|
||||
return;
|
||||
}
|
||||
|
||||
this.feetPosition = resolvedMotion.feetPosition;
|
||||
this.grounded = resolvedMotion.grounded;
|
||||
|
||||
@@ -155,7 +165,7 @@ export class FirstPersonNavigationController implements NavigationController {
|
||||
return;
|
||||
}
|
||||
|
||||
const eyePosition = toEyePosition(this.feetPosition);
|
||||
const eyePosition = toEyePosition(this.feetPosition, getFirstPersonPlayerEyeHeight(this.context.getRuntimeScene().playerCollider));
|
||||
this.cameraRotation.x = this.pitchRadians;
|
||||
// Authoring yaw treats 0 degrees as facing +Z, while a three.js camera
|
||||
// looks down -Z by default. Offset by 180 degrees so runtime view matches
|
||||
@@ -176,7 +186,7 @@ export class FirstPersonNavigationController implements NavigationController {
|
||||
feetPosition: {
|
||||
...this.feetPosition
|
||||
},
|
||||
eyePosition: toEyePosition(this.feetPosition),
|
||||
eyePosition: toEyePosition(this.feetPosition, getFirstPersonPlayerEyeHeight(this.context.getRuntimeScene().playerCollider)),
|
||||
grounded: this.grounded,
|
||||
pointerLocked: this.pointerLocked,
|
||||
spawn: this.context.getRuntimeScene().spawn
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { PerspectiveCamera } from "three";
|
||||
|
||||
import type { Vec3 } from "../core/vector";
|
||||
|
||||
import type { FirstPersonPlayerShape, ResolvedPlayerMotion } from "./player-collision";
|
||||
import type { RuntimeNavigationMode, RuntimeSceneDefinition, RuntimeSpawnPoint } from "./runtime-scene-build";
|
||||
|
||||
export interface FirstPersonTelemetry {
|
||||
@@ -16,6 +17,7 @@ export interface RuntimeControllerContext {
|
||||
camera: PerspectiveCamera;
|
||||
domElement: HTMLCanvasElement;
|
||||
getRuntimeScene(): RuntimeSceneDefinition;
|
||||
resolveFirstPersonMotion(feetPosition: Vec3, motion: Vec3, shape: FirstPersonPlayerShape): ResolvedPlayerMotion | null;
|
||||
setRuntimeMessage(message: string | null): void;
|
||||
setFirstPersonTelemetry(telemetry: FirstPersonTelemetry | null): void;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import type { Vec3 } from "../core/vector";
|
||||
|
||||
import type { RuntimeBoxCollider } from "./runtime-scene-build";
|
||||
|
||||
export interface FirstPersonPlayerShape {
|
||||
radius: number;
|
||||
height: number;
|
||||
eyeHeight: number;
|
||||
}
|
||||
export type FirstPersonPlayerShape =
|
||||
| {
|
||||
mode: "capsule";
|
||||
radius: number;
|
||||
height: number;
|
||||
eyeHeight: number;
|
||||
}
|
||||
| {
|
||||
mode: "box";
|
||||
size: Vec3;
|
||||
eyeHeight: number;
|
||||
}
|
||||
| {
|
||||
mode: "none";
|
||||
eyeHeight: number;
|
||||
};
|
||||
|
||||
export interface ResolvedPlayerMotion {
|
||||
feetPosition: Vec3;
|
||||
@@ -19,131 +28,23 @@ export interface ResolvedPlayerMotion {
|
||||
}
|
||||
|
||||
export const FIRST_PERSON_PLAYER_SHAPE: FirstPersonPlayerShape = {
|
||||
mode: "capsule",
|
||||
radius: 0.3,
|
||||
height: 1.8,
|
||||
eyeHeight: 1.6
|
||||
};
|
||||
|
||||
type Axis = "x" | "y" | "z";
|
||||
|
||||
interface RuntimeAabb {
|
||||
min: Vec3;
|
||||
max: Vec3;
|
||||
export function getFirstPersonPlayerEyeHeight(shape: FirstPersonPlayerShape): number {
|
||||
return shape.eyeHeight;
|
||||
}
|
||||
|
||||
function createPlayerAabb(feetPosition: Vec3, shape: FirstPersonPlayerShape): RuntimeAabb {
|
||||
return {
|
||||
min: {
|
||||
x: feetPosition.x - shape.radius,
|
||||
y: feetPosition.y,
|
||||
z: feetPosition.z - shape.radius
|
||||
},
|
||||
max: {
|
||||
x: feetPosition.x + shape.radius,
|
||||
y: feetPosition.y + shape.height,
|
||||
z: feetPosition.z + shape.radius
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function rangesOverlap(minA: number, maxA: number, minB: number, maxB: number): boolean {
|
||||
return minA < maxB && maxA > minB;
|
||||
}
|
||||
|
||||
function resolveAxis(
|
||||
axis: Axis,
|
||||
nextFeetPosition: Vec3,
|
||||
delta: number,
|
||||
shape: FirstPersonPlayerShape,
|
||||
colliders: RuntimeBoxCollider[]
|
||||
): { collided: boolean; grounded: boolean } {
|
||||
if (delta === 0) {
|
||||
return {
|
||||
collided: false,
|
||||
grounded: false
|
||||
};
|
||||
export function getFirstPersonPlayerHeight(shape: FirstPersonPlayerShape): number | null {
|
||||
switch (shape.mode) {
|
||||
case "capsule":
|
||||
return shape.height;
|
||||
case "box":
|
||||
return shape.size.y;
|
||||
case "none":
|
||||
return null;
|
||||
}
|
||||
|
||||
nextFeetPosition[axis] += delta;
|
||||
|
||||
let collided = false;
|
||||
let grounded = false;
|
||||
|
||||
for (const collider of colliders) {
|
||||
const playerAabb = createPlayerAabb(nextFeetPosition, shape);
|
||||
const overlapsOtherAxes =
|
||||
axis === "x"
|
||||
? rangesOverlap(playerAabb.min.y, playerAabb.max.y, collider.min.y, collider.max.y) &&
|
||||
rangesOverlap(playerAabb.min.z, playerAabb.max.z, collider.min.z, collider.max.z)
|
||||
: axis === "y"
|
||||
? rangesOverlap(playerAabb.min.x, playerAabb.max.x, collider.min.x, collider.max.x) &&
|
||||
rangesOverlap(playerAabb.min.z, playerAabb.max.z, collider.min.z, collider.max.z)
|
||||
: rangesOverlap(playerAabb.min.x, playerAabb.max.x, collider.min.x, collider.max.x) &&
|
||||
rangesOverlap(playerAabb.min.y, playerAabb.max.y, collider.min.y, collider.max.y);
|
||||
|
||||
if (!overlapsOtherAxes) {
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (axis) {
|
||||
case "x":
|
||||
if (delta > 0 && playerAabb.max.x > collider.min.x && playerAabb.min.x < collider.min.x) {
|
||||
nextFeetPosition.x = collider.min.x - shape.radius;
|
||||
collided = true;
|
||||
} else if (delta < 0 && playerAabb.min.x < collider.max.x && playerAabb.max.x > collider.max.x) {
|
||||
nextFeetPosition.x = collider.max.x + shape.radius;
|
||||
collided = true;
|
||||
}
|
||||
break;
|
||||
case "y":
|
||||
if (delta > 0 && playerAabb.max.y > collider.min.y && playerAabb.min.y < collider.min.y) {
|
||||
nextFeetPosition.y = collider.min.y - shape.height;
|
||||
collided = true;
|
||||
} else if (delta < 0 && playerAabb.min.y < collider.max.y && playerAabb.max.y > collider.max.y) {
|
||||
nextFeetPosition.y = collider.max.y;
|
||||
collided = true;
|
||||
grounded = true;
|
||||
}
|
||||
break;
|
||||
case "z":
|
||||
if (delta > 0 && playerAabb.max.z > collider.min.z && playerAabb.min.z < collider.min.z) {
|
||||
nextFeetPosition.z = collider.min.z - shape.radius;
|
||||
collided = true;
|
||||
} else if (delta < 0 && playerAabb.min.z < collider.max.z && playerAabb.max.z > collider.max.z) {
|
||||
nextFeetPosition.z = collider.max.z + shape.radius;
|
||||
collided = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
collided,
|
||||
grounded
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveFirstPersonMotion(
|
||||
feetPosition: Vec3,
|
||||
motion: Vec3,
|
||||
shape: FirstPersonPlayerShape,
|
||||
colliders: RuntimeBoxCollider[]
|
||||
): ResolvedPlayerMotion {
|
||||
const nextFeetPosition = {
|
||||
...feetPosition
|
||||
};
|
||||
|
||||
const xResolution = resolveAxis("x", nextFeetPosition, motion.x, shape, colliders);
|
||||
const zResolution = resolveAxis("z", nextFeetPosition, motion.z, shape, colliders);
|
||||
const yResolution = resolveAxis("y", nextFeetPosition, motion.y, shape, colliders);
|
||||
|
||||
return {
|
||||
feetPosition: nextFeetPosition,
|
||||
grounded: yResolution.grounded,
|
||||
collidedAxes: {
|
||||
x: xResolution.collided,
|
||||
y: yResolution.collided,
|
||||
z: zResolution.collided
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
357
src/runtime-three/rapier-collision-world.ts
Normal file
357
src/runtime-three/rapier-collision-world.ts
Normal file
@@ -0,0 +1,357 @@
|
||||
import RAPIER from "@dimforge/rapier3d-compat";
|
||||
import { Euler, MathUtils, Quaternion } from "three";
|
||||
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import type {
|
||||
GeneratedModelBoxCollider,
|
||||
GeneratedModelCollider,
|
||||
GeneratedModelCompoundCollider,
|
||||
GeneratedModelHeightfieldCollider,
|
||||
GeneratedModelTriMeshCollider
|
||||
} from "../geometry/model-instance-collider-generation";
|
||||
|
||||
import type { FirstPersonPlayerShape, ResolvedPlayerMotion } from "./player-collision";
|
||||
import type { RuntimeBoxCollider, RuntimeSceneCollider } from "./runtime-scene-build";
|
||||
|
||||
const CHARACTER_CONTROLLER_OFFSET = 0.01;
|
||||
const COLLISION_EPSILON = 1e-5;
|
||||
|
||||
let rapierInitPromise: Promise<typeof RAPIER> | null = null;
|
||||
|
||||
function componentScale(vector: Vec3, scale: Vec3): Vec3 {
|
||||
return {
|
||||
x: vector.x * scale.x,
|
||||
y: vector.y * scale.y,
|
||||
z: vector.z * scale.z
|
||||
};
|
||||
}
|
||||
|
||||
function createRapierQuaternion(rotationDegrees: Vec3): RAPIER.Rotation {
|
||||
const quaternion = new Quaternion().setFromEuler(
|
||||
new Euler(
|
||||
MathUtils.degToRad(rotationDegrees.x),
|
||||
MathUtils.degToRad(rotationDegrees.y),
|
||||
MathUtils.degToRad(rotationDegrees.z),
|
||||
"XYZ"
|
||||
)
|
||||
);
|
||||
|
||||
return {
|
||||
x: quaternion.x,
|
||||
y: quaternion.y,
|
||||
z: quaternion.z,
|
||||
w: quaternion.w
|
||||
};
|
||||
}
|
||||
|
||||
function scaleVertices(vertices: Float32Array, scale: Vec3): Float32Array {
|
||||
const scaledVertices = new Float32Array(vertices.length);
|
||||
|
||||
for (let index = 0; index < vertices.length; index += 3) {
|
||||
scaledVertices[index] = vertices[index] * scale.x;
|
||||
scaledVertices[index + 1] = vertices[index + 1] * scale.y;
|
||||
scaledVertices[index + 2] = vertices[index + 2] * scale.z;
|
||||
}
|
||||
|
||||
return scaledVertices;
|
||||
}
|
||||
|
||||
function scaleBoundsCenter(bounds: { min: Vec3; max: Vec3 }, scale: Vec3): Vec3 {
|
||||
return {
|
||||
x: ((bounds.min.x + bounds.max.x) * 0.5) * scale.x,
|
||||
y: ((bounds.min.y + bounds.max.y) * 0.5) * scale.y,
|
||||
z: ((bounds.min.z + bounds.max.z) * 0.5) * scale.z
|
||||
};
|
||||
}
|
||||
|
||||
function createRapierHeightfieldHeights(collider: GeneratedModelHeightfieldCollider): Float32Array {
|
||||
const heights = new Float32Array(collider.heights.length);
|
||||
|
||||
// Rapier's heightfield samples are column-major, with the Z axis varying
|
||||
// fastest inside each X column. Our generated collider stores X-major rows
|
||||
// for easier editor/debug mesh reconstruction, so transpose here.
|
||||
for (let zIndex = 0; zIndex < collider.cols; zIndex += 1) {
|
||||
for (let xIndex = 0; xIndex < collider.rows; xIndex += 1) {
|
||||
heights[zIndex + xIndex * collider.cols] = collider.heights[xIndex + zIndex * collider.rows];
|
||||
}
|
||||
}
|
||||
|
||||
return heights;
|
||||
}
|
||||
|
||||
function createFixedBodyForModelCollider(world: RAPIER.World, collider: GeneratedModelCollider): RAPIER.RigidBody {
|
||||
return world.createRigidBody(
|
||||
RAPIER.RigidBodyDesc.fixed()
|
||||
.setTranslation(collider.transform.position.x, collider.transform.position.y, collider.transform.position.z)
|
||||
.setRotation(createRapierQuaternion(collider.transform.rotationDegrees))
|
||||
);
|
||||
}
|
||||
|
||||
function attachBrushCollider(world: RAPIER.World, collider: RuntimeBoxCollider) {
|
||||
const body = world.createRigidBody(
|
||||
RAPIER.RigidBodyDesc.fixed()
|
||||
.setTranslation(collider.center.x, collider.center.y, collider.center.z)
|
||||
.setRotation(createRapierQuaternion(collider.rotationDegrees))
|
||||
);
|
||||
const halfExtents = {
|
||||
x: collider.size.x * 0.5,
|
||||
y: collider.size.y * 0.5,
|
||||
z: collider.size.z * 0.5
|
||||
};
|
||||
|
||||
world.createCollider(RAPIER.ColliderDesc.cuboid(halfExtents.x, halfExtents.y, halfExtents.z), body);
|
||||
}
|
||||
|
||||
function attachSimpleModelCollider(world: RAPIER.World, collider: GeneratedModelBoxCollider) {
|
||||
const body = createFixedBodyForModelCollider(world, collider);
|
||||
const scaledCenter = componentScale(collider.center, collider.transform.scale);
|
||||
const scaledHalfExtents = componentScale(
|
||||
{
|
||||
x: collider.size.x * 0.5,
|
||||
y: collider.size.y * 0.5,
|
||||
z: collider.size.z * 0.5
|
||||
},
|
||||
collider.transform.scale
|
||||
);
|
||||
|
||||
world.createCollider(
|
||||
RAPIER.ColliderDesc.cuboid(scaledHalfExtents.x, scaledHalfExtents.y, scaledHalfExtents.z).setTranslation(
|
||||
scaledCenter.x,
|
||||
scaledCenter.y,
|
||||
scaledCenter.z
|
||||
),
|
||||
body
|
||||
);
|
||||
}
|
||||
|
||||
function attachStaticModelCollider(world: RAPIER.World, collider: GeneratedModelTriMeshCollider) {
|
||||
const body = createFixedBodyForModelCollider(world, collider);
|
||||
world.createCollider(RAPIER.ColliderDesc.trimesh(scaleVertices(collider.vertices, collider.transform.scale), collider.indices), body);
|
||||
}
|
||||
|
||||
function attachTerrainModelCollider(world: RAPIER.World, collider: GeneratedModelHeightfieldCollider) {
|
||||
if (collider.rows < 2 || collider.cols < 2) {
|
||||
throw new Error(`Terrain collider ${collider.instanceId} must have at least a 2x2 height sample grid.`);
|
||||
}
|
||||
|
||||
const body = createFixedBodyForModelCollider(world, collider);
|
||||
const center = scaleBoundsCenter(
|
||||
{
|
||||
min: {
|
||||
x: collider.minX,
|
||||
y: 0,
|
||||
z: collider.minZ
|
||||
},
|
||||
max: {
|
||||
x: collider.maxX,
|
||||
y: 0,
|
||||
z: collider.maxZ
|
||||
}
|
||||
},
|
||||
collider.transform.scale
|
||||
);
|
||||
const rowSubdivisions = collider.rows - 1;
|
||||
const colSubdivisions = collider.cols - 1;
|
||||
|
||||
world.createCollider(
|
||||
// Rapier expects the number of grid subdivisions here, while our generated
|
||||
// collider stores the sampled height grid dimensions.
|
||||
RAPIER.ColliderDesc.heightfield(rowSubdivisions, colSubdivisions, createRapierHeightfieldHeights(collider), {
|
||||
x: (collider.maxX - collider.minX) * collider.transform.scale.x,
|
||||
y: collider.transform.scale.y,
|
||||
z: (collider.maxZ - collider.minZ) * collider.transform.scale.z
|
||||
}).setTranslation(center.x, center.y, center.z),
|
||||
body
|
||||
);
|
||||
}
|
||||
|
||||
function attachDynamicModelCollider(world: RAPIER.World, collider: GeneratedModelCompoundCollider) {
|
||||
const body = createFixedBodyForModelCollider(world, collider);
|
||||
|
||||
for (const piece of collider.pieces) {
|
||||
const scaledPoints = scaleVertices(piece.points, collider.transform.scale);
|
||||
const descriptor = RAPIER.ColliderDesc.convexHull(scaledPoints);
|
||||
|
||||
if (descriptor === null) {
|
||||
throw new Error(`Dynamic collider piece ${piece.id} could not form a valid convex hull.`);
|
||||
}
|
||||
|
||||
world.createCollider(descriptor, body);
|
||||
}
|
||||
}
|
||||
|
||||
function attachModelCollider(world: RAPIER.World, collider: GeneratedModelCollider) {
|
||||
switch (collider.kind) {
|
||||
case "box":
|
||||
attachSimpleModelCollider(world, collider);
|
||||
break;
|
||||
case "trimesh":
|
||||
attachStaticModelCollider(world, collider);
|
||||
break;
|
||||
case "heightfield":
|
||||
attachTerrainModelCollider(world, collider);
|
||||
break;
|
||||
case "compound":
|
||||
attachDynamicModelCollider(world, collider);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function feetPositionToColliderCenter(feetPosition: Vec3, shape: FirstPersonPlayerShape): Vec3 {
|
||||
switch (shape.mode) {
|
||||
case "capsule": {
|
||||
const cylindricalHalfHeight = Math.max(0, (shape.height - shape.radius * 2) * 0.5);
|
||||
|
||||
return {
|
||||
x: feetPosition.x,
|
||||
y: feetPosition.y + shape.radius + cylindricalHalfHeight,
|
||||
z: feetPosition.z
|
||||
};
|
||||
}
|
||||
case "box":
|
||||
return {
|
||||
x: feetPosition.x,
|
||||
y: feetPosition.y + shape.size.y * 0.5,
|
||||
z: feetPosition.z
|
||||
};
|
||||
case "none":
|
||||
return {
|
||||
...feetPosition
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function colliderCenterToFeetPosition(center: Vec3, shape: FirstPersonPlayerShape): Vec3 {
|
||||
switch (shape.mode) {
|
||||
case "capsule": {
|
||||
const cylindricalHalfHeight = Math.max(0, (shape.height - shape.radius * 2) * 0.5);
|
||||
|
||||
return {
|
||||
x: center.x,
|
||||
y: center.y - (shape.radius + cylindricalHalfHeight),
|
||||
z: center.z
|
||||
};
|
||||
}
|
||||
case "box":
|
||||
return {
|
||||
x: center.x,
|
||||
y: center.y - shape.size.y * 0.5,
|
||||
z: center.z
|
||||
};
|
||||
case "none":
|
||||
return {
|
||||
...center
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function createPlayerCollider(world: RAPIER.World, rapier: typeof RAPIER, playerShape: FirstPersonPlayerShape): RAPIER.Collider | null {
|
||||
switch (playerShape.mode) {
|
||||
case "capsule":
|
||||
return world.createCollider(
|
||||
rapier.ColliderDesc.capsule(Math.max(0, (playerShape.height - playerShape.radius * 2) * 0.5), playerShape.radius)
|
||||
);
|
||||
case "box":
|
||||
return world.createCollider(
|
||||
rapier.ColliderDesc.cuboid(playerShape.size.x * 0.5, playerShape.size.y * 0.5, playerShape.size.z * 0.5)
|
||||
);
|
||||
case "none":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function initializeRapierCollisionWorld(): Promise<typeof RAPIER> {
|
||||
rapierInitPromise ??= RAPIER.init().then(() => RAPIER);
|
||||
return rapierInitPromise;
|
||||
}
|
||||
|
||||
export class RapierCollisionWorld {
|
||||
static async create(colliders: RuntimeSceneCollider[], playerShape: FirstPersonPlayerShape): Promise<RapierCollisionWorld> {
|
||||
const rapier = await initializeRapierCollisionWorld();
|
||||
const world = new rapier.World({
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
});
|
||||
|
||||
for (const collider of colliders) {
|
||||
if (collider.source === "brush") {
|
||||
attachBrushCollider(world, collider);
|
||||
continue;
|
||||
}
|
||||
|
||||
attachModelCollider(world, collider);
|
||||
}
|
||||
|
||||
const playerCollider = createPlayerCollider(world, rapier, playerShape);
|
||||
const characterController = playerCollider === null ? null : world.createCharacterController(CHARACTER_CONTROLLER_OFFSET);
|
||||
|
||||
if (characterController !== null) {
|
||||
characterController.setUp({ x: 0, y: 1, z: 0 });
|
||||
characterController.setSlideEnabled(true);
|
||||
characterController.enableSnapToGround(0.2);
|
||||
characterController.enableAutostep(0.35, 0.15, false);
|
||||
characterController.setMaxSlopeClimbAngle(Math.PI * 0.45);
|
||||
characterController.setMinSlopeSlideAngle(Math.PI * 0.5);
|
||||
}
|
||||
|
||||
world.step();
|
||||
|
||||
return new RapierCollisionWorld(world, characterController, playerCollider);
|
||||
}
|
||||
|
||||
private constructor(
|
||||
private readonly world: RAPIER.World,
|
||||
private readonly characterController: RAPIER.KinematicCharacterController | null,
|
||||
private readonly playerCollider: RAPIER.Collider | null
|
||||
) {}
|
||||
|
||||
resolveFirstPersonMotion(feetPosition: Vec3, motion: Vec3, shape: FirstPersonPlayerShape): ResolvedPlayerMotion {
|
||||
if (this.playerCollider === null || this.characterController === null || shape.mode === "none") {
|
||||
return {
|
||||
feetPosition: {
|
||||
x: feetPosition.x + motion.x,
|
||||
y: feetPosition.y + motion.y,
|
||||
z: feetPosition.z + motion.z
|
||||
},
|
||||
grounded: false,
|
||||
collidedAxes: {
|
||||
x: false,
|
||||
y: false,
|
||||
z: false
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const currentCenter = feetPositionToColliderCenter(feetPosition, shape);
|
||||
this.playerCollider.setTranslation(currentCenter);
|
||||
this.characterController.computeColliderMovement(this.playerCollider, motion);
|
||||
|
||||
const correctedMovement = this.characterController.computedMovement();
|
||||
const collidedAxes = {
|
||||
x: Math.abs(correctedMovement.x - motion.x) > COLLISION_EPSILON,
|
||||
y: Math.abs(correctedMovement.y - motion.y) > COLLISION_EPSILON,
|
||||
z: Math.abs(correctedMovement.z - motion.z) > COLLISION_EPSILON
|
||||
};
|
||||
const nextCenter = {
|
||||
x: currentCenter.x + correctedMovement.x,
|
||||
y: currentCenter.y + correctedMovement.y,
|
||||
z: currentCenter.z + correctedMovement.z
|
||||
};
|
||||
|
||||
this.playerCollider.setTranslation(nextCenter);
|
||||
|
||||
return {
|
||||
feetPosition: colliderCenterToFeetPosition(nextCenter, shape),
|
||||
grounded: this.characterController.computedGrounded() || (motion.y < 0 && collidedAxes.y),
|
||||
collidedAxes
|
||||
};
|
||||
}
|
||||
|
||||
dispose() {
|
||||
if (this.characterController !== null) {
|
||||
this.world.removeCharacterController(this.characterController);
|
||||
}
|
||||
this.world.free();
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
|
||||
import { FirstPersonNavigationController } from "./first-person-navigation-controller";
|
||||
import type { FirstPersonTelemetry, NavigationController, RuntimeControllerContext } from "./navigation-controller";
|
||||
import { RapierCollisionWorld } from "./rapier-collision-world";
|
||||
import { RuntimeInteractionSystem, type RuntimeInteractionDispatcher, type RuntimeInteractionPrompt } from "./runtime-interaction-system";
|
||||
import { RuntimeAudioSystem } from "./runtime-audio-system";
|
||||
import { OrbitVisitorNavigationController } from "./orbit-visitor-navigation-controller";
|
||||
@@ -85,6 +86,8 @@ export class RuntimeHost {
|
||||
private readonly controllerContext: RuntimeControllerContext;
|
||||
private readonly renderer: WebGLRenderer | null;
|
||||
private runtimeScene: RuntimeSceneDefinition | null = null;
|
||||
private collisionWorld: RapierCollisionWorld | null = null;
|
||||
private collisionWorldRequestId = 0;
|
||||
private currentWorld: RuntimeSceneDefinition["world"] | null = null;
|
||||
private currentAdvancedRenderingSettings: AdvancedRenderingSettings | null = null;
|
||||
private advancedRenderingComposer: EffectComposer | null = null;
|
||||
@@ -131,6 +134,7 @@ export class RuntimeHost {
|
||||
|
||||
return this.runtimeScene;
|
||||
},
|
||||
resolveFirstPersonMotion: (feetPosition, motion, shape) => this.collisionWorld?.resolveFirstPersonMotion(feetPosition, motion, shape) ?? null,
|
||||
setRuntimeMessage: (message) => {
|
||||
if (message === this.currentRuntimeMessage) {
|
||||
return;
|
||||
@@ -171,6 +175,7 @@ export class RuntimeHost {
|
||||
this.rebuildLocalLights(runtimeScene.localLights);
|
||||
this.rebuildBrushMeshes(runtimeScene.brushes);
|
||||
this.rebuildModelInstances(runtimeScene.modelInstances);
|
||||
void this.rebuildCollisionWorld(runtimeScene.colliders, runtimeScene.playerCollider);
|
||||
this.audioSystem.loadScene(runtimeScene);
|
||||
}
|
||||
|
||||
@@ -244,6 +249,8 @@ export class RuntimeHost {
|
||||
this.clearLocalLights();
|
||||
this.clearBrushMeshes();
|
||||
this.clearModelInstances();
|
||||
this.collisionWorldRequestId += 1;
|
||||
this.clearCollisionWorld();
|
||||
this.audioSystem.dispose();
|
||||
this.advancedRenderingComposer?.dispose();
|
||||
this.advancedRenderingComposer = null;
|
||||
@@ -306,6 +313,36 @@ export class RuntimeHost {
|
||||
this.applyShadowState();
|
||||
}
|
||||
|
||||
private async rebuildCollisionWorld(colliders: RuntimeSceneDefinition["colliders"], playerShape: RuntimeSceneDefinition["playerCollider"]) {
|
||||
const requestId = ++this.collisionWorldRequestId;
|
||||
|
||||
this.clearCollisionWorld();
|
||||
|
||||
try {
|
||||
const nextCollisionWorld = await RapierCollisionWorld.create(colliders, playerShape);
|
||||
|
||||
if (requestId !== this.collisionWorldRequestId) {
|
||||
nextCollisionWorld.dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
this.collisionWorld = nextCollisionWorld;
|
||||
} catch (error) {
|
||||
if (requestId !== this.collisionWorldRequestId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : "Runner collision initialization failed.";
|
||||
this.currentRuntimeMessage = `Runner collision initialization failed: ${message}`;
|
||||
this.runtimeMessageHandler?.(this.currentRuntimeMessage);
|
||||
}
|
||||
}
|
||||
|
||||
private clearCollisionWorld() {
|
||||
this.collisionWorld?.dispose();
|
||||
this.collisionWorld = null;
|
||||
}
|
||||
|
||||
private syncAdvancedRenderingComposer(settings: AdvancedRenderingSettings) {
|
||||
if (this.renderer === null) {
|
||||
return;
|
||||
@@ -437,6 +474,11 @@ export class RuntimeHost {
|
||||
|
||||
const mesh = new Mesh(geometry, materials);
|
||||
mesh.position.set(brush.center.x, brush.center.y, brush.center.z);
|
||||
mesh.rotation.set(
|
||||
(brush.rotationDegrees.x * Math.PI) / 180,
|
||||
(brush.rotationDegrees.y * Math.PI) / 180,
|
||||
(brush.rotationDegrees.z * Math.PI) / 180
|
||||
);
|
||||
this.brushGroup.add(mesh);
|
||||
this.brushMeshes.set(brush.id, mesh);
|
||||
}
|
||||
@@ -458,13 +500,16 @@ export class RuntimeHost {
|
||||
name: modelInstance.name,
|
||||
position: modelInstance.position,
|
||||
rotationDegrees: modelInstance.rotationDegrees,
|
||||
scale: modelInstance.scale
|
||||
scale: modelInstance.scale,
|
||||
collision: {
|
||||
mode: "none",
|
||||
visible: false
|
||||
}
|
||||
},
|
||||
asset,
|
||||
loadedAsset,
|
||||
false
|
||||
);
|
||||
|
||||
this.modelGroup.add(renderGroup);
|
||||
this.modelRenderObjects.set(modelInstance.instanceId, renderGroup);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { LoadedModelAsset } from "../assets/gltf-model-import";
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import { getModelInstances } from "../assets/model-instances";
|
||||
import type { BoxBrush, BoxFaceId, FaceUvState } from "../document/brushes";
|
||||
@@ -5,10 +6,12 @@ import type { SceneDocument } from "../document/scene-document";
|
||||
import { cloneWorldSettings, type WorldSettings } from "../document/world-settings";
|
||||
import { getEntityInstances, getPrimaryPlayerStartEntity, type EntityInstance } from "../entities/entity-instances";
|
||||
import { getBoxBrushBounds } from "../geometry/box-brush";
|
||||
import { buildGeneratedModelCollider, type GeneratedColliderBounds, type GeneratedModelCollider } from "../geometry/model-instance-collider-generation";
|
||||
import { cloneInteractionLink, getInteractionLinks, type InteractionLink } from "../interactions/interaction-links";
|
||||
import { cloneMaterialDef, type MaterialDef } from "../materials/starter-material-library";
|
||||
import { cloneFaceUvState } from "../document/brushes";
|
||||
import { assertRuntimeSceneBuildable } from "./runtime-scene-validation";
|
||||
import { FIRST_PERSON_PLAYER_SHAPE, type FirstPersonPlayerShape } from "./player-collision";
|
||||
|
||||
export type RuntimeNavigationMode = "firstPerson" | "orbitVisitor";
|
||||
|
||||
@@ -22,17 +25,26 @@ export interface RuntimeBoxBrushInstance {
|
||||
id: string;
|
||||
kind: "box";
|
||||
center: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
size: Vec3;
|
||||
faces: Record<BoxFaceId, RuntimeBrushFace>;
|
||||
}
|
||||
|
||||
export interface RuntimeBoxCollider {
|
||||
kind: "box";
|
||||
source: "brush";
|
||||
brushId: string;
|
||||
min: Vec3;
|
||||
max: Vec3;
|
||||
center: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
size: Vec3;
|
||||
worldBounds: {
|
||||
min: Vec3;
|
||||
max: Vec3;
|
||||
};
|
||||
}
|
||||
|
||||
export type RuntimeSceneCollider = RuntimeBoxCollider | GeneratedModelCollider;
|
||||
|
||||
export interface RuntimeSceneBounds {
|
||||
min: Vec3;
|
||||
max: Vec3;
|
||||
@@ -44,6 +56,7 @@ export interface RuntimePlayerStart {
|
||||
entityId: string;
|
||||
position: Vec3;
|
||||
yawDegrees: number;
|
||||
collider: FirstPersonPlayerShape;
|
||||
}
|
||||
|
||||
export interface RuntimeSoundEmitter {
|
||||
@@ -132,17 +145,19 @@ export interface RuntimeSceneDefinition {
|
||||
world: WorldSettings;
|
||||
localLights: RuntimeLocalLightCollection;
|
||||
brushes: RuntimeBoxBrushInstance[];
|
||||
colliders: RuntimeBoxCollider[];
|
||||
colliders: RuntimeSceneCollider[];
|
||||
sceneBounds: RuntimeSceneBounds | null;
|
||||
modelInstances: RuntimeModelInstance[];
|
||||
entities: RuntimeEntityCollection;
|
||||
interactionLinks: InteractionLink[];
|
||||
playerStart: RuntimePlayerStart | null;
|
||||
playerCollider: FirstPersonPlayerShape;
|
||||
spawn: RuntimeSpawnPoint;
|
||||
}
|
||||
|
||||
interface BuildRuntimeSceneOptions {
|
||||
navigationMode?: RuntimeNavigationMode;
|
||||
loadedModelAssets?: Record<string, LoadedModelAsset>;
|
||||
}
|
||||
|
||||
function cloneVec3(vector: Vec3): Vec3 {
|
||||
@@ -172,6 +187,7 @@ function buildRuntimeBrush(brush: BoxBrush, document: SceneDocument): RuntimeBox
|
||||
id: brush.id,
|
||||
kind: "box",
|
||||
center: cloneVec3(brush.center),
|
||||
rotationDegrees: cloneVec3(brush.rotationDegrees),
|
||||
size: cloneVec3(brush.size),
|
||||
faces: {
|
||||
posX: {
|
||||
@@ -213,9 +229,15 @@ function buildRuntimeCollider(brush: BoxBrush): RuntimeBoxCollider {
|
||||
|
||||
return {
|
||||
kind: "box",
|
||||
source: "brush",
|
||||
brushId: brush.id,
|
||||
min: cloneVec3(bounds.min),
|
||||
max: cloneVec3(bounds.max)
|
||||
center: cloneVec3(brush.center),
|
||||
rotationDegrees: cloneVec3(brush.rotationDegrees),
|
||||
size: cloneVec3(brush.size),
|
||||
worldBounds: {
|
||||
min: cloneVec3(bounds.min),
|
||||
max: cloneVec3(bounds.max)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -232,21 +254,37 @@ function buildRuntimeModelInstance(modelInstance: SceneDocument["modelInstances"
|
||||
};
|
||||
}
|
||||
|
||||
function combineColliderBounds(colliders: RuntimeBoxCollider[]): RuntimeSceneBounds | null {
|
||||
function getColliderBounds(collider: RuntimeSceneCollider): GeneratedColliderBounds {
|
||||
if (collider.source === "brush") {
|
||||
return {
|
||||
min: cloneVec3(collider.worldBounds.min),
|
||||
max: cloneVec3(collider.worldBounds.max)
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
min: cloneVec3(collider.worldBounds.min),
|
||||
max: cloneVec3(collider.worldBounds.max)
|
||||
};
|
||||
}
|
||||
|
||||
function combineColliderBounds(colliders: RuntimeSceneCollider[]): RuntimeSceneBounds | null {
|
||||
if (colliders.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const min = cloneVec3(colliders[0].min);
|
||||
const max = cloneVec3(colliders[0].max);
|
||||
const firstBounds = getColliderBounds(colliders[0]);
|
||||
const min = cloneVec3(firstBounds.min);
|
||||
const max = cloneVec3(firstBounds.max);
|
||||
|
||||
for (const collider of colliders.slice(1)) {
|
||||
min.x = Math.min(min.x, collider.min.x);
|
||||
min.y = Math.min(min.y, collider.min.y);
|
||||
min.z = Math.min(min.z, collider.min.z);
|
||||
max.x = Math.max(max.x, collider.max.x);
|
||||
max.y = Math.max(max.y, collider.max.y);
|
||||
max.z = Math.max(max.z, collider.max.z);
|
||||
const bounds = getColliderBounds(collider);
|
||||
min.x = Math.min(min.x, bounds.min.x);
|
||||
min.y = Math.min(min.y, bounds.min.y);
|
||||
min.z = Math.min(min.z, bounds.min.z);
|
||||
max.x = Math.max(max.x, bounds.max.x);
|
||||
max.y = Math.max(max.y, bounds.max.y);
|
||||
max.z = Math.max(max.z, bounds.max.z);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -335,7 +373,8 @@ function buildRuntimeSceneCollections(document: SceneDocument): RuntimeSceneColl
|
||||
runtimeEntities.playerStarts.push({
|
||||
entityId: entity.id,
|
||||
position: cloneVec3(entity.position),
|
||||
yawDegrees: entity.yawDegrees
|
||||
yawDegrees: entity.yawDegrees,
|
||||
collider: buildRuntimePlayerShape(entity)
|
||||
});
|
||||
break;
|
||||
case "soundEmitter":
|
||||
@@ -395,23 +434,72 @@ function assertNever(value: never): never {
|
||||
throw new Error(`Unsupported runtime entity: ${String((value as EntityInstance).kind)}`);
|
||||
}
|
||||
|
||||
function buildRuntimePlayerShape(
|
||||
playerStartEntity: ReturnType<typeof getPrimaryPlayerStartEntity>
|
||||
): FirstPersonPlayerShape {
|
||||
if (playerStartEntity === null) {
|
||||
return FIRST_PERSON_PLAYER_SHAPE;
|
||||
}
|
||||
|
||||
switch (playerStartEntity.collider.mode) {
|
||||
case "capsule":
|
||||
return {
|
||||
mode: "capsule",
|
||||
radius: playerStartEntity.collider.capsuleRadius,
|
||||
height: playerStartEntity.collider.capsuleHeight,
|
||||
eyeHeight: playerStartEntity.collider.eyeHeight
|
||||
};
|
||||
case "box":
|
||||
return {
|
||||
mode: "box",
|
||||
size: cloneVec3(playerStartEntity.collider.boxSize),
|
||||
eyeHeight: playerStartEntity.collider.eyeHeight
|
||||
};
|
||||
case "none":
|
||||
return {
|
||||
mode: "none",
|
||||
eyeHeight: playerStartEntity.collider.eyeHeight
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function buildRuntimeSceneFromDocument(document: SceneDocument, options: BuildRuntimeSceneOptions = {}): RuntimeSceneDefinition {
|
||||
assertRuntimeSceneBuildable(document, options.navigationMode ?? "orbitVisitor");
|
||||
assertRuntimeSceneBuildable(document, {
|
||||
navigationMode: options.navigationMode ?? "orbitVisitor",
|
||||
loadedModelAssets: options.loadedModelAssets
|
||||
});
|
||||
|
||||
const brushes = Object.values(document.brushes).map((brush) => buildRuntimeBrush(brush, document));
|
||||
const colliders = Object.values(document.brushes).map((brush) => buildRuntimeCollider(brush));
|
||||
const sceneBounds = combineColliderBounds(colliders);
|
||||
const colliders: RuntimeSceneCollider[] = Object.values(document.brushes).map((brush) => buildRuntimeCollider(brush));
|
||||
const modelInstances = getModelInstances(document.modelInstances).map(buildRuntimeModelInstance);
|
||||
const collections = buildRuntimeSceneCollections(document);
|
||||
const interactionLinks = getInteractionLinks(document.interactionLinks).map((link) => cloneInteractionLink(link));
|
||||
const playerStartEntity = getPrimaryPlayerStartEntity(document.entities);
|
||||
const playerCollider = buildRuntimePlayerShape(playerStartEntity);
|
||||
|
||||
for (const modelInstance of getModelInstances(document.modelInstances)) {
|
||||
const asset = document.assets[modelInstance.assetId];
|
||||
|
||||
if (asset === undefined || asset.kind !== "model") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const generatedCollider = buildGeneratedModelCollider(modelInstance, asset, options.loadedModelAssets?.[modelInstance.assetId]);
|
||||
|
||||
if (generatedCollider !== null) {
|
||||
colliders.push(generatedCollider);
|
||||
}
|
||||
}
|
||||
|
||||
const combinedSceneBounds = combineColliderBounds(colliders);
|
||||
const playerStart =
|
||||
playerStartEntity === null
|
||||
? null
|
||||
: {
|
||||
entityId: playerStartEntity.id,
|
||||
position: cloneVec3(playerStartEntity.position),
|
||||
yawDegrees: playerStartEntity.yawDegrees
|
||||
yawDegrees: playerStartEntity.yawDegrees,
|
||||
collider: playerCollider
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -419,14 +507,15 @@ export function buildRuntimeSceneFromDocument(document: SceneDocument, options:
|
||||
localLights: collections.localLights,
|
||||
brushes,
|
||||
colliders,
|
||||
sceneBounds,
|
||||
sceneBounds: combinedSceneBounds,
|
||||
modelInstances,
|
||||
entities: collections.entities,
|
||||
interactionLinks,
|
||||
playerStart,
|
||||
playerCollider,
|
||||
spawn:
|
||||
playerStart === null
|
||||
? buildFallbackSpawn(sceneBounds)
|
||||
? buildFallbackSpawn(combinedSceneBounds)
|
||||
: {
|
||||
source: "playerStart",
|
||||
entityId: playerStart.entityId,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { LoadedModelAsset } from "../assets/gltf-model-import";
|
||||
import { getModelInstances } from "../assets/model-instances";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
import {
|
||||
assertSceneDocumentIsValid,
|
||||
@@ -6,6 +8,7 @@ import {
|
||||
type SceneDiagnostic
|
||||
} from "../document/scene-document-validation";
|
||||
import { getPrimaryPlayerStartEntity } from "../entities/entity-instances";
|
||||
import { buildGeneratedModelCollider, ModelColliderGenerationError } from "../geometry/model-instance-collider-generation";
|
||||
|
||||
export interface RuntimeSceneBuildValidationResult {
|
||||
diagnostics: SceneDiagnostic[];
|
||||
@@ -13,13 +16,18 @@ export interface RuntimeSceneBuildValidationResult {
|
||||
warnings: SceneDiagnostic[];
|
||||
}
|
||||
|
||||
interface ValidateRuntimeSceneBuildOptions {
|
||||
navigationMode: "firstPerson" | "orbitVisitor";
|
||||
loadedModelAssets?: Record<string, LoadedModelAsset>;
|
||||
}
|
||||
|
||||
export function validateRuntimeSceneBuild(
|
||||
document: SceneDocument,
|
||||
navigationMode: "firstPerson" | "orbitVisitor"
|
||||
options: ValidateRuntimeSceneBuildOptions
|
||||
): RuntimeSceneBuildValidationResult {
|
||||
const diagnostics: SceneDiagnostic[] = [];
|
||||
|
||||
if (navigationMode === "firstPerson" && getPrimaryPlayerStartEntity(document.entities) === null) {
|
||||
if (options.navigationMode === "firstPerson" && getPrimaryPlayerStartEntity(document.entities) === null) {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"error",
|
||||
@@ -31,6 +39,39 @@ export function validateRuntimeSceneBuild(
|
||||
);
|
||||
}
|
||||
|
||||
for (const modelInstance of getModelInstances(document.modelInstances)) {
|
||||
const path = `modelInstances.${modelInstance.id}.collision.mode`;
|
||||
const asset = document.assets[modelInstance.assetId];
|
||||
|
||||
if (modelInstance.collision.mode === "none" || asset === undefined || asset.kind !== "model") {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const generatedCollider = buildGeneratedModelCollider(modelInstance, asset, options.loadedModelAssets?.[modelInstance.assetId]);
|
||||
|
||||
if (generatedCollider?.mode === "dynamic") {
|
||||
diagnostics.push(
|
||||
createDiagnostic(
|
||||
"warning",
|
||||
"dynamic-model-collider-fixed-query-only",
|
||||
"Dynamic model collision currently generates convex compound pieces for Rapier queries, but the runner still uses them as fixed world collision rather than fully simulated rigid bodies.",
|
||||
path,
|
||||
"build"
|
||||
)
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Imported model collision generation failed.";
|
||||
const code =
|
||||
error instanceof ModelColliderGenerationError
|
||||
? error.code
|
||||
: "invalid-model-instance-collision-mode";
|
||||
|
||||
diagnostics.push(createDiagnostic("error", code, message, path, "build"));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
diagnostics,
|
||||
errors: diagnostics.filter((diagnostic) => diagnostic.severity === "error"),
|
||||
@@ -38,10 +79,10 @@ export function validateRuntimeSceneBuild(
|
||||
};
|
||||
}
|
||||
|
||||
export function assertRuntimeSceneBuildable(document: SceneDocument, navigationMode: "firstPerson" | "orbitVisitor") {
|
||||
export function assertRuntimeSceneBuildable(document: SceneDocument, options: ValidateRuntimeSceneBuildOptions) {
|
||||
assertSceneDocumentIsValid(document);
|
||||
|
||||
const validation = validateRuntimeSceneBuild(document, navigationMode);
|
||||
const validation = validateRuntimeSceneBuild(document, options);
|
||||
|
||||
if (validation.errors.length > 0) {
|
||||
throw new Error(`Runtime build is blocked: ${formatSceneDiagnosticSummary(validation.errors)}`);
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { createEmptySceneDocument, type SceneDocument } from "../document/scene-document";
|
||||
import {
|
||||
VIEWPORT_PANEL_IDS,
|
||||
cloneViewportLayoutState,
|
||||
createDefaultViewportLayoutState,
|
||||
type ViewportLayoutMode,
|
||||
type ViewportLayoutState,
|
||||
type ViewportPanelId
|
||||
} from "../viewport-three/viewport-layout";
|
||||
|
||||
import { parseSceneDocumentJson, serializeSceneDocument } from "./scene-document-json";
|
||||
|
||||
@@ -18,16 +26,24 @@ export type SaveSceneDocumentDraftResult =
|
||||
| { status: "error"; message: string };
|
||||
|
||||
export type LoadSceneDocumentDraftResult =
|
||||
| { status: "loaded"; document: SceneDocument; message: string }
|
||||
| { status: "loaded"; document: SceneDocument; viewportLayoutState: ViewportLayoutState | null; message: string }
|
||||
| { status: "missing"; message: string }
|
||||
| { status: "error"; message: string };
|
||||
|
||||
export interface LoadOrCreateSceneDocumentResult {
|
||||
document: SceneDocument;
|
||||
viewportLayoutState: ViewportLayoutState | null;
|
||||
diagnostic: string | null;
|
||||
}
|
||||
|
||||
export const DEFAULT_SCENE_DRAFT_STORAGE_KEY = "webeditor3d.scene-document-draft";
|
||||
const EDITOR_DRAFT_ENVELOPE_FORMAT = "webeditor3d.editor-draft.v1";
|
||||
|
||||
interface StoredEditorDraftEnvelope {
|
||||
format: typeof EDITOR_DRAFT_ENVELOPE_FORMAT;
|
||||
document: unknown;
|
||||
viewportLayoutState?: unknown;
|
||||
}
|
||||
|
||||
function getErrorDetail(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
@@ -41,6 +57,111 @@ function formatStorageDiagnostic(prefix: string, error: unknown): string {
|
||||
return `${prefix} ${getErrorDetail(error)}`;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function isFiniteNumber(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value);
|
||||
}
|
||||
|
||||
function parseViewportLayoutMode(value: unknown): ViewportLayoutMode | null {
|
||||
return value === "single" || value === "quad" ? value : null;
|
||||
}
|
||||
|
||||
function parseViewportPanelId(value: unknown): ViewportPanelId | null {
|
||||
return typeof value === "string" && (VIEWPORT_PANEL_IDS as readonly string[]).includes(value) ? (value as ViewportPanelId) : null;
|
||||
}
|
||||
|
||||
function parseViewportLayoutState(value: unknown): ViewportLayoutState | null {
|
||||
if (!isRecord(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const layoutMode = parseViewportLayoutMode(value.layoutMode);
|
||||
const activePanelId = parseViewportPanelId(value.activePanelId);
|
||||
const viewportQuadSplit = isRecord(value.viewportQuadSplit) ? value.viewportQuadSplit : null;
|
||||
const panels = isRecord(value.panels) ? value.panels : null;
|
||||
|
||||
if (layoutMode === null || activePanelId === null || viewportQuadSplit === null || panels === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!isFiniteNumber(viewportQuadSplit.x) || !isFiniteNumber(viewportQuadSplit.y)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const defaultLayoutState = createDefaultViewportLayoutState();
|
||||
const nextLayoutState = cloneViewportLayoutState(defaultLayoutState);
|
||||
|
||||
nextLayoutState.layoutMode = layoutMode;
|
||||
nextLayoutState.activePanelId = activePanelId;
|
||||
nextLayoutState.viewportQuadSplit = {
|
||||
x: viewportQuadSplit.x,
|
||||
y: viewportQuadSplit.y
|
||||
};
|
||||
|
||||
for (const panelId of VIEWPORT_PANEL_IDS) {
|
||||
const storedPanel = panels[panelId];
|
||||
|
||||
if (!isRecord(storedPanel)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const storedViewMode = storedPanel.viewMode;
|
||||
const storedDisplayMode = storedPanel.displayMode;
|
||||
const storedCameraState = isRecord(storedPanel.cameraState) ? storedPanel.cameraState : null;
|
||||
const storedPerspectiveOrbit = storedCameraState !== null && isRecord(storedCameraState.perspectiveOrbit) ? storedCameraState.perspectiveOrbit : null;
|
||||
const storedTarget = storedCameraState !== null && isRecord(storedCameraState.target) ? storedCameraState.target : null;
|
||||
|
||||
if (
|
||||
(storedViewMode !== "perspective" && storedViewMode !== "top" && storedViewMode !== "front" && storedViewMode !== "side") ||
|
||||
(storedDisplayMode !== "normal" && storedDisplayMode !== "authoring" && storedDisplayMode !== "wireframe") ||
|
||||
storedCameraState === null ||
|
||||
storedPerspectiveOrbit === null ||
|
||||
storedTarget === null
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
!isFiniteNumber(storedTarget.x) ||
|
||||
!isFiniteNumber(storedTarget.y) ||
|
||||
!isFiniteNumber(storedTarget.z) ||
|
||||
!isFiniteNumber(storedPerspectiveOrbit.radius) ||
|
||||
!isFiniteNumber(storedPerspectiveOrbit.theta) ||
|
||||
!isFiniteNumber(storedPerspectiveOrbit.phi) ||
|
||||
!isFiniteNumber(storedCameraState.orthographicZoom)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
nextLayoutState.panels[panelId] = {
|
||||
viewMode: storedViewMode,
|
||||
displayMode: storedDisplayMode,
|
||||
cameraState: {
|
||||
target: {
|
||||
x: storedTarget.x,
|
||||
y: storedTarget.y,
|
||||
z: storedTarget.z
|
||||
},
|
||||
perspectiveOrbit: {
|
||||
radius: storedPerspectiveOrbit.radius,
|
||||
theta: storedPerspectiveOrbit.theta,
|
||||
phi: storedPerspectiveOrbit.phi
|
||||
},
|
||||
orthographicZoom: storedCameraState.orthographicZoom
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return nextLayoutState;
|
||||
}
|
||||
|
||||
function isStoredEditorDraftEnvelope(value: unknown): value is StoredEditorDraftEnvelope {
|
||||
return isRecord(value) && value.format === EDITOR_DRAFT_ENVELOPE_FORMAT && "document" in value;
|
||||
}
|
||||
|
||||
export function getBrowserStorageAccess(): BrowserStorageAccessResult {
|
||||
if (typeof window === "undefined") {
|
||||
return {
|
||||
@@ -69,10 +190,19 @@ export function getBrowserStorage(): KeyValueStorage | null {
|
||||
export function saveSceneDocumentDraft(
|
||||
storage: KeyValueStorage,
|
||||
document: SceneDocument,
|
||||
viewportLayoutState: ViewportLayoutState | null = null,
|
||||
key = DEFAULT_SCENE_DRAFT_STORAGE_KEY
|
||||
): SaveSceneDocumentDraftResult {
|
||||
try {
|
||||
storage.setItem(key, serializeSceneDocument(document));
|
||||
const rawDocument = serializeSceneDocument(document);
|
||||
storage.setItem(
|
||||
key,
|
||||
JSON.stringify({
|
||||
format: EDITOR_DRAFT_ENVELOPE_FORMAT,
|
||||
document: JSON.parse(rawDocument),
|
||||
viewportLayoutState: viewportLayoutState === null ? null : cloneViewportLayoutState(viewportLayoutState)
|
||||
} satisfies StoredEditorDraftEnvelope)
|
||||
);
|
||||
|
||||
return {
|
||||
status: "saved",
|
||||
@@ -100,9 +230,21 @@ export function loadSceneDocumentDraft(
|
||||
};
|
||||
}
|
||||
|
||||
const parsedDraft = JSON.parse(rawDocument) as unknown;
|
||||
|
||||
if (isStoredEditorDraftEnvelope(parsedDraft)) {
|
||||
return {
|
||||
status: "loaded",
|
||||
document: parseSceneDocumentJson(JSON.stringify(parsedDraft.document)),
|
||||
viewportLayoutState: parseViewportLayoutState(parsedDraft.viewportLayoutState ?? null),
|
||||
message: "Local draft loaded."
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: "loaded",
|
||||
document: parseSceneDocumentJson(rawDocument),
|
||||
viewportLayoutState: null,
|
||||
message: "Local draft loaded."
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -120,6 +262,7 @@ export function loadOrCreateSceneDocument(
|
||||
if (storage === null) {
|
||||
return {
|
||||
document: createEmptySceneDocument(),
|
||||
viewportLayoutState: null,
|
||||
diagnostic: null
|
||||
};
|
||||
}
|
||||
@@ -130,16 +273,19 @@ export function loadOrCreateSceneDocument(
|
||||
case "loaded":
|
||||
return {
|
||||
document: draftResult.document,
|
||||
viewportLayoutState: draftResult.viewportLayoutState,
|
||||
diagnostic: null
|
||||
};
|
||||
case "missing":
|
||||
return {
|
||||
document: createEmptySceneDocument(),
|
||||
viewportLayoutState: null,
|
||||
diagnostic: null
|
||||
};
|
||||
case "error":
|
||||
return {
|
||||
document: createEmptySceneDocument(),
|
||||
viewportLayoutState: null,
|
||||
diagnostic: `${draftResult.message} Starting with a fresh empty document.`
|
||||
};
|
||||
}
|
||||
|
||||
109
src/shared-ui/HierarchicalMenu.tsx
Normal file
109
src/shared-ui/HierarchicalMenu.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
|
||||
export type HierarchicalMenuPosition = {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
|
||||
export type HierarchicalMenuItem =
|
||||
| {
|
||||
kind: "action";
|
||||
label: string;
|
||||
onSelect: () => void;
|
||||
testId?: string;
|
||||
disabled?: boolean;
|
||||
onHoverChange?: (hovered: boolean) => void;
|
||||
}
|
||||
| {
|
||||
kind: "group";
|
||||
label: string;
|
||||
testId?: string;
|
||||
children: HierarchicalMenuItem[];
|
||||
}
|
||||
| {
|
||||
kind: "separator";
|
||||
};
|
||||
|
||||
interface HierarchicalMenuProps {
|
||||
title: string;
|
||||
position: HierarchicalMenuPosition;
|
||||
items: HierarchicalMenuItem[];
|
||||
onClose(): void;
|
||||
}
|
||||
|
||||
function clampMenuPosition(position: HierarchicalMenuPosition): HierarchicalMenuPosition {
|
||||
const horizontalPadding = 12;
|
||||
const verticalPadding = 12;
|
||||
const estimatedMenuWidth = 300;
|
||||
const estimatedMenuHeight = 420;
|
||||
|
||||
return {
|
||||
x: Math.max(horizontalPadding, Math.min(position.x, window.innerWidth - estimatedMenuWidth - horizontalPadding)),
|
||||
y: Math.max(verticalPadding, Math.min(position.y, window.innerHeight - estimatedMenuHeight - verticalPadding))
|
||||
};
|
||||
}
|
||||
|
||||
function renderHierarchicalMenuItems(items: HierarchicalMenuItem[], onClose: () => void): ReactNode {
|
||||
return items.map((item, index) => {
|
||||
if (item.kind === "separator") {
|
||||
return <div key={`separator-${index}`} className="hierarchical-menu__separator" role="separator" />;
|
||||
}
|
||||
|
||||
if (item.kind === "group") {
|
||||
return (
|
||||
<details key={`${item.label}-${index}`} className="hierarchical-menu__group">
|
||||
<summary className="hierarchical-menu__group-summary" data-testid={item.testId}>
|
||||
<span className="hierarchical-menu__group-label">{item.label}</span>
|
||||
<span className="hierarchical-menu__group-chevron" aria-hidden="true" />
|
||||
</summary>
|
||||
<div className="hierarchical-menu__children">{renderHierarchicalMenuItems(item.children, onClose)}</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
key={`${item.label}-${index}`}
|
||||
className="hierarchical-menu__action"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
data-testid={item.testId}
|
||||
disabled={item.disabled}
|
||||
onClick={() => {
|
||||
if (item.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
item.onSelect();
|
||||
onClose();
|
||||
}}
|
||||
onPointerEnter={() => item.onHoverChange?.(true)}
|
||||
onPointerLeave={() => item.onHoverChange?.(false)}
|
||||
onFocus={() => item.onHoverChange?.(true)}
|
||||
onBlur={() => item.onHoverChange?.(false)}
|
||||
>
|
||||
<span className="hierarchical-menu__action-label">{item.label}</span>
|
||||
<span className="hierarchical-menu__action-plus" aria-hidden="true">
|
||||
+
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function HierarchicalMenu({ title, position, items, onClose }: HierarchicalMenuProps) {
|
||||
const clampedPosition = clampMenuPosition(position);
|
||||
const style: CSSProperties = {
|
||||
left: `${clampedPosition.x}px`,
|
||||
top: `${clampedPosition.y}px`
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="hierarchical-menu__backdrop" onPointerDown={onClose} role="presentation">
|
||||
<div className="hierarchical-menu" role="menu" aria-label={title} style={style} onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="hierarchical-menu__title">{title}</div>
|
||||
<div className="hierarchical-menu__list">{renderHierarchicalMenuItems(items, onClose)}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,55 +4,92 @@ import type { LoadedModelAsset } from "../assets/gltf-model-import";
|
||||
import type { LoadedImageAsset } from "../assets/image-assets";
|
||||
import type { ProjectAssetRecord } from "../assets/project-assets";
|
||||
import type { EditorSelection } from "../core/selection";
|
||||
import { getWhiteboxSelectionFeedbackLabel } from "../core/whitebox-selection-feedback";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import { getWhiteboxSelectionModeLabel, type WhiteboxSelectionMode } from "../core/whitebox-selection-mode";
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import { DEFAULT_BOX_BRUSH_CENTER, DEFAULT_BOX_BRUSH_SIZE } from "../document/brushes";
|
||||
import type { ActiveTransformSession, TransformSessionState } from "../core/transform-session";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
import type { WorldSettings } from "../document/world-settings";
|
||||
import { DEFAULT_GRID_SIZE } from "../geometry/grid-snapping";
|
||||
import { createWorldBackgroundStyle } from "../shared-ui/world-background-style";
|
||||
import {
|
||||
getViewportPanelLabel,
|
||||
type ViewportDisplayMode,
|
||||
type ViewportLayoutMode,
|
||||
type ViewportPanelCameraState,
|
||||
type ViewportPanelId
|
||||
} from "./viewport-layout";
|
||||
import {
|
||||
getViewportViewModeLabel,
|
||||
type ViewportViewMode
|
||||
} from "./viewport-view-modes";
|
||||
import type { CreationViewportToolPreview, ViewportToolPreview } from "./viewport-transient-state";
|
||||
|
||||
import { ViewportHost } from "./viewport-host";
|
||||
|
||||
interface ViewportCanvasProps {
|
||||
panelId: ViewportPanelId;
|
||||
world: WorldSettings;
|
||||
sceneDocument: SceneDocument;
|
||||
projectAssets: Record<string, ProjectAssetRecord>;
|
||||
loadedModelAssets: Record<string, LoadedModelAsset>;
|
||||
loadedImageAssets: Record<string, LoadedImageAsset>;
|
||||
whiteboxSelectionMode: WhiteboxSelectionMode;
|
||||
whiteboxSnapEnabled: boolean;
|
||||
whiteboxSnapStep: number;
|
||||
selection: EditorSelection;
|
||||
toolMode: ToolMode;
|
||||
toolPreview: ViewportToolPreview;
|
||||
transformSession: TransformSessionState;
|
||||
cameraState: ViewportPanelCameraState;
|
||||
viewMode: ViewportViewMode;
|
||||
displayMode: ViewportDisplayMode;
|
||||
layoutMode: ViewportLayoutMode;
|
||||
isActivePanel: boolean;
|
||||
focusRequestId: number;
|
||||
focusSelection: EditorSelection;
|
||||
onSelectionChange(selection: EditorSelection): void;
|
||||
onCreateBoxBrush(center: Vec3): void;
|
||||
}
|
||||
|
||||
function formatVec3(vector: Vec3 | null): string {
|
||||
if (vector === null) {
|
||||
return "Move over the grid to preview a snapped placement.";
|
||||
}
|
||||
|
||||
return `${vector.x}, ${vector.y}, ${vector.z}`;
|
||||
onCommitCreation(toolPreview: CreationViewportToolPreview): boolean;
|
||||
onCameraStateChange(cameraState: ViewportPanelCameraState): void;
|
||||
onToolPreviewChange(toolPreview: ViewportToolPreview): void;
|
||||
onTransformSessionChange(transformSession: TransformSessionState): void;
|
||||
onTransformCommit(transformSession: ActiveTransformSession): void;
|
||||
onTransformCancel(): void;
|
||||
}
|
||||
|
||||
export function ViewportCanvas({
|
||||
panelId,
|
||||
world,
|
||||
sceneDocument,
|
||||
projectAssets,
|
||||
loadedModelAssets,
|
||||
loadedImageAssets,
|
||||
whiteboxSelectionMode,
|
||||
whiteboxSnapEnabled,
|
||||
whiteboxSnapStep,
|
||||
selection,
|
||||
toolMode,
|
||||
toolPreview,
|
||||
transformSession,
|
||||
cameraState,
|
||||
viewMode,
|
||||
displayMode,
|
||||
layoutMode,
|
||||
isActivePanel,
|
||||
focusRequestId,
|
||||
focusSelection,
|
||||
onSelectionChange,
|
||||
onCreateBoxBrush
|
||||
onCommitCreation,
|
||||
onCameraStateChange,
|
||||
onToolPreviewChange,
|
||||
onTransformSessionChange,
|
||||
onTransformCommit,
|
||||
onTransformCancel
|
||||
}: ViewportCanvasProps) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const hostRef = useRef<ViewportHost | null>(null);
|
||||
const [viewportMessage, setViewportMessage] = useState<string | null>(null);
|
||||
const [boxCreatePreview, setBoxCreatePreview] = useState<Vec3 | null>(null);
|
||||
const [hoveredWhiteboxLabel, setHoveredWhiteboxLabel] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
@@ -75,6 +112,7 @@ export function ViewportCanvas({
|
||||
try {
|
||||
const viewportHost = new ViewportHost();
|
||||
hostRef.current = viewportHost;
|
||||
viewportHost.setPanelId(panelId);
|
||||
viewportHost.mount(container);
|
||||
setViewportMessage(null);
|
||||
|
||||
@@ -89,6 +127,10 @@ export function ViewportCanvas({
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setPanelId(panelId);
|
||||
}, [panelId]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.updateWorld(world);
|
||||
}, [world]);
|
||||
@@ -97,30 +139,83 @@ export function ViewportCanvas({
|
||||
hostRef.current?.updateAssets(projectAssets, loadedModelAssets, loadedImageAssets);
|
||||
}, [projectAssets, loadedModelAssets, loadedImageAssets]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setWhiteboxSnapSettings(whiteboxSnapEnabled, whiteboxSnapStep);
|
||||
}, [whiteboxSnapEnabled, whiteboxSnapStep]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setWhiteboxSelectionMode(whiteboxSelectionMode);
|
||||
}, [whiteboxSelectionMode]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.updateDocument(sceneDocument, selection);
|
||||
}, [sceneDocument, selection]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setViewMode(viewMode);
|
||||
}, [viewMode]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setDisplayMode(displayMode);
|
||||
}, [displayMode]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setCameraState(cameraState);
|
||||
}, [cameraState]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setBrushSelectionChangeHandler(onSelectionChange);
|
||||
}, [onSelectionChange]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setCreateBoxBrushHandler(onCreateBoxBrush);
|
||||
}, [onCreateBoxBrush]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setBoxCreatePreviewHandler(setBoxCreatePreview);
|
||||
hostRef.current?.setWhiteboxHoverLabelChangeHandler(setHoveredWhiteboxLabel);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setToolMode(toolMode);
|
||||
hostRef.current?.setCameraStateChangeHandler(onCameraStateChange);
|
||||
}, [onCameraStateChange]);
|
||||
|
||||
if (toolMode !== "box-create") {
|
||||
setBoxCreatePreview(null);
|
||||
}
|
||||
useEffect(() => {
|
||||
hostRef.current?.setCreationPreviewChangeHandler((nextToolPreview) => {
|
||||
onToolPreviewChange(
|
||||
nextToolPreview.kind === "create"
|
||||
? {
|
||||
...nextToolPreview,
|
||||
sourcePanelId: panelId
|
||||
}
|
||||
: nextToolPreview
|
||||
);
|
||||
});
|
||||
}, [onToolPreviewChange, panelId]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setCreationCommitHandler(onCommitCreation);
|
||||
}, [onCommitCreation]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setTransformSessionChangeHandler(onTransformSessionChange);
|
||||
}, [onTransformSessionChange]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setTransformCommitHandler(onTransformCommit);
|
||||
}, [onTransformCommit]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setTransformCancelHandler(onTransformCancel);
|
||||
}, [onTransformCancel]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setToolMode(toolMode);
|
||||
}, [toolMode]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setCreationPreview(toolMode === "create" && toolPreview.kind === "create" ? toolPreview : null);
|
||||
}, [toolMode, toolPreview]);
|
||||
|
||||
useEffect(() => {
|
||||
hostRef.current?.setTransformSession(transformSession);
|
||||
}, [transformSession]);
|
||||
|
||||
useEffect(() => {
|
||||
if (focusRequestId === 0) {
|
||||
return;
|
||||
@@ -129,35 +224,93 @@ export function ViewportCanvas({
|
||||
hostRef.current?.focusSelection(sceneDocument, focusSelection);
|
||||
}, [focusRequestId, focusSelection, sceneDocument]);
|
||||
|
||||
const previewVisible = toolMode === "create" && toolPreview.kind === "create" && toolPreview.center !== null;
|
||||
const transformPreviewVisible = transformSession.kind === "active";
|
||||
const selectionModeVisible = toolMode === "select";
|
||||
const selectedWhiteboxLabel = selectionModeVisible ? getWhiteboxSelectionFeedbackLabel(sceneDocument, selection) : null;
|
||||
const showViewModeOverlay = layoutMode === "quad";
|
||||
const showOverlay = showViewModeOverlay || selectionModeVisible || previewVisible || transformPreviewVisible || selectedWhiteboxLabel !== null || hoveredWhiteboxLabel !== null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={`viewport-canvas viewport-canvas--${toolMode}`}
|
||||
data-testid="viewport-shell"
|
||||
aria-label="Editor viewport"
|
||||
style={createWorldBackgroundStyle(world.background, world.background.mode === "image" ? loadedImageAssets[world.background.assetId]?.sourceUrl ?? null : null)}
|
||||
className={`viewport-canvas viewport-canvas--${toolMode} viewport-canvas--${viewMode} viewport-canvas--${displayMode} viewport-canvas--${layoutMode}`}
|
||||
data-testid={`viewport-canvas-${panelId}`}
|
||||
data-active={isActivePanel ? "true" : "false"}
|
||||
aria-label={`${getViewportPanelLabel(panelId)} editor viewport`}
|
||||
style={
|
||||
displayMode !== "normal"
|
||||
? {
|
||||
backgroundColor: "#000000",
|
||||
backgroundImage: "none"
|
||||
}
|
||||
: createWorldBackgroundStyle(world.background, world.background.mode === "image" ? loadedImageAssets[world.background.assetId]?.sourceUrl ?? null : null)
|
||||
}
|
||||
>
|
||||
<div className="viewport-canvas__overlay" data-testid="viewport-overlay">
|
||||
<div className="viewport-canvas__overlay-badge">{toolMode === "box-create" ? "Box Create" : "Select"}</div>
|
||||
<div className="viewport-canvas__overlay-text">
|
||||
{toolMode === "box-create"
|
||||
? `Click to place a ${DEFAULT_BOX_BRUSH_SIZE.x} x ${DEFAULT_BOX_BRUSH_SIZE.y} x ${DEFAULT_BOX_BRUSH_SIZE.z} box on the ${DEFAULT_GRID_SIZE}m grid.`
|
||||
: "Click to select. Middle-drag orbits, Shift + middle-drag pans, wheel zooms, and Numpad Comma frames the selection."}
|
||||
{!showOverlay ? null : (
|
||||
<div className="viewport-canvas__overlay" data-testid={`viewport-overlay-${panelId}`}>
|
||||
{!showViewModeOverlay ? null : (
|
||||
<div className="viewport-canvas__overlay-badges">
|
||||
<div className="viewport-canvas__overlay-badge viewport-canvas__overlay-badge--view">{getViewportViewModeLabel(viewMode)}</div>
|
||||
{!selectionModeVisible ? null : (
|
||||
<div
|
||||
className="viewport-canvas__overlay-badge viewport-canvas__overlay-badge--selection"
|
||||
data-testid={`viewport-selection-mode-${panelId}`}
|
||||
>
|
||||
{getWhiteboxSelectionModeLabel(whiteboxSelectionMode)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{showViewModeOverlay || !selectionModeVisible ? null : (
|
||||
<div className="viewport-canvas__overlay-badges">
|
||||
<div
|
||||
className="viewport-canvas__overlay-badge viewport-canvas__overlay-badge--selection"
|
||||
data-testid={`viewport-selection-mode-${panelId}`}
|
||||
>
|
||||
{getWhiteboxSelectionModeLabel(whiteboxSelectionMode)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!previewVisible ? null : (
|
||||
<div className="viewport-canvas__overlay-preview" data-testid={`viewport-snap-preview-${panelId}`}>
|
||||
Preview: {(toolPreview.center as Vec3).x}, {(toolPreview.center as Vec3).y}, {(toolPreview.center as Vec3).z}
|
||||
</div>
|
||||
)}
|
||||
{!transformPreviewVisible ? null : (
|
||||
<div className="viewport-canvas__overlay-preview" data-testid={`viewport-transform-preview-${panelId}`}>
|
||||
{transformSession.kind !== "active"
|
||||
? null
|
||||
: `${transformSession.operation}${transformSession.axisConstraint === null ? "" : ` · ${transformSession.axisConstraint.toUpperCase()}`}`}
|
||||
</div>
|
||||
)}
|
||||
{selectedWhiteboxLabel === null ? null : (
|
||||
<div className="viewport-canvas__overlay-preview" data-testid={`viewport-selected-whitebox-${panelId}`}>
|
||||
Selected: {selectedWhiteboxLabel}
|
||||
</div>
|
||||
)}
|
||||
{hoveredWhiteboxLabel === null ? null : (
|
||||
<div className="viewport-canvas__overlay-preview" data-testid={`viewport-hovered-whitebox-${panelId}`}>
|
||||
Hover: {hoveredWhiteboxLabel}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{toolMode !== "box-create" ? null : (
|
||||
<div className="viewport-canvas__overlay-preview" data-testid="viewport-snap-preview">
|
||||
Next box center: {formatVec3(boxCreatePreview)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{viewportMessage === null ? null : (
|
||||
<div className="viewport-canvas__fallback" role="status">
|
||||
<div className="viewport-canvas__fallback-title">Viewport Unavailable</div>
|
||||
<div>{viewportMessage}</div>
|
||||
{toolMode !== "box-create" ? null : (
|
||||
<button className="toolbar__button toolbar__button--accent" type="button" data-testid="viewport-fallback-create-box" onClick={() => onCreateBoxBrush(DEFAULT_BOX_BRUSH_CENTER)}>
|
||||
Create Default Box
|
||||
{toolMode !== "create" || toolPreview.kind !== "create" ? null : (
|
||||
<button
|
||||
className="toolbar__button toolbar__button--accent"
|
||||
type="button"
|
||||
data-testid={`viewport-fallback-create-${panelId}`}
|
||||
onClick={() => {
|
||||
onCommitCreation(toolPreview);
|
||||
}}
|
||||
>
|
||||
Commit Creation Preview
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
184
src/viewport-three/ViewportPanel.tsx
Normal file
184
src/viewport-three/ViewportPanel.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
import type { CSSProperties } from "react";
|
||||
|
||||
import { ViewportCanvas } from "./ViewportCanvas";
|
||||
import {
|
||||
getViewportDisplayModeLabel,
|
||||
getViewportPanelLabel,
|
||||
type ViewportPanelCameraState,
|
||||
type ViewportDisplayMode,
|
||||
type ViewportLayoutMode,
|
||||
type ViewportPanelId,
|
||||
type ViewportPanelState
|
||||
} from "./viewport-layout";
|
||||
import { VIEWPORT_VIEW_MODES, getViewportViewModeLabel, type ViewportViewMode } from "./viewport-view-modes";
|
||||
import type { CreationViewportToolPreview, ViewportToolPreview } from "./viewport-transient-state";
|
||||
import type { LoadedModelAsset } from "../assets/gltf-model-import";
|
||||
import type { LoadedImageAsset } from "../assets/image-assets";
|
||||
import type { ProjectAssetRecord } from "../assets/project-assets";
|
||||
import type { EditorSelection } from "../core/selection";
|
||||
import type { WhiteboxSelectionMode } from "../core/whitebox-selection-mode";
|
||||
import type { ActiveTransformSession, TransformSessionState } from "../core/transform-session";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
import type { WorldSettings } from "../document/world-settings";
|
||||
|
||||
interface ViewportPanelProps {
|
||||
panelId: ViewportPanelId;
|
||||
panelState: ViewportPanelState;
|
||||
layoutMode: ViewportLayoutMode;
|
||||
isActive: boolean;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
world: WorldSettings;
|
||||
sceneDocument: SceneDocument;
|
||||
projectAssets: Record<string, ProjectAssetRecord>;
|
||||
loadedModelAssets: Record<string, LoadedModelAsset>;
|
||||
loadedImageAssets: Record<string, LoadedImageAsset>;
|
||||
whiteboxSelectionMode: WhiteboxSelectionMode;
|
||||
whiteboxSnapEnabled: boolean;
|
||||
whiteboxSnapStep: number;
|
||||
selection: EditorSelection;
|
||||
toolMode: ToolMode;
|
||||
toolPreview: ViewportToolPreview;
|
||||
transformSession: TransformSessionState;
|
||||
cameraState: ViewportPanelCameraState;
|
||||
focusRequestId: number;
|
||||
focusSelection: EditorSelection;
|
||||
onActivatePanel(panelId: ViewportPanelId): void;
|
||||
onSetPanelViewMode(panelId: ViewportPanelId, viewMode: ViewportViewMode): void;
|
||||
onSetPanelDisplayMode(panelId: ViewportPanelId, displayMode: ViewportDisplayMode): void;
|
||||
onCommitCreation(toolPreview: CreationViewportToolPreview): boolean;
|
||||
onCameraStateChange(cameraState: ViewportPanelCameraState): void;
|
||||
onToolPreviewChange(toolPreview: ViewportToolPreview): void;
|
||||
onTransformSessionChange(transformSession: TransformSessionState): void;
|
||||
onTransformCommit(transformSession: ActiveTransformSession): void;
|
||||
onTransformCancel(): void;
|
||||
onSelectionChange(selection: EditorSelection): void;
|
||||
}
|
||||
|
||||
export function ViewportPanel({
|
||||
panelId,
|
||||
panelState,
|
||||
layoutMode,
|
||||
isActive,
|
||||
className,
|
||||
style,
|
||||
world,
|
||||
sceneDocument,
|
||||
projectAssets,
|
||||
loadedModelAssets,
|
||||
loadedImageAssets,
|
||||
whiteboxSelectionMode,
|
||||
whiteboxSnapEnabled,
|
||||
whiteboxSnapStep,
|
||||
selection,
|
||||
toolMode,
|
||||
toolPreview,
|
||||
transformSession,
|
||||
cameraState,
|
||||
focusRequestId,
|
||||
focusSelection,
|
||||
onActivatePanel,
|
||||
onSetPanelViewMode,
|
||||
onSetPanelDisplayMode,
|
||||
onCommitCreation,
|
||||
onCameraStateChange,
|
||||
onToolPreviewChange,
|
||||
onTransformSessionChange,
|
||||
onTransformCommit,
|
||||
onTransformCancel,
|
||||
onSelectionChange
|
||||
}: ViewportPanelProps) {
|
||||
const shouldShow = layoutMode === "quad" || isActive;
|
||||
const panelStyle = shouldShow ? style : { ...(style ?? {}), display: "none" };
|
||||
|
||||
return (
|
||||
<section
|
||||
className={`viewport-panel ${layoutMode === "single" ? "viewport-panel--single" : "viewport-panel--quad"} ${className ?? ""}`.trim()}
|
||||
data-testid={`viewport-panel-${panelId}`}
|
||||
data-active={isActive ? "true" : "false"}
|
||||
data-viewport-panel-id={panelId}
|
||||
aria-hidden={shouldShow ? undefined : true}
|
||||
aria-label={`${getViewportPanelLabel(panelId)} viewport panel`}
|
||||
style={panelStyle}
|
||||
onPointerDownCapture={() => onActivatePanel(panelId)}
|
||||
onFocusCapture={() => onActivatePanel(panelId)}
|
||||
>
|
||||
<div className="viewport-panel__header">
|
||||
{layoutMode !== "quad" ? null : (
|
||||
<div className="viewport-panel__meta">
|
||||
<div className="viewport-panel__title-row">
|
||||
<div className="viewport-panel__title">{getViewportPanelLabel(panelId)}</div>
|
||||
{!isActive ? null : (
|
||||
<div className="viewport-panel__active-badge" data-testid={`viewport-panel-active-badge-${panelId}`}>
|
||||
Active
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="viewport-panel__controls">
|
||||
<div className="viewport-panel__control-group" role="group" aria-label={`${getViewportPanelLabel(panelId)} view mode`}>
|
||||
{VIEWPORT_VIEW_MODES.map((viewMode) => (
|
||||
<button
|
||||
key={viewMode}
|
||||
className={`viewport-panel__button ${panelState.viewMode === viewMode ? "viewport-panel__button--active" : ""}`}
|
||||
type="button"
|
||||
data-testid={`viewport-panel-${panelId}-view-${viewMode}`}
|
||||
aria-pressed={panelState.viewMode === viewMode}
|
||||
onClick={() => onSetPanelViewMode(panelId, viewMode)}
|
||||
>
|
||||
{getViewportViewModeLabel(viewMode)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="viewport-panel__control-group" role="group" aria-label={`${getViewportPanelLabel(panelId)} display mode`}>
|
||||
{(["normal", "authoring", "wireframe"] as const).map((displayMode) => (
|
||||
<button
|
||||
key={displayMode}
|
||||
className={`viewport-panel__button ${panelState.displayMode === displayMode ? "viewport-panel__button--active" : ""}`}
|
||||
type="button"
|
||||
data-testid={`viewport-panel-${panelId}-display-${displayMode}`}
|
||||
aria-pressed={panelState.displayMode === displayMode}
|
||||
onClick={() => onSetPanelDisplayMode(panelId, displayMode)}
|
||||
>
|
||||
{getViewportDisplayModeLabel(displayMode)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ViewportCanvas
|
||||
panelId={panelId}
|
||||
world={world}
|
||||
sceneDocument={sceneDocument}
|
||||
projectAssets={projectAssets}
|
||||
loadedModelAssets={loadedModelAssets}
|
||||
loadedImageAssets={loadedImageAssets}
|
||||
whiteboxSelectionMode={whiteboxSelectionMode}
|
||||
whiteboxSnapEnabled={whiteboxSnapEnabled}
|
||||
whiteboxSnapStep={whiteboxSnapStep}
|
||||
selection={selection}
|
||||
toolMode={toolMode}
|
||||
toolPreview={toolPreview}
|
||||
transformSession={transformSession}
|
||||
cameraState={cameraState}
|
||||
viewMode={panelState.viewMode}
|
||||
displayMode={panelState.displayMode}
|
||||
layoutMode={layoutMode}
|
||||
isActivePanel={isActive}
|
||||
focusRequestId={focusRequestId}
|
||||
focusSelection={focusSelection}
|
||||
onSelectionChange={onSelectionChange}
|
||||
onCommitCreation={onCommitCreation}
|
||||
onCameraStateChange={onCameraStateChange}
|
||||
onToolPreviewChange={onToolPreviewChange}
|
||||
onTransformSessionChange={onTransformSessionChange}
|
||||
onTransformCommit={onTransformCommit}
|
||||
onTransformCancel={onTransformCancel}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type { SceneDocument } from "../document/scene-document";
|
||||
import type { EntityInstance } from "../entities/entity-instances";
|
||||
import type { ModelInstance } from "../assets/model-instances";
|
||||
import type { ProjectAssetRecord } from "../assets/project-assets";
|
||||
import { getBoxBrushBounds } from "../geometry/box-brush";
|
||||
|
||||
const PLAYER_START_FOCUS_HALF_EXTENTS: Vec3 = {
|
||||
x: 0.35,
|
||||
@@ -88,25 +89,8 @@ function createBrushFocusTarget(brush: BoxBrush): ViewportFocusTarget {
|
||||
}
|
||||
|
||||
function includeBrush(bounds: FocusBoundsAccumulator, brush: BoxBrush) {
|
||||
const halfSize = {
|
||||
x: brush.size.x * 0.5,
|
||||
y: brush.size.y * 0.5,
|
||||
z: brush.size.z * 0.5
|
||||
};
|
||||
|
||||
includeBounds(
|
||||
bounds,
|
||||
{
|
||||
x: brush.center.x - halfSize.x,
|
||||
y: brush.center.y - halfSize.y,
|
||||
z: brush.center.z - halfSize.z
|
||||
},
|
||||
{
|
||||
x: brush.center.x + halfSize.x,
|
||||
y: brush.center.y + halfSize.y,
|
||||
z: brush.center.z + halfSize.z
|
||||
}
|
||||
);
|
||||
const brushBounds = getBoxBrushBounds(brush);
|
||||
includeBounds(bounds, brushBounds.min, brushBounds.max);
|
||||
}
|
||||
|
||||
function includePlayerStart(bounds: FocusBoundsAccumulator, position: Vec3) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
185
src/viewport-three/viewport-layout.ts
Normal file
185
src/viewport-three/viewport-layout.ts
Normal file
@@ -0,0 +1,185 @@
|
||||
import type { Vec3 } from "../core/vector";
|
||||
|
||||
import type { ViewportViewMode } from "./viewport-view-modes";
|
||||
|
||||
export type ViewportLayoutMode = "single" | "quad";
|
||||
|
||||
export type ViewportDisplayMode = "normal" | "authoring" | "wireframe";
|
||||
|
||||
export type ViewportPanelId = "topLeft" | "topRight" | "bottomLeft" | "bottomRight";
|
||||
|
||||
export const VIEWPORT_LAYOUT_MODES = ["single", "quad"] as const;
|
||||
|
||||
export const VIEWPORT_PANEL_IDS = ["topLeft", "topRight", "bottomLeft", "bottomRight"] as const;
|
||||
|
||||
export interface ViewportPerspectiveOrbitState {
|
||||
radius: number;
|
||||
theta: number;
|
||||
phi: number;
|
||||
}
|
||||
|
||||
export interface ViewportPanelCameraState {
|
||||
target: Vec3;
|
||||
perspectiveOrbit: ViewportPerspectiveOrbitState;
|
||||
orthographicZoom: number;
|
||||
}
|
||||
|
||||
export interface ViewportPanelState {
|
||||
viewMode: ViewportViewMode;
|
||||
displayMode: ViewportDisplayMode;
|
||||
cameraState: ViewportPanelCameraState;
|
||||
}
|
||||
|
||||
export interface ViewportQuadSplit {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface ViewportLayoutState {
|
||||
layoutMode: ViewportLayoutMode;
|
||||
activePanelId: ViewportPanelId;
|
||||
panels: Record<ViewportPanelId, ViewportPanelState>;
|
||||
viewportQuadSplit: ViewportQuadSplit;
|
||||
}
|
||||
|
||||
const DEFAULT_PERSPECTIVE_CAMERA_POSITION = {
|
||||
x: 10,
|
||||
y: 9,
|
||||
z: 10
|
||||
} as const;
|
||||
|
||||
export const DEFAULT_VIEWPORT_LAYOUT_STATE: ViewportLayoutState = {
|
||||
layoutMode: "single",
|
||||
activePanelId: "topLeft",
|
||||
panels: {
|
||||
topLeft: {
|
||||
viewMode: "perspective",
|
||||
displayMode: "normal",
|
||||
cameraState: createDefaultViewportPanelCameraState()
|
||||
},
|
||||
topRight: {
|
||||
viewMode: "top",
|
||||
displayMode: "authoring",
|
||||
cameraState: createDefaultViewportPanelCameraState()
|
||||
},
|
||||
bottomLeft: {
|
||||
viewMode: "front",
|
||||
displayMode: "authoring",
|
||||
cameraState: createDefaultViewportPanelCameraState()
|
||||
},
|
||||
bottomRight: {
|
||||
viewMode: "side",
|
||||
displayMode: "authoring",
|
||||
cameraState: createDefaultViewportPanelCameraState()
|
||||
}
|
||||
},
|
||||
viewportQuadSplit: {
|
||||
x: 0.5,
|
||||
y: 0.5
|
||||
}
|
||||
};
|
||||
|
||||
function createDefaultPerspectiveOrbitState(): ViewportPerspectiveOrbitState {
|
||||
const { x, y, z } = DEFAULT_PERSPECTIVE_CAMERA_POSITION;
|
||||
const radius = Math.sqrt(x * x + y * y + z * z);
|
||||
|
||||
return {
|
||||
radius,
|
||||
theta: Math.atan2(x, z),
|
||||
phi: Math.acos(y / radius)
|
||||
};
|
||||
}
|
||||
|
||||
export function createDefaultViewportPanelCameraState(): ViewportPanelCameraState {
|
||||
return {
|
||||
target: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
perspectiveOrbit: createDefaultPerspectiveOrbitState(),
|
||||
orthographicZoom: 1
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneViewportPanelCameraState(cameraState: ViewportPanelCameraState): ViewportPanelCameraState {
|
||||
return {
|
||||
target: {
|
||||
...cameraState.target
|
||||
},
|
||||
perspectiveOrbit: {
|
||||
...cameraState.perspectiveOrbit
|
||||
},
|
||||
orthographicZoom: cameraState.orthographicZoom
|
||||
};
|
||||
}
|
||||
|
||||
export function areViewportPanelCameraStatesEqual(a: ViewportPanelCameraState, b: ViewportPanelCameraState): boolean {
|
||||
return (
|
||||
a.target.x === b.target.x &&
|
||||
a.target.y === b.target.y &&
|
||||
a.target.z === b.target.z &&
|
||||
a.perspectiveOrbit.radius === b.perspectiveOrbit.radius &&
|
||||
a.perspectiveOrbit.theta === b.perspectiveOrbit.theta &&
|
||||
a.perspectiveOrbit.phi === b.perspectiveOrbit.phi &&
|
||||
a.orthographicZoom === b.orthographicZoom
|
||||
);
|
||||
}
|
||||
|
||||
export function cloneViewportPanelState(panelState: ViewportPanelState): ViewportPanelState {
|
||||
return {
|
||||
viewMode: panelState.viewMode,
|
||||
displayMode: panelState.displayMode,
|
||||
cameraState: cloneViewportPanelCameraState(panelState.cameraState)
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneViewportLayoutState(layoutState: ViewportLayoutState): ViewportLayoutState {
|
||||
return {
|
||||
layoutMode: layoutState.layoutMode,
|
||||
activePanelId: layoutState.activePanelId,
|
||||
panels: {
|
||||
topLeft: cloneViewportPanelState(layoutState.panels.topLeft),
|
||||
topRight: cloneViewportPanelState(layoutState.panels.topRight),
|
||||
bottomLeft: cloneViewportPanelState(layoutState.panels.bottomLeft),
|
||||
bottomRight: cloneViewportPanelState(layoutState.panels.bottomRight)
|
||||
},
|
||||
viewportQuadSplit: {
|
||||
...layoutState.viewportQuadSplit
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createDefaultViewportLayoutState(): ViewportLayoutState {
|
||||
return cloneViewportLayoutState(DEFAULT_VIEWPORT_LAYOUT_STATE);
|
||||
}
|
||||
|
||||
const VIEWPORT_PANEL_LABELS: Record<ViewportPanelId, string> = {
|
||||
topLeft: "Top Left",
|
||||
topRight: "Top Right",
|
||||
bottomLeft: "Bottom Left",
|
||||
bottomRight: "Bottom Right"
|
||||
};
|
||||
|
||||
const VIEWPORT_LAYOUT_MODE_LABELS: Record<ViewportLayoutMode, string> = {
|
||||
single: "Single View",
|
||||
quad: "4-Panel"
|
||||
};
|
||||
|
||||
const VIEWPORT_DISPLAY_MODE_LABELS: Record<ViewportDisplayMode, string> = {
|
||||
normal: "Normal",
|
||||
authoring: "Authoring",
|
||||
wireframe: "Wireframe"
|
||||
};
|
||||
|
||||
export function getViewportPanelLabel(panelId: ViewportPanelId): string {
|
||||
return VIEWPORT_PANEL_LABELS[panelId];
|
||||
}
|
||||
|
||||
export function getViewportLayoutModeLabel(layoutMode: ViewportLayoutMode): string {
|
||||
return VIEWPORT_LAYOUT_MODE_LABELS[layoutMode];
|
||||
}
|
||||
|
||||
export function getViewportDisplayModeLabel(displayMode: ViewportDisplayMode): string {
|
||||
return VIEWPORT_DISPLAY_MODE_LABELS[displayMode];
|
||||
}
|
||||
131
src/viewport-three/viewport-transient-state.ts
Normal file
131
src/viewport-three/viewport-transient-state.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import {
|
||||
areTransformSessionsEqual,
|
||||
cloneTransformSession,
|
||||
createInactiveTransformSession,
|
||||
type TransformSessionState
|
||||
} from "../core/transform-session";
|
||||
import type { EntityKind } from "../entities/entity-instances";
|
||||
import type { ViewportPanelId } from "./viewport-layout";
|
||||
|
||||
export type CreationTarget =
|
||||
| {
|
||||
kind: "box-brush";
|
||||
}
|
||||
| {
|
||||
kind: "entity";
|
||||
entityKind: EntityKind;
|
||||
audioAssetId: string | null;
|
||||
}
|
||||
| {
|
||||
kind: "model-instance";
|
||||
assetId: string;
|
||||
};
|
||||
|
||||
export interface CreationViewportToolPreview {
|
||||
kind: "create";
|
||||
sourcePanelId: ViewportPanelId;
|
||||
target: CreationTarget;
|
||||
center: Vec3 | null;
|
||||
}
|
||||
|
||||
export type ViewportToolPreview = CreationViewportToolPreview | { kind: "none" };
|
||||
|
||||
export interface ViewportTransientState {
|
||||
toolPreview: ViewportToolPreview;
|
||||
transformSession: TransformSessionState;
|
||||
}
|
||||
|
||||
export function createDefaultViewportTransientState(): ViewportTransientState {
|
||||
return {
|
||||
toolPreview: {
|
||||
kind: "none"
|
||||
},
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneViewportToolPreview(toolPreview: ViewportToolPreview): ViewportToolPreview {
|
||||
if (toolPreview.kind === "none") {
|
||||
return toolPreview;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "create",
|
||||
sourcePanelId: toolPreview.sourcePanelId,
|
||||
target:
|
||||
toolPreview.target.kind === "entity"
|
||||
? {
|
||||
kind: "entity",
|
||||
entityKind: toolPreview.target.entityKind,
|
||||
audioAssetId: toolPreview.target.audioAssetId
|
||||
}
|
||||
: toolPreview.target.kind === "model-instance"
|
||||
? {
|
||||
kind: "model-instance",
|
||||
assetId: toolPreview.target.assetId
|
||||
}
|
||||
: {
|
||||
kind: "box-brush"
|
||||
},
|
||||
center: toolPreview.center === null ? null : { ...toolPreview.center }
|
||||
};
|
||||
}
|
||||
|
||||
export function areViewportToolPreviewsEqual(left: ViewportToolPreview, right: ViewportToolPreview): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.kind === "none" || right.kind === "none") {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (left.kind !== "create" || right.kind !== "create") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.sourcePanelId !== right.sourcePanelId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.target.kind !== right.target.kind) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.target.kind === "entity" && right.target.kind === "entity") {
|
||||
if (left.target.entityKind !== right.target.entityKind || left.target.audioAssetId !== right.target.audioAssetId) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.target.kind === "model-instance" && right.target.kind === "model-instance" && left.target.assetId !== right.target.assetId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.center === null || right.center === null) {
|
||||
return left.center === right.center;
|
||||
}
|
||||
|
||||
return left.center.x === right.center.x && left.center.y === right.center.y && left.center.z === right.center.z;
|
||||
}
|
||||
|
||||
export function isViewportToolPreviewCompatible(toolMode: ToolMode, toolPreview: ViewportToolPreview): boolean {
|
||||
if (toolPreview.kind === "none") {
|
||||
return true;
|
||||
}
|
||||
|
||||
return toolMode === "create" && toolPreview.kind === "create";
|
||||
}
|
||||
|
||||
export function cloneViewportTransientState(transientState: ViewportTransientState): ViewportTransientState {
|
||||
return {
|
||||
toolPreview: cloneViewportToolPreview(transientState.toolPreview),
|
||||
transformSession: cloneTransformSession(transientState.transformSession)
|
||||
};
|
||||
}
|
||||
|
||||
export function areViewportTransientStatesEqual(left: ViewportTransientState, right: ViewportTransientState): boolean {
|
||||
return areViewportToolPreviewsEqual(left.toolPreview, right.toolPreview) && areTransformSessionsEqual(left.transformSession, right.transformSession);
|
||||
}
|
||||
114
src/viewport-three/viewport-view-modes.ts
Normal file
114
src/viewport-three/viewport-view-modes.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import type { Vec3 } from "../core/vector";
|
||||
|
||||
export type ViewportViewMode = "perspective" | "top" | "front" | "side";
|
||||
|
||||
export const VIEWPORT_VIEW_MODES = ["perspective", "top", "front", "side"] as const;
|
||||
|
||||
export type ViewportGridPlane = "xz" | "xy" | "yz";
|
||||
export type ViewportAxis = "x" | "y" | "z";
|
||||
|
||||
export interface ViewportViewModeDefinition {
|
||||
id: ViewportViewMode;
|
||||
label: string;
|
||||
cameraType: "perspective" | "orthographic";
|
||||
cameraDirection: Vec3 | null;
|
||||
cameraUp: Vec3;
|
||||
gridPlane: ViewportGridPlane;
|
||||
snapAxis: ViewportAxis;
|
||||
controlHint: string;
|
||||
}
|
||||
|
||||
const VIEWPORT_VIEW_MODE_DEFINITIONS: Record<ViewportViewMode, ViewportViewModeDefinition> = {
|
||||
perspective: {
|
||||
id: "perspective",
|
||||
label: "Perspective",
|
||||
cameraType: "perspective",
|
||||
cameraDirection: null,
|
||||
cameraUp: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
gridPlane: "xz",
|
||||
snapAxis: "y",
|
||||
controlHint: "Middle-drag orbits, Shift + middle-drag pans, wheel zooms, and Numpad Comma frames the selection."
|
||||
},
|
||||
top: {
|
||||
id: "top",
|
||||
label: "Top",
|
||||
cameraType: "orthographic",
|
||||
cameraDirection: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
cameraUp: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: -1
|
||||
},
|
||||
gridPlane: "xz",
|
||||
snapAxis: "y",
|
||||
controlHint: "Middle-drag pans, wheel zooms, and Numpad Comma frames the selection."
|
||||
},
|
||||
front: {
|
||||
id: "front",
|
||||
label: "Front",
|
||||
cameraType: "orthographic",
|
||||
cameraDirection: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 1
|
||||
},
|
||||
cameraUp: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
gridPlane: "xy",
|
||||
snapAxis: "z",
|
||||
controlHint: "Middle-drag pans, wheel zooms, and Numpad Comma frames the selection."
|
||||
},
|
||||
side: {
|
||||
id: "side",
|
||||
label: "Side",
|
||||
cameraType: "orthographic",
|
||||
cameraDirection: {
|
||||
x: -1,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
cameraUp: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
gridPlane: "yz",
|
||||
snapAxis: "x",
|
||||
controlHint: "Middle-drag pans, wheel zooms, and Numpad Comma frames the selection."
|
||||
}
|
||||
};
|
||||
|
||||
export function getViewportViewModeDefinition(viewMode: ViewportViewMode): ViewportViewModeDefinition {
|
||||
return VIEWPORT_VIEW_MODE_DEFINITIONS[viewMode];
|
||||
}
|
||||
|
||||
export function getViewportViewModeLabel(viewMode: ViewportViewMode): string {
|
||||
return VIEWPORT_VIEW_MODE_DEFINITIONS[viewMode].label;
|
||||
}
|
||||
|
||||
export function getViewportViewModeGridPlaneLabel(viewMode: ViewportViewMode): string {
|
||||
return VIEWPORT_VIEW_MODE_DEFINITIONS[viewMode].gridPlane.toUpperCase();
|
||||
}
|
||||
|
||||
export function getViewportViewModeControlHint(viewMode: ViewportViewMode): string {
|
||||
return VIEWPORT_VIEW_MODE_DEFINITIONS[viewMode].controlHint;
|
||||
}
|
||||
|
||||
export function getViewportViewModeSnapAxis(viewMode: ViewportViewMode): ViewportAxis {
|
||||
return VIEWPORT_VIEW_MODE_DEFINITIONS[viewMode].snapAxis;
|
||||
}
|
||||
|
||||
export function isOrthographicViewportViewMode(viewMode: ViewportViewMode): boolean {
|
||||
return viewMode !== "perspective";
|
||||
}
|
||||
43
testing.md
43
testing.md
@@ -33,14 +33,15 @@ Highest-priority confidence areas:
|
||||
|
||||
1. document validity and migrations
|
||||
2. undo/redo correctness
|
||||
3. brush generation correctness
|
||||
3. whitebox geometry generation correctness
|
||||
4. per-face material/UV persistence
|
||||
5. runtime build correctness
|
||||
6. asset import survival
|
||||
7. project package portability once binary assets exist
|
||||
8. runner navigation/input reliability
|
||||
9. spatial audio and interaction basics
|
||||
10. critical regressions caught in CI
|
||||
7. imported-model collider generation and runtime collision correctness
|
||||
8. project package portability once binary assets exist
|
||||
9. runner navigation/input reliability
|
||||
10. spatial audio and interaction basics
|
||||
11. critical regressions caught in CI
|
||||
|
||||
---
|
||||
|
||||
@@ -94,7 +95,7 @@ Purpose:
|
||||
Scope:
|
||||
|
||||
- math helpers
|
||||
- grid snapping
|
||||
- snapping helpers
|
||||
- ID utilities
|
||||
- small schema defaults
|
||||
- validation helpers
|
||||
@@ -114,6 +115,7 @@ Examples:
|
||||
|
||||
- `snapValue(1.23, 0.5) -> 1.0`
|
||||
- UV rotate/flip calculations
|
||||
- axis/local transform constraint calculations
|
||||
- entity schema default application
|
||||
- command label generation if logic matters
|
||||
|
||||
@@ -136,7 +138,7 @@ Scope:
|
||||
|
||||
Examples:
|
||||
|
||||
- create brush command adds valid brush
|
||||
- create whitebox-solid command adds valid geometry
|
||||
- undo removes it cleanly
|
||||
- redo restores the same result
|
||||
- invalid entity reference is detected
|
||||
@@ -150,33 +152,45 @@ These tests should not need a browser renderer.
|
||||
|
||||
Purpose:
|
||||
|
||||
- verify brush/kernel correctness
|
||||
- verify whitebox geometry/kernel correctness
|
||||
|
||||
Scope:
|
||||
|
||||
- primitive generation
|
||||
- face generation
|
||||
- edge/vertex derivation where canonical
|
||||
- topology expectations
|
||||
- collision mesh generation
|
||||
- imported-model collider generation
|
||||
- Rapier-backed collider/query integration where relevant
|
||||
- UV projection generation
|
||||
- clipping results
|
||||
- derived mesh determinism
|
||||
|
||||
Examples:
|
||||
|
||||
- box brush creates expected face count
|
||||
- box-based whitebox solid creates expected face count
|
||||
- stairs generator creates expected step count
|
||||
- fit-to-face UV produces finite values
|
||||
- clipping yields valid child brushes
|
||||
- edited solids triangulate without NaNs or invalid indices
|
||||
- generated geometry contains no NaNs
|
||||
- rebuild is deterministic for the same input
|
||||
- non-planar quad faces triangulate deterministically
|
||||
- non-convex whitebox solids either derive valid output or fail clearly when unsupported
|
||||
- imported model collider generation produces finite valid data for the selected mode
|
||||
- imported-model collider generation honors the authored mode semantics:
|
||||
- terrain -> heightfield
|
||||
- static -> triangle mesh
|
||||
- dynamic -> compound convex pieces
|
||||
- simple -> primitive or convex hull
|
||||
- unsupported imported-model collision modes fail clearly instead of producing silent garbage
|
||||
|
||||
### Geometry test principles
|
||||
|
||||
- assert invariants, not fragile exact arrays unless necessary
|
||||
- prefer bounded numeric comparisons
|
||||
- verify no degenerate triangles where required
|
||||
- test edge cases: tiny sizes, rejected zero-like values, unsupported cases failing clearly
|
||||
- test edge cases: tiny sizes, float transforms, component edits, unsupported cases failing clearly
|
||||
|
||||
Geometry is a high-risk area and deserves dense testing.
|
||||
|
||||
@@ -200,6 +214,7 @@ Examples:
|
||||
|
||||
- scene round-trips without losing face materials
|
||||
- UV state survives save/load
|
||||
- floating point transforms survive save/load without accidental snapping
|
||||
- imported asset refs survive save/load
|
||||
- project package export/import preserves asset-backed scenes
|
||||
- unsupported version throws an understandable error
|
||||
@@ -212,6 +227,12 @@ For every substantial document feature, add at least:
|
||||
- one round-trip save/load test
|
||||
- one migration or backward-compatibility consideration if schema changed
|
||||
|
||||
For authored imported-model collision settings, also add at least:
|
||||
|
||||
- one round-trip test for the selected collision mode/settings
|
||||
- one validation/build-path test for missing asset or incompatible collision-mode assumptions where relevant
|
||||
- one runtime/query-path test proving the generated collider participates in the actual collision/query layer rather than only existing as dead metadata
|
||||
|
||||
---
|
||||
|
||||
## 5. Browser integration tests
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BoxGeometry } from "three";
|
||||
|
||||
import { createBoxBrush } from "../../src/document/brushes";
|
||||
import { createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
@@ -15,6 +16,7 @@ import { createTeleportPlayerInteractionLink, createToggleVisibilityInteractionL
|
||||
import { createModelInstance } from "../../src/assets/model-instances";
|
||||
import { createProjectAssetStorageKey, type AudioAssetRecord } from "../../src/assets/project-assets";
|
||||
import { buildRuntimeSceneFromDocument } from "../../src/runtime-three/runtime-scene-build";
|
||||
import { createFixtureLoadedModelAssetFromGeometry } from "../helpers/model-collider-fixtures";
|
||||
|
||||
describe("buildRuntimeSceneFromDocument", () => {
|
||||
it("builds runtime brush data, colliders, and an authored player spawn from the document", () => {
|
||||
@@ -40,7 +42,18 @@ describe("buildRuntimeSceneFromDocument", () => {
|
||||
y: 0,
|
||||
z: -1
|
||||
},
|
||||
yawDegrees: 90
|
||||
yawDegrees: 90,
|
||||
collider: {
|
||||
mode: "box",
|
||||
eyeHeight: 1.4,
|
||||
capsuleRadius: 0.3,
|
||||
capsuleHeight: 1.8,
|
||||
boxSize: {
|
||||
x: 0.8,
|
||||
y: 1.6,
|
||||
z: 0.7
|
||||
}
|
||||
}
|
||||
});
|
||||
const soundEmitter = createSoundEmitterEntity({
|
||||
id: "entity-sound-lobby",
|
||||
@@ -282,20 +295,43 @@ describe("buildRuntimeSceneFromDocument", () => {
|
||||
}
|
||||
}
|
||||
]);
|
||||
expect(runtimeScene.brushes[0].rotationDegrees).toEqual({
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
});
|
||||
expect(runtimeScene.brushes[0].faces.posY.material?.id).toBe("starter-concrete-checker");
|
||||
expect(runtimeScene.colliders).toEqual([
|
||||
{
|
||||
kind: "box",
|
||||
source: "brush",
|
||||
brushId: "brush-room-floor",
|
||||
min: {
|
||||
x: -4,
|
||||
y: -1,
|
||||
z: -4
|
||||
center: {
|
||||
x: 0,
|
||||
y: -0.5,
|
||||
z: 0
|
||||
},
|
||||
max: {
|
||||
x: 4,
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 4
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 8,
|
||||
y: 1,
|
||||
z: 8
|
||||
},
|
||||
worldBounds: {
|
||||
min: {
|
||||
x: -4,
|
||||
y: -1,
|
||||
z: -4
|
||||
},
|
||||
max: {
|
||||
x: 4,
|
||||
y: 0,
|
||||
z: 4
|
||||
}
|
||||
}
|
||||
}
|
||||
]);
|
||||
@@ -330,7 +366,16 @@ describe("buildRuntimeSceneFromDocument", () => {
|
||||
y: 0,
|
||||
z: -1
|
||||
},
|
||||
yawDegrees: 90
|
||||
yawDegrees: 90,
|
||||
collider: {
|
||||
mode: "box",
|
||||
eyeHeight: 1.4,
|
||||
size: {
|
||||
x: 0.8,
|
||||
y: 1.6,
|
||||
z: 0.7
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
soundEmitters: [
|
||||
@@ -462,7 +507,25 @@ describe("buildRuntimeSceneFromDocument", () => {
|
||||
y: 0,
|
||||
z: -1
|
||||
},
|
||||
yawDegrees: 90
|
||||
yawDegrees: 90,
|
||||
collider: {
|
||||
mode: "box",
|
||||
eyeHeight: 1.4,
|
||||
size: {
|
||||
x: 0.8,
|
||||
y: 1.6,
|
||||
z: 0.7
|
||||
}
|
||||
}
|
||||
});
|
||||
expect(runtimeScene.playerCollider).toEqual({
|
||||
mode: "box",
|
||||
eyeHeight: 1.4,
|
||||
size: {
|
||||
x: 0.8,
|
||||
y: 1.6,
|
||||
z: 0.7
|
||||
}
|
||||
});
|
||||
expect(runtimeScene.spawn).toEqual({
|
||||
source: "playerStart",
|
||||
@@ -499,6 +562,12 @@ describe("buildRuntimeSceneFromDocument", () => {
|
||||
});
|
||||
|
||||
expect(runtimeScene.playerStart).toBeNull();
|
||||
expect(runtimeScene.playerCollider).toEqual({
|
||||
mode: "capsule",
|
||||
radius: 0.3,
|
||||
height: 1.8,
|
||||
eyeHeight: 1.6
|
||||
});
|
||||
expect(runtimeScene.entities).toEqual({
|
||||
playerStarts: [],
|
||||
soundEmitters: [],
|
||||
@@ -526,4 +595,109 @@ describe("buildRuntimeSceneFromDocument", () => {
|
||||
})
|
||||
).toThrow("First-person run requires an authored Player Start");
|
||||
});
|
||||
|
||||
it("adds generated imported-model colliders to the runtime scene build", () => {
|
||||
const floorBrush = createBoxBrush({
|
||||
id: "brush-runtime-floor",
|
||||
center: {
|
||||
x: 0,
|
||||
y: -0.5,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 8,
|
||||
y: 1,
|
||||
z: 8
|
||||
}
|
||||
});
|
||||
const { asset, loadedAsset } = createFixtureLoadedModelAssetFromGeometry("asset-runtime-collider", new BoxGeometry(1, 2, 1));
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-runtime-collider",
|
||||
assetId: asset.id,
|
||||
position: {
|
||||
x: 2,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
collision: {
|
||||
mode: "static",
|
||||
visible: true
|
||||
}
|
||||
});
|
||||
|
||||
const runtimeScene = buildRuntimeSceneFromDocument(
|
||||
{
|
||||
...createEmptySceneDocument({ name: "Imported Collider Scene" }),
|
||||
assets: {
|
||||
[asset.id]: asset
|
||||
},
|
||||
brushes: {
|
||||
[floorBrush.id]: floorBrush
|
||||
},
|
||||
modelInstances: {
|
||||
[modelInstance.id]: modelInstance
|
||||
}
|
||||
},
|
||||
{
|
||||
loadedModelAssets: {
|
||||
[asset.id]: loadedAsset
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
expect(runtimeScene.colliders).toHaveLength(2);
|
||||
expect(runtimeScene.colliders[1]).toMatchObject({
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: asset.id,
|
||||
kind: "trimesh",
|
||||
mode: "static",
|
||||
visible: true
|
||||
});
|
||||
expect(runtimeScene.sceneBounds?.max.y).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it("preserves rotated whitebox box transforms for runner rendering and collision bounds", () => {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-rotated-room",
|
||||
center: {
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.75
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 45,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 4
|
||||
}
|
||||
});
|
||||
const runtimeScene = buildRuntimeSceneFromDocument({
|
||||
...createEmptySceneDocument({ name: "Rotated Whitebox Scene" }),
|
||||
brushes: {
|
||||
[brush.id]: brush
|
||||
}
|
||||
});
|
||||
|
||||
expect(runtimeScene.brushes[0]).toMatchObject({
|
||||
center: brush.center,
|
||||
rotationDegrees: brush.rotationDegrees,
|
||||
size: brush.size
|
||||
});
|
||||
expect(runtimeScene.colliders[0]).toMatchObject({
|
||||
source: "brush",
|
||||
brushId: brush.id,
|
||||
center: brush.center,
|
||||
rotationDegrees: brush.rotationDegrees,
|
||||
size: brush.size
|
||||
});
|
||||
expect(runtimeScene.sceneBounds?.min.x).toBeCloseTo(-0.8713203436);
|
||||
expect(runtimeScene.sceneBounds?.max.x).toBeCloseTo(3.3713203436);
|
||||
expect(runtimeScene.sceneBounds?.min.z).toBeCloseTo(-2.8713203436);
|
||||
expect(runtimeScene.sceneBounds?.max.z).toBeCloseTo(1.3713203436);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { createEditorStore } from "../../src/app/editor-store";
|
||||
import { createCreateBoxBrushCommand } from "../../src/commands/create-box-brush-command";
|
||||
import { createMoveBoxBrushCommand } from "../../src/commands/move-box-brush-command";
|
||||
import { createRotateBoxBrushCommand } from "../../src/commands/rotate-box-brush-command";
|
||||
import { createResizeBoxBrushCommand } from "../../src/commands/resize-box-brush-command";
|
||||
import { createSetBoxBrushNameCommand } from "../../src/commands/set-box-brush-name-command";
|
||||
|
||||
@@ -34,6 +35,11 @@ describe("box brush commands", () => {
|
||||
y: 1,
|
||||
z: -1
|
||||
});
|
||||
expect(brush.rotationDegrees).toEqual({
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
});
|
||||
expect(brush.size).toEqual({
|
||||
x: 2,
|
||||
y: 3,
|
||||
@@ -135,6 +141,121 @@ describe("box brush commands", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves floating-point move, rotate, and scale authoring when snapping is disabled", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
store.executeCommand(
|
||||
createCreateBoxBrushCommand({
|
||||
center: {
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.75
|
||||
},
|
||||
size: {
|
||||
x: 2.5,
|
||||
y: 3.25,
|
||||
z: 4.75
|
||||
},
|
||||
snapToGrid: false
|
||||
})
|
||||
);
|
||||
|
||||
const createdBrush = Object.values(store.getState().document.brushes)[0];
|
||||
|
||||
store.executeCommand(
|
||||
createMoveBoxBrushCommand({
|
||||
brushId: createdBrush.id,
|
||||
center: {
|
||||
x: 2.125,
|
||||
y: 3.375,
|
||||
z: -1.625
|
||||
},
|
||||
snapToGrid: false
|
||||
})
|
||||
);
|
||||
store.executeCommand(
|
||||
createRotateBoxBrushCommand({
|
||||
brushId: createdBrush.id,
|
||||
rotationDegrees: {
|
||||
x: 12.5,
|
||||
y: 37.5,
|
||||
z: -8.25
|
||||
}
|
||||
})
|
||||
);
|
||||
store.executeCommand(
|
||||
createResizeBoxBrushCommand({
|
||||
brushId: createdBrush.id,
|
||||
size: {
|
||||
x: 3.5,
|
||||
y: 1.75,
|
||||
z: 5.125
|
||||
},
|
||||
snapToGrid: false
|
||||
})
|
||||
);
|
||||
|
||||
expect(store.getState().document.brushes[createdBrush.id]).toMatchObject({
|
||||
center: {
|
||||
x: 2.125,
|
||||
y: 3.375,
|
||||
z: -1.625
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 12.5,
|
||||
y: 37.5,
|
||||
z: -8.25
|
||||
},
|
||||
size: {
|
||||
x: 3.5,
|
||||
y: 1.75,
|
||||
z: 5.125
|
||||
}
|
||||
});
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().document.brushes[createdBrush.id].size).toEqual({
|
||||
x: 2.5,
|
||||
y: 3.25,
|
||||
z: 4.75
|
||||
});
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().document.brushes[createdBrush.id].rotationDegrees).toEqual({
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
});
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().document.brushes[createdBrush.id].center).toEqual({
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.75
|
||||
});
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
expect(store.redo()).toBe(true);
|
||||
expect(store.redo()).toBe(true);
|
||||
expect(store.getState().document.brushes[createdBrush.id]).toMatchObject({
|
||||
center: {
|
||||
x: 2.125,
|
||||
y: 3.375,
|
||||
z: -1.625
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 12.5,
|
||||
y: 37.5,
|
||||
z: -8.25
|
||||
},
|
||||
size: {
|
||||
x: 3.5,
|
||||
y: 1.75,
|
||||
z: 5.125
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("renames a box brush through an undoable command", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createEditorStore } from "../../src/app/editor-store";
|
||||
import { createCreateBoxBrushCommand } from "../../src/commands/create-box-brush-command";
|
||||
import { createSetSceneNameCommand } from "../../src/commands/set-scene-name-command";
|
||||
import { createTransformSession } from "../../src/core/transform-session";
|
||||
import { createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
import type { KeyValueStorage } from "../../src/serialization/local-draft-storage";
|
||||
|
||||
@@ -70,6 +72,23 @@ describe("EditorStore", () => {
|
||||
const writerStore = createEditorStore({ storage });
|
||||
|
||||
writerStore.executeCommand(createSetSceneNameCommand("Draft Scene"));
|
||||
writerStore.setViewportLayoutMode("quad");
|
||||
writerStore.setActiveViewportPanel("bottomRight");
|
||||
writerStore.setViewportPanelViewMode("topLeft", "top");
|
||||
writerStore.setViewportPanelDisplayMode("topLeft", "wireframe");
|
||||
writerStore.setViewportPanelCameraState("topLeft", {
|
||||
target: {
|
||||
x: 6,
|
||||
y: 2,
|
||||
z: -4
|
||||
},
|
||||
perspectiveOrbit: {
|
||||
radius: 18,
|
||||
theta: 0.9,
|
||||
phi: 1.1
|
||||
},
|
||||
orthographicZoom: 2.25
|
||||
});
|
||||
expect(writerStore.saveDraft()).toEqual({
|
||||
status: "saved",
|
||||
message: "Local draft saved."
|
||||
@@ -85,6 +104,25 @@ describe("EditorStore", () => {
|
||||
message: "Local draft loaded."
|
||||
});
|
||||
expect(readerStore.getState().document.name).toBe("Draft Scene");
|
||||
expect(readerStore.getState().viewportLayoutMode).toBe("quad");
|
||||
expect(readerStore.getState().activeViewportPanelId).toBe("bottomRight");
|
||||
expect(readerStore.getState().viewportPanels.topLeft).toMatchObject({
|
||||
viewMode: "top",
|
||||
displayMode: "wireframe",
|
||||
cameraState: {
|
||||
target: {
|
||||
x: 6,
|
||||
y: 2,
|
||||
z: -4
|
||||
},
|
||||
perspectiveOrbit: {
|
||||
radius: 18,
|
||||
theta: 0.9,
|
||||
phi: 1.1
|
||||
},
|
||||
orthographicZoom: 2.25
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("fails gracefully when storage access throws", () => {
|
||||
@@ -104,13 +142,284 @@ describe("EditorStore", () => {
|
||||
it("restores the previous editor tool when leaving play mode", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
store.setToolMode("box-create");
|
||||
store.setToolMode("create");
|
||||
store.enterPlayMode();
|
||||
|
||||
expect(store.getState().toolMode).toBe("play");
|
||||
|
||||
store.exitPlayMode();
|
||||
|
||||
expect(store.getState().toolMode).toBe("box-create");
|
||||
expect(store.getState().toolMode).toBe("create");
|
||||
});
|
||||
|
||||
it("tracks viewport layout and per-panel state independently from the document", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
expect(store.getState().whiteboxSelectionMode).toBe("object");
|
||||
expect(store.getState().viewportLayoutMode).toBe("single");
|
||||
expect(store.getState().activeViewportPanelId).toBe("topLeft");
|
||||
expect(store.getState().viewportPanels.topLeft.viewMode).toBe("perspective");
|
||||
expect(store.getState().viewportPanels.topRight.viewMode).toBe("top");
|
||||
expect(store.getState().viewportPanels.topRight.displayMode).toBe("authoring");
|
||||
expect(store.getState().viewportQuadSplit).toEqual({
|
||||
x: 0.5,
|
||||
y: 0.5
|
||||
});
|
||||
|
||||
store.setViewportLayoutMode("quad");
|
||||
store.setActiveViewportPanel("bottomRight");
|
||||
store.setViewportPanelViewMode("bottomRight", "front");
|
||||
store.setViewportPanelDisplayMode("bottomRight", "normal");
|
||||
store.setViewportQuadSplit({
|
||||
x: 0.38,
|
||||
y: 0.62
|
||||
});
|
||||
|
||||
expect(store.getState().viewportLayoutMode).toBe("quad");
|
||||
expect(store.getState().activeViewportPanelId).toBe("bottomRight");
|
||||
expect(store.getState().viewportPanels.bottomRight.viewMode).toBe("front");
|
||||
expect(store.getState().viewportPanels.bottomRight.displayMode).toBe("normal");
|
||||
expect(store.getState().viewportQuadSplit).toEqual({
|
||||
x: 0.38,
|
||||
y: 0.62
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks whitebox component selection mode independently from document state", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
store.setWhiteboxSelectionMode("face");
|
||||
expect(store.getState().whiteboxSelectionMode).toBe("face");
|
||||
|
||||
store.setWhiteboxSelectionMode("edge");
|
||||
expect(store.getState().whiteboxSelectionMode).toBe("edge");
|
||||
|
||||
store.setWhiteboxSelectionMode("vertex");
|
||||
expect(store.getState().whiteboxSelectionMode).toBe("vertex");
|
||||
|
||||
store.setWhiteboxSelectionMode("object");
|
||||
expect(store.getState().whiteboxSelectionMode).toBe("object");
|
||||
});
|
||||
|
||||
it("normalizes selected whitebox components back to the owning solid when switching to a different component mode", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
store.executeCommand(createCreateBoxBrushCommand());
|
||||
const createdBrush = Object.values(store.getState().document.brushes)[0];
|
||||
|
||||
store.setWhiteboxSelectionMode("face");
|
||||
store.setSelection({
|
||||
kind: "brushFace",
|
||||
brushId: createdBrush.id,
|
||||
faceId: "posY"
|
||||
});
|
||||
|
||||
expect(store.getState().selection).toEqual({
|
||||
kind: "brushFace",
|
||||
brushId: createdBrush.id,
|
||||
faceId: "posY"
|
||||
});
|
||||
|
||||
store.setWhiteboxSelectionMode("edge");
|
||||
expect(store.getState().selection).toEqual({
|
||||
kind: "brushes",
|
||||
ids: [createdBrush.id]
|
||||
});
|
||||
|
||||
store.setSelection({
|
||||
kind: "brushEdge",
|
||||
brushId: createdBrush.id,
|
||||
edgeId: "edgeX_posY_negZ"
|
||||
});
|
||||
store.setWhiteboxSelectionMode("vertex");
|
||||
expect(store.getState().selection).toEqual({
|
||||
kind: "brushes",
|
||||
ids: [createdBrush.id]
|
||||
});
|
||||
|
||||
store.setSelection({
|
||||
kind: "brushVertex",
|
||||
brushId: createdBrush.id,
|
||||
vertexId: "posX_posY_negZ"
|
||||
});
|
||||
store.setWhiteboxSelectionMode("object");
|
||||
expect(store.getState().selection).toEqual({
|
||||
kind: "brushes",
|
||||
ids: [createdBrush.id]
|
||||
});
|
||||
});
|
||||
|
||||
it("shares transient creation preview state across viewport panels", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
expect(store.getState().viewportTransientState.toolPreview).toEqual({
|
||||
kind: "none"
|
||||
});
|
||||
|
||||
store.setViewportToolPreview({
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "box-brush"
|
||||
},
|
||||
center: {
|
||||
x: 4,
|
||||
y: 0,
|
||||
z: 8
|
||||
}
|
||||
});
|
||||
|
||||
expect(store.getState().viewportTransientState.toolPreview).toEqual({
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "box-brush"
|
||||
},
|
||||
center: {
|
||||
x: 4,
|
||||
y: 0,
|
||||
z: 8
|
||||
}
|
||||
});
|
||||
|
||||
store.setViewportToolPreview({
|
||||
kind: "create",
|
||||
sourcePanelId: "bottomRight",
|
||||
target: {
|
||||
kind: "entity",
|
||||
entityKind: "pointLight",
|
||||
audioAssetId: null
|
||||
},
|
||||
center: {
|
||||
x: 2,
|
||||
y: 1,
|
||||
z: -3
|
||||
}
|
||||
});
|
||||
|
||||
expect(store.getState().viewportTransientState.toolPreview).toEqual({
|
||||
kind: "create",
|
||||
sourcePanelId: "bottomRight",
|
||||
target: {
|
||||
kind: "entity",
|
||||
entityKind: "pointLight",
|
||||
audioAssetId: null
|
||||
},
|
||||
center: {
|
||||
x: 2,
|
||||
y: 1,
|
||||
z: -3
|
||||
}
|
||||
});
|
||||
|
||||
store.clearViewportToolPreview("topRight");
|
||||
expect(store.getState().viewportTransientState.toolPreview).toEqual({
|
||||
kind: "create",
|
||||
sourcePanelId: "bottomRight",
|
||||
target: {
|
||||
kind: "entity",
|
||||
entityKind: "pointLight",
|
||||
audioAssetId: null
|
||||
},
|
||||
center: {
|
||||
x: 2,
|
||||
y: 1,
|
||||
z: -3
|
||||
}
|
||||
});
|
||||
|
||||
store.clearViewportToolPreview("bottomRight");
|
||||
expect(store.getState().viewportTransientState.toolPreview).toEqual({
|
||||
kind: "none"
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks a shared transient transform session and clears it when selection changes", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
store.setTransformSession(
|
||||
createTransformSession({
|
||||
source: "keyboard",
|
||||
sourcePanelId: "bottomRight",
|
||||
operation: "translate",
|
||||
target: {
|
||||
kind: "brush",
|
||||
brushId: "brush-main",
|
||||
initialCenter: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
initialRotationDegrees: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
initialSize: {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 2
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
expect(store.getState().viewportTransientState.transformSession).toMatchObject({
|
||||
kind: "active",
|
||||
source: "keyboard",
|
||||
sourcePanelId: "bottomRight",
|
||||
operation: "translate",
|
||||
target: {
|
||||
kind: "brush",
|
||||
brushId: "brush-main"
|
||||
},
|
||||
preview: {
|
||||
kind: "brush",
|
||||
center: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 2
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
store.setSelection({
|
||||
kind: "brushes",
|
||||
ids: ["brush-main"]
|
||||
});
|
||||
|
||||
expect(store.getState().viewportTransientState.transformSession).toEqual({
|
||||
kind: "none"
|
||||
});
|
||||
});
|
||||
|
||||
it("clears transient viewport preview when leaving create mode", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
store.setToolMode("create");
|
||||
store.setViewportToolPreview({
|
||||
kind: "create",
|
||||
sourcePanelId: "bottomRight",
|
||||
target: {
|
||||
kind: "model-instance",
|
||||
assetId: "asset-1"
|
||||
},
|
||||
center: null
|
||||
});
|
||||
store.setToolMode("select");
|
||||
|
||||
expect(store.getState().viewportTransientState.toolPreview).toEqual({
|
||||
kind: "none"
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,7 +19,7 @@ describe("typed entity upsert command", () => {
|
||||
maxDistance: 12
|
||||
});
|
||||
|
||||
store.setToolMode("box-create");
|
||||
store.setToolMode("create");
|
||||
store.executeCommand(
|
||||
createUpsertEntityCommand({
|
||||
entity: soundEmitter,
|
||||
@@ -35,7 +35,7 @@ describe("typed entity upsert command", () => {
|
||||
expect(store.getState().document.entities[soundEmitter.id]).toEqual(soundEmitter);
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().toolMode).toBe("box-create");
|
||||
expect(store.getState().toolMode).toBe("create");
|
||||
expect(store.getState().document.entities).toEqual({});
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
@@ -56,7 +56,7 @@ describe("typed entity upsert command", () => {
|
||||
distance: 9
|
||||
});
|
||||
|
||||
store.setToolMode("box-create");
|
||||
store.setToolMode("create");
|
||||
store.executeCommand(
|
||||
createUpsertEntityCommand({
|
||||
entity: pointLight,
|
||||
@@ -72,7 +72,7 @@ describe("typed entity upsert command", () => {
|
||||
expect(store.getState().document.entities[pointLight.id]).toEqual(pointLight);
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().toolMode).toBe("box-create");
|
||||
expect(store.getState().toolMode).toBe("create");
|
||||
expect(store.getState().document.entities).toEqual({});
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
@@ -112,7 +112,7 @@ describe("typed entity upsert command", () => {
|
||||
label: "Place trigger volume"
|
||||
})
|
||||
);
|
||||
store.setToolMode("box-create");
|
||||
store.setToolMode("create");
|
||||
store.executeCommand(
|
||||
createUpsertEntityCommand({
|
||||
entity: movedTriggerVolume,
|
||||
@@ -124,7 +124,7 @@ describe("typed entity upsert command", () => {
|
||||
expect(store.getState().document.entities[triggerVolume.id]).toEqual(movedTriggerVolume);
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().toolMode).toBe("box-create");
|
||||
expect(store.getState().toolMode).toBe("create");
|
||||
expect(store.getState().document.entities[triggerVolume.id]).toEqual(triggerVolume);
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
@@ -165,7 +165,7 @@ describe("typed entity upsert command", () => {
|
||||
label: "Place spot light"
|
||||
})
|
||||
);
|
||||
store.setToolMode("box-create");
|
||||
store.setToolMode("create");
|
||||
store.executeCommand(
|
||||
createUpsertEntityCommand({
|
||||
entity: movedSpotLight,
|
||||
@@ -177,7 +177,7 @@ describe("typed entity upsert command", () => {
|
||||
expect(store.getState().document.entities[spotLight.id]).toEqual(movedSpotLight);
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().toolMode).toBe("box-create");
|
||||
expect(store.getState().toolMode).toBe("create");
|
||||
expect(store.getState().document.entities[spotLight.id]).toEqual(spotLight);
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
|
||||
@@ -7,7 +7,7 @@ describe("player start command", () => {
|
||||
it("restores the previous tool mode across undo and redo when placing PlayerStart", () => {
|
||||
const store = createEditorStore();
|
||||
|
||||
store.setToolMode("box-create");
|
||||
store.setToolMode("create");
|
||||
store.executeCommand(
|
||||
createSetPlayerStartCommand({
|
||||
position: {
|
||||
@@ -25,7 +25,7 @@ describe("player start command", () => {
|
||||
expect(store.getState().toolMode).toBe("select");
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().toolMode).toBe("box-create");
|
||||
expect(store.getState().toolMode).toBe("create");
|
||||
expect(store.getState().document.entities).toEqual({});
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
@@ -49,7 +49,7 @@ describe("player start command", () => {
|
||||
|
||||
const existingPlayerStart = Object.values(store.getState().document.entities)[0];
|
||||
|
||||
store.setToolMode("box-create");
|
||||
store.setToolMode("create");
|
||||
store.executeCommand(
|
||||
createSetPlayerStartCommand({
|
||||
entityId: existingPlayerStart.id,
|
||||
@@ -73,7 +73,7 @@ describe("player start command", () => {
|
||||
});
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().toolMode).toBe("box-create");
|
||||
expect(store.getState().toolMode).toBe("create");
|
||||
expect(store.getState().document.entities[existingPlayerStart.id]).toEqual(existingPlayerStart);
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
|
||||
414
tests/domain/rapier-collision-world.test.ts
Normal file
414
tests/domain/rapier-collision-world.test.ts
Normal file
@@ -0,0 +1,414 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BoxGeometry, PlaneGeometry } from "three";
|
||||
|
||||
import { createModelInstance } from "../../src/assets/model-instances";
|
||||
import { createBoxBrush } from "../../src/document/brushes";
|
||||
import { createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
import { createPlayerStartEntity } from "../../src/entities/entity-instances";
|
||||
import { RapierCollisionWorld } from "../../src/runtime-three/rapier-collision-world";
|
||||
import { buildRuntimeSceneFromDocument } from "../../src/runtime-three/runtime-scene-build";
|
||||
import { createFixtureLoadedModelAssetFromGeometry } from "../helpers/model-collider-fixtures";
|
||||
|
||||
describe("RapierCollisionWorld", () => {
|
||||
it("resolves first-person motion against brush and imported model colliders in one query path", async () => {
|
||||
const floorBrush = createBoxBrush({
|
||||
id: "brush-floor",
|
||||
center: {
|
||||
x: 0,
|
||||
y: -0.5,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 10,
|
||||
y: 1,
|
||||
z: 10
|
||||
}
|
||||
});
|
||||
const { asset, loadedAsset } = createFixtureLoadedModelAssetFromGeometry("asset-model-crate", new BoxGeometry(1, 1, 1));
|
||||
const crateInstance = createModelInstance({
|
||||
id: "model-instance-crate",
|
||||
assetId: asset.id,
|
||||
position: {
|
||||
x: 2,
|
||||
y: 0.5,
|
||||
z: 0
|
||||
},
|
||||
collision: {
|
||||
mode: "static",
|
||||
visible: true
|
||||
}
|
||||
});
|
||||
const runtimeScene = buildRuntimeSceneFromDocument(
|
||||
{
|
||||
...createEmptySceneDocument({ name: "Brush And Model Collision Scene" }),
|
||||
assets: {
|
||||
[asset.id]: asset
|
||||
},
|
||||
brushes: {
|
||||
[floorBrush.id]: floorBrush
|
||||
},
|
||||
modelInstances: {
|
||||
[crateInstance.id]: crateInstance
|
||||
}
|
||||
},
|
||||
{
|
||||
loadedModelAssets: {
|
||||
[asset.id]: loadedAsset
|
||||
}
|
||||
}
|
||||
);
|
||||
const collisionWorld = await RapierCollisionWorld.create(runtimeScene.colliders, runtimeScene.playerCollider);
|
||||
|
||||
try {
|
||||
const landing = collisionWorld.resolveFirstPersonMotion(
|
||||
{
|
||||
x: 0,
|
||||
y: 2,
|
||||
z: 0
|
||||
},
|
||||
{
|
||||
x: 0,
|
||||
y: -3,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
|
||||
expect(landing.grounded).toBe(true);
|
||||
expect(landing.feetPosition.y).toBeLessThan(0.02);
|
||||
|
||||
const blocked = collisionWorld.resolveFirstPersonMotion(
|
||||
{
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
{
|
||||
x: 3,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
|
||||
expect(blocked.feetPosition.x).toBeLessThan(1.21);
|
||||
expect(blocked.feetPosition.y).toBeLessThan(0.02);
|
||||
expect(blocked.collidedAxes.x).toBe(true);
|
||||
} finally {
|
||||
collisionWorld.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("initializes and resolves first-person motion against terrain heightfield colliders", async () => {
|
||||
const terrainGeometry = new PlaneGeometry(8, 8, 4, 4);
|
||||
terrainGeometry.rotateX(-Math.PI / 2);
|
||||
const positionAttribute = terrainGeometry.getAttribute("position");
|
||||
|
||||
for (let index = 0; index < positionAttribute.count; index += 1) {
|
||||
const x = positionAttribute.getX(index);
|
||||
const z = positionAttribute.getZ(index);
|
||||
positionAttribute.setY(index, 2 + x * 0.25 + z * 0.75);
|
||||
}
|
||||
|
||||
positionAttribute.needsUpdate = true;
|
||||
terrainGeometry.computeVertexNormals();
|
||||
|
||||
const { asset, loadedAsset } = createFixtureLoadedModelAssetFromGeometry("asset-model-terrain", terrainGeometry);
|
||||
const terrainInstance = createModelInstance({
|
||||
id: "model-instance-terrain",
|
||||
assetId: asset.id,
|
||||
position: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
collision: {
|
||||
mode: "terrain",
|
||||
visible: true
|
||||
}
|
||||
});
|
||||
const runtimeScene = buildRuntimeSceneFromDocument(
|
||||
{
|
||||
...createEmptySceneDocument({ name: "Terrain Collision Scene" }),
|
||||
assets: {
|
||||
[asset.id]: asset
|
||||
},
|
||||
modelInstances: {
|
||||
[terrainInstance.id]: terrainInstance
|
||||
}
|
||||
},
|
||||
{
|
||||
loadedModelAssets: {
|
||||
[asset.id]: loadedAsset
|
||||
}
|
||||
}
|
||||
);
|
||||
const collisionWorld = await RapierCollisionWorld.create(runtimeScene.colliders, runtimeScene.playerCollider);
|
||||
|
||||
try {
|
||||
const highLanding = collisionWorld.resolveFirstPersonMotion(
|
||||
{
|
||||
x: -2,
|
||||
y: 6,
|
||||
z: 2
|
||||
},
|
||||
{
|
||||
x: 0,
|
||||
y: -8,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
const lowLanding = collisionWorld.resolveFirstPersonMotion(
|
||||
{
|
||||
x: 2,
|
||||
y: 6,
|
||||
z: -2
|
||||
},
|
||||
{
|
||||
x: 0,
|
||||
y: -8,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
|
||||
expect(highLanding.grounded).toBe(true);
|
||||
expect(highLanding.feetPosition.y).toBeGreaterThan(2.9);
|
||||
expect(highLanding.feetPosition.y).toBeLessThan(3.1);
|
||||
expect(lowLanding.grounded).toBe(true);
|
||||
expect(lowLanding.feetPosition.y).toBeGreaterThan(0.9);
|
||||
expect(lowLanding.feetPosition.y).toBeLessThan(1.1);
|
||||
|
||||
const traversed = collisionWorld.resolveFirstPersonMotion(
|
||||
highLanding.feetPosition,
|
||||
{
|
||||
x: -1,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
|
||||
expect(traversed.feetPosition.x).toBeLessThan(-2.5);
|
||||
expect(traversed.collidedAxes.x).toBe(false);
|
||||
} finally {
|
||||
collisionWorld.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves motion against freely rotated whitebox box colliders", async () => {
|
||||
const floorBrush = createBoxBrush({
|
||||
id: "brush-floor-rotated-wall",
|
||||
center: {
|
||||
x: 0,
|
||||
y: -0.5,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 10,
|
||||
y: 1,
|
||||
z: 10
|
||||
}
|
||||
});
|
||||
const wallBrush = createBoxBrush({
|
||||
id: "brush-wall-rotated",
|
||||
center: {
|
||||
x: 1.2,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 45,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 0.4,
|
||||
y: 2,
|
||||
z: 4
|
||||
}
|
||||
});
|
||||
const runtimeScene = buildRuntimeSceneFromDocument({
|
||||
...createEmptySceneDocument({ name: "Rotated Brush Collision Scene" }),
|
||||
brushes: {
|
||||
[floorBrush.id]: floorBrush,
|
||||
[wallBrush.id]: wallBrush
|
||||
}
|
||||
});
|
||||
const collisionWorld = await RapierCollisionWorld.create(runtimeScene.colliders, runtimeScene.playerCollider);
|
||||
|
||||
try {
|
||||
const blocked = collisionWorld.resolveFirstPersonMotion(
|
||||
{
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
{
|
||||
x: 2,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
|
||||
expect(blocked.collidedAxes.x).toBe(true);
|
||||
expect(blocked.feetPosition.x).toBeLessThan(1.3);
|
||||
expect(blocked.feetPosition.z).toBeGreaterThan(0.25);
|
||||
expect(blocked.feetPosition.z).toBeLessThan(1.25);
|
||||
} finally {
|
||||
collisionWorld.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the authored Player Start box collider in the Rapier motion path", async () => {
|
||||
const floorBrush = createBoxBrush({
|
||||
id: "brush-floor-box-player",
|
||||
center: {
|
||||
x: 0,
|
||||
y: -0.5,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 10,
|
||||
y: 1,
|
||||
z: 10
|
||||
}
|
||||
});
|
||||
const wallBrush = createBoxBrush({
|
||||
id: "brush-wall-box-player",
|
||||
center: {
|
||||
x: 1.2,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 0.4,
|
||||
y: 2,
|
||||
z: 4
|
||||
}
|
||||
});
|
||||
const playerStart = createPlayerStartEntity({
|
||||
id: "entity-player-start-box",
|
||||
collider: {
|
||||
mode: "box",
|
||||
eyeHeight: 1.4,
|
||||
capsuleRadius: 0.3,
|
||||
capsuleHeight: 1.8,
|
||||
boxSize: {
|
||||
x: 0.8,
|
||||
y: 1.6,
|
||||
z: 0.8
|
||||
}
|
||||
}
|
||||
});
|
||||
const runtimeScene = buildRuntimeSceneFromDocument({
|
||||
...createEmptySceneDocument({ name: "Box Player Collider Scene" }),
|
||||
brushes: {
|
||||
[floorBrush.id]: floorBrush,
|
||||
[wallBrush.id]: wallBrush
|
||||
},
|
||||
entities: {
|
||||
[playerStart.id]: playerStart
|
||||
}
|
||||
});
|
||||
const collisionWorld = await RapierCollisionWorld.create(runtimeScene.colliders, runtimeScene.playerCollider);
|
||||
|
||||
try {
|
||||
const landing = collisionWorld.resolveFirstPersonMotion(
|
||||
{
|
||||
x: 0,
|
||||
y: 2,
|
||||
z: 0
|
||||
},
|
||||
{
|
||||
x: 0,
|
||||
y: -3,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
|
||||
expect(landing.grounded).toBe(true);
|
||||
expect(landing.feetPosition.y).toBeLessThan(0.02);
|
||||
|
||||
const blocked = collisionWorld.resolveFirstPersonMotion(
|
||||
landing.feetPosition,
|
||||
{
|
||||
x: 2,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
|
||||
expect(blocked.collidedAxes.x).toBe(true);
|
||||
expect(blocked.feetPosition.x).toBeLessThan(0.61);
|
||||
} finally {
|
||||
collisionWorld.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("supports authored Player Start collision mode none without world clipping", async () => {
|
||||
const wallBrush = createBoxBrush({
|
||||
id: "brush-wall-no-collision",
|
||||
center: {
|
||||
x: 0.5,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 0.4,
|
||||
y: 2,
|
||||
z: 4
|
||||
}
|
||||
});
|
||||
const playerStart = createPlayerStartEntity({
|
||||
id: "entity-player-start-none",
|
||||
collider: {
|
||||
mode: "none",
|
||||
eyeHeight: 1.6,
|
||||
capsuleRadius: 0.3,
|
||||
capsuleHeight: 1.8,
|
||||
boxSize: {
|
||||
x: 0.6,
|
||||
y: 1.8,
|
||||
z: 0.6
|
||||
}
|
||||
}
|
||||
});
|
||||
const runtimeScene = buildRuntimeSceneFromDocument({
|
||||
...createEmptySceneDocument({ name: "No Collision Player Scene" }),
|
||||
brushes: {
|
||||
[wallBrush.id]: wallBrush
|
||||
},
|
||||
entities: {
|
||||
[playerStart.id]: playerStart
|
||||
}
|
||||
});
|
||||
const collisionWorld = await RapierCollisionWorld.create(runtimeScene.colliders, runtimeScene.playerCollider);
|
||||
|
||||
try {
|
||||
const moved = collisionWorld.resolveFirstPersonMotion(
|
||||
{
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
{
|
||||
x: 2,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
runtimeScene.playerCollider
|
||||
);
|
||||
|
||||
expect(moved.collidedAxes.x).toBe(false);
|
||||
expect(moved.feetPosition.x).toBe(2);
|
||||
expect(moved.feetPosition.y).toBe(0);
|
||||
} finally {
|
||||
collisionWorld.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -115,6 +115,12 @@ function createRuntimeSceneFixture(): RuntimeSceneDefinition {
|
||||
},
|
||||
interactionLinks: [],
|
||||
playerStart: null,
|
||||
playerCollider: {
|
||||
mode: "capsule",
|
||||
radius: 0.3,
|
||||
height: 1.8,
|
||||
eyeHeight: 1.6
|
||||
},
|
||||
spawn: {
|
||||
source: "fallback",
|
||||
entityId: null,
|
||||
|
||||
101
tests/domain/runtime-scene-validation.test.ts
Normal file
101
tests/domain/runtime-scene-validation.test.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BoxGeometry } from "three";
|
||||
|
||||
import { createModelInstance } from "../../src/assets/model-instances";
|
||||
import { createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
import { validateRuntimeSceneBuild } from "../../src/runtime-three/runtime-scene-validation";
|
||||
import { createFixtureLoadedModelAssetFromGeometry } from "../helpers/model-collider-fixtures";
|
||||
|
||||
describe("validateRuntimeSceneBuild", () => {
|
||||
it("reports missing loaded geometry for collider modes that depend on imported mesh data", () => {
|
||||
const { asset } = createFixtureLoadedModelAssetFromGeometry("asset-model-static-validation", new BoxGeometry(1, 1, 1));
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-static-validation",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "static",
|
||||
visible: false
|
||||
}
|
||||
});
|
||||
const validation = validateRuntimeSceneBuild(
|
||||
{
|
||||
...createEmptySceneDocument({ name: "Missing Model Geometry Scene" }),
|
||||
assets: {
|
||||
[asset.id]: asset
|
||||
},
|
||||
modelInstances: {
|
||||
[modelInstance.id]: modelInstance
|
||||
}
|
||||
},
|
||||
{
|
||||
navigationMode: "orbitVisitor",
|
||||
loadedModelAssets: {}
|
||||
}
|
||||
);
|
||||
|
||||
expect(validation.errors.map((diagnostic) => diagnostic.code)).toContain("missing-model-collider-geometry");
|
||||
});
|
||||
|
||||
it("fails terrain mode clearly when the source mesh is incompatible with the heightfield path", () => {
|
||||
const { asset, loadedAsset } = createFixtureLoadedModelAssetFromGeometry("asset-model-terrain-validation", new BoxGeometry(1, 1, 1));
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-terrain-validation",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "terrain",
|
||||
visible: true
|
||||
}
|
||||
});
|
||||
const validation = validateRuntimeSceneBuild(
|
||||
{
|
||||
...createEmptySceneDocument({ name: "Invalid Terrain Scene" }),
|
||||
assets: {
|
||||
[asset.id]: asset
|
||||
},
|
||||
modelInstances: {
|
||||
[modelInstance.id]: modelInstance
|
||||
}
|
||||
},
|
||||
{
|
||||
navigationMode: "orbitVisitor",
|
||||
loadedModelAssets: {
|
||||
[asset.id]: loadedAsset
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
expect(validation.errors.map((diagnostic) => diagnostic.code)).toContain("unsupported-terrain-model-collider");
|
||||
});
|
||||
|
||||
it("warns that dynamic collision currently participates as fixed queryable world geometry", () => {
|
||||
const { asset, loadedAsset } = createFixtureLoadedModelAssetFromGeometry("asset-model-dynamic-validation", new BoxGeometry(1, 1, 1));
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-dynamic-validation",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "dynamic",
|
||||
visible: false
|
||||
}
|
||||
});
|
||||
const validation = validateRuntimeSceneBuild(
|
||||
{
|
||||
...createEmptySceneDocument({ name: "Dynamic Collider Scene" }),
|
||||
assets: {
|
||||
[asset.id]: asset
|
||||
},
|
||||
modelInstances: {
|
||||
[modelInstance.id]: modelInstance
|
||||
}
|
||||
},
|
||||
{
|
||||
navigationMode: "orbitVisitor",
|
||||
loadedModelAssets: {
|
||||
[asset.id]: loadedAsset
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
expect(validation.errors).toEqual([]);
|
||||
expect(validation.warnings.map((diagnostic) => diagnostic.code)).toContain("dynamic-model-collider-fixed-query-only");
|
||||
});
|
||||
});
|
||||
@@ -73,6 +73,7 @@ describe("validateSceneDocument", () => {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-invalid"
|
||||
});
|
||||
brush.rotationDegrees.y = Number.NaN;
|
||||
brush.size.x = 0;
|
||||
brush.faces.posZ.materialId = "material-that-does-not-exist";
|
||||
|
||||
@@ -85,6 +86,10 @@ describe("validateSceneDocument", () => {
|
||||
|
||||
expect(validation.errors).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
code: "invalid-box-rotation",
|
||||
path: "brushes.brush-invalid.rotationDegrees"
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "invalid-box-size",
|
||||
path: "brushes.brush-invalid.size"
|
||||
@@ -109,7 +114,18 @@ describe("validateSceneDocument", () => {
|
||||
y: Number.NaN,
|
||||
z: 0
|
||||
},
|
||||
yawDegrees: Number.NaN
|
||||
yawDegrees: Number.NaN,
|
||||
collider: {
|
||||
mode: "capsule",
|
||||
eyeHeight: 3,
|
||||
capsuleRadius: 0.4,
|
||||
capsuleHeight: 0.5,
|
||||
boxSize: {
|
||||
x: 0.6,
|
||||
y: -1,
|
||||
z: 0.6
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -121,6 +137,15 @@ describe("validateSceneDocument", () => {
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "invalid-player-start-yaw"
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "invalid-player-start-capsule-proportions"
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "invalid-player-start-box-size"
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "invalid-player-start-eye-height"
|
||||
})
|
||||
])
|
||||
);
|
||||
|
||||
444
tests/domain/transform-session.command.test.ts
Normal file
444
tests/domain/transform-session.command.test.ts
Normal file
@@ -0,0 +1,444 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createEditorStore } from "../../src/app/editor-store";
|
||||
import { createModelInstance } from "../../src/assets/model-instances";
|
||||
import { createProjectAssetStorageKey, type ModelAssetRecord } from "../../src/assets/project-assets";
|
||||
import { createCommitTransformSessionCommand } from "../../src/commands/commit-transform-session-command";
|
||||
import {
|
||||
createTransformSession,
|
||||
resolveTransformTarget,
|
||||
supportsTransformOperation
|
||||
} from "../../src/core/transform-session";
|
||||
import { createBoxBrush } from "../../src/document/brushes";
|
||||
import { createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
import { createPlayerStartEntity } from "../../src/entities/entity-instances";
|
||||
|
||||
const modelAsset = {
|
||||
id: "asset-model-transform-fixture",
|
||||
kind: "model",
|
||||
sourceName: "transform-fixture.glb",
|
||||
mimeType: "model/gltf-binary",
|
||||
storageKey: createProjectAssetStorageKey("asset-model-transform-fixture"),
|
||||
byteLength: 64,
|
||||
metadata: {
|
||||
kind: "model",
|
||||
format: "glb",
|
||||
sceneName: "Transform Fixture",
|
||||
nodeCount: 1,
|
||||
meshCount: 1,
|
||||
materialNames: [],
|
||||
textureNames: [],
|
||||
animationNames: [],
|
||||
boundingBox: {
|
||||
min: {
|
||||
x: -0.5,
|
||||
y: 0,
|
||||
z: -0.5
|
||||
},
|
||||
max: {
|
||||
x: 0.5,
|
||||
y: 1,
|
||||
z: 0.5
|
||||
},
|
||||
size: {
|
||||
x: 1,
|
||||
y: 1,
|
||||
z: 1
|
||||
}
|
||||
},
|
||||
warnings: []
|
||||
}
|
||||
} satisfies ModelAssetRecord;
|
||||
|
||||
describe("transform session commit commands", () => {
|
||||
it("requires Object mode for whitebox box transforms and does not silently promote component selections", () => {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-main"
|
||||
});
|
||||
const document = {
|
||||
...createEmptySceneDocument(),
|
||||
brushes: {
|
||||
[brush.id]: brush
|
||||
}
|
||||
};
|
||||
|
||||
const faceResolved = resolveTransformTarget(document, {
|
||||
kind: "brushFace",
|
||||
brushId: brush.id,
|
||||
faceId: "posZ"
|
||||
});
|
||||
const edgeResolved = resolveTransformTarget(
|
||||
document,
|
||||
{
|
||||
kind: "brushEdge",
|
||||
brushId: brush.id,
|
||||
edgeId: "edgeX_posY_negZ"
|
||||
},
|
||||
"edge"
|
||||
);
|
||||
const vertexResolved = resolveTransformTarget(
|
||||
document,
|
||||
{
|
||||
kind: "brushVertex",
|
||||
brushId: brush.id,
|
||||
vertexId: "posX_posY_negZ"
|
||||
},
|
||||
"vertex"
|
||||
);
|
||||
const faceModeBrushResolved = resolveTransformTarget(
|
||||
document,
|
||||
{
|
||||
kind: "brushes",
|
||||
ids: [brush.id]
|
||||
},
|
||||
"face"
|
||||
);
|
||||
const objectResolved = resolveTransformTarget(document, {
|
||||
kind: "brushes",
|
||||
ids: [brush.id]
|
||||
});
|
||||
|
||||
expect(faceResolved.target).toBeNull();
|
||||
expect(faceResolved.message).toContain("Face selection");
|
||||
expect(edgeResolved.target).toBeNull();
|
||||
expect(edgeResolved.message).toContain("Edge transforms");
|
||||
expect(vertexResolved.target).toBeNull();
|
||||
expect(vertexResolved.message).toContain("Vertex transforms");
|
||||
expect(faceModeBrushResolved.target).toBeNull();
|
||||
expect(faceModeBrushResolved.message).toContain("Object mode");
|
||||
expect(objectResolved.target).toMatchObject({
|
||||
kind: "brush",
|
||||
brushId: brush.id,
|
||||
initialCenter: brush.center,
|
||||
initialRotationDegrees: brush.rotationDegrees,
|
||||
initialSize: brush.size
|
||||
});
|
||||
expect(objectResolved.target).not.toBeNull();
|
||||
expect(supportsTransformOperation(objectResolved.target as NonNullable<typeof objectResolved.target>, "translate")).toBe(true);
|
||||
expect(supportsTransformOperation(objectResolved.target as NonNullable<typeof objectResolved.target>, "rotate")).toBe(true);
|
||||
expect(supportsTransformOperation(objectResolved.target as NonNullable<typeof objectResolved.target>, "scale")).toBe(true);
|
||||
});
|
||||
|
||||
it("commits whitebox box rotate and scale transforms with undo and redo", () => {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-transform-main",
|
||||
center: {
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.75
|
||||
},
|
||||
size: {
|
||||
x: 2.5,
|
||||
y: 2,
|
||||
z: 4
|
||||
}
|
||||
});
|
||||
const store = createEditorStore({
|
||||
initialDocument: {
|
||||
...createEmptySceneDocument({ name: "Brush Transform Fixture" }),
|
||||
brushes: {
|
||||
[brush.id]: brush
|
||||
}
|
||||
}
|
||||
});
|
||||
const target = resolveTransformTarget(store.getState().document, {
|
||||
kind: "brushes",
|
||||
ids: [brush.id]
|
||||
}).target;
|
||||
|
||||
if (target === null || target.kind !== "brush") {
|
||||
throw new Error("Expected a whitebox box transform target.");
|
||||
}
|
||||
|
||||
const rotateSession = createTransformSession({
|
||||
source: "keyboard",
|
||||
sourcePanelId: "topLeft",
|
||||
operation: "rotate",
|
||||
target
|
||||
});
|
||||
|
||||
rotateSession.preview = {
|
||||
kind: "brush",
|
||||
center: {
|
||||
...brush.center
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
},
|
||||
size: {
|
||||
...brush.size
|
||||
}
|
||||
};
|
||||
|
||||
store.executeCommand(createCommitTransformSessionCommand(store.getState().document, rotateSession));
|
||||
|
||||
expect(store.getState().document.brushes[brush.id].rotationDegrees).toEqual({
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
});
|
||||
|
||||
const scaleTarget = resolveTransformTarget(store.getState().document, {
|
||||
kind: "brushes",
|
||||
ids: [brush.id]
|
||||
}).target;
|
||||
|
||||
if (scaleTarget === null || scaleTarget.kind !== "brush") {
|
||||
throw new Error("Expected a whitebox box transform target after rotation.");
|
||||
}
|
||||
|
||||
const scaleSession = createTransformSession({
|
||||
source: "keyboard",
|
||||
sourcePanelId: "topLeft",
|
||||
operation: "scale",
|
||||
target: scaleTarget
|
||||
});
|
||||
|
||||
scaleSession.preview = {
|
||||
kind: "brush",
|
||||
center: {
|
||||
...brush.center
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
},
|
||||
size: {
|
||||
x: 3.25,
|
||||
y: 1.75,
|
||||
z: 5.5
|
||||
}
|
||||
};
|
||||
|
||||
store.executeCommand(createCommitTransformSessionCommand(store.getState().document, scaleSession));
|
||||
|
||||
expect(store.getState().document.brushes[brush.id]).toMatchObject({
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
},
|
||||
size: {
|
||||
x: 3.25,
|
||||
y: 1.75,
|
||||
z: 5.5
|
||||
}
|
||||
});
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().document.brushes[brush.id]).toMatchObject({
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
},
|
||||
size: {
|
||||
x: 2.5,
|
||||
y: 2,
|
||||
z: 4
|
||||
}
|
||||
});
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().document.brushes[brush.id]).toEqual(brush);
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
expect(store.redo()).toBe(true);
|
||||
expect(store.getState().document.brushes[brush.id]).toMatchObject({
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
},
|
||||
size: {
|
||||
x: 3.25,
|
||||
y: 1.75,
|
||||
z: 5.5
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("commits a model instance translate/rotate/scale transform with undo and redo", () => {
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-main",
|
||||
assetId: modelAsset.id,
|
||||
position: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
scale: {
|
||||
x: 1,
|
||||
y: 1,
|
||||
z: 1
|
||||
}
|
||||
});
|
||||
const store = createEditorStore({
|
||||
initialDocument: {
|
||||
...createEmptySceneDocument({ name: "Transform Fixture" }),
|
||||
assets: {
|
||||
[modelAsset.id]: modelAsset
|
||||
},
|
||||
modelInstances: {
|
||||
[modelInstance.id]: modelInstance
|
||||
}
|
||||
}
|
||||
});
|
||||
const target = resolveTransformTarget(store.getState().document, {
|
||||
kind: "modelInstances",
|
||||
ids: [modelInstance.id]
|
||||
}).target;
|
||||
|
||||
if (target === null || target.kind !== "modelInstance") {
|
||||
throw new Error("Expected a model instance transform target.");
|
||||
}
|
||||
|
||||
const session = createTransformSession({
|
||||
source: "keyboard",
|
||||
sourcePanelId: "topLeft",
|
||||
operation: "scale",
|
||||
target
|
||||
});
|
||||
|
||||
session.preview = {
|
||||
kind: "modelInstance",
|
||||
position: {
|
||||
x: 4,
|
||||
y: 1,
|
||||
z: -2
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 90,
|
||||
z: 0
|
||||
},
|
||||
scale: {
|
||||
x: 1.5,
|
||||
y: 2,
|
||||
z: 1.5
|
||||
}
|
||||
};
|
||||
|
||||
store.executeCommand(createCommitTransformSessionCommand(store.getState().document, session));
|
||||
|
||||
expect(store.getState().document.modelInstances[modelInstance.id]).toMatchObject({
|
||||
position: {
|
||||
x: 4,
|
||||
y: 1,
|
||||
z: -2
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 90,
|
||||
z: 0
|
||||
},
|
||||
scale: {
|
||||
x: 1.5,
|
||||
y: 2,
|
||||
z: 1.5
|
||||
}
|
||||
});
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().document.modelInstances[modelInstance.id]).toEqual(modelInstance);
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
expect(store.getState().document.modelInstances[modelInstance.id]).toMatchObject({
|
||||
position: {
|
||||
x: 4,
|
||||
y: 1,
|
||||
z: -2
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 90,
|
||||
z: 0
|
||||
},
|
||||
scale: {
|
||||
x: 1.5,
|
||||
y: 2,
|
||||
z: 1.5
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("commits a rotatable entity transform with undo and redo", () => {
|
||||
const playerStart = createPlayerStartEntity({
|
||||
id: "entity-player-start-main",
|
||||
position: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
yawDegrees: 0
|
||||
});
|
||||
const store = createEditorStore({
|
||||
initialDocument: {
|
||||
...createEmptySceneDocument({ name: "Entity Transform Fixture" }),
|
||||
entities: {
|
||||
[playerStart.id]: playerStart
|
||||
}
|
||||
}
|
||||
});
|
||||
const target = resolveTransformTarget(store.getState().document, {
|
||||
kind: "entities",
|
||||
ids: [playerStart.id]
|
||||
}).target;
|
||||
|
||||
if (target === null || target.kind !== "entity") {
|
||||
throw new Error("Expected an entity transform target.");
|
||||
}
|
||||
|
||||
const session = createTransformSession({
|
||||
source: "keyboard",
|
||||
sourcePanelId: "topLeft",
|
||||
operation: "rotate",
|
||||
target
|
||||
});
|
||||
|
||||
session.preview = {
|
||||
kind: "entity",
|
||||
position: {
|
||||
x: 6,
|
||||
y: 0,
|
||||
z: -4
|
||||
},
|
||||
rotation: {
|
||||
kind: "yaw",
|
||||
yawDegrees: 90
|
||||
}
|
||||
};
|
||||
|
||||
store.executeCommand(createCommitTransformSessionCommand(store.getState().document, session));
|
||||
|
||||
expect(store.getState().document.entities[playerStart.id]).toMatchObject({
|
||||
position: {
|
||||
x: 6,
|
||||
y: 0,
|
||||
z: -4
|
||||
},
|
||||
yawDegrees: 90
|
||||
});
|
||||
|
||||
expect(store.undo()).toBe(true);
|
||||
expect(store.getState().document.entities[playerStart.id]).toEqual(playerStart);
|
||||
|
||||
expect(store.redo()).toBe(true);
|
||||
expect(store.getState().document.entities[playerStart.id]).toMatchObject({
|
||||
position: {
|
||||
x: 6,
|
||||
y: 0,
|
||||
z: -4
|
||||
},
|
||||
yawDegrees: 90
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -18,14 +18,12 @@ test("app boots and shows the viewport shell", async ({ page }) => {
|
||||
|
||||
await expect(page.getByTestId("toolbar-scene-name")).toHaveValue("Untitled Scene");
|
||||
await expect(page.getByTestId("viewport-shell")).toBeVisible();
|
||||
await expect(page.getByTestId("viewport-panel-topLeft")).toBeVisible();
|
||||
await expect(page.getByTestId("viewport-layout-single")).toBeVisible();
|
||||
await expect(page.getByTestId("viewport-layout-quad")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "World" })).toBeVisible();
|
||||
await expect(page.getByTestId("world-background-mode-value")).toBeVisible();
|
||||
await expect(page.getByTestId("enter-run-mode")).toBeVisible();
|
||||
await expect(page.getByTestId("material-button-starter-amber-grid")).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Materials" }).click();
|
||||
await expect(page.getByTestId("material-button-starter-amber-grid")).toHaveCount(0);
|
||||
|
||||
await page.getByRole("button", { name: "Materials" }).click();
|
||||
await expect(page.getByTestId("material-button-starter-amber-grid")).toBeVisible();
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("user can create a box brush and keep it through a draft reload", async ({ page }) => {
|
||||
import { beginBoxCreation, clickViewport, getEditorStoreSnapshot } from "./viewport-test-helpers";
|
||||
|
||||
test("user can create a whitebox box with float transforms and keep it through reload and run mode", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
|
||||
@@ -20,33 +22,72 @@ test("user can create a box brush and keep it through a draft reload", async ({
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByRole("button", { name: "Box Create" }).click();
|
||||
const viewportCanvas = page.locator('[data-testid="viewport-shell"] canvas');
|
||||
if ((await viewportCanvas.count()) > 0) {
|
||||
await viewportCanvas.click();
|
||||
} else {
|
||||
await page.getByTestId("viewport-fallback-create-box").click();
|
||||
}
|
||||
await expect(page.getByRole("button", { name: /Box Brush 1/ })).toBeVisible();
|
||||
await expect(page.getByText("1 brush selected (Box Brush 1)")).toBeVisible();
|
||||
await beginBoxCreation(page);
|
||||
const creationSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(creationSnapshot).toMatchObject({
|
||||
toolMode: "create",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "box-brush"
|
||||
},
|
||||
center: null
|
||||
}
|
||||
}
|
||||
});
|
||||
await page.keyboard.press("Escape");
|
||||
const cancelledSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(cancelledSnapshot).toMatchObject({
|
||||
toolMode: "select",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "none"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await beginBoxCreation(page);
|
||||
await clickViewport(page);
|
||||
await page.getByTestId("whitebox-snap-toggle").click();
|
||||
const committedSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(committedSnapshot).toMatchObject({
|
||||
toolMode: "select",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "none"
|
||||
}
|
||||
}
|
||||
});
|
||||
await expect(page.getByRole("button", { name: /Whitebox Box 1/ })).toBeVisible();
|
||||
await expect(page.getByText("1 solid selected (Whitebox Box 1)")).toBeVisible();
|
||||
await expect(page.getByTestId("apply-brush-position")).toHaveCount(0);
|
||||
await expect(page.getByTestId("apply-brush-size")).toHaveCount(0);
|
||||
await page.getByTestId("brush-center-y").fill("2");
|
||||
await page.getByTestId("brush-center-x").fill("1.25");
|
||||
await page.getByTestId("brush-center-x").press("Tab");
|
||||
await page.getByTestId("brush-center-y").fill("2.125");
|
||||
await page.getByTestId("brush-center-y").press("Tab");
|
||||
await page.getByTestId("brush-size-z").fill("4");
|
||||
await page.getByTestId("brush-rotation-y").fill("37.5");
|
||||
await page.getByTestId("brush-rotation-y").press("Tab");
|
||||
await page.getByTestId("brush-size-z").fill("4.5");
|
||||
await page.getByTestId("brush-size-z").press("Tab");
|
||||
await page.getByTestId("selected-brush-name").fill("Entry Room");
|
||||
await page.getByTestId("selected-brush-name").press("Tab");
|
||||
await expect(page.getByRole("button", { name: /Entry Room/ })).toBeVisible();
|
||||
await expect(page.getByTestId("selected-brush-name")).toHaveValue("Entry Room");
|
||||
|
||||
await page.getByRole("button", { name: "Save Draft" }).click();
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByRole("button", { name: /Entry Room/ })).toBeVisible();
|
||||
await page.getByRole("button", { name: /Entry Room/ }).click();
|
||||
await expect(page.getByTestId("brush-center-y")).toHaveValue("2");
|
||||
await expect(page.getByTestId("brush-size-z")).toHaveValue("4");
|
||||
await expect(page.getByTestId("viewport-overlay")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: /^Entry Room$/ })).toBeVisible();
|
||||
await page.getByRole("button", { name: /^Entry Room$/ }).click();
|
||||
await expect(page.getByTestId("brush-center-x")).toHaveValue("1.25");
|
||||
await expect(page.getByTestId("brush-center-y")).toHaveValue("2.125");
|
||||
await expect(page.getByTestId("brush-rotation-y")).toHaveValue("37.5");
|
||||
await expect(page.getByTestId("brush-size-z")).toHaveValue("4.5");
|
||||
await expect(page.getByTestId("viewport-overlay-topLeft")).toHaveCount(0);
|
||||
await page.getByTestId("enter-run-mode").click();
|
||||
await expect(page.getByTestId("runner-shell")).toBeVisible();
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
@@ -59,19 +100,10 @@ test("switching selection while a transform input is active does not overwrite t
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
const viewportCanvas = page.locator('[data-testid="viewport-shell"] canvas');
|
||||
await page.getByRole("button", { name: "Box Create" }).click();
|
||||
if ((await viewportCanvas.count()) > 0) {
|
||||
await viewportCanvas.click();
|
||||
} else {
|
||||
await page.getByTestId("viewport-fallback-create-box").click();
|
||||
}
|
||||
await page.getByRole("button", { name: "Box Create" }).click();
|
||||
if ((await viewportCanvas.count()) > 0) {
|
||||
await viewportCanvas.click();
|
||||
} else {
|
||||
await page.getByTestId("viewport-fallback-create-box").click();
|
||||
}
|
||||
await beginBoxCreation(page);
|
||||
await clickViewport(page);
|
||||
await beginBoxCreation(page);
|
||||
await clickViewport(page);
|
||||
|
||||
const outlinerButtons = page.getByTestId("outliner-brush-list").getByRole("button");
|
||||
|
||||
@@ -79,7 +111,7 @@ test("switching selection while a transform input is active does not overwrite t
|
||||
await page.getByTestId("brush-size-z").fill("4");
|
||||
await outlinerButtons.nth(1).click();
|
||||
|
||||
await expect(page.getByText("1 brush selected (Box Brush 2)")).toBeVisible();
|
||||
await expect(page.getByText("1 solid selected (Whitebox Box 2)")).toBeVisible();
|
||||
await expect(page.getByTestId("brush-size-z")).toHaveValue("2");
|
||||
|
||||
await outlinerButtons.nth(0).click();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { clickViewport, getEditorStoreSnapshot, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
test("user can place and select typed entities from the entity foundation workflow", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
@@ -20,7 +22,42 @@ test("user can place and select typed entities from the entity foundation workfl
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByTestId("add-entity-soundEmitter").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-sound-emitter").click();
|
||||
await setViewportCreationPreview(
|
||||
page,
|
||||
"topLeft",
|
||||
{ kind: "entity", entityKind: "soundEmitter", audioAssetId: null },
|
||||
{ x: 4, y: 1, z: -6 }
|
||||
);
|
||||
await expect(page.getByTestId("viewport-snap-preview-topLeft")).toBeVisible();
|
||||
await clickViewport(page, "topLeft");
|
||||
const soundEmitterSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(soundEmitterSnapshot).toMatchObject({
|
||||
toolMode: "select",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "none"
|
||||
}
|
||||
}
|
||||
});
|
||||
const selectedSoundEmitterId =
|
||||
soundEmitterSnapshot.selection.kind === "entities" ? soundEmitterSnapshot.selection.ids?.[0] ?? null : null;
|
||||
|
||||
expect(selectedSoundEmitterId).not.toBeNull();
|
||||
|
||||
const selectedSoundEmitter = soundEmitterSnapshot.document.entities[selectedSoundEmitterId as string];
|
||||
|
||||
if (selectedSoundEmitter === undefined) {
|
||||
throw new Error("Placed sound emitter is missing from the document snapshot.");
|
||||
}
|
||||
|
||||
expect(selectedSoundEmitter.position).toMatchObject({
|
||||
x: 4,
|
||||
y: 1,
|
||||
z: -6
|
||||
});
|
||||
await expect(page.getByTestId("sound-emitter-ref-distance")).toHaveValue("6");
|
||||
await expect(page.getByTestId("sound-emitter-max-distance")).toHaveValue("24");
|
||||
|
||||
@@ -32,7 +69,26 @@ test("user can place and select typed entities from the entity foundation workfl
|
||||
await expect(page.getByTestId("sound-emitter-autoplay")).toBeChecked();
|
||||
await expect(page.getByTestId("sound-emitter-loop")).toBeChecked();
|
||||
|
||||
await page.getByTestId("add-entity-interactable").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-interactable").click();
|
||||
await setViewportCreationPreview(
|
||||
page,
|
||||
"topLeft",
|
||||
{ kind: "entity", entityKind: "interactable", audioAssetId: null },
|
||||
{ x: -8, y: 1, z: 12 }
|
||||
);
|
||||
await expect(page.getByTestId("viewport-snap-preview-topLeft")).toBeVisible();
|
||||
await clickViewport(page, "topLeft");
|
||||
const interactableSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(interactableSnapshot).toMatchObject({
|
||||
toolMode: "select",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "none"
|
||||
}
|
||||
}
|
||||
});
|
||||
await expect(page.getByTestId("interactable-prompt")).toHaveValue("Use");
|
||||
|
||||
await page
|
||||
@@ -49,3 +105,99 @@ test("user can place and select typed entities from the entity foundation workfl
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
});
|
||||
|
||||
test("shift+a opens the add menu at the cursor", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
|
||||
page.on("pageerror", (error) => {
|
||||
pageErrors.push(error.message);
|
||||
});
|
||||
|
||||
page.on("console", (message) => {
|
||||
if (message.type() === "error") {
|
||||
consoleErrors.push(message.text());
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto("/");
|
||||
await page.evaluate((storageKey) => {
|
||||
window.localStorage.removeItem(storageKey);
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.mouse.move(420, 260);
|
||||
await page.keyboard.press("Shift+A");
|
||||
|
||||
await expect(page.getByRole("menu", { name: "Add" })).toBeVisible();
|
||||
await page.getByTestId("add-menu-lights").click();
|
||||
await page.getByTestId("add-menu-point-light").click();
|
||||
await setViewportCreationPreview(
|
||||
page,
|
||||
"topLeft",
|
||||
{ kind: "entity", entityKind: "pointLight", audioAssetId: null },
|
||||
{ x: 12, y: 3, z: -4 }
|
||||
);
|
||||
await clickViewport(page, "topLeft");
|
||||
await expect(page.getByTestId("point-light-intensity")).toHaveValue("1.25");
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
});
|
||||
|
||||
test("escape cancels a typed entity creation preview", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
|
||||
page.on("pageerror", (error) => {
|
||||
pageErrors.push(error.message);
|
||||
});
|
||||
|
||||
page.on("console", (message) => {
|
||||
if (message.type() === "error") {
|
||||
consoleErrors.push(message.text());
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto("/");
|
||||
await page.evaluate((storageKey) => {
|
||||
window.localStorage.removeItem(storageKey);
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-player-start").click();
|
||||
|
||||
const creationSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(creationSnapshot).toMatchObject({
|
||||
toolMode: "create",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "entity",
|
||||
entityKind: "playerStart",
|
||||
audioAssetId: null
|
||||
},
|
||||
center: null
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
const cancelledSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(cancelledSnapshot).toMatchObject({
|
||||
toolMode: "select",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "none"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { beginBoxCreation, clickViewport } from "./viewport-test-helpers";
|
||||
|
||||
test("user can assign a face material through the UI and keep it through a draft reload", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
@@ -20,13 +22,8 @@ test("user can assign a face material through the UI and keep it through a draft
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByRole("button", { name: "Box Create" }).click();
|
||||
const viewportCanvas = page.locator('[data-testid="viewport-shell"] canvas');
|
||||
if ((await viewportCanvas.count()) > 0) {
|
||||
await viewportCanvas.click();
|
||||
} else {
|
||||
await page.getByTestId("viewport-fallback-create-box").click();
|
||||
}
|
||||
await beginBoxCreation(page);
|
||||
await clickViewport(page);
|
||||
await page.getByTestId("face-button-posZ").click();
|
||||
await page.getByTestId("material-button-starter-amber-grid").click();
|
||||
|
||||
@@ -35,7 +32,7 @@ test("user can assign a face material through the UI and keep it through a draft
|
||||
await page.getByRole("button", { name: "Save Draft" }).click();
|
||||
await page.reload();
|
||||
|
||||
await page.getByRole("button", { name: /Box Brush 1/ }).click();
|
||||
await page.getByRole("button", { name: /Whitebox Box 1/ }).click();
|
||||
await page.getByTestId("face-button-posZ").click();
|
||||
await expect(page.getByTestId("selected-face-material-name")).toContainText("Amber Grid");
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { beginBoxCreation, clickViewport, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
test("first-room workflow covers create, texture, save/load, and run", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
@@ -20,13 +22,8 @@ test("first-room workflow covers create, texture, save/load, and run", async ({
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByRole("button", { name: "Box Create" }).click();
|
||||
const viewportCanvas = page.locator('[data-testid="viewport-shell"] canvas');
|
||||
if ((await viewportCanvas.count()) > 0) {
|
||||
await viewportCanvas.click();
|
||||
} else {
|
||||
await page.getByTestId("viewport-fallback-create-box").click();
|
||||
}
|
||||
await beginBoxCreation(page);
|
||||
await clickViewport(page);
|
||||
await page.getByTestId("face-button-posZ").click();
|
||||
await page.getByTestId("material-button-starter-amber-grid").click();
|
||||
|
||||
@@ -34,7 +31,11 @@ test("first-room workflow covers create, texture, save/load, and run", async ({
|
||||
await expect(page.getByTestId("status-message")).toContainText("Author a Player Start before running");
|
||||
await expect(page.getByTestId("status-run-preflight")).toContainText("Blocked");
|
||||
|
||||
await page.getByTestId("place-player-start").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-player-start").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "playerStart", audioAssetId: null }, { x: 0, y: 0, z: 0 });
|
||||
await clickViewport(page, "topLeft");
|
||||
await page.getByTestId("player-start-position-x").fill("2");
|
||||
await page.getByTestId("player-start-position-x").press("Tab");
|
||||
await page.getByTestId("player-start-position-z").fill("-2");
|
||||
@@ -45,18 +46,14 @@ test("first-room workflow covers create, texture, save/load, and run", async ({
|
||||
await expect(page.getByTestId("status-run-preflight")).toContainText("Ready for First Person");
|
||||
|
||||
await page.getByRole("button", { name: "Save Draft" }).click();
|
||||
await page.getByRole("button", { name: "Box Create" }).click();
|
||||
if ((await viewportCanvas.count()) > 0) {
|
||||
await viewportCanvas.click();
|
||||
} else {
|
||||
await page.getByTestId("viewport-fallback-create-box").click();
|
||||
}
|
||||
await expect(page.getByRole("button", { name: /Box Brush 2/ })).toBeVisible();
|
||||
await beginBoxCreation(page);
|
||||
await clickViewport(page);
|
||||
await expect(page.getByRole("button", { name: /Whitebox Box 2/ })).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Load Draft" }).click();
|
||||
await expect(page.getByRole("button", { name: /Box Brush 2/ })).toHaveCount(0);
|
||||
await expect(page.getByRole("button", { name: /Whitebox Box 2/ })).toHaveCount(0);
|
||||
|
||||
await page.getByRole("button", { name: /Box Brush 1/ }).click();
|
||||
await page.getByRole("button", { name: /Whitebox Box 1/ }).click();
|
||||
await page.getByTestId("face-button-posZ").click();
|
||||
await expect(page.getByTestId("selected-face-material-name")).toContainText("Amber Grid");
|
||||
|
||||
@@ -64,7 +61,8 @@ test("first-room workflow covers create, texture, save/load, and run", async ({
|
||||
|
||||
await expect(page.getByTestId("runner-shell")).toBeVisible();
|
||||
await expect(page.getByTestId("runner-spawn-state")).toContainText("Player Start");
|
||||
await expect(page.getByTestId("runner-player-position")).toContainText("2.00, 0.00, -2.00");
|
||||
await expect(page.getByTestId("runner-player-position")).toContainText("2.00,");
|
||||
await expect(page.getByTestId("runner-player-position")).toContainText(", -2.00");
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
|
||||
@@ -2,6 +2,8 @@ import path from "node:path";
|
||||
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { clickViewport, getEditorStoreSnapshot, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
const fixturePath = path.resolve(process.cwd(), "fixtures/assets/tiny-triangle-draco.glb");
|
||||
|
||||
test("imports a draco-compressed glb asset, places an instance, and survives reload", async ({ page }) => {
|
||||
@@ -20,22 +22,63 @@ test("imports a draco-compressed glb asset, places an instance, and survives rel
|
||||
|
||||
await page.goto("/");
|
||||
|
||||
await expect(page.getByRole("button", { name: "Import Model" })).toBeEnabled();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-import").click();
|
||||
await page.getByTestId("import-menu-model").click();
|
||||
|
||||
await page.locator('input[type="file"][accept*="gltf"]').setInputFiles(fixturePath);
|
||||
|
||||
await expect(page.getByTestId("asset-list").getByText("tiny-triangle-draco.glb", { exact: true })).toBeVisible();
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(1);
|
||||
|
||||
await page.getByRole("button", { name: "Place Instance" }).click();
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(2);
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-assets").click();
|
||||
await page.getByTestId("add-menu-assets-models").click();
|
||||
const addMenu = page.getByRole("menu", { name: "Add" });
|
||||
await expect(addMenu.getByRole("menuitem", { name: "tiny-triangle-draco.glb" })).toBeVisible();
|
||||
await addMenu.getByRole("menuitem", { name: "tiny-triangle-draco.glb" }).click();
|
||||
const importedSnapshot = await getEditorStoreSnapshot(page);
|
||||
const importedModelAsset = Object.values(importedSnapshot.document.assets).find(
|
||||
(asset) => asset.kind === "model" && asset.sourceName === "tiny-triangle-draco.glb"
|
||||
);
|
||||
|
||||
await page.getByRole("button", { name: "Save Draft" }).click();
|
||||
if (importedModelAsset === undefined) {
|
||||
throw new Error("Imported model asset was not found in the document snapshot.");
|
||||
}
|
||||
|
||||
await setViewportCreationPreview(
|
||||
page,
|
||||
"topLeft",
|
||||
{ kind: "model-instance", assetId: importedModelAsset.id },
|
||||
{ x: 84, y: 0, z: -88 }
|
||||
);
|
||||
await expect(page.getByTestId("viewport-snap-preview-topLeft")).toBeVisible();
|
||||
await clickViewport(page, "topLeft");
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(2);
|
||||
const snapshot = await getEditorStoreSnapshot(page);
|
||||
const selectedModelInstanceId = snapshot.selection.kind === "modelInstances" ? snapshot.selection.ids?.[0] ?? null : null;
|
||||
|
||||
expect(selectedModelInstanceId).not.toBeNull();
|
||||
|
||||
const selectedModelInstance = snapshot.document.modelInstances[selectedModelInstanceId as string];
|
||||
|
||||
if (selectedModelInstance === undefined) {
|
||||
throw new Error("Placed model instance is missing from the document snapshot.");
|
||||
}
|
||||
|
||||
expect(selectedModelInstance.position).toMatchObject({
|
||||
x: 84,
|
||||
z: -88
|
||||
});
|
||||
|
||||
await page.getByRole("button", { name: "Save Draft" }).dispatchEvent("click");
|
||||
await expect(page.getByTestId("status-message")).toContainText("Local draft saved.");
|
||||
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByTestId("asset-list").getByText("tiny-triangle-draco.glb", { exact: true })).toBeVisible();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-assets").click();
|
||||
await page.getByTestId("add-menu-assets-models").click();
|
||||
await expect(page.getByRole("menu", { name: "Add" }).getByRole("menuitem", { name: "tiny-triangle-draco.glb" })).toBeVisible();
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(2);
|
||||
await expect(page.getByTestId("asset-status-message")).toHaveCount(0);
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@ import path from "node:path";
|
||||
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { clickViewport, getEditorStoreSnapshot, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
const gltfFixturePath = path.resolve(process.cwd(), "fixtures/assets/external-triangle/scene.gltf");
|
||||
const binFixturePath = path.resolve(process.cwd(), "fixtures/assets/external-triangle/triangle.bin");
|
||||
|
||||
test("imports a gltf asset with external resources and survives reload", async ({ page }) => {
|
||||
test("imports a gltf asset with external resources and places an instance", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
|
||||
@@ -21,24 +23,50 @@ test("imports a gltf asset with external resources and survives reload", async (
|
||||
|
||||
await page.goto("/");
|
||||
|
||||
await expect(page.getByRole("button", { name: "Import Model" })).toBeEnabled();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-import").click();
|
||||
await page.getByTestId("import-menu-model").click();
|
||||
|
||||
await page.locator('input[type="file"][accept*="gltf"]').setInputFiles([gltfFixturePath, binFixturePath]);
|
||||
|
||||
await expect(page.getByTestId("asset-list").getByText("scene.gltf", { exact: true })).toBeVisible();
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(1);
|
||||
|
||||
await page.getByRole("button", { name: "Place Instance" }).click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-assets").click();
|
||||
await page.getByTestId("add-menu-assets-models").click();
|
||||
const addMenu = page.getByRole("menu", { name: "Add" });
|
||||
await expect(addMenu.getByRole("menuitem", { name: "scene.gltf" })).toBeVisible();
|
||||
await addMenu.getByRole("menuitem", { name: "scene.gltf" }).hover();
|
||||
await expect(page.getByTestId("status-asset-hover")).toContainText("Storage key:");
|
||||
await addMenu.getByRole("menuitem", { name: "scene.gltf" }).click();
|
||||
const importedSnapshot = await getEditorStoreSnapshot(page);
|
||||
const importedModelAsset = Object.values(importedSnapshot.document.assets).find(
|
||||
(asset) => asset.kind === "model" && asset.sourceName === "scene.gltf"
|
||||
);
|
||||
|
||||
if (importedModelAsset === undefined) {
|
||||
throw new Error("Imported model asset was not found in the document snapshot.");
|
||||
}
|
||||
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "model-instance", assetId: importedModelAsset.id }, { x: 88, y: 0, z: -84 });
|
||||
await expect(page.getByTestId("viewport-snap-preview-topLeft")).toBeVisible();
|
||||
await clickViewport(page, "topLeft");
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(2);
|
||||
const snapshot = await getEditorStoreSnapshot(page);
|
||||
const selectedModelInstanceId = snapshot.selection.kind === "modelInstances" ? snapshot.selection.ids?.[0] ?? null : null;
|
||||
|
||||
await page.getByRole("button", { name: "Save Draft" }).click();
|
||||
await expect(page.getByTestId("status-message")).toContainText("Local draft saved.");
|
||||
expect(selectedModelInstanceId).not.toBeNull();
|
||||
|
||||
await page.reload();
|
||||
const selectedModelInstance = snapshot.document.modelInstances[selectedModelInstanceId as string];
|
||||
|
||||
await expect(page.getByTestId("asset-list").getByText("scene.gltf", { exact: true })).toBeVisible();
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(2);
|
||||
await expect(page.getByTestId("asset-status-message")).toHaveCount(0);
|
||||
if (selectedModelInstance === undefined) {
|
||||
throw new Error("Placed model instance is missing from the document snapshot.");
|
||||
}
|
||||
|
||||
expect(selectedModelInstance.position).toMatchObject({
|
||||
x: 88,
|
||||
z: -84
|
||||
});
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
|
||||
@@ -2,6 +2,8 @@ import path from "node:path";
|
||||
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { clickViewport, getEditorStoreSnapshot, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
const fixturePath = path.resolve(process.cwd(), "fixtures/assets/tiny-triangle.gltf");
|
||||
|
||||
test("imports a model asset, places an instance, and survives reload", async ({ page }) => {
|
||||
@@ -20,22 +22,101 @@ test("imports a model asset, places an instance, and survives reload", async ({
|
||||
|
||||
await page.goto("/");
|
||||
|
||||
await expect(page.getByRole("button", { name: "Import Model" })).toBeEnabled();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-import").click();
|
||||
await expect(page.getByTestId("import-menu-model")).toBeVisible();
|
||||
await expect(page.getByTestId("import-menu-environment")).toBeVisible();
|
||||
await expect(page.getByTestId("import-menu-audio")).toBeVisible();
|
||||
await page.getByTestId("import-menu-model").click();
|
||||
|
||||
await page.locator('input[type="file"][accept*="gltf"]').setInputFiles(fixturePath);
|
||||
|
||||
await expect(page.getByTestId("asset-list").getByText("tiny-triangle.gltf", { exact: true })).toBeVisible();
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(1);
|
||||
|
||||
await page.getByRole("button", { name: "Place Instance" }).click();
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(2);
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-assets").click();
|
||||
await page.getByTestId("add-menu-assets-models").click();
|
||||
const addMenu = page.getByRole("menu", { name: "Add" });
|
||||
await expect(addMenu.getByRole("menuitem", { name: "tiny-triangle.gltf" })).toBeVisible();
|
||||
await addMenu.getByRole("menuitem", { name: "tiny-triangle.gltf" }).hover();
|
||||
await expect(page.getByTestId("status-asset-hover")).toContainText("Storage key:");
|
||||
await addMenu.getByRole("menuitem", { name: "tiny-triangle.gltf" }).click();
|
||||
const importedSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(importedSnapshot).toMatchObject({
|
||||
toolMode: "create",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "model-instance",
|
||||
assetId: expect.any(String)
|
||||
},
|
||||
center: null
|
||||
}
|
||||
}
|
||||
});
|
||||
const importedModelAsset = Object.values(importedSnapshot.document.assets).find(
|
||||
(asset) => asset.kind === "model" && asset.sourceName === "tiny-triangle.gltf"
|
||||
);
|
||||
|
||||
await page.getByRole("button", { name: "Save Draft" }).click();
|
||||
if (importedModelAsset === undefined) {
|
||||
throw new Error("Imported model asset was not found in the document snapshot.");
|
||||
}
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
const cancelledSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(cancelledSnapshot).toMatchObject({
|
||||
toolMode: "select",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "none"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-assets").click();
|
||||
await page.getByTestId("add-menu-assets-models").click();
|
||||
await page.getByRole("menu", { name: "Add" }).getByRole("menuitem", { name: "tiny-triangle.gltf" }).click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "model-instance", assetId: importedModelAsset.id }, { x: 92, y: 0, z: -76 });
|
||||
await expect(page.getByTestId("viewport-snap-preview-topLeft")).toBeVisible();
|
||||
await clickViewport(page, "topLeft");
|
||||
const committedSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(committedSnapshot).toMatchObject({
|
||||
toolMode: "select",
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "none"
|
||||
}
|
||||
}
|
||||
});
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(2);
|
||||
const snapshot = committedSnapshot;
|
||||
const selectedModelInstanceId = snapshot.selection.kind === "modelInstances" ? snapshot.selection.ids?.[0] ?? null : null;
|
||||
|
||||
expect(selectedModelInstanceId).not.toBeNull();
|
||||
|
||||
const selectedModelInstance = snapshot.document.modelInstances[selectedModelInstanceId as string];
|
||||
|
||||
if (selectedModelInstance === undefined) {
|
||||
throw new Error("Placed model instance is missing from the document snapshot.");
|
||||
}
|
||||
|
||||
expect(selectedModelInstance.position).toMatchObject({
|
||||
x: 92,
|
||||
z: -76
|
||||
});
|
||||
|
||||
await page.getByRole("button", { name: "Save Draft" }).dispatchEvent("click");
|
||||
await expect(page.getByTestId("status-message")).toContainText("Local draft saved.");
|
||||
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByTestId("asset-list").getByText("tiny-triangle.gltf", { exact: true })).toBeVisible();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-assets").click();
|
||||
await page.getByTestId("add-menu-assets-models").click();
|
||||
await expect(page.getByRole("menu", { name: "Add" }).getByRole("menuitem", { name: "tiny-triangle.gltf" })).toBeVisible();
|
||||
await expect(page.getByTestId("outliner-model-instance-list").getByRole("button")).toHaveCount(2);
|
||||
await expect(page.getByTestId("asset-status-message")).toHaveCount(0);
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import path from "node:path";
|
||||
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { clickViewport, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
const panoramaFixturePath = path.resolve(process.cwd(), "fixtures/assets/skybox-panorama.svg");
|
||||
|
||||
test("local lights and background images persist through editor and runner flows", async ({ page }) => {
|
||||
@@ -24,19 +26,37 @@ test("local lights and background images persist through editor and runner flows
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-import").click();
|
||||
await page.getByTestId("import-menu-environment").click();
|
||||
await page.locator('input[type="file"][accept*="image"]').setInputFiles(panoramaFixturePath);
|
||||
|
||||
await expect(page.getByTestId("asset-list")).toContainText("skybox-panorama.svg");
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-assets").click();
|
||||
await page.getByTestId("add-menu-assets-environments").click();
|
||||
const addMenu = page.getByRole("menu", { name: "Add" });
|
||||
await expect(addMenu.getByRole("menuitem", { name: "skybox-panorama.svg" })).toBeVisible();
|
||||
await addMenu.getByRole("menuitem", { name: "skybox-panorama.svg" }).click();
|
||||
await expect(page.getByTestId("world-background-mode-value")).toContainText("Image");
|
||||
await expect(page.getByTestId("world-background-asset-value")).toContainText("skybox-panorama.svg");
|
||||
await expect(page.getByTestId("viewport-shell")).toHaveCSS("background-image", /url/);
|
||||
await expect(page.getByTestId("viewport-canvas-topLeft")).toHaveCSS("background-image", /url/);
|
||||
|
||||
await page.getByTestId("add-entity-pointLight").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-lights").click();
|
||||
await page.getByTestId("add-menu-point-light").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "pointLight", audioAssetId: null }, { x: 12, y: 3, z: -4 });
|
||||
await expect(page.getByTestId("viewport-snap-preview-topLeft")).toBeVisible();
|
||||
await clickViewport(page, "topLeft");
|
||||
await expect(page.getByTestId("point-light-distance")).toHaveValue("8");
|
||||
await page.getByTestId("point-light-distance").fill("12");
|
||||
await page.getByTestId("point-light-distance").press("Tab");
|
||||
|
||||
await page.getByTestId("add-entity-spotLight").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-lights").click();
|
||||
await page.getByTestId("add-menu-spot-light").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "spotLight", audioAssetId: null }, { x: -10, y: 4, z: 6 });
|
||||
await expect(page.getByTestId("viewport-snap-preview-topLeft")).toBeVisible();
|
||||
await clickViewport(page, "topLeft");
|
||||
await expect(page.getByTestId("spot-light-angle")).toHaveValue("35");
|
||||
await page.getByTestId("spot-light-angle").fill("48");
|
||||
await page.getByTestId("spot-light-angle").press("Tab");
|
||||
@@ -50,9 +70,14 @@ test("local lights and background images persist through editor and runner flows
|
||||
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByTestId("asset-list")).toContainText("skybox-panorama.svg");
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-assets").click();
|
||||
await page.getByTestId("add-menu-assets-environments").click();
|
||||
const reloadedAddMenu = page.getByRole("menu", { name: "Add" });
|
||||
await expect(reloadedAddMenu.getByRole("menuitem", { name: "skybox-panorama.svg" })).toBeVisible();
|
||||
await reloadedAddMenu.getByRole("menuitem", { name: "skybox-panorama.svg" }).click();
|
||||
await expect(page.locator('[data-testid^="outliner-entity-"]')).toHaveCount(2);
|
||||
await expect(page.getByTestId("viewport-shell")).toHaveCSS("background-image", /url/);
|
||||
await expect(page.getByTestId("viewport-canvas-topLeft")).toHaveCSS("background-image", /url/);
|
||||
|
||||
await page.getByTestId("enter-run-mode").click();
|
||||
|
||||
|
||||
60
tests/e2e/orthographic-views.e2e.ts
Normal file
60
tests/e2e/orthographic-views.e2e.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { beginBoxCreation, clickViewport, getViewportOverlay, getViewportPanel } from "./viewport-test-helpers";
|
||||
|
||||
test("orthographic panel controls keep brush authoring and selection behavior intact", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
|
||||
page.on("pageerror", (error) => {
|
||||
pageErrors.push(error.message);
|
||||
});
|
||||
|
||||
page.on("console", (message) => {
|
||||
if (message.type() === "error") {
|
||||
consoleErrors.push(message.text());
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto("/");
|
||||
await page.evaluate((storageKey) => {
|
||||
window.localStorage.removeItem(storageKey);
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await beginBoxCreation(page);
|
||||
await clickViewport(page, "topLeft");
|
||||
|
||||
await expect(page.getByRole("button", { name: /Whitebox Box 1/ })).toBeVisible();
|
||||
await expect(page.getByText("1 solid selected (Whitebox Box 1)")).toBeVisible();
|
||||
await expect(page.getByTestId("viewport-active-panel")).toHaveCount(0);
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-view-perspective")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(getViewportOverlay(page, "topLeft")).toBeVisible();
|
||||
await expect(page.getByTestId("viewport-selection-mode-topLeft")).toHaveText("Object");
|
||||
|
||||
await page.getByTestId("viewport-panel-topLeft-view-top").dispatchEvent("click");
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-view-top")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-selection-mode-topLeft")).toHaveText("Object");
|
||||
|
||||
await page.getByTestId("viewport-panel-topLeft-view-front").dispatchEvent("click");
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-view-front")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-selection-mode-topLeft")).toHaveText("Object");
|
||||
|
||||
await page.getByTestId("viewport-panel-topLeft-view-side").dispatchEvent("click");
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-view-side")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-selection-mode-topLeft")).toHaveText("Object");
|
||||
|
||||
await page.getByTestId("viewport-panel-topLeft-display-authoring").dispatchEvent("click");
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-display-authoring")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-canvas-topLeft")).toHaveCSS("background-color", "rgb(0, 0, 0)");
|
||||
await expect(getViewportPanel(page, "topLeft")).toHaveAttribute("data-active", "true");
|
||||
await expect(page.getByText("1 solid selected (Whitebox Box 1)")).toBeVisible();
|
||||
|
||||
await page.getByTestId("viewport-panel-topLeft-display-wireframe").dispatchEvent("click");
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-display-wireframe")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-canvas-topLeft")).toHaveCSS("background-color", "rgb(0, 0, 0)");
|
||||
await expect(page.getByText("1 solid selected (Whitebox Box 1)")).toBeVisible();
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { clickViewport, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
test("user can place PlayerStart, enter run mode, and spawn from it", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
@@ -20,7 +22,11 @@ test("user can place PlayerStart, enter run mode, and spawn from it", async ({ p
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByTestId("place-player-start").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-player-start").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "playerStart", audioAssetId: null }, { x: 0, y: 0, z: 0 });
|
||||
await clickViewport(page, "topLeft");
|
||||
await page.getByTestId("player-start-position-x").fill("4");
|
||||
await page.getByTestId("player-start-position-x").press("Tab");
|
||||
await page.getByTestId("player-start-position-z").fill("-2");
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { clickViewport, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
test("Interactable click prompt can teleport the player in run mode", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
@@ -20,8 +22,16 @@ test("Interactable click prompt can teleport the player in run mode", async ({ p
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByTestId("place-player-start").click();
|
||||
await page.getByTestId("add-entity-interactable").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-player-start").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "playerStart", audioAssetId: null }, { x: 0, y: 0, z: 0 });
|
||||
await clickViewport(page, "topLeft");
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-interactable").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "interactable", audioAssetId: null }, { x: 0, y: 0, z: 0 });
|
||||
await clickViewport(page, "topLeft");
|
||||
await page.getByTestId("interactable-position-y").fill("1");
|
||||
await page.getByTestId("interactable-position-y").press("Tab");
|
||||
await page.getByTestId("interactable-position-z").fill("1");
|
||||
@@ -31,7 +41,11 @@ test("Interactable click prompt can teleport the player in run mode", async ({ p
|
||||
await page.getByTestId("interactable-prompt").fill("Use Console");
|
||||
await page.getByTestId("interactable-prompt").press("Tab");
|
||||
|
||||
await page.getByTestId("add-entity-teleportTarget").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-teleport-target").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "teleportTarget", audioAssetId: null }, { x: 0, y: 0, z: 0 });
|
||||
await clickViewport(page, "topLeft");
|
||||
await page.getByTestId("teleportTarget-position-x").fill("6");
|
||||
await page.getByTestId("teleportTarget-position-x").press("Tab");
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { clickViewport, setViewportCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
test("Trigger Volume enter can teleport the player to a Teleport Target", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
@@ -20,9 +22,21 @@ test("Trigger Volume enter can teleport the player to a Teleport Target", async
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await page.getByTestId("place-player-start").click();
|
||||
await page.getByTestId("add-entity-triggerVolume").click();
|
||||
await page.getByTestId("add-entity-teleportTarget").click();
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-player-start").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "playerStart", audioAssetId: null }, { x: 0, y: 0, z: 0 });
|
||||
await clickViewport(page, "topLeft");
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-trigger-volume").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "triggerVolume", audioAssetId: null }, { x: 0, y: 0, z: 0 });
|
||||
await clickViewport(page, "topLeft");
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-entities").click();
|
||||
await page.getByTestId("add-menu-teleport-target").click();
|
||||
await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "teleportTarget", audioAssetId: null }, { x: 0, y: 0, z: 0 });
|
||||
await clickViewport(page, "topLeft");
|
||||
|
||||
await page.getByTestId("teleportTarget-position-x").fill("6");
|
||||
await page.getByTestId("teleportTarget-position-x").press("Tab");
|
||||
|
||||
155
tests/e2e/viewport-quad-layout.e2e.ts
Normal file
155
tests/e2e/viewport-quad-layout.e2e.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { beginBoxCreation, clickViewport, getEditorStoreSnapshot, getViewportPanel, setSharedBoxCreationPreview } from "./viewport-test-helpers";
|
||||
|
||||
test("quad viewport layout shows four linked panels with shared selection and active panel state", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
|
||||
page.on("pageerror", (error) => {
|
||||
pageErrors.push(error.message);
|
||||
});
|
||||
|
||||
page.on("console", (message) => {
|
||||
if (message.type() === "error") {
|
||||
consoleErrors.push(message.text());
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto("/");
|
||||
await page.evaluate((storageKey) => {
|
||||
window.localStorage.removeItem(storageKey);
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
await beginBoxCreation(page);
|
||||
await clickViewport(page, "topLeft");
|
||||
await expect(page.getByRole("button", { name: /Whitebox Box 1/ })).toBeVisible();
|
||||
await expect(page.getByText("1 solid selected (Whitebox Box 1)")).toBeVisible();
|
||||
|
||||
await page.getByTestId("viewport-layout-quad").click();
|
||||
|
||||
await expect(page.getByTestId("viewport-panel-topLeft")).toBeVisible();
|
||||
await expect(page.getByTestId("viewport-panel-topRight")).toBeVisible();
|
||||
await expect(page.getByTestId("viewport-panel-bottomLeft")).toBeVisible();
|
||||
await expect(page.getByTestId("viewport-panel-bottomRight")).toBeVisible();
|
||||
|
||||
const initialLayoutSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(initialLayoutSnapshot.viewportQuadSplit).toEqual({
|
||||
x: 0.5,
|
||||
y: 0.5
|
||||
});
|
||||
|
||||
const dragSplitter = async (testId: string, deltaX: number, deltaY: number) => {
|
||||
const splitter = page.getByTestId(testId);
|
||||
const box = await splitter.boundingBox();
|
||||
|
||||
if (box === null) {
|
||||
throw new Error(`Missing splitter handle: ${testId}`);
|
||||
}
|
||||
|
||||
await page.mouse.move(box.x + box.width * 0.5, box.y + box.height * 0.5);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(box.x + box.width * 0.5 + deltaX, box.y + box.height * 0.5 + deltaY);
|
||||
await page.mouse.up();
|
||||
};
|
||||
|
||||
await dragSplitter("viewport-quad-splitter-center", 80, 48);
|
||||
const afterCenterResizeSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(afterCenterResizeSnapshot.viewportQuadSplit.x).toBeGreaterThan(0.5);
|
||||
expect(afterCenterResizeSnapshot.viewportQuadSplit.y).toBeGreaterThan(0.5);
|
||||
|
||||
await dragSplitter("viewport-quad-splitter-vertical", -60, 0);
|
||||
const afterVerticalResizeSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(afterVerticalResizeSnapshot.viewportQuadSplit.x).toBeLessThan(afterCenterResizeSnapshot.viewportQuadSplit.x);
|
||||
expect(Math.abs(afterVerticalResizeSnapshot.viewportQuadSplit.y - afterCenterResizeSnapshot.viewportQuadSplit.y)).toBeLessThan(0.02);
|
||||
|
||||
await dragSplitter("viewport-quad-splitter-horizontal", 0, -40);
|
||||
const afterHorizontalResizeSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(Math.abs(afterHorizontalResizeSnapshot.viewportQuadSplit.x - afterVerticalResizeSnapshot.viewportQuadSplit.x)).toBeLessThan(0.02);
|
||||
expect(afterHorizontalResizeSnapshot.viewportQuadSplit.y).toBeLessThan(afterVerticalResizeSnapshot.viewportQuadSplit.y);
|
||||
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-view-perspective")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-display-normal")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-panel-topRight-view-top")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-panel-topRight-display-authoring")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-canvas-topRight")).toHaveCSS("background-color", "rgb(0, 0, 0)");
|
||||
await expect(page.getByTestId("viewport-panel-bottomLeft-view-front")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-panel-bottomLeft-display-authoring")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-panel-bottomRight-view-side")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-panel-bottomRight-display-authoring")).toHaveAttribute("aria-pressed", "true");
|
||||
|
||||
for (const panelId of ["topLeft", "topRight", "bottomLeft", "bottomRight"] as const) {
|
||||
await expect(getViewportPanel(page, panelId).locator(".viewport-panel__subtitle")).toHaveCount(0);
|
||||
await expect(getViewportPanel(page, panelId).locator(".viewport-canvas__overlay-text")).toHaveCount(0);
|
||||
}
|
||||
|
||||
await setSharedBoxCreationPreview(page, "topLeft", { x: 4, y: 0, z: 8 });
|
||||
const initialSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(initialSnapshot).toMatchObject({
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "box-brush"
|
||||
},
|
||||
center: {
|
||||
x: 4,
|
||||
y: 0,
|
||||
z: 8
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await getViewportPanel(page, "topRight").click({ position: { x: 16, y: 16 }, force: true });
|
||||
await page.getByTestId("viewport-panel-topRight-view-side").dispatchEvent("click");
|
||||
await expect(getViewportPanel(page, "topRight")).toHaveAttribute("data-active", "true");
|
||||
await expect(page.getByTestId("viewport-panel-topRight-view-side")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByRole("button", { name: /Whitebox Box 1/ })).toBeVisible();
|
||||
const transferredSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(transferredSnapshot).toMatchObject({
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "box-brush"
|
||||
},
|
||||
center: {
|
||||
x: 4,
|
||||
y: 0,
|
||||
z: 8
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await getViewportPanel(page, "topLeft").click({ position: { x: 16, y: 16 }, force: true });
|
||||
await page.getByTestId("viewport-panel-topLeft-display-authoring").dispatchEvent("click");
|
||||
await expect(getViewportPanel(page, "topLeft")).toHaveAttribute("data-active", "true");
|
||||
await expect(page.getByTestId("viewport-panel-topLeft-display-authoring")).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByTestId("viewport-canvas-topLeft")).toHaveCSS("background-color", "rgb(0, 0, 0)");
|
||||
await expect(page.getByText("1 solid selected (Whitebox Box 1)")).toBeVisible();
|
||||
const finalSnapshot = await getEditorStoreSnapshot(page);
|
||||
expect(finalSnapshot).toMatchObject({
|
||||
viewportTransientState: {
|
||||
toolPreview: {
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "box-brush"
|
||||
},
|
||||
center: {
|
||||
x: 4,
|
||||
y: 0,
|
||||
z: 8
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
});
|
||||
201
tests/e2e/viewport-test-helpers.ts
Normal file
201
tests/e2e/viewport-test-helpers.ts
Normal file
@@ -0,0 +1,201 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
|
||||
import type { TransformSessionState } from "../../src/core/transform-session";
|
||||
import type { SceneDocument } from "../../src/document/scene-document";
|
||||
import type { CreationTarget, ViewportToolPreview } from "../../src/viewport-three/viewport-transient-state";
|
||||
import type { ViewportPanelId } from "../../src/viewport-three/viewport-layout";
|
||||
|
||||
export const DEFAULT_VIEWPORT_PANEL_ID: ViewportPanelId = "topLeft";
|
||||
|
||||
export function getViewportPanel(page: Page, panelId: string = DEFAULT_VIEWPORT_PANEL_ID) {
|
||||
return page.getByTestId(`viewport-panel-${panelId}`);
|
||||
}
|
||||
|
||||
export function getViewportCanvas(page: Page, panelId: string = DEFAULT_VIEWPORT_PANEL_ID) {
|
||||
return getViewportPanel(page, panelId).locator("canvas");
|
||||
}
|
||||
|
||||
export function getViewportOverlay(page: Page, panelId: string = DEFAULT_VIEWPORT_PANEL_ID) {
|
||||
return page.getByTestId(`viewport-overlay-${panelId}`);
|
||||
}
|
||||
|
||||
interface EditorStoreSnapshot {
|
||||
selection: {
|
||||
kind: string;
|
||||
ids?: string[];
|
||||
brushId?: string;
|
||||
faceId?: string;
|
||||
edgeId?: string;
|
||||
vertexId?: string;
|
||||
};
|
||||
whiteboxSelectionMode: string;
|
||||
toolMode: string;
|
||||
document: {
|
||||
assets: Record<string, { id: string; kind: string; sourceName: string }>;
|
||||
brushes: Record<string, { center: { x: number; y: number; z: number } }>;
|
||||
modelInstances: Record<string, { position: { x: number; y: number; z: number } }>;
|
||||
entities: Record<string, { position: { x: number; y: number; z: number } }>;
|
||||
};
|
||||
viewportQuadSplit: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
viewportTransientState: {
|
||||
toolPreview: ViewportToolPreview;
|
||||
transformSession: TransformSessionState;
|
||||
};
|
||||
}
|
||||
|
||||
export async function getEditorStoreSnapshot(page: Page): Promise<EditorStoreSnapshot> {
|
||||
return page.evaluate(() => {
|
||||
const store = (window as Window & {
|
||||
__webeditor3dEditorStore?: {
|
||||
getState(): EditorStoreSnapshot;
|
||||
};
|
||||
}).__webeditor3dEditorStore;
|
||||
|
||||
if (store === undefined) {
|
||||
throw new Error("Editor store debug hook is unavailable.");
|
||||
}
|
||||
|
||||
return store.getState();
|
||||
});
|
||||
}
|
||||
|
||||
export async function getViewportToolPreview(page: Page): Promise<EditorStoreSnapshot["viewportTransientState"]["toolPreview"]> {
|
||||
const snapshot = await getEditorStoreSnapshot(page);
|
||||
return snapshot.viewportTransientState.toolPreview;
|
||||
}
|
||||
|
||||
export async function replaceSceneDocument(page: Page, document: SceneDocument) {
|
||||
await page.evaluate((nextDocument) => {
|
||||
const store = (window as Window & {
|
||||
__webeditor3dEditorStore?: {
|
||||
replaceDocument(document: SceneDocument, resetHistory?: boolean): void;
|
||||
};
|
||||
}).__webeditor3dEditorStore;
|
||||
|
||||
if (store === undefined) {
|
||||
throw new Error("Editor store debug hook is unavailable.");
|
||||
}
|
||||
|
||||
store.replaceDocument(nextDocument);
|
||||
}, document);
|
||||
}
|
||||
|
||||
export async function setViewportCreationPreview(
|
||||
page: Page,
|
||||
panelId: ViewportPanelId,
|
||||
target: CreationTarget,
|
||||
center: { x: number; y: number; z: number } | null
|
||||
) {
|
||||
await page.evaluate(
|
||||
({ sourcePanelId, nextTarget, nextCenter }) => {
|
||||
const store = (window as Window & {
|
||||
__webeditor3dEditorStore?: {
|
||||
setViewportToolPreview(preview: ViewportToolPreview): void;
|
||||
};
|
||||
}).__webeditor3dEditorStore;
|
||||
|
||||
if (store === undefined) {
|
||||
throw new Error("Editor store debug hook is unavailable.");
|
||||
}
|
||||
|
||||
store.setViewportToolPreview({
|
||||
kind: "create",
|
||||
sourcePanelId,
|
||||
target: nextTarget,
|
||||
center: nextCenter
|
||||
});
|
||||
},
|
||||
{
|
||||
sourcePanelId: panelId,
|
||||
nextTarget: target,
|
||||
nextCenter: center
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export async function clearViewportCreationPreview(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
const store = (window as Window & {
|
||||
__webeditor3dEditorStore?: {
|
||||
setViewportToolPreview(preview: ViewportToolPreview): void;
|
||||
};
|
||||
}).__webeditor3dEditorStore;
|
||||
|
||||
if (store === undefined) {
|
||||
throw new Error("Editor store debug hook is unavailable.");
|
||||
}
|
||||
|
||||
store.setViewportToolPreview({
|
||||
kind: "none"
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function beginBoxCreation(page: Page) {
|
||||
await page.getByTestId("outliner-add-button").click();
|
||||
await page.getByTestId("add-menu-box").click();
|
||||
}
|
||||
|
||||
export async function clickViewport(page: Page, panelId: string = DEFAULT_VIEWPORT_PANEL_ID) {
|
||||
const viewportPanel = getViewportPanel(page, panelId);
|
||||
await viewportPanel.click({ position: { x: 16, y: 16 }, force: true });
|
||||
|
||||
const fallbackButton = viewportPanel.getByTestId(`viewport-fallback-create-${panelId}`);
|
||||
|
||||
if ((await fallbackButton.count()) > 0) {
|
||||
await fallbackButton.click();
|
||||
return;
|
||||
}
|
||||
|
||||
const viewportCanvas = getViewportCanvas(page, panelId);
|
||||
|
||||
if ((await viewportCanvas.count()) > 0) {
|
||||
await viewportCanvas.click();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export async function clickViewportAtRatio(page: Page, panelId: string, xRatio: number, yRatio: number) {
|
||||
const viewportCanvas = getViewportCanvas(page, panelId);
|
||||
|
||||
if ((await viewportCanvas.count()) > 0) {
|
||||
const canvasBox = await viewportCanvas.boundingBox();
|
||||
|
||||
if (canvasBox !== null) {
|
||||
await viewportCanvas.click({
|
||||
position: {
|
||||
x: canvasBox.width * xRatio,
|
||||
y: canvasBox.height * yRatio
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const viewportPanel = getViewportPanel(page, panelId);
|
||||
const box = await viewportPanel.boundingBox();
|
||||
|
||||
if (box === null) {
|
||||
throw new Error(`Missing viewport panel for ${panelId}.`);
|
||||
}
|
||||
|
||||
await page.mouse.click(box.x + box.width * xRatio, box.y + box.height * yRatio);
|
||||
}
|
||||
|
||||
export async function setSharedBoxCreationPreview(
|
||||
page: Page,
|
||||
panelId: ViewportPanelId,
|
||||
center: { x: number; y: number; z: number } | null
|
||||
) {
|
||||
return setViewportCreationPreview(
|
||||
page,
|
||||
panelId,
|
||||
{
|
||||
kind: "box-brush"
|
||||
},
|
||||
center
|
||||
);
|
||||
}
|
||||
186
tests/e2e/whitebox-component-selection.e2e.ts
Normal file
186
tests/e2e/whitebox-component-selection.e2e.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { createBoxBrush } from "../../src/document/brushes";
|
||||
import { createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
import {
|
||||
clickViewportAtRatio,
|
||||
getEditorStoreSnapshot,
|
||||
replaceSceneDocument
|
||||
} from "./viewport-test-helpers";
|
||||
|
||||
test("whitebox component selection modes keep object picking intentional across perspective and orthographic panes", async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
const consoleErrors: string[] = [];
|
||||
|
||||
page.on("pageerror", (error) => {
|
||||
pageErrors.push(error.message);
|
||||
});
|
||||
|
||||
page.on("console", (message) => {
|
||||
if (message.type() === "error") {
|
||||
consoleErrors.push(message.text());
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto("/");
|
||||
await page.evaluate((storageKey) => {
|
||||
window.localStorage.removeItem(storageKey);
|
||||
}, "webeditor3d.scene-document-draft");
|
||||
await page.reload();
|
||||
|
||||
test.skip((await page.getByText("Viewport Unavailable").count()) > 0, "WebGL is unavailable in this Playwright environment.");
|
||||
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-selection-modes-main",
|
||||
name: "Selection Fixture",
|
||||
center: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 2
|
||||
}
|
||||
});
|
||||
|
||||
await replaceSceneDocument(page, {
|
||||
...createEmptySceneDocument({ name: "Selection Modes Scene" }),
|
||||
brushes: {
|
||||
[brush.id]: brush
|
||||
}
|
||||
});
|
||||
|
||||
await page.evaluate(({ target }) => {
|
||||
const store = (window as Window & {
|
||||
__webeditor3dEditorStore?: {
|
||||
getState(): {
|
||||
viewportPanels: {
|
||||
topLeft: {
|
||||
cameraState: {
|
||||
target: { x: number; y: number; z: number };
|
||||
perspectiveOrbit: { radius: number; theta: number; phi: number };
|
||||
orthographicZoom: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
setViewportPanelCameraState(panelId: "topLeft", cameraState: {
|
||||
target: { x: number; y: number; z: number };
|
||||
perspectiveOrbit: { radius: number; theta: number; phi: number };
|
||||
orthographicZoom: number;
|
||||
}): void;
|
||||
};
|
||||
}).__webeditor3dEditorStore;
|
||||
|
||||
if (store === undefined) {
|
||||
throw new Error("Editor store debug hook is unavailable.");
|
||||
}
|
||||
|
||||
const topLeftCameraState = store.getState().viewportPanels.topLeft.cameraState;
|
||||
|
||||
store.setViewportPanelCameraState("topLeft", {
|
||||
...topLeftCameraState,
|
||||
target,
|
||||
perspectiveOrbit: {
|
||||
radius: 4.5,
|
||||
theta: 0.72,
|
||||
phi: 1.08
|
||||
}
|
||||
});
|
||||
}, { target: brush.center });
|
||||
|
||||
await expect(page.getByTestId("viewport-selection-mode-topLeft")).toHaveText("Object");
|
||||
await clickViewportAtRatio(page, "topLeft", 0.5, 0.52);
|
||||
let snapshot = await getEditorStoreSnapshot(page);
|
||||
expect(snapshot.whiteboxSelectionMode).toBe("object");
|
||||
expect(snapshot.selection).toMatchObject({
|
||||
kind: "brushes",
|
||||
ids: [brush.id]
|
||||
});
|
||||
|
||||
await page.getByTestId("viewport-layout-quad").click();
|
||||
|
||||
await page.evaluate(({ target }) => {
|
||||
const store = (window as Window & {
|
||||
__webeditor3dEditorStore?: {
|
||||
getState(): {
|
||||
viewportPanels: {
|
||||
topRight: {
|
||||
cameraState: {
|
||||
target: { x: number; y: number; z: number };
|
||||
perspectiveOrbit: { radius: number; theta: number; phi: number };
|
||||
orthographicZoom: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
setViewportPanelViewMode(panelId: "topRight", viewMode: "top"): void;
|
||||
setViewportPanelCameraState(panelId: "topRight", cameraState: {
|
||||
target: { x: number; y: number; z: number };
|
||||
perspectiveOrbit: { radius: number; theta: number; phi: number };
|
||||
orthographicZoom: number;
|
||||
}): void;
|
||||
};
|
||||
}).__webeditor3dEditorStore;
|
||||
|
||||
if (store === undefined) {
|
||||
throw new Error("Editor store debug hook is unavailable.");
|
||||
}
|
||||
|
||||
const topRightCameraState = store.getState().viewportPanels.topRight.cameraState;
|
||||
store.setViewportPanelViewMode("topRight", "top");
|
||||
store.setViewportPanelCameraState("topRight", {
|
||||
...topRightCameraState,
|
||||
target,
|
||||
orthographicZoom: 8
|
||||
});
|
||||
}, { target: brush.center });
|
||||
|
||||
await page.getByTestId("whitebox-selection-mode-face").click();
|
||||
await expect(page.getByTestId("viewport-selection-mode-topRight")).toHaveText("Face");
|
||||
await clickViewportAtRatio(page, "topRight", 0.5, 0.5);
|
||||
snapshot = await getEditorStoreSnapshot(page);
|
||||
expect(snapshot.whiteboxSelectionMode).toBe("face");
|
||||
expect(snapshot.selection).toMatchObject({
|
||||
kind: "brushFace",
|
||||
brushId: brush.id,
|
||||
faceId: "posY"
|
||||
});
|
||||
await expect(page.getByTestId("viewport-panel-active-badge-topRight")).toBeVisible();
|
||||
|
||||
await page.getByTestId("whitebox-selection-mode-edge").click();
|
||||
await expect(page.getByTestId("viewport-selection-mode-topRight")).toHaveText("Edge");
|
||||
await clickViewportAtRatio(page, "topRight", 0.5, 0.12);
|
||||
snapshot = await getEditorStoreSnapshot(page);
|
||||
expect(snapshot.whiteboxSelectionMode).toBe("edge");
|
||||
expect(snapshot.selection).toMatchObject({
|
||||
kind: "brushEdge",
|
||||
brushId: brush.id,
|
||||
edgeId: "edgeX_posY_negZ"
|
||||
});
|
||||
|
||||
await page.getByTestId("whitebox-selection-mode-vertex").click();
|
||||
await expect(page.getByTestId("viewport-selection-mode-topRight")).toHaveText("Vertex");
|
||||
await clickViewportAtRatio(page, "topRight", 0.88, 0.12);
|
||||
snapshot = await getEditorStoreSnapshot(page);
|
||||
expect(snapshot.whiteboxSelectionMode).toBe("vertex");
|
||||
expect(snapshot.selection).toMatchObject({
|
||||
kind: "brushVertex",
|
||||
brushId: brush.id,
|
||||
vertexId: "posX_posY_negZ"
|
||||
});
|
||||
|
||||
await page.getByTestId("whitebox-selection-mode-object").click();
|
||||
await clickViewportAtRatio(page, "topRight", 0.5, 0.5);
|
||||
snapshot = await getEditorStoreSnapshot(page);
|
||||
expect(snapshot.whiteboxSelectionMode).toBe("object");
|
||||
expect(snapshot.selection).toMatchObject({
|
||||
kind: "brushes",
|
||||
ids: [brush.id]
|
||||
});
|
||||
|
||||
expect(pageErrors).toEqual([]);
|
||||
expect(consoleErrors).toEqual([]);
|
||||
});
|
||||
@@ -42,7 +42,7 @@ test("world environment settings persist and carry into the runner", async ({ pa
|
||||
await page.getByTestId("world-sun-direction-x").press("Tab");
|
||||
|
||||
await expect(page.getByTestId("world-background-mode-value")).toContainText("Vertical Gradient");
|
||||
await expect(page.getByTestId("viewport-shell")).toHaveCSS("background-image", /linear-gradient/);
|
||||
await expect(page.getByTestId("viewport-canvas-topLeft")).toHaveCSS("background-image", /linear-gradient/);
|
||||
|
||||
await page.getByRole("button", { name: "Save Draft" }).click();
|
||||
|
||||
@@ -55,7 +55,7 @@ test("world environment settings persist and carry into the runner", async ({ pa
|
||||
|
||||
await expect(page.getByTestId("world-background-mode-value")).toContainText("Vertical Gradient");
|
||||
await expect(page.getByTestId("world-ambient-intensity")).toHaveValue("0.45");
|
||||
await expect(page.getByTestId("viewport-shell")).toHaveCSS("background-image", /linear-gradient/);
|
||||
await expect(page.getByTestId("viewport-canvas-topLeft")).toHaveCSS("background-image", /linear-gradient/);
|
||||
|
||||
await page.getByTestId("enter-run-mode").click();
|
||||
|
||||
|
||||
@@ -37,4 +37,34 @@ describe("box brush geometry", () => {
|
||||
expect(new Set(corners.map((corner) => `${corner.x}:${corner.y}:${corner.z}`)).size).toBe(8);
|
||||
expect(corners.every((corner) => Number.isFinite(corner.x) && Number.isFinite(corner.y) && Number.isFinite(corner.z))).toBe(true);
|
||||
});
|
||||
|
||||
it("derives rotated world bounds from authored box rotation without changing stable corner count", () => {
|
||||
const brush = createBoxBrush({
|
||||
center: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 45,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 4
|
||||
}
|
||||
});
|
||||
|
||||
const bounds = getBoxBrushBounds(brush);
|
||||
const corners = getBoxBrushCornerPositions(brush);
|
||||
|
||||
expect(bounds.min.x).toBeCloseTo(-2.1213203436);
|
||||
expect(bounds.max.x).toBeCloseTo(2.1213203436);
|
||||
expect(bounds.min.z).toBeCloseTo(-2.1213203436);
|
||||
expect(bounds.max.z).toBeCloseTo(2.1213203436);
|
||||
expect(corners).toHaveLength(8);
|
||||
expect(new Set(corners.map((corner) => `${corner.x}:${corner.y}:${corner.z}`)).size).toBe(8);
|
||||
});
|
||||
});
|
||||
|
||||
147
tests/geometry/model-instance-collider-generation.test.ts
Normal file
147
tests/geometry/model-instance-collider-generation.test.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BoxGeometry, Group, Mesh, MeshBasicMaterial, PlaneGeometry } from "three";
|
||||
|
||||
import { createModelInstance } from "../../src/assets/model-instances";
|
||||
import { buildGeneratedModelCollider } from "../../src/geometry/model-instance-collider-generation";
|
||||
import {
|
||||
createFixtureLoadedModelAsset,
|
||||
createFixtureLoadedModelAssetFromGeometry,
|
||||
createFixtureModelAssetRecord
|
||||
} from "../helpers/model-collider-fixtures";
|
||||
|
||||
describe("buildGeneratedModelCollider", () => {
|
||||
it("builds a simple oriented box collider from asset bounds", () => {
|
||||
const { asset } = createFixtureLoadedModelAssetFromGeometry("asset-model-simple", new BoxGeometry(2, 4, 6));
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-simple",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "simple",
|
||||
visible: true
|
||||
}
|
||||
});
|
||||
|
||||
const collider = buildGeneratedModelCollider(modelInstance, asset);
|
||||
|
||||
expect(collider).not.toBeNull();
|
||||
expect(collider).toMatchObject({
|
||||
kind: "box",
|
||||
mode: "simple",
|
||||
visible: true,
|
||||
center: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 2,
|
||||
y: 4,
|
||||
z: 6
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("builds a static triangle-mesh collider from loaded model geometry", () => {
|
||||
const { asset, loadedAsset } = createFixtureLoadedModelAssetFromGeometry("asset-model-static", new BoxGeometry(2, 1, 3));
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-static",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "static",
|
||||
visible: false
|
||||
}
|
||||
});
|
||||
|
||||
const collider = buildGeneratedModelCollider(modelInstance, asset, loadedAsset);
|
||||
|
||||
expect(collider).not.toBeNull();
|
||||
expect(collider?.kind).toBe("trimesh");
|
||||
|
||||
if (collider === null || collider.kind !== "trimesh") {
|
||||
throw new Error("Expected a trimesh collider.");
|
||||
}
|
||||
|
||||
expect(collider.mode).toBe("static");
|
||||
expect(Array.from(collider.vertices)).toSatisfy((values: number[]) => values.every(Number.isFinite));
|
||||
expect(Array.from(collider.indices)).toSatisfy((values: number[]) => values.every(Number.isInteger));
|
||||
});
|
||||
|
||||
it("builds a terrain heightfield from a regular-grid mesh", () => {
|
||||
const geometry = new PlaneGeometry(4, 4, 2, 2);
|
||||
geometry.rotateX(-Math.PI * 0.5);
|
||||
const { asset, loadedAsset } = createFixtureLoadedModelAssetFromGeometry("asset-model-terrain", geometry);
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-terrain",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "terrain",
|
||||
visible: true
|
||||
}
|
||||
});
|
||||
|
||||
const collider = buildGeneratedModelCollider(modelInstance, asset, loadedAsset);
|
||||
|
||||
expect(collider).not.toBeNull();
|
||||
expect(collider?.kind).toBe("heightfield");
|
||||
|
||||
if (collider === null || collider.kind !== "heightfield") {
|
||||
throw new Error("Expected a heightfield collider.");
|
||||
}
|
||||
|
||||
expect(collider).toMatchObject({
|
||||
mode: "terrain",
|
||||
rows: 3,
|
||||
cols: 3
|
||||
});
|
||||
expect(Array.from(collider.heights)).toSatisfy((values: number[]) => values.every(Number.isFinite));
|
||||
});
|
||||
|
||||
it("fails terrain mode for meshes that are not a clean regular-grid terrain surface", () => {
|
||||
const { asset, loadedAsset } = createFixtureLoadedModelAssetFromGeometry("asset-model-invalid-terrain", new BoxGeometry(2, 2, 2));
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-invalid-terrain",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "terrain",
|
||||
visible: false
|
||||
}
|
||||
});
|
||||
|
||||
expect(() => buildGeneratedModelCollider(modelInstance, asset, loadedAsset)).toThrow("cannot use terrain collision");
|
||||
});
|
||||
|
||||
it("builds explicit convex compound pieces for dynamic mode", () => {
|
||||
const template = new Group();
|
||||
const material = new MeshBasicMaterial();
|
||||
const leftBox = new Mesh(new BoxGeometry(1, 1, 1), material);
|
||||
const rightBox = new Mesh(new BoxGeometry(1, 2, 1), material);
|
||||
|
||||
leftBox.position.set(-1.25, 0.5, 0);
|
||||
rightBox.position.set(1.25, 1, 0);
|
||||
template.add(leftBox);
|
||||
template.add(rightBox);
|
||||
template.updateMatrixWorld(true);
|
||||
|
||||
const asset = createFixtureModelAssetRecord("asset-model-dynamic", template);
|
||||
const loadedAsset = createFixtureLoadedModelAsset(asset, template);
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-dynamic",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "dynamic",
|
||||
visible: true
|
||||
}
|
||||
});
|
||||
|
||||
const collider = buildGeneratedModelCollider(modelInstance, asset, loadedAsset);
|
||||
|
||||
expect(collider).not.toBeNull();
|
||||
expect(collider).toMatchObject({
|
||||
kind: "compound",
|
||||
mode: "dynamic",
|
||||
decomposition: "spatial-bisect",
|
||||
runtimeBehavior: "fixedQueryOnly"
|
||||
});
|
||||
expect(collider?.kind === "compound" ? collider.pieces.length : 0).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
104
tests/helpers/model-collider-fixtures.ts
Normal file
104
tests/helpers/model-collider-fixtures.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { Box3, Group, Mesh, MeshBasicMaterial, type BufferGeometry } from "three";
|
||||
|
||||
import type { LoadedModelAsset } from "../../src/assets/gltf-model-import";
|
||||
import { createProjectAssetStorageKey, type ModelAssetRecord } from "../../src/assets/project-assets";
|
||||
|
||||
function countMeshes(group: Group): number {
|
||||
let count = 0;
|
||||
|
||||
group.traverse((object) => {
|
||||
if ((object as Mesh).isMesh === true) {
|
||||
count += 1;
|
||||
}
|
||||
});
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
function countNodes(group: Group): number {
|
||||
let count = 0;
|
||||
|
||||
group.traverse(() => {
|
||||
count += 1;
|
||||
});
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
function createBoundingBox(group: Group): ModelAssetRecord["metadata"]["boundingBox"] {
|
||||
const bounds = new Box3().setFromObject(group);
|
||||
|
||||
if (bounds.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
min: {
|
||||
x: bounds.min.x,
|
||||
y: bounds.min.y,
|
||||
z: bounds.min.z
|
||||
},
|
||||
max: {
|
||||
x: bounds.max.x,
|
||||
y: bounds.max.y,
|
||||
z: bounds.max.z
|
||||
},
|
||||
size: {
|
||||
x: bounds.max.x - bounds.min.x,
|
||||
y: bounds.max.y - bounds.min.y,
|
||||
z: bounds.max.z - bounds.min.z
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createFixtureModelAssetRecord(id: string, template: Group, sourceName = `${id}.glb`): ModelAssetRecord {
|
||||
template.updateMatrixWorld(true);
|
||||
|
||||
return {
|
||||
id,
|
||||
kind: "model",
|
||||
sourceName,
|
||||
mimeType: "model/gltf-binary",
|
||||
storageKey: createProjectAssetStorageKey(id),
|
||||
byteLength: 128,
|
||||
metadata: {
|
||||
kind: "model",
|
||||
format: "glb",
|
||||
sceneName: sourceName,
|
||||
nodeCount: countNodes(template),
|
||||
meshCount: countMeshes(template),
|
||||
materialNames: [],
|
||||
textureNames: [],
|
||||
animationNames: [],
|
||||
boundingBox: createBoundingBox(template),
|
||||
warnings: []
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createFixtureLoadedModelAsset(asset: ModelAssetRecord, template: Group): LoadedModelAsset {
|
||||
template.updateMatrixWorld(true);
|
||||
|
||||
return {
|
||||
assetId: asset.id,
|
||||
storageKey: asset.storageKey,
|
||||
metadata: asset.metadata,
|
||||
template,
|
||||
animations: []
|
||||
};
|
||||
}
|
||||
|
||||
export function createFixtureLoadedModelAssetFromGeometry(assetId: string, geometry: BufferGeometry): {
|
||||
asset: ModelAssetRecord;
|
||||
loadedAsset: LoadedModelAsset;
|
||||
} {
|
||||
const template = new Group();
|
||||
template.add(new Mesh(geometry, new MeshBasicMaterial()));
|
||||
template.updateMatrixWorld(true);
|
||||
const asset = createFixtureModelAssetRecord(assetId, template);
|
||||
|
||||
return {
|
||||
asset,
|
||||
loadedAsset: createFixtureLoadedModelAsset(asset, template)
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createBoxBrush } from "../../src/document/brushes";
|
||||
import { SCENE_DOCUMENT_VERSION, createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
import { serializeSceneDocument } from "../../src/serialization/scene-document-json";
|
||||
import {
|
||||
DEFAULT_SCENE_DRAFT_STORAGE_KEY,
|
||||
getBrowserStorageAccess,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
saveSceneDocumentDraft,
|
||||
type KeyValueStorage
|
||||
} from "../../src/serialization/local-draft-storage";
|
||||
import { createDefaultViewportLayoutState } from "../../src/viewport-three/viewport-layout";
|
||||
|
||||
class MemoryStorage implements KeyValueStorage {
|
||||
private readonly values = new Map<string, string>();
|
||||
@@ -118,6 +120,71 @@ describe("local draft storage", () => {
|
||||
expect(result.message).toContain("quota exceeded");
|
||||
});
|
||||
|
||||
it("stores and restores editor viewport layout state alongside the document draft", () => {
|
||||
const storage = new MemoryStorage();
|
||||
const viewportLayoutState = createDefaultViewportLayoutState();
|
||||
|
||||
viewportLayoutState.layoutMode = "quad";
|
||||
viewportLayoutState.activePanelId = "bottomRight";
|
||||
viewportLayoutState.panels.topLeft.displayMode = "wireframe";
|
||||
viewportLayoutState.panels.topLeft.cameraState.target = {
|
||||
x: 8,
|
||||
y: 3,
|
||||
z: -5
|
||||
};
|
||||
viewportLayoutState.panels.topLeft.cameraState.perspectiveOrbit.theta = 1.25;
|
||||
viewportLayoutState.panels.topLeft.cameraState.orthographicZoom = 2.5;
|
||||
|
||||
expect(saveSceneDocumentDraft(storage, createEmptySceneDocument({ name: "Viewport Draft" }), viewportLayoutState)).toEqual({
|
||||
status: "saved",
|
||||
message: "Local draft saved."
|
||||
});
|
||||
|
||||
const result = loadSceneDocumentDraft(storage);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "loaded",
|
||||
document: {
|
||||
name: "Viewport Draft"
|
||||
},
|
||||
viewportLayoutState: {
|
||||
layoutMode: "quad",
|
||||
activePanelId: "bottomRight",
|
||||
panels: {
|
||||
topLeft: {
|
||||
displayMode: "wireframe",
|
||||
cameraState: {
|
||||
target: {
|
||||
x: 8,
|
||||
y: 3,
|
||||
z: -5
|
||||
},
|
||||
perspectiveOrbit: {
|
||||
theta: 1.25
|
||||
},
|
||||
orthographicZoom: 2.5
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("loads older raw scene-document drafts without requiring viewport layout state", () => {
|
||||
const storage = new MemoryStorage();
|
||||
storage.setItem(DEFAULT_SCENE_DRAFT_STORAGE_KEY, serializeSceneDocument(createEmptySceneDocument({ name: "Legacy Draft" })));
|
||||
|
||||
const result = loadSceneDocumentDraft(storage);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "loaded",
|
||||
document: {
|
||||
name: "Legacy Draft"
|
||||
},
|
||||
viewportLayoutState: null
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses to save an invalid scene document draft", () => {
|
||||
const invalidBrush = createBoxBrush({
|
||||
id: "brush-invalid"
|
||||
|
||||
@@ -3,10 +3,13 @@ import { describe, expect, it } from "vitest";
|
||||
import { createBoxBrush } from "../../src/document/brushes";
|
||||
import {
|
||||
ANIMATION_PLAYBACK_SCENE_DOCUMENT_VERSION,
|
||||
ENTITY_NAMES_SCENE_DOCUMENT_VERSION,
|
||||
ENTITY_SYSTEM_FOUNDATION_SCENE_DOCUMENT_VERSION,
|
||||
FIRST_ROOM_POLISH_SCENE_DOCUMENT_VERSION,
|
||||
IMPORTED_MODEL_COLLIDERS_SCENE_DOCUMENT_VERSION,
|
||||
LOCAL_LIGHTS_AND_SKYBOX_SCENE_DOCUMENT_VERSION,
|
||||
MODEL_ASSET_PIPELINE_SCENE_DOCUMENT_VERSION,
|
||||
PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION,
|
||||
SCENE_DOCUMENT_VERSION,
|
||||
SPATIAL_AUDIO_SCENE_DOCUMENT_VERSION,
|
||||
TRIGGER_ACTION_TARGET_FOUNDATION_SCENE_DOCUMENT_VERSION,
|
||||
@@ -69,6 +72,35 @@ describe("scene document JSON", () => {
|
||||
expect(parseSceneDocumentJson(serializeSceneDocument(document))).toEqual(document);
|
||||
});
|
||||
|
||||
it("round-trips floating-point whitebox box transforms without accidental snapping", () => {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-float-transform",
|
||||
center: {
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.875
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 12.5,
|
||||
y: 37.5,
|
||||
z: -8.25
|
||||
},
|
||||
size: {
|
||||
x: 2.5,
|
||||
y: 3.25,
|
||||
z: 4.75
|
||||
}
|
||||
});
|
||||
const document = {
|
||||
...createEmptySceneDocument({ name: "Float Transform Scene" }),
|
||||
brushes: {
|
||||
[brush.id]: brush
|
||||
}
|
||||
};
|
||||
|
||||
expect(parseSceneDocumentJson(serializeSceneDocument(document))).toEqual(document);
|
||||
});
|
||||
|
||||
it("round-trips per-face material and UV state", () => {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-face-room",
|
||||
@@ -257,12 +289,24 @@ describe("scene document JSON", () => {
|
||||
it("round-trips a document containing an authored PlayerStart entity", () => {
|
||||
const playerStart = createPlayerStartEntity({
|
||||
id: "entity-player-start-main",
|
||||
name: "Main Spawn",
|
||||
position: {
|
||||
x: 4,
|
||||
y: 0,
|
||||
z: -2
|
||||
},
|
||||
yawDegrees: 135
|
||||
yawDegrees: 135,
|
||||
collider: {
|
||||
mode: "box",
|
||||
eyeHeight: 1.4,
|
||||
capsuleRadius: 0.3,
|
||||
capsuleHeight: 1.8,
|
||||
boxSize: {
|
||||
x: 0.8,
|
||||
y: 1.6,
|
||||
z: 0.7
|
||||
}
|
||||
}
|
||||
});
|
||||
const document = {
|
||||
...createEmptySceneDocument({ name: "Player Start Scene" }),
|
||||
@@ -274,6 +318,185 @@ describe("scene document JSON", () => {
|
||||
expect(parseSceneDocumentJson(serializeSceneDocument(document))).toEqual(document);
|
||||
});
|
||||
|
||||
it("migrates version 14 documents without entity names", () => {
|
||||
const pointLight = createPointLightEntity({
|
||||
id: "entity-point-light-legacy",
|
||||
position: {
|
||||
x: 2,
|
||||
y: 3,
|
||||
z: 1
|
||||
},
|
||||
colorHex: "#ffeeaa",
|
||||
intensity: 1.75,
|
||||
distance: 9
|
||||
});
|
||||
const legacyDocument = {
|
||||
...createEmptySceneDocument({ name: "Legacy Entity Name Scene" }),
|
||||
version: 14 as const,
|
||||
entities: {
|
||||
[pointLight.id]: pointLight
|
||||
}
|
||||
};
|
||||
|
||||
const migratedDocument = migrateSceneDocument(legacyDocument);
|
||||
|
||||
expect(migratedDocument.version).toBe(SCENE_DOCUMENT_VERSION);
|
||||
expect(migratedDocument.entities[pointLight.id]).toEqual(pointLight);
|
||||
});
|
||||
|
||||
it("migrates version 15 model instances to include default collider settings", () => {
|
||||
const asset = {
|
||||
id: "asset-model-legacy-collider",
|
||||
kind: "model",
|
||||
sourceName: "legacy-collider.glb",
|
||||
mimeType: "model/gltf-binary",
|
||||
storageKey: createProjectAssetStorageKey("asset-model-legacy-collider"),
|
||||
byteLength: 64,
|
||||
metadata: {
|
||||
kind: "model",
|
||||
format: "glb",
|
||||
sceneName: "Legacy Collider Scene",
|
||||
nodeCount: 1,
|
||||
meshCount: 1,
|
||||
materialNames: [],
|
||||
textureNames: [],
|
||||
animationNames: [],
|
||||
boundingBox: {
|
||||
min: {
|
||||
x: -0.5,
|
||||
y: 0,
|
||||
z: -0.5
|
||||
},
|
||||
max: {
|
||||
x: 0.5,
|
||||
y: 1,
|
||||
z: 0.5
|
||||
},
|
||||
size: {
|
||||
x: 1,
|
||||
y: 1,
|
||||
z: 1
|
||||
}
|
||||
},
|
||||
warnings: []
|
||||
}
|
||||
} satisfies ModelAssetRecord;
|
||||
const migratedDocument = migrateSceneDocument({
|
||||
...createEmptySceneDocument({ name: "Legacy Model Collider Scene" }),
|
||||
version: ENTITY_NAMES_SCENE_DOCUMENT_VERSION,
|
||||
assets: {
|
||||
[asset.id]: asset
|
||||
},
|
||||
modelInstances: {
|
||||
"model-instance-legacy-collider": {
|
||||
id: "model-instance-legacy-collider",
|
||||
kind: "modelInstance",
|
||||
assetId: asset.id,
|
||||
position: {
|
||||
x: 1,
|
||||
y: 0,
|
||||
z: -2
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 45,
|
||||
z: 0
|
||||
},
|
||||
scale: {
|
||||
x: 1,
|
||||
y: 1,
|
||||
z: 1
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
expect(migratedDocument.version).toBe(SCENE_DOCUMENT_VERSION);
|
||||
expect(migratedDocument.modelInstances["model-instance-legacy-collider"].collision).toEqual({
|
||||
mode: "none",
|
||||
visible: false
|
||||
});
|
||||
});
|
||||
|
||||
it("migrates version 17 box brushes to include default whitebox rotation", () => {
|
||||
const migratedDocument = migrateSceneDocument({
|
||||
...createEmptySceneDocument({ name: "Legacy Whitebox Transform Scene" }),
|
||||
version: PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION,
|
||||
brushes: {
|
||||
"brush-legacy-room": {
|
||||
id: "brush-legacy-room",
|
||||
kind: "box",
|
||||
center: {
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.75
|
||||
},
|
||||
size: {
|
||||
x: 2.5,
|
||||
y: 3.25,
|
||||
z: 4.75
|
||||
},
|
||||
faces: {
|
||||
posX: { materialId: null, uv: createBoxBrush().faces.posX.uv },
|
||||
negX: { materialId: null, uv: createBoxBrush().faces.negX.uv },
|
||||
posY: { materialId: null, uv: createBoxBrush().faces.posY.uv },
|
||||
negY: { materialId: null, uv: createBoxBrush().faces.negY.uv },
|
||||
posZ: { materialId: null, uv: createBoxBrush().faces.posZ.uv },
|
||||
negZ: { materialId: null, uv: createBoxBrush().faces.negZ.uv }
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
expect(migratedDocument.version).toBe(SCENE_DOCUMENT_VERSION);
|
||||
expect(migratedDocument.brushes["brush-legacy-room"]).toMatchObject({
|
||||
center: {
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.75
|
||||
},
|
||||
size: {
|
||||
x: 2.5,
|
||||
y: 3.25,
|
||||
z: 4.75
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("migrates version 16 Player Start entities to include default collider settings", () => {
|
||||
const playerStart = {
|
||||
id: "entity-player-start-legacy-collider",
|
||||
kind: "playerStart" as const,
|
||||
position: {
|
||||
x: 1,
|
||||
y: 0,
|
||||
z: -3
|
||||
},
|
||||
yawDegrees: 45
|
||||
};
|
||||
const legacyDocument = {
|
||||
...createEmptySceneDocument({ name: "Legacy Player Collider Scene" }),
|
||||
version: IMPORTED_MODEL_COLLIDERS_SCENE_DOCUMENT_VERSION,
|
||||
entities: {
|
||||
[playerStart.id]: playerStart
|
||||
}
|
||||
};
|
||||
|
||||
const migratedDocument = migrateSceneDocument(legacyDocument);
|
||||
|
||||
expect(migratedDocument.version).toBe(SCENE_DOCUMENT_VERSION);
|
||||
expect(migratedDocument.entities[playerStart.id]).toEqual(
|
||||
createPlayerStartEntity({
|
||||
...playerStart
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("round-trips the initial typed entity registry without mixing entities into model instances", () => {
|
||||
const playerStart = createPlayerStartEntity({
|
||||
id: "entity-player-start-main"
|
||||
@@ -483,6 +706,64 @@ describe("scene document JSON", () => {
|
||||
expect(parseSceneDocumentJson(serializeSceneDocument(document))).toEqual(document);
|
||||
});
|
||||
|
||||
it("round-trips authored model-instance collision settings", () => {
|
||||
const asset = {
|
||||
id: "asset-model-collider",
|
||||
kind: "model",
|
||||
sourceName: "collision-test.glb",
|
||||
mimeType: "model/gltf-binary",
|
||||
storageKey: createProjectAssetStorageKey("asset-model-collider"),
|
||||
byteLength: 64,
|
||||
metadata: {
|
||||
kind: "model",
|
||||
format: "glb",
|
||||
sceneName: "Collision Test Scene",
|
||||
nodeCount: 1,
|
||||
meshCount: 1,
|
||||
materialNames: [],
|
||||
textureNames: [],
|
||||
animationNames: [],
|
||||
boundingBox: {
|
||||
min: {
|
||||
x: -1,
|
||||
y: 0,
|
||||
z: -1
|
||||
},
|
||||
max: {
|
||||
x: 1,
|
||||
y: 2,
|
||||
z: 1
|
||||
},
|
||||
size: {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 2
|
||||
}
|
||||
},
|
||||
warnings: []
|
||||
}
|
||||
} satisfies ModelAssetRecord;
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-collider",
|
||||
assetId: asset.id,
|
||||
collision: {
|
||||
mode: "dynamic",
|
||||
visible: true
|
||||
}
|
||||
});
|
||||
const document = {
|
||||
...createEmptySceneDocument({ name: "Model Collision Scene" }),
|
||||
assets: {
|
||||
[asset.id]: asset
|
||||
},
|
||||
modelInstances: {
|
||||
[modelInstance.id]: modelInstance
|
||||
}
|
||||
};
|
||||
|
||||
expect(parseSceneDocumentJson(serializeSceneDocument(document))).toEqual(document);
|
||||
});
|
||||
|
||||
it("round-trips canonical interaction links", () => {
|
||||
const triggerVolume = createTriggerVolumeEntity({
|
||||
id: "entity-trigger-main"
|
||||
|
||||
@@ -4,6 +4,10 @@ import {
|
||||
DEFAULT_POINT_LIGHT_COLOR_HEX,
|
||||
DEFAULT_POINT_LIGHT_DISTANCE,
|
||||
DEFAULT_POINT_LIGHT_INTENSITY,
|
||||
DEFAULT_PLAYER_START_BOX_SIZE,
|
||||
DEFAULT_PLAYER_START_CAPSULE_HEIGHT,
|
||||
DEFAULT_PLAYER_START_CAPSULE_RADIUS,
|
||||
DEFAULT_PLAYER_START_EYE_HEIGHT,
|
||||
DEFAULT_SPOT_LIGHT_ANGLE_DEGREES,
|
||||
DEFAULT_SPOT_LIGHT_COLOR_HEX,
|
||||
DEFAULT_SPOT_LIGHT_DISTANCE,
|
||||
@@ -27,7 +31,14 @@ describe("entity registry defaults", () => {
|
||||
expect(createDefaultEntityInstance("playerStart")).toMatchObject({
|
||||
kind: "playerStart",
|
||||
position: { x: 0, y: 0, z: 0 },
|
||||
yawDegrees: 0
|
||||
yawDegrees: 0,
|
||||
collider: {
|
||||
mode: "capsule",
|
||||
eyeHeight: DEFAULT_PLAYER_START_EYE_HEIGHT,
|
||||
capsuleRadius: DEFAULT_PLAYER_START_CAPSULE_RADIUS,
|
||||
capsuleHeight: DEFAULT_PLAYER_START_CAPSULE_HEIGHT,
|
||||
boxSize: DEFAULT_PLAYER_START_BOX_SIZE
|
||||
}
|
||||
});
|
||||
|
||||
expect(createDefaultEntityInstance("pointLight")).toMatchObject({
|
||||
|
||||
584
tests/unit/transform-foundation.integration.test.tsx
Normal file
584
tests/unit/transform-foundation.integration.test.tsx
Normal file
@@ -0,0 +1,584 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { App } from "../../src/app/App";
|
||||
import { createEditorStore } from "../../src/app/editor-store";
|
||||
import { createModelInstance } from "../../src/assets/model-instances";
|
||||
import { createProjectAssetStorageKey, type ModelAssetRecord } from "../../src/assets/project-assets";
|
||||
import type { ActiveTransformSession, TransformSessionState } from "../../src/core/transform-session";
|
||||
import { createBoxBrush } from "../../src/document/brushes";
|
||||
import { createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
import { createPlayerStartEntity } from "../../src/entities/entity-instances";
|
||||
|
||||
const { MockViewportHost, viewportHostInstances } = vi.hoisted(() => {
|
||||
const viewportHostInstances: Array<{
|
||||
panelId: string | null;
|
||||
setPanelId: ReturnType<typeof vi.fn>;
|
||||
mount: ReturnType<typeof vi.fn>;
|
||||
dispose: ReturnType<typeof vi.fn>;
|
||||
updateWorld: ReturnType<typeof vi.fn>;
|
||||
updateAssets: ReturnType<typeof vi.fn>;
|
||||
updateDocument: ReturnType<typeof vi.fn>;
|
||||
setViewMode: ReturnType<typeof vi.fn>;
|
||||
setDisplayMode: ReturnType<typeof vi.fn>;
|
||||
setCameraState: ReturnType<typeof vi.fn>;
|
||||
setBrushSelectionChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setCameraStateChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setCreationPreviewChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setCreationCommitHandler: ReturnType<typeof vi.fn>;
|
||||
setTransformSessionChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setTransformCommitHandler: ReturnType<typeof vi.fn>;
|
||||
setTransformCancelHandler: ReturnType<typeof vi.fn>;
|
||||
setWhiteboxHoverLabelChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setWhiteboxSelectionMode: ReturnType<typeof vi.fn>;
|
||||
setWhiteboxSnapSettings: ReturnType<typeof vi.fn>;
|
||||
setToolMode: ReturnType<typeof vi.fn>;
|
||||
setCreationPreview: ReturnType<typeof vi.fn>;
|
||||
setTransformSession: ReturnType<typeof vi.fn>;
|
||||
focusSelection: ReturnType<typeof vi.fn>;
|
||||
}> = [];
|
||||
|
||||
class MockViewportHost {
|
||||
panelId: string | null = null;
|
||||
setPanelId = vi.fn((panelId: string) => {
|
||||
this.panelId = panelId;
|
||||
});
|
||||
mount = vi.fn();
|
||||
dispose = vi.fn();
|
||||
updateWorld = vi.fn();
|
||||
updateAssets = vi.fn();
|
||||
updateDocument = vi.fn();
|
||||
setViewMode = vi.fn();
|
||||
setDisplayMode = vi.fn();
|
||||
setCameraState = vi.fn();
|
||||
setBrushSelectionChangeHandler = vi.fn();
|
||||
setCameraStateChangeHandler = vi.fn();
|
||||
setCreationPreviewChangeHandler = vi.fn();
|
||||
setCreationCommitHandler = vi.fn();
|
||||
setTransformSessionChangeHandler = vi.fn();
|
||||
setTransformCommitHandler = vi.fn();
|
||||
setTransformCancelHandler = vi.fn();
|
||||
setWhiteboxHoverLabelChangeHandler = vi.fn();
|
||||
setWhiteboxSelectionMode = vi.fn();
|
||||
setWhiteboxSnapSettings = vi.fn();
|
||||
setToolMode = vi.fn();
|
||||
setCreationPreview = vi.fn();
|
||||
setTransformSession = vi.fn();
|
||||
focusSelection = vi.fn();
|
||||
|
||||
constructor() {
|
||||
viewportHostInstances.push(this);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
MockViewportHost,
|
||||
viewportHostInstances
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../src/viewport-three/viewport-host", () => ({
|
||||
ViewportHost: MockViewportHost
|
||||
}));
|
||||
|
||||
vi.mock("../../src/assets/project-asset-storage", () => ({
|
||||
getBrowserProjectAssetStorageAccess: vi.fn(async () => ({
|
||||
storage: null,
|
||||
diagnostic: null
|
||||
}))
|
||||
}));
|
||||
|
||||
const modelAsset = {
|
||||
id: "asset-model-transform-integration",
|
||||
kind: "model",
|
||||
sourceName: "transform-fixture.glb",
|
||||
mimeType: "model/gltf-binary",
|
||||
storageKey: createProjectAssetStorageKey("asset-model-transform-integration"),
|
||||
byteLength: 64,
|
||||
metadata: {
|
||||
kind: "model",
|
||||
format: "glb",
|
||||
sceneName: "Transform Fixture",
|
||||
nodeCount: 1,
|
||||
meshCount: 1,
|
||||
materialNames: [],
|
||||
textureNames: [],
|
||||
animationNames: [],
|
||||
boundingBox: {
|
||||
min: {
|
||||
x: -0.5,
|
||||
y: 0,
|
||||
z: -0.5
|
||||
},
|
||||
max: {
|
||||
x: 0.5,
|
||||
y: 1,
|
||||
z: 0.5
|
||||
},
|
||||
size: {
|
||||
x: 1,
|
||||
y: 1,
|
||||
z: 1
|
||||
}
|
||||
},
|
||||
warnings: []
|
||||
}
|
||||
} satisfies ModelAssetRecord;
|
||||
|
||||
function getTopLeftViewportHost() {
|
||||
const viewportHost = viewportHostInstances.find((instance) => instance.panelId === "topLeft");
|
||||
|
||||
if (viewportHost === undefined) {
|
||||
throw new Error("Top-left viewport host was not mounted.");
|
||||
}
|
||||
|
||||
return viewportHost;
|
||||
}
|
||||
|
||||
async function renderTransformFixtureApp() {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-transform-main",
|
||||
name: "Brush Transform Fixture",
|
||||
center: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
}
|
||||
});
|
||||
const playerStart = createPlayerStartEntity({
|
||||
id: "entity-player-start-transform",
|
||||
name: "Player Start Fixture",
|
||||
position: {
|
||||
x: 2,
|
||||
y: 0,
|
||||
z: -2
|
||||
},
|
||||
yawDegrees: 0
|
||||
});
|
||||
const modelInstance = createModelInstance({
|
||||
id: "model-instance-transform-main",
|
||||
assetId: modelAsset.id,
|
||||
name: "Model Transform Fixture",
|
||||
position: {
|
||||
x: -3,
|
||||
y: 0,
|
||||
z: 3
|
||||
}
|
||||
});
|
||||
const store = createEditorStore({
|
||||
initialDocument: {
|
||||
...createEmptySceneDocument({ name: "Transform Fixture" }),
|
||||
brushes: {
|
||||
[brush.id]: brush
|
||||
},
|
||||
assets: {
|
||||
[modelAsset.id]: modelAsset
|
||||
},
|
||||
entities: {
|
||||
[playerStart.id]: playerStart
|
||||
},
|
||||
modelInstances: {
|
||||
[modelInstance.id]: modelInstance
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
render(<App store={store} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(viewportHostInstances.length).toBeGreaterThan(0);
|
||||
expect(getTopLeftViewportHost().setTransformCommitHandler).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
return {
|
||||
store,
|
||||
brush,
|
||||
playerStart,
|
||||
modelInstance,
|
||||
viewportHost: getTopLeftViewportHost()
|
||||
};
|
||||
}
|
||||
|
||||
async function renderQuadTransformFixtureApp() {
|
||||
const fixture = await renderTransformFixtureApp();
|
||||
|
||||
act(() => {
|
||||
fixture.store.setViewportLayoutMode("quad");
|
||||
});
|
||||
|
||||
return fixture;
|
||||
}
|
||||
|
||||
function getLatestTransformSession(store: ReturnType<typeof createEditorStore>): ActiveTransformSession {
|
||||
const transformSession = store.getState().viewportTransientState.transformSession;
|
||||
|
||||
if (transformSession.kind !== "active") {
|
||||
throw new Error("Expected an active transform session.");
|
||||
}
|
||||
|
||||
return transformSession;
|
||||
}
|
||||
|
||||
function emitTransformPreview(
|
||||
viewportHost: ReturnType<typeof getTopLeftViewportHost>,
|
||||
transformSession: ActiveTransformSession
|
||||
) {
|
||||
const handler = viewportHost.setTransformSessionChangeHandler.mock.calls.at(-1)?.[0] as ((transformSession: TransformSessionState) => void) | undefined;
|
||||
|
||||
if (handler === undefined) {
|
||||
throw new Error("Transform session change handler was not registered.");
|
||||
}
|
||||
|
||||
act(() => {
|
||||
handler(transformSession);
|
||||
});
|
||||
}
|
||||
|
||||
function commitTransform(viewportHost: ReturnType<typeof getTopLeftViewportHost>, transformSession: ActiveTransformSession) {
|
||||
const handler = viewportHost.setTransformCommitHandler.mock.calls.at(-1)?.[0] as ((transformSession: ActiveTransformSession) => void) | undefined;
|
||||
|
||||
if (handler === undefined) {
|
||||
throw new Error("Transform commit handler was not registered.");
|
||||
}
|
||||
|
||||
act(() => {
|
||||
handler(transformSession);
|
||||
});
|
||||
}
|
||||
|
||||
describe("transform foundation integration", () => {
|
||||
beforeEach(() => {
|
||||
viewportHostInstances.length = 0;
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => ({}) as never);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("moves a whole brush through keyboard entry, axis constraint, and viewport commit", async () => {
|
||||
const { store, brush, viewportHost } = await renderTransformFixtureApp();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Brush Transform Fixture$/ }));
|
||||
});
|
||||
|
||||
fireEvent.keyDown(window, {
|
||||
key: "g",
|
||||
code: "KeyG"
|
||||
});
|
||||
|
||||
expect(store.getState().viewportTransientState.transformSession).toMatchObject({
|
||||
kind: "active",
|
||||
operation: "translate",
|
||||
axisConstraint: null,
|
||||
target: {
|
||||
kind: "brush",
|
||||
brushId: brush.id
|
||||
}
|
||||
});
|
||||
|
||||
fireEvent.keyDown(window, {
|
||||
key: "x",
|
||||
code: "KeyX"
|
||||
});
|
||||
|
||||
expect(store.getState().viewportTransientState.transformSession).toMatchObject({
|
||||
kind: "active",
|
||||
axisConstraint: "x"
|
||||
});
|
||||
|
||||
const previewSession = {
|
||||
...getLatestTransformSession(store),
|
||||
preview: {
|
||||
kind: "brush" as const,
|
||||
center: {
|
||||
x: 6,
|
||||
y: brush.center.y,
|
||||
z: brush.center.z
|
||||
},
|
||||
rotationDegrees: {
|
||||
...brush.rotationDegrees
|
||||
},
|
||||
size: {
|
||||
...brush.size
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
emitTransformPreview(viewportHost, previewSession);
|
||||
commitTransform(viewportHost, previewSession);
|
||||
|
||||
expect(store.getState().viewportTransientState.transformSession).toEqual({
|
||||
kind: "none"
|
||||
});
|
||||
expect(store.getState().document.brushes[brush.id].center).toEqual({
|
||||
x: 6,
|
||||
y: brush.center.y,
|
||||
z: brush.center.z
|
||||
});
|
||||
});
|
||||
|
||||
it("rotates and scales a whole whitebox box through the shared transform controller", async () => {
|
||||
const { store, brush, viewportHost } = await renderTransformFixtureApp();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Brush Transform Fixture$/ }));
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByTestId("transform-rotate-button"));
|
||||
|
||||
const rotatePreviewSession = {
|
||||
...getLatestTransformSession(store),
|
||||
preview: {
|
||||
kind: "brush" as const,
|
||||
center: {
|
||||
...brush.center
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
},
|
||||
size: {
|
||||
...brush.size
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
emitTransformPreview(viewportHost, rotatePreviewSession);
|
||||
commitTransform(viewportHost, rotatePreviewSession);
|
||||
|
||||
expect(store.getState().document.brushes[brush.id].rotationDegrees).toEqual({
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByTestId("transform-scale-button"));
|
||||
|
||||
const scalePreviewSession = {
|
||||
...getLatestTransformSession(store),
|
||||
preview: {
|
||||
kind: "brush" as const,
|
||||
center: {
|
||||
...brush.center
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
},
|
||||
size: {
|
||||
x: 3.5,
|
||||
y: 2.5,
|
||||
z: 4.5
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
emitTransformPreview(viewportHost, scalePreviewSession);
|
||||
commitTransform(viewportHost, scalePreviewSession);
|
||||
|
||||
expect(store.getState().document.brushes[brush.id]).toMatchObject({
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 37.5,
|
||||
z: 12.5
|
||||
},
|
||||
size: {
|
||||
x: 3.5,
|
||||
y: 2.5,
|
||||
z: 4.5
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps whole-box transforms in Object mode and disables them in component modes", async () => {
|
||||
const { store, brush } = await renderTransformFixtureApp();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Brush Transform Fixture$/ }));
|
||||
});
|
||||
|
||||
expect(screen.getByTestId("transform-translate-button")).not.toBeDisabled();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByTestId("whitebox-selection-mode-face"));
|
||||
});
|
||||
|
||||
expect(store.getState().whiteboxSelectionMode).toBe("face");
|
||||
expect(screen.getByTestId("transform-translate-button")).toBeDisabled();
|
||||
|
||||
act(() => {
|
||||
store.setSelection({
|
||||
kind: "brushFace",
|
||||
brushId: brush.id,
|
||||
faceId: "posY"
|
||||
});
|
||||
});
|
||||
|
||||
expect(screen.getByTestId("transform-translate-button")).toBeDisabled();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByTestId("whitebox-selection-mode-object"));
|
||||
});
|
||||
|
||||
expect(store.getState().whiteboxSelectionMode).toBe("object");
|
||||
expect(store.getState().selection).toEqual({
|
||||
kind: "brushes",
|
||||
ids: [brush.id]
|
||||
});
|
||||
expect(screen.getByTestId("transform-translate-button")).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it("moves an entity through the shared transform controller", async () => {
|
||||
const { store, playerStart, viewportHost } = await renderTransformFixtureApp();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Player Start Fixture$/ }));
|
||||
});
|
||||
|
||||
fireEvent.keyDown(window, {
|
||||
key: "g",
|
||||
code: "KeyG"
|
||||
});
|
||||
|
||||
const previewSession = {
|
||||
...getLatestTransformSession(store),
|
||||
preview: {
|
||||
kind: "entity" as const,
|
||||
position: {
|
||||
x: 8,
|
||||
y: 0,
|
||||
z: -4
|
||||
},
|
||||
rotation: {
|
||||
kind: "yaw" as const,
|
||||
yawDegrees: playerStart.yawDegrees
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
emitTransformPreview(viewportHost, previewSession);
|
||||
commitTransform(viewportHost, previewSession);
|
||||
|
||||
expect(store.getState().document.entities[playerStart.id]).toMatchObject({
|
||||
position: {
|
||||
x: 8,
|
||||
y: 0,
|
||||
z: -4
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels an active transform with Escape without committing preview changes", async () => {
|
||||
const { store, playerStart, viewportHost } = await renderTransformFixtureApp();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Player Start Fixture$/ }));
|
||||
});
|
||||
|
||||
fireEvent.keyDown(window, {
|
||||
key: "g",
|
||||
code: "KeyG"
|
||||
});
|
||||
|
||||
emitTransformPreview(viewportHost, {
|
||||
...getLatestTransformSession(store),
|
||||
preview: {
|
||||
kind: "entity",
|
||||
position: {
|
||||
x: 12,
|
||||
y: 0,
|
||||
z: -6
|
||||
},
|
||||
rotation: {
|
||||
kind: "yaw",
|
||||
yawDegrees: playerStart.yawDegrees
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
fireEvent.keyDown(window, {
|
||||
key: "Escape",
|
||||
code: "Escape"
|
||||
});
|
||||
|
||||
expect(store.getState().viewportTransientState.transformSession).toEqual({
|
||||
kind: "none"
|
||||
});
|
||||
expect(store.getState().document.entities[playerStart.id]).toEqual(playerStart);
|
||||
});
|
||||
|
||||
it("moves a model instance through the shared transform controller", async () => {
|
||||
const { store, modelInstance, viewportHost } = await renderTransformFixtureApp();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Model Transform Fixture$/ }));
|
||||
});
|
||||
|
||||
fireEvent.keyDown(window, {
|
||||
key: "g",
|
||||
code: "KeyG"
|
||||
});
|
||||
|
||||
const previewSession = {
|
||||
...getLatestTransformSession(store),
|
||||
preview: {
|
||||
kind: "modelInstance" as const,
|
||||
position: {
|
||||
x: -1,
|
||||
y: 0,
|
||||
z: 7
|
||||
},
|
||||
rotationDegrees: {
|
||||
...modelInstance.rotationDegrees
|
||||
},
|
||||
scale: {
|
||||
...modelInstance.scale
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
emitTransformPreview(viewportHost, previewSession);
|
||||
commitTransform(viewportHost, previewSession);
|
||||
|
||||
expect(store.getState().document.modelInstances[modelInstance.id]).toMatchObject({
|
||||
position: {
|
||||
x: -1,
|
||||
y: 0,
|
||||
z: 7
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the hovered quad viewport as the active transform panel for keyboard entry", async () => {
|
||||
const { store, brush } = await renderQuadTransformFixtureApp();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Brush Transform Fixture$/ }));
|
||||
});
|
||||
|
||||
fireEvent.pointerMove(screen.getByTestId("viewport-panel-bottomRight"), {
|
||||
clientX: 24,
|
||||
clientY: 24
|
||||
});
|
||||
fireEvent.keyDown(window, {
|
||||
key: "g",
|
||||
code: "KeyG"
|
||||
});
|
||||
|
||||
expect(store.getState().activeViewportPanelId).toBe("bottomRight");
|
||||
expect(store.getState().viewportTransientState.transformSession).toMatchObject({
|
||||
kind: "active",
|
||||
operation: "translate",
|
||||
sourcePanelId: "bottomRight",
|
||||
target: {
|
||||
kind: "brush",
|
||||
brushId: brush.id
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
194
tests/unit/viewport-canvas.test.tsx
Normal file
194
tests/unit/viewport-canvas.test.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createInactiveTransformSession, type ActiveTransformSession, type TransformSessionState } from "../../src/core/transform-session";
|
||||
import { createEmptySceneDocument } from "../../src/document/scene-document";
|
||||
import { ViewportCanvas } from "../../src/viewport-three/ViewportCanvas";
|
||||
import { createDefaultViewportPanelCameraState, type ViewportPanelCameraState } from "../../src/viewport-three/viewport-layout";
|
||||
import type { CreationViewportToolPreview, ViewportToolPreview } from "../../src/viewport-three/viewport-transient-state";
|
||||
|
||||
const { MockViewportHost, viewportHostInstances } = vi.hoisted(() => {
|
||||
const viewportHostInstances: Array<{
|
||||
mount: ReturnType<typeof vi.fn>;
|
||||
dispose: ReturnType<typeof vi.fn>;
|
||||
updateWorld: ReturnType<typeof vi.fn>;
|
||||
updateAssets: ReturnType<typeof vi.fn>;
|
||||
updateDocument: ReturnType<typeof vi.fn>;
|
||||
setViewMode: ReturnType<typeof vi.fn>;
|
||||
setDisplayMode: ReturnType<typeof vi.fn>;
|
||||
setCameraState: ReturnType<typeof vi.fn>;
|
||||
setBrushSelectionChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setCameraStateChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setCreationPreviewChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setCreationCommitHandler: ReturnType<typeof vi.fn>;
|
||||
setTransformSessionChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setTransformCommitHandler: ReturnType<typeof vi.fn>;
|
||||
setTransformCancelHandler: ReturnType<typeof vi.fn>;
|
||||
setWhiteboxHoverLabelChangeHandler: ReturnType<typeof vi.fn>;
|
||||
setWhiteboxSelectionMode: ReturnType<typeof vi.fn>;
|
||||
setWhiteboxSnapSettings: ReturnType<typeof vi.fn>;
|
||||
setToolMode: ReturnType<typeof vi.fn>;
|
||||
setCreationPreview: ReturnType<typeof vi.fn>;
|
||||
setTransformSession: ReturnType<typeof vi.fn>;
|
||||
setPanelId: ReturnType<typeof vi.fn>;
|
||||
focusSelection: ReturnType<typeof vi.fn>;
|
||||
}> = [];
|
||||
|
||||
class MockViewportHost {
|
||||
mount = vi.fn();
|
||||
dispose = vi.fn();
|
||||
updateWorld = vi.fn();
|
||||
updateAssets = vi.fn();
|
||||
updateDocument = vi.fn();
|
||||
setViewMode = vi.fn();
|
||||
setDisplayMode = vi.fn();
|
||||
setCameraState = vi.fn();
|
||||
setBrushSelectionChangeHandler = vi.fn();
|
||||
setCameraStateChangeHandler = vi.fn();
|
||||
setCreationPreviewChangeHandler = vi.fn();
|
||||
setCreationCommitHandler = vi.fn();
|
||||
setTransformSessionChangeHandler = vi.fn();
|
||||
setTransformCommitHandler = vi.fn();
|
||||
setTransformCancelHandler = vi.fn();
|
||||
setWhiteboxHoverLabelChangeHandler = vi.fn();
|
||||
setWhiteboxSelectionMode = vi.fn();
|
||||
setWhiteboxSnapSettings = vi.fn();
|
||||
setToolMode = vi.fn();
|
||||
setCreationPreview = vi.fn();
|
||||
setTransformSession = vi.fn();
|
||||
setPanelId = vi.fn();
|
||||
focusSelection = vi.fn();
|
||||
|
||||
constructor() {
|
||||
viewportHostInstances.push(this);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
MockViewportHost,
|
||||
viewportHostInstances
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../src/viewport-three/viewport-host", () => ({
|
||||
ViewportHost: MockViewportHost
|
||||
}));
|
||||
|
||||
describe("ViewportCanvas", () => {
|
||||
beforeEach(() => {
|
||||
viewportHostInstances.length = 0;
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => ({}) as never);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("wires the creation commit handler into the viewport host", async () => {
|
||||
const sceneDocument = createEmptySceneDocument();
|
||||
const cameraState = createDefaultViewportPanelCameraState();
|
||||
const toolPreview: CreationViewportToolPreview = {
|
||||
kind: "create",
|
||||
sourcePanelId: "topLeft",
|
||||
target: {
|
||||
kind: "box-brush"
|
||||
},
|
||||
center: null
|
||||
};
|
||||
const onCommitCreation = vi.fn(() => true);
|
||||
const onCameraStateChange = vi.fn((_cameraState: ViewportPanelCameraState) => undefined);
|
||||
const onToolPreviewChange = vi.fn((_toolPreview: ViewportToolPreview) => undefined);
|
||||
const onTransformSessionChange = vi.fn((_transformSession: TransformSessionState) => undefined);
|
||||
const onTransformCommit = vi.fn((_transformSession: ActiveTransformSession) => undefined);
|
||||
const onTransformCancel = vi.fn(() => undefined);
|
||||
const onSelectionChange = vi.fn();
|
||||
|
||||
render(
|
||||
<ViewportCanvas
|
||||
panelId="topLeft"
|
||||
world={sceneDocument.world}
|
||||
sceneDocument={sceneDocument}
|
||||
projectAssets={sceneDocument.assets}
|
||||
loadedModelAssets={{}}
|
||||
loadedImageAssets={{}}
|
||||
whiteboxSelectionMode="object"
|
||||
whiteboxSnapEnabled
|
||||
whiteboxSnapStep={1}
|
||||
selection={{ kind: "none" }}
|
||||
toolMode="create"
|
||||
toolPreview={toolPreview}
|
||||
transformSession={createInactiveTransformSession()}
|
||||
cameraState={cameraState}
|
||||
viewMode="perspective"
|
||||
displayMode="authoring"
|
||||
layoutMode="single"
|
||||
isActivePanel
|
||||
focusRequestId={0}
|
||||
focusSelection={{ kind: "none" }}
|
||||
onSelectionChange={onSelectionChange}
|
||||
onCommitCreation={onCommitCreation}
|
||||
onCameraStateChange={onCameraStateChange}
|
||||
onToolPreviewChange={onToolPreviewChange}
|
||||
onTransformSessionChange={onTransformSessionChange}
|
||||
onTransformCommit={onTransformCommit}
|
||||
onTransformCancel={onTransformCancel}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(viewportHostInstances).toHaveLength(1);
|
||||
expect(viewportHostInstances[0].setCreationCommitHandler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const registeredHandler = viewportHostInstances[0].setCreationCommitHandler.mock.calls[0][0] as (
|
||||
toolPreview: CreationViewportToolPreview
|
||||
) => boolean;
|
||||
|
||||
expect(registeredHandler(toolPreview)).toBe(true);
|
||||
expect(onCommitCreation).toHaveBeenCalledWith(toolPreview);
|
||||
});
|
||||
|
||||
it("applies and subscribes to persisted camera state through the viewport host", async () => {
|
||||
const sceneDocument = createEmptySceneDocument();
|
||||
const cameraState = createDefaultViewportPanelCameraState();
|
||||
const onCameraStateChange = vi.fn((_cameraState: ViewportPanelCameraState) => undefined);
|
||||
|
||||
render(
|
||||
<ViewportCanvas
|
||||
panelId="topLeft"
|
||||
world={sceneDocument.world}
|
||||
sceneDocument={sceneDocument}
|
||||
projectAssets={sceneDocument.assets}
|
||||
loadedModelAssets={{}}
|
||||
loadedImageAssets={{}}
|
||||
whiteboxSelectionMode="object"
|
||||
whiteboxSnapEnabled
|
||||
whiteboxSnapStep={1}
|
||||
selection={{ kind: "none" }}
|
||||
toolMode="select"
|
||||
toolPreview={{ kind: "none" }}
|
||||
transformSession={createInactiveTransformSession()}
|
||||
cameraState={cameraState}
|
||||
viewMode="perspective"
|
||||
displayMode="normal"
|
||||
layoutMode="single"
|
||||
isActivePanel
|
||||
focusRequestId={0}
|
||||
focusSelection={{ kind: "none" }}
|
||||
onSelectionChange={vi.fn()}
|
||||
onCommitCreation={vi.fn(() => true)}
|
||||
onCameraStateChange={onCameraStateChange}
|
||||
onToolPreviewChange={vi.fn()}
|
||||
onTransformSessionChange={vi.fn()}
|
||||
onTransformCommit={vi.fn()}
|
||||
onTransformCancel={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(viewportHostInstances).toHaveLength(1);
|
||||
expect(viewportHostInstances[0].setCameraState).toHaveBeenCalledWith(cameraState);
|
||||
expect(viewportHostInstances[0].setCameraStateChangeHandler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -42,6 +42,47 @@ describe("resolveViewportFocusTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("frames rotated whitebox boxes around their authored center with a stable object radius", () => {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-rotated-room",
|
||||
center: {
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.75
|
||||
},
|
||||
rotationDegrees: {
|
||||
x: 0,
|
||||
y: 45,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 4
|
||||
}
|
||||
});
|
||||
const document = {
|
||||
...createEmptySceneDocument(),
|
||||
brushes: {
|
||||
[brush.id]: brush
|
||||
}
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveViewportFocusTarget(document, {
|
||||
kind: "brushes",
|
||||
ids: [brush.id]
|
||||
})
|
||||
).toEqual({
|
||||
center: {
|
||||
x: 1.25,
|
||||
y: 1.5,
|
||||
z: -0.75
|
||||
},
|
||||
radius: Math.hypot(2, 2, 4) * 0.5
|
||||
});
|
||||
});
|
||||
|
||||
it("frames the owning brush when a face is selected", () => {
|
||||
const brush = createBoxBrush({
|
||||
id: "brush-face-room"
|
||||
|
||||
45
tests/unit/viewport-layout.test.ts
Normal file
45
tests/unit/viewport-layout.test.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createDefaultViewportLayoutState,
|
||||
getViewportDisplayModeLabel,
|
||||
getViewportLayoutModeLabel,
|
||||
getViewportPanelLabel
|
||||
} from "../../src/viewport-three/viewport-layout";
|
||||
|
||||
describe("viewport layout", () => {
|
||||
it("defaults to a quad-ready panel arrangement with orthographic authoring panes", () => {
|
||||
const layout = createDefaultViewportLayoutState();
|
||||
|
||||
expect(layout.layoutMode).toBe("single");
|
||||
expect(layout.activePanelId).toBe("topLeft");
|
||||
expect(layout.panels.topLeft).toMatchObject({
|
||||
viewMode: "perspective",
|
||||
displayMode: "normal"
|
||||
});
|
||||
expect(layout.panels.topRight).toMatchObject({
|
||||
viewMode: "top",
|
||||
displayMode: "authoring"
|
||||
});
|
||||
expect(layout.panels.bottomLeft).toMatchObject({
|
||||
viewMode: "front",
|
||||
displayMode: "authoring"
|
||||
});
|
||||
expect(layout.panels.bottomRight).toMatchObject({
|
||||
viewMode: "side",
|
||||
displayMode: "authoring"
|
||||
});
|
||||
expect(layout.viewportQuadSplit).toEqual({
|
||||
x: 0.5,
|
||||
y: 0.5
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes readable labels for the layout and panel chrome", () => {
|
||||
expect(getViewportLayoutModeLabel("single")).toBe("Single View");
|
||||
expect(getViewportLayoutModeLabel("quad")).toBe("4-Panel");
|
||||
expect(getViewportDisplayModeLabel("authoring")).toBe("Authoring");
|
||||
expect(getViewportDisplayModeLabel("wireframe")).toBe("Wireframe");
|
||||
expect(getViewportPanelLabel("topRight")).toBe("Top Right");
|
||||
});
|
||||
});
|
||||
71
tests/unit/viewport-view-modes.test.ts
Normal file
71
tests/unit/viewport-view-modes.test.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getViewportViewModeControlHint,
|
||||
getViewportViewModeDefinition,
|
||||
getViewportViewModeGridPlaneLabel,
|
||||
getViewportViewModeLabel
|
||||
} from "../../src/viewport-three/viewport-view-modes";
|
||||
|
||||
describe("viewport view modes", () => {
|
||||
it("defines the orthographic axes and grid planes explicitly", () => {
|
||||
expect(getViewportViewModeDefinition("top")).toMatchObject({
|
||||
label: "Top",
|
||||
cameraType: "orthographic",
|
||||
cameraDirection: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
cameraUp: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: -1
|
||||
},
|
||||
gridPlane: "xz",
|
||||
snapAxis: "y"
|
||||
});
|
||||
|
||||
expect(getViewportViewModeDefinition("front")).toMatchObject({
|
||||
label: "Front",
|
||||
cameraType: "orthographic",
|
||||
cameraDirection: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 1
|
||||
},
|
||||
cameraUp: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
gridPlane: "xy",
|
||||
snapAxis: "z"
|
||||
});
|
||||
|
||||
expect(getViewportViewModeDefinition("side")).toMatchObject({
|
||||
label: "Side",
|
||||
cameraType: "orthographic",
|
||||
cameraDirection: {
|
||||
x: -1,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
cameraUp: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
},
|
||||
gridPlane: "yz",
|
||||
snapAxis: "x"
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes readable labels and grid hints for the UI", () => {
|
||||
expect(getViewportViewModeLabel("perspective")).toBe("Perspective");
|
||||
expect(getViewportViewModeLabel("top")).toBe("Top");
|
||||
expect(getViewportViewModeGridPlaneLabel("front")).toBe("XY");
|
||||
expect(getViewportViewModeControlHint("perspective")).toContain("orbits");
|
||||
expect(getViewportViewModeControlHint("side")).toContain("pans");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user