Compare commits

...

592 Commits

Author SHA1 Message Date
d9b6b3e7fc Add name and loadingScreen to ProjectDocument and ProjectScene interfaces in architecture.md 2026-04-11 13:30:07 +02:00
abda1bd1dd Update local draft storage to handle scene documents 2026-04-11 13:28:15 +02:00
811b51bd6a Update tests for project document serialization and add project name handling 2026-04-11 13:26:59 +02:00
8506b235db Add flex-wrap to toolbar elements and project name styling 2026-04-11 13:26:59 +02:00
cd11a779c5 Update App to include project name functionality 2026-04-11 13:26:09 +02:00
ace59ce8a0 Add set project name command 2026-04-11 13:26:09 +02:00
b3ff49d38c Add project name validation and default value in document migration 2026-04-11 13:25:29 +02:00
88047649f9 Update SceneDocument version and add project name field 2026-04-11 13:25:22 +02:00
b63071e815 Update test for scene document JSON migration of player start entity 2026-04-11 12:44:28 +02:00
747669aef5 Refactor scene document JSON tests for better structure and floating-point precision 2026-04-11 12:43:13 +02:00
920b9555a1 Refactor scene document JSON tests and update player start entity handling 2026-04-11 12:38:53 +02:00
7dbb287dd6 Update type definitions and function signatures in migrate-scene-document.ts 2026-04-11 12:38:43 +02:00
203afa9079 Add new scene document version for player start input bindings 2026-04-11 12:38:20 +02:00
fb0ae99bf5 Update version check in migrateSceneDocument function 2026-04-11 12:35:27 +02:00
c4e8410b20 Remove unused import in migrate-scene-document.ts 2026-04-11 12:35:27 +02:00
0f0bfc853d Update scene document JSON tests for input bindings and migration 2026-04-11 12:34:09 +02:00
eabc9ab294 Add gamepad support for third-person camera orbit in tests 2026-04-11 12:33:54 +02:00
a89a9ba58d Add test for camera look using gamepad right stick without pointer lock 2026-04-11 12:33:43 +02:00
478baed1b6 Update App.tsx to support gamepad camera look bindings 2026-04-11 12:33:01 +02:00
7aaebe9ee8 Add validation for player start gamepad camera look binding 2026-04-11 12:31:34 +02:00
99482236d1 Add support for player start gamepad camera look binding 2026-04-11 12:31:30 +02:00
d823fa5a39 Bump scene document version and add new constant 2026-04-11 12:31:30 +02:00
324c10bdc0 Update third-person navigation controller to include gamepad look input 2026-04-11 12:30:42 +02:00
0bd2a8ad22 Add gamepad support for camera look in first-person navigation controller 2026-04-11 12:30:33 +02:00
4e7549bb5a Add camera look input handling for gamepads 2026-04-11 12:30:19 +02:00
bf5c87f86d Simplify keyboard binding type and add camera look bindings 2026-04-11 12:30:11 +02:00
9355531c0c Update third-person-navigation-controller.test.ts with new imports and resolved player motion type 2026-04-11 12:20:03 +02:00
26e86baf98 Update FirstPersonNavigationController context and resolveFirstPersonMotion type 2026-04-11 12:19:59 +02:00
5e1b865f56 Include player input bindings in scene document validation test 2026-04-11 12:19:59 +02:00
0dafb0974b Update import statement for createPlayerStartInputBindings 2026-04-11 12:19:59 +02:00
c9c46ed7d7 Add player input bindings to runtime scene fixture 2026-04-11 12:19:59 +02:00
8da57eddab Add PlayerStartInputBindingOverrides interface and update createPlayerStartEntity function 2026-04-11 12:19:11 +02:00
fc2e0818f4 Include inputBindings in buildRuntimeSceneFromDocument test 2026-04-11 12:18:25 +02:00
8e335a5c42 Add PLAYER_START_NAVIGATION_MODE_SCENE_DOCUMENT_VERSION check in migrate-scene-document.ts 2026-04-11 12:18:25 +02:00
a4b9bf0dbb Update architecture.md with new movement mode requirements 2026-04-11 12:18:25 +02:00
f5408ee8a9 Fix moveLeft binding in entity-instances.ts 2026-04-11 12:18:25 +02:00
89caa179f2 Add migration test for Player Start entities with default input bindings 2026-04-11 12:17:09 +02:00
6b1bb90062 Update build-runtime-scene.test.ts to include input bindings 2026-04-11 12:17:09 +02:00
4d682eed17 Add unit test for ThirdPersonNavigationController 2026-04-11 12:17:09 +02:00
c3b156040d Add mock gamepad and update tests for FirstPersonNavigationController 2026-04-11 12:16:14 +02:00
190c696319 Add input bindings configuration for player start entity 2026-04-11 12:15:31 +02:00
ec1f04e5cc Add validation for player start input bindings in scene-document-validation.ts 2026-04-11 12:14:05 +02:00
bdae77bf80 Add input binding reading functions and update player start entity 2026-04-11 12:13:55 +02:00
04544a0e7c Update third-person navigation controller to use player input bindings 2026-04-11 12:13:24 +02:00
156ded4774 Update first-person navigation controller to use new input bindings 2026-04-11 12:13:19 +02:00
3b2e3326e8 Add player input bindings for gamepad and keyboard 2026-04-11 12:13:19 +02:00
119ca52b75 Update scene document version and add input bindings support 2026-04-11 12:12:55 +02:00
67738884ec Add input bindings to PlayerStartEntity 2026-04-11 12:12:48 +02:00
1dddeaf0b8 Remove unused state and function in App component 2026-04-11 12:01:46 +02:00
db8ef092a4 Add navigation mode to player start entity creation 2026-04-11 11:54:51 +02:00
d448063dd7 Extend applyPlayerStartChange to include navigationMode override 2026-04-11 11:53:26 +02:00
0b148b404b Update tests to select player start navigation mode 2026-04-11 11:45:57 +02:00
279084c7be Update interaction prompt handling and UI text in multiple components 2026-04-11 11:41:58 +02:00
43e9e7baa0 Simplify interaction prompt display and handling in various components 2026-04-11 11:40:25 +02:00
9026a34c72 Change invalid navigation mode in test case 2026-04-11 11:24:48 +02:00
b9bed17a2f Add third-person camera collision resolution in tests 2026-04-11 11:22:23 +02:00
499fbcfec8 Update documentation for third-person mode 2026-04-11 11:22:23 +02:00
c81c40f8ea Modify RunnerCanvas test to check third-person mode HUD 2026-04-11 11:21:45 +02:00
04d7cbde08 Update e2e test to include third-person navigation 2026-04-11 11:21:45 +02:00
9d3317066b Add unit test for RapierCollisionWorld 2026-04-11 11:21:45 +02:00
3afa71396b Add test for authored Player Start navigation mode in third-person scenes 2026-04-11 11:20:34 +02:00
0187d832b7 Update test for invalid navigation mode in scene document validation 2026-04-11 11:20:34 +02:00
af4c10130d Add test for round-tripping authored third-person Player Start navigation 2026-04-11 11:20:19 +02:00
c1c79b5dc6 Add test for migrating Player Start entities to default to first-person navigation 2026-04-11 11:20:11 +02:00
2113dffac0 Include navigationMode in build-runtime-scene tests 2026-04-11 11:20:03 +02:00
d36b40c333 Add navigationMode to entity-instances test data 2026-04-11 11:20:03 +02:00
1576282819 Update types and formatting in first-person-navigation-controller.test.ts 2026-04-11 11:20:03 +02:00
9b8aa3a00b Update tests for thirdPerson navigation mode 2026-04-11 11:19:08 +02:00
bf3e405a4f Remove orbit-visitor-navigation-controller 2026-04-11 11:18:59 +02:00
bafee9809d Enhance player start navigation mode type checking 2026-04-11 11:18:59 +02:00
7470b4472a Update RunnerCanvas to set navigation mode and load scene 2026-04-11 11:18:59 +02:00
337a2c08b8 Add navigation mode selection to App component 2026-04-11 11:17:52 +02:00
e7f32a36f6 Remove navigation mode buttons from toolbar 2026-04-11 11:17:46 +02:00
b563223c4c Remove first person and orbit visitor buttons, update active mode display 2026-04-11 11:17:42 +02:00
90f1c4c09d Add navigationMode to player start 2026-04-11 11:17:42 +02:00
0a58329c88 Remove preferred navigation mode logic, update status messages 2026-04-11 11:17:23 +02:00
4f35f2c06c Update active navigation mode on runtime scene change 2026-04-11 11:17:23 +02:00
414b1951c6 Add player start navigation mode draft handling 2026-04-11 11:17:23 +02:00
075a5de9b9 Update player start navigation mode handling and validation 2026-04-11 11:17:02 +02:00
46cac5435f Add default player start navigation mode and type 2026-04-11 11:17:02 +02:00
5cf600e601 Refactor interaction prompt logic in runtime-host.ts 2026-04-11 11:16:40 +02:00
650d3271c1 Add third-person camera collision resolution and update controller handling 2026-04-11 11:16:34 +02:00
96754dfcf6 Switch default navigation mode to third person and update imports 2026-04-11 11:16:29 +02:00
072bbdfcb6 Update first-person navigation controller messages 2026-04-11 11:16:29 +02:00
9a48f514c2 Add third-person navigation controller 2026-04-11 11:16:29 +02:00
74654c9c98 Add camera collision resolution in RapierCollisionWorld 2026-04-11 11:15:03 +02:00
e571b758f1 auto-git:
[change] src/runtime-three/navigation-controller.ts
2026-04-11 11:14:57 +02:00
aa812c4829 auto-git:
[change] src/runtime-three/runtime-scene-validation.ts
2026-04-11 11:14:57 +02:00
ef628d90be auto-git:
[change] src/runtime-three/runtime-scene-build.ts
2026-04-11 11:14:57 +02:00
007447d60b Add third-person navigation mode and update runtime scene definition 2026-04-11 11:14:42 +02:00
c9fd7bcd62 Validate player start navigation mode 2026-04-11 11:14:34 +02:00
e2ec75aadc Include new scene document version in project migration 2026-04-11 11:14:34 +02:00
2422374fc4 Update scene document version check 2026-04-11 11:14:34 +02:00
d6f2d6b68a Add navigation mode to player start entity 2026-04-11 11:14:34 +02:00
07fbdd05ed Add function to read player start navigation mode 2026-04-11 11:14:09 +02:00
d968bd2ed2 Update scene document version and add player start navigation mode 2026-04-11 11:14:09 +02:00
6c8d7b506e Add navigation mode to PlayerStartEntity 2026-04-11 11:14:02 +02:00
27a948e4ab Refactor pointer lock handling in tests 2026-04-11 05:17:29 +02:00
75d8723565 Add tests and update navigation controller deactivation logic 2026-04-11 05:17:01 +02:00
5dbd68e0ce Implement options parameter in FirstPersonNavigationController deactivate method 2026-04-11 05:16:52 +02:00
6f329ed1c1 Add options parameter to NavigationController deactivate method 2026-04-11 05:16:52 +02:00
1960cf97ab Refactor test setup for RunnerCanvas component 2026-04-11 04:57:05 +02:00
c892aa0f6c Add test for runtime host recreation logic 2026-04-11 04:57:01 +02:00
d666295bc9 Reorganize scene exit handler setup in RunnerCanvas 2026-04-11 04:57:01 +02:00
50977af4e0 Add integration test for app scene transition 2026-04-11 04:42:52 +02:00
e01eb777b7 Fix JSON serialization in project document test 2026-04-11 04:42:52 +02:00
61d3bef338 Add test for Scene Exit target validation in project-document-json.test.ts 2026-04-11 04:41:32 +02:00
9d0a3a6481 Remove unused import in project-document-json.test.ts 2026-04-11 04:41:32 +02:00
910f9c2ad3 Update test to reflect migration of v23 project documents without Scene Entry and Scene Exit entities 2026-04-11 04:40:37 +02:00
08b91ae553 Update project document JSON tests for scene entry and exit entities 2026-04-11 04:40:33 +02:00
d4f2e1a171 Add setSceneExitHandler and onSceneExitActivated to RunnerCanvas tests 2026-04-11 04:40:33 +02:00
58c5428c2b Add Scene Entry and Exit Entities to Build Runtime Scene Tests 2026-04-11 04:40:11 +02:00
f3c715033e Update tests for Scene Exit entities and interactions 2026-04-11 04:39:54 +02:00
8d459c9791 Add sceneEntry and sceneExit to entity rotation resolution 2026-04-11 04:39:54 +02:00
c6ef980604 Support scene entry and scene exit in transform session command 2026-04-11 04:39:27 +02:00
8250d53078 Update interaction prompt to include Scene Exit 2026-04-11 04:39:27 +02:00
2cfa8eedc3 Add check for scene exit destination before creation 2026-04-11 04:39:27 +02:00
491b96223c Add scene exit configuration options in App.tsx 2026-04-11 04:38:08 +02:00
5f01ff050a Add Yaw input field for selected scene entry in App.tsx 2026-04-11 04:37:45 +02:00
df091c201f Enhance RunnerCanvas component with additional props and UI elements 2026-04-11 04:37:37 +02:00
51b4ac6cdf Update scene handling logic in App.tsx 2026-04-11 04:37:23 +02:00
72301ef4bd Add Scene Entry and Scene Exit options to App.tsx 2026-04-11 04:37:16 +02:00
977395bcc6 Add applySceneExitChange function to handle scene exit changes 2026-04-11 04:37:11 +02:00
569d631ffd Add functionality to apply scene entry changes 2026-04-11 04:37:05 +02:00
2dd1c30001 Add scene transition and exit handling logic in App.tsx 2026-04-11 04:36:49 +02:00
0436eff527 Add project validation and diagnostics in App.tsx 2026-04-11 04:36:18 +02:00
401413019a Update dependency in App.tsx 2026-04-11 04:36:18 +02:00
d2eab58881 Add scene entry and exit settings to App component 2026-04-11 04:36:06 +02:00
ac736c0174 Add missing scene entry option handling in App.tsx 2026-04-11 04:35:56 +02:00
4d065cd666 Add scene exit configuration fields in App.tsx 2026-04-11 04:35:49 +02:00
21bcd3c5d1 Add support for scene entry and exit in App component 2026-04-11 04:35:41 +02:00
ed76bda2e3 Add scene entry and exit entities with associated settings and validation 2026-04-11 04:35:31 +02:00
c83ccbb8c1 Include sceneEntry and sceneExit in focus calculations 2026-04-11 04:34:48 +02:00
88aebbe639 Add scene exit transition handler to RunnerCanvas 2026-04-11 04:34:48 +02:00
8432562252 Add scene exit transition request handling in RuntimeHost 2026-04-11 04:34:31 +02:00
bf501a6e38 Add support for scene exits in interaction system 2026-04-11 04:34:25 +02:00
fa705f18bb Add scene entry and exit interfaces and update spawn logic 2026-04-11 04:34:11 +02:00
5d06b73b12 Add validation for SceneEntry and SceneExit entities 2026-04-11 04:33:55 +02:00
9ac5cd5e46 Update scene document migration to handle new version 2026-04-11 04:30:31 +02:00
a74f0a1b2a Add scene entry and exit entities to document migration and reading 2026-04-11 04:29:25 +02:00
062a771eab Extend entity instances with scene entry and exit entities 2026-04-11 04:29:16 +02:00
f200d1043a Add runtime global state interfaces and default creation function 2026-04-11 04:29:16 +02:00
8a1d41567e Add loadingScreen properties to scene-main in local draft storage test 2026-04-11 04:23:39 +02:00
cd3ea64e25 Format and refactor code in App.tsx 2026-04-11 04:22:32 +02:00
7131581703 Add closing tag in App.tsx 2026-04-11 04:22:32 +02:00
e205cea50c auto-git:
[change] src/app/app.css
 [change] src/commands/set-scene-loading-screen-command.ts
 [change] src/document/migrate-scene-document.ts
 [change] src/document/scene-document-validation.ts
 [change] src/document/scene-document.ts
 [change] src/runner-web/RunnerCanvas.tsx
 [change] src/runtime-three/first-person-navigation-controller.ts
 [change] src/runtime-three/navigation-controller.ts
 [change] src/runtime-three/orbit-visitor-navigation-controller.ts
 [change] src/runtime-three/runtime-host.ts
 [change] tests/domain/editor-store.test.ts
 [change] tests/serialization/local-draft-storage.test.ts
 [change] tests/serialization/project-document-json.test.ts
 [change] tests/serialization/project-package.test.ts
 [change] tests/unit/runner-canvas.test.tsx
 [change] tests/unit/runtime-host.test.ts
2026-04-11 04:19:51 +02:00
75986da19d auto-git:
[change] tests/unit/runtime-host.test.ts
2026-04-11 04:19:51 +02:00
8c112c88af Add loading screen properties to local draft storage test 2026-04-11 04:19:04 +02:00
af6c7e00b1 Add test for updating scene loading overlay settings 2026-04-11 04:19:00 +02:00
57bc7716c3 Update project package test with loading screen settings 2026-04-11 04:19:00 +02:00
002215fd3c Add unit test for project document JSON serialization 2026-04-11 04:19:00 +02:00
e6944f6c32 Add unit test for RuntimeHost 2026-04-11 04:19:00 +02:00
d3d47abb98 Update RunnerCanvas tests to include scene loading and error handling 2026-04-11 04:18:11 +02:00
9b1f135399 Add loading overlay styles for runner canvas 2026-04-11 04:17:49 +02:00
40824c6078 Add scene loading screen and error handling to RunnerCanvas 2026-04-11 04:17:40 +02:00
c802652aae Update UI for Scene settings and enhance World background display 2026-04-11 04:17:06 +02:00
465de798a0 Remove runtime message and add scene name to RunnerCanvas 2026-04-11 04:17:05 +02:00
bd67055696 Add functions to apply scene loading screen settings 2026-04-11 04:16:19 +02:00
75c89d0d00 Add state management for scene loading headline and description in App.tsx 2026-04-11 04:16:11 +02:00
ee6d941014 Throw error if activeProjectScene is undefined 2026-04-11 04:16:04 +02:00
825ca26c30 Add activeProjectScene variable in App.tsx 2026-04-11 04:16:04 +02:00
1aa8e55487 Import and use setSceneLoadingScreenCommand in App.tsx 2026-04-11 04:16:04 +02:00
e4ad280ea5 Add scene readiness check in RuntimeHost 2026-04-11 04:15:38 +02:00
5e64f4db1e Refactor collision world rebuild logic in runtime-host.ts 2026-04-11 04:15:32 +02:00
a773c9f6e5 Add scene load state management and navigation controller activation in runtime-host.ts 2026-04-11 04:15:27 +02:00
ab2a6e09d1 Enhance scene loading and navigation handling in RuntimeHost 2026-04-11 04:15:18 +02:00
9d7bc88596 Add resetSceneState method and scene load state interface 2026-04-11 04:15:07 +02:00
b8d6e30f84 Implement resetSceneState in FirstPersonNavigationController 2026-04-11 04:15:00 +02:00
7081d54c82 Update NavigationController interface 2026-04-11 04:15:00 +02:00
7500406efd Add set scene loading screen command 2026-04-11 04:15:00 +02:00
3b8b115b3a Add scene loading screen validation 2026-04-11 04:15:00 +02:00
876496a0d7 Add validation for project scene loading screen properties 2026-04-11 04:14:33 +02:00
ec0f4247ba Update scene document migration to handle new version 2026-04-11 04:14:33 +02:00
3bf7dca99c Add support for loading screen in project scene migration 2026-04-11 04:14:16 +02:00
f439d2a873 Add functions for reading optional scene loading text and settings 2026-04-11 04:14:09 +02:00
4a9dea81cf Add runner loading screen version and update imports 2026-04-11 04:14:01 +02:00
158a5b8944 Bump scene document version and update loading screen handling 2026-04-11 04:14:01 +02:00
3c3723531a Add loading screen settings to scene document 2026-04-11 04:08:03 +02:00
4200b4ea04 Update architecture.md with persisted project structure details 2026-04-11 03:53:48 +02:00
58b7be9f6b Fix JSON key quoting in local-draft-storage.test.ts 2026-04-11 03:53:48 +02:00
659485870a Add setGridVisible to MockViewportHost 2026-04-11 03:53:08 +02:00
d016c47803 Fix scene ID quotes in project package test 2026-04-11 03:53:08 +02:00
ca8dd5361d Fix scene ID quotes in local draft storage test 2026-04-11 03:53:08 +02:00
2f40bdc184 Refactor imports and types in create-scene-command.ts 2026-04-11 03:52:29 +02:00
664fe443c2 Remove unused import in editor-store.ts 2026-04-11 03:52:29 +02:00
e35a06131c Add tests for scene creation, active scene switching, and command history management 2026-04-11 03:52:07 +02:00
cf47635ba6 Update project package serialization tests to support multiple scenes and improve document creation 2026-04-11 03:51:45 +02:00
eab3e4511a Update test to use createProjectDocumentFromSceneDocument 2026-04-11 03:51:13 +02:00
e80b75e7e0 Expand tests for local draft storage and project scenes 2026-04-11 03:51:10 +02:00
fe1d81b3a4 Update test to use projectDocument instead of document 2026-04-11 03:51:10 +02:00
ac5febcb11 Add styles for toolbar components in app.css 2026-04-11 03:49:49 +02:00
9a1a8884e7 Refactor scene controls and add new scene button in App.tsx 2026-04-11 03:49:45 +02:00
8c6e08d4ac Update project save logic in App.tsx 2026-04-11 03:49:45 +02:00
37a37ef0a6 Add handlers for creating scenes and changing active scenes 2026-04-11 03:49:34 +02:00
b25be0d036 Extract sceneList from editorState.projectDocument.scenes 2026-04-11 03:49:34 +02:00
de8360183c Import and prepare commands for scene creation and active scene setting 2026-04-11 03:49:34 +02:00
af3af9c857 Rename initialDocument to initialProjectDocument in createEditorStore 2026-04-11 03:49:34 +02:00
422b570749 Update EditorStore to support project documents and scenes 2026-04-11 03:49:10 +02:00
dd0048ff84 Update project package serialization to use ProjectDocument 2026-04-11 03:48:29 +02:00
27060a97e1 Update local draft storage to use ProjectDocument 2026-04-11 03:48:24 +02:00
5b454b91ea Add serialization functions for ProjectDocument 2026-04-11 03:48:14 +02:00
6a6462a368 Remove unused import and update scene creation logic 2026-04-11 03:48:14 +02:00
1e6ea11e23 Add project document validation and resource checks 2026-04-11 03:48:06 +02:00
cd5655b521 Update scene document migration to support project documents 2026-04-11 03:47:36 +02:00
a6bb276678 Add scene creation and active scene switching commands 2026-04-11 03:47:36 +02:00
f1ab5f8282 Introduce ProjectScene and ProjectDocument interfaces with utility functions 2026-04-11 03:46:52 +02:00
2b3e5858f4 Add styles for status bar items 2026-04-11 03:29:29 +02:00
69336d210b Add E2E test for transform status bar and update CSS for status bar items 2026-04-11 03:29:04 +02:00
0f65009304 Update viewport-host.ts to handle non-brush and modelInstance targets 2026-04-11 03:24:11 +02:00
d2c0066643 Change useEffect to useLayoutEffect in ViewportCanvas 2026-04-11 03:24:06 +02:00
23eaeebb90 Add transform-axis-mapping test file 2026-04-11 03:24:06 +02:00
581da40993 Add cameraSyncRequestId to ViewportCanvas tests 2026-04-11 03:24:06 +02:00
a1fc1fa2b7 Use useLayoutEffect in ViewportCanvas and add cameraSyncRequestId prop 2026-04-11 03:22:50 +02:00
3845934be7 Add cameraSyncRequestId prop to ViewportPanel 2026-04-11 03:22:49 +02:00
3f9e89569f Add requestViewportCameraSync function and update related logic in App.tsx 2026-04-11 03:22:34 +02:00
e6e40246ce Update App.tsx and ViewportHost.ts to include viewport camera sync request ID and resolve object scale constraint axis 2026-04-11 03:22:24 +02:00
754eb60a25 Add transform axis mapping functionality 2026-04-11 03:22:24 +02:00
0b48c6e931 Update roadmap.md and testing.md with new guidelines 2026-04-11 03:15:13 +02:00
a6cff8b3b1 Add AGENTS.md and update CHAT_CONTEXT.md, architecture.md 2026-04-11 03:15:10 +02:00
3d66f7ec5c Remove AGENTS.md file 2026-04-11 03:14:45 +02:00
8e5240a950 Update testing.md with additional steps for each E2E flow 2026-04-11 02:45:59 +02:00
4a66cccd79 auto-git:
[change] src/app/App.tsx
 [change] src/app/editor-store.ts
 [change] src/core/transform-session.ts
 [change] src/viewport-three/ViewportCanvas.tsx
 [change] src/viewport-three/ViewportPanel.tsx
 [change] src/viewport-three/viewport-host.ts
 [change] tests/unit/viewport-canvas.test.tsx
2026-04-11 02:44:49 +02:00
9950444027 auto-git:
[change] tests/unit/transform-foundation.integration.test.tsx
2026-04-11 02:44:49 +02:00
c991f41158 auto-git:
[change] src/viewport-three/viewport-host.ts
 [change] tests/unit/viewport-canvas.test.tsx
2026-04-11 02:44:49 +02:00
53f666d301 Update testing.md with new ergonomics slice checklist 2026-04-11 02:44:04 +02:00
a40089d956 Update App.tsx and ViewportHost.ts with axis constraint space and message updates 2026-04-11 02:43:38 +02:00
5ed5cb25d3 Set viewportGridVisible to true in tests and component props 2026-04-11 02:43:38 +02:00
ff05e9c9cb Add test for local axis constraint support in transform sessions 2026-04-11 02:42:27 +02:00
528d29a4e0 Add tests for transform session axis constraint toggling and viewport camera state persistence 2026-04-11 02:42:13 +02:00
1eddabb5f9 Add emitCameraStateChange function and import ViewportPanelCameraState 2026-04-11 02:41:59 +02:00
ee30f04616 Add setGridVisible to MockViewportHost in transform-foundation integration test 2026-04-11 02:41:59 +02:00
d5d6e1f4bd Add setGridVisible to MockViewportHost and update tests 2026-04-11 02:41:59 +02:00
031ce48aaa Update ViewportCanvas to include transform axis labels 2026-04-11 02:41:10 +02:00
8786e4c12b Add viewportGridVisible prop and effect to ViewportCanvas 2026-04-11 02:41:06 +02:00
3211bd2f7a Add viewportGridVisible prop to ViewportPanel 2026-04-11 02:41:06 +02:00
ab86208e63 Add toggle for viewport grid visibility and update axis constraint handling in App.tsx 2026-04-11 02:40:58 +02:00
c51a396a82 Enhance transform session handling and grid visibility in ViewportHost 2026-04-11 02:40:51 +02:00
dad94d6ec9 Add grid visibility flag and constants in ViewportHost 2026-04-11 02:38:09 +02:00
bb422a98f1 Add axis constraint space parameter to transform session 2026-04-11 02:38:05 +02:00
9e47af9bc6 Add support for local axis constraint in transform session 2026-04-11 02:38:00 +02:00
40cf4ec240 Reorder expected file list in project-package test 2026-04-10 12:34:28 +02:00
e38cb1358f Add setRenderEnabled method to MockViewportHost 2026-04-10 12:34:28 +02:00
d0eca56c35 Refactor project-package.test.ts to use new Zip and ZipDeflate classes from fflate, add buildZipArchive function 2026-04-10 12:33:17 +02:00
3cfa510379 Update project package serialization to use Map and improve error handling 2026-04-10 12:33:09 +02:00
822f870f07 Add probe archive debug logging to test serialization 2026-04-10 12:32:21 +02:00
cf0c92585f Log type and constructor of scene bytes during serialization 2026-04-10 12:32:21 +02:00
7338e4a1eb Add debug logging for project package serialization 2026-04-10 12:32:21 +02:00
d28c23aa48 Add listPackagedFiles function and update tests in project-package.test.ts 2026-04-10 12:28:18 +02:00
32e217d4ee Add ProjectPackageTree type and setPackagedFile function in project-package.ts 2026-04-10 12:28:13 +02:00
ebde30ab22 Refactor test mocks in app-project-persistence.integration.test.tsx 2026-04-10 12:28:13 +02:00
713b42e9b2 Add cloneArrayBuffer function and update tests 2026-04-10 12:27:23 +02:00
3816ad4b33 Convert project bytes to Uint8Array before creating Blob 2026-04-10 12:27:23 +02:00
10dde354f7 Update project-package.ts to handle asset metadata and improve cloning logic 2026-04-10 12:27:04 +02:00
1ecf4bbe78 Replace Save Draft button with reload in e2e tests 2026-04-10 12:26:21 +02:00
f98c32a7af Update local draft storage test messages and add recovery diagnostic check 2026-04-10 12:26:04 +02:00
19fb68b1ce Add tests and update messages for autosave functionality 2026-04-10 12:26:04 +02:00
a57247a7a0 Add project-package serialization tests 2026-04-10 12:25:30 +02:00
df616188f4 Update diagnostic handling in local-draft-storage 2026-04-10 12:25:30 +02:00
5b8842b199 Update dependencies in App.tsx 2026-04-10 12:23:52 +02:00
faaa6775f2 Update toolbar buttons and file input handling in App.tsx 2026-04-10 12:23:41 +02:00
63b9f29ef5 Refactor save and load functionality in App.tsx 2026-04-10 12:23:35 +02:00
65bf168d3a Add autosave functionality and update project package handling 2026-04-10 12:23:26 +02:00
72ca505a61 Add editor-autosave.ts for autosave functionality 2026-04-10 12:23:11 +02:00
7ed2cf92f9 Add project-package.ts for scene serialization 2026-04-10 12:23:11 +02:00
9dca4d3c2f Add fflate dependency and update package.json 2026-04-10 12:23:11 +02:00
2c5ee65291 Add test for SSAO radius value in advanced rendering 2026-04-07 12:18:22 +02:00
6e28024097 Enhance ambient occlusion effect with dual-layer SSAO and additional parameters 2026-04-07 12:17:15 +02:00
486f0f3f3c Enhance advanced rendering by adding normal pass and refining SSAO effect settings 2026-04-07 12:16:56 +02:00
56bf1c4e32 Update FOG_STEPS value in fog-material test 2026-04-07 11:35:12 +02:00
d4587ebfcd Add fog material creation and management in ViewportHost 2026-04-07 11:34:03 +02:00
f6cb305243 Add fog material creation and disposal methods in RuntimeHost 2026-04-07 11:33:34 +02:00
1b16aacf93 Optimize fog material calculations and parameters 2026-04-07 11:33:11 +02:00
4238bce5f5 Remove unnecessary onBeforeRender assignment in configureFogVolumeMesh methods 2026-04-07 11:20:47 +02:00
55290572e0 Add test for localCameraPosition uniform in fog-material 2026-04-07 11:20:47 +02:00
014b157a35 Add fog volume mesh configuration in ViewportHost 2026-04-07 11:19:30 +02:00
7a62d8ed7b Add fog volume mesh configuration in ViewportHost 2026-04-07 11:19:17 +02:00
5c5aaff8b1 Add fog volume mesh configuration in RuntimeHost 2026-04-07 11:19:06 +02:00
edea9a6976 Add fog volume mesh configuration in runtime-host.ts 2026-04-07 11:18:57 +02:00
cf48cabb11 Add local camera position uniform to fog material shaders 2026-04-07 11:18:36 +02:00
40a53801a7 Add fog quality material and update runtime/viewport hosts 2026-04-07 11:08:57 +02:00
802d3e026c Add conditional rendering based on layout mode and active panel status in ViewportCanvas 2026-04-07 10:54:36 +02:00
47cdebf7f8 Implement render enablement and disablement in ViewportHost 2026-04-07 10:53:29 +02:00
e993ff6116 Add render control based on layout mode and active panel 2026-04-07 10:53:28 +02:00
ee83c31f74 Add render enablement control in ViewportHost 2026-04-07 10:53:06 +02:00
cbed3c1503 Update water material test expectations 2026-04-07 10:46:22 +02:00
09159a1e3f Add functions for creating signed distance to patch region and box patch from segment loop in water-material.js 2026-04-07 10:46:18 +02:00
5a29c4a2c9 Add functions for creating signed distance to patch region and box patch from segment loop in water-material.ts 2026-04-07 10:46:04 +02:00
73fdff0167 Add test case for water material contact patches with box brush 2026-04-07 10:44:41 +02:00
e22c899d63 Add tests for water contact patch creation and foam generation 2026-04-07 10:38:32 +02:00
a171f26988 Update water material collision detection logic in JavaScript 2026-04-07 10:38:32 +02:00
12fe38c268 Update water material collision detection logic 2026-04-07 10:38:32 +02:00
05caaf888f Add logic to preserve and manage WebGL render targets for water reflections in viewport rendering 2026-04-07 08:48:37 +02:00
7ea659e195 Add water reflection update interval and last update time tracking in ViewportHost 2026-04-07 08:40:04 +02:00
ebafda0833 Simplify reflection enabled condition and handle null render target 2026-04-07 08:32:36 +02:00
691b0ca645 Refactor uniform creation in water material shaders and tests 2026-04-07 07:50:46 +02:00
372a5551aa Add test for subdividing displaced water geometry without altering collider 2026-04-07 07:46:57 +02:00
de8ceafb7f Add water surface subdivision and UV interpolation in box brush mesh 2026-04-07 07:46:47 +02:00
27071fc3f3 Add missing closing brace in App.tsx 2026-04-07 07:37:55 +02:00
f8e23bcb4e Refactor App.tsx to use inline function for onBlur event 2026-04-07 07:36:37 +02:00
36b474c2aa Add onBlur event handler for interaction links in App.tsx 2026-04-07 07:36:21 +02:00
79dac5911c Update tests for water material and volume integration 2026-04-07 07:33:37 +02:00
578f316db7 Refactor water settings handling and update reflection logic in rendering 2026-04-07 07:33:25 +02:00
c82d547dd8 Add surfaceDisplacementEnabled to water material tests and validation 2026-04-07 07:22:24 +02:00
0b4c144090 Add support for water surface displacement in scene documents 2026-04-07 07:21:38 +02:00
cb2b511cfc Add water reflection update interval and fix fog handling in RuntimeHost 2026-04-07 07:19:46 +02:00
6881b3ae2f Add surface displacement feature to water material 2026-04-07 07:15:18 +02:00
6a7ff5ba4a Update underwater fog density calculation based on point position 2026-04-07 07:14:59 +02:00
289369674d Validate surfaceDisplacementEnabled in scene document validation 2026-04-07 07:14:59 +02:00
5ae932fdcc Add surfaceDisplacementEnabled to water volume settings 2026-04-07 07:14:59 +02:00
c7797cdf9b Add surface displacement enabled setting to box brush water settings 2026-04-07 07:14:30 +02:00
d12f6103fa Bump scene document version and add water surface displacement version 2026-04-07 07:14:30 +02:00
f65e00b94f Optimize water reflection rendering with time-based updates 2026-04-07 07:14:00 +02:00
49a64b2d9b Reset lastReflectionUpdateTime when resizing reflection render targets 2026-04-07 07:14:00 +02:00
2789859360 Add surfaceDisplacementEnabled to water material properties 2026-04-07 07:14:00 +02:00
bfb3eebd2c Refactor fog handling and add reflection update timestamp 2026-04-07 07:13:38 +02:00
052b0a3bcb Implement reflection update interval and fog handling 2026-04-07 07:13:33 +02:00
d5d7219c57 Reset lastReflectionUpdateTime when resizing reflection target 2026-04-07 07:13:33 +02:00
0d5855171a Add surfaceDisplacementEnabled to water material properties 2026-04-07 07:13:33 +02:00
85acd40fbc Disable underwater scene fog by default 2026-04-07 07:13:33 +02:00
5d87c62754 Add lastReflectionUpdateTime to RuntimeWaterContactUniformBinding 2026-04-07 07:13:33 +02:00
be7ccc93e8 Update underwater fog calculations and add local point function 2026-04-07 07:11:52 +02:00
4c0b429964 Add surface displacement option to water material 2026-04-07 07:11:46 +02:00
66bb99b5ac Add water surface displacement option in App and update document migration & validation 2026-04-07 07:11:26 +02:00
e32c00e0ef Add surface displacement enabled setting to box brush water settings 2026-04-07 07:11:15 +02:00
90012d9499 Bump scene document version and add water surface displacement version 2026-04-07 07:11:15 +02:00
f9f0a4cfd1 Add foamContactLimit to water volume test 2026-04-07 06:57:42 +02:00
f4624d4bc1 Add foamContactLimit to water properties in multiple tests 2026-04-07 06:56:35 +02:00
238e8390a2 Add foamContactLimit to water properties in water-volume.integration.test.tsx 2026-04-07 06:56:35 +02:00
e73aed9063 Add foamContactLimit to water properties in create-box-brush.command.test.ts 2026-04-07 06:56:35 +02:00
0241e076ba Add foamContactLimit to water properties in build-runtime-scene.test.ts 2026-04-07 06:56:35 +02:00
5ec9099a02 Extract and use runtime water foam contact limit calculation in multiple methods 2026-04-07 06:55:36 +02:00
3be887d0aa Extract and use getRuntimeWaterFoamContactLimit method in RuntimeHost 2026-04-07 06:55:29 +02:00
32b50fe95e Add test for foam contact patch count cap and update water material tests 2026-04-07 06:54:30 +02:00
0609882a16 Add water reflection mode and foam contact limit handling in scene document JSON tests 2026-04-07 06:53:34 +02:00
4fe105aa1b auto-git:
[change] tests/domain/world-settings.test.ts
2026-04-07 06:53:27 +02:00
196bb6cef8 auto-git:
[change] tests/domain/create-empty-scene-document.test.js
2026-04-07 06:53:27 +02:00
720a53c2f4 auto-git:
[change] tests/domain/create-empty-scene-document.test.ts
2026-04-07 06:53:27 +02:00
99716fbe30 Add water reflection mode selection in advanced rendering settings 2026-04-07 06:46:37 +02:00
047204bada Add Foam Contact Limit input field in App.tsx 2026-04-07 06:46:31 +02:00
b206149c68 auto-git:
[change] src/app/App.tsx
2026-04-07 06:46:25 +02:00
f88ad88ff2 Include water foam contact limit in box settings update 2026-04-07 06:46:20 +02:00
a587b08a82 Add state and handling for box volume water foam contact limit 2026-04-07 06:46:20 +02:00
0a66233db7 Implement readWaterFoamContactLimitDraft and formatAdvancedRenderingWaterReflectionModeLabel functions 2026-04-07 06:46:00 +02:00
80840536c8 auto-git:
[change] src/app/App.tsx
2026-04-07 06:46:00 +02:00
d810f96d10 Add water reflection functionality to ViewportHost 2026-04-07 06:45:03 +02:00
d7294e2de1 Refactor viewport-host.js to simplify water contact patch collection and usage 2026-04-07 06:44:46 +02:00
fecd08b9ad Update water material to include reflection properties 2026-04-07 06:44:33 +02:00
2e5c86e274 Add AxesHelper and WebGLRenderTarget import in viewport-host.js 2026-04-07 06:44:33 +02:00
445d0acf6b Enhance water contact handling and reflection management in RuntimeHost 2026-04-07 06:44:07 +02:00
c4739493d9 Update shader and add water reflection features in runtime-host.js 2026-04-07 06:43:56 +02:00
a155291778 Update water material handling with reflection properties 2026-04-07 06:43:18 +02:00
e65e6b730e Add water reflection camera to RuntimeHost class 2026-04-07 06:43:18 +02:00
08c880ccf2 Import additional Three.js modules and update planar reflection 2026-04-07 06:43:18 +02:00
0624f2ae96 Refactor water reflection target size calculation in viewport-host.ts 2026-04-07 06:42:41 +02:00
a9ca100c3d Adjust water reflection target creation and resizing logic 2026-04-07 06:42:36 +02:00
a6a7abfbdd Update viewport water reflections in render loop 2026-04-07 06:42:36 +02:00
e28ca1bcd0 Resize water reflection targets on resize 2026-04-07 06:42:36 +02:00
1b7b0d87c5 Dispose reflection render targets in clear method 2026-04-07 06:42:36 +02:00
83475a72f9 Add water reflection functionality in viewport-host.ts 2026-04-07 06:42:05 +02:00
be2ccd8208 Refactor viewport water contact patch collection and usage 2026-04-07 06:41:41 +02:00
a50793b268 Update water material to include reflection properties 2026-04-07 06:41:36 +02:00
d28d7f3a47 Add axes helper and water reflection camera to ViewportHost 2026-04-07 06:41:36 +02:00
d8cb047eb2 Define ViewportWaterSurfaceBinding interface 2026-04-07 06:41:26 +02:00
83f76ed164 Import additional Three.js classes and functions 2026-04-07 06:41:25 +02:00
5fd02cdece Add water reflection target disposal and resize handling in RuntimeHost 2026-04-07 06:37:22 +02:00
aa94c950e1 Update water contact patch handling in runtime-host.ts 2026-04-07 06:36:13 +02:00
d1f0957a7b Add water reflection functionality in runtime-host.ts 2026-04-07 06:35:29 +02:00
5061ddbcb3 Add reflection properties to water material and update shader uniforms 2026-04-07 06:35:15 +02:00
728dc02d72 Add reflection support to runtime-host.ts 2026-04-07 06:35:00 +02:00
7720b458ff Add planar reflection implementation in JavaScript and TypeScript 2026-04-07 06:34:29 +02:00
018a6ad1c5 Add reflection support to water material 2026-04-07 06:32:30 +02:00
282c282f9c Add reflection support to water material 2026-04-07 06:31:50 +02:00
d2bb70434b Add water reflection mode and foam contact limit validation 2026-04-07 06:30:48 +02:00
8bbdd634da Add water reflection mode and foam contact limit to advanced rendering settings 2026-04-07 06:30:28 +02:00
8b76e1688c Add validation for water reflection mode and foam contact limit 2026-04-07 06:30:19 +02:00
662369e6e3 Add foam contact limit to box brush water settings and update world settings with water reflection modes 2026-04-07 06:30:13 +02:00
f4714e8c25 Add foamContactLimit to BoxBrushWaterSettings and waterReflectionMode to AdvancedRenderingSettings 2026-04-07 06:30:04 +02:00
b2ed3d7383 Make points readonly in measureSegmentExtentsInBasis 2026-04-07 06:17:25 +02:00
32cef4334d Update water material tests 2026-04-07 06:17:25 +02:00
b6f34a3604 Add underwater fog functionality 2026-04-07 06:17:25 +02:00
7d61cd322d Add underwater fog effect and update shader material for water patches 2026-04-07 06:15:39 +02:00
3e370591d3 Add underwater fog effect and update water material handling 2026-04-07 06:15:18 +02:00
786225b4b7 Add support for different shapes in water contact patches 2026-04-07 06:15:02 +02:00
bbf28f9590 Add segment patch creation and handling in water-material.js 2026-04-07 06:14:35 +02:00
a1669a1d69 Add support for segment-shaped water contact patches 2026-04-07 06:13:56 +02:00
acf82132ba Update test vertices for water material 2026-04-07 06:04:11 +02:00
76b7cf538a Update vertex coordinates in water material test 2026-04-07 06:03:01 +02:00
3c54ba00c9 Add waterline segment creation and update contact patch logic 2026-04-07 06:01:45 +02:00
0cb68e3737 Adjust gap settings in water material for better alignment and spacing 2026-04-07 05:52:43 +02:00
47efbbfd43 Update vertex coordinates in water material test 2026-04-07 05:52:19 +02:00
8a774a8e7f Update test data for water material helpers 2026-04-07 05:51:49 +02:00
b62edd7e88 Enhance water material merging logic with normal alignment and profile settings 2026-04-07 05:51:42 +02:00
b9bda55693 Add patch merging functionality in water-material 2026-04-07 05:48:48 +02:00
b289a8d72c Add functions for clipping polygons and creating patches from projected points 2026-04-07 05:44:58 +02:00
a74a7c02f0 Update collision detection to handle triangle meshes and transformed colliders 2026-04-07 05:44:28 +02:00
a9567d3dc8 Add support for triangle mesh water contact source 2026-04-07 05:44:04 +02:00
0826cc78bb Update RunnerCanvas to use cameraSubmerged for underwater overlay and add tests 2026-04-07 05:30:24 +02:00
b062b2beea Add polygon clipping and area calculation to water contact patch collection 2026-04-07 05:12:55 +02:00
340ea8c3d3 Update water material test size values 2026-04-07 05:04:12 +02:00
a8ad839ee2 Remove unused imports in viewport-host.ts 2026-04-07 05:02:53 +02:00
867a20ab15 Update water contact patch handling in runtime and viewport components 2026-04-07 05:01:43 +02:00
de430fdda1 Add support for oriented boxes in water material rendering 2026-04-07 05:01:26 +02:00
0e4bd01e69 Update water contact patch collection and handling in rendering and runtime modules 2026-04-07 04:59:09 +02:00
30ddb565db Add support for oriented boxes in water material contact patches 2026-04-07 04:58:48 +02:00
6587f59cda Update createFaceMaterial to include staticContactPatches in runtime-host.js and .ts, adjust tests in water-material.test.ts 2026-04-06 20:55:31 +02:00
0e86dd3d07 Enable WebGL rendering unconditionally and update telemetry handling in RunnerCanvas.js 2026-04-06 20:54:40 +02:00
a46640bfb6 Add underwater effect to RunnerCanvas and update WebGL rendering check 2026-04-06 20:54:24 +02:00
e4146ea35e Disable antialiasing in WebGL renderer 2026-04-06 20:54:24 +02:00
7c26caa2e8 Disable antialiasing in WebGLRenderer and update water contact patch collection logic 2026-04-06 20:53:56 +02:00
748273ff38 Refactor water material and runtime handling for better performance and accuracy 2026-04-06 20:52:19 +02:00
25c39e0507 Rename radius to halfWidth and intensity to halfDepth in WaterContactPatch interface 2026-04-06 20:52:05 +02:00
47362036bf Enhance advanced rendering settings and water material handling 2026-04-06 18:06:50 +02:00
14bb36f7a6 Update rendering settings and remove WebGL check in ViewportCanvas 2026-04-06 18:04:52 +02:00
c3d28b11ab Add water contact patch uniform handling in RuntimeHost 2026-04-06 18:04:44 +02:00
c7433820a4 Add contact patches uniform to water material and update tests 2026-04-06 18:04:25 +02:00
ab44a2b9c5 Refactor water material shader and add contact patch collection 2026-04-06 17:54:42 +02:00
ff23723797 Refactor water material to use ShaderMaterial for better rendering effects 2026-04-06 17:48:23 +02:00
6da77e8495 Update water material properties and tests 2026-04-06 17:43:33 +02:00
b89f30a5b6 Remove unused method createWaterQualityMaterial from runtime-host.js 2026-04-06 17:37:53 +02:00
4e455d4076 Remove unused water quality material creation function 2026-04-06 17:37:28 +02:00
230a45e857 Refactor texture creation and contact patch collection in viewport-host.ts 2026-04-06 17:36:12 +02:00
2f8d22640d Refactor water volume integration test to use waitFor instead of fake timers 2026-04-06 17:35:21 +02:00
a157eefd1f Add water material and volume tests 2026-04-06 17:34:54 +02:00
7a134d8685 Add volume animation update to ViewportHost 2026-04-06 17:34:54 +02:00
fd5b8b2dad Implement collectViewportWaterContactPatches method in viewport-host.js 2026-04-06 17:33:35 +02:00
df6d5936c0 Add contact patch collection for water brushes in viewport-host.js 2026-04-06 17:33:35 +02:00
94c423878e Add contact patch collection and update material creation for water brushes 2026-04-06 17:32:56 +02:00
ab4eb22662 Import additional modules and add volume time tracking in viewport-host.js 2026-04-06 17:32:44 +02:00
ab88923c85 Add water contact patch collection and material update in viewport-host.ts 2026-04-06 17:32:44 +02:00
592a062b32 Add water material support and contact patch collection in runtime-host.js 2026-04-06 17:31:34 +02:00
4d32769fda Add volume animation support in viewport-host.ts 2026-04-06 17:30:48 +02:00
aa9a532ae9 Add method to collect viewport water contact patches 2026-04-06 17:29:41 +02:00
ee1b9f80e1 Add contact patch handling for water brushes in viewport-host.ts 2026-04-06 17:29:36 +02:00
cdfb401832 Add volume time and animated uniforms to ViewportHost 2026-04-06 17:28:39 +02:00
4caa673a1d Reset volume animated uniforms on clear 2026-04-06 17:28:39 +02:00
cef207de4a Update volume time for animated uniforms 2026-04-06 17:28:39 +02:00
0529975ef7 Add support for water material in runtime host 2026-04-06 17:27:13 +02:00
4d59e00ac9 Update App.tsx to handle box water and fog color changes with draft commits 2026-04-06 17:27:02 +02:00
f9f4d6a4a1 Add water material implementation in JavaScript and TypeScript 2026-04-06 17:27:02 +02:00
580eb7f856 Add depth-based water effect and specular highlights in runtime-host.js 2026-04-06 17:05:21 +02:00
46553a050d Enhance water shader with object interaction and improved foam effects 2026-04-06 17:04:59 +02:00
565e6e54a3 Update shader for more realistic water effects 2026-04-06 16:58:16 +02:00
ef1c7fa0df Enhance water shader with Gerstner waves, normal mapping, refraction, and foam effects 2026-04-06 16:56:46 +02:00
3191b2cefd Add clearModelInstances method to RuntimeHost 2026-04-06 09:21:06 +02:00
41feeb463e Add shader-based water and fog materials with animation support 2026-04-06 09:20:00 +02:00
8bfdcd5f9c Update material creation methods to use volume properties directly 2026-04-06 09:19:31 +02:00
163609fb02 Refactor water and fog material creation methods to accept configuration objects 2026-04-06 09:18:14 +02:00
c76c42d5c6 Refactor material creation logic for water and fog modes in runtime-host.ts 2026-04-06 09:17:47 +02:00
9a5b48a02f Add volume time update and material uniform handling in runtime-host.ts 2026-04-06 09:16:49 +02:00
d6eba50dac Update runtime-host.ts to support additional materials and volume animation 2026-04-06 09:16:49 +02:00
e6405fb3de Reorganize Volume Rendering Paths section in App.tsx 2026-04-06 09:16:29 +02:00
18f69a7d20 Configure Vite to prefer TypeScript source files 2026-04-06 09:07:10 +02:00
dc9daf0ce2 Remove Volume Rendering Paths section from App.tsx 2026-04-06 09:04:08 +02:00
620e73d380 Add advanced rendering options for fog and water paths in App.tsx 2026-04-06 09:02:21 +02:00
e8e9dc61a4 Configure Vite to prefer TypeScript source files 2026-04-06 09:02:11 +02:00
e284344f69 Update test case with additional camera properties 2026-04-06 08:55:58 +02:00
635ab33d4e Update test case with additional camera properties 2026-04-06 08:55:58 +02:00
1e1f781c2c Remove thickness property from material settings in multiple files 2026-04-06 08:50:33 +02:00
dfb9018e41 Remove transmission property from material settings 2026-04-06 08:50:33 +02:00
40fb0a0973 Add volumes property to runtime scene fixture 2026-04-06 08:50:33 +02:00
c456b63204 Initialize volumes object in runtime scene fixture 2026-04-06 08:45:14 +02:00
d7369da1c3 Remove transmission property from material settings in ViewportHost 2026-04-06 08:45:14 +02:00
40bd7540e9 Add type annotation for volumeRenderPaths in RuntimeHost 2026-04-06 08:45:14 +02:00
6cdb99e80e Update validation tests for scene document 2026-04-06 08:44:11 +02:00
f130bd0af9 Add fogPath and waterPath to scene document JSON test 2026-04-06 08:44:10 +02:00
ae0838838d Update tests for invalid volume settings in scene document validation 2026-04-06 08:44:01 +02:00
30b7b152c3 Add tests for advanced rendering logic 2026-04-06 08:34:39 +02:00
df4064ba12 Update test for scene document JSON migration 2026-04-06 08:33:29 +02:00
87651ee670 Add tests for whitebox geometry volume settings and migration of legacy scenes 2026-04-06 08:33:26 +02:00
2b282ad01a Add validation for advanced rendering fog and water paths, and box volume settings 2026-04-06 08:33:16 +02:00
55482624f1 Update build-runtime-scene.test.ts to include water and fog volumes 2026-04-06 08:33:10 +02:00
da6d6d1c2c auto-git:
[change] tests/domain/create-box-brush.command.test.ts
2026-04-06 08:33:00 +02:00
c8fe4125ec Add locomotion state and water/fog volume status to runner stats in App.js 2026-04-06 08:33:00 +02:00
c074f3e597 Add locomotion, water volume, and fog volume stats to App.tsx 2026-04-06 08:31:23 +02:00
2f5fd46044 Add volume mode selection and settings for water and fog in App.tsx 2026-04-06 08:29:51 +02:00
b4cd57c5fa Add volume rendering paths selection to App component 2026-04-06 08:29:15 +02:00
3a12826d6b Add advanced rendering fog and water path settings in App.tsx 2026-04-06 08:29:03 +02:00
f42ca08334 Add functions to apply box volume settings and modes in App.tsx 2026-04-06 08:28:59 +02:00
b6e0f57251 Update selected brush handling to include volume properties in App.tsx 2026-04-06 08:28:41 +02:00
ce27bc718a Add state variables for box volume properties in App.tsx 2026-04-06 08:28:41 +02:00
f3abebeb17 Add helper functions for formatting box volume mode and render path labels in App.tsx 2026-04-06 08:28:28 +02:00
720a182305 Import and add BoxBrushVolumeSettingsCommand to App.tsx 2026-04-06 08:28:28 +02:00
d7bad93e67 Add support for water and fog volume rendering in ViewportHost 2026-04-06 08:27:40 +02:00
ce341494ef Add water and fog rendering logic in viewport-host.ts 2026-04-06 08:27:23 +02:00
0d225e3f64 Import Euler from three.js in runtime-host.ts 2026-04-06 08:27:23 +02:00
0eac272aaa Update runtime-host.js to include volume rendering paths and enhance material creation logic 2026-04-06 08:26:46 +02:00
71dc2ac75f Update runtime-host.ts to handle volume rendering paths and improve material creation logic 2026-04-06 08:26:35 +02:00
edf3552c5f Add volume state resolution and point inside oriented volume check in RuntimeHost 2026-04-06 08:26:12 +02:00
104808b876 Add player volume state resolution in RuntimeHost 2026-04-06 08:25:56 +02:00
66e1b78ca1 Add volume state tracking and update locomotion logic in first-person navigation controller 2026-04-06 08:25:45 +02:00
e17a4c3373 Add volume state tracking and locomotion state management in FirstPersonNavigationController 2026-04-06 08:22:24 +02:00
85f6b4d74a Add locomotion state and volume checks to navigation controller 2026-04-06 08:21:33 +02:00
c5d45fe51d Add resolveBoxVolumeRenderPaths function in advanced-rendering.js and advanced-rendering.ts 2026-04-06 08:21:11 +02:00
7167b328af Add support for fog and water volumes in runtime scene build 2026-04-06 08:21:04 +02:00
af659a4646 Update runtime scene build to include volume data 2026-04-06 08:20:38 +02:00
439789e139 Add set box brush volume settings command 2026-04-06 08:20:38 +02:00
b66a642234 Add validation for box volume mode and settings in scene document 2026-04-06 08:19:52 +02:00
39868b72b7 Add validation for advanced rendering fog and water paths, and box volume mode and settings 2026-04-06 08:19:28 +02:00
706edfddcd Add fog and water settings to advanced rendering and update box brush volume handling 2026-04-06 08:19:17 +02:00
54d7ec7329 Remove unused constant BOX_BRUSH_VOLUME_MODES 2026-04-06 08:19:17 +02:00
9e4a17a4a8 Update migrate-scene-document.ts with new box brush volume settings 2026-04-06 08:18:38 +02:00
4abb93203c Bump SCENE_DOCUMENT_VERSION to 20 and add WHITEBOX_BOX_VOLUME_SCENE_DOCUMENT_VERSION 2026-04-06 08:18:38 +02:00
46f8310514 Update scene document version and add box volume render paths 2026-04-06 08:18:09 +02:00
d80a3c5627 Add volume modes and settings for box brushes 2026-04-06 08:18:03 +02:00
8e04c4e7c3 Add volume settings to BoxBrush and related interfaces 2026-04-06 08:17:52 +02:00
693f039171 Add method to apply local light render object transform 2026-04-05 06:54:23 +02:00
b32c34ef47 Add method to apply local light render object transform 2026-04-05 06:54:11 +02:00
892e142caa Update gltf-model-import to use SkeletonUtils.clone for better skinned mesh handling 2026-04-05 06:38:43 +02:00
f68d2b7aa4 Update tests for duplicate selection command to match new behavior 2026-04-05 04:37:16 +02:00
cc709509ff Update box brush duplication test to expect same center in JS 2026-04-05 04:36:57 +02:00
0d965bce29 Update box brush duplication test to expect same center 2026-04-05 04:36:57 +02:00
ebb4371e18 Update tests to ensure correct duplication without offset 2026-04-05 04:36:45 +02:00
14e401c9fa Enhance selection duplication handling in App.js 2026-04-05 04:36:38 +02:00
d846b4bb6f Enhance duplication logic with transform session handling 2026-04-05 04:36:32 +02:00
7790b6a895 Simplify duplicate selection command by removing offset logic 2026-04-05 04:36:25 +02:00
986c606c14 Remove unused imports and offset logic in duplicate selection command 2026-04-05 04:36:19 +02:00
aa8abd2baf Update box-brush-authoring.e2e.js test to check transform session state 2026-04-05 04:34:49 +02:00
0581d49ecc Enhance selection duplication logic and update tests 2026-04-05 04:33:34 +02:00
db1210831c Enhance duplication logic with transformation check 2026-04-05 04:33:28 +02:00
30294442e9 Improve code formatting in duplicate-selection-command.js 2026-04-05 04:29:43 +02:00
d3199fae5c Update duplicate model instance logic to handle asset placement 2026-04-05 04:29:38 +02:00
70cd0369e7 Update model instance duplication logic to handle asset placement 2026-04-05 04:29:31 +02:00
8e9ca3252b Add test for Shift+D duplication and typing behavior 2026-04-05 04:26:10 +02:00
7ff300fdc6 Add tests for duplicate selection command and update box brush authoring test 2026-04-05 04:26:00 +02:00
32f2b26035 Implement detailed tests for duplicate selection command 2026-04-05 04:25:23 +02:00
b0b5ef1027 Add tests for duplicate selection command 2026-04-05 04:25:23 +02:00
d7debe7280 Add duplicate selection shortcut 2026-04-05 04:25:23 +02:00
70725fa989 Add duplicate selection functionality in App.js 2026-04-05 04:24:01 +02:00
f195d2b0b5 Add function to check if selection can be duplicated 2026-04-05 04:23:55 +02:00
5332d16d0a Import duplicate selection command 2026-04-05 04:23:55 +02:00
fa440f2e33 Add duplicate selection functionality 2026-04-05 04:23:25 +02:00
e7605511a3 Implement JavaScript logic for duplicate selection command 2026-04-05 04:23:19 +02:00
28e361b85e Add JavaScript version of duplicate selection command 2026-04-05 04:23:19 +02:00
e85e953fb9 Update duplicate selection command to use SceneDocument type 2026-04-05 04:23:19 +02:00
53c19deffb Add duplicate selection command 2026-04-05 04:23:18 +02:00
0876154ebc Update runtime-host.js to use new box brush mesh data builder 2026-04-05 03:18:45 +02:00
acc225aea9 Enhance transform session handling by including geometry and update viewport rendering logic accordingly 2026-04-05 03:06:51 +02:00
eb07782253 Add test for committing deformed vertex geometry without forcing all vertices onto box extents 2026-04-05 03:05:42 +02:00
733295b36c Update tests to include initialGeometry for brushes 2026-04-05 02:59:57 +02:00
f35cf82574 Add geometry to initial brush in viewport-host.ts 2026-04-05 02:59:57 +02:00
1f572cc7fe Modify set-box-brush-transform-command.js for geometry handling 2026-04-05 02:58:37 +02:00
b9b3759207 Update viewport-host.ts to include geometry in preview 2026-04-05 02:58:37 +02:00
4cf85cecf5 auto-git:
[change] src/viewport-three/viewport-host.ts
2026-04-05 02:58:22 +02:00
ab07a599cd Remove unused parameter 'size' from applyBrushRenderObjectTransform method 2026-04-05 02:57:14 +02:00
fbc725ee25 Add geometry update for box brush in ViewportHost 2026-04-05 02:57:06 +02:00
8caec6c0b4 auto-git:
[change] src/viewport-three/viewport-host.ts
2026-04-05 02:56:49 +02:00
95703fc5ec Update viewport host with additional box brush functions and types 2026-04-05 02:55:49 +02:00
1903b29d65 Add geometry to commit transform session command 2026-04-05 02:55:49 +02:00
b83b11e75f Add function to transform world point to local in box brush components 2026-04-05 02:55:09 +02:00
667849750c Add geometry to transform session command and update box brush transform command 2026-04-05 02:54:57 +02:00
c5f4f99598 Add support for brush geometry in transform targets and previews 2026-04-05 02:54:51 +02:00
98bbc49d41 Import and use new geometry functions in box brush commands 2026-04-05 02:39:14 +02:00
faf0cfcf03 Update box brush commands to include geometry tracking and scaling 2026-04-05 02:37:59 +02:00
a1d410d6d3 Add scaleBoxBrushGeometryToSize function in brushes.js and brushes.ts 2026-04-05 02:37:30 +02:00
67b435e3e2 Update scene-document-json.test.ts to include brush size derivation 2026-04-05 02:37:04 +02:00
8c46b8991a Update box validation and collision world logic 2026-04-05 02:35:35 +02:00
82664df74d Add support for custom box brush geometry in scene documents 2026-04-05 02:35:29 +02:00
cf65b02e8d Add error handling for non-trimesh brush colliders in test 2026-04-05 02:33:43 +02:00
8cc5804278 Update tests to check collider kind and flatten triangles 2026-04-05 02:33:43 +02:00
8f8f6894af Update tests for collider and geometry changes 2026-04-05 02:33:08 +02:00
db72c4783f Add brush geometry validation to runtime scene build 2026-04-05 02:32:15 +02:00
d2de8c4793 Update viewport-host.ts to use BufferGeometry and buildBoxBrushDerivedMeshData 2026-04-05 02:31:20 +02:00
2382ff0d79 Remove unused import BoxGeometry from runtime-host.ts 2026-04-05 02:31:20 +02:00
ac678bd732 Update runtime-host.ts to use BufferGeometry and buildBoxBrushDerivedMeshData 2026-04-05 02:31:20 +02:00
8e55495285 Update collision handling for brush colliders 2026-04-05 02:30:08 +02:00
2e29aa7ae2 Update box brush geometry and collider handling in runtime scene build 2026-04-05 02:30:04 +02:00
efc5d5b0cf Validate box brush geometry vertices for finiteness in scene document validation 2026-04-05 02:28:44 +02:00
67d87fe7dc Add geometry reading to box brushes and update version check in scene document migration 2026-04-05 02:28:44 +02:00
f47cc2606c Add function to read box brush geometry 2026-04-05 02:28:17 +02:00
6a081863c7 Import additional constants and functions for migration 2026-04-05 02:28:17 +02:00
213cf5828a Update scene document version and add new constant 2026-04-05 02:28:17 +02:00
203aa93137 Refactor box face UV projection to remove unused import and simplify halfSize calculation 2026-04-05 02:26:49 +02:00
03465d1d84 auto-git:
[change] src/geometry/box-brush-mesh.ts
 [change] src/geometry/box-face-uvs.ts
2026-04-05 02:25:29 +02:00
0b54fa14c9 auto-git:
[add] playwright.config.js
 [add] src/app/App.js
 [add] src/app/editor-store.js
 [add] src/app/use-editor-store.js
 [add] src/assets/audio-assets.js
 [add] src/assets/gltf-model-import.js
 [add] src/assets/image-assets.js
 [add] src/assets/model-instance-labels.js
 [add] src/assets/model-instance-rendering.js
 [add] src/assets/model-instances.js
 [add] src/assets/project-asset-storage.js
 [add] src/assets/project-assets.js
 [add] src/commands/brush-command-helpers.js
 [add] src/commands/command-history.js
 [add] src/commands/command.js
 [add] src/commands/commit-transform-session-command.js
 [add] src/commands/create-box-brush-command.js
 [add] src/commands/delete-box-brush-command.js
 [add] src/commands/delete-entity-command.js
 [add] src/commands/delete-interaction-link-command.js
 [add] src/commands/delete-model-instance-command.js
 [add] src/commands/import-audio-asset-command.js
 [add] src/commands/import-background-image-asset-command.js
 [add] src/commands/import-model-asset-command.js
 [add] src/commands/move-box-brush-command.js
 [add] src/commands/resize-box-brush-command.js
 [add] src/commands/rotate-box-brush-command.js
 [add] src/commands/set-box-brush-face-material-command.js
 [add] src/commands/set-box-brush-face-uv-state-command.js
 [add] src/commands/set-box-brush-name-command.js
 [add] src/commands/set-box-brush-transform-command.js
 [add] src/commands/set-entity-name-command.js
 [add] src/commands/set-model-instance-name-command.js
 [add] src/commands/set-player-start-command.js
 [add] src/commands/set-scene-name-command.js
 [add] src/commands/set-world-settings-command.js
 [add] src/commands/upsert-entity-command.js
 [add] src/commands/upsert-interaction-link-command.js
 [add] src/commands/upsert-model-instance-command.js
 [add] src/core/ids.js
 [add] src/core/selection.js
 [add] src/core/tool-mode.js
 [add] src/core/transform-session.js
 [add] src/core/vector.js
 [add] src/core/whitebox-selection-feedback.js
 [add] src/core/whitebox-selection-mode.js
 [add] src/document/brushes.js
 [add] src/document/migrate-scene-document.js
 [add] src/document/scene-document-validation.js
 [add] src/document/scene-document.js
 [add] src/document/world-settings.js
 [add] src/entities/entity-instances.js
 [add] src/entities/entity-labels.js
 [add] src/geometry/box-brush-components.js
 [add] src/geometry/box-brush-mesh.js
 [add] src/geometry/box-brush.js
 [add] src/geometry/box-face-uvs.js
 [add] src/geometry/grid-snapping.js
 [add] src/geometry/model-instance-collider-debug-mesh.js
 [add] src/geometry/model-instance-collider-generation.js
 [add] src/interactions/interaction-links.js
 [add] src/main.js
 [add] src/materials/starter-material-library.js
 [add] src/materials/starter-material-textures.js
 [add] src/rendering/advanced-rendering.js
 [add] src/runner-web/RunnerCanvas.js
 [add] src/runtime-three/first-person-navigation-controller.js
 [add] src/runtime-three/navigation-controller.js
 [add] src/runtime-three/orbit-visitor-navigation-controller.js
 [add] src/runtime-three/player-collision.js
 [add] src/runtime-three/rapier-collision-world.js
 [add] src/runtime-three/runtime-audio-system.js
 [add] src/runtime-three/runtime-host.js
 [add] src/runtime-three/runtime-interaction-system.js
 [add] src/runtime-three/runtime-scene-build.js
 [add] src/runtime-three/runtime-scene-validation.js
 [add] src/serialization/local-draft-storage.js
 [add] src/serialization/scene-document-json.js
 [add] src/shared-ui/HierarchicalMenu.js
 [add] src/shared-ui/Panel.js
 [add] src/shared-ui/world-background-style.js
 [add] src/viewport-three/ViewportCanvas.js
 [add] src/viewport-three/ViewportPanel.js
 [add] src/viewport-three/viewport-entity-markers.js
 [add] src/viewport-three/viewport-focus.js
 [add] src/viewport-three/viewport-host.js
 [add] src/viewport-three/viewport-layout.js
 [add] src/viewport-three/viewport-transient-state.js
 [add] src/viewport-three/viewport-view-modes.js
 [add] tests/domain/box-brush-face-editing.command.test.js
 [add] tests/domain/build-runtime-scene.test.js
 [add] tests/domain/create-box-brush.command.test.js
 [add] tests/domain/create-empty-scene-document.test.js
 [add] tests/domain/editor-store.test.js
 [add] tests/domain/entity.command.test.js
 [add] tests/domain/interaction-links.validation.test.js
 [add] tests/domain/model-import.test.js
 [add] tests/domain/model-instance.command.test.js
 [add] tests/domain/player-start.command.test.js
 [add] tests/domain/rapier-collision-world.test.js
 [add] tests/domain/runtime-audio-system.test.js
 [add] tests/domain/runtime-interaction-system.test.js
 [add] tests/domain/runtime-scene-validation.test.js
 [add] tests/domain/scene-document-validation.test.js
 [add] tests/domain/transform-session.command.test.js
 [add] tests/domain/world-settings.command.test.js
 [add] tests/domain/world-settings.test.js
 [add] tests/e2e/app-smoke.e2e.js
 [add] tests/e2e/box-brush-authoring.e2e.js
 [add] tests/e2e/entities-foundation.e2e.js
 [add] tests/e2e/face-material-authoring.e2e.js
 [add] tests/e2e/first-room-workflow.e2e.js
 [add] tests/e2e/import-draco-model-asset.e2e.js
 [add] tests/e2e/import-external-model-asset.e2e.js
 [add] tests/e2e/import-model-asset.e2e.js
 [add] tests/e2e/local-lights-and-background.e2e.js
 [add] tests/e2e/orthographic-views.e2e.js
 [add] tests/e2e/runner-v1.e2e.js
 [add] tests/e2e/runtime-click-interaction.e2e.js
 [add] tests/e2e/runtime-trigger-teleport.e2e.js
 [add] tests/e2e/viewport-quad-layout.e2e.js
 [add] tests/e2e/viewport-test-helpers.js
 [add] tests/e2e/whitebox-component-selection.e2e.js
 [add] tests/e2e/world-environment.e2e.js
 [add] tests/geometry/box-brush-geometry.test.js
 [add] tests/geometry/box-face-uvs.test.js
 [add] tests/geometry/model-instance-collider-generation.test.js
 [add] tests/helpers/model-collider-fixtures.js
 [add] tests/serialization/local-draft-storage.test.js
 [add] tests/serialization/project-asset-storage.test.js
 [add] tests/serialization/scene-document-json.test.js
 [add] tests/setup/vitest.setup.js
 [add] tests/unit/audio-assets.test.js
 [add] tests/unit/entity-instances.test.js
 [add] tests/unit/package-scripts.test.js
 [add] tests/unit/transform-foundation.integration.test.js
 [add] tests/unit/viewport-canvas.test.js
 [add] tests/unit/viewport-entity-markers.test.js
 [add] tests/unit/viewport-focus.test.js
 [add] tests/unit/viewport-layout.test.js
 [add] tests/unit/viewport-view-modes.test.js
 [add] vite.config.js
 [add] vitest.config.js
2026-04-05 02:25:29 +02:00
b23cb0dd32 Update box brush calculations to use face and vertex IDs 2026-04-05 02:23:16 +02:00
ce5e18641b Update box brush corner position calculation 2026-04-05 02:23:08 +02:00
711289cc9e Add box brush mesh geometry implementation 2026-04-05 02:23:08 +02:00
c02acc32af Add geometry support to BoxBrush and related functions 2026-04-05 02:21:50 +02:00
c25aa3f32b Add tests for axis-constraint rules in transform sessions 2026-04-05 02:02:35 +02:00
26844c5900 Update test expectations for transform button states 2026-04-05 02:02:35 +02:00
69b7864f40 Add tests for face and vertex transform previews with undo/redo 2026-04-05 02:01:34 +02:00
759c84e5af Update test to ensure transform controls are coherent across modes 2026-04-05 02:01:15 +02:00
3e6e343943 Update transform session command tests to resolve component targets correctly and enforce operation support 2026-04-05 02:01:10 +02:00
38c9d8a8c5 Update box brush rotation handling 2026-04-05 01:58:12 +02:00
7262824e0f Extend transform gizmo handling for additional brush types 2026-04-05 01:58:06 +02:00
0845ac436c Add methods for creating and updating brush previews in ViewportHost 2026-04-05 01:57:59 +02:00
30f4a24571 Refactor brush transformation pivot position calculation in viewport-host.ts 2026-04-05 01:57:17 +02:00
5dce46904d Add support for brush face, edge, and vertex transformations in ViewportHost 2026-04-05 01:56:52 +02:00
086405f55b Update viewport-host.ts with additional geometry functions 2026-04-05 01:56:36 +02:00
865f6ae859 Add set box brush transform command and update commit transform session command 2026-04-05 01:56:31 +02:00
924b0c93fe Add support for brush face, edge, and vertex transform targets in transform session 2026-04-05 01:56:13 +02:00
f6ed103be3 Add transformation metadata and functions for box brush components 2026-04-05 01:55:51 +02:00
251 changed files with 57468 additions and 4784 deletions

677
AGENTS.md
View File

@@ -1,562 +1,247 @@
# AGENTS.md
## Project identity
## Purpose
This repository contains a browser-based engine/editor for creating interactive 3D environments, with a built-in browser runner for immediate playtesting.
This is the mandatory high-signal brief for agents working in this repo.
The product goal is:
Read this file first.
Then read `CHAT_CONTEXT.md`.
After that, inspect the code and open only the relevant sections of `architecture.md`, `roadmap.md`, and `testing.md`.
- 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
Do not read the large docs end-to-end by default.
This is not a general-purpose DCC.
This is not an unlimited AAA engine platform.
This is a focused engine/editor for browser-delivered interactive 3D environments.
When docs and code disagree:
1. trust the code for current behavior
2. trust `AGENTS.md` + `CHAT_CONTEXT.md` for current intent
3. use the larger docs as selective reference
4. update stale docs if your slice materially changes behavior
---
## Product pillars
## Product
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.
This repo is a browser-based engine/editor for interactive 3D environments with a built-in runner.
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.
Core loop:
3. **Imported assets are first-class**
- glTF / GLB import must feel native.
- Imported meshes, materials, textures, and animations must coexist cleanly with whitebox-authored worlds.
- Imported assets complement whiteboxing; they do not replace it.
1. author
2. save/load
3. run immediately in-browser
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.
Primary product priorities:
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.
- intuitive whiteboxing / level blocking
- imported assets as first-class content
- typed entities and simple interactions
- very fast edit -> run iteration
- web-native delivery and sharing
This is not:
- a Blender replacement
- a general CAD tool
- an unlimited engine platform
- a full physics sandbox unless the roadmap explicitly says so
---
## Architectural stance
## Hard Rules
When making design decisions, prefer:
### Canonical state
- plain three.js over unnecessary abstraction
- explicit data models over implicit scene graph state
- deterministic rebuilds over hidden mutations
- command-based editing over ad hoc state changes
- typed scene entities over free-form JSON blobs
- vertical slices over speculative infrastructure
- boring, maintainable code over cleverness
- The canonical `SceneDocument` / project state is the source of truth.
- Do not store three.js objects in canonical document state.
- Do not make the three.js scene graph the source of truth.
- Editor-authored mutations should go through commands.
The project uses:
### Layering
- React for application shell and editor UI
- three.js for viewport and runtime rendering
- a canonical editor document model independent of three.js
- command pattern for undo/redo
- runtime entity systems for navigation, triggers, audio, and interaction
- glTF / GLB as the main imported 3D asset format
- JSON as the canonical authoring format
Do not collapse editor state into raw three.js objects.
Do not make the three.js scene the source of truth.
Do not make glTF the canonical editor save format.
---
## Early binding decisions
These defaults are intentionally fixed for the early slices unless a later slice explicitly changes them.
### Coordinate system
- world space is right-handed and **Y-up**
- `+X` is right, `+Y` is up
- scene units are meter-like and should be used consistently for movement, collision, and audio distances
### Early repo shape
- start as a single Vite app
- keep domain folders under `src/`
- do not introduce `/apps` + `/packages` or a monorepo split until the current code actually needs it
### State ownership
- do not use the React tree as the canonical state container
- keep canonical editor state in a thin external editor store/service
- React renders and dispatches commands; it does not own the document
- `document` owns canonical state
- `commands` own undoable mutations
- `geometry` owns derived solid/mesh/collider generation
- `viewport-three` owns editor rendering and interaction helpers
- `runtime-three` owns play-mode runtime behavior
- `entities` own typed non-model scene objects
- `assets` own imported external resources and adapters
- `serialization` owns save/load/versioning/migrations
### Persistence
- the canonical scene document is versioned from day one
- M0-M2 may use local draft persistence plus explicit JSON import/export
- once binary assets matter, user-facing save/load must become a portable project package containing canonical scene JSON plus referenced assets
- canonical scene JSON remains the source document format, but by itself is no longer a portable project once external assets exist
- runner/deployment output is a separate downstream package, not the editable project format
- 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
- The document is versioned from day one.
- If persisted schema changes, update version/migration/validation and add at least one compatibility test.
- Canonical save format is project JSON.
- Once binary assets matter, user-facing save/load must be a portable project package containing canonical JSON plus referenced assets.
- Runner/deployment output is separate from editable save/load.
- Never rely on Blob URLs as the only persisted asset reference.
### Current box-solid defaults
### Models, entities, world
- early slices began with axis-aligned box brushes
- canonical box face IDs are fixed and stable:
- `posX`
- `negX`
- `posY`
- `negY`
- `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
- Imported assets live in the asset registry.
- Placed imported models live in `modelInstances`.
- `modelInstances` are not `entities`.
- Typed runtime/editor objects such as `PlayerStart`, `TriggerVolume`, and lights live in `entities`.
- Global ambient/sun/background/fog belong in `world` settings.
- Local authored lights belong in typed entity schemas.
### Whitebox geometry direction
### Imported model collision
- 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
### Whitebox editing scope
- 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
---
## Non-goals
Unless explicitly added to the roadmap, do not turn this project into:
- a general CAD package
- a Blender replacement
- a multiplayer MMO editor
- a full node-based visual scripting environment
- a full physics sandbox
- a photoreal AAA renderer
- a React Three Fiber showcase
- an ECS research project
We may add optional scripting, plugins, collaboration, or advanced baking later.
They are not v1 priorities.
---
## Core product vocabulary
Use these terms consistently:
- **Document**: canonical editor state
- **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
- **Runner Package**: deployable playable output for the built-in runner
- **Runner**: browser runtime that loads and plays scenes
- **Viewport**: editor rendering surface
- **Command**: undoable state transition
- **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
Avoid vague terms like “object”, “thing”, “item”, or “component” when a more precise domain term exists.
---
## Repo expectations for agents
When working in this repo:
1. Read:
- `AGENTS.md`
- `CHAT_CONTEXT.md`
- then inspect the relevant sections of `architecture.md`, `roadmap.md`, and `testing.md` for the active slice
- if a slice touches persistence, runtime, or testing boundaries in a non-obvious way, read the relevant full doc sections before changing code
2. Respect the current vertical slice.
- Do not “prepare for future flexibility” by adding unnecessary systems.
- Implement the smallest coherent version that preserves the architecture.
3. Preserve layering.
- `document` owns canonical state.
- `commands` apply valid state changes.
- `geometry` owns derived solid and collider generation.
- `viewport-three` renders editor state.
- `runtime-three` plays runtime state.
- `entities` owns typed non-brush scene objects.
- `assets` adapts external asset/audio/media formats.
- `serialization` persists canonical state.
4. Do not bypass command infrastructure for editor mutations.
- If the user can do it in the editor, it should usually be represented as a command.
5. If persisted schema changes, update compatibility explicitly.
- bump the document schema version when required
- add or update migrations
- add at least one migration or compatibility test
6. Prefer explicit typing and explicit invariants.
- Avoid permissive `any`, loose maps, or magic strings when a discriminated union or typed schema is appropriate.
7. Keep systems testable.
- Geometry generation should be testable outside the browser UI.
- Serialization should be round-trip tested.
- Runtime interactions should be testable through deterministic fixtures where possible.
8. Keep browser concerns in mind.
- Gracefully handle pointer lock failure, audio unlock requirements, missing gamepads, and asset load failures.
- Avoid architecture that assumes native desktop privileges.
---
## Code quality rules
### General
- TypeScript only
- strict typing enabled
- prefer pure functions for transforms/build steps
- isolate impure browser/three.js side effects
- no silent catch-and-ignore
- no dead feature flags without roadmap justification
- no hidden singleton globals unless explicitly part of infrastructure
### Naming
- use descriptive names
- prefer domain names over generic utility names
- avoid abbreviations unless they are standard and obvious
- function names should describe intent, not implementation detail
Good:
- `buildRuntimeSceneFromDocument`
- `applyMaterialToSelectedFaces`
- `createBoxBrushCommand`
Bad:
- `handleThing`
- `updateData`
- `doBuild`
### File organization
- small files where it helps clarity
- split by domain, not by arbitrary technical categories
- avoid giant “misc” or “utils” dumping grounds
- every folder should have a clear reason to exist
### Comments
- explain *why*, not what the code obviously does
- use comments to document invariants, constraints, and tricky browser behavior
- remove stale comments promptly
### Error handling
- fail loudly in development
- surface usable diagnostics in the editor UI
- never corrupt the document silently
- preserve previous valid state on failed builds where possible
---
## Data model rules
The canonical authoring state must remain independent from three.js scene graph objects.
### Required separation
Maintain these layers:
1. **Authoring model**
- JSON-serializable
- versioned
- typed
- stable across runtime/editor rebuilds
2. **Editor view model**
- three.js meshes, helpers, overlays, gizmos
- disposable and rebuildable
3. **Runtime model**
- play-mode scene graph
- controllers, triggers, emitters, colliders, animation mixers
Do not let editor-only helpers leak into the canonical document.
Do not store raw three.js objects inside canonical document state.
### Whitebox geometry rules
- whitebox solids are canonical authoring objects, not raw renderer state
- face material assignments are per-face
- UV transforms are canonical editor data
- render triangulation is derived data
- collision generation is derived data
- 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
- entities must be typed
- entity schemas must be explicit
- entity defaults must be centralized
- 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:
- Collision authoring for imported models belongs on `modelInstances`, not assets.
- Supported imported-model collision modes must stay explicit and typed.
- Generated collision data is derived data, not canonical source data.
- If broad-phase/narrow-phase pruning or non-box collider support is needed, prefer Rapier over custom collision math.
- Collision mode meanings are fixed unless deliberately changed:
- `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
---
### Whiteboxing direction
## Performance rules
Performance matters, but premature micro-optimization does not.
Priorities:
1. editor responsiveness during common operations
2. deterministic rebuild behavior
3. predictable memory usage
4. runtime smoothness for modest scenes
5. export/build correctness
When optimizing:
- measure first
- optimize hotspots, not aesthetics
- document assumptions
- prefer algorithmic improvements over clever hacks
Expected hotspots:
- picking/raycasting
- whitebox mesh rebuilds / solid triangulation
- face highlighting
- large texture browser lists
- imported asset previews
- runtime trigger scanning if implemented naively
- The product is moving away from grid-bound brush thinking toward whitebox solids.
- Floating point position/rotation/scale are allowed.
- The grid is a snap/reference helper, not a hard law.
- Whiteboxing should converge on one coherent transform-driven interaction model.
- Object / face / edge / vertex editing are valid goals.
- Non-planar quads are acceptable if derived triangulation is deterministic.
- Whitebox solids do not have to remain convex.
- Collision should come from the solid collider path, not old axis-aligned assumptions.
---
## UX rules
## Implementation Strategy
The editor should feel like a real authoring tool, not a tech demo.
### Default workflow
1. Inspect the current repo first.
2. Extend the existing implementation.
3. Keep the slice as small and vertical as possible.
4. Reuse existing paths instead of adding parallel architecture.
5. Verify with the narrowest relevant checks.
### Vertical slices
Good slice:
- document changes
- commands
- viewport/editor behavior
- UI
- persistence
- runner behavior if relevant
- tests
- brief manual QA notes
Bad slice:
- scaffolding with no user-facing payoff
- duplicate systems
- speculative abstractions
### Read selectively
Only open full reference sections when needed:
- `architecture.md` for non-trivial runtime/editor/data-model boundaries
- `roadmap.md` for future direction and accepted scope
- `testing.md` for which test layers to add
If the slice is local and obvious, do not reload half the repo’s docs.
---
## Code Rules
### Do
- use TypeScript only
- keep types explicit
- prefer pure functions for transforms/build steps
- isolate browser/three.js side effects
- fail loudly in development
- surface useful diagnostics instead of silently ignoring errors
- keep geometry/collision generation testable outside the browser where practical
### Don’t
- add R3F casually
- add ECS casually
- over-generalize the entity system
- replace canonical whitebox data with hidden renderer-only mutations
- invent hidden magic behavior without schema support
- remove tests to get green CI
- silently corrupt state on failure
---
## UX Rules
Prioritize:
- fast selection
- trustworthy snapping when enabled
- visible grid and transform feedback
- obvious active tool state
- low-friction material application
- direct transforms
- understandable tool state
- visible feedback
- quick play testing
- understandable errors
- clear failure modes
Every new feature should answer:
- What does the user see?
- What does the user click/drag/type?
- How is failure communicated?
- How is the action undone?
- How is the result tested?
Every meaningful feature should answer:
- what the user sees
- what the user clicks/drags/types
- how it is undone
- how failure is shown
- how it is tested
---
## Vertical slice policy
## Testing Rules
We build in vertical slices.
Each slice must deliver a complete, usable capability across all relevant layers.
At minimum, match the slice:
A good slice includes:
- document changes
- commands
- viewport behavior
- UI panel updates
- runner behavior if relevant
- persistence
- tests
- manual QA notes
- pure/domain tests for deterministic logic
- serialization tests for persisted features
- runtime/build tests where runtime behavior changes
- browser/e2e only when real browser behavior matters
A bad slice is “just backend structure” or “just a partial UI”.
If schema changes:
Do not land architectural scaffolding that has no immediate use in the current slice.
- add round-trip coverage
- add migration/compatibility coverage
If a roadmap item is too large for one pass, split it into smaller end-to-end sub-slices instead of landing half-systems.
Prefer small explicit fixtures over giant snapshots.
---
## Typical slice shape
## Vocabulary
For each slice, agents should aim to deliver:
Use precise terms:
1. domain model changes
2. command(s)
3. viewport interaction/tooling
4. UI affordance
5. serialization support
6. runtime/build support if needed
7. tests
8. docs update if behavior changed materially
- `Document`: canonical editor state
- `Whitebox Solid`: author-authored blockout / gameplay-space solid
- `Box Solid`: the first whitebox solid shape; old code may still say “box brush”
- `Face` / `Edge` / `Vertex`: editable parts of a whitebox solid
- `Asset`: imported external resource
- `Model Instance`: placed instance of an imported asset
- `Entity`: typed scene object with editor/runtime semantics
- `Collider`: derived runtime collision representation
- `Project Package`: portable editable bundle
- `Runner Package`: deployable playable output
- `Build`: deterministic document -> runtime transformation
Avoid vague terms like “thing” or “object” when a domain term exists.
---
## Decision heuristics
## Required Closeout
When uncertain:
### Prefer plain three.js over extra abstraction
Unless abstraction clearly simplifies repeated patterns.
### Prefer canonical JSON over reusing runtime/export data structures
The editor’s needs are different from export/runtime needs.
### Prefer typed entity schemas over generic script bags
Especially in early versions.
### Prefer constrained capabilities that feel good over flexible capabilities that feel vague
Example:
- 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.
---
## What agents must not do
Do not:
- rewrite broad project structure without a strong reason
- introduce new framework dependencies casually
- add R3F because “we might want it later”
- introduce ECS because “games use ECS”
- over-generalize the entity system
- 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
- ignore browser restrictions around input/audio
---
## Required deliverables in implementation responses
When making meaningful changes, include:
For meaningful changes, report briefly:
1. what changed
2. why it changed
3. which files were added/updated
4. how to run/test it
2. why
3. files touched
4. how you verified it
5. known limitations
6. follow-up suggestions only if directly relevant
If the environment prevents verification, state exactly what was and was not verified.
---
## Definition of done for a slice
A slice is done when:
- the feature can be used end-to-end
- the feature is represented in canonical document data
- the feature can be saved and loaded
- the feature is test-covered appropriately
- the feature has manual verification notes
- the feature does not violate the architecture
- obvious failures produce usable diagnostics
- undo/redo works if the feature is editor-authored
---
## Preferred stack unless changed deliberately
- TypeScript
- React
- Vite
- three.js
- Vitest
- Playwright
- ESLint
- Prettier
- a small state store if needed
- minimal dependencies overall
Add dependencies only when they clearly save time and complexity over building in-house.
---
## Final instruction to agents
Build the smallest coherent thing that feels real.
The product should always trend toward:
- spatial immediacy
- authoring clarity
- browser-native practicality
- fast iteration
- strong foundations for whiteboxing, assets, entities, and runner behavior
If forced to choose, preserve the integrity of:
1. the canonical document model
2. the whiteboxing workflow
3. the edit -> run loop
If you could not verify something, say so plainly.

View File

@@ -1,198 +1,139 @@
# CHAT_CONTEXT.md
This file is the lightweight startup context for new Codex chats.
This file is the small startup brief for new implementation chats.
Read this after `AGENTS.md`.
Then inspect only the relevant sections of `architecture.md`, `roadmap.md`, and `testing.md` for the active slice.
Then inspect the code.
Then open only the relevant sections of `architecture.md`, `roadmap.md`, and `testing.md`.
This file does not replace the full docs.
It exists to keep new chats focused and to reduce repeated context load.
The large docs are reference docs, not mandatory full reads.
---
## Product summary
## Current Status
This repo is a browser-based 3D scene authoring tool with a built-in runner.
As of now, the repo is no longer in the very early “empty skeleton” phase.
Core loop:
Broadly implemented already:
1. author a scene
2. save/load it reliably
3. run it in-browser immediately
- foundational document/command/persistence/test setup
- box-based room authoring and per-face materials / UVs
- built-in runner with edit -> run loop
- world settings / lighting / environment basics
- typed entities and trigger/action/target interaction flow
- GLB/GLTF model import and model instances
- local lights, animation playback, spatial audio
- advanced rendering
- better material-library workflow
- runner package / embeddable runner work
- multi-viewport editor foundations
- unified creation/placement foundations
- transform foundations
The product prioritizes:
Important consequence:
- intuitive whiteboxing / level blocking for interactive 3D environments
- imported assets as first-class additions
- typed entities and simple interactions
- browser-native delivery
- many roadmap sections are now historical context, not literal todo items
- do not assume Milestone 0-3 are untouched just because they are still documented
It is not:
- an unlimited general-purpose engine platform
- a Blender replacement
- a general CAD tool
- an R3F showcase
When in doubt, inspect the current code before trusting old milestone wording.
---
## Hard architectural rules
## Current Product Direction
- The canonical `SceneDocument` is the source of truth.
- The document must stay independent from three.js objects.
- Editor-authored mutations should flow through commands.
- The editor viewport is derived from the document.
- The runner is a sibling system, not an editor hack.
- Canonical document format is project JSON, not glTF/GLB.
- Portable save/load for asset-bearing scenes should use a project package built around that JSON.
- Runner/deployment output is downstream from the document/runtime build and is separate from editable project save/load.
- Model instances are separate from typed entities.
The product is a browser-native engine/editor for interactive 3D environments.
Key direction:
- intuitive whiteboxing / level blocking
- imported assets as first-class content
- typed entities and runtime interactions
- fast built-in runner workflow
The geometry direction is shifting from old grid-bound “brush” thinking toward whitebox solids:
- floating point transforms allowed
- free object rotation allowed
- grid is optional snap/reference help
- object / face / edge / vertex editing should converge on one transform-driven model
- non-planar quads are acceptable if triangulated deterministically
- non-convex whitebox solids are acceptable if the solid mesh/collider path supports them
Old code and docs may still say “brush” in places.
Treat current box-brush structures as the starting point for whitebox solids unless the slice deliberately changes that.
---
## Early binding decisions
## Hard Current Assumptions
These are fixed for the early milestones unless a later slice explicitly changes them.
- world is right-handed and Y-up
- canonical state lives outside the React tree
- document/project state remains source of truth
- editor changes should flow through commands
- model instances remain separate from entities
- world settings own global background / ambient / sun / fog
- local authored lights stay in typed entities
- project save/load and runner export are separate concerns
### Coordinates and units
Imported model collision:
- world is right-handed and **Y-up**
- `+X` is right
- `+Y` is up
- units are meter-like
### Repo shape
- keep the repo as a single Vite app
- keep domain folders under `src/`
- do not split into a monorepo early
### State ownership
- do not use the React tree as the canonical state container
- keep canonical state in a thin external editor store/service
### Persistence
- version the document from day one
- keep migrations explicit
- early project persistence can be local draft storage plus JSON import/export
- once binary assets exist, portable save/load should use a project package such as `scene.json` plus bundled assets
- canonical JSON stays the source document format underneath that project package
- runner package output is a separate deployable artifact
- binary assets must survive reload via embedded or project-scoped persistent storage
- never rely on Blob URLs as the only persisted asset reference
### Current box-solid foundation
- early slices began with an axis-aligned box shape and stable face IDs
- stable box face IDs are:
- `posX`
- `negX`
- `posY`
- `negY`
- `posZ`
- `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:
- `offset`
- `scale`
- `rotationQuarterTurns`
- `flipU`
- `flipV`
“Fit to face” should rewrite explicit values, not add a magical persistent flag.
### Model placement
- 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
- keep `Trigger -> Action -> Target` typed and explicit
- do not add actions for systems that do not exist yet
### World environment vs local lights
- global background / ambient / sun / fog belong in `world` settings
- local authored lights belong in typed entity schemas
- true skyboxes or environment textures belong after persistent asset storage exists
- authored collision settings belong on `modelInstances`
- generated collider data is derived, not canonical
- if non-box collider support needs broad-phase/narrow-phase pruning, prefer Rapier over custom app-side collision math
---
## What a good slice looks like
## Reading Strategy
Each slice should land the smallest coherent end-to-end version of the feature across the layers it touches:
Default:
- document data
- commands
- viewport behavior
- runner behavior if relevant
- persistence
- UI
- tests
1. read `AGENTS.md`
2. read this file
3. inspect the code paths touched by the slice
4. open only the relevant sections of:
- `architecture.md`
- `roadmap.md`
- `testing.md`
Do not land speculative scaffolding with no immediate slice use.
Open the larger docs only when needed:
If a roadmap item is too large, split it into smaller vertical slices.
- `architecture.md`
- data-model boundaries
- runtime/editor integration
- geometry/collision semantics
- persistence/export/package architecture
- `roadmap.md`
- whether a direction is already chosen
- whether something is intentionally deferred
- how a large topic should be split into slices
- `testing.md`
- what test layers to add
- schema/migration expectations
- browser/e2e guidance
If the slice is small and local, do not reread unrelated doc sections.
---
## Required habits for implementation
## What To Be Careful About
- Inspect the current repo first.
- Extend the current implementation instead of restarting architecture.
- If persisted schema changes, update versioning/migrations and add a compatibility test.
- Run the narrowest relevant checks you can.
- Report what was actually verified.
- do not restart architecture just because the original docs were written earlier
- extend existing paths instead of introducing parallel systems
- if docs and code disagree on current behavior, trust the code and update docs if your slice changes direction materially
- keep responses brief and verification scoped to the actual slice
---
## Early slice ordering to keep in mind
## Likely Near-Term Themes
- M0: foundation, document, commands, persistence, test setup
- 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
The next large topics are more likely to be things like:
That ordering matters because:
- whitebox-solid editing model
- multi-scene / project structure
- richer runtime systems
- remaining packaging / portability work
- future primitives and topology tools after the whitebox direction is coherent
- world settings do not need entity or asset pipelines
- local lights need the entity system
- skyboxes need persistent asset storage
- animation and audio actions should land only with those runtime systems
---
## When to open the full docs
Open the relevant full sections when:
- persistence schema changes
- runtime/editor boundaries are being touched
- a slice adds new tests or new failure modes
- geometry semantics are non-trivial
- import/export behavior changes
Otherwise, stay focused on the active slice and keep the implementation small.
Do not assume the old prompt list is still the whole plan.

View File

@@ -1,5 +1,12 @@
# architecture.md
Use this as a selective reference doc.
Do not read this file end-to-end by default.
Read only the headings relevant to the active slice after reading `AGENTS.md`, `CHAT_CONTEXT.md`, and inspecting the current code.
If examples in this file lag behind the code, trust the code for current behavior and update the docs when your slice materially changes direction.
## Overview
This project is a browser-based 3D scene authoring tool with a built-in runtime runner.
@@ -365,15 +372,24 @@ Rules:
- no three.js object references
- should be testable in isolation
Example structure:
Example persisted project structure:
```ts
interface SceneDocument {
interface ProjectDocument {
version: number;
world: WorldSettings;
name: string;
activeSceneId: string;
scenes: Record<string, ProjectScene>;
materials: Record<string, MaterialDef>;
textures: Record<string, TextureDef>;
assets: Record<string, AssetRecord>;
}
interface ProjectScene {
id: string;
name: string;
loadingScreen: SceneLoadingScreenSettings;
world: WorldSettings;
brushes: Record<string, Brush>;
modelInstances: Record<string, ModelInstance>;
entities: Record<string, EntityInstance>;
@@ -575,7 +591,7 @@ Near-term runtime collision is intentionally narrower than a full game-engine ph
Initial modes:
- first-person
- orbit visitor
- third-person
Later optional modes:
@@ -584,6 +600,8 @@ Later optional modes:
- click-to-teleport
- controller-supported variants where applicable
Every new movement mode or controller feature must ship with default keyboard and standard-gamepad bindings, even if the authored inspector UI stays simple.
These modes should share a common interface:
```ts
@@ -831,6 +849,8 @@ At that point, the user-facing save/load format should be a **project package**
- `scene.json`
- referenced asset payloads
`scene.json` may still contain multiple authored scenes inside one project document; the file name does not imply a single loaded runtime scene.
Recommended logical shape:
```txt

View File

@@ -18,6 +18,7 @@
},
"dependencies": {
"@dimforge/rapier3d-compat": "^0.19.3",
"fflate": "^0.8.2",
"postprocessing": "^6.39.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",

29
playwright.config.js Normal file
View File

@@ -0,0 +1,29 @@
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests/e2e",
testMatch: ["**/*.e2e.ts"],
timeout: 30_000,
expect: {
timeout: 5_000
},
use: {
baseURL: "http://127.0.0.1:4173",
trace: "on-first-retry"
},
projects: [
{
name: "chromium",
use: {
...devices["Desktop Chrome"],
launchOptions: {
args: ["--enable-webgl", "--use-gl=angle", "--use-angle=swiftshader-webgl"]
}
}
}
],
webServer: {
command: "npm run dev -- --host 127.0.0.1 --port 4173",
url: "http://127.0.0.1:4173",
reuseExistingServer: !process.env.CI
}
});

View File

@@ -1,5 +1,12 @@
# roadmap.md
Use this as a direction/scope doc, not as proof that every earlier slice is still unimplemented.
Do not read this file end-to-end by default.
Read only the relevant milestone/slice headings after checking the current code.
Completed or partially completed historical slices may still be documented here for context.
## Overview
This roadmap is organized as vertical slices.
@@ -180,7 +187,7 @@ This is the first proof that the product is real.
- runtime build from document
- first-person navigation
- orbit visitor mode
- third-person mode
- mode switch
- minimal typed `PlayerStart` support
- basic collision against axis-aligned box brush geometry
@@ -190,7 +197,7 @@ This is the first proof that the product is real.
- user can press Run and navigate the scene
- first-person works with keyboard/mouse
- orbit visitor works
- third-person works
- leaving run mode returns to editor state safely
- `PlayerStart` does not need to be rebuilt later as a separate foundation

3615
src/app/App.js Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -32,7 +32,11 @@ body {
min-height: 100vh;
overflow: hidden;
background:
radial-gradient(circle at top, rgba(80, 96, 120, 0.35) 0%, rgba(23, 28, 37, 0) 42%),
radial-gradient(
circle at top,
rgba(80, 96, 120, 0.35) 0%,
rgba(23, 28, 37, 0) 42%
),
linear-gradient(180deg, #1b2029 0%, #101318 100%);
color: var(--color-text);
}
@@ -74,6 +78,7 @@ button:disabled {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 12px;
padding: 8px 14px;
background: rgba(18, 22, 28, 0.88);
@@ -103,12 +108,37 @@ button:disabled {
line-height: 1.2;
}
.toolbar__scene-controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
flex: 1 1 520px;
min-width: 260px;
}
.toolbar__project-name {
flex: 1 1 240px;
min-width: 180px;
max-width: 320px;
}
.toolbar__scene-picker {
flex: 0 1 220px;
min-width: 160px;
}
.toolbar__scene-name {
flex: 1 1 320px;
min-width: 220px;
min-width: 180px;
max-width: 460px;
}
.toolbar__scene-select {
min-height: 36px;
width: 100%;
}
.toolbar__actions {
display: flex;
align-items: center;
@@ -176,6 +206,7 @@ button:disabled {
box-shadow: inset 0 0 0 1px rgba(255, 241, 213, 0.28);
}
.toolbar__project-name-input,
.toolbar__scene-name-input {
height: 36px;
padding: 0 12px;
@@ -185,7 +216,10 @@ button:disabled {
.workspace {
display: grid;
grid-template-columns: minmax(240px, 280px) minmax(0, 1fr) minmax(280px, 320px);
grid-template-columns: minmax(240px, 280px) minmax(0, 1fr) minmax(
280px,
320px
);
gap: 12px;
min-height: 0;
overflow: hidden;
@@ -278,7 +312,11 @@ button:disabled {
.stat-card {
padding: 12px;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.02) 100%);
background: linear-gradient(
180deg,
rgba(255, 255, 255, 0.04) 0%,
rgba(255, 255, 255, 0.02) 100%
);
border: 1px solid var(--color-border);
border-radius: 14px;
}
@@ -970,7 +1008,11 @@ button:disabled {
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%),
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%);
}
@@ -1127,7 +1169,11 @@ button:disabled {
gap: 8px;
padding: 18px;
color: #f3e8da;
background: linear-gradient(180deg, rgba(8, 10, 14, 0.12) 0%, rgba(8, 10, 14, 0.58) 100%);
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: auto;
@@ -1141,6 +1187,78 @@ button:disabled {
text-transform: uppercase;
}
.runner-canvas__loading-overlay {
position: absolute;
inset: 0;
z-index: 5;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
opacity: 1;
visibility: visible;
transition:
opacity 240ms ease,
visibility 240ms ease;
pointer-events: auto;
}
.runner-canvas__loading-overlay--hidden {
opacity: 0;
visibility: hidden;
pointer-events: none;
}
.runner-canvas__loading-card {
width: min(480px, 100%);
display: flex;
flex-direction: column;
gap: 10px;
padding: 20px 22px;
color: #f6efe5;
background: rgba(8, 10, 14, 0.68);
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 18px;
box-shadow: 0 28px 52px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
}
.runner-canvas__loading-badge {
color: var(--color-accent-strong);
font-size: 0.72rem;
font-weight: 700;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.runner-canvas__loading-scene-name {
font-size: 1.3rem;
font-weight: 700;
line-height: 1.2;
}
.runner-canvas__loading-headline {
font-size: 1rem;
font-weight: 600;
line-height: 1.35;
}
.runner-canvas__loading-description {
color: rgba(246, 239, 229, 0.78);
font-size: 0.92rem;
line-height: 1.5;
}
.runner-canvas__loading-error {
padding: 10px 12px;
color: #ffd9cf;
background: rgba(110, 18, 6, 0.34);
border: 1px solid rgba(255, 170, 149, 0.18);
border-radius: 12px;
font-size: 0.85rem;
line-height: 1.45;
}
.runner-canvas__crosshair {
position: absolute;
top: 50%;
@@ -1163,6 +1281,26 @@ button:disabled {
border-radius: 999px;
}
.runner-canvas--underwater {
box-shadow: inset 0 0 0 9999px rgba(9, 38, 62, 0.08);
}
.runner-canvas__underwater {
position: absolute;
inset: 0;
z-index: 2;
pointer-events: none;
background:
radial-gradient(
circle at 50% 18%,
rgba(146, 223, 255, 0.2),
transparent 42%
),
linear-gradient(180deg, rgba(38, 113, 153, 0.16), rgba(8, 40, 63, 0.42));
backdrop-filter: blur(1.5px) saturate(1.08);
mix-blend-mode: screen;
}
.runner-canvas__prompt {
position: absolute;
left: 50%;
@@ -1206,9 +1344,10 @@ button:disabled {
display: flex;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
flex-wrap: nowrap;
gap: 12px;
min-height: 36px;
height: 36px;
padding: 6px 12px;
background: rgba(18, 22, 28, 0.88);
border: 1px solid var(--color-border);
@@ -1216,13 +1355,24 @@ button:disabled {
color: var(--color-muted);
font-size: 0.8rem;
line-height: 1.2;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: thin;
}
.status-bar__item {
display: flex;
align-items: baseline;
gap: 4px;
flex: 0 0 auto;
min-width: 0;
white-space: nowrap;
}
.status-bar__item--message {
flex: 1 1 320px;
overflow: hidden;
text-overflow: ellipsis;
}
.status-bar__item--asset {
@@ -1304,6 +1454,18 @@ button:disabled {
.status-bar {
flex-direction: column;
align-items: flex-start;
height: auto;
padding: 12px 16px;
overflow: visible;
}
.status-bar__item {
white-space: normal;
}
.status-bar__item--message,
.status-bar__item--asset {
overflow: visible;
text-overflow: clip;
}
}

391
src/app/editor-store.js Normal file
View File

@@ -0,0 +1,391 @@
import { CommandHistory } from "../commands/command-history";
import { areEditorSelectionsEqual, normalizeSelectionForWhiteboxSelectionMode } from "../core/selection";
import {} from "../core/whitebox-selection-mode";
import { areTransformSessionsEqual, cloneTransformSession, createInactiveTransformSession } from "../core/transform-session";
import { createEmptySceneDocument } from "../document/scene-document";
import { DEFAULT_SCENE_DRAFT_STORAGE_KEY, loadSceneDocumentDraft, saveSceneDocumentDraft } from "../serialization/local-draft-storage";
import { parseSceneDocumentJson, serializeSceneDocument } from "../serialization/scene-document-json";
import { areViewportToolPreviewsEqual, cloneViewportToolPreview, createDefaultViewportTransientState, isViewportToolPreviewCompatible } from "../viewport-three/viewport-transient-state";
import { areViewportPanelCameraStatesEqual, cloneViewportLayoutState, cloneViewportPanelCameraState, createDefaultViewportLayoutState } from "../viewport-three/viewport-layout";
export class EditorStore {
document;
selection = { kind: "none" };
whiteboxSelectionMode = "object";
toolMode = "select";
viewportLayoutMode;
activeViewportPanelId;
viewportPanels;
viewportQuadSplit;
viewportTransientState = createDefaultViewportTransientState();
previousEditingToolMode = "select";
history = new CommandHistory();
listeners = new Set();
storage;
storageKey;
lastCommandLabel = null;
snapshot;
commandContext = {
getDocument: () => this.document,
setDocument: (document) => {
this.document = document;
},
getSelection: () => this.selection,
setSelection: (selection) => {
this.selection = selection;
},
getToolMode: () => this.toolMode,
setToolMode: (toolMode) => {
this.toolMode = toolMode;
}
};
constructor(options = {}) {
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();
}
subscribe = (listener) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
getState = () => this.snapshot;
setToolMode(toolMode) {
if (this.toolMode === toolMode) {
return;
}
if (toolMode !== "play") {
this.previousEditingToolMode = toolMode;
}
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) {
if (this.viewportLayoutMode === viewportLayoutMode) {
return;
}
this.viewportLayoutMode = viewportLayoutMode;
this.emit();
}
setActiveViewportPanel(panelId) {
if (this.activeViewportPanelId === panelId) {
return;
}
this.activeViewportPanelId = panelId;
this.emit();
}
setViewportPanelViewMode(panelId, viewMode) {
if (this.viewportPanels[panelId].viewMode === viewMode) {
return;
}
this.viewportPanels = {
...this.viewportPanels,
[panelId]: {
...this.viewportPanels[panelId],
viewMode
}
};
this.emit();
}
setViewportPanelDisplayMode(panelId, displayMode) {
if (this.viewportPanels[panelId].displayMode === displayMode) {
return;
}
this.viewportPanels = {
...this.viewportPanels,
[panelId]: {
...this.viewportPanels[panelId],
displayMode
}
};
this.emit();
}
setViewportPanelCameraState(panelId, cameraState) {
if (areViewportPanelCameraStatesEqual(this.viewportPanels[panelId].cameraState, cameraState)) {
return;
}
this.viewportPanels = {
...this.viewportPanels,
[panelId]: {
...this.viewportPanels[panelId],
cameraState: cloneViewportPanelCameraState(cameraState)
}
};
this.emit();
}
setViewportQuadSplit(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) {
const nextToolPreview = cloneViewportToolPreview(toolPreview);
if (areViewportToolPreviewsEqual(this.viewportTransientState.toolPreview, nextToolPreview)) {
return;
}
this.viewportTransientState = {
...this.viewportTransientState,
toolPreview: nextToolPreview
};
this.emit();
}
clearViewportToolPreview(sourcePanelId) {
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) {
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) {
if (this.viewportTransientState.transformSession.kind !== "active") {
return;
}
if (this.viewportTransientState.transformSession.axisConstraint === axisConstraint) {
return;
}
this.viewportTransientState = {
...this.viewportTransientState,
transformSession: {
...cloneTransformSession(this.viewportTransientState.transformSession),
axisConstraint
}
};
this.emit();
}
setViewportViewMode(viewportViewMode) {
this.setViewportPanelViewMode(this.activeViewportPanelId, viewportViewMode);
}
enterPlayMode() {
if (this.toolMode === "play") {
return;
}
this.previousEditingToolMode = this.toolMode;
this.toolMode = "play";
if (this.viewportTransientState.toolPreview.kind !== "none") {
this.viewportTransientState = createDefaultViewportTransientState();
}
this.emit();
}
exitPlayMode() {
if (this.toolMode !== "play") {
return;
}
this.toolMode = this.previousEditingToolMode;
this.emit();
}
setSelection(selection) {
if (this.viewportTransientState.transformSession.kind === "active" && !areEditorSelectionsEqual(this.selection, selection)) {
this.viewportTransientState = {
...this.viewportTransientState,
transformSession: createInactiveTransformSession()
};
}
this.selection = selection;
this.emit();
}
setWhiteboxSelectionMode(mode) {
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) {
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() {
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;
}
this.lastCommandLabel = `Undid ${command.label}`;
this.emit();
return true;
}
redo() {
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;
}
this.lastCommandLabel = `Redid ${command.label}`;
this.emit();
return true;
}
replaceDocument(document, 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();
this.lastCommandLabel = null;
}
this.emit();
}
saveDraft() {
if (this.storage === null) {
return {
status: "error",
message: "Browser local storage is unavailable."
};
}
return saveSceneDocumentDraft(this.storage, this.document, this.createViewportLayoutState(), this.storageKey);
}
loadDraft() {
if (this.storage === null) {
return {
status: "error",
message: "Browser local storage is unavailable."
};
}
const draftResult = loadSceneDocumentDraft(this.storage, this.storageKey);
if (draftResult.status !== "loaded") {
return draftResult;
}
this.replaceDocument(draftResult.document);
if (draftResult.viewportLayoutState !== null) {
this.applyViewportLayoutState(draftResult.viewportLayoutState);
this.emit();
}
return draftResult;
}
exportDocumentJson() {
return serializeSceneDocument(this.document);
}
importDocumentJson(source) {
const document = parseSceneDocumentJson(source);
this.replaceDocument(document);
return document;
}
emit() {
this.snapshot = this.createSnapshot();
for (const listener of this.listeners) {
listener();
}
}
createViewportLayoutState() {
return cloneViewportLayoutState({
layoutMode: this.viewportLayoutMode,
activePanelId: this.activeViewportPanelId,
panels: this.viewportPanels,
viewportQuadSplit: this.viewportQuadSplit
});
}
applyViewportLayoutState(viewportLayoutState) {
const nextViewportLayoutState = cloneViewportLayoutState(viewportLayoutState);
this.viewportLayoutMode = nextViewportLayoutState.layoutMode;
this.activeViewportPanelId = nextViewportLayoutState.activePanelId;
this.viewportPanels = nextViewportLayoutState.panels;
this.viewportQuadSplit = nextViewportLayoutState.viewportQuadSplit;
}
createSnapshot() {
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,
storageAvailable: this.storage !== null
};
}
}
export function createEditorStore(options) {
return new EditorStore(options);
}

View File

@@ -12,9 +12,17 @@ import {
cloneTransformSession,
createInactiveTransformSession,
type TransformAxis,
type TransformAxisSpace,
type TransformSessionState
} from "../core/transform-session";
import { createEmptySceneDocument, type SceneDocument } from "../document/scene-document";
import {
applySceneDocumentToProject,
createEmptyProjectDocument,
createProjectDocumentFromSceneDocument,
createSceneDocumentFromProject,
type ProjectDocument,
type SceneDocument
} from "../document/scene-document";
import {
DEFAULT_SCENE_DRAFT_STORAGE_KEY,
type LoadSceneDocumentDraftResult,
@@ -23,7 +31,10 @@ import {
type SaveSceneDocumentDraftResult,
saveSceneDocumentDraft
} from "../serialization/local-draft-storage";
import { parseSceneDocumentJson, serializeSceneDocument } from "../serialization/scene-document-json";
import {
parseProjectDocumentJson,
serializeProjectDocument
} from "../serialization/scene-document-json";
import type { ViewportViewMode } from "../viewport-three/viewport-view-modes";
import {
areViewportToolPreviewsEqual,
@@ -48,6 +59,8 @@ import {
} from "../viewport-three/viewport-layout";
export interface EditorStoreState {
projectDocument: ProjectDocument;
activeSceneId: string;
document: SceneDocument;
selection: EditorSelection;
whiteboxSelectionMode: WhiteboxSelectionMode;
@@ -65,6 +78,7 @@ export interface EditorStoreState {
interface EditorStoreOptions {
initialDocument?: SceneDocument;
initialProjectDocument?: ProjectDocument;
initialViewportLayoutState?: ViewportLayoutState;
storage?: KeyValueStorage | null;
storageKey?: string;
@@ -76,7 +90,9 @@ export type EditorDraftSaveResult = SaveSceneDocumentDraftResult;
export type EditorDraftLoadResult = LoadSceneDocumentDraftResult;
export class EditorStore {
private projectDocument: ProjectDocument;
private document: SceneDocument;
private commandTargetSceneId: string | null = null;
private selection: EditorSelection = { kind: "none" };
private whiteboxSelectionMode: WhiteboxSelectionMode = "object";
private toolMode: ToolMode = "select";
@@ -94,9 +110,23 @@ export class EditorStore {
private snapshot: EditorStoreState;
private readonly commandContext: CommandContext = {
getDocument: () => this.document,
getDocument: () =>
createSceneDocumentFromProject(
this.projectDocument,
this.resolveCommandSceneId()
),
setDocument: (document) => {
this.document = document;
this.projectDocument = applySceneDocumentToProject(
this.projectDocument,
this.resolveCommandSceneId(),
document
);
this.syncActiveSceneDocument();
},
getProjectDocument: () => this.projectDocument,
setProjectDocument: (document) => {
this.projectDocument = document;
this.syncActiveSceneDocument();
},
getSelection: () => this.selection,
setSelection: (selection) => {
@@ -109,9 +139,16 @@ export class EditorStore {
};
constructor(options: EditorStoreOptions = {}) {
const initialViewportLayoutState = cloneViewportLayoutState(options.initialViewportLayoutState ?? createDefaultViewportLayoutState());
const initialViewportLayoutState = cloneViewportLayoutState(
options.initialViewportLayoutState ?? createDefaultViewportLayoutState()
);
this.document = options.initialDocument ?? createEmptySceneDocument();
this.projectDocument =
options.initialProjectDocument ??
(options.initialDocument !== undefined
? createProjectDocumentFromSceneDocument(options.initialDocument)
: createEmptyProjectDocument());
this.document = createSceneDocumentFromProject(this.projectDocument);
this.viewportLayoutMode = initialViewportLayoutState.layoutMode;
this.activeViewportPanelId = initialViewportLayoutState.activePanelId;
this.viewportPanels = initialViewportLayoutState.panels;
@@ -142,14 +179,22 @@ export class EditorStore {
this.toolMode = toolMode;
if (!isViewportToolPreviewCompatible(toolMode, this.viewportTransientState.toolPreview)) {
if (
!isViewportToolPreviewCompatible(
toolMode,
this.viewportTransientState.toolPreview
)
) {
this.viewportTransientState = {
...this.viewportTransientState,
toolPreview: createDefaultViewportTransientState().toolPreview
};
}
if (toolMode !== "select" && this.viewportTransientState.transformSession.kind !== "none") {
if (
toolMode !== "select" &&
this.viewportTransientState.transformSession.kind !== "none"
) {
this.viewportTransientState = {
...this.viewportTransientState,
transformSession: createInactiveTransformSession()
@@ -177,7 +222,10 @@ export class EditorStore {
this.emit();
}
setViewportPanelViewMode(panelId: ViewportPanelId, viewMode: ViewportViewMode) {
setViewportPanelViewMode(
panelId: ViewportPanelId,
viewMode: ViewportViewMode
) {
if (this.viewportPanels[panelId].viewMode === viewMode) {
return;
}
@@ -192,7 +240,10 @@ export class EditorStore {
this.emit();
}
setViewportPanelDisplayMode(panelId: ViewportPanelId, displayMode: ViewportDisplayMode) {
setViewportPanelDisplayMode(
panelId: ViewportPanelId,
displayMode: ViewportDisplayMode
) {
if (this.viewportPanels[panelId].displayMode === displayMode) {
return;
}
@@ -207,8 +258,16 @@ export class EditorStore {
this.emit();
}
setViewportPanelCameraState(panelId: ViewportPanelId, cameraState: ViewportPanelCameraState) {
if (areViewportPanelCameraStatesEqual(this.viewportPanels[panelId].cameraState, cameraState)) {
setViewportPanelCameraState(
panelId: ViewportPanelId,
cameraState: ViewportPanelCameraState
) {
if (
areViewportPanelCameraStatesEqual(
this.viewportPanels[panelId].cameraState,
cameraState
)
) {
return;
}
@@ -223,7 +282,10 @@ export class EditorStore {
}
setViewportQuadSplit(viewportQuadSplit: ViewportQuadSplit) {
if (this.viewportQuadSplit.x === viewportQuadSplit.x && this.viewportQuadSplit.y === viewportQuadSplit.y) {
if (
this.viewportQuadSplit.x === viewportQuadSplit.x &&
this.viewportQuadSplit.y === viewportQuadSplit.y
) {
return;
}
@@ -237,7 +299,12 @@ export class EditorStore {
setViewportToolPreview(toolPreview: ViewportToolPreview) {
const nextToolPreview = cloneViewportToolPreview(toolPreview);
if (areViewportToolPreviewsEqual(this.viewportTransientState.toolPreview, nextToolPreview)) {
if (
areViewportToolPreviewsEqual(
this.viewportTransientState.toolPreview,
nextToolPreview
)
) {
return;
}
@@ -255,7 +322,10 @@ export class EditorStore {
return;
}
if (sourcePanelId !== undefined && currentToolPreview.sourcePanelId !== sourcePanelId) {
if (
sourcePanelId !== undefined &&
currentToolPreview.sourcePanelId !== sourcePanelId
) {
return;
}
@@ -269,7 +339,12 @@ export class EditorStore {
setTransformSession(transformSession: TransformSessionState) {
const nextTransformSession = cloneTransformSession(transformSession);
if (areTransformSessionsEqual(this.viewportTransientState.transformSession, nextTransformSession)) {
if (
areTransformSessionsEqual(
this.viewportTransientState.transformSession,
nextTransformSession
)
) {
return;
}
@@ -292,20 +367,31 @@ export class EditorStore {
this.emit();
}
setTransformAxisConstraint(axisConstraint: TransformAxis | null) {
setTransformAxisConstraint(
axisConstraint: TransformAxis | null,
axisConstraintSpace: TransformAxisSpace = "world"
) {
if (this.viewportTransientState.transformSession.kind !== "active") {
return;
}
if (this.viewportTransientState.transformSession.axisConstraint === axisConstraint) {
if (
this.viewportTransientState.transformSession.axisConstraint ===
axisConstraint &&
this.viewportTransientState.transformSession.axisConstraintSpace ===
axisConstraintSpace
) {
return;
}
this.viewportTransientState = {
...this.viewportTransientState,
transformSession: {
...(cloneTransformSession(this.viewportTransientState.transformSession) as Extract<TransformSessionState, { kind: "active" }>),
axisConstraint
...(cloneTransformSession(
this.viewportTransientState.transformSession
) as Extract<TransformSessionState, { kind: "active" }>),
axisConstraint,
axisConstraintSpace
}
};
this.emit();
@@ -340,7 +426,10 @@ export class EditorStore {
}
setSelection(selection: EditorSelection) {
if (this.viewportTransientState.transformSession.kind === "active" && !areEditorSelectionsEqual(this.selection, selection)) {
if (
this.viewportTransientState.transformSession.kind === "active" &&
!areEditorSelectionsEqual(this.selection, selection)
) {
this.viewportTransientState = {
...this.viewportTransientState,
transformSession: createInactiveTransformSession()
@@ -364,7 +453,10 @@ export class EditorStore {
}
this.whiteboxSelectionMode = mode;
this.selection = normalizeSelectionForWhiteboxSelectionMode(this.selection, mode);
this.selection = normalizeSelectionForWhiteboxSelectionMode(
this.selection,
mode
);
this.emit();
}
@@ -376,7 +468,7 @@ export class EditorStore {
};
}
this.history.execute(command, this.commandContext);
this.history.execute(this.createScopedCommand(command), this.commandContext);
this.lastCommandLabel = command.label;
this.emit();
}
@@ -433,8 +525,15 @@ export class EditorStore {
return true;
}
replaceDocument(document: SceneDocument, resetHistory = true) {
this.document = document;
replaceDocument(
document: SceneDocument | ProjectDocument,
resetHistory = true
) {
this.projectDocument = isProjectDocument(document)
? document
: createProjectDocumentFromSceneDocument(document);
this.syncActiveSceneDocument();
this.commandTargetSceneId = null;
this.selection = { kind: "none" };
this.whiteboxSelectionMode = "object";
this.toolMode = "select";
@@ -457,7 +556,12 @@ export class EditorStore {
};
}
return saveSceneDocumentDraft(this.storage, this.document, this.createViewportLayoutState(), this.storageKey);
return saveSceneDocumentDraft(
this.storage,
this.projectDocument,
this.createViewportLayoutState(),
this.storageKey
);
}
loadDraft(): EditorDraftLoadResult {
@@ -485,11 +589,11 @@ export class EditorStore {
}
exportDocumentJson(): string {
return serializeSceneDocument(this.document);
return serializeProjectDocument(this.projectDocument);
}
importDocumentJson(source: string): SceneDocument {
const document = parseSceneDocumentJson(source);
importDocumentJson(source: string): ProjectDocument {
const document = parseProjectDocumentJson(source);
this.replaceDocument(document);
return document;
}
@@ -512,7 +616,8 @@ export class EditorStore {
}
private applyViewportLayoutState(viewportLayoutState: ViewportLayoutState) {
const nextViewportLayoutState = cloneViewportLayoutState(viewportLayoutState);
const nextViewportLayoutState =
cloneViewportLayoutState(viewportLayoutState);
this.viewportLayoutMode = nextViewportLayoutState.layoutMode;
this.activeViewportPanelId = nextViewportLayoutState.activePanelId;
@@ -522,6 +627,8 @@ export class EditorStore {
private createSnapshot(): EditorStoreState {
return {
projectDocument: this.projectDocument,
activeSceneId: this.projectDocument.activeSceneId,
document: this.document,
selection: this.selection,
whiteboxSelectionMode: this.whiteboxSelectionMode,
@@ -537,8 +644,45 @@ export class EditorStore {
storageAvailable: this.storage !== null
};
}
private syncActiveSceneDocument() {
this.document = createSceneDocumentFromProject(this.projectDocument);
}
private resolveCommandSceneId(): string {
return this.commandTargetSceneId ?? this.projectDocument.activeSceneId;
}
private withCommandSceneScope<T>(sceneId: string, run: () => T): T {
const previousSceneId = this.commandTargetSceneId;
this.commandTargetSceneId = sceneId;
try {
return run();
} finally {
this.commandTargetSceneId = previousSceneId;
}
}
private createScopedCommand(command: EditorCommand): EditorCommand {
const sceneId = this.projectDocument.activeSceneId;
return {
...command,
execute: (context) =>
this.withCommandSceneScope(sceneId, () => command.execute(context)),
undo: (context) =>
this.withCommandSceneScope(sceneId, () => command.undo(context))
};
}
}
export function createEditorStore(options?: EditorStoreOptions): EditorStore {
return new EditorStore(options);
}
function isProjectDocument(
document: SceneDocument | ProjectDocument
): document is ProjectDocument {
return "scenes" in document && "activeSceneId" in document;
}

View File

@@ -0,0 +1,4 @@
import { useSyncExternalStore } from "react";
export function useEditorStoreState(store) {
return useSyncExternalStore(store.subscribe, store.getState, store.getState);
}

166
src/assets/audio-assets.js Normal file
View File

@@ -0,0 +1,166 @@
import { createOpaqueId } from "../core/ids";
import { createProjectAssetStorageKey } from "./project-assets";
function getErrorDetail(error) {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message.trim();
}
return "Unknown error.";
}
function getFileExtension(sourceName) {
const match = /\.([^.]+)$/u.exec(sourceName.trim());
return match === null ? "" : match[1].toLowerCase();
}
function inferAudioMimeType(sourceName, fallbackMimeType) {
if (fallbackMimeType.trim().startsWith("audio/")) {
return fallbackMimeType.trim();
}
switch (getFileExtension(sourceName)) {
case "aac":
return "audio/aac";
case "flac":
return "audio/flac";
case "m4a":
case "mp4":
return "audio/mp4";
case "mp3":
return "audio/mpeg";
case "oga":
case "ogg":
return "audio/ogg";
case "wav":
case "wave":
return "audio/wav";
case "webm":
return "audio/webm";
default:
throw new Error(`Unsupported audio asset format for ${sourceName}. Use a browser-supported audio file.`);
}
}
function getImportedFilePath(file) {
const relativePath = typeof file.webkitRelativePath === "string" ? file.webkitRelativePath.trim() : "";
const sourcePath = relativePath.length > 0 ? relativePath : file.name.trim();
return sourcePath.replace(/\\/gu, "/");
}
function createAudioContext() {
const AudioContextConstructor = globalThis.AudioContext ??
globalThis.webkitAudioContext;
if (AudioContextConstructor === undefined) {
throw new Error("Audio context is unavailable in this browser environment.");
}
return new AudioContextConstructor();
}
async function decodeAudioBuffer(bytes) {
const audioContext = createAudioContext();
try {
return await audioContext.decodeAudioData(bytes.slice(0));
}
catch (error) {
throw new Error(getErrorDetail(error));
}
finally {
await audioContext.close().catch(() => undefined);
}
}
function extractAudioAssetMetadata(buffer) {
if (!Number.isFinite(buffer.duration) || buffer.duration <= 0) {
throw new Error("Imported audio assets must have measurable duration.");
}
return {
kind: "audio",
durationSeconds: buffer.duration,
channelCount: buffer.numberOfChannels,
sampleRateHz: buffer.sampleRate,
warnings: []
};
}
function createLoadedAudioAsset(asset, buffer) {
return {
assetId: asset.id,
storageKey: asset.storageKey,
metadata: asset.metadata,
buffer
};
}
function createAudioAssetRecord(sourceName, mimeType, byteLength, metadata) {
const assetId = createOpaqueId("asset-audio");
return {
id: assetId,
kind: "audio",
sourceName,
mimeType,
storageKey: createProjectAssetStorageKey(assetId),
byteLength,
metadata
};
}
async function loadAudioAssetFromFileRecord(asset, fileRecord) {
try {
const buffer = await decodeAudioBuffer(fileRecord.bytes);
return createLoadedAudioAsset(asset, buffer);
}
catch (error) {
throw new Error(`Audio asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
}
}
function getStoredAudioAssetFile(asset, storedAsset) {
const directFile = storedAsset.files[asset.sourceName];
if (directFile !== undefined) {
return directFile;
}
const storedFiles = Object.values(storedAsset.files);
if (storedFiles.length === 1) {
return storedFiles[0];
}
return null;
}
export async function importAudioAssetFromFile(file, storage) {
const sourceName = getImportedFilePath(file);
const mimeType = inferAudioMimeType(sourceName, file.type);
const bytes = await file.arrayBuffer();
let buffer;
try {
buffer = await decodeAudioBuffer(bytes);
}
catch (error) {
throw new Error(`Audio import failed for ${sourceName}: ${getErrorDetail(error)}`);
}
const metadata = extractAudioAssetMetadata(buffer);
const asset = createAudioAssetRecord(sourceName, mimeType, bytes.byteLength, metadata);
const loadedAsset = createLoadedAudioAsset(asset, buffer);
const packageRecord = {
files: {
[sourceName]: {
bytes,
mimeType
}
}
};
try {
await storage.putAsset(asset.storageKey, packageRecord);
return {
asset,
loadedAsset
};
}
catch (error) {
await storage.deleteAsset(asset.storageKey).catch(() => undefined);
throw error;
}
}
export async function loadAudioAssetFromStorage(storage, asset) {
let storedAsset;
try {
storedAsset = await storage.getAsset(asset.storageKey);
}
catch (error) {
throw new Error(`Audio asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
}
if (storedAsset === null) {
throw new Error(`Missing stored binary data for imported audio asset ${asset.sourceName}.`);
}
const storedAudioFile = getStoredAudioAssetFile(asset, storedAsset);
if (storedAudioFile === null) {
throw new Error(`Missing stored audio file for imported audio asset ${asset.sourceName}.`);
}
return loadAudioAssetFromFileRecord(asset, storedAudioFile);
}

View File

@@ -0,0 +1,592 @@
import { Box3, Group, Mesh } from "three";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { clone as cloneSkeleton } from "three/examples/jsm/utils/SkeletonUtils.js";
import { createModelInstance } from "./model-instances";
import { createProjectAssetStorageKey } from "./project-assets";
import { createOpaqueId } from "../core/ids";
const DRACO_DECODER_PATH = "/draco/gltf/";
let sharedDracoLoader = null;
function getErrorDetail(error) {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message.trim();
}
return "Unknown error.";
}
function getFileExtension(sourceName) {
const match = /\.([^.]+)$/u.exec(sourceName.trim());
return match === null ? "" : match[1].toLowerCase();
}
function inferFileMimeType(sourceName, fallbackMimeType) {
if (fallbackMimeType.trim().length > 0 && fallbackMimeType !== "application/octet-stream") {
return fallbackMimeType;
}
switch (getFileExtension(sourceName)) {
case "bin":
return "application/octet-stream";
case "png":
return "image/png";
case "jpg":
case "jpeg":
return "image/jpeg";
case "gif":
return "image/gif";
case "webp":
return "image/webp";
case "avif":
return "image/avif";
case "ktx2":
return "image/ktx2";
case "wav":
return "audio/wav";
case "mp3":
return "audio/mpeg";
case "ogg":
return "audio/ogg";
case "glb":
return "model/gltf-binary";
case "gltf":
return "model/gltf+json";
default:
return fallbackMimeType.trim().length > 0 ? fallbackMimeType : "application/octet-stream";
}
}
function inferModelAssetFormat(sourceName, mimeType) {
const extension = getFileExtension(sourceName);
if (mimeType === "model/gltf-binary" || extension === "glb") {
return "glb";
}
if (mimeType === "model/gltf+json" || mimeType === "application/json" || extension === "gltf") {
return "gltf";
}
throw new Error(`Unsupported model asset format for ${sourceName}. Use .glb or .gltf.`);
}
function inferModelMimeType(format) {
return format === "glb" ? "model/gltf-binary" : "model/gltf+json";
}
function stripUrlQueryAndHash(path) {
const queryIndex = path.search(/[?#]/u);
return queryIndex === -1 ? path : path.slice(0, queryIndex);
}
function normalizeRelativePath(path) {
const normalizedPath = stripUrlQueryAndHash(path.trim()).replace(/\\/gu, "/");
const segments = normalizedPath.split("/");
const resolvedSegments = [];
for (const segment of segments) {
if (segment === "" || segment === ".") {
continue;
}
if (segment === "..") {
const previousSegment = resolvedSegments.at(-1);
if (previousSegment !== undefined && previousSegment !== "..") {
resolvedSegments.pop();
}
else {
resolvedSegments.push("..");
}
continue;
}
resolvedSegments.push(segment);
}
return resolvedSegments.join("/");
}
function getPathDirectory(path) {
const normalizedPath = normalizeRelativePath(path);
const lastSlashIndex = normalizedPath.lastIndexOf("/");
return lastSlashIndex === -1 ? "" : normalizedPath.slice(0, lastSlashIndex);
}
function getRelativePath(fromDirectory, targetPath) {
const normalizedFromSegments = normalizeRelativePath(fromDirectory).split("/").filter((segment) => segment.length > 0);
const normalizedTargetSegments = normalizeRelativePath(targetPath).split("/").filter((segment) => segment.length > 0);
while (normalizedFromSegments.length > 0 &&
normalizedTargetSegments.length > 0 &&
normalizedFromSegments[0] === normalizedTargetSegments[0]) {
normalizedFromSegments.shift();
normalizedTargetSegments.shift();
}
return [...new Array(normalizedFromSegments.length).fill(".."), ...normalizedTargetSegments].join("/");
}
function getImportedFilePath(file) {
const relativePath = typeof file.webkitRelativePath === "string" ? file.webkitRelativePath.trim() : "";
return normalizeRelativePath(relativePath.length > 0 ? relativePath : file.name.trim());
}
function createBoundingBoxFromObject(object) {
const box = new Box3().setFromObject(object);
if (box.isEmpty()) {
return null;
}
const min = {
x: box.min.x,
y: box.min.y,
z: box.min.z
};
const max = {
x: box.max.x,
y: box.max.y,
z: box.max.z
};
return {
min,
max,
size: {
x: max.x - min.x,
y: max.y - min.y,
z: max.z - min.z
}
};
}
function collectMaterialNames(scene) {
const names = new Set();
scene.traverse((object) => {
const maybeMesh = object;
if (maybeMesh.isMesh !== true) {
return;
}
const materials = Array.isArray(maybeMesh.material) ? maybeMesh.material : [maybeMesh.material];
for (const material of materials) {
if (material.name.trim().length > 0) {
names.add(material.name);
}
}
});
return [...names].sort((left, right) => left.localeCompare(right));
}
function collectTextureNames(parserJson) {
const textures = parserJson.textures ?? [];
const names = new Set();
for (const texture of textures) {
if (texture.name !== undefined && texture.name.trim().length > 0) {
names.add(texture.name);
}
}
return [...names].sort((left, right) => left.localeCompare(right));
}
function collectAnimationNames(gltf) {
return gltf.animations
.map((animation, index) => (animation.name.trim().length > 0 ? animation.name : `Animation ${index + 1}`))
.sort((left, right) => left.localeCompare(right));
}
function countNodes(scene) {
let count = 0;
scene.traverse(() => {
count += 1;
});
return count;
}
export function extractModelAssetMetadata(gltf, format) {
gltf.scene.updateMatrixWorld(true);
const boundingBox = createBoundingBoxFromObject(gltf.scene);
let actualMeshCount = 0;
gltf.scene.traverse((object) => {
if (object.isMesh === true) {
actualMeshCount += 1;
}
});
const parserJson = gltf.parser.json;
const materialNames = collectMaterialNames(gltf.scene);
const textureNames = collectTextureNames(parserJson);
const animationNames = collectAnimationNames(gltf);
const warnings = [];
if (boundingBox === null) {
warnings.push("The imported model does not contain measurable geometry.");
}
if (actualMeshCount === 0) {
warnings.push("The imported model does not contain any meshes.");
}
if (materialNames.length === 0 && (parserJson.materials?.length ?? 0) > 0) {
for (const material of parserJson.materials ?? []) {
if (material.name !== undefined && material.name.trim().length > 0) {
materialNames.push(material.name);
}
}
}
return {
kind: "model",
format,
sceneName: gltf.scene.name.trim().length > 0 ? gltf.scene.name : null,
nodeCount: countNodes(gltf.scene),
meshCount: actualMeshCount,
materialNames: [...new Set(materialNames)].sort((left, right) => left.localeCompare(right)),
textureNames,
animationNames,
boundingBox,
warnings
};
}
function createLoadedModelAsset(asset, template, animations) {
return {
assetId: asset.id,
storageKey: asset.storageKey,
metadata: asset.metadata,
template,
animations
};
}
function createModelAssetRecord(sourceName, mimeType, byteLength, metadata) {
const assetId = createOpaqueId("asset-model");
return {
id: assetId,
kind: "model",
sourceName,
mimeType,
storageKey: createProjectAssetStorageKey(assetId),
byteLength,
metadata
};
}
async function loadGltfFromArrayBuffer(arrayBuffer) {
const loader = createConfiguredGltfLoader();
return loader.parseAsync(arrayBuffer, "");
}
function createConfiguredGltfLoader() {
const loader = new GLTFLoader();
loader.setDRACOLoader(getSharedDracoLoader());
return loader;
}
function getSharedDracoLoader() {
if (sharedDracoLoader === null) {
sharedDracoLoader = new DRACOLoader();
sharedDracoLoader.setDecoderPath(DRACO_DECODER_PATH);
}
return sharedDracoLoader;
}
function createDataUrlForStoredFile(file) {
const byteArray = new Uint8Array(file.bytes);
let binary = "";
const chunkSize = 0x8000;
for (let index = 0; index < byteArray.length; index += chunkSize) {
binary += String.fromCharCode(...byteArray.subarray(index, index + chunkSize));
}
const base64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(file.bytes).toString("base64");
return `data:${file.mimeType};base64,${base64}`;
}
function createTransientResourceUrl(file) {
if (typeof URL.createObjectURL === "function" && typeof Blob !== "undefined") {
const objectUrl = URL.createObjectURL(new Blob([file.bytes], { type: file.mimeType }));
return {
url: objectUrl,
revoke: () => {
if (typeof URL.revokeObjectURL === "function") {
URL.revokeObjectURL(objectUrl);
}
}
};
}
return {
url: createDataUrlForStoredFile(file),
revoke: () => undefined
};
}
function rewriteGltfResourceUris(gltfJson, files) {
const dataUrlsByPath = new Map();
const revokeUrls = [];
const missingUris = new Set();
const resolveUri = (uri) => {
if (uri.startsWith("data:") || uri.startsWith("blob:")) {
return uri;
}
const normalizedUri = normalizeRelativePath(uri);
const storedFile = files[normalizedUri];
if (storedFile === undefined) {
return null;
}
const cachedDataUrl = dataUrlsByPath.get(normalizedUri);
if (cachedDataUrl !== undefined) {
return cachedDataUrl;
}
const transientResourceUrl = createTransientResourceUrl(storedFile);
dataUrlsByPath.set(normalizedUri, transientResourceUrl.url);
revokeUrls.push(transientResourceUrl.revoke);
return transientResourceUrl.url;
};
const rewriteUri = (value) => {
if (typeof value !== "string") {
return value;
}
const resolvedUri = resolveUri(stripUrlQueryAndHash(value));
if (resolvedUri === null) {
missingUris.add(normalizeRelativePath(value));
return value;
}
return resolvedUri;
};
const buffers = Array.isArray(gltfJson.buffers) ? gltfJson.buffers : [];
for (const buffer of buffers) {
if (typeof buffer.uri === "string") {
buffer.uri = rewriteUri(buffer.uri);
}
}
const images = Array.isArray(gltfJson.images) ? gltfJson.images : [];
for (const image of images) {
if (typeof image.uri === "string") {
image.uri = rewriteUri(image.uri);
}
}
return {
missingUris: [...missingUris],
revokeUrls
};
}
function cloneTemplateScene(scene) {
// Use SkeletonUtils.clone so that SkinnedMesh.skeleton.bones are remapped
// to the cloned hierarchy. A plain scene.clone(true) leaves the bones array
// pointing at the original loader's nodes, which are gone after parsing,
// making every skinned mesh invisible at runtime.
return cloneSkeleton(scene);
}
function cloneMaterial(material) {
return material.clone();
}
function cloneMeshResources(object) {
const maybeMesh = object;
if (maybeMesh.isMesh !== true) {
return;
}
maybeMesh.geometry = maybeMesh.geometry.clone();
maybeMesh.material = Array.isArray(maybeMesh.material)
? maybeMesh.material.map((material) => cloneMaterial(material))
: cloneMaterial(maybeMesh.material);
}
function disposeTexture(texture, seenTextures) {
if (seenTextures.has(texture)) {
return;
}
seenTextures.add(texture);
texture.dispose();
}
function disposeMaterialResources(material, disposeTextures, seenTextures) {
if (disposeTextures) {
for (const value of Object.values(material)) {
if (value === null || value === undefined) {
continue;
}
if (Array.isArray(value)) {
for (const entry of value) {
if (entry !== null && typeof entry === "object" && "isTexture" in entry) {
disposeTexture(entry, seenTextures);
}
}
continue;
}
if (typeof value === "object" && "isTexture" in value) {
disposeTexture(value, seenTextures);
}
}
}
material.dispose();
}
function disposeMeshResources(object, disposeTextures, seenTextures) {
const maybeMesh = object;
if (maybeMesh.isMesh !== true) {
return;
}
maybeMesh.geometry.dispose();
if (Array.isArray(maybeMesh.material)) {
for (const material of maybeMesh.material) {
disposeMaterialResources(material, disposeTextures, seenTextures);
}
}
else {
disposeMaterialResources(maybeMesh.material, disposeTextures, seenTextures);
}
}
export function instantiateModelTemplate(template) {
const clone = cloneSkeleton(template);
clone.traverse(cloneMeshResources);
return clone;
}
export function disposeModelTemplate(template) {
const seenTextures = new Set();
template.traverse((object) => {
disposeMeshResources(object, true, seenTextures);
});
}
export function disposeModelInstance(instance) {
const seenTextures = new Set();
instance.traverse((object) => {
disposeMeshResources(object, false, seenTextures);
});
}
async function loadModelFileSet(files) {
if (files.length === 0) {
throw new Error("Select a .glb or .gltf file to import.");
}
const modelFiles = files.filter((file) => {
try {
inferModelAssetFormat(file.name, file.type);
return true;
}
catch {
return false;
}
});
if (modelFiles.length === 0) {
throw new Error("Select a .glb or .gltf file to import.");
}
if (modelFiles.length > 1) {
throw new Error("Select exactly one .glb or .gltf file and any matching sidecar resources.");
}
const rootFile = modelFiles[0];
const rootSourcePath = getImportedFilePath(rootFile);
const rootDirectory = getPathDirectory(rootSourcePath);
const importedFiles = await Promise.all(files.map(async (file) => ({
file,
bytes: await file.arrayBuffer()
})));
const fileEntries = [];
const packageFiles = {};
for (const { file, bytes } of importedFiles) {
const sourcePath = file === rootFile ? normalizeRelativePath(rootFile.name.trim()) : getRelativePath(rootDirectory, getImportedFilePath(file));
const mimeType = inferFileMimeType(file.name, file.type);
if (packageFiles[sourcePath] !== undefined) {
throw new Error(`Duplicate imported file path ${sourcePath}.`);
}
const entry = {
bytes,
mimeType,
path: sourcePath
};
fileEntries.push(entry);
packageFiles[sourcePath] = {
bytes,
mimeType
};
}
const rootEntry = fileEntries.find((entry) => entry.path === normalizeRelativePath(rootFile.name.trim()));
if (rootEntry === undefined) {
throw new Error(`Unable to locate the root model file ${rootFile.name}.`);
}
// Keep the root file's canonical storage path equal to its source name so reloads can find it directly.
const packageRecord = {
files: packageFiles
};
return {
fileEntries,
packageRecord,
rootFile: rootEntry,
totalByteLength: fileEntries.reduce((total, entry) => total + entry.bytes.byteLength, 0)
};
}
async function loadGltfFromImportedModelFileSet(fileSet) {
const rootFormat = inferModelAssetFormat(fileSet.rootFile.path, fileSet.rootFile.mimeType);
if (rootFormat === "glb") {
return loadGltfFromArrayBuffer(fileSet.rootFile.bytes);
}
const text = new TextDecoder().decode(fileSet.rootFile.bytes);
const gltfJson = JSON.parse(text);
const { missingUris, revokeUrls } = rewriteGltfResourceUris(gltfJson, fileSet.packageRecord.files);
if (missingUris.length > 0) {
for (const revokeUrl of revokeUrls) {
revokeUrl();
}
throw new Error(`Missing external model resource(s): ${missingUris.join(", ")}.`);
}
const loader = createConfiguredGltfLoader();
try {
return await loader.parseAsync(JSON.stringify(gltfJson), "");
}
finally {
for (const revokeUrl of revokeUrls) {
revokeUrl();
}
}
}
function createModelAssetRecordFromFileSet(sourceName, mimeType, byteLength, metadata) {
return createModelAssetRecord(sourceName, mimeType, byteLength, metadata);
}
export async function importModelAssetFromFiles(files, storage) {
let fileSet;
try {
fileSet = await loadModelFileSet(files);
}
catch (error) {
throw new Error(`Model import failed: ${getErrorDetail(error)}`);
}
const sourceName = fileSet.rootFile.path;
const format = inferModelAssetFormat(sourceName, fileSet.rootFile.mimeType);
const mimeType = inferModelMimeType(format);
let gltf;
try {
gltf = await loadGltfFromImportedModelFileSet(fileSet);
}
catch (error) {
throw new Error(`Model import failed for ${sourceName}: ${getErrorDetail(error)}`);
}
const metadata = extractModelAssetMetadata(gltf, format);
const asset = createModelAssetRecordFromFileSet(sourceName, mimeType, fileSet.totalByteLength, metadata);
try {
await storage.putAsset(asset.storageKey, fileSet.packageRecord);
const modelInstance = createModelInstance({
assetId: asset.id,
name: undefined
});
return {
asset,
modelInstance,
loadedAsset: createLoadedModelAsset(asset, cloneTemplateScene(gltf.scene), gltf.animations)
};
}
catch (error) {
await storage.deleteAsset(asset.storageKey).catch(() => undefined);
throw error;
}
}
export async function importModelAssetFromFile(file, storage) {
return importModelAssetFromFiles([file], storage);
}
function getStoredModelAssetFile(asset, storedAsset) {
const directFile = storedAsset.files[asset.sourceName];
if (directFile !== undefined) {
return directFile;
}
const storedFiles = Object.values(storedAsset.files);
if (storedFiles.length === 1) {
return storedFiles[0];
}
return null;
}
export async function loadModelAssetFromStorage(storage, asset) {
let storedAsset;
try {
storedAsset = await storage.getAsset(asset.storageKey);
}
catch (error) {
throw new Error(`Model asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
}
if (storedAsset === null) {
throw new Error(`Missing stored binary data for imported model asset ${asset.sourceName}.`);
}
const storedModelFile = getStoredModelAssetFile(asset, storedAsset);
if (storedModelFile === null) {
throw new Error(`Missing stored root file for imported model asset ${asset.sourceName}.`);
}
if (asset.metadata.format === "glb") {
try {
const gltf = await loadGltfFromArrayBuffer(storedModelFile.bytes);
return createLoadedModelAsset(asset, cloneTemplateScene(gltf.scene), gltf.animations);
}
catch (error) {
throw new Error(`Model asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
}
}
const fileEntries = storedAsset.files;
const rootFileBytes = storedModelFile.bytes;
const gltfJson = JSON.parse(new TextDecoder().decode(rootFileBytes));
const { missingUris, revokeUrls } = rewriteGltfResourceUris(gltfJson, fileEntries);
if (missingUris.length > 0) {
for (const revokeUrl of revokeUrls) {
revokeUrl();
}
throw new Error(`Missing stored external model resource(s): ${missingUris.join(", ")}.`);
}
const loader = createConfiguredGltfLoader();
try {
const gltf = await loader.parseAsync(JSON.stringify(gltfJson), "");
return createLoadedModelAsset(asset, cloneTemplateScene(gltf.scene), gltf.animations);
}
finally {
for (const revokeUrl of revokeUrls) {
revokeUrl();
}
}
}

View File

@@ -453,7 +453,11 @@ function rewriteGltfResourceUris(
}
function cloneTemplateScene(scene: Group): Group {
return scene.clone(true);
// Use SkeletonUtils.clone so that SkinnedMesh.skeleton.bones are remapped
// to the cloned hierarchy. A plain scene.clone(true) leaves the bones array
// pointing at the original loader's nodes, which are gone after parsing,
// making every skinned mesh invisible at runtime.
return cloneSkeleton(scene) as Group;
}
function cloneMaterial(material: Material): Material {

306
src/assets/image-assets.js Normal file
View File

@@ -0,0 +1,306 @@
import { DataTexture, EquirectangularReflectionMapping, LinearSRGBColorSpace, SRGBColorSpace, Texture } from "three";
import { EXRLoader } from "three/examples/jsm/loaders/EXRLoader.js";
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader.js";
import { createOpaqueId } from "../core/ids";
import { createProjectAssetStorageKey } from "./project-assets";
import {} from "./project-asset-storage";
function getErrorDetail(error) {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message.trim();
}
return "Unknown error.";
}
function getFileExtension(sourceName) {
const match = /\.([^.]+)$/u.exec(sourceName.trim());
return match === null ? "" : match[1].toLowerCase();
}
function inferImageMimeType(sourceName, fallbackMimeType) {
if (fallbackMimeType.trim().startsWith("image/")) {
return fallbackMimeType.trim();
}
switch (getFileExtension(sourceName)) {
case "avif":
return "image/avif";
case "exr":
return "image/x-exr";
case "gif":
return "image/gif";
case "hdr":
return "image/vnd.radiance";
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "svg":
return "image/svg+xml";
case "webp":
return "image/webp";
default:
throw new Error(`Unsupported image asset format for ${sourceName}. Use a browser-supported image file or .exr/.hdr.`);
}
}
function isHdrFormat(sourceName) {
const ext = getFileExtension(sourceName);
return ext === "exr" || ext === "hdr";
}
function getImportedFilePath(file) {
const relativePath = typeof file.webkitRelativePath === "string" ? file.webkitRelativePath.trim() : "";
const sourcePath = relativePath.length > 0 ? relativePath : file.name.trim();
return sourcePath.replace(/\\/gu, "/");
}
function createDataUrlForStoredFile(file) {
const byteArray = new Uint8Array(file.bytes);
let binary = "";
const chunkSize = 0x8000;
for (let index = 0; index < byteArray.length; index += chunkSize) {
binary += String.fromCharCode(...byteArray.subarray(index, index + chunkSize));
}
const base64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(file.bytes).toString("base64");
return `data:${file.mimeType};base64,${base64}`;
}
function createTransientResourceUrl(file) {
if (typeof URL.createObjectURL === "function" && typeof Blob !== "undefined") {
const objectUrl = URL.createObjectURL(new Blob([file.bytes], { type: file.mimeType }));
return {
url: objectUrl,
revoke: () => {
if (typeof URL.revokeObjectURL === "function") {
URL.revokeObjectURL(objectUrl);
}
}
};
}
return {
url: createDataUrlForStoredFile(file),
revoke: () => undefined
};
}
function loadImageElement(sourceUrl) {
return new Promise((resolve, reject) => {
const image = new Image();
image.decoding = "async";
image.addEventListener("load", () => {
resolve(image);
});
image.addEventListener("error", () => {
reject(new Error(`Image could not be loaded from ${sourceUrl}.`));
});
image.src = sourceUrl;
});
}
function detectImageHasAlpha(image) {
const canvas = document.createElement("canvas");
const sampleWidth = Math.max(1, Math.min(64, image.naturalWidth || image.width));
const sampleHeight = Math.max(1, Math.min(64, image.naturalHeight || image.height));
const context = canvas.getContext("2d", {
willReadFrequently: true
});
if (context === null) {
return false;
}
canvas.width = sampleWidth;
canvas.height = sampleHeight;
context.drawImage(image, 0, 0, sampleWidth, sampleHeight);
try {
const pixels = context.getImageData(0, 0, sampleWidth, sampleHeight).data;
for (let index = 3; index < pixels.length; index += 4) {
if (pixels[index] !== 255) {
return true;
}
}
}
catch {
return false;
}
return false;
}
function extractImageAssetMetadata(image) {
const width = image.naturalWidth || image.width;
const height = image.naturalHeight || image.height;
if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) {
throw new Error("Imported image assets must have measurable dimensions.");
}
const warnings = [];
const aspectRatio = width / height;
if (Math.abs(aspectRatio - 2) > 0.15) {
warnings.push("Background images work best as a 2:1 equirectangular panorama.");
}
return {
kind: "image",
width,
height,
hasAlpha: detectImageHasAlpha(image),
warnings
};
}
function extractHdrTextureMetadata(texture) {
const width = texture.image.width;
const height = texture.image.height;
const warnings = [];
if (Math.abs(width / height - 2) > 0.15) {
warnings.push("Background images work best as a 2:1 equirectangular panorama.");
}
return { kind: "image", width, height, hasAlpha: false, warnings };
}
function createImageTexture(image) {
const texture = new Texture(image);
texture.colorSpace = SRGBColorSpace;
texture.mapping = EquirectangularReflectionMapping;
texture.needsUpdate = true;
return texture;
}
function configureHdrTexture(texture) {
// HDR/EXR data is linear — do not apply sRGB color space
texture.colorSpace = LinearSRGBColorSpace;
texture.mapping = EquirectangularReflectionMapping;
texture.needsUpdate = true;
return texture;
}
function loadHdrTexture(url, sourceName) {
return new Promise((resolve, reject) => {
if (getFileExtension(sourceName) === "exr") {
new EXRLoader().load(url, resolve, undefined, () => {
reject(new Error(`EXR file could not be loaded: ${sourceName}.`));
});
}
else {
new RGBELoader().load(url, resolve, undefined, () => {
reject(new Error(`HDR file could not be loaded: ${sourceName}.`));
});
}
});
}
function createLoadedImageAsset(asset, image, sourceUrl, revokeSourceUrl) {
return {
assetId: asset.id,
storageKey: asset.storageKey,
metadata: asset.metadata,
texture: createImageTexture(image),
sourceUrl,
revokeSourceUrl
};
}
function createLoadedHdrImageAsset(asset, texture, sourceUrl, revokeSourceUrl) {
return {
assetId: asset.id,
storageKey: asset.storageKey,
metadata: asset.metadata,
texture: configureHdrTexture(texture),
sourceUrl,
revokeSourceUrl
};
}
function createImageAssetRecord(sourceName, mimeType, byteLength, metadata) {
const assetId = createOpaqueId("asset-image");
return {
id: assetId,
kind: "image",
sourceName,
mimeType,
storageKey: createProjectAssetStorageKey(assetId),
byteLength,
metadata
};
}
function getStoredImageAssetFile(asset, storedAsset) {
const directFile = storedAsset.files[asset.sourceName];
if (directFile !== undefined) {
return directFile;
}
const storedFiles = Object.values(storedAsset.files);
if (storedFiles.length === 1) {
return storedFiles[0];
}
return null;
}
async function loadImageAssetFromFileRecord(asset, fileRecord) {
const transientResourceUrl = createTransientResourceUrl(fileRecord);
if (isHdrFormat(asset.sourceName)) {
try {
const texture = await loadHdrTexture(transientResourceUrl.url, asset.sourceName);
return createLoadedHdrImageAsset(asset, texture, transientResourceUrl.url, transientResourceUrl.revoke);
}
catch (error) {
transientResourceUrl.revoke();
throw new Error(`Image asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
}
}
try {
const image = await loadImageElement(transientResourceUrl.url);
return createLoadedImageAsset(asset, image, transientResourceUrl.url, transientResourceUrl.revoke);
}
catch (error) {
transientResourceUrl.revoke();
throw new Error(`Image asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
}
}
export async function importBackgroundImageAssetFromFile(file, storage) {
const sourceName = getImportedFilePath(file);
const mimeType = inferImageMimeType(sourceName, file.type);
const bytes = await file.arrayBuffer();
const fileRecord = { bytes, mimeType };
let asset;
let loadedAsset;
if (isHdrFormat(sourceName)) {
const transientResourceUrl = createTransientResourceUrl(fileRecord);
let texture;
try {
texture = await loadHdrTexture(transientResourceUrl.url, sourceName);
}
catch (error) {
transientResourceUrl.revoke();
throw new Error(`Image import failed for ${sourceName}: ${getErrorDetail(error)}`);
}
const metadata = extractHdrTextureMetadata(texture);
asset = createImageAssetRecord(sourceName, mimeType, bytes.byteLength, metadata);
loadedAsset = createLoadedHdrImageAsset(asset, texture, transientResourceUrl.url, transientResourceUrl.revoke);
}
else {
const transientResourceUrl = createTransientResourceUrl(fileRecord);
let image;
try {
image = await loadImageElement(transientResourceUrl.url);
}
catch (error) {
transientResourceUrl.revoke();
throw new Error(`Image import failed for ${sourceName}: ${getErrorDetail(error)}`);
}
const metadata = extractImageAssetMetadata(image);
asset = createImageAssetRecord(sourceName, mimeType, bytes.byteLength, metadata);
loadedAsset = createLoadedImageAsset(asset, image, transientResourceUrl.url, transientResourceUrl.revoke);
}
const packageRecord = {
files: { [sourceName]: fileRecord }
};
try {
await storage.putAsset(asset.storageKey, packageRecord);
return { asset, loadedAsset };
}
catch (error) {
disposeLoadedImageAsset(loadedAsset);
await storage.deleteAsset(asset.storageKey).catch(() => undefined);
throw error;
}
}
export async function loadImageAssetFromStorage(storage, asset) {
let storedAsset;
try {
storedAsset = await storage.getAsset(asset.storageKey);
}
catch (error) {
throw new Error(`Image asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
}
if (storedAsset === null) {
throw new Error(`Missing stored binary data for imported image asset ${asset.sourceName}.`);
}
const storedImageFile = getStoredImageAssetFile(asset, storedAsset);
if (storedImageFile === null) {
throw new Error(`Missing stored image file for imported image asset ${asset.sourceName}.`);
}
return loadImageAssetFromFileRecord(asset, storedImageFile);
}
export function disposeLoadedImageAsset(asset) {
asset.texture.dispose();
asset.revokeSourceUrl();
}

View File

@@ -0,0 +1,27 @@
import { getModelInstances } from "./model-instances";
function getModelInstanceBaseLabel(modelInstance, assets) {
if (modelInstance.name !== undefined) {
return modelInstance.name;
}
const asset = assets[modelInstance.assetId];
if (asset === undefined) {
return "Model Instance";
}
return asset.sourceName;
}
export function getModelInstanceDisplayLabel(modelInstance, assets) {
return getModelInstanceBaseLabel(modelInstance, assets);
}
export function getModelInstanceDisplayLabelById(modelInstanceId, modelInstances, assets) {
const modelInstance = modelInstances[modelInstanceId];
if (modelInstance === undefined) {
return "Model Instance";
}
return getModelInstanceDisplayLabel(modelInstance, assets);
}
export function getSortedModelInstanceDisplayLabels(modelInstances, assets) {
return getModelInstances(modelInstances).map((modelInstance) => ({
modelInstance,
label: getModelInstanceDisplayLabel(modelInstance, assets)
}));
}

View File

@@ -0,0 +1,157 @@
import { BoxGeometry, Group, Mesh, MeshBasicMaterial } from "three";
import { instantiateModelTemplate } from "./gltf-model-import";
const MODEL_PLACEHOLDER_COLOR = 0x89b6ff;
const MODEL_SELECTION_COLOR = 0xf7d2aa;
const MODEL_PREVIEW_SHELL_OPACITY = 0.5;
function getLocalModelBounds(asset) {
if (asset?.kind === "model" && asset.metadata.boundingBox !== null) {
const boundingBox = asset.metadata.boundingBox;
return {
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: {
x: Math.max(0.1, Math.abs(boundingBox.max.x - boundingBox.min.x)),
y: Math.max(0.1, Math.abs(boundingBox.max.y - boundingBox.min.y)),
z: Math.max(0.1, Math.abs(boundingBox.max.z - boundingBox.min.z))
}
};
}
return {
center: {
x: 0,
y: 0,
z: 0
},
size: {
x: 1,
y: 1,
z: 1
}
};
}
function createWireframeBox(size, color, opacity) {
return new Mesh(new BoxGeometry(size.x, size.y, size.z), new MeshBasicMaterial({
color,
wireframe: true,
transparent: true,
opacity,
depthWrite: false
}));
}
function createWireframeMaterial(material) {
const source = material;
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.traverse((object) => {
const maybeMesh = object;
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, seenTextures) {
if (seenTextures.has(texture)) {
return;
}
seenTextures.add(texture);
texture.dispose();
}
function disposeMaterialResources(material, disposeTextures, seenTextures) {
if (disposeTextures) {
for (const value of Object.values(material)) {
if (value === null || value === undefined) {
continue;
}
if (Array.isArray(value)) {
for (const entry of value) {
if (entry !== null && typeof entry === "object" && "isTexture" in entry) {
disposeTexture(entry, seenTextures);
}
}
continue;
}
if (typeof value === "object" && "isTexture" in value) {
disposeTexture(value, seenTextures);
}
}
}
material.dispose();
}
function disposeMeshResources(object, disposeTextures, seenTextures) {
const maybeMesh = object;
if (maybeMesh.isMesh !== true) {
return;
}
maybeMesh.geometry.dispose();
if (Array.isArray(maybeMesh.material)) {
for (const material of maybeMesh.material) {
disposeMaterialResources(material, disposeTextures, seenTextures);
}
}
else {
disposeMaterialResources(maybeMesh.material, disposeTextures, seenTextures);
}
}
export function createModelInstanceRenderGroup(modelInstance, asset, loadedAsset, selected = false, previewShellColor, renderMode = "normal") {
const bounds = getLocalModelBounds(asset);
const group = new Group();
group.position.set(modelInstance.position.x, modelInstance.position.y, modelInstance.position.z);
group.rotation.set((modelInstance.rotationDegrees.x * Math.PI) / 180, (modelInstance.rotationDegrees.y * Math.PI) / 180, (modelInstance.rotationDegrees.z * Math.PI) / 180);
group.scale.set(modelInstance.scale.x, modelInstance.scale.y, modelInstance.scale.z);
group.userData.modelInstanceId = modelInstance.id;
group.userData.assetId = modelInstance.assetId;
if (loadedAsset !== undefined) {
const instantiatedModel = instantiateModelTemplate(loadedAsset.template);
if (renderMode === "wireframe") {
applyWireframeMaterialPresentation(instantiatedModel);
}
group.add(instantiatedModel);
}
else {
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);
selectionShell.userData.shadowIgnored = true;
group.add(selectionShell);
}
return group;
}
export function disposeModelInstance(instance) {
const seenTextures = new Set();
instance.traverse((object) => {
disposeMeshResources(object, false, seenTextures);
});
}

View File

@@ -0,0 +1,144 @@
import { createOpaqueId } from "../core/ids";
export const MODEL_INSTANCE_COLLISION_MODES = ["none", "terrain", "static", "dynamic", "simple"];
export const DEFAULT_MODEL_INSTANCE_POSITION = {
x: 0,
y: 0,
z: 0
};
export const DEFAULT_MODEL_INSTANCE_ROTATION_DEGREES = {
x: 0,
y: 0,
z: 0
};
export const DEFAULT_MODEL_INSTANCE_SCALE = {
x: 1,
y: 1,
z: 1
};
export const DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS = {
mode: "none",
visible: false
};
function cloneVec3(vector) {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function areVec3Equal(left, right) {
return left.x === right.x && left.y === right.y && left.z === right.z;
}
export function isModelInstanceCollisionMode(value) {
return MODEL_INSTANCE_COLLISION_MODES.includes(value);
}
export function createModelInstanceCollisionSettings(overrides = {}) {
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) {
return createModelInstanceCollisionSettings(settings);
}
export function areModelInstanceCollisionSettingsEqual(left, right) {
return left.mode === right.mode && left.visible === right.visible;
}
export function normalizeModelInstanceName(name) {
if (name === undefined || name === null) {
return undefined;
}
const trimmedName = name.trim();
return trimmedName.length === 0 ? undefined : trimmedName;
}
function assertFiniteVec3(vector, label) {
if (!Number.isFinite(vector.x) || !Number.isFinite(vector.y) || !Number.isFinite(vector.z)) {
throw new Error(`${label} must be finite on every axis.`);
}
}
function assertPositiveFiniteVec3(vector, label) {
assertFiniteVec3(vector, label);
if (vector.x <= 0 || vector.y <= 0 || vector.z <= 0) {
throw new Error(`${label} must remain positive on every axis.`);
}
}
export function createModelInstance(overrides) {
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.");
}
assertFiniteVec3(position, "Model instance position");
assertFiniteVec3(rotationDegrees, "Model instance rotation");
assertPositiveFiniteVec3(scale, "Model instance scale");
return {
id: overrides.id ?? createOpaqueId("model-instance"),
kind: "modelInstance",
assetId: overrides.assetId,
name: normalizeModelInstanceName(overrides.name),
position,
rotationDegrees,
scale,
collision,
animationClipName: overrides.animationClipName,
animationAutoplay: overrides.animationAutoplay
};
}
export function createModelInstancePlacementPosition(asset, anchor) {
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) {
return createModelInstance(instance);
}
export function areModelInstancesEqual(left, right) {
return (left.id === right.id &&
left.kind === right.kind &&
left.assetId === right.assetId &&
left.name === right.name &&
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);
}
export function compareModelInstances(left, right) {
if (left.assetId !== right.assetId) {
return left.assetId.localeCompare(right.assetId);
}
const leftName = left.name ?? "";
const rightName = right.name ?? "";
if (leftName !== rightName) {
return leftName.localeCompare(rightName);
}
return left.id.localeCompare(right.id);
}
export function getModelInstances(modelInstances) {
return Object.values(modelInstances).sort(compareModelInstances);
}
export function getModelInstanceKindLabel() {
return "Model Instance";
}

View File

@@ -0,0 +1,177 @@
const PROJECT_ASSET_DATABASE_NAME = "webeditor3d-project-assets";
const PROJECT_ASSET_DATABASE_VERSION = 1;
const PROJECT_ASSET_OBJECT_STORE_NAME = "assets";
function cloneArrayBuffer(bytes) {
return bytes.slice(0);
}
function cloneFileRecord(file) {
return {
bytes: cloneArrayBuffer(file.bytes),
mimeType: file.mimeType
};
}
export function cloneProjectAssetStorageRecord(record) {
const files = {};
for (const [path, file] of Object.entries(record.files)) {
files[path] = cloneFileRecord(file);
}
return {
files
};
}
function isObject(value) {
return value !== null && typeof value === "object";
}
function isLegacyProjectAssetStorageRecord(value) {
return (isObject(value) &&
value.bytes instanceof ArrayBuffer &&
typeof value.mimeType === "string");
}
function isProjectAssetStoragePackageRecord(value) {
if (!isObject(value) || !isObject(value.files)) {
return false;
}
return Object.values(value.files).every((entry) => {
return (isObject(entry) &&
entry.bytes instanceof ArrayBuffer &&
typeof entry.mimeType === "string");
});
}
function normalizeStoredAssetRecord(storageKey, value) {
if (isProjectAssetStoragePackageRecord(value)) {
return cloneProjectAssetStorageRecord(value);
}
if (isLegacyProjectAssetStorageRecord(value)) {
return {
files: {
[storageKey]: cloneFileRecord(value)
}
};
}
return null;
}
function getErrorDetail(error) {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message.trim();
}
return "Unknown error.";
}
function formatDiagnostic(prefix, error) {
return `${prefix} ${getErrorDetail(error)}`;
}
function promisifyRequest(request) {
return new Promise((resolve, reject) => {
request.addEventListener("success", () => {
resolve(request.result);
});
request.addEventListener("error", () => {
reject(request.error ?? new Error("IndexedDB request failed."));
});
});
}
function openIndexedDb() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(PROJECT_ASSET_DATABASE_NAME, PROJECT_ASSET_DATABASE_VERSION);
request.addEventListener("upgradeneeded", () => {
const database = request.result;
if (!database.objectStoreNames.contains(PROJECT_ASSET_OBJECT_STORE_NAME)) {
database.createObjectStore(PROJECT_ASSET_OBJECT_STORE_NAME);
}
});
request.addEventListener("success", () => {
resolve(request.result);
});
request.addEventListener("error", () => {
reject(request.error ?? new Error("IndexedDB open failed."));
});
});
}
class IndexedDbProjectAssetStorage {
databasePromise;
constructor(databasePromise) {
this.databasePromise = databasePromise;
}
async withStore(mode, callback) {
const database = await this.databasePromise;
const transaction = database.transaction(PROJECT_ASSET_OBJECT_STORE_NAME, mode);
const store = transaction.objectStore(PROJECT_ASSET_OBJECT_STORE_NAME);
const result = await promisifyRequest(callback(store));
await new Promise((resolve, reject) => {
transaction.addEventListener("complete", () => resolve());
transaction.addEventListener("error", () => reject(transaction.error ?? new Error("IndexedDB transaction failed.")));
transaction.addEventListener("abort", () => reject(transaction.error ?? new Error("IndexedDB transaction aborted.")));
});
return result;
}
async getAsset(storageKey) {
const database = await this.databasePromise;
const transaction = database.transaction(PROJECT_ASSET_OBJECT_STORE_NAME, "readonly");
const store = transaction.objectStore(PROJECT_ASSET_OBJECT_STORE_NAME);
const result = await promisifyRequest(store.get(storageKey));
return normalizeStoredAssetRecord(storageKey, result);
}
async putAsset(storageKey, asset) {
await this.withStore("readwrite", (store) => store.put(cloneProjectAssetStorageRecord(asset), storageKey));
}
async deleteAsset(storageKey) {
await this.withStore("readwrite", (store) => store.delete(storageKey));
}
}
class InMemoryProjectAssetStorage {
values = new Map();
constructor(initialValues = {}) {
for (const [storageKey, asset] of Object.entries(initialValues)) {
this.values.set(storageKey, cloneStoredAsset(asset));
}
}
async getAsset(storageKey) {
const asset = this.values.get(storageKey);
if (asset === undefined) {
return null;
}
return normalizeStoredAssetRecord(storageKey, asset);
}
async putAsset(storageKey, asset) {
this.values.set(storageKey, cloneProjectAssetStorageRecord(asset));
}
async deleteAsset(storageKey) {
this.values.delete(storageKey);
}
}
function cloneStoredAsset(asset) {
if (isLegacyProjectAssetStorageRecord(asset)) {
return cloneFileRecord(asset);
}
return cloneProjectAssetStorageRecord(asset);
}
export function createInMemoryProjectAssetStorage(initialValues = {}) {
return new InMemoryProjectAssetStorage(initialValues);
}
export async function getBrowserProjectAssetStorageAccess() {
if (typeof window === "undefined") {
return {
storage: null,
diagnostic: null
};
}
if (typeof indexedDB === "undefined") {
return {
storage: null,
diagnostic: "IndexedDB is unavailable in this browser environment."
};
}
try {
const databasePromise = openIndexedDb();
await databasePromise;
return {
storage: new IndexedDbProjectAssetStorage(databasePromise),
diagnostic: null
};
}
catch (error) {
return {
storage: null,
diagnostic: formatDiagnostic("Project asset storage could not be opened.", error)
};
}
}

View File

@@ -0,0 +1,100 @@
export const PROJECT_ASSET_KINDS = ["model", "image", "audio"];
export function createProjectAssetStorageKey(assetId) {
return `project-asset:${assetId}`;
}
export function isProjectAssetKind(value) {
return value === "model" || value === "image" || value === "audio";
}
function cloneVec3(vector) {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function cloneBoundingBox(boundingBox) {
if (boundingBox === null) {
return null;
}
return {
min: cloneVec3(boundingBox.min),
max: cloneVec3(boundingBox.max),
size: cloneVec3(boundingBox.size)
};
}
function cloneModelAssetMetadata(metadata) {
return {
kind: "model",
format: metadata.format,
sceneName: metadata.sceneName,
nodeCount: metadata.nodeCount,
meshCount: metadata.meshCount,
materialNames: [...metadata.materialNames],
textureNames: [...metadata.textureNames],
animationNames: [...metadata.animationNames],
boundingBox: cloneBoundingBox(metadata.boundingBox),
warnings: [...metadata.warnings]
};
}
function cloneImageAssetMetadata(metadata) {
return {
kind: "image",
width: metadata.width,
height: metadata.height,
hasAlpha: metadata.hasAlpha,
warnings: [...metadata.warnings]
};
}
function cloneAudioAssetMetadata(metadata) {
return {
kind: "audio",
durationSeconds: metadata.durationSeconds,
channelCount: metadata.channelCount,
sampleRateHz: metadata.sampleRateHz,
warnings: [...metadata.warnings]
};
}
export function cloneProjectAssetRecord(asset) {
switch (asset.kind) {
case "model":
return {
id: asset.id,
kind: "model",
sourceName: asset.sourceName,
mimeType: asset.mimeType,
storageKey: asset.storageKey,
byteLength: asset.byteLength,
metadata: cloneModelAssetMetadata(asset.metadata)
};
case "image":
return {
id: asset.id,
kind: "image",
sourceName: asset.sourceName,
mimeType: asset.mimeType,
storageKey: asset.storageKey,
byteLength: asset.byteLength,
metadata: cloneImageAssetMetadata(asset.metadata)
};
case "audio":
return {
id: asset.id,
kind: "audio",
sourceName: asset.sourceName,
mimeType: asset.mimeType,
storageKey: asset.storageKey,
byteLength: asset.byteLength,
metadata: cloneAudioAssetMetadata(asset.metadata)
};
}
}
export function getProjectAssetKindLabel(kind) {
switch (kind) {
case "model":
return "Model";
case "image":
return "Image";
case "audio":
return "Audio";
}
}

View File

@@ -0,0 +1,82 @@
import { cloneEditorSelection } from "../core/selection";
import { cloneFaceUvState } from "../document/brushes";
export function getBoxBrushOrThrow(document, brushId) {
const brush = document.brushes[brushId];
if (brush === undefined) {
throw new Error(`Box brush ${brushId} does not exist.`);
}
if (brush.kind !== "box") {
throw new Error(`Brush ${brushId} is not a supported box brush.`);
}
return brush;
}
export function setSingleBrushSelection(brushId) {
return {
kind: "brushes",
ids: [brushId]
};
}
export function setSingleBrushFaceSelection(brushId, faceId) {
return {
kind: "brushFace",
brushId,
faceId
};
}
export function setSingleBrushEdgeSelection(brushId, edgeId) {
return {
kind: "brushEdge",
brushId,
edgeId
};
}
export function setSingleBrushVertexSelection(brushId, vertexId) {
return {
kind: "brushVertex",
brushId,
vertexId
};
}
export function cloneSelectionForCommand(selection) {
return cloneEditorSelection(selection);
}
export function replaceBrush(document, brush) {
return {
...document,
brushes: {
...document.brushes,
[brush.id]: brush
}
};
}
export function removeBrush(document, brushId) {
const remainingBrushes = {
...document.brushes
};
delete remainingBrushes[brushId];
return {
...document,
brushes: remainingBrushes
};
}
export function getBoxBrushFaceOrThrow(document, brushId, faceId) {
const brush = getBoxBrushOrThrow(document, brushId);
const face = brush.faces[faceId];
if (face === undefined) {
throw new Error(`Box brush ${brushId} does not contain face ${faceId}.`);
}
return face;
}
export function replaceBoxBrushFace(document, brushId, faceId, face) {
const brush = getBoxBrushOrThrow(document, brushId);
return replaceBrush(document, {
...brush,
faces: {
...brush.faces,
[faceId]: {
materialId: face.materialId,
uv: cloneFaceUvState(face.uv)
}
}
});
}

View File

@@ -0,0 +1,37 @@
export class CommandHistory {
undoStack = [];
redoStack = [];
execute(command, context) {
command.execute(context);
this.undoStack.push(command);
this.redoStack.length = 0;
}
undo(context) {
const command = this.undoStack.pop();
if (command === undefined) {
return null;
}
command.undo(context);
this.redoStack.push(command);
return command;
}
redo(context) {
const command = this.redoStack.pop();
if (command === undefined) {
return null;
}
command.execute(context);
this.undoStack.push(command);
return command;
}
clear() {
this.undoStack.length = 0;
this.redoStack.length = 0;
}
canUndo() {
return this.undoStack.length > 0;
}
canRedo() {
return this.redoStack.length > 0;
}
}

1
src/commands/command.js Normal file
View File

@@ -0,0 +1 @@
export {};

View File

@@ -1,10 +1,12 @@
import type { EditorSelection } from "../core/selection";
import type { ToolMode } from "../core/tool-mode";
import type { SceneDocument } from "../document/scene-document";
import type { ProjectDocument, SceneDocument } from "../document/scene-document";
export interface CommandContext {
getDocument(): SceneDocument;
setDocument(document: SceneDocument): void;
getProjectDocument(): ProjectDocument;
setProjectDocument(document: ProjectDocument): void;
getSelection(): EditorSelection;
setSelection(selection: EditorSelection): void;
getToolMode(): ToolMode;

View File

@@ -0,0 +1,200 @@
import { createMoveBoxBrushCommand } from "./move-box-brush-command";
import { createResizeBoxBrushCommand } from "./resize-box-brush-command";
import { createRotateBoxBrushCommand } from "./rotate-box-brush-command";
import { createSetBoxBrushTransformCommand } from "./set-box-brush-transform-command";
import { createUpsertEntityCommand } from "./upsert-entity-command";
import { createUpsertModelInstanceCommand } from "./upsert-model-instance-command";
import { createModelInstance } from "../assets/model-instances";
import { createInteractableEntity, createPlayerStartEntity, createPointLightEntity, createSoundEmitterEntity, createSpotLightEntity, createTeleportTargetEntity, createTriggerVolumeEntity } from "../entities/entity-instances";
import { getTransformOperationLabel } from "../core/transform-session";
function createTransformCommandLabel(session) {
return `${getTransformOperationLabel(session.operation)} ${session.target.kind === "brush"
? "whitebox box"
: session.target.kind === "brushFace"
? "whitebox face"
: session.target.kind === "brushEdge"
? "whitebox edge"
: session.target.kind === "brushVertex"
? "whitebox vertex"
: 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, session) {
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 "brushFace":
if (session.preview.kind !== "brush") {
throw new Error("Whitebox face transform preview is invalid.");
}
return createSetBoxBrushTransformCommand({
selection: {
kind: "brushFace",
brushId: session.target.brushId,
faceId: session.target.faceId
},
center: session.preview.center,
rotationDegrees: session.preview.rotationDegrees,
size: session.preview.size,
geometry: session.preview.geometry,
label: createTransformCommandLabel(session)
});
case "brushEdge":
if (session.preview.kind !== "brush") {
throw new Error("Whitebox edge transform preview is invalid.");
}
return createSetBoxBrushTransformCommand({
selection: {
kind: "brushEdge",
brushId: session.target.brushId,
edgeId: session.target.edgeId
},
center: session.preview.center,
rotationDegrees: session.preview.rotationDegrees,
size: session.preview.size,
geometry: session.preview.geometry,
label: createTransformCommandLabel(session)
});
case "brushVertex":
if (session.preview.kind !== "brush") {
throw new Error("Whitebox vertex transform preview is invalid.");
}
return createSetBoxBrushTransformCommand({
selection: {
kind: "brushVertex",
brushId: session.target.brushId,
vertexId: session.target.vertexId
},
center: session.preview.center,
rotationDegrees: session.preview.rotationDegrees,
size: session.preview.size,
geometry: session.preview.geometry,
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)
});
}
}
}
}

View File

@@ -1,6 +1,7 @@
import { createMoveBoxBrushCommand } from "./move-box-brush-command";
import { createResizeBoxBrushCommand } from "./resize-box-brush-command";
import { createRotateBoxBrushCommand } from "./rotate-box-brush-command";
import { createSetBoxBrushTransformCommand } from "./set-box-brush-transform-command";
import { createUpsertEntityCommand } from "./upsert-entity-command";
import { createUpsertModelInstanceCommand } from "./upsert-model-instance-command";
import type { EditorCommand } from "./command";
@@ -10,6 +11,8 @@ import {
createInteractableEntity,
createPlayerStartEntity,
createPointLightEntity,
createSceneEntryEntity,
createSceneExitEntity,
createSoundEmitterEntity,
createSpotLightEntity,
createTeleportTargetEntity,
@@ -24,6 +27,12 @@ function createTransformCommandLabel(session: ActiveTransformSession): string {
return `${getTransformOperationLabel(session.operation)} ${
session.target.kind === "brush"
? "whitebox box"
: session.target.kind === "brushFace"
? "whitebox face"
: session.target.kind === "brushEdge"
? "whitebox edge"
: session.target.kind === "brushVertex"
? "whitebox vertex"
: session.target.kind === "entity"
? session.target.entityKind === "playerStart"
? "player start"
@@ -35,9 +44,13 @@ function createTransformCommandLabel(session: ActiveTransformSession): string {
? "sound emitter"
: session.target.entityKind === "triggerVolume"
? "trigger volume"
: session.target.entityKind === "sceneEntry"
? "scene entry"
: session.target.entityKind === "teleportTarget"
? "teleport target"
: "interactable"
: session.target.entityKind === "interactable"
? "interactable"
: "scene exit"
: "model instance"
}`;
}
@@ -71,6 +84,57 @@ export function createCommitTransformSessionCommand(document: SceneDocument, ses
label: createTransformCommandLabel(session)
});
}
case "brushFace":
if (session.preview.kind !== "brush") {
throw new Error("Whitebox face transform preview is invalid.");
}
return createSetBoxBrushTransformCommand({
selection: {
kind: "brushFace",
brushId: session.target.brushId,
faceId: session.target.faceId
},
center: session.preview.center,
rotationDegrees: session.preview.rotationDegrees,
size: session.preview.size,
geometry: session.preview.geometry,
label: createTransformCommandLabel(session)
});
case "brushEdge":
if (session.preview.kind !== "brush") {
throw new Error("Whitebox edge transform preview is invalid.");
}
return createSetBoxBrushTransformCommand({
selection: {
kind: "brushEdge",
brushId: session.target.brushId,
edgeId: session.target.edgeId
},
center: session.preview.center,
rotationDegrees: session.preview.rotationDegrees,
size: session.preview.size,
geometry: session.preview.geometry,
label: createTransformCommandLabel(session)
});
case "brushVertex":
if (session.preview.kind !== "brush") {
throw new Error("Whitebox vertex transform preview is invalid.");
}
return createSetBoxBrushTransformCommand({
selection: {
kind: "brushVertex",
brushId: session.target.brushId,
vertexId: session.target.vertexId
},
center: session.preview.center,
rotationDegrees: session.preview.rotationDegrees,
size: session.preview.size,
geometry: session.preview.geometry,
label: createTransformCommandLabel(session)
});
case "modelInstance": {
if (session.preview.kind !== "modelInstance") {
throw new Error("Model instance transform preview is invalid.");
@@ -130,6 +194,18 @@ export function createCommitTransformSessionCommand(document: SceneDocument, ses
}),
label: createTransformCommandLabel(session)
});
case "sceneEntry":
return createUpsertEntityCommand({
entity: createSceneEntryEntity({
...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({
@@ -163,6 +239,14 @@ export function createCommitTransformSessionCommand(document: SceneDocument, ses
}),
label: createTransformCommandLabel(session)
});
case "sceneExit":
return createUpsertEntityCommand({
entity: createSceneExitEntity({
...entity,
position: session.preview.position
}),
label: createTransformCommandLabel(session)
});
}
}
}

View File

@@ -0,0 +1,51 @@
import { createBoxBrush, DEFAULT_BOX_BRUSH_CENTER, DEFAULT_BOX_BRUSH_SIZE } from "../document/brushes";
import { DEFAULT_GRID_SIZE, snapPositiveSizeToGrid, snapVec3ToGrid } from "../geometry/grid-snapping";
import { createOpaqueId } from "../core/ids";
import { cloneSelectionForCommand, removeBrush, setSingleBrushSelection } from "./brush-command-helpers";
export function createCreateBoxBrushCommand(options = {}) {
const snapToGrid = options.snapToGrid ?? true;
const brush = createBoxBrush({
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 = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: "Create box brush",
execute(context) {
const currentDocument = context.getDocument();
if (currentDocument.brushes[brush.id] !== undefined) {
throw new Error(`Box brush ${brush.id} already exists.`);
}
if (previousSelection === null) {
previousSelection = cloneSelectionForCommand(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
context.setDocument({
...currentDocument,
brushes: {
...currentDocument.brushes,
[brush.id]: brush
}
});
context.setSelection(setSingleBrushSelection(brush.id));
context.setToolMode("select");
},
undo(context) {
context.setDocument(removeBrush(context.getDocument(), brush.id));
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,69 @@
import { createOpaqueId } from "../core/ids";
import {
createEmptyProjectScene,
type ProjectDocument
} from "../document/scene-document";
import type { EditorCommand } from "./command";
function createUniqueSceneName(existingNames: string[]): string {
const normalizedNames = new Set(
existingNames.map((name) => name.trim().toLowerCase())
);
let suffix = existingNames.length + 1;
while (normalizedNames.has(`scene ${suffix}`)) {
suffix += 1;
}
return `Scene ${suffix}`;
}
export function createCreateSceneCommand(): EditorCommand {
const createdSceneId = createOpaqueId("scene");
let createdSceneName: string | null = null;
let previousProjectDocumentSerialized: string | null = null;
return {
id: createOpaqueId("command"),
label: "Create scene",
execute(context) {
const currentProjectDocument = context.getProjectDocument();
if (previousProjectDocumentSerialized === null) {
previousProjectDocumentSerialized = JSON.stringify(currentProjectDocument);
}
if (createdSceneName === null) {
createdSceneName = createUniqueSceneName(
Object.values(currentProjectDocument.scenes).map((scene) => scene.name)
);
}
context.setProjectDocument({
...currentProjectDocument,
activeSceneId: createdSceneId,
scenes: {
...currentProjectDocument.scenes,
[createdSceneId]: createEmptyProjectScene({
id: createdSceneId,
name: createdSceneName
})
}
});
context.setSelection({ kind: "none" });
context.setToolMode("select");
},
undo(context) {
if (previousProjectDocumentSerialized === null) {
return;
}
context.setProjectDocument(
JSON.parse(previousProjectDocumentSerialized) as ProjectDocument
);
context.setSelection({ kind: "none" });
context.setToolMode("select");
}
};
}

View File

@@ -0,0 +1,59 @@
import { createOpaqueId } from "../core/ids";
import { cloneBoxBrush } from "../document/brushes";
import { cloneSelectionForCommand, removeBrush } from "./brush-command-helpers";
function selectionIncludesBrush(selection, brushId) {
return ((selection.kind === "brushes" && selection.ids.includes(brushId)) ||
((selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") &&
selection.brushId === brushId));
}
export function createDeleteBoxBrushCommand(brushId) {
let previousBrush = null;
let previousSelection = null;
let previousToolMode = 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);
}
}
};
}

View File

@@ -0,0 +1,64 @@
import { createOpaqueId } from "../core/ids";
import { cloneEditorSelection } from "../core/selection";
import { cloneEntityInstance } from "../entities/entity-instances";
function selectionIncludesEntity(selection, entityId) {
return selection.kind === "entities" && selection.ids.includes(entityId);
}
export function createDeleteEntityCommand(entityId) {
let previousEntity = null;
let previousSelection = null;
let previousToolMode = 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);
}
}
};
}

View File

@@ -0,0 +1,40 @@
import { createOpaqueId } from "../core/ids";
import { cloneInteractionLink } from "../interactions/interaction-links";
export function createDeleteInteractionLinkCommand(linkId) {
let previousLink = null;
return {
id: createOpaqueId("command"),
label: "Delete interaction link",
execute(context) {
const currentDocument = context.getDocument();
const currentLink = currentDocument.interactionLinks[linkId];
if (currentLink === undefined) {
throw new Error(`Interaction link ${linkId} does not exist.`);
}
if (previousLink === null) {
previousLink = cloneInteractionLink(currentLink);
}
const nextInteractionLinks = {
...currentDocument.interactionLinks
};
delete nextInteractionLinks[linkId];
context.setDocument({
...currentDocument,
interactionLinks: nextInteractionLinks
});
},
undo(context) {
if (previousLink === null) {
return;
}
const currentDocument = context.getDocument();
context.setDocument({
...currentDocument,
interactionLinks: {
...currentDocument.interactionLinks,
[previousLink.id]: cloneInteractionLink(previousLink)
}
});
}
};
}

View File

@@ -0,0 +1,64 @@
import { createOpaqueId } from "../core/ids";
import { cloneEditorSelection } from "../core/selection";
import { cloneModelInstance } from "../assets/model-instances";
function selectionIncludesModelInstance(selection, modelInstanceId) {
return selection.kind === "modelInstances" && selection.ids.includes(modelInstanceId);
}
export function createDeleteModelInstanceCommand(modelInstanceId) {
let previousModelInstance = null;
let previousSelection = null;
let previousToolMode = 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);
}
}
};
}

View File

@@ -0,0 +1,237 @@
import { cloneModelInstance } from "../assets/model-instances";
import { createOpaqueId } from "../core/ids";
import { cloneEditorSelection } from "../core/selection";
import { cloneBoxBrush } from "../document/brushes";
import { cloneEntityInstance } from "../entities/entity-instances";
function duplicateBrush(brush) {
const duplicatedBrush = cloneBoxBrush(brush);
duplicatedBrush.id = createOpaqueId("brush");
return duplicatedBrush;
}
function duplicateEntity(entity) {
const duplicatedEntity = cloneEntityInstance(entity);
duplicatedEntity.id = createOpaqueId(`entity-${duplicatedEntity.kind}`);
return duplicatedEntity;
}
function duplicateModelInstance(modelInstance) {
const duplicatedModelInstance = cloneModelInstance(modelInstance);
duplicatedModelInstance.id = createOpaqueId("model-instance");
return duplicatedModelInstance;
}
function resolveDuplicatableBrushIds(selection) {
switch (selection.kind) {
case "brushes":
return selection.ids;
case "brushFace":
case "brushEdge":
case "brushVertex":
return [selection.brushId];
default:
return null;
}
}
function createDuplicateSelectionResult(currentDocument, selection) {
const duplicatableBrushIds = resolveDuplicatableBrushIds(selection);
if (duplicatableBrushIds !== null) {
if (duplicatableBrushIds.length === 0) {
throw new Error("Select at least one whitebox solid to duplicate.");
}
const duplicatedBrushes = duplicatableBrushIds.map((brushId) => {
const sourceBrush = currentDocument.brushes[brushId];
if (sourceBrush === undefined) {
throw new Error(`Box brush ${brushId} does not exist.`);
}
if (sourceBrush.kind !== "box") {
throw new Error(`Brush ${brushId} is not a supported box brush.`);
}
return duplicateBrush(sourceBrush);
});
return {
selection: {
kind: "brushes",
ids: duplicatedBrushes.map((brush) => brush.id)
},
brushes: duplicatedBrushes,
entities: null,
modelInstances: null
};
}
if (selection.kind === "entities") {
if (selection.ids.length === 0) {
throw new Error("Select at least one entity to duplicate.");
}
const duplicatedEntities = selection.ids.map((entityId) => {
const sourceEntity = currentDocument.entities[entityId];
if (sourceEntity === undefined) {
throw new Error(`Entity ${entityId} does not exist.`);
}
return duplicateEntity(sourceEntity);
});
return {
selection: {
kind: "entities",
ids: duplicatedEntities.map((entity) => entity.id)
},
brushes: null,
entities: duplicatedEntities,
modelInstances: null
};
}
if (selection.kind === "modelInstances") {
if (selection.ids.length === 0) {
throw new Error("Select at least one model instance to duplicate.");
}
const duplicatedModelInstances = selection.ids.map((modelInstanceId) => {
const sourceModelInstance = currentDocument.modelInstances[modelInstanceId];
if (sourceModelInstance === undefined) {
throw new Error(`Model instance ${modelInstanceId} does not exist.`);
}
return duplicateModelInstance(sourceModelInstance);
});
return {
selection: {
kind: "modelInstances",
ids: duplicatedModelInstances.map((modelInstance) => modelInstance.id)
},
brushes: null,
entities: null,
modelInstances: duplicatedModelInstances
};
}
throw new Error("Selection must contain whitebox solids, entities, or model instances to duplicate.");
}
export function createDuplicateSelectionCommand() {
let previousSelection = null;
let previousToolMode = null;
let duplicateSelectionResult = null;
return {
id: createOpaqueId("command"),
label: "Duplicate selection",
execute(context) {
const currentDocument = context.getDocument();
if (previousSelection === null) {
previousSelection = cloneEditorSelection(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
if (duplicateSelectionResult === null) {
duplicateSelectionResult = createDuplicateSelectionResult(currentDocument, context.getSelection());
}
if (duplicateSelectionResult.brushes !== null) {
context.setDocument({
...currentDocument,
brushes: {
...currentDocument.brushes,
...Object.fromEntries(duplicateSelectionResult.brushes.map((brush) => [brush.id, cloneBoxBrush(brush)]))
}
});
} else if (duplicateSelectionResult.entities !== null) {
context.setDocument({
...currentDocument,
entities: {
...currentDocument.entities,
...Object.fromEntries(duplicateSelectionResult.entities.map((entity) => [entity.id, cloneEntityInstance(entity)]))
}
});
} else if (duplicateSelectionResult.modelInstances !== null) {
context.setDocument({
...currentDocument,
modelInstances: {
...currentDocument.modelInstances,
...Object.fromEntries(
duplicateSelectionResult.modelInstances.map((modelInstance) => [modelInstance.id, cloneModelInstance(modelInstance)])
)
}
});
}
context.setSelection(cloneEditorSelection(duplicateSelectionResult.selection));
context.setToolMode("select");
},
undo(context) {
if (duplicateSelectionResult === null) {
return;
}
const currentDocument = context.getDocument();
if (duplicateSelectionResult.brushes !== null) {
const nextBrushes = {
...currentDocument.brushes
};
for (const duplicatedBrush of duplicateSelectionResult.brushes) {
delete nextBrushes[duplicatedBrush.id];
}
context.setDocument({
...currentDocument,
brushes: nextBrushes
});
} else if (duplicateSelectionResult.entities !== null) {
const nextEntities = {
...currentDocument.entities
};
for (const duplicatedEntity of duplicateSelectionResult.entities) {
delete nextEntities[duplicatedEntity.id];
}
context.setDocument({
...currentDocument,
entities: nextEntities
});
} else if (duplicateSelectionResult.modelInstances !== null) {
const nextModelInstances = {
...currentDocument.modelInstances
};
for (const duplicatedModelInstance of duplicateSelectionResult.modelInstances) {
delete nextModelInstances[duplicatedModelInstance.id];
}
context.setDocument({
...currentDocument,
modelInstances: nextModelInstances
});
}
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,248 @@
import { cloneModelInstance, type ModelInstance } from "../assets/model-instances";
import { createOpaqueId } from "../core/ids";
import { cloneEditorSelection, type EditorSelection } from "../core/selection";
import type { ToolMode } from "../core/tool-mode";
import { cloneBoxBrush, type BoxBrush } from "../document/brushes";
import type { SceneDocument } from "../document/scene-document";
import { cloneEntityInstance, type EntityInstance } from "../entities/entity-instances";
import type { EditorCommand } from "./command";
interface DuplicateSelectionResult {
selection: EditorSelection;
brushes: BoxBrush[] | null;
entities: EntityInstance[] | null;
modelInstances: ModelInstance[] | null;
}
function duplicateBrush(brush: BoxBrush): BoxBrush {
const duplicatedBrush = cloneBoxBrush(brush);
duplicatedBrush.id = createOpaqueId("brush");
return duplicatedBrush;
}
function duplicateEntity(entity: EntityInstance): EntityInstance {
const duplicatedEntity = cloneEntityInstance(entity);
duplicatedEntity.id = createOpaqueId(`entity-${duplicatedEntity.kind}`);
return duplicatedEntity;
}
function duplicateModelInstance(modelInstance: ModelInstance): ModelInstance {
const duplicatedModelInstance = cloneModelInstance(modelInstance);
duplicatedModelInstance.id = createOpaqueId("model-instance");
return duplicatedModelInstance;
}
function resolveDuplicatableBrushIds(selection: EditorSelection): string[] | null {
switch (selection.kind) {
case "brushes":
return selection.ids;
case "brushFace":
case "brushEdge":
case "brushVertex":
return [selection.brushId];
default:
return null;
}
}
function createDuplicateSelectionResult(currentDocument: SceneDocument, selection: EditorSelection): DuplicateSelectionResult {
const duplicatableBrushIds = resolveDuplicatableBrushIds(selection);
if (duplicatableBrushIds !== null) {
if (duplicatableBrushIds.length === 0) {
throw new Error("Select at least one whitebox solid to duplicate.");
}
const duplicatedBrushes = duplicatableBrushIds.map((brushId) => {
const sourceBrush = currentDocument.brushes[brushId];
if (sourceBrush === undefined) {
throw new Error(`Box brush ${brushId} does not exist.`);
}
if (sourceBrush.kind !== "box") {
throw new Error(`Brush ${brushId} is not a supported box brush.`);
}
return duplicateBrush(sourceBrush);
});
return {
selection: {
kind: "brushes",
ids: duplicatedBrushes.map((brush) => brush.id)
},
brushes: duplicatedBrushes,
entities: null,
modelInstances: null
};
}
if (selection.kind === "entities") {
if (selection.ids.length === 0) {
throw new Error("Select at least one entity to duplicate.");
}
const duplicatedEntities = selection.ids.map((entityId) => {
const sourceEntity = currentDocument.entities[entityId];
if (sourceEntity === undefined) {
throw new Error(`Entity ${entityId} does not exist.`);
}
return duplicateEntity(sourceEntity);
});
return {
selection: {
kind: "entities",
ids: duplicatedEntities.map((entity) => entity.id)
},
brushes: null,
entities: duplicatedEntities,
modelInstances: null
};
}
if (selection.kind === "modelInstances") {
if (selection.ids.length === 0) {
throw new Error("Select at least one model instance to duplicate.");
}
const duplicatedModelInstances = selection.ids.map((modelInstanceId) => {
const sourceModelInstance = currentDocument.modelInstances[modelInstanceId];
if (sourceModelInstance === undefined) {
throw new Error(`Model instance ${modelInstanceId} does not exist.`);
}
return duplicateModelInstance(sourceModelInstance);
});
return {
selection: {
kind: "modelInstances",
ids: duplicatedModelInstances.map((modelInstance) => modelInstance.id)
},
brushes: null,
entities: null,
modelInstances: duplicatedModelInstances
};
}
throw new Error("Selection must contain whitebox solids, entities, or model instances to duplicate.");
}
export function createDuplicateSelectionCommand(): EditorCommand {
let previousSelection: EditorSelection | null = null;
let previousToolMode: ToolMode | null = null;
let duplicateSelectionResult: DuplicateSelectionResult | null = null;
return {
id: createOpaqueId("command"),
label: "Duplicate selection",
execute(context) {
const currentDocument = context.getDocument();
if (previousSelection === null) {
previousSelection = cloneEditorSelection(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
if (duplicateSelectionResult === null) {
duplicateSelectionResult = createDuplicateSelectionResult(currentDocument, context.getSelection());
}
if (duplicateSelectionResult.brushes !== null) {
context.setDocument({
...currentDocument,
brushes: {
...currentDocument.brushes,
...Object.fromEntries(duplicateSelectionResult.brushes.map((brush) => [brush.id, cloneBoxBrush(brush)]))
}
});
} else if (duplicateSelectionResult.entities !== null) {
context.setDocument({
...currentDocument,
entities: {
...currentDocument.entities,
...Object.fromEntries(duplicateSelectionResult.entities.map((entity) => [entity.id, cloneEntityInstance(entity)]))
}
});
} else if (duplicateSelectionResult.modelInstances !== null) {
context.setDocument({
...currentDocument,
modelInstances: {
...currentDocument.modelInstances,
...Object.fromEntries(
duplicateSelectionResult.modelInstances.map((modelInstance) => [modelInstance.id, cloneModelInstance(modelInstance)])
)
}
});
}
context.setSelection(cloneEditorSelection(duplicateSelectionResult.selection));
context.setToolMode("select");
},
undo(context) {
if (duplicateSelectionResult === null) {
return;
}
const currentDocument = context.getDocument();
if (duplicateSelectionResult.brushes !== null) {
const nextBrushes = {
...currentDocument.brushes
};
for (const duplicatedBrush of duplicateSelectionResult.brushes) {
delete nextBrushes[duplicatedBrush.id];
}
context.setDocument({
...currentDocument,
brushes: nextBrushes
});
} else if (duplicateSelectionResult.entities !== null) {
const nextEntities = {
...currentDocument.entities
};
for (const duplicatedEntity of duplicateSelectionResult.entities) {
delete nextEntities[duplicatedEntity.id];
}
context.setDocument({
...currentDocument,
entities: nextEntities
});
} else if (duplicateSelectionResult.modelInstances !== null) {
const nextModelInstances = {
...currentDocument.modelInstances
};
for (const duplicatedModelInstance of duplicateSelectionResult.modelInstances) {
delete nextModelInstances[duplicatedModelInstance.id];
}
context.setDocument({
...currentDocument,
modelInstances: nextModelInstances
});
}
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,33 @@
import { createOpaqueId } from "../core/ids";
import { cloneProjectAssetRecord } from "../assets/project-assets";
export function createImportAudioAssetCommand(options) {
const nextAsset = cloneProjectAssetRecord(options.asset);
return {
id: createOpaqueId("command"),
label: options.label ?? `Import ${nextAsset.sourceName}`,
execute(context) {
const currentDocument = context.getDocument();
if (currentDocument.assets[nextAsset.id] !== undefined) {
throw new Error(`Asset ${nextAsset.id} already exists.`);
}
context.setDocument({
...currentDocument,
assets: {
...currentDocument.assets,
[nextAsset.id]: cloneProjectAssetRecord(nextAsset)
}
});
},
undo(context) {
const currentDocument = context.getDocument();
const nextAssets = {
...currentDocument.assets
};
delete nextAssets[nextAsset.id];
context.setDocument({
...currentDocument,
assets: nextAssets
});
}
};
}

View File

@@ -0,0 +1,41 @@
import { createOpaqueId } from "../core/ids";
import { cloneWorldSettings } from "../document/world-settings";
import { cloneProjectAssetRecord } from "../assets/project-assets";
export function createImportBackgroundImageAssetCommand(options) {
const nextAsset = cloneProjectAssetRecord(options.asset);
const nextWorld = cloneWorldSettings(options.world);
let previousWorld = null;
return {
id: createOpaqueId("command"),
label: options.label ?? `Import ${nextAsset.sourceName} as background`,
execute(context) {
const currentDocument = context.getDocument();
if (currentDocument.assets[nextAsset.id] !== undefined) {
throw new Error(`Asset ${nextAsset.id} already exists.`);
}
if (previousWorld === null) {
previousWorld = cloneWorldSettings(currentDocument.world);
}
context.setDocument({
...currentDocument,
assets: {
...currentDocument.assets,
[nextAsset.id]: cloneProjectAssetRecord(nextAsset)
},
world: cloneWorldSettings(nextWorld)
});
},
undo(context) {
const currentDocument = context.getDocument();
const nextAssets = {
...currentDocument.assets
};
delete nextAssets[nextAsset.id];
context.setDocument({
...currentDocument,
assets: nextAssets,
world: previousWorld === null ? cloneWorldSettings(currentDocument.world) : cloneWorldSettings(previousWorld)
});
}
};
}

View File

@@ -0,0 +1,70 @@
import { createOpaqueId } from "../core/ids";
import { cloneEditorSelection } from "../core/selection";
import { cloneModelInstance } from "../assets/model-instances";
import { cloneProjectAssetRecord } from "../assets/project-assets";
function setSingleModelInstanceSelection(modelInstanceId) {
return {
kind: "modelInstances",
ids: [modelInstanceId]
};
}
export function createImportModelAssetCommand(options) {
const nextAsset = cloneProjectAssetRecord(options.asset);
const nextModelInstance = cloneModelInstance(options.modelInstance);
let previousSelection = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: options.label ?? `Import ${nextAsset.sourceName}`,
execute(context) {
const currentDocument = context.getDocument();
if (currentDocument.assets[nextAsset.id] !== undefined) {
throw new Error(`Asset ${nextAsset.id} already exists.`);
}
if (currentDocument.modelInstances[nextModelInstance.id] !== undefined) {
throw new Error(`Model instance ${nextModelInstance.id} already exists.`);
}
if (previousSelection === null) {
previousSelection = cloneEditorSelection(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
context.setDocument({
...currentDocument,
assets: {
...currentDocument.assets,
[nextAsset.id]: cloneProjectAssetRecord(nextAsset)
},
modelInstances: {
...currentDocument.modelInstances,
[nextModelInstance.id]: cloneModelInstance(nextModelInstance)
}
});
context.setSelection(setSingleModelInstanceSelection(nextModelInstance.id));
context.setToolMode("select");
},
undo(context) {
const currentDocument = context.getDocument();
const nextAssets = {
...currentDocument.assets
};
const nextModelInstances = {
...currentDocument.modelInstances
};
delete nextAssets[nextAsset.id];
delete nextModelInstances[nextModelInstance.id];
context.setDocument({
...currentDocument,
assets: nextAssets,
modelInstances: nextModelInstances
});
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,55 @@
import { DEFAULT_GRID_SIZE, snapVec3ToGrid } from "../geometry/grid-snapping";
import { createOpaqueId } from "../core/ids";
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushSelection } from "./brush-command-helpers";
export function createMoveBoxBrushCommand(options) {
const resolvedCenter = options.snapToGrid === false ? options.center : snapVec3ToGrid(options.center, options.gridSize ?? DEFAULT_GRID_SIZE);
let previousCenter = null;
let previousSelection = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: options.label ?? "Move box brush",
execute(context) {
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
if (previousCenter === null) {
previousCenter = {
...brush.center
};
}
if (previousSelection === null) {
previousSelection = cloneSelectionForCommand(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
context.setDocument(replaceBrush(currentDocument, {
...brush,
center: {
...resolvedCenter
}
}));
context.setSelection(setSingleBrushSelection(options.brushId));
context.setToolMode("select");
},
undo(context) {
if (previousCenter === null) {
return;
}
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
context.setDocument(replaceBrush(currentDocument, {
...brush,
center: {
...previousCenter
}
}));
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,61 @@
import { DEFAULT_GRID_SIZE, snapPositiveSizeToGrid } from "../geometry/grid-snapping";
import { createOpaqueId } from "../core/ids";
import { cloneBoxBrushGeometry, scaleBoxBrushGeometryToSize } from "../document/brushes";
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushSelection } from "./brush-command-helpers";
export function createResizeBoxBrushCommand(options) {
const resolvedSize = options.snapToGrid === false ? options.size : snapPositiveSizeToGrid(options.size, options.gridSize ?? DEFAULT_GRID_SIZE);
let previousSize = null;
let previousGeometry = null;
let previousSelection = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: options.label ?? "Resize box brush",
execute(context) {
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
if (previousSize === null) {
previousSize = {
...brush.size
};
previousGeometry = cloneBoxBrushGeometry(brush.geometry);
}
if (previousSelection === null) {
previousSelection = cloneSelectionForCommand(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
const nextGeometry = scaleBoxBrushGeometryToSize(brush.geometry, resolvedSize);
context.setDocument(replaceBrush(currentDocument, {
...brush,
size: {
...resolvedSize
},
geometry: nextGeometry
}));
context.setSelection(setSingleBrushSelection(options.brushId));
context.setToolMode("select");
},
undo(context) {
if (previousSize === null || previousGeometry === null) {
return;
}
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
context.setDocument(replaceBrush(currentDocument, {
...brush,
size: {
...previousSize
},
geometry: cloneBoxBrushGeometry(previousGeometry)
}));
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -1,5 +1,6 @@
import type { ToolMode } from "../core/tool-mode";
import { DEFAULT_GRID_SIZE, snapPositiveSizeToGrid } from "../geometry/grid-snapping";
import { cloneBoxBrushGeometry, scaleBoxBrushGeometryToSize } from "../document/brushes";
import { createOpaqueId } from "../core/ids";
import type { EditorSelection } from "../core/selection";
@@ -21,6 +22,7 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
options.snapToGrid === false ? options.size : snapPositiveSizeToGrid(options.size, options.gridSize ?? DEFAULT_GRID_SIZE);
let previousSize: Vec3 | null = null;
let previousGeometry: ReturnType<typeof cloneBoxBrushGeometry> | null = null;
let previousSelection: EditorSelection | null = null;
let previousToolMode: ToolMode | null = null;
@@ -35,6 +37,7 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
previousSize = {
...brush.size
};
previousGeometry = cloneBoxBrushGeometry(brush.geometry);
}
if (previousSelection === null) {
@@ -45,19 +48,22 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
previousToolMode = context.getToolMode();
}
const nextGeometry = scaleBoxBrushGeometryToSize(brush.geometry, resolvedSize);
context.setDocument(
replaceBrush(currentDocument, {
...brush,
size: {
...resolvedSize
}
},
geometry: nextGeometry
})
);
context.setSelection(setSingleBrushSelection(options.brushId));
context.setToolMode("select");
},
undo(context) {
if (previousSize === null) {
if (previousSize === null || previousGeometry === null) {
return;
}
@@ -69,7 +75,8 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
...brush,
size: {
...previousSize
}
},
geometry: cloneBoxBrushGeometry(previousGeometry)
})
);

View File

@@ -0,0 +1,53 @@
import { createOpaqueId } from "../core/ids";
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushSelection } from "./brush-command-helpers";
export function createRotateBoxBrushCommand(options) {
let previousRotationDegrees = null;
let previousSelection = null;
let previousToolMode = 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);
}
}
};
}

View File

@@ -0,0 +1,48 @@
import { createOpaqueId } from "../core/ids";
import type { EditorCommand } from "./command";
export function createSetActiveSceneCommand(nextSceneId: string): EditorCommand {
let previousSceneId: string | null = null;
return {
id: createOpaqueId("command"),
label: "Switch active scene",
execute(context) {
const currentProjectDocument = context.getProjectDocument();
if (currentProjectDocument.scenes[nextSceneId] === undefined) {
throw new Error(`Cannot activate missing scene ${nextSceneId}.`);
}
if (previousSceneId === null) {
previousSceneId = currentProjectDocument.activeSceneId;
}
context.setProjectDocument({
...currentProjectDocument,
activeSceneId: nextSceneId
});
context.setSelection({ kind: "none" });
context.setToolMode("select");
},
undo(context) {
if (previousSceneId === null) {
return;
}
const currentProjectDocument = context.getProjectDocument();
if (currentProjectDocument.scenes[previousSceneId] === undefined) {
throw new Error(`Cannot restore missing scene ${previousSceneId}.`);
}
context.setProjectDocument({
...currentProjectDocument,
activeSceneId: previousSceneId
});
context.setSelection({ kind: "none" });
context.setToolMode("select");
}
};
}

View File

@@ -0,0 +1,50 @@
import { createOpaqueId } from "../core/ids";
import { cloneSelectionForCommand, getBoxBrushFaceOrThrow, replaceBoxBrushFace, setSingleBrushFaceSelection } from "./brush-command-helpers";
export function createSetBoxBrushFaceMaterialCommand(options) {
let previousMaterialId;
let previousSelection = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: options.materialId === null ? `Clear ${options.faceId} face material` : `Apply material to ${options.faceId} face`,
execute(context) {
const currentDocument = context.getDocument();
const currentFace = getBoxBrushFaceOrThrow(currentDocument, options.brushId, options.faceId);
if (options.materialId !== null && currentDocument.materials[options.materialId] === undefined) {
throw new Error(`Material ${options.materialId} does not exist in the document registry.`);
}
if (previousMaterialId === undefined) {
previousMaterialId = currentFace.materialId;
}
if (previousSelection === null) {
previousSelection = cloneSelectionForCommand(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
context.setDocument(replaceBoxBrushFace(currentDocument, options.brushId, options.faceId, {
...currentFace,
materialId: options.materialId
}));
context.setSelection(setSingleBrushFaceSelection(options.brushId, options.faceId));
context.setToolMode("select");
},
undo(context) {
if (previousMaterialId === undefined) {
return;
}
const currentDocument = context.getDocument();
const currentFace = getBoxBrushFaceOrThrow(currentDocument, options.brushId, options.faceId);
context.setDocument(replaceBoxBrushFace(currentDocument, options.brushId, options.faceId, {
...currentFace,
materialId: previousMaterialId
}));
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,48 @@
import { createOpaqueId } from "../core/ids";
import { cloneFaceUvState } from "../document/brushes";
import { cloneSelectionForCommand, getBoxBrushFaceOrThrow, replaceBoxBrushFace, setSingleBrushFaceSelection } from "./brush-command-helpers";
export function createSetBoxBrushFaceUvStateCommand(options) {
let previousUvState = null;
let previousSelection = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: options.label ?? `Update ${options.faceId} face UVs`,
execute(context) {
const currentDocument = context.getDocument();
const currentFace = getBoxBrushFaceOrThrow(currentDocument, options.brushId, options.faceId);
if (previousUvState === null) {
previousUvState = cloneFaceUvState(currentFace.uv);
}
if (previousSelection === null) {
previousSelection = cloneSelectionForCommand(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
context.setDocument(replaceBoxBrushFace(currentDocument, options.brushId, options.faceId, {
...currentFace,
uv: cloneFaceUvState(options.uvState)
}));
context.setSelection(setSingleBrushFaceSelection(options.brushId, options.faceId));
context.setToolMode("select");
},
undo(context) {
if (previousUvState === null) {
return;
}
const currentDocument = context.getDocument();
const currentFace = getBoxBrushFaceOrThrow(currentDocument, options.brushId, options.faceId);
context.setDocument(replaceBoxBrushFace(currentDocument, options.brushId, options.faceId, {
...currentFace,
uv: cloneFaceUvState(previousUvState)
}));
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,30 @@
import { createOpaqueId } from "../core/ids";
import { normalizeBrushName } from "../document/brushes";
import { getBoxBrushOrThrow, replaceBrush } from "./brush-command-helpers";
export function createSetBoxBrushNameCommand(options) {
const normalizedName = normalizeBrushName(options.name);
let previousName;
return {
id: createOpaqueId("command"),
label: normalizedName === undefined ? "Clear box brush name" : `Rename box brush to ${normalizedName}`,
execute(context) {
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
if (previousName === undefined) {
previousName = brush.name;
}
context.setDocument(replaceBrush(currentDocument, {
...brush,
name: normalizedName
}));
},
undo(context) {
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
context.setDocument(replaceBrush(currentDocument, {
...brush,
name: previousName
}));
}
};
}

View File

@@ -0,0 +1,95 @@
import { createOpaqueId } from "../core/ids";
import { cloneBoxBrushGeometry, deriveBoxBrushSizeFromGeometry, scaleBoxBrushGeometryToSize } from "../document/brushes";
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushEdgeSelection, setSingleBrushFaceSelection, setSingleBrushSelection, setSingleBrushVertexSelection } from "./brush-command-helpers";
function cloneVec3(vector) {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function selectionToEditorSelection(selection) {
switch (selection.kind) {
case "brush":
return setSingleBrushSelection(selection.brushId);
case "brushFace":
return setSingleBrushFaceSelection(selection.brushId, selection.faceId);
case "brushEdge":
return setSingleBrushEdgeSelection(selection.brushId, selection.edgeId);
case "brushVertex":
return setSingleBrushVertexSelection(selection.brushId, selection.vertexId);
}
}
function getBrushId(selection) {
return selection.brushId;
}
function assertPositiveSize(size) {
if (!(size.x > 0 && size.y > 0 && size.z > 0)) {
throw new Error("Whitebox box size must remain positive on every axis.");
}
if (!Number.isFinite(size.x) || !Number.isFinite(size.y) || !Number.isFinite(size.z)) {
throw new Error("Whitebox box size values must be finite numbers.");
}
}
export function createSetBoxBrushTransformCommand(options) {
assertPositiveSize(options.size);
let previousSnapshot = null;
let previousSelection = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: options.label ?? "Set box brush transform",
execute(context) {
const currentDocument = context.getDocument();
const brushId = getBrushId(options.selection);
const brush = getBoxBrushOrThrow(currentDocument, brushId);
if (previousSnapshot === null) {
previousSnapshot = {
center: cloneVec3(brush.center),
rotationDegrees: cloneVec3(brush.rotationDegrees),
size: cloneVec3(brush.size),
geometry: cloneBoxBrushGeometry(brush.geometry)
};
}
if (previousSelection === null) {
previousSelection = cloneSelectionForCommand(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
const nextGeometry = options.geometry === undefined ? scaleBoxBrushGeometryToSize(brush.geometry, options.size) : cloneBoxBrushGeometry(options.geometry);
const nextSize = deriveBoxBrushSizeFromGeometry(nextGeometry);
assertPositiveSize(nextSize);
context.setDocument(replaceBrush(currentDocument, {
...brush,
center: cloneVec3(options.center),
rotationDegrees: cloneVec3(options.rotationDegrees),
size: nextSize,
geometry: nextGeometry
}));
context.setSelection(selectionToEditorSelection(options.selection));
context.setToolMode("select");
},
undo(context) {
if (previousSnapshot === null) {
return;
}
const currentDocument = context.getDocument();
const brushId = getBrushId(options.selection);
const brush = getBoxBrushOrThrow(currentDocument, brushId);
context.setDocument(replaceBrush(currentDocument, {
...brush,
center: cloneVec3(previousSnapshot.center),
rotationDegrees: cloneVec3(previousSnapshot.rotationDegrees),
size: cloneVec3(previousSnapshot.size),
geometry: cloneBoxBrushGeometry(previousSnapshot.geometry)
}));
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,154 @@
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 { cloneBoxBrushGeometry, deriveBoxBrushSizeFromGeometry, scaleBoxBrushGeometryToSize, type BoxBrushGeometry } from "../document/brushes";
import {
cloneSelectionForCommand,
getBoxBrushOrThrow,
replaceBrush,
setSingleBrushEdgeSelection,
setSingleBrushFaceSelection,
setSingleBrushSelection,
setSingleBrushVertexSelection
} from "./brush-command-helpers";
import type { EditorCommand } from "./command";
import type { BoxEdgeId, BoxFaceId, BoxVertexId } from "../document/brushes";
type BrushTransformCommandSelection =
| { kind: "brush"; brushId: string }
| { kind: "brushFace"; brushId: string; faceId: BoxFaceId }
| { kind: "brushEdge"; brushId: string; edgeId: BoxEdgeId }
| { kind: "brushVertex"; brushId: string; vertexId: BoxVertexId };
interface SetBoxBrushTransformCommandOptions {
selection: BrushTransformCommandSelection;
center: Vec3;
rotationDegrees: Vec3;
size: Vec3;
geometry?: BoxBrushGeometry;
label?: string;
}
interface BrushTransformSnapshot {
center: Vec3;
rotationDegrees: Vec3;
size: Vec3;
geometry: ReturnType<typeof cloneBoxBrushGeometry>;
}
function cloneVec3(vector: Vec3): Vec3 {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function selectionToEditorSelection(selection: BrushTransformCommandSelection): EditorSelection {
switch (selection.kind) {
case "brush":
return setSingleBrushSelection(selection.brushId);
case "brushFace":
return setSingleBrushFaceSelection(selection.brushId, selection.faceId);
case "brushEdge":
return setSingleBrushEdgeSelection(selection.brushId, selection.edgeId);
case "brushVertex":
return setSingleBrushVertexSelection(selection.brushId, selection.vertexId);
}
}
function getBrushId(selection: BrushTransformCommandSelection): string {
return selection.brushId;
}
function assertPositiveSize(size: Vec3) {
if (!(size.x > 0 && size.y > 0 && size.z > 0)) {
throw new Error("Whitebox box size must remain positive on every axis.");
}
if (!Number.isFinite(size.x) || !Number.isFinite(size.y) || !Number.isFinite(size.z)) {
throw new Error("Whitebox box size values must be finite numbers.");
}
}
export function createSetBoxBrushTransformCommand(options: SetBoxBrushTransformCommandOptions): EditorCommand {
assertPositiveSize(options.size);
let previousSnapshot: BrushTransformSnapshot | null = null;
let previousSelection: EditorSelection | null = null;
let previousToolMode: ToolMode | null = null;
return {
id: createOpaqueId("command"),
label: options.label ?? "Set box brush transform",
execute(context) {
const currentDocument = context.getDocument();
const brushId = getBrushId(options.selection);
const brush = getBoxBrushOrThrow(currentDocument, brushId);
if (previousSnapshot === null) {
previousSnapshot = {
center: cloneVec3(brush.center),
rotationDegrees: cloneVec3(brush.rotationDegrees),
size: cloneVec3(brush.size),
geometry: cloneBoxBrushGeometry(brush.geometry)
};
}
if (previousSelection === null) {
previousSelection = cloneSelectionForCommand(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
const nextGeometry = options.geometry === undefined ? scaleBoxBrushGeometryToSize(brush.geometry, options.size) : cloneBoxBrushGeometry(options.geometry);
const nextSize = deriveBoxBrushSizeFromGeometry(nextGeometry);
assertPositiveSize(nextSize);
context.setDocument(
replaceBrush(currentDocument, {
...brush,
center: cloneVec3(options.center),
rotationDegrees: cloneVec3(options.rotationDegrees),
size: nextSize,
geometry: nextGeometry
})
);
context.setSelection(selectionToEditorSelection(options.selection));
context.setToolMode("select");
},
undo(context) {
if (previousSnapshot === null) {
return;
}
const currentDocument = context.getDocument();
const brushId = getBrushId(options.selection);
const brush = getBoxBrushOrThrow(currentDocument, brushId);
context.setDocument(
replaceBrush(currentDocument, {
...brush,
center: cloneVec3(previousSnapshot.center),
rotationDegrees: cloneVec3(previousSnapshot.rotationDegrees),
size: cloneVec3(previousSnapshot.size),
geometry: cloneBoxBrushGeometry(previousSnapshot.geometry)
})
);
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,33 @@
import { createOpaqueId } from "../core/ids";
import { cloneBoxBrushVolumeSettings } from "../document/brushes";
import { getBoxBrushOrThrow, replaceBrush } from "./brush-command-helpers";
export function createSetBoxBrushVolumeSettingsCommand(options) {
const nextVolume = cloneBoxBrushVolumeSettings(options.volume);
let previousVolume = null;
return {
id: createOpaqueId("command"),
label: options.label ?? "Set box volume settings",
execute(context) {
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
if (previousVolume === null) {
previousVolume = cloneBoxBrushVolumeSettings(brush.volume);
}
context.setDocument(replaceBrush(currentDocument, {
...brush,
volume: cloneBoxBrushVolumeSettings(nextVolume)
}));
},
undo(context) {
if (previousVolume === null) {
return;
}
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
context.setDocument(replaceBrush(currentDocument, {
...brush,
volume: cloneBoxBrushVolumeSettings(previousVolume)
}));
}
};
}

View File

@@ -0,0 +1,51 @@
import { createOpaqueId } from "../core/ids";
import { cloneBoxBrushVolumeSettings, type BoxBrushVolumeSettings } from "../document/brushes";
import { getBoxBrushOrThrow, replaceBrush } from "./brush-command-helpers";
import type { EditorCommand } from "./command";
interface SetBoxBrushVolumeSettingsCommandOptions {
brushId: string;
volume: BoxBrushVolumeSettings;
label?: string;
}
export function createSetBoxBrushVolumeSettingsCommand(options: SetBoxBrushVolumeSettingsCommandOptions): EditorCommand {
const nextVolume = cloneBoxBrushVolumeSettings(options.volume);
let previousVolume: BoxBrushVolumeSettings | null = null;
return {
id: createOpaqueId("command"),
label: options.label ?? "Set box volume settings",
execute(context) {
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
if (previousVolume === null) {
previousVolume = cloneBoxBrushVolumeSettings(brush.volume);
}
context.setDocument(
replaceBrush(currentDocument, {
...brush,
volume: cloneBoxBrushVolumeSettings(nextVolume)
})
);
},
undo(context) {
if (previousVolume === null) {
return;
}
const currentDocument = context.getDocument();
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
context.setDocument(
replaceBrush(currentDocument, {
...brush,
volume: cloneBoxBrushVolumeSettings(previousVolume)
})
);
}
};
}

View File

@@ -0,0 +1,47 @@
import { createOpaqueId } from "../core/ids";
import { cloneEntityInstance, normalizeEntityName } from "../entities/entity-instances";
export function createSetEntityNameCommand(options) {
const normalizedName = normalizeEntityName(options.name);
let previousName;
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
})
}
});
}
};
}

View File

@@ -0,0 +1,47 @@
import { createOpaqueId } from "../core/ids";
import { cloneModelInstance, normalizeModelInstanceName } from "../assets/model-instances";
export function createSetModelInstanceNameCommand(options) {
const normalizedName = normalizeModelInstanceName(options.name);
let previousName;
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
})
}
});
}
};
}

View File

@@ -0,0 +1,12 @@
import { createPlayerStartEntity } from "../entities/entity-instances";
import { createUpsertEntityCommand } from "./upsert-entity-command";
export function createSetPlayerStartCommand(options) {
return createUpsertEntityCommand({
entity: createPlayerStartEntity({
id: options.entityId,
position: options.position,
yawDegrees: options.yawDegrees
}),
label: options.entityId === undefined ? "Place player start" : "Move player start"
});
}

View File

@@ -0,0 +1,37 @@
import { createOpaqueId } from "../core/ids";
import { DEFAULT_PROJECT_NAME } from "../document/scene-document";
import type { EditorCommand } from "./command";
export function createSetProjectNameCommand(nextName: string): EditorCommand {
const normalizedName = nextName.trim() || DEFAULT_PROJECT_NAME;
let previousName: string | null = null;
return {
id: createOpaqueId("command"),
label: `Rename project to ${normalizedName}`,
execute(context) {
const currentProjectDocument = context.getProjectDocument();
if (previousName === null) {
previousName = currentProjectDocument.name;
}
context.setProjectDocument({
...currentProjectDocument,
name: normalizedName
});
},
undo(context) {
if (previousName === null) {
return;
}
const currentProjectDocument = context.getProjectDocument();
context.setProjectDocument({
...currentProjectDocument,
name: previousName
});
}
};
}

View File

@@ -0,0 +1,81 @@
import { createOpaqueId } from "../core/ids";
import {
cloneSceneLoadingScreenSettings,
type SceneLoadingScreenSettings
} from "../document/scene-document";
import type { EditorCommand } from "./command";
interface SetSceneLoadingScreenCommandOptions {
sceneId: string;
label: string;
loadingScreen: SceneLoadingScreenSettings;
}
export function createSetSceneLoadingScreenCommand(
options: SetSceneLoadingScreenCommandOptions
): EditorCommand {
const nextLoadingScreen = cloneSceneLoadingScreenSettings(
options.loadingScreen
);
let previousLoadingScreen: SceneLoadingScreenSettings | null = null;
return {
id: createOpaqueId("command"),
label: options.label,
execute(context) {
const currentProjectDocument = context.getProjectDocument();
const currentScene = currentProjectDocument.scenes[options.sceneId];
if (currentScene === undefined) {
throw new Error(
`Cannot update loading overlay for missing scene ${options.sceneId}.`
);
}
if (previousLoadingScreen === null) {
previousLoadingScreen = cloneSceneLoadingScreenSettings(
currentScene.loadingScreen
);
}
context.setProjectDocument({
...currentProjectDocument,
scenes: {
...currentProjectDocument.scenes,
[options.sceneId]: {
...currentScene,
loadingScreen: cloneSceneLoadingScreenSettings(nextLoadingScreen)
}
}
});
},
undo(context) {
if (previousLoadingScreen === null) {
return;
}
const currentProjectDocument = context.getProjectDocument();
const currentScene = currentProjectDocument.scenes[options.sceneId];
if (currentScene === undefined) {
throw new Error(
`Cannot restore loading overlay for missing scene ${options.sceneId}.`
);
}
context.setProjectDocument({
...currentProjectDocument,
scenes: {
...currentProjectDocument.scenes,
[options.sceneId]: {
...currentScene,
loadingScreen: cloneSceneLoadingScreenSettings(
previousLoadingScreen
)
}
}
});
}
};
}

View File

@@ -0,0 +1,29 @@
import { createOpaqueId } from "../core/ids";
export function createSetSceneNameCommand(nextName) {
const normalizedName = nextName.trim() || "Untitled Scene";
let previousName = null;
return {
id: createOpaqueId("command"),
label: `Rename scene to ${normalizedName}`,
execute(context) {
const currentDocument = context.getDocument();
if (previousName === null) {
previousName = currentDocument.name;
}
context.setDocument({
...currentDocument,
name: normalizedName
});
},
undo(context) {
if (previousName === null) {
return;
}
const currentDocument = context.getDocument();
context.setDocument({
...currentDocument,
name: previousName
});
}
};
}

View File

@@ -0,0 +1,30 @@
import { createOpaqueId } from "../core/ids";
import { cloneWorldSettings } from "../document/world-settings";
export function createSetWorldSettingsCommand(options) {
const nextWorld = cloneWorldSettings(options.world);
let previousWorld = null;
return {
id: createOpaqueId("command"),
label: options.label,
execute(context) {
const currentDocument = context.getDocument();
if (previousWorld === null) {
previousWorld = cloneWorldSettings(currentDocument.world);
}
context.setDocument({
...currentDocument,
world: cloneWorldSettings(nextWorld)
});
},
undo(context) {
if (previousWorld === null) {
return;
}
const currentDocument = context.getDocument();
context.setDocument({
...currentDocument,
world: cloneWorldSettings(previousWorld)
});
}
};
}

View File

@@ -0,0 +1,70 @@
import { cloneEditorSelection } from "../core/selection";
import { createOpaqueId } from "../core/ids";
import { cloneEntityInstance, getEntityKindLabel } from "../entities/entity-instances";
function setSingleEntitySelection(entityId) {
return {
kind: "entities",
ids: [entityId]
};
}
function createDefaultEntityCommandLabel(entity, isNewEntity) {
const action = isNewEntity ? "Place" : "Update";
return `${action} ${getEntityKindLabel(entity.kind).toLowerCase()}`;
}
export function createUpsertEntityCommand(options) {
const nextEntity = cloneEntityInstance(options.entity);
let previousEntity = null;
let previousSelection = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: options.label ?? createDefaultEntityCommandLabel(nextEntity, true),
execute(context) {
const currentDocument = context.getDocument();
const currentEntity = currentDocument.entities[nextEntity.id];
if (currentEntity !== undefined && currentEntity.kind !== nextEntity.kind) {
throw new Error(`Entity ${nextEntity.id} is a ${currentEntity.kind}, not a ${nextEntity.kind}.`);
}
if (previousSelection === null) {
previousSelection = cloneEditorSelection(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
if (previousEntity === null && currentEntity !== undefined) {
previousEntity = cloneEntityInstance(currentEntity);
}
context.setDocument({
...currentDocument,
entities: {
...currentDocument.entities,
[nextEntity.id]: cloneEntityInstance(nextEntity)
}
});
context.setSelection(setSingleEntitySelection(nextEntity.id));
context.setToolMode("select");
},
undo(context) {
const currentDocument = context.getDocument();
const nextEntities = {
...currentDocument.entities
};
if (previousEntity === null) {
delete nextEntities[nextEntity.id];
}
else {
nextEntities[nextEntity.id] = cloneEntityInstance(previousEntity);
}
context.setDocument({
...currentDocument,
entities: nextEntities
});
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

View File

@@ -0,0 +1,40 @@
import { cloneInteractionLink } from "../interactions/interaction-links";
import { createOpaqueId } from "../core/ids";
export function createUpsertInteractionLinkCommand(options) {
const nextLink = cloneInteractionLink(options.link);
let previousLink = null;
return {
id: createOpaqueId("command"),
label: options.label ?? "Update interaction link",
execute(context) {
const currentDocument = context.getDocument();
const currentLink = currentDocument.interactionLinks[nextLink.id];
if (previousLink === null && currentLink !== undefined) {
previousLink = cloneInteractionLink(currentLink);
}
context.setDocument({
...currentDocument,
interactionLinks: {
...currentDocument.interactionLinks,
[nextLink.id]: cloneInteractionLink(nextLink)
}
});
},
undo(context) {
const currentDocument = context.getDocument();
const nextInteractionLinks = {
...currentDocument.interactionLinks
};
if (previousLink === null) {
delete nextInteractionLinks[nextLink.id];
}
else {
nextInteractionLinks[nextLink.id] = cloneInteractionLink(previousLink);
}
context.setDocument({
...currentDocument,
interactionLinks: nextInteractionLinks
});
}
};
}

View File

@@ -0,0 +1,75 @@
import { createOpaqueId } from "../core/ids";
import { cloneEditorSelection } from "../core/selection";
import { cloneModelInstance, getModelInstanceKindLabel } from "../assets/model-instances";
import { getProjectAssetKindLabel } from "../assets/project-assets";
function setSingleModelInstanceSelection(modelInstanceId) {
return {
kind: "modelInstances",
ids: [modelInstanceId]
};
}
function createDefaultModelInstanceCommandLabel(isNewModelInstance) {
const action = isNewModelInstance ? "Place" : "Update";
return `${action} ${getModelInstanceKindLabel().toLowerCase()}`;
}
export function createUpsertModelInstanceCommand(options) {
const nextModelInstance = cloneModelInstance(options.modelInstance);
let previousModelInstance = null;
let previousSelection = null;
let previousToolMode = null;
return {
id: createOpaqueId("command"),
label: options.label ?? createDefaultModelInstanceCommandLabel(true),
execute(context) {
const currentDocument = context.getDocument();
const currentAsset = currentDocument.assets[nextModelInstance.assetId];
if (currentAsset === undefined) {
throw new Error(`Model instance ${nextModelInstance.id} cannot reference missing asset ${nextModelInstance.assetId}.`);
}
if (currentAsset.kind !== "model") {
throw new Error(`Model instance ${nextModelInstance.id} must reference a model asset, not ${getProjectAssetKindLabel(currentAsset.kind).toLowerCase()}.`);
}
const currentModelInstance = currentDocument.modelInstances[nextModelInstance.id];
if (previousSelection === null) {
previousSelection = cloneEditorSelection(context.getSelection());
}
if (previousToolMode === null) {
previousToolMode = context.getToolMode();
}
if (previousModelInstance === null && currentModelInstance !== undefined) {
previousModelInstance = cloneModelInstance(currentModelInstance);
}
context.setDocument({
...currentDocument,
modelInstances: {
...currentDocument.modelInstances,
[nextModelInstance.id]: cloneModelInstance(nextModelInstance)
}
});
context.setSelection(setSingleModelInstanceSelection(nextModelInstance.id));
context.setToolMode("select");
},
undo(context) {
const currentDocument = context.getDocument();
const nextModelInstances = {
...currentDocument.modelInstances
};
if (previousModelInstance === null) {
delete nextModelInstances[nextModelInstance.id];
}
else {
nextModelInstances[nextModelInstance.id] = cloneModelInstance(previousModelInstance);
}
context.setDocument({
...currentDocument,
modelInstances: nextModelInstances
});
if (previousSelection !== null) {
context.setSelection(previousSelection);
}
if (previousToolMode !== null) {
context.setToolMode(previousToolMode);
}
}
};
}

8
src/core/ids.js Normal file
View File

@@ -0,0 +1,8 @@
let fallbackCounter = 0;
export function createOpaqueId(prefix) {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return `${prefix}-${crypto.randomUUID()}`;
}
fallbackCounter += 1;
return `${prefix}-${Date.now()}-${fallbackCounter}`;
}

134
src/core/selection.js Normal file
View File

@@ -0,0 +1,134 @@
export function cloneEditorSelection(selection) {
if (selection.kind === "none") {
return {
kind: "none"
};
}
if (selection.kind === "brushFace") {
return {
kind: "brushFace",
brushId: selection.brushId,
faceId: selection.faceId
};
}
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, right) {
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) {
if (selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") {
return selection.brushId;
}
if (selection.kind !== "brushes" || selection.ids.length !== 1) {
return null;
}
return selection.ids[0];
}
export function getSelectedBrushFaceId(selection) {
if (selection.kind !== "brushFace") {
return null;
}
return selection.faceId;
}
export function getSelectedBrushEdgeId(selection) {
if (selection.kind !== "brushEdge") {
return null;
}
return selection.edgeId;
}
export function getSelectedBrushVertexId(selection) {
if (selection.kind !== "brushVertex") {
return null;
}
return selection.vertexId;
}
export function getSingleSelectedEntityId(selection) {
if (selection.kind !== "entities" || selection.ids.length !== 1) {
return null;
}
return selection.ids[0];
}
export function getSingleSelectedModelInstanceId(selection) {
if (selection.kind !== "modelInstances" || selection.ids.length !== 1) {
return null;
}
return selection.ids[0];
}
export function isBrushSelected(selection, brushId) {
return ((selection.kind === "brushes" && selection.ids.includes(brushId)) ||
((selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") &&
selection.brushId === brushId));
}
export function isBrushFaceSelected(selection, brushId, faceId) {
return selection.kind === "brushFace" && selection.brushId === brushId && selection.faceId === faceId;
}
export function isBrushEdgeSelected(selection, brushId, edgeId) {
return selection.kind === "brushEdge" && selection.brushId === brushId && selection.edgeId === edgeId;
}
export function isBrushVertexSelected(selection, brushId, vertexId) {
return selection.kind === "brushVertex" && selection.brushId === brushId && selection.vertexId === vertexId;
}
export function isModelInstanceSelected(selection, modelInstanceId) {
return selection.kind === "modelInstances" && selection.ids.includes(modelInstanceId);
}
export function normalizeSelectionForWhiteboxSelectionMode(selection, mode) {
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
src/core/tool-mode.js Normal file
View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,596 @@
import { createOpaqueId } from "./ids";
import { BOX_VERTEX_IDS, BOX_EDGE_LABELS, BOX_FACE_LABELS, BOX_VERTEX_LABELS, cloneBoxBrushGeometry } from "../document/brushes";
import { cloneEntityInstance, getEntityKindLabel } from "../entities/entity-instances";
import { cloneModelInstance, getModelInstanceKindLabel } from "../assets/model-instances";
function areBrushGeometriesEqual(left, right) {
return BOX_VERTEX_IDS.every((vertexId) => {
const leftVertex = left.vertices[vertexId];
const rightVertex = right.vertices[vertexId];
return areVec3Equal(leftVertex, rightVertex);
});
}
function cloneVec3(vector) {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function areVec3Equal(left, right) {
return left.x === right.x && left.y === right.y && left.z === right.z;
}
function cloneEntityTransformRotationState(rotation) {
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, right) {
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() {
return {
kind: "none"
};
}
export function cloneTransformTarget(target) {
switch (target.kind) {
case "brush":
return {
kind: "brush",
brushId: target.brushId,
initialCenter: cloneVec3(target.initialCenter),
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
initialSize: cloneVec3(target.initialSize),
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
};
case "brushFace":
return {
kind: "brushFace",
brushId: target.brushId,
faceId: target.faceId,
initialCenter: cloneVec3(target.initialCenter),
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
initialSize: cloneVec3(target.initialSize),
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
};
case "brushEdge":
return {
kind: "brushEdge",
brushId: target.brushId,
edgeId: target.edgeId,
initialCenter: cloneVec3(target.initialCenter),
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
initialSize: cloneVec3(target.initialSize),
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
};
case "brushVertex":
return {
kind: "brushVertex",
brushId: target.brushId,
vertexId: target.vertexId,
initialCenter: cloneVec3(target.initialCenter),
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
initialSize: cloneVec3(target.initialSize),
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
};
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) {
switch (preview.kind) {
case "brush":
return {
kind: "brush",
center: cloneVec3(preview.center),
rotationDegrees: cloneVec3(preview.rotationDegrees),
size: cloneVec3(preview.size),
geometry: cloneBoxBrushGeometry(preview.geometry)
};
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) {
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, right) {
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, right) {
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) &&
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry));
case "brushFace":
return (right.kind === "brushFace" &&
left.brushId === right.brushId &&
left.faceId === right.faceId &&
areVec3Equal(left.initialCenter, right.initialCenter) &&
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
areVec3Equal(left.initialSize, right.initialSize) &&
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry));
case "brushEdge":
return (right.kind === "brushEdge" &&
left.brushId === right.brushId &&
left.edgeId === right.edgeId &&
areVec3Equal(left.initialCenter, right.initialCenter) &&
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
areVec3Equal(left.initialSize, right.initialSize) &&
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry));
case "brushVertex":
return (right.kind === "brushVertex" &&
left.brushId === right.brushId &&
left.vertexId === right.vertexId &&
areVec3Equal(left.initialCenter, right.initialCenter) &&
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
areVec3Equal(left.initialSize, right.initialSize) &&
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry));
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, right) {
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) &&
areBrushGeometriesEqual(left.geometry, right.geometry));
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) {
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) {
switch (target.kind) {
case "brush":
case "brushFace":
case "brushEdge":
case "brushVertex":
return {
kind: "brush",
center: cloneVec3(target.initialCenter),
rotationDegrees: cloneVec3(target.initialRotationDegrees),
size: cloneVec3(target.initialSize),
geometry: cloneBoxBrushGeometry(target.initialGeometry)
};
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) {
switch (session.target.kind) {
case "brush":
case "brushFace":
case "brushEdge":
case "brushVertex":
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) ||
!areBrushGeometriesEqual(session.preview.geometry, session.target.initialGeometry)));
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) {
switch (operation) {
case "translate":
return "Move";
case "rotate":
return "Rotate";
case "scale":
return "Scale";
}
}
export function getTransformAxisLabel(axis) {
return axis.toUpperCase();
}
export function getTransformTargetLabel(target) {
switch (target.kind) {
case "brush":
return "Whitebox Box";
case "brushFace":
return `Whitebox Face (${BOX_FACE_LABELS[target.faceId]})`;
case "brushEdge":
return `Whitebox Edge (${BOX_EDGE_LABELS[target.edgeId]})`;
case "brushVertex":
return `Whitebox Vertex (${BOX_VERTEX_LABELS[target.vertexId]})`;
case "modelInstance":
return getModelInstanceKindLabel();
case "entity":
return getEntityKindLabel(target.entityKind);
}
}
export function getSupportedTransformOperations(target) {
switch (target.kind) {
case "brush":
case "brushFace":
case "brushEdge":
return ["translate", "rotate", "scale"];
case "brushVertex":
return ["translate"];
case "modelInstance":
return ["translate", "rotate", "scale"];
case "entity":
return target.initialRotation.kind === "none" ? ["translate"] : ["translate", "rotate"];
}
}
export function supportsTransformOperation(target, operation) {
return getSupportedTransformOperations(target).includes(operation);
}
export function supportsTransformAxisConstraint(session, axis) {
switch (session.operation) {
case "translate":
return true;
case "scale":
if (session.target.kind === "modelInstance" || session.target.kind === "brush" || session.target.kind === "brushVertex") {
return session.target.kind !== "brushVertex";
}
if (session.target.kind === "brushFace") {
const normalAxis = session.target.faceId === "posX" || session.target.faceId === "negX" ? "x" : session.target.faceId === "posY" || session.target.faceId === "negY" ? "y" : "z";
return axis === normalAxis;
}
if (session.target.kind === "brushEdge") {
if (session.target.edgeId.startsWith("edgeX_")) {
return axis !== "x";
}
if (session.target.edgeId.startsWith("edgeY_")) {
return axis !== "y";
}
return axis !== "z";
}
return false;
case "rotate":
if (session.target.kind === "entity" && session.target.initialRotation.kind === "yaw") {
return axis === "y";
}
if (session.target.kind === "brushFace") {
const normalAxis = session.target.faceId === "posX" || session.target.faceId === "negX" ? "x" : session.target.faceId === "posY" || session.target.faceId === "negY" ? "y" : "z";
return axis === normalAxis;
}
if (session.target.kind === "brushEdge") {
if (session.target.edgeId.startsWith("edgeX_")) {
return axis === "x";
}
if (session.target.edgeId.startsWith("edgeY_")) {
return axis === "y";
}
return axis === "z";
}
if (session.target.kind === "brushVertex") {
return false;
}
return true;
}
}
function resolveEntityRotation(entity) {
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, brushId) {
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),
initialGeometry: cloneBoxBrushGeometry(brush.geometry)
},
message: null
};
}
function createBrushFaceTransformTarget(document, brushId, faceId) {
const brushResolution = createBrushTransformTarget(document, brushId);
if (brushResolution.target === null || brushResolution.target.kind !== "brush") {
return brushResolution;
}
return {
target: {
kind: "brushFace",
brushId,
faceId,
initialCenter: cloneVec3(brushResolution.target.initialCenter),
initialRotationDegrees: cloneVec3(brushResolution.target.initialRotationDegrees),
initialSize: cloneVec3(brushResolution.target.initialSize),
initialGeometry: cloneBoxBrushGeometry(brushResolution.target.initialGeometry)
},
message: null
};
}
function createBrushEdgeTransformTarget(document, brushId, edgeId) {
const brushResolution = createBrushTransformTarget(document, brushId);
if (brushResolution.target === null || brushResolution.target.kind !== "brush") {
return brushResolution;
}
return {
target: {
kind: "brushEdge",
brushId,
edgeId,
initialCenter: cloneVec3(brushResolution.target.initialCenter),
initialRotationDegrees: cloneVec3(brushResolution.target.initialRotationDegrees),
initialSize: cloneVec3(brushResolution.target.initialSize),
initialGeometry: cloneBoxBrushGeometry(brushResolution.target.initialGeometry)
},
message: null
};
}
function createBrushVertexTransformTarget(document, brushId, vertexId) {
const brushResolution = createBrushTransformTarget(document, brushId);
if (brushResolution.target === null || brushResolution.target.kind !== "brush") {
return brushResolution;
}
return {
target: {
kind: "brushVertex",
brushId,
vertexId,
initialCenter: cloneVec3(brushResolution.target.initialCenter),
initialRotationDegrees: cloneVec3(brushResolution.target.initialRotationDegrees),
initialSize: cloneVec3(brushResolution.target.initialSize),
initialGeometry: cloneBoxBrushGeometry(brushResolution.target.initialGeometry)
},
message: null
};
}
function createEntityTransformTarget(document, entityId) {
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, modelInstanceId) {
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, selection, whiteboxSelectionMode = "object") {
switch (selection.kind) {
case "none":
return {
target: null,
message: "Select a single brush, entity, or model instance before transforming it."
};
case "brushFace":
if (whiteboxSelectionMode !== "face") {
return {
target: null,
message: "Switch to Face mode to transform a selected whitebox face."
};
}
return createBrushFaceTransformTarget(document, selection.brushId, selection.faceId);
case "brushEdge":
if (whiteboxSelectionMode !== "edge") {
return {
target: null,
message: "Switch to Edge mode to transform a selected whitebox edge."
};
}
return createBrushEdgeTransformTarget(document, selection.brushId, selection.edgeId);
case "brushVertex":
if (whiteboxSelectionMode !== "vertex") {
return {
target: null,
message: "Switch to Vertex mode to transform a selected whitebox vertex."
};
}
return createBrushVertexTransformTarget(document, selection.brushId, selection.vertexId);
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]);
}
}

View File

@@ -2,6 +2,17 @@ import { createOpaqueId } from "./ids";
import type { EditorSelection } from "./selection";
import type { WhiteboxSelectionMode } from "./whitebox-selection-mode";
import type { Vec3 } from "./vector";
import {
BOX_VERTEX_IDS,
BOX_EDGE_LABELS,
BOX_FACE_LABELS,
BOX_VERTEX_LABELS,
cloneBoxBrushGeometry,
type BoxBrushGeometry,
type BoxEdgeId,
type BoxFaceId,
type BoxVertexId
} from "../document/brushes";
import type { SceneDocument } from "../document/scene-document";
import {
cloneEntityInstance,
@@ -9,11 +20,15 @@ import {
type EntityInstance,
type EntityKind
} from "../entities/entity-instances";
import { cloneModelInstance, getModelInstanceKindLabel } from "../assets/model-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 TransformAxisSpace = "world" | "local";
export type TransformSessionSource = "keyboard" | "gizmo" | "toolbar";
export interface YawEntityRotationState {
@@ -30,7 +45,10 @@ export interface NoEntityRotationState {
kind: "none";
}
export type EntityTransformRotationState = NoEntityRotationState | YawEntityRotationState | DirectionEntityRotationState;
export type EntityTransformRotationState =
| NoEntityRotationState
| YawEntityRotationState
| DirectionEntityRotationState;
export interface BrushTransformTarget {
kind: "brush";
@@ -38,6 +56,37 @@ export interface BrushTransformTarget {
initialCenter: Vec3;
initialRotationDegrees: Vec3;
initialSize: Vec3;
initialGeometry: BoxBrushGeometry;
}
export interface BrushFaceTransformTarget {
kind: "brushFace";
brushId: string;
faceId: BoxFaceId;
initialCenter: Vec3;
initialRotationDegrees: Vec3;
initialSize: Vec3;
initialGeometry: BoxBrushGeometry;
}
export interface BrushEdgeTransformTarget {
kind: "brushEdge";
brushId: string;
edgeId: BoxEdgeId;
initialCenter: Vec3;
initialRotationDegrees: Vec3;
initialSize: Vec3;
initialGeometry: BoxBrushGeometry;
}
export interface BrushVertexTransformTarget {
kind: "brushVertex";
brushId: string;
vertexId: BoxVertexId;
initialCenter: Vec3;
initialRotationDegrees: Vec3;
initialSize: Vec3;
initialGeometry: BoxBrushGeometry;
}
export interface ModelInstanceTransformTarget {
@@ -57,13 +106,31 @@ export interface EntityTransformTarget {
initialRotation: EntityTransformRotationState;
}
export type TransformTarget = BrushTransformTarget | ModelInstanceTransformTarget | EntityTransformTarget;
export type TransformTarget =
| BrushTransformTarget
| BrushFaceTransformTarget
| BrushEdgeTransformTarget
| BrushVertexTransformTarget
| ModelInstanceTransformTarget
| EntityTransformTarget;
export interface BrushTransformPreview {
kind: "brush";
center: Vec3;
rotationDegrees: Vec3;
size: Vec3;
geometry: BoxBrushGeometry;
}
function areBrushGeometriesEqual(
left: BoxBrushGeometry,
right: BoxBrushGeometry
): boolean {
return BOX_VERTEX_IDS.every((vertexId) => {
const leftVertex = left.vertices[vertexId];
const rightVertex = right.vertices[vertexId];
return areVec3Equal(leftVertex, rightVertex);
});
}
export interface ModelInstanceTransformPreview {
@@ -79,7 +146,10 @@ export interface EntityTransformPreview {
rotation: EntityTransformRotationState;
}
export type TransformPreview = BrushTransformPreview | ModelInstanceTransformPreview | EntityTransformPreview;
export type TransformPreview =
| BrushTransformPreview
| ModelInstanceTransformPreview
| EntityTransformPreview;
export interface ActiveTransformSession {
kind: "active";
@@ -88,6 +158,7 @@ export interface ActiveTransformSession {
sourcePanelId: ViewportPanelId;
operation: TransformOperation;
axisConstraint: TransformAxis | null;
axisConstraintSpace: TransformAxisSpace;
target: TransformTarget;
preview: TransformPreview;
}
@@ -111,7 +182,9 @@ 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 {
function cloneEntityTransformRotationState(
rotation: EntityTransformRotationState
): EntityTransformRotationState {
switch (rotation.kind) {
case "none":
return {
@@ -130,7 +203,10 @@ function cloneEntityTransformRotationState(rotation: EntityTransformRotationStat
}
}
function areEntityTransformRotationsEqual(left: EntityTransformRotationState, right: EntityTransformRotationState): boolean {
function areEntityTransformRotationsEqual(
left: EntityTransformRotationState,
right: EntityTransformRotationState
): boolean {
if (left.kind !== right.kind) {
return false;
}
@@ -141,7 +217,10 @@ function areEntityTransformRotationsEqual(left: EntityTransformRotationState, ri
case "yaw":
return right.kind === "yaw" && left.yawDegrees === right.yawDegrees;
case "direction":
return right.kind === "direction" && areVec3Equal(left.direction, right.direction);
return (
right.kind === "direction" &&
areVec3Equal(left.direction, right.direction)
);
}
}
@@ -159,7 +238,38 @@ export function cloneTransformTarget(target: TransformTarget): TransformTarget {
brushId: target.brushId,
initialCenter: cloneVec3(target.initialCenter),
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
initialSize: cloneVec3(target.initialSize)
initialSize: cloneVec3(target.initialSize),
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
};
case "brushFace":
return {
kind: "brushFace",
brushId: target.brushId,
faceId: target.faceId,
initialCenter: cloneVec3(target.initialCenter),
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
initialSize: cloneVec3(target.initialSize),
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
};
case "brushEdge":
return {
kind: "brushEdge",
brushId: target.brushId,
edgeId: target.edgeId,
initialCenter: cloneVec3(target.initialCenter),
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
initialSize: cloneVec3(target.initialSize),
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
};
case "brushVertex":
return {
kind: "brushVertex",
brushId: target.brushId,
vertexId: target.vertexId,
initialCenter: cloneVec3(target.initialCenter),
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
initialSize: cloneVec3(target.initialSize),
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
};
case "modelInstance":
return {
@@ -176,19 +286,24 @@ export function cloneTransformTarget(target: TransformTarget): TransformTarget {
entityId: target.entityId,
entityKind: target.entityKind,
initialPosition: cloneVec3(target.initialPosition),
initialRotation: cloneEntityTransformRotationState(target.initialRotation)
initialRotation: cloneEntityTransformRotationState(
target.initialRotation
)
};
}
}
export function cloneTransformPreview(preview: TransformPreview): TransformPreview {
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)
size: cloneVec3(preview.size),
geometry: cloneBoxBrushGeometry(preview.geometry)
};
case "modelInstance":
return {
@@ -206,7 +321,9 @@ export function cloneTransformPreview(preview: TransformPreview): TransformPrevi
}
}
export function cloneTransformSession(session: TransformSessionState): TransformSessionState {
export function cloneTransformSession(
session: TransformSessionState
): TransformSessionState {
if (session.kind === "none") {
return session;
}
@@ -218,12 +335,16 @@ export function cloneTransformSession(session: TransformSessionState): Transform
sourcePanelId: session.sourcePanelId,
operation: session.operation,
axisConstraint: session.axisConstraint,
axisConstraintSpace: session.axisConstraintSpace,
target: cloneTransformTarget(session.target),
preview: cloneTransformPreview(session.preview)
};
}
export function areTransformSessionsEqual(left: TransformSessionState, right: TransformSessionState): boolean {
export function areTransformSessionsEqual(
left: TransformSessionState,
right: TransformSessionState
): boolean {
if (left.kind !== right.kind) {
return false;
}
@@ -238,12 +359,16 @@ export function areTransformSessionsEqual(left: TransformSessionState, right: Tr
left.sourcePanelId === right.sourcePanelId &&
left.operation === right.operation &&
left.axisConstraint === right.axisConstraint &&
left.axisConstraintSpace === right.axisConstraintSpace &&
areTransformTargetsEqual(left.target, right.target) &&
areTransformPreviewsEqual(left.preview, right.preview)
);
}
function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget): boolean {
function areTransformTargetsEqual(
left: TransformTarget,
right: TransformTarget
): boolean {
if (left.kind !== right.kind) {
return false;
}
@@ -254,8 +379,51 @@ function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget)
right.kind === "brush" &&
left.brushId === right.brushId &&
areVec3Equal(left.initialCenter, right.initialCenter) &&
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
areVec3Equal(left.initialSize, right.initialSize)
areVec3Equal(
left.initialRotationDegrees,
right.initialRotationDegrees
) &&
areVec3Equal(left.initialSize, right.initialSize) &&
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry)
);
case "brushFace":
return (
right.kind === "brushFace" &&
left.brushId === right.brushId &&
left.faceId === right.faceId &&
areVec3Equal(left.initialCenter, right.initialCenter) &&
areVec3Equal(
left.initialRotationDegrees,
right.initialRotationDegrees
) &&
areVec3Equal(left.initialSize, right.initialSize) &&
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry)
);
case "brushEdge":
return (
right.kind === "brushEdge" &&
left.brushId === right.brushId &&
left.edgeId === right.edgeId &&
areVec3Equal(left.initialCenter, right.initialCenter) &&
areVec3Equal(
left.initialRotationDegrees,
right.initialRotationDegrees
) &&
areVec3Equal(left.initialSize, right.initialSize) &&
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry)
);
case "brushVertex":
return (
right.kind === "brushVertex" &&
left.brushId === right.brushId &&
left.vertexId === right.vertexId &&
areVec3Equal(left.initialCenter, right.initialCenter) &&
areVec3Equal(
left.initialRotationDegrees,
right.initialRotationDegrees
) &&
areVec3Equal(left.initialSize, right.initialSize) &&
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry)
);
case "modelInstance":
return (
@@ -263,7 +431,10 @@ function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget)
left.modelInstanceId === right.modelInstanceId &&
left.assetId === right.assetId &&
areVec3Equal(left.initialPosition, right.initialPosition) &&
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
areVec3Equal(
left.initialRotationDegrees,
right.initialRotationDegrees
) &&
areVec3Equal(left.initialScale, right.initialScale)
);
case "entity":
@@ -272,12 +443,18 @@ function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget)
left.entityId === right.entityId &&
left.entityKind === right.entityKind &&
areVec3Equal(left.initialPosition, right.initialPosition) &&
areEntityTransformRotationsEqual(left.initialRotation, right.initialRotation)
areEntityTransformRotationsEqual(
left.initialRotation,
right.initialRotation
)
);
}
}
function areTransformPreviewsEqual(left: TransformPreview, right: TransformPreview): boolean {
function areTransformPreviewsEqual(
left: TransformPreview,
right: TransformPreview
): boolean {
if (left.kind !== right.kind) {
return false;
}
@@ -288,7 +465,8 @@ function areTransformPreviewsEqual(left: TransformPreview, right: TransformPrevi
right.kind === "brush" &&
areVec3Equal(left.center, right.center) &&
areVec3Equal(left.rotationDegrees, right.rotationDegrees) &&
areVec3Equal(left.size, right.size)
areVec3Equal(left.size, right.size) &&
areBrushGeometriesEqual(left.geometry, right.geometry)
);
case "modelInstance":
return (
@@ -298,7 +476,11 @@ function areTransformPreviewsEqual(left: TransformPreview, right: TransformPrevi
areVec3Equal(left.scale, right.scale)
);
case "entity":
return right.kind === "entity" && areVec3Equal(left.position, right.position) && areEntityTransformRotationsEqual(left.rotation, right.rotation);
return (
right.kind === "entity" &&
areVec3Equal(left.position, right.position) &&
areEntityTransformRotationsEqual(left.rotation, right.rotation)
);
}
}
@@ -307,6 +489,7 @@ export function createTransformSession(options: {
sourcePanelId: ViewportPanelId;
operation: TransformOperation;
axisConstraint?: TransformAxis | null;
axisConstraintSpace?: TransformAxisSpace;
target: TransformTarget;
}): ActiveTransformSession {
return {
@@ -316,19 +499,26 @@ export function createTransformSession(options: {
sourcePanelId: options.sourcePanelId,
operation: options.operation,
axisConstraint: options.axisConstraint ?? null,
axisConstraintSpace: options.axisConstraintSpace ?? "world",
target: cloneTransformTarget(options.target),
preview: createTransformPreviewFromTarget(options.target)
};
}
export function createTransformPreviewFromTarget(target: TransformTarget): TransformPreview {
export function createTransformPreviewFromTarget(
target: TransformTarget
): TransformPreview {
switch (target.kind) {
case "brush":
case "brushFace":
case "brushEdge":
case "brushVertex":
return {
kind: "brush",
center: cloneVec3(target.initialCenter),
rotationDegrees: cloneVec3(target.initialRotationDegrees),
size: cloneVec3(target.initialSize)
size: cloneVec3(target.initialSize),
geometry: cloneBoxBrushGeometry(target.initialGeometry)
};
case "modelInstance":
return {
@@ -346,32 +536,58 @@ export function createTransformPreviewFromTarget(target: TransformTarget): Trans
}
}
export function doesTransformSessionChangeTarget(session: ActiveTransformSession): boolean {
export function doesTransformSessionChangeTarget(
session: ActiveTransformSession
): boolean {
switch (session.target.kind) {
case "brush":
case "brushFace":
case "brushEdge":
case "brushVertex":
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))
!areVec3Equal(
session.preview.rotationDegrees,
session.target.initialRotationDegrees
) ||
!areVec3Equal(session.preview.size, session.target.initialSize) ||
!areBrushGeometriesEqual(
session.preview.geometry,
session.target.initialGeometry
))
);
case "modelInstance":
return (
session.preview.kind === "modelInstance" &&
(!areVec3Equal(session.preview.position, session.target.initialPosition) ||
!areVec3Equal(session.preview.rotationDegrees, session.target.initialRotationDegrees) ||
(!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))
(!areVec3Equal(
session.preview.position,
session.target.initialPosition
) ||
!areEntityTransformRotationsEqual(
session.preview.rotation,
session.target.initialRotation
))
);
}
}
export function getTransformOperationLabel(operation: TransformOperation): string {
export function getTransformOperationLabel(
operation: TransformOperation
): string {
switch (operation) {
case "translate":
return "Move";
@@ -386,10 +602,27 @@ export function getTransformAxisLabel(axis: TransformAxis): string {
return axis.toUpperCase();
}
export function getTransformAxisSpaceLabel(
axisSpace: TransformAxisSpace
): string {
switch (axisSpace) {
case "world":
return "World";
case "local":
return "Local";
}
}
export function getTransformTargetLabel(target: TransformTarget): string {
switch (target.kind) {
case "brush":
return "Whitebox Box";
case "brushFace":
return `Whitebox Face (${BOX_FACE_LABELS[target.faceId]})`;
case "brushEdge":
return `Whitebox Edge (${BOX_EDGE_LABELS[target.edgeId]})`;
case "brushVertex":
return `Whitebox Vertex (${BOX_VERTEX_LABELS[target.vertexId]})`;
case "modelInstance":
return getModelInstanceKindLabel();
case "entity":
@@ -397,39 +630,142 @@ export function getTransformTargetLabel(target: TransformTarget): string {
}
}
export function getSupportedTransformOperations(target: TransformTarget): TransformOperation[] {
export function getSupportedTransformOperations(
target: TransformTarget
): TransformOperation[] {
switch (target.kind) {
case "brush":
case "brushFace":
case "brushEdge":
return ["translate", "rotate", "scale"];
case "brushVertex":
return ["translate"];
case "modelInstance":
return ["translate", "rotate", "scale"];
case "entity":
return target.initialRotation.kind === "none" ? ["translate"] : ["translate", "rotate"];
return target.initialRotation.kind === "none"
? ["translate"]
: ["translate", "rotate"];
}
}
export function supportsTransformOperation(target: TransformTarget, operation: TransformOperation): boolean {
export function supportsTransformOperation(
target: TransformTarget,
operation: TransformOperation
): boolean {
return getSupportedTransformOperations(target).includes(operation);
}
export function supportsTransformAxisConstraint(session: ActiveTransformSession, axis: TransformAxis): boolean {
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";
if (
session.target.kind === "modelInstance" ||
session.target.kind === "brush" ||
session.target.kind === "brushVertex"
) {
return session.target.kind !== "brushVertex";
}
if (session.target.kind === "brushFace") {
const normalAxis =
session.target.faceId === "posX" || session.target.faceId === "negX"
? "x"
: session.target.faceId === "posY" ||
session.target.faceId === "negY"
? "y"
: "z";
return axis === normalAxis;
}
if (session.target.kind === "brushEdge") {
if (session.target.edgeId.startsWith("edgeX_")) {
return axis !== "x";
}
if (session.target.edgeId.startsWith("edgeY_")) {
return axis !== "y";
}
return axis !== "z";
}
return false;
case "rotate":
if (session.target.kind === "entity" && session.target.initialRotation.kind === "yaw") {
if (
session.target.kind === "entity" &&
session.target.initialRotation.kind === "yaw"
) {
return axis === "y";
}
if (session.target.kind === "brushFace") {
const normalAxis =
session.target.faceId === "posX" || session.target.faceId === "negX"
? "x"
: session.target.faceId === "posY" ||
session.target.faceId === "negY"
? "y"
: "z";
return axis === normalAxis;
}
if (session.target.kind === "brushEdge") {
if (session.target.edgeId.startsWith("edgeX_")) {
return axis === "x";
}
if (session.target.edgeId.startsWith("edgeY_")) {
return axis === "y";
}
return axis === "z";
}
if (session.target.kind === "brushVertex") {
return false;
}
return true;
}
}
function resolveEntityRotation(entity: EntityInstance): EntityTransformRotationState {
export function supportsLocalTransformAxisConstraint(
session: ActiveTransformSession,
axis: TransformAxis
): boolean {
if (!supportsTransformAxisConstraint(session, axis)) {
return false;
}
if (session.operation === "scale") {
return false;
}
switch (session.target.kind) {
case "brush":
case "modelInstance":
return true;
case "entity":
return session.target.initialRotation.kind !== "none";
case "brushFace":
case "brushEdge":
case "brushVertex":
return false;
}
}
function resolveEntityRotation(
entity: EntityInstance
): EntityTransformRotationState {
switch (entity.kind) {
case "playerStart":
case "sceneEntry":
case "teleportTarget":
return {
kind: "yaw",
@@ -444,13 +780,17 @@ function resolveEntityRotation(entity: EntityInstance): EntityTransformRotationS
case "soundEmitter":
case "triggerVolume":
case "interactable":
case "sceneExit":
return {
kind: "none"
};
}
}
function createBrushTransformTarget(document: SceneDocument, brushId: string): TransformTargetResolution {
function createBrushTransformTarget(
document: SceneDocument,
brushId: string
): TransformTargetResolution {
const brush = document.brushes[brushId];
if (brush === undefined || brush.kind !== "box") {
@@ -466,13 +806,113 @@ function createBrushTransformTarget(document: SceneDocument, brushId: string): T
brushId: brush.id,
initialCenter: cloneVec3(brush.center),
initialRotationDegrees: cloneVec3(brush.rotationDegrees),
initialSize: cloneVec3(brush.size)
initialSize: cloneVec3(brush.size),
initialGeometry: cloneBoxBrushGeometry(brush.geometry)
},
message: null
};
}
function createEntityTransformTarget(document: SceneDocument, entityId: string): TransformTargetResolution {
function createBrushFaceTransformTarget(
document: SceneDocument,
brushId: string,
faceId: BoxFaceId
): TransformTargetResolution {
const brushResolution = createBrushTransformTarget(document, brushId);
if (
brushResolution.target === null ||
brushResolution.target.kind !== "brush"
) {
return brushResolution;
}
return {
target: {
kind: "brushFace",
brushId,
faceId,
initialCenter: cloneVec3(brushResolution.target.initialCenter),
initialRotationDegrees: cloneVec3(
brushResolution.target.initialRotationDegrees
),
initialSize: cloneVec3(brushResolution.target.initialSize),
initialGeometry: cloneBoxBrushGeometry(
brushResolution.target.initialGeometry
)
},
message: null
};
}
function createBrushEdgeTransformTarget(
document: SceneDocument,
brushId: string,
edgeId: BoxEdgeId
): TransformTargetResolution {
const brushResolution = createBrushTransformTarget(document, brushId);
if (
brushResolution.target === null ||
brushResolution.target.kind !== "brush"
) {
return brushResolution;
}
return {
target: {
kind: "brushEdge",
brushId,
edgeId,
initialCenter: cloneVec3(brushResolution.target.initialCenter),
initialRotationDegrees: cloneVec3(
brushResolution.target.initialRotationDegrees
),
initialSize: cloneVec3(brushResolution.target.initialSize),
initialGeometry: cloneBoxBrushGeometry(
brushResolution.target.initialGeometry
)
},
message: null
};
}
function createBrushVertexTransformTarget(
document: SceneDocument,
brushId: string,
vertexId: BoxVertexId
): TransformTargetResolution {
const brushResolution = createBrushTransformTarget(document, brushId);
if (
brushResolution.target === null ||
brushResolution.target.kind !== "brush"
) {
return brushResolution;
}
return {
target: {
kind: "brushVertex",
brushId,
vertexId,
initialCenter: cloneVec3(brushResolution.target.initialCenter),
initialRotationDegrees: cloneVec3(
brushResolution.target.initialRotationDegrees
),
initialSize: cloneVec3(brushResolution.target.initialSize),
initialGeometry: cloneBoxBrushGeometry(
brushResolution.target.initialGeometry
)
},
message: null
};
}
function createEntityTransformTarget(
document: SceneDocument,
entityId: string
): TransformTargetResolution {
const entity = document.entities[entityId];
if (entity === undefined) {
@@ -496,7 +936,10 @@ function createEntityTransformTarget(document: SceneDocument, entityId: string):
};
}
function createModelInstanceTransformTarget(document: SceneDocument, modelInstanceId: string): TransformTargetResolution {
function createModelInstanceTransformTarget(
document: SceneDocument,
modelInstanceId: string
): TransformTargetResolution {
const modelInstance = document.modelInstances[modelInstanceId];
if (modelInstance === undefined) {
@@ -530,23 +973,49 @@ export function resolveTransformTarget(
case "none":
return {
target: null,
message: "Select a single brush, entity, or model instance before transforming it."
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."
};
if (whiteboxSelectionMode !== "face") {
return {
target: null,
message: "Switch to Face mode to transform a selected whitebox face."
};
}
return createBrushFaceTransformTarget(
document,
selection.brushId,
selection.faceId
);
case "brushEdge":
return {
target: null,
message: "Edge transforms land in the next whitebox slice. Switch to Object mode to transform the whole whitebox box."
};
if (whiteboxSelectionMode !== "edge") {
return {
target: null,
message: "Switch to Edge mode to transform a selected whitebox edge."
};
}
return createBrushEdgeTransformTarget(
document,
selection.brushId,
selection.edgeId
);
case "brushVertex":
return {
target: null,
message: "Vertex transforms land in the next whitebox slice. Switch to Object mode to transform the whole whitebox box."
};
if (whiteboxSelectionMode !== "vertex") {
return {
target: null,
message:
"Switch to Vertex mode to transform a selected whitebox vertex."
};
}
return createBrushVertexTransformTarget(
document,
selection.brushId,
selection.vertexId
);
case "brushes":
if (whiteboxSelectionMode !== "object") {
return {

5
src/core/vector.js Normal file
View File

@@ -0,0 +1,5 @@
export const DEFAULT_SUN_DIRECTION = {
x: -0.6,
y: 1,
z: 0.35
};

View File

@@ -0,0 +1,23 @@
import { BOX_EDGE_LABELS, BOX_FACE_LABELS, BOX_VERTEX_LABELS } from "../document/brushes";
function getBrushDisplayLabel(document, brushId) {
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, selection) {
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;
}
}

View File

@@ -0,0 +1,10 @@
export const WHITEBOX_SELECTION_MODES = ["object", "face", "edge", "vertex"];
export const WHITEBOX_SELECTION_MODE_LABELS = {
object: "Object",
face: "Face",
edge: "Edge",
vertex: "Vertex"
};
export function getWhiteboxSelectionModeLabel(mode) {
return WHITEBOX_SELECTION_MODE_LABELS[mode];
}

395
src/document/brushes.js Normal file
View File

@@ -0,0 +1,395 @@
import { createOpaqueId } from "../core/ids";
export const BOX_FACE_IDS = ["posX", "negX", "posY", "negY", "posZ", "negZ"];
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"
];
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"
];
export const FACE_UV_ROTATION_QUARTER_TURNS = [0, 1, 2, 3];
export const BOX_BRUSH_VOLUME_MODES = ["none", "water", "fog"];
export const BOX_FACE_LABELS = {
posX: "Right",
negX: "Left",
posY: "Top",
negY: "Bottom",
posZ: "Front",
negZ: "Back"
};
export const BOX_EDGE_LABELS = {
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 = {
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 const DEFAULT_BOX_BRUSH_CENTER = {
x: 0,
y: 1,
z: 0
};
export const DEFAULT_BOX_BRUSH_SIZE = {
x: 2,
y: 2,
z: 2
};
export const DEFAULT_BOX_BRUSH_ROTATION_DEGREES = {
x: 0,
y: 0,
z: 0
};
export const DEFAULT_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT = 6;
export const MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT = 24;
const DEFAULT_BOX_BRUSH_WATER_SETTINGS = {
colorHex: "#4da6d9",
surfaceOpacity: 0.55,
waveStrength: 0.35,
foamContactLimit: DEFAULT_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT,
surfaceDisplacementEnabled: false
};
const DEFAULT_BOX_BRUSH_FOG_SETTINGS = {
colorHex: "#9cb7c7",
density: 0.08,
padding: 0.2
};
export function normalizeBrushName(name) {
if (name === undefined || name === null) {
return undefined;
}
const trimmedName = name.trim();
return trimmedName.length === 0 ? undefined : trimmedName;
}
function cloneVec3(vector) {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function cloneBrushFace(face) {
return {
materialId: face.materialId,
uv: cloneFaceUvState(face.uv)
};
}
function cloneBoxBrushGeometryVertex(vertex) {
return {
x: vertex.x,
y: vertex.y,
z: vertex.z
};
}
export function cloneBoxBrushGeometry(geometry) {
return {
vertices: {
negX_negY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_negY_negZ),
posX_negY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_negY_negZ),
negX_posY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_posY_negZ),
posX_posY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_posY_negZ),
negX_negY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_negY_posZ),
posX_negY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_negY_posZ),
negX_posY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_posY_posZ),
posX_posY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_posY_posZ)
}
};
}
export function getBoxBrushGeometryLocalBounds(geometry) {
const vertices = Object.values(geometry.vertices);
const firstVertex = vertices[0];
const min = { ...firstVertex };
const max = { ...firstVertex };
for (const vertex of vertices.slice(1)) {
min.x = Math.min(min.x, vertex.x);
min.y = Math.min(min.y, vertex.y);
min.z = Math.min(min.z, vertex.z);
max.x = Math.max(max.x, vertex.x);
max.y = Math.max(max.y, vertex.y);
max.z = Math.max(max.z, vertex.z);
}
return {
min,
max
};
}
export function deriveBoxBrushSizeFromGeometry(geometry) {
const bounds = getBoxBrushGeometryLocalBounds(geometry);
return {
x: bounds.max.x - bounds.min.x,
y: bounds.max.y - bounds.min.y,
z: bounds.max.z - bounds.min.z
};
}
export function scaleBoxBrushGeometryToSize(geometry, size) {
const bounds = getBoxBrushGeometryLocalBounds(geometry);
const currentSize = deriveBoxBrushSizeFromGeometry(geometry);
if (!hasPositiveBoxSize(currentSize) || !hasPositiveBoxSize(size)) {
throw new Error("Box brush geometry size must remain positive on every axis.");
}
const center = {
x: (bounds.min.x + bounds.max.x) * 0.5,
y: (bounds.min.y + bounds.max.y) * 0.5,
z: (bounds.min.z + bounds.max.z) * 0.5
};
const scale = {
x: size.x / currentSize.x,
y: size.y / currentSize.y,
z: size.z / currentSize.z
};
return {
vertices: {
negX_negY_negZ: {
x: center.x + (geometry.vertices.negX_negY_negZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.negX_negY_negZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.negX_negY_negZ.z - center.z) * scale.z
},
posX_negY_negZ: {
x: center.x + (geometry.vertices.posX_negY_negZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.posX_negY_negZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.posX_negY_negZ.z - center.z) * scale.z
},
negX_posY_negZ: {
x: center.x + (geometry.vertices.negX_posY_negZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.negX_posY_negZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.negX_posY_negZ.z - center.z) * scale.z
},
posX_posY_negZ: {
x: center.x + (geometry.vertices.posX_posY_negZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.posX_posY_negZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.posX_posY_negZ.z - center.z) * scale.z
},
negX_negY_posZ: {
x: center.x + (geometry.vertices.negX_negY_posZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.negX_negY_posZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.negX_negY_posZ.z - center.z) * scale.z
},
posX_negY_posZ: {
x: center.x + (geometry.vertices.posX_negY_posZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.posX_negY_posZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.posX_negY_posZ.z - center.z) * scale.z
},
negX_posY_posZ: {
x: center.x + (geometry.vertices.negX_posY_posZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.negX_posY_posZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.negX_posY_posZ.z - center.z) * scale.z
},
posX_posY_posZ: {
x: center.x + (geometry.vertices.posX_posY_posZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.posX_posY_posZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.posX_posY_posZ.z - center.z) * scale.z
}
}
};
}
export function createDefaultBoxBrushGeometry(size = DEFAULT_BOX_BRUSH_SIZE) {
const halfSize = {
x: size.x * 0.5,
y: size.y * 0.5,
z: size.z * 0.5
};
return {
vertices: {
negX_negY_negZ: { x: -halfSize.x, y: -halfSize.y, z: -halfSize.z },
posX_negY_negZ: { x: halfSize.x, y: -halfSize.y, z: -halfSize.z },
negX_posY_negZ: { x: -halfSize.x, y: halfSize.y, z: -halfSize.z },
posX_posY_negZ: { x: halfSize.x, y: halfSize.y, z: -halfSize.z },
negX_negY_posZ: { x: -halfSize.x, y: -halfSize.y, z: halfSize.z },
posX_negY_posZ: { x: halfSize.x, y: -halfSize.y, z: halfSize.z },
negX_posY_posZ: { x: -halfSize.x, y: halfSize.y, z: halfSize.z },
posX_posY_posZ: { x: halfSize.x, y: halfSize.y, z: halfSize.z }
}
};
}
export function isBoxFaceId(value) {
return typeof value === "string" && BOX_FACE_IDS.some((faceId) => faceId === value);
}
export function isBoxEdgeId(value) {
return typeof value === "string" && BOX_EDGE_IDS.some((edgeId) => edgeId === value);
}
export function isBoxVertexId(value) {
return typeof value === "string" && BOX_VERTEX_IDS.some((vertexId) => vertexId === value);
}
export function isFaceUvRotationQuarterTurns(value) {
return typeof value === "number" && FACE_UV_ROTATION_QUARTER_TURNS.includes(value);
}
export function isBoxBrushVolumeMode(value) {
return typeof value === "string" && BOX_BRUSH_VOLUME_MODES.includes(value);
}
export function hasPositiveBoxSize(size) {
return size.x > 0 && size.y > 0 && size.z > 0;
}
export function createDefaultFaceUvState() {
return {
offset: {
x: 0,
y: 0
},
scale: {
x: 1,
y: 1
},
rotationQuarterTurns: 0,
flipU: false,
flipV: false
};
}
export function cloneFaceUvState(uv) {
return {
offset: {
...uv.offset
},
scale: {
...uv.scale
},
rotationQuarterTurns: uv.rotationQuarterTurns,
flipU: uv.flipU,
flipV: uv.flipV
};
}
export function cloneBoxBrushFaces(faces) {
return {
posX: cloneBrushFace(faces.posX),
negX: cloneBrushFace(faces.negX),
posY: cloneBrushFace(faces.posY),
negY: cloneBrushFace(faces.negY),
posZ: cloneBrushFace(faces.posZ),
negZ: cloneBrushFace(faces.negZ)
};
}
export function createDefaultBoxBrushFaces() {
return {
posX: {
materialId: null,
uv: createDefaultFaceUvState()
},
negX: {
materialId: null,
uv: createDefaultFaceUvState()
},
posY: {
materialId: null,
uv: createDefaultFaceUvState()
},
negY: {
materialId: null,
uv: createDefaultFaceUvState()
},
posZ: {
materialId: null,
uv: createDefaultFaceUvState()
},
negZ: {
materialId: null,
uv: createDefaultFaceUvState()
}
};
}
export function createDefaultBoxBrushWaterSettings() {
return {
colorHex: DEFAULT_BOX_BRUSH_WATER_SETTINGS.colorHex,
surfaceOpacity: DEFAULT_BOX_BRUSH_WATER_SETTINGS.surfaceOpacity,
waveStrength: DEFAULT_BOX_BRUSH_WATER_SETTINGS.waveStrength,
foamContactLimit: DEFAULT_BOX_BRUSH_WATER_SETTINGS.foamContactLimit,
surfaceDisplacementEnabled: DEFAULT_BOX_BRUSH_WATER_SETTINGS.surfaceDisplacementEnabled
};
}
export function createDefaultBoxBrushFogSettings() {
return {
colorHex: DEFAULT_BOX_BRUSH_FOG_SETTINGS.colorHex,
density: DEFAULT_BOX_BRUSH_FOG_SETTINGS.density,
padding: DEFAULT_BOX_BRUSH_FOG_SETTINGS.padding
};
}
export function createDefaultBoxBrushVolumeSettings() {
return {
mode: "none"
};
}
export function cloneBoxBrushVolumeSettings(volume) {
switch (volume.mode) {
case "none":
return {
mode: "none"
};
case "water":
return {
mode: "water",
water: {
colorHex: volume.water.colorHex,
surfaceOpacity: volume.water.surfaceOpacity,
waveStrength: volume.water.waveStrength,
foamContactLimit: volume.water.foamContactLimit,
surfaceDisplacementEnabled: volume.water.surfaceDisplacementEnabled
}
};
case "fog":
return {
mode: "fog",
fog: {
colorHex: volume.fog.colorHex,
density: volume.fog.density,
padding: volume.fog.padding
}
};
}
}
export function createBoxBrush(overrides = {}) {
const center = cloneVec3(overrides.center ?? DEFAULT_BOX_BRUSH_CENTER);
const rotationDegrees = cloneVec3(overrides.rotationDegrees ?? DEFAULT_BOX_BRUSH_ROTATION_DEGREES);
const fallbackSize = cloneVec3(overrides.size ?? DEFAULT_BOX_BRUSH_SIZE);
const geometry = overrides.geometry === undefined ? createDefaultBoxBrushGeometry(fallbackSize) : cloneBoxBrushGeometry(overrides.geometry);
const size = deriveBoxBrushSizeFromGeometry(geometry);
if (!hasPositiveBoxSize(size)) {
throw new Error("Box brush size must remain positive on every axis.");
}
return {
id: overrides.id ?? createOpaqueId("brush"),
kind: "box",
name: normalizeBrushName(overrides.name),
center,
rotationDegrees,
size,
geometry,
faces: overrides.faces === undefined ? createDefaultBoxBrushFaces() : cloneBoxBrushFaces(overrides.faces),
volume: overrides.volume === undefined ? createDefaultBoxBrushVolumeSettings() : cloneBoxBrushVolumeSettings(overrides.volume),
layerId: overrides.layerId,
groupId: overrides.groupId
};
}
export function cloneBoxBrush(brush) {
return createBoxBrush(brush);
}

View File

@@ -27,11 +27,13 @@ export const BOX_VERTEX_IDS = [
"posX_posY_posZ"
] as const;
export const FACE_UV_ROTATION_QUARTER_TURNS = [0, 1, 2, 3] as const;
export const BOX_BRUSH_VOLUME_MODES = ["none", "water", "fog"] 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 type BoxBrushVolumeMode = (typeof BOX_BRUSH_VOLUME_MODES)[number];
export const BOX_FACE_LABELS: Record<BoxFaceId, string> = {
posX: "Right",
@@ -81,8 +83,41 @@ export interface BrushFace {
uv: FaceUvState;
}
export interface BoxBrushWaterSettings {
colorHex: string;
surfaceOpacity: number;
waveStrength: number;
foamContactLimit: number;
surfaceDisplacementEnabled: boolean;
}
export interface BoxBrushFogSettings {
colorHex: string;
density: number;
padding: number;
}
export type BoxBrushVolumeSettings =
| {
mode: "none";
}
| {
mode: "water";
water: BoxBrushWaterSettings;
}
| {
mode: "fog";
fog: BoxBrushFogSettings;
};
export type BoxBrushFaces = Record<BoxFaceId, BrushFace>;
export type BoxBrushGeometryVertices = Record<BoxVertexId, Vec3>;
export interface BoxBrushGeometry {
vertices: BoxBrushGeometryVertices;
}
export interface BoxBrush {
id: string;
kind: "box";
@@ -90,7 +125,9 @@ export interface BoxBrush {
center: Vec3;
rotationDegrees: Vec3;
size: Vec3;
geometry: BoxBrushGeometry;
faces: BoxBrushFaces;
volume: BoxBrushVolumeSettings;
layerId?: string;
groupId?: string;
}
@@ -115,6 +152,23 @@ export const DEFAULT_BOX_BRUSH_ROTATION_DEGREES: Vec3 = {
z: 0
};
export const DEFAULT_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT = 6;
export const MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT = 24;
const DEFAULT_BOX_BRUSH_WATER_SETTINGS: BoxBrushWaterSettings = {
colorHex: "#4da6d9",
surfaceOpacity: 0.55,
waveStrength: 0.35,
foamContactLimit: DEFAULT_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT,
surfaceDisplacementEnabled: false
};
const DEFAULT_BOX_BRUSH_FOG_SETTINGS: BoxBrushFogSettings = {
colorHex: "#9cb7c7",
density: 0.08,
padding: 0.2
};
export function normalizeBrushName(name: string | null | undefined): string | undefined {
if (name === undefined || name === null) {
return undefined;
@@ -139,6 +193,146 @@ function cloneBrushFace(face: BrushFace): BrushFace {
};
}
function cloneBoxBrushGeometryVertex(vertex: Vec3): Vec3 {
return {
x: vertex.x,
y: vertex.y,
z: vertex.z
};
}
export function cloneBoxBrushGeometry(geometry: BoxBrushGeometry): BoxBrushGeometry {
return {
vertices: {
negX_negY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_negY_negZ),
posX_negY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_negY_negZ),
negX_posY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_posY_negZ),
posX_posY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_posY_negZ),
negX_negY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_negY_posZ),
posX_negY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_negY_posZ),
negX_posY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_posY_posZ),
posX_posY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_posY_posZ)
}
};
}
export function getBoxBrushGeometryLocalBounds(geometry: BoxBrushGeometry): { min: Vec3; max: Vec3 } {
const vertices = Object.values(geometry.vertices);
const firstVertex = vertices[0];
const min = { ...firstVertex };
const max = { ...firstVertex };
for (const vertex of vertices.slice(1)) {
min.x = Math.min(min.x, vertex.x);
min.y = Math.min(min.y, vertex.y);
min.z = Math.min(min.z, vertex.z);
max.x = Math.max(max.x, vertex.x);
max.y = Math.max(max.y, vertex.y);
max.z = Math.max(max.z, vertex.z);
}
return {
min,
max
};
}
export function deriveBoxBrushSizeFromGeometry(geometry: BoxBrushGeometry): Vec3 {
const bounds = getBoxBrushGeometryLocalBounds(geometry);
return {
x: bounds.max.x - bounds.min.x,
y: bounds.max.y - bounds.min.y,
z: bounds.max.z - bounds.min.z
};
}
export function scaleBoxBrushGeometryToSize(geometry: BoxBrushGeometry, size: Vec3): BoxBrushGeometry {
const bounds = getBoxBrushGeometryLocalBounds(geometry);
const currentSize = deriveBoxBrushSizeFromGeometry(geometry);
if (!hasPositiveBoxSize(currentSize) || !hasPositiveBoxSize(size)) {
throw new Error("Box brush geometry size must remain positive on every axis.");
}
const center = {
x: (bounds.min.x + bounds.max.x) * 0.5,
y: (bounds.min.y + bounds.max.y) * 0.5,
z: (bounds.min.z + bounds.max.z) * 0.5
};
const scale = {
x: size.x / currentSize.x,
y: size.y / currentSize.y,
z: size.z / currentSize.z
};
return {
vertices: {
negX_negY_negZ: {
x: center.x + (geometry.vertices.negX_negY_negZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.negX_negY_negZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.negX_negY_negZ.z - center.z) * scale.z
},
posX_negY_negZ: {
x: center.x + (geometry.vertices.posX_negY_negZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.posX_negY_negZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.posX_negY_negZ.z - center.z) * scale.z
},
negX_posY_negZ: {
x: center.x + (geometry.vertices.negX_posY_negZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.negX_posY_negZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.negX_posY_negZ.z - center.z) * scale.z
},
posX_posY_negZ: {
x: center.x + (geometry.vertices.posX_posY_negZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.posX_posY_negZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.posX_posY_negZ.z - center.z) * scale.z
},
negX_negY_posZ: {
x: center.x + (geometry.vertices.negX_negY_posZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.negX_negY_posZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.negX_negY_posZ.z - center.z) * scale.z
},
posX_negY_posZ: {
x: center.x + (geometry.vertices.posX_negY_posZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.posX_negY_posZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.posX_negY_posZ.z - center.z) * scale.z
},
negX_posY_posZ: {
x: center.x + (geometry.vertices.negX_posY_posZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.negX_posY_posZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.negX_posY_posZ.z - center.z) * scale.z
},
posX_posY_posZ: {
x: center.x + (geometry.vertices.posX_posY_posZ.x - center.x) * scale.x,
y: center.y + (geometry.vertices.posX_posY_posZ.y - center.y) * scale.y,
z: center.z + (geometry.vertices.posX_posY_posZ.z - center.z) * scale.z
}
}
};
}
export function createDefaultBoxBrushGeometry(size: Vec3 = DEFAULT_BOX_BRUSH_SIZE): BoxBrushGeometry {
const halfSize = {
x: size.x * 0.5,
y: size.y * 0.5,
z: size.z * 0.5
};
return {
vertices: {
negX_negY_negZ: { x: -halfSize.x, y: -halfSize.y, z: -halfSize.z },
posX_negY_negZ: { x: halfSize.x, y: -halfSize.y, z: -halfSize.z },
negX_posY_negZ: { x: -halfSize.x, y: halfSize.y, z: -halfSize.z },
posX_posY_negZ: { x: halfSize.x, y: halfSize.y, z: -halfSize.z },
negX_negY_posZ: { x: -halfSize.x, y: -halfSize.y, z: halfSize.z },
posX_negY_posZ: { x: halfSize.x, y: -halfSize.y, z: halfSize.z },
negX_posY_posZ: { x: -halfSize.x, y: halfSize.y, z: halfSize.z },
posX_posY_posZ: { x: halfSize.x, y: halfSize.y, z: halfSize.z }
}
};
}
export function isBoxFaceId(value: unknown): value is BoxFaceId {
return typeof value === "string" && BOX_FACE_IDS.some((faceId) => faceId === value);
}
@@ -155,6 +349,10 @@ export function isFaceUvRotationQuarterTurns(value: unknown): value is FaceUvRot
return typeof value === "number" && FACE_UV_ROTATION_QUARTER_TURNS.includes(value as FaceUvRotationQuarterTurns);
}
export function isBoxBrushVolumeMode(value: unknown): value is BoxBrushVolumeMode {
return typeof value === "string" && BOX_BRUSH_VOLUME_MODES.includes(value as BoxBrushVolumeMode);
}
export function hasPositiveBoxSize(size: Vec3): boolean {
return size.x > 0 && size.y > 0 && size.z > 0;
}
@@ -229,12 +427,69 @@ export function createDefaultBoxBrushFaces(): BoxBrushFaces {
};
}
export function createDefaultBoxBrushWaterSettings(): BoxBrushWaterSettings {
return {
colorHex: DEFAULT_BOX_BRUSH_WATER_SETTINGS.colorHex,
surfaceOpacity: DEFAULT_BOX_BRUSH_WATER_SETTINGS.surfaceOpacity,
waveStrength: DEFAULT_BOX_BRUSH_WATER_SETTINGS.waveStrength,
foamContactLimit: DEFAULT_BOX_BRUSH_WATER_SETTINGS.foamContactLimit,
surfaceDisplacementEnabled: DEFAULT_BOX_BRUSH_WATER_SETTINGS.surfaceDisplacementEnabled
};
}
export function createDefaultBoxBrushFogSettings(): BoxBrushFogSettings {
return {
colorHex: DEFAULT_BOX_BRUSH_FOG_SETTINGS.colorHex,
density: DEFAULT_BOX_BRUSH_FOG_SETTINGS.density,
padding: DEFAULT_BOX_BRUSH_FOG_SETTINGS.padding
};
}
export function createDefaultBoxBrushVolumeSettings(): BoxBrushVolumeSettings {
return {
mode: "none"
};
}
export function cloneBoxBrushVolumeSettings(volume: BoxBrushVolumeSettings): BoxBrushVolumeSettings {
switch (volume.mode) {
case "none":
return {
mode: "none"
};
case "water":
return {
mode: "water",
water: {
colorHex: volume.water.colorHex,
surfaceOpacity: volume.water.surfaceOpacity,
waveStrength: volume.water.waveStrength,
foamContactLimit: volume.water.foamContactLimit,
surfaceDisplacementEnabled: volume.water.surfaceDisplacementEnabled
}
};
case "fog":
return {
mode: "fog",
fog: {
colorHex: volume.fog.colorHex,
density: volume.fog.density,
padding: volume.fog.padding
}
};
}
}
export function createBoxBrush(
overrides: Partial<Pick<BoxBrush, "id" | "name" | "center" | "rotationDegrees" | "size" | "faces" | "layerId" | "groupId">> = {}
overrides: Partial<
Pick<BoxBrush, "id" | "name" | "center" | "rotationDegrees" | "size" | "geometry" | "faces" | "volume" | "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);
const fallbackSize = cloneVec3(overrides.size ?? DEFAULT_BOX_BRUSH_SIZE);
const geometry = overrides.geometry === undefined ? createDefaultBoxBrushGeometry(fallbackSize) : cloneBoxBrushGeometry(overrides.geometry);
const size = deriveBoxBrushSizeFromGeometry(geometry);
if (!hasPositiveBoxSize(size)) {
throw new Error("Box brush size must remain positive on every axis.");
@@ -247,7 +502,9 @@ export function createBoxBrush(
center,
rotationDegrees,
size,
geometry,
faces: overrides.faces === undefined ? createDefaultBoxBrushFaces() : cloneBoxBrushFaces(overrides.faces),
volume: overrides.volume === undefined ? createDefaultBoxBrushVolumeSettings() : cloneBoxBrushVolumeSettings(overrides.volume),
layerId: overrides.layerId,
groupId: overrides.groupId
};

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,690 @@
import {} from "../assets/project-assets";
import { isModelInstanceCollisionMode } from "../assets/model-instances";
import { isPlayerStartColliderMode, getPlayerStartColliderHeight } from "../entities/entity-instances";
import {} from "../interactions/interaction-links";
import { BOX_FACE_IDS, BOX_VERTEX_IDS, MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT, hasPositiveBoxSize, isBoxBrushVolumeMode } from "./brushes";
import { isAdvancedRenderingShadowMapSize, isAdvancedRenderingShadowType, isBoxVolumeRenderPath, isAdvancedRenderingToneMappingMode, isHexColorString } from "./world-settings";
export function createDiagnostic(severity, code, message, path, scope = "document") {
return {
code,
severity,
scope,
message,
path
};
}
function isFiniteNumber(value) {
return typeof value === "number" && Number.isFinite(value);
}
function isFiniteVec3(vector) {
return isFiniteNumber(vector.x) && isFiniteNumber(vector.y) && isFiniteNumber(vector.z);
}
function hasPositiveFiniteVec3(vector) {
return isFiniteVec3(vector) && vector.x > 0 && vector.y > 0 && vector.z > 0;
}
function isNonNegativeFiniteNumber(value) {
return isFiniteNumber(value) && value >= 0;
}
function isPositiveFiniteNumber(value) {
return isFiniteNumber(value) && value > 0;
}
function isPositiveInteger(value) {
return isFiniteNumber(value) && Number.isInteger(value) && value > 0;
}
function isPositiveIntegerInRange(value, max) {
return isPositiveInteger(value) && value <= max;
}
function isBoolean(value) {
return typeof value === "boolean";
}
function hasNonZeroVectorLength(vector) {
return vector.x !== 0 || vector.y !== 0 || vector.z !== 0;
}
function validateWorldSettings(world, document, diagnostics) {
if (world.background.mode === "solid") {
if (!isHexColorString(world.background.colorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-world-background-color", "Solid world backgrounds must use #RRGGBB colors.", "world.background.colorHex"));
}
}
else if (world.background.mode === "verticalGradient") {
if (!isHexColorString(world.background.topColorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-world-background-top-color", "Gradient world backgrounds must use #RRGGBB colors for the top color.", "world.background.topColorHex"));
}
if (!isHexColorString(world.background.bottomColorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-world-background-bottom-color", "Gradient world backgrounds must use #RRGGBB colors for the bottom color.", "world.background.bottomColorHex"));
}
}
else {
if (typeof world.background.assetId !== "string" || world.background.assetId.trim().length === 0) {
diagnostics.push(createDiagnostic("error", "invalid-world-background-asset-id", "World background images must reference a non-empty asset id.", "world.background.assetId"));
}
else {
const backgroundAsset = document.assets[world.background.assetId];
if (backgroundAsset === undefined) {
diagnostics.push(createDiagnostic("error", "missing-world-background-asset", `World background image asset ${world.background.assetId} does not exist.`, "world.background.assetId"));
}
else if (backgroundAsset.kind !== "image") {
diagnostics.push(createDiagnostic("error", "invalid-world-background-asset-kind", "World background images must reference image assets.", "world.background.assetId"));
}
}
if (!isNonNegativeFiniteNumber(world.background.environmentIntensity)) {
diagnostics.push(createDiagnostic("error", "invalid-world-background-environment-intensity", "World background environment intensity must be a non-negative finite number.", "world.background.environmentIntensity"));
}
}
if (!isHexColorString(world.ambientLight.colorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-world-ambient-color", "World ambient light must use a #RRGGBB color.", "world.ambientLight.colorHex"));
}
if (!isNonNegativeFiniteNumber(world.ambientLight.intensity)) {
diagnostics.push(createDiagnostic("error", "invalid-world-ambient-intensity", "World ambient light intensity must remain finite and zero or greater.", "world.ambientLight.intensity"));
}
if (!isHexColorString(world.sunLight.colorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-world-sun-color", "World sun color must use a #RRGGBB color.", "world.sunLight.colorHex"));
}
if (!isNonNegativeFiniteNumber(world.sunLight.intensity)) {
diagnostics.push(createDiagnostic("error", "invalid-world-sun-intensity", "World sun intensity must remain finite and zero or greater.", "world.sunLight.intensity"));
}
if (!isFiniteVec3(world.sunLight.direction) || !hasNonZeroVectorLength(world.sunLight.direction)) {
diagnostics.push(createDiagnostic("error", "invalid-world-sun-direction", "World sun direction must remain finite and must not be the zero vector.", "world.sunLight.direction"));
}
const advancedRendering = world.advancedRendering;
if (!isBoolean(advancedRendering.enabled)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-enabled", "Advanced rendering enabled must be a boolean.", "world.advancedRendering.enabled"));
}
if (!isBoolean(advancedRendering.shadows.enabled)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-shadows-enabled", "Advanced rendering shadow enabled must be a boolean.", "world.advancedRendering.shadows.enabled"));
}
if (!isAdvancedRenderingShadowMapSize(advancedRendering.shadows.mapSize)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-shadow-map-size", "Advanced rendering shadow map size must be one of 512, 1024, 2048, or 4096.", "world.advancedRendering.shadows.mapSize"));
}
if (!isAdvancedRenderingShadowType(advancedRendering.shadows.type)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-shadow-type", "Advanced rendering shadow type must be basic, pcf, or pcfSoft.", "world.advancedRendering.shadows.type"));
}
if (!isFiniteNumber(advancedRendering.shadows.bias)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-shadow-bias", "Advanced rendering shadow bias must be a finite number.", "world.advancedRendering.shadows.bias"));
}
if (!isBoolean(advancedRendering.ambientOcclusion.enabled)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-ao-enabled", "Advanced rendering ambient occlusion enabled must be a boolean.", "world.advancedRendering.ambientOcclusion.enabled"));
}
if (!isNonNegativeFiniteNumber(advancedRendering.ambientOcclusion.intensity)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-ao-intensity", "Advanced rendering ambient occlusion intensity must be a non-negative finite number.", "world.advancedRendering.ambientOcclusion.intensity"));
}
if (!isNonNegativeFiniteNumber(advancedRendering.ambientOcclusion.radius)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-ao-radius", "Advanced rendering ambient occlusion radius must be a non-negative finite number.", "world.advancedRendering.ambientOcclusion.radius"));
}
if (!isPositiveInteger(advancedRendering.ambientOcclusion.samples)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-ao-samples", "Advanced rendering ambient occlusion samples must be a positive integer.", "world.advancedRendering.ambientOcclusion.samples"));
}
if (!isBoolean(advancedRendering.bloom.enabled)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-bloom-enabled", "Advanced rendering bloom enabled must be a boolean.", "world.advancedRendering.bloom.enabled"));
}
if (!isNonNegativeFiniteNumber(advancedRendering.bloom.intensity)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-bloom-intensity", "Advanced rendering bloom intensity must be a non-negative finite number.", "world.advancedRendering.bloom.intensity"));
}
if (!isNonNegativeFiniteNumber(advancedRendering.bloom.threshold)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-bloom-threshold", "Advanced rendering bloom threshold must be a non-negative finite number.", "world.advancedRendering.bloom.threshold"));
}
if (!isNonNegativeFiniteNumber(advancedRendering.bloom.radius)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-bloom-radius", "Advanced rendering bloom radius must be a non-negative finite number.", "world.advancedRendering.bloom.radius"));
}
if (!isAdvancedRenderingToneMappingMode(advancedRendering.toneMapping.mode)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-tone-mapping-mode", "Advanced rendering tone mapping mode must be none, linear, reinhard, cineon, or acesFilmic.", "world.advancedRendering.toneMapping.mode"));
}
if (!isPositiveFiniteNumber(advancedRendering.toneMapping.exposure)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-tone-mapping-exposure", "Advanced rendering tone mapping exposure must be a positive finite number.", "world.advancedRendering.toneMapping.exposure"));
}
if (!isBoolean(advancedRendering.depthOfField.enabled)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-dof-enabled", "Advanced rendering depth of field enabled must be a boolean.", "world.advancedRendering.depthOfField.enabled"));
}
if (!isNonNegativeFiniteNumber(advancedRendering.depthOfField.focusDistance)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-dof-focus-distance", "Advanced rendering depth of field focus distance must be a non-negative finite number.", "world.advancedRendering.depthOfField.focusDistance"));
}
if (!isPositiveFiniteNumber(advancedRendering.depthOfField.focalLength)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-dof-focal-length", "Advanced rendering depth of field focal length must be a positive finite number.", "world.advancedRendering.depthOfField.focalLength"));
}
if (!isPositiveFiniteNumber(advancedRendering.depthOfField.bokehScale)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-dof-bokeh-scale", "Advanced rendering depth of field bokeh scale must be a positive finite number.", "world.advancedRendering.depthOfField.bokehScale"));
}
if (!isBoxVolumeRenderPath(advancedRendering.fogPath)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-fog-path", "Advanced rendering fog path must be performance or quality.", "world.advancedRendering.fogPath"));
}
if (!isBoxVolumeRenderPath(advancedRendering.waterPath)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-water-path", "Advanced rendering water path must be performance or quality.", "world.advancedRendering.waterPath"));
}
if (!["none", "world", "all"].includes(advancedRendering.waterReflectionMode)) {
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-water-reflection-mode", "Advanced rendering water reflection mode must be none, world, or all.", "world.advancedRendering.waterReflectionMode"));
}
}
function validatePointLightEntity(entity, path, diagnostics) {
if (!isFiniteVec3(entity.position)) {
diagnostics.push(createDiagnostic("error", "invalid-point-light-position", "Point Light position must remain finite on every axis.", `${path}.position`));
}
if (!isHexColorString(entity.colorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-point-light-color", "Point Light color must use a #RRGGBB color.", `${path}.colorHex`));
}
if (!isNonNegativeFiniteNumber(entity.intensity)) {
diagnostics.push(createDiagnostic("error", "invalid-point-light-intensity", "Point Light intensity must remain finite and zero or greater.", `${path}.intensity`));
}
if (!isPositiveFiniteNumber(entity.distance)) {
diagnostics.push(createDiagnostic("error", "invalid-point-light-distance", "Point Light distance must remain finite and greater than zero.", `${path}.distance`));
}
}
function validateSpotLightEntity(entity, path, diagnostics) {
if (!isFiniteVec3(entity.position)) {
diagnostics.push(createDiagnostic("error", "invalid-spot-light-position", "Spot Light position must remain finite on every axis.", `${path}.position`));
}
if (!isFiniteVec3(entity.direction) || !hasNonZeroVectorLength(entity.direction)) {
diagnostics.push(createDiagnostic("error", "invalid-spot-light-direction", "Spot Light direction must remain finite and must not be the zero vector.", `${path}.direction`));
}
if (!isHexColorString(entity.colorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-spot-light-color", "Spot Light color must use a #RRGGBB color.", `${path}.colorHex`));
}
if (!isNonNegativeFiniteNumber(entity.intensity)) {
diagnostics.push(createDiagnostic("error", "invalid-spot-light-intensity", "Spot Light intensity must remain finite and zero or greater.", `${path}.intensity`));
}
if (!isPositiveFiniteNumber(entity.distance)) {
diagnostics.push(createDiagnostic("error", "invalid-spot-light-distance", "Spot Light distance must remain finite and greater than zero.", `${path}.distance`));
}
if (!isFiniteNumber(entity.angleDegrees) || entity.angleDegrees <= 0 || entity.angleDegrees >= 180) {
diagnostics.push(createDiagnostic("error", "invalid-spot-light-angle", "Spot Light angle must remain a finite degree value between 0 and 180.", `${path}.angleDegrees`));
}
}
function validateProjectAssetBoundingBox(boundingBox, path, diagnostics) {
if (boundingBox === null) {
return;
}
if (!isFiniteVec3(boundingBox.min)) {
diagnostics.push(createDiagnostic("error", "invalid-asset-bounding-box-min", "Model asset bounding boxes must have finite minimum coordinates.", `${path}.min`));
}
if (!isFiniteVec3(boundingBox.max)) {
diagnostics.push(createDiagnostic("error", "invalid-asset-bounding-box-max", "Model asset bounding boxes must have finite maximum coordinates.", `${path}.max`));
}
if (!isFiniteVec3(boundingBox.size) || boundingBox.size.x < 0 || boundingBox.size.y < 0 || boundingBox.size.z < 0) {
diagnostics.push(createDiagnostic("error", "invalid-asset-bounding-box-size", "Model asset bounding boxes must have finite, zero-or-greater size values.", `${path}.size`));
}
}
function validateModelAssetMetadata(metadata, path, diagnostics) {
if (metadata.format !== "glb" && metadata.format !== "gltf") {
diagnostics.push(createDiagnostic("error", "invalid-model-asset-format", "Model asset format must be glb or gltf.", `${path}.format`));
}
if (metadata.sceneName !== null && metadata.sceneName.trim().length === 0) {
diagnostics.push(createDiagnostic("error", "invalid-model-asset-scene-name", "Model asset scene names must be non-empty when authored.", `${path}.sceneName`));
}
if (!isNonNegativeFiniteNumber(metadata.nodeCount)) {
diagnostics.push(createDiagnostic("error", "invalid-model-asset-node-count", "Model asset node counts must be finite and zero or greater.", `${path}.nodeCount`));
}
if (!isNonNegativeFiniteNumber(metadata.meshCount)) {
diagnostics.push(createDiagnostic("error", "invalid-model-asset-mesh-count", "Model asset mesh counts must be finite and zero or greater.", `${path}.meshCount`));
}
if (!Array.isArray(metadata.materialNames) || metadata.materialNames.some((name) => typeof name !== "string")) {
diagnostics.push(createDiagnostic("error", "invalid-model-asset-material-names", "Model asset material names must be string arrays.", `${path}.materialNames`));
}
if (!Array.isArray(metadata.textureNames) || metadata.textureNames.some((name) => typeof name !== "string")) {
diagnostics.push(createDiagnostic("error", "invalid-model-asset-texture-names", "Model asset texture names must be string arrays.", `${path}.textureNames`));
}
if (!Array.isArray(metadata.animationNames) || metadata.animationNames.some((name) => typeof name !== "string")) {
diagnostics.push(createDiagnostic("error", "invalid-model-asset-animation-names", "Model asset animation names must be string arrays.", `${path}.animationNames`));
}
validateProjectAssetBoundingBox(metadata.boundingBox, `${path}.boundingBox`, diagnostics);
if (!Array.isArray(metadata.warnings) || metadata.warnings.some((warning) => typeof warning !== "string")) {
diagnostics.push(createDiagnostic("error", "invalid-model-asset-warnings", "Model asset warnings must be string arrays.", `${path}.warnings`));
}
}
function validateImageAssetMetadata(metadata, path, diagnostics) {
if (!isPositiveFiniteNumber(metadata.width)) {
diagnostics.push(createDiagnostic("error", "invalid-image-asset-width", "Image asset width must be finite and greater than zero.", `${path}.width`));
}
if (!isPositiveFiniteNumber(metadata.height)) {
diagnostics.push(createDiagnostic("error", "invalid-image-asset-height", "Image asset height must be finite and greater than zero.", `${path}.height`));
}
if (!isBoolean(metadata.hasAlpha)) {
diagnostics.push(createDiagnostic("error", "invalid-image-asset-alpha", "Image asset alpha flags must be booleans.", `${path}.hasAlpha`));
}
if (!Array.isArray(metadata.warnings) || metadata.warnings.some((warning) => typeof warning !== "string")) {
diagnostics.push(createDiagnostic("error", "invalid-image-asset-warnings", "Image asset warnings must be string arrays.", `${path}.warnings`));
}
}
function validateAudioAssetMetadata(metadata, path, diagnostics) {
if (metadata.durationSeconds !== null && !isNonNegativeFiniteNumber(metadata.durationSeconds)) {
diagnostics.push(createDiagnostic("error", "invalid-audio-asset-duration", "Audio asset durations must be finite and zero or greater when authored.", `${path}.durationSeconds`));
}
if (metadata.channelCount !== null && !isPositiveFiniteNumber(metadata.channelCount)) {
diagnostics.push(createDiagnostic("error", "invalid-audio-asset-channel-count", "Audio asset channel counts must be finite and greater than zero when authored.", `${path}.channelCount`));
}
if (metadata.sampleRateHz !== null && !isPositiveFiniteNumber(metadata.sampleRateHz)) {
diagnostics.push(createDiagnostic("error", "invalid-audio-asset-sample-rate", "Audio asset sample rates must be finite and greater than zero when authored.", `${path}.sampleRateHz`));
}
if (!Array.isArray(metadata.warnings) || metadata.warnings.some((warning) => typeof warning !== "string")) {
diagnostics.push(createDiagnostic("error", "invalid-audio-asset-warnings", "Audio asset warnings must be string arrays.", `${path}.warnings`));
}
}
function validateProjectAsset(asset, path, diagnostics) {
if (asset.sourceName.trim().length === 0) {
diagnostics.push(createDiagnostic("error", "invalid-asset-source-name", "Asset source names must be non-empty strings.", `${path}.sourceName`));
}
if (asset.mimeType.trim().length === 0) {
diagnostics.push(createDiagnostic("error", "invalid-asset-mime-type", "Asset mime types must be non-empty strings.", `${path}.mimeType`));
}
if (asset.storageKey.trim().length === 0) {
diagnostics.push(createDiagnostic("error", "invalid-asset-storage-key", "Asset storage keys must be non-empty strings.", `${path}.storageKey`));
}
if (!isPositiveFiniteNumber(asset.byteLength)) {
diagnostics.push(createDiagnostic("error", "invalid-asset-byte-length", "Asset byte lengths must be finite and greater than zero.", `${path}.byteLength`));
}
switch (asset.kind) {
case "model":
validateModelAssetMetadata(asset.metadata, `${path}.metadata`, diagnostics);
break;
case "image":
validateImageAssetMetadata(asset.metadata, `${path}.metadata`, diagnostics);
break;
case "audio":
validateAudioAssetMetadata(asset.metadata, `${path}.metadata`, diagnostics);
break;
}
}
function validateModelInstance(modelInstance, path, document, diagnostics) {
if (modelInstance.name !== undefined && modelInstance.name.trim().length === 0) {
diagnostics.push(createDiagnostic("error", "invalid-model-instance-name", "Model instance names must be non-empty when authored.", `${path}.name`));
}
if (!isFiniteVec3(modelInstance.position)) {
diagnostics.push(createDiagnostic("error", "invalid-model-instance-position", "Model instance positions must remain finite on every axis.", `${path}.position`));
}
if (!isFiniteVec3(modelInstance.rotationDegrees)) {
diagnostics.push(createDiagnostic("error", "invalid-model-instance-rotation", "Model instance rotations must remain finite on every axis.", `${path}.rotationDegrees`));
}
if (!hasPositiveFiniteVec3(modelInstance.scale)) {
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) {
diagnostics.push(createDiagnostic("error", "missing-model-instance-asset", `Model instance asset ${modelInstance.assetId} does not exist.`, `${path}.assetId`));
return;
}
if (asset.kind !== "model") {
diagnostics.push(createDiagnostic("error", "invalid-model-instance-asset-kind", "Model instances may only reference model assets.", `${path}.assetId`));
}
}
function validateEntityName(name, path, diagnostics) {
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, path, diagnostics) {
if (!isFiniteVec3(entity.position)) {
diagnostics.push(createDiagnostic("error", "invalid-player-start-position", "Player Start position must remain finite on every axis.", `${path}.position`));
}
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(entity, path, document, diagnostics, missingSeverity) {
if (entity.audioAssetId === null) {
diagnostics.push(createDiagnostic(missingSeverity, "missing-sound-emitter-audio-asset", entity.autoplay
? "Sound Emitter autoplay requires an assigned audio asset."
: "Sound Emitter has no audio asset assigned yet.", `${path}.audioAssetId`));
return null;
}
const asset = document.assets[entity.audioAssetId];
if (asset === undefined) {
diagnostics.push(createDiagnostic("error", "missing-sound-emitter-audio-asset", `Sound Emitter audio asset ${entity.audioAssetId} does not exist.`, `${path}.audioAssetId`));
return null;
}
if (asset.kind !== "audio") {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-audio-asset-kind", "Sound Emitter audioAssetId must reference an audio asset.", `${path}.audioAssetId`));
return null;
}
return asset;
}
function validateSoundEmitterEntity(entity, path, document, diagnostics) {
if (!isFiniteVec3(entity.position)) {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-position", "Sound Emitter position must remain finite on every axis.", `${path}.position`));
}
if (!isNonNegativeFiniteNumber(entity.volume)) {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-volume", "Sound Emitter volume must remain finite and zero or greater.", `${path}.volume`));
}
if (!isPositiveFiniteNumber(entity.refDistance)) {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-ref-distance", "Sound Emitter ref distance must remain finite and greater than zero.", `${path}.refDistance`));
}
if (!isPositiveFiniteNumber(entity.maxDistance)) {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-max-distance", "Sound Emitter max distance must remain finite and greater than zero.", `${path}.maxDistance`));
}
if (isPositiveFiniteNumber(entity.refDistance) && isPositiveFiniteNumber(entity.maxDistance) && entity.maxDistance < entity.refDistance) {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-distance-order", "Sound Emitter max distance must be greater than or equal to ref distance.", `${path}.maxDistance`));
}
if (!isBoolean(entity.autoplay)) {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-autoplay", "Sound Emitter autoplay must remain a boolean.", `${path}.autoplay`));
}
if (!isBoolean(entity.loop)) {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-loop", "Sound Emitter loop must remain a boolean.", `${path}.loop`));
}
validateSoundEmitterAudioAsset(entity, path, document, diagnostics, entity.autoplay ? "error" : "warning");
}
function validateTriggerVolumeEntity(entity, path, diagnostics) {
if (!isFiniteVec3(entity.position)) {
diagnostics.push(createDiagnostic("error", "invalid-trigger-volume-position", "Trigger Volume position must remain finite on every axis.", `${path}.position`));
}
if (!hasPositiveFiniteVec3(entity.size)) {
diagnostics.push(createDiagnostic("error", "invalid-trigger-volume-size", "Trigger Volume size must remain finite and positive on every axis.", `${path}.size`));
}
if (!isBoolean(entity.triggerOnEnter)) {
diagnostics.push(createDiagnostic("error", "invalid-trigger-volume-enter-flag", "Trigger Volume triggerOnEnter must remain a boolean.", `${path}.triggerOnEnter`));
}
if (!isBoolean(entity.triggerOnExit)) {
diagnostics.push(createDiagnostic("error", "invalid-trigger-volume-exit-flag", "Trigger Volume triggerOnExit must remain a boolean.", `${path}.triggerOnExit`));
}
}
function validateTeleportTargetEntity(entity, path, diagnostics) {
if (!isFiniteVec3(entity.position)) {
diagnostics.push(createDiagnostic("error", "invalid-teleport-target-position", "Teleport Target position must remain finite on every axis.", `${path}.position`));
}
if (!isFiniteNumber(entity.yawDegrees)) {
diagnostics.push(createDiagnostic("error", "invalid-teleport-target-yaw", "Teleport Target yaw must remain a finite number.", `${path}.yawDegrees`));
}
}
function validateInteractableEntity(entity, path, diagnostics) {
if (!isFiniteVec3(entity.position)) {
diagnostics.push(createDiagnostic("error", "invalid-interactable-position", "Interactable position must remain finite on every axis.", `${path}.position`));
}
if (!isPositiveFiniteNumber(entity.radius)) {
diagnostics.push(createDiagnostic("error", "invalid-interactable-radius", "Interactable radius must remain finite and greater than zero.", `${path}.radius`));
}
if (typeof entity.prompt !== "string" || entity.prompt.trim().length === 0) {
diagnostics.push(createDiagnostic("error", "invalid-interactable-prompt", "Interactable prompt must remain a non-empty string.", `${path}.prompt`));
}
if (!isBoolean(entity.enabled)) {
diagnostics.push(createDiagnostic("error", "invalid-interactable-enabled", "Interactable enabled must remain a boolean.", `${path}.enabled`));
}
}
function validateInteractionLink(link, path, document, diagnostics) {
const sourceEntity = document.entities[link.sourceEntityId];
if (sourceEntity === undefined) {
diagnostics.push(createDiagnostic("error", "missing-interaction-source-entity", `Interaction source entity ${link.sourceEntityId} does not exist.`, `${path}.sourceEntityId`));
return;
}
if (sourceEntity.kind !== "triggerVolume" && sourceEntity.kind !== "interactable") {
diagnostics.push(createDiagnostic("error", "invalid-interaction-source-kind", "Interaction links may only source from Trigger Volume or Interactable entities in the current slice.", `${path}.sourceEntityId`));
}
if (sourceEntity.kind === "triggerVolume") {
if (link.trigger !== "enter" && link.trigger !== "exit") {
diagnostics.push(createDiagnostic("error", "unsupported-interaction-trigger", "Trigger Volume links may only use enter or exit triggers.", `${path}.trigger`));
}
}
else if (sourceEntity.kind === "interactable") {
if (link.trigger !== "click") {
diagnostics.push(createDiagnostic("error", "unsupported-interaction-trigger", "Interactable links may only use the click trigger.", `${path}.trigger`));
}
}
switch (link.action.type) {
case "teleportPlayer": {
const targetEntity = document.entities[link.action.targetEntityId];
if (targetEntity === undefined) {
diagnostics.push(createDiagnostic("error", "missing-teleport-target-entity", `Teleport target entity ${link.action.targetEntityId} does not exist.`, `${path}.action.targetEntityId`));
return;
}
if (targetEntity.kind !== "teleportTarget") {
diagnostics.push(createDiagnostic("error", "invalid-teleport-target-kind", "Teleport player actions must target a Teleport Target entity.", `${path}.action.targetEntityId`));
}
break;
}
case "toggleVisibility":
if (document.brushes[link.action.targetBrushId] === undefined) {
diagnostics.push(createDiagnostic("error", "missing-visibility-target-brush", `Visibility target brush ${link.action.targetBrushId} does not exist.`, `${path}.action.targetBrushId`));
}
if (link.action.visible !== undefined && typeof link.action.visible !== "boolean") {
diagnostics.push(createDiagnostic("error", "invalid-visibility-action-visible", "Visibility actions must use a boolean visible value when authored.", `${path}.action.visible`));
}
break;
case "playAnimation":
{
const targetModelInstance = document.modelInstances[link.action.targetModelInstanceId];
if (targetModelInstance === undefined) {
diagnostics.push(createDiagnostic("error", "missing-play-animation-target-instance", `Play animation target model instance ${link.action.targetModelInstanceId} does not exist.`, `${path}.action.targetModelInstanceId`));
return;
}
if (link.action.clipName.trim().length === 0) {
diagnostics.push(createDiagnostic("error", "invalid-play-animation-clip-name", "Play animation clip name must be non-empty.", `${path}.action.clipName`));
return;
}
const targetAsset = document.assets[targetModelInstance.assetId];
if (targetAsset === undefined || targetAsset.kind !== "model") {
return;
}
if (!targetAsset.metadata.animationNames.includes(link.action.clipName)) {
diagnostics.push(createDiagnostic("error", "missing-play-animation-clip", `Play animation clip ${link.action.clipName} does not exist on model asset ${targetAsset.id}.`, `${path}.action.clipName`));
}
break;
}
case "stopAnimation":
// Validate that the target model instance exists in the document
if (document.modelInstances[link.action.targetModelInstanceId] === undefined) {
diagnostics.push(createDiagnostic("error", "missing-stop-animation-target-instance", `Stop animation target model instance ${link.action.targetModelInstanceId} does not exist.`, `${path}.action.targetModelInstanceId`));
}
break;
case "playSound":
case "stopSound": {
const targetEntity = document.entities[link.action.targetSoundEmitterId];
if (targetEntity === undefined) {
diagnostics.push(createDiagnostic("error", "missing-sound-emitter-entity", `Sound emitter entity ${link.action.targetSoundEmitterId} does not exist.`, `${path}.action.targetSoundEmitterId`));
break;
}
if (targetEntity.kind !== "soundEmitter") {
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-kind", "Sound playback actions must target a Sound Emitter entity.", `${path}.action.targetSoundEmitterId`));
break;
}
if (targetEntity.audioAssetId === null) {
diagnostics.push(createDiagnostic("error", "missing-sound-emitter-audio-asset", "Sound playback actions require a Sound Emitter that references an audio asset.", `${path}.action.targetSoundEmitterId`));
}
break;
}
default:
diagnostics.push(createDiagnostic("error", "unsupported-interaction-action", `Unsupported interaction action ${link.action.type}.`, `${path}.action.type`));
break;
}
}
function registerAuthoredId(id, path, seenIds, diagnostics) {
const previousPath = seenIds.get(id);
if (previousPath !== undefined) {
diagnostics.push(createDiagnostic("error", "duplicate-authored-id", `Duplicate authored id ${id} is already used at ${previousPath}.`, path));
return;
}
seenIds.set(id, path);
}
export function formatSceneDiagnostic(diagnostic) {
return diagnostic.path === undefined ? diagnostic.message : `${diagnostic.path}: ${diagnostic.message}`;
}
export function formatSceneDiagnosticSummary(diagnostics, limit = 3) {
if (diagnostics.length === 0) {
return "No diagnostics.";
}
const visibleDiagnostics = diagnostics.slice(0, Math.max(1, limit));
const summary = visibleDiagnostics.map((diagnostic) => formatSceneDiagnostic(diagnostic)).join("; ");
const remainingCount = diagnostics.length - visibleDiagnostics.length;
return remainingCount > 0 ? `${summary}; +${remainingCount} more` : summary;
}
export function validateSceneDocument(document) {
const diagnostics = [];
const seenIds = new Map();
validateWorldSettings(document.world, document, diagnostics);
for (const [materialKey, material] of Object.entries(document.materials)) {
const path = `materials.${materialKey}`;
if (material.id !== materialKey) {
diagnostics.push(createDiagnostic("error", "material-id-mismatch", "Material ids must match their registry key.", `${path}.id`));
}
registerAuthoredId(material.id, path, seenIds, diagnostics);
}
for (const [assetKey, asset] of Object.entries(document.assets)) {
const path = `assets.${assetKey}`;
if (asset.id !== assetKey) {
diagnostics.push(createDiagnostic("error", "asset-id-mismatch", "Asset ids must match their registry key.", `${path}.id`));
}
registerAuthoredId(asset.id, path, seenIds, diagnostics);
validateProjectAsset(asset, path, diagnostics);
}
for (const [brushKey, brush] of Object.entries(document.brushes)) {
const path = `brushes.${brushKey}`;
if (brush.id !== brushKey) {
diagnostics.push(createDiagnostic("error", "brush-id-mismatch", "Brush ids must match their registry key.", `${path}.id`));
}
registerAuthoredId(brush.id, path, seenIds, diagnostics);
if (brush.name !== undefined && brush.name.trim().length === 0) {
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`));
}
for (const vertexId of BOX_VERTEX_IDS) {
if (!isFiniteVec3(brush.geometry.vertices[vertexId])) {
diagnostics.push(createDiagnostic("error", "invalid-box-geometry-vertex", "Box brush geometry vertices must remain finite on every axis.", `${path}.geometry.vertices.${vertexId}`));
}
}
for (const faceId of BOX_FACE_IDS) {
const materialId = brush.faces[faceId].materialId;
if (materialId !== null && document.materials[materialId] === undefined) {
diagnostics.push(createDiagnostic("error", "missing-material-ref", `Face material reference ${materialId} does not exist in the document material registry.`, `${path}.faces.${faceId}.materialId`));
}
}
const volume = brush.volume;
if (!isBoxBrushVolumeMode(volume?.mode)) {
diagnostics.push(createDiagnostic("error", "invalid-box-volume-mode", "Box volume mode must be none, water, or fog.", `${path}.volume.mode`));
continue;
}
if (volume.mode === "water") {
const water = volume.water;
if (water === undefined) {
diagnostics.push(createDiagnostic("error", "invalid-box-water-settings", "Water volumes must define water settings.", `${path}.volume.water`));
}
else {
if (typeof water.colorHex !== "string" || !isHexColorString(water.colorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-box-water-color", "Water volume color must use #RRGGBB format.", `${path}.volume.water.colorHex`));
}
if (!isNonNegativeFiniteNumber(water.surfaceOpacity)) {
diagnostics.push(createDiagnostic("error", "invalid-box-water-surface-opacity", "Water surface opacity must be a non-negative finite number.", `${path}.volume.water.surfaceOpacity`));
}
if (!isNonNegativeFiniteNumber(water.waveStrength)) {
diagnostics.push(createDiagnostic("error", "invalid-box-water-wave-strength", "Water wave strength must be a non-negative finite number.", `${path}.volume.water.waveStrength`));
}
if (!isPositiveIntegerInRange(water.foamContactLimit, MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT)) {
diagnostics.push(createDiagnostic("error", "invalid-box-water-foam-contact-limit", `Water foam contact limit must be a positive integer between 1 and ${MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT}.`, `${path}.volume.water.foamContactLimit`));
}
if (typeof water.surfaceDisplacementEnabled !== "boolean") {
diagnostics.push(createDiagnostic("error", "invalid-box-water-surface-displacement-enabled", "Water surface displacement must be enabled or disabled explicitly.", `${path}.volume.water.surfaceDisplacementEnabled`));
}
}
}
if (volume.mode === "fog") {
const fog = volume.fog;
if (fog === undefined) {
diagnostics.push(createDiagnostic("error", "invalid-box-fog-settings", "Fog volumes must define fog settings.", `${path}.volume.fog`));
}
else {
if (typeof fog.colorHex !== "string" || !isHexColorString(fog.colorHex)) {
diagnostics.push(createDiagnostic("error", "invalid-box-fog-color", "Fog volume color must use #RRGGBB format.", `${path}.volume.fog.colorHex`));
}
if (!isNonNegativeFiniteNumber(fog.density)) {
diagnostics.push(createDiagnostic("error", "invalid-box-fog-density", "Fog volume density must be a non-negative finite number.", `${path}.volume.fog.density`));
}
if (!isNonNegativeFiniteNumber(fog.padding)) {
diagnostics.push(createDiagnostic("error", "invalid-box-fog-padding", "Fog volume padding must be a non-negative finite number.", `${path}.volume.fog.padding`));
}
}
}
}
for (const [modelInstanceKey, modelInstance] of Object.entries(document.modelInstances)) {
const path = `modelInstances.${modelInstanceKey}`;
if (modelInstance.id !== modelInstanceKey) {
diagnostics.push(createDiagnostic("error", "model-instance-id-mismatch", "Model instance ids must match their registry key.", `${path}.id`));
}
registerAuthoredId(modelInstance.id, path, seenIds, diagnostics);
validateModelInstance(modelInstance, path, document, diagnostics);
}
for (const [entityKey, entity] of Object.entries(document.entities)) {
const path = `entities.${entityKey}`;
if (entity.id !== entityKey) {
diagnostics.push(createDiagnostic("error", "entity-id-mismatch", "Entity ids must match their registry key.", `${path}.id`));
}
registerAuthoredId(entity.id, path, seenIds, diagnostics);
validateEntityName(entity.name, path, diagnostics);
switch (entity.kind) {
case "pointLight":
validatePointLightEntity(entity, path, diagnostics);
break;
case "spotLight":
validateSpotLightEntity(entity, path, diagnostics);
break;
case "playerStart":
validatePlayerStartEntity(entity, path, diagnostics);
break;
case "soundEmitter":
validateSoundEmitterEntity(entity, path, document, diagnostics);
break;
case "triggerVolume":
validateTriggerVolumeEntity(entity, path, diagnostics);
break;
case "teleportTarget":
validateTeleportTargetEntity(entity, path, diagnostics);
break;
case "interactable":
validateInteractableEntity(entity, path, diagnostics);
break;
default:
diagnostics.push(createDiagnostic("error", "unsupported-entity-kind", `Unsupported entity kind ${entity.kind}.`, `${path}.kind`));
break;
}
}
for (const [linkKey, link] of Object.entries(document.interactionLinks)) {
const path = `interactionLinks.${linkKey}`;
if (link.id !== linkKey) {
diagnostics.push(createDiagnostic("error", "interaction-link-id-mismatch", "Interaction link ids must match their registry key.", `${path}.id`));
}
registerAuthoredId(link.id, path, seenIds, diagnostics);
validateInteractionLink(link, path, document, diagnostics);
}
return {
diagnostics,
errors: diagnostics.filter((diagnostic) => diagnostic.severity === "error"),
warnings: diagnostics.filter((diagnostic) => diagnostic.severity === "warning")
};
}
export function assertSceneDocumentIsValid(document) {
const validation = validateSceneDocument(document);
if (validation.errors.length > 0) {
throw new Error(`Scene document has ${validation.errors.length} validation error(s): ${formatSceneDiagnosticSummary(validation.errors)}`);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
import { cloneMaterialRegistry, createStarterMaterialRegistry } from "../materials/starter-material-library";
import { createDefaultWorldSettings } from "./world-settings";
export const SCENE_DOCUMENT_VERSION = 21;
export const WATER_SURFACE_DISPLACEMENT_SCENE_DOCUMENT_VERSION = 21;
export const WHITEBOX_BOX_VOLUME_SCENE_DOCUMENT_VERSION = 20;
export const WHITEBOX_GEOMETRY_SCENE_DOCUMENT_VERSION = 19;
export const WHITEBOX_FLOAT_TRANSFORM_SCENE_DOCUMENT_VERSION = 18;
export const PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION = 17;
export const IMPORTED_MODEL_COLLIDERS_SCENE_DOCUMENT_VERSION = 16;
export const ENTITY_NAMES_SCENE_DOCUMENT_VERSION = 15;
export const SPATIAL_AUDIO_SCENE_DOCUMENT_VERSION = 13;
export const ANIMATION_PLAYBACK_SCENE_DOCUMENT_VERSION = 12;
export const LOCAL_LIGHTS_AND_SKYBOX_SCENE_DOCUMENT_VERSION = 10;
export const MODEL_ASSET_PIPELINE_SCENE_DOCUMENT_VERSION = 9;
export const FOUNDATION_SCENE_DOCUMENT_VERSION = 1;
export const BOX_BRUSH_SCENE_DOCUMENT_VERSION = 2;
export const FACE_MATERIALS_SCENE_DOCUMENT_VERSION = 3;
export const RUNNER_V1_SCENE_DOCUMENT_VERSION = 4;
export const FIRST_ROOM_POLISH_SCENE_DOCUMENT_VERSION = 5;
export const WORLD_ENVIRONMENT_SCENE_DOCUMENT_VERSION = 6;
export const ENTITY_SYSTEM_FOUNDATION_SCENE_DOCUMENT_VERSION = 7;
export const TRIGGER_ACTION_TARGET_FOUNDATION_SCENE_DOCUMENT_VERSION = 8;
export function createEmptySceneDocument(overrides = {}) {
return {
version: SCENE_DOCUMENT_VERSION,
name: overrides.name ?? "Untitled Scene",
world: overrides.world ?? createDefaultWorldSettings(),
materials: cloneMaterialRegistry(overrides.materials ?? createStarterMaterialRegistry()),
textures: {},
assets: {},
brushes: {},
modelInstances: {},
entities: {},
interactionLinks: {}
};
}

View File

@@ -1,14 +1,32 @@
import { createOpaqueId } from "../core/ids";
import type { Brush } from "./brushes";
import type { ModelInstance } from "../assets/model-instances";
import type { ProjectAssetRecord } from "../assets/project-assets";
import type { EntityInstance } from "../entities/entity-instances";
import type { InteractionLink } from "../interactions/interaction-links";
import { cloneMaterialRegistry, createStarterMaterialRegistry, type MaterialDef } from "../materials/starter-material-library";
import { createDefaultWorldSettings, type WorldSettings } from "./world-settings";
import {
cloneMaterialRegistry,
createStarterMaterialRegistry,
type MaterialDef
} from "../materials/starter-material-library";
import {
createDefaultWorldSettings,
type WorldSettings
} from "./world-settings";
export const SCENE_DOCUMENT_VERSION = 18 as const;
export const SCENE_DOCUMENT_VERSION = 28 as const;
export const PROJECT_NAME_SCENE_DOCUMENT_VERSION = 28 as const;
export const PLAYER_START_GAMEPAD_CAMERA_LOOK_SCENE_DOCUMENT_VERSION = 27 as const;
export const PLAYER_START_INPUT_BINDINGS_SCENE_DOCUMENT_VERSION = 26 as const;
export const PLAYER_START_NAVIGATION_MODE_SCENE_DOCUMENT_VERSION = 25 as const;
export const SCENE_TRANSITION_ENTITIES_SCENE_DOCUMENT_VERSION = 24 as const;
export const MULTI_SCENE_FOUNDATION_SCENE_DOCUMENT_VERSION = 22 as const;
export const WATER_SURFACE_DISPLACEMENT_SCENE_DOCUMENT_VERSION = 21 as const;
export const WHITEBOX_BOX_VOLUME_SCENE_DOCUMENT_VERSION = 20 as const;
export const WHITEBOX_GEOMETRY_SCENE_DOCUMENT_VERSION = 19 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 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;
@@ -22,7 +40,39 @@ export const RUNNER_V1_SCENE_DOCUMENT_VERSION = 4 as const;
export const FIRST_ROOM_POLISH_SCENE_DOCUMENT_VERSION = 5 as const;
export const WORLD_ENVIRONMENT_SCENE_DOCUMENT_VERSION = 6 as const;
export const ENTITY_SYSTEM_FOUNDATION_SCENE_DOCUMENT_VERSION = 7 as const;
export const TRIGGER_ACTION_TARGET_FOUNDATION_SCENE_DOCUMENT_VERSION = 8 as const;
export const TRIGGER_ACTION_TARGET_FOUNDATION_SCENE_DOCUMENT_VERSION =
8 as const;
export const RUNNER_LOADING_SCREEN_SCENE_DOCUMENT_VERSION = 23 as const;
export const DEFAULT_PROJECT_NAME = "Untitled Project" as const;
export const DEFAULT_PROJECT_SCENE_ID = "scene-main" as const;
export interface SceneLoadingScreenSettings {
colorHex: string;
headline: string | null;
description: string | null;
}
export interface ProjectScene {
id: string;
name: string;
loadingScreen: SceneLoadingScreenSettings;
world: WorldSettings;
brushes: Record<string, Brush>;
modelInstances: Record<string, ModelInstance>;
entities: Record<string, EntityInstance>;
interactionLinks: Record<string, InteractionLink>;
}
export interface ProjectDocument {
version: typeof SCENE_DOCUMENT_VERSION;
name: string;
activeSceneId: string;
scenes: Record<string, ProjectScene>;
materials: Record<string, MaterialDef>;
textures: Record<string, never>;
assets: Record<string, ProjectAssetRecord>;
}
export interface SceneDocument {
version: typeof SCENE_DOCUMENT_VERSION;
@@ -37,12 +87,16 @@ export interface SceneDocument {
interactionLinks: Record<string, InteractionLink>;
}
export function createEmptySceneDocument(overrides: Partial<Pick<SceneDocument, "name" | "world" | "materials">> = {}): SceneDocument {
export function createEmptySceneDocument(
overrides: Partial<Pick<SceneDocument, "name" | "world" | "materials">> = {}
): SceneDocument {
return {
version: SCENE_DOCUMENT_VERSION,
name: overrides.name ?? "Untitled Scene",
world: overrides.world ?? createDefaultWorldSettings(),
materials: cloneMaterialRegistry(overrides.materials ?? createStarterMaterialRegistry()),
materials: cloneMaterialRegistry(
overrides.materials ?? createStarterMaterialRegistry()
),
textures: {},
assets: {},
brushes: {},
@@ -51,3 +105,173 @@ export function createEmptySceneDocument(overrides: Partial<Pick<SceneDocument,
interactionLinks: {}
};
}
export function createEmptyProjectScene(
overrides: Partial<
Pick<ProjectScene, "id" | "name" | "loadingScreen" | "world">
> = {}
): ProjectScene {
return {
id: overrides.id ?? createOpaqueId("scene"),
name: overrides.name ?? "Untitled Scene",
loadingScreen: cloneSceneLoadingScreenSettings(
overrides.loadingScreen ?? createDefaultSceneLoadingScreenSettings()
),
world: overrides.world ?? createDefaultWorldSettings(),
brushes: {},
modelInstances: {},
entities: {},
interactionLinks: {}
};
}
export function createEmptyProjectDocument(
overrides: Partial<
Pick<
ProjectDocument,
"name" | "activeSceneId" | "materials" | "textures" | "assets"
>
> & {
sceneId?: string;
sceneName?: string;
world?: WorldSettings;
} = {}
): ProjectDocument {
const initialScene = createEmptyProjectScene({
id:
overrides.sceneId ?? overrides.activeSceneId ?? DEFAULT_PROJECT_SCENE_ID,
name: overrides.sceneName,
world: overrides.world
});
return {
version: SCENE_DOCUMENT_VERSION,
name: overrides.name ?? DEFAULT_PROJECT_NAME,
activeSceneId: initialScene.id,
scenes: {
[initialScene.id]: initialScene
},
materials: cloneMaterialRegistry(
overrides.materials ?? createStarterMaterialRegistry()
),
textures: overrides.textures ?? {},
assets: overrides.assets ?? {}
};
}
export function getProjectScene(
projectDocument: ProjectDocument,
sceneId = projectDocument.activeSceneId
): ProjectScene {
const scene = projectDocument.scenes[sceneId];
if (scene === undefined) {
throw new Error(`Project scene ${sceneId} does not exist.`);
}
return scene;
}
export function createSceneDocumentFromProject(
projectDocument: ProjectDocument,
sceneId = projectDocument.activeSceneId
): SceneDocument {
const scene = getProjectScene(projectDocument, sceneId);
return {
version: projectDocument.version,
name: scene.name,
world: scene.world,
materials: projectDocument.materials,
textures: projectDocument.textures,
assets: projectDocument.assets,
brushes: scene.brushes,
modelInstances: scene.modelInstances,
entities: scene.entities,
interactionLinks: scene.interactionLinks
};
}
export function createProjectDocumentFromSceneDocument(
sceneDocument: SceneDocument,
sceneId = DEFAULT_PROJECT_SCENE_ID,
projectName = DEFAULT_PROJECT_NAME
): ProjectDocument {
return {
version: SCENE_DOCUMENT_VERSION,
name: projectName,
activeSceneId: sceneId,
scenes: {
[sceneId]: {
id: sceneId,
name: sceneDocument.name,
loadingScreen: createDefaultSceneLoadingScreenSettings(),
world: sceneDocument.world,
brushes: sceneDocument.brushes,
modelInstances: sceneDocument.modelInstances,
entities: sceneDocument.entities,
interactionLinks: sceneDocument.interactionLinks
}
},
materials: sceneDocument.materials,
textures: sceneDocument.textures,
assets: sceneDocument.assets
};
}
export function applySceneDocumentToProject(
projectDocument: ProjectDocument,
sceneId: string,
sceneDocument: SceneDocument
): ProjectDocument {
const previousScene = getProjectScene(projectDocument, sceneId);
return {
...projectDocument,
version: SCENE_DOCUMENT_VERSION,
materials: sceneDocument.materials,
textures: sceneDocument.textures,
assets: sceneDocument.assets,
scenes: {
...projectDocument.scenes,
[sceneId]: {
...previousScene,
name: sceneDocument.name,
world: sceneDocument.world,
brushes: sceneDocument.brushes,
modelInstances: sceneDocument.modelInstances,
entities: sceneDocument.entities,
interactionLinks: sceneDocument.interactionLinks
}
}
};
}
export function createDefaultSceneLoadingScreenSettings(): SceneLoadingScreenSettings {
return {
colorHex: "#0d1117",
headline: null,
description: null
};
}
export function cloneSceneLoadingScreenSettings(
settings: SceneLoadingScreenSettings
): SceneLoadingScreenSettings {
return {
colorHex: settings.colorHex,
headline: settings.headline,
description: settings.description
};
}
export function areSceneLoadingScreenSettingsEqual(
left: SceneLoadingScreenSettings,
right: SceneLoadingScreenSettings
): boolean {
return (
left.colorHex === right.colorHex &&
left.headline === right.headline &&
left.description === right.description
);
}

View File

@@ -0,0 +1,254 @@
import { DEFAULT_SUN_DIRECTION } from "../core/vector";
export const ADVANCED_RENDERING_SHADOW_MAP_SIZES = [512, 1024, 2048, 4096];
export const ADVANCED_RENDERING_SHADOW_TYPES = ["basic", "pcf", "pcfSoft"];
export const ADVANCED_RENDERING_TONE_MAPPING_MODES = ["none", "linear", "reinhard", "cineon", "acesFilmic"];
export const BOX_VOLUME_RENDER_PATHS = ["performance", "quality"];
export const ADVANCED_RENDERING_WATER_REFLECTION_MODES = ["none", "world", "all"];
const DEFAULT_SOLID_BACKGROUND_COLOR = "#2f3947";
const DEFAULT_GRADIENT_TOP_COLOR = DEFAULT_SOLID_BACKGROUND_COLOR;
const DEFAULT_GRADIENT_BOTTOM_COLOR = "#141a22";
const DEFAULT_ADVANCED_RENDERING_SHADOW_MAP_SIZE = 2048;
const DEFAULT_ADVANCED_RENDERING_SHADOW_TYPE = "pcfSoft";
const DEFAULT_ADVANCED_RENDERING_SHADOW_BIAS = -0.0005;
const DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_INTENSITY = 1;
const DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_RADIUS = 0.5;
const DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_SAMPLES = 8;
const DEFAULT_ADVANCED_RENDERING_BLOOM_INTENSITY = 0.75;
const DEFAULT_ADVANCED_RENDERING_BLOOM_THRESHOLD = 0.85;
const DEFAULT_ADVANCED_RENDERING_BLOOM_RADIUS = 0.35;
const DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_MODE = "acesFilmic";
const DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_EXPOSURE = 1;
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCUS_DISTANCE = 10;
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCAL_LENGTH = 0.03;
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_BOKEH_SCALE = 1.5;
const DEFAULT_BOX_VOLUME_RENDER_PATH = "performance";
const DEFAULT_ADVANCED_RENDERING_WATER_REFLECTION_MODE = "none";
export function isAdvancedRenderingShadowMapSize(value) {
return ADVANCED_RENDERING_SHADOW_MAP_SIZES.includes(value);
}
export function isAdvancedRenderingShadowType(value) {
return ADVANCED_RENDERING_SHADOW_TYPES.includes(value);
}
export function isAdvancedRenderingToneMappingMode(value) {
return ADVANCED_RENDERING_TONE_MAPPING_MODES.includes(value);
}
export function isBoxVolumeRenderPath(value) {
return BOX_VOLUME_RENDER_PATHS.includes(value);
}
export function isAdvancedRenderingWaterReflectionMode(value) {
return ADVANCED_RENDERING_WATER_REFLECTION_MODES.includes(value);
}
export function createDefaultAdvancedRenderingSettings() {
return {
enabled: false,
shadows: {
enabled: false,
mapSize: DEFAULT_ADVANCED_RENDERING_SHADOW_MAP_SIZE,
type: DEFAULT_ADVANCED_RENDERING_SHADOW_TYPE,
bias: DEFAULT_ADVANCED_RENDERING_SHADOW_BIAS
},
ambientOcclusion: {
enabled: false,
intensity: DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_INTENSITY,
radius: DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_RADIUS,
samples: DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_SAMPLES
},
bloom: {
enabled: false,
intensity: DEFAULT_ADVANCED_RENDERING_BLOOM_INTENSITY,
threshold: DEFAULT_ADVANCED_RENDERING_BLOOM_THRESHOLD,
radius: DEFAULT_ADVANCED_RENDERING_BLOOM_RADIUS
},
toneMapping: {
mode: DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_MODE,
exposure: DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_EXPOSURE
},
depthOfField: {
enabled: false,
focusDistance: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCUS_DISTANCE,
focalLength: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCAL_LENGTH,
bokehScale: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_BOKEH_SCALE
},
fogPath: DEFAULT_BOX_VOLUME_RENDER_PATH,
waterPath: DEFAULT_BOX_VOLUME_RENDER_PATH,
waterReflectionMode: DEFAULT_ADVANCED_RENDERING_WATER_REFLECTION_MODE
};
}
export function createDefaultWorldSettings() {
return {
background: {
mode: "solid",
colorHex: DEFAULT_SOLID_BACKGROUND_COLOR
},
ambientLight: {
colorHex: "#f7f1e8",
intensity: 1
},
sunLight: {
colorHex: "#fff1d5",
intensity: 1.75,
direction: {
...DEFAULT_SUN_DIRECTION
}
},
advancedRendering: createDefaultAdvancedRenderingSettings()
};
}
export function isHexColorString(value) {
return /^#[0-9a-f]{6}$/i.test(value);
}
export function isWorldBackgroundMode(value) {
return value === "solid" || value === "verticalGradient" || value === "image";
}
export function cloneWorldBackgroundSettings(background) {
if (background.mode === "solid") {
return {
mode: "solid",
colorHex: background.colorHex
};
}
if (background.mode === "verticalGradient") {
return {
mode: "verticalGradient",
topColorHex: background.topColorHex,
bottomColorHex: background.bottomColorHex
};
}
return {
mode: "image",
assetId: background.assetId,
environmentIntensity: background.environmentIntensity
};
}
export function cloneWorldSettings(world) {
return {
background: cloneWorldBackgroundSettings(world.background),
ambientLight: {
...world.ambientLight
},
sunLight: {
...world.sunLight,
direction: {
...world.sunLight.direction
}
},
advancedRendering: cloneAdvancedRenderingSettings(world.advancedRendering)
};
}
export function cloneAdvancedRenderingSettings(settings) {
return {
enabled: settings.enabled,
shadows: {
...settings.shadows
},
ambientOcclusion: {
...settings.ambientOcclusion
},
bloom: {
...settings.bloom
},
toneMapping: {
...settings.toneMapping
},
depthOfField: {
...settings.depthOfField
},
fogPath: settings.fogPath,
waterPath: settings.waterPath,
waterReflectionMode: settings.waterReflectionMode
};
}
export function areWorldBackgroundSettingsEqual(left, right) {
if (left.mode !== right.mode) {
return false;
}
if (left.mode === "solid" && right.mode === "solid") {
return left.colorHex === right.colorHex;
}
if (left.mode === "verticalGradient" && right.mode === "verticalGradient") {
return left.topColorHex === right.topColorHex && left.bottomColorHex === right.bottomColorHex;
}
return left.mode === "image" && right.mode === "image" && left.assetId === right.assetId && left.environmentIntensity === right.environmentIntensity;
}
export function areWorldSettingsEqual(left, right) {
return (areWorldBackgroundSettingsEqual(left.background, right.background) &&
left.ambientLight.colorHex === right.ambientLight.colorHex &&
left.ambientLight.intensity === right.ambientLight.intensity &&
left.sunLight.colorHex === right.sunLight.colorHex &&
left.sunLight.intensity === right.sunLight.intensity &&
left.sunLight.direction.x === right.sunLight.direction.x &&
left.sunLight.direction.y === right.sunLight.direction.y &&
left.sunLight.direction.z === right.sunLight.direction.z &&
areAdvancedRenderingSettingsEqual(left.advancedRendering, right.advancedRendering));
}
export function areAdvancedRenderingSettingsEqual(left, right) {
return (left.enabled === right.enabled &&
left.shadows.enabled === right.shadows.enabled &&
left.shadows.mapSize === right.shadows.mapSize &&
left.shadows.type === right.shadows.type &&
left.shadows.bias === right.shadows.bias &&
left.ambientOcclusion.enabled === right.ambientOcclusion.enabled &&
left.ambientOcclusion.intensity === right.ambientOcclusion.intensity &&
left.ambientOcclusion.radius === right.ambientOcclusion.radius &&
left.ambientOcclusion.samples === right.ambientOcclusion.samples &&
left.bloom.enabled === right.bloom.enabled &&
left.bloom.intensity === right.bloom.intensity &&
left.bloom.threshold === right.bloom.threshold &&
left.bloom.radius === right.bloom.radius &&
left.toneMapping.mode === right.toneMapping.mode &&
left.toneMapping.exposure === right.toneMapping.exposure &&
left.depthOfField.enabled === right.depthOfField.enabled &&
left.depthOfField.focusDistance === right.depthOfField.focusDistance &&
left.depthOfField.focalLength === right.depthOfField.focalLength &&
left.depthOfField.bokehScale === right.depthOfField.bokehScale &&
left.fogPath === right.fogPath &&
left.waterPath === right.waterPath &&
left.waterReflectionMode === right.waterReflectionMode);
}
export function changeWorldBackgroundMode(background, mode, imageAssetId) {
if (mode === "image") {
if (imageAssetId === undefined || imageAssetId.trim().length === 0) {
if (background.mode === "image") {
return cloneWorldBackgroundSettings(background);
}
throw new Error("An image asset must be selected to use an image background.");
}
return {
mode: "image",
assetId: imageAssetId,
environmentIntensity: background.mode === "image" ? background.environmentIntensity : 0.5
};
}
if (background.mode === mode) {
return cloneWorldBackgroundSettings(background);
}
if (mode === "solid") {
return {
mode: "solid",
colorHex: background.mode === "solid"
? background.colorHex
: background.mode === "verticalGradient"
? background.topColorHex
: DEFAULT_SOLID_BACKGROUND_COLOR
};
}
if (background.mode === "solid") {
return {
mode: "verticalGradient",
topColorHex: background.colorHex,
bottomColorHex: DEFAULT_GRADIENT_BOTTOM_COLOR
};
}
if (background.mode === "verticalGradient") {
return {
mode: "verticalGradient",
topColorHex: background.topColorHex,
bottomColorHex: background.bottomColorHex
};
}
return {
mode: "verticalGradient",
topColorHex: DEFAULT_GRADIENT_TOP_COLOR,
bottomColorHex: DEFAULT_GRADIENT_BOTTOM_COLOR
};
}

View File

@@ -5,10 +5,14 @@ export type WorldBackgroundMode = "solid" | "verticalGradient" | "image";
export const ADVANCED_RENDERING_SHADOW_MAP_SIZES = [512, 1024, 2048, 4096] as const;
export const ADVANCED_RENDERING_SHADOW_TYPES = ["basic", "pcf", "pcfSoft"] as const;
export const ADVANCED_RENDERING_TONE_MAPPING_MODES = ["none", "linear", "reinhard", "cineon", "acesFilmic"] as const;
export const BOX_VOLUME_RENDER_PATHS = ["performance", "quality"] as const;
export const ADVANCED_RENDERING_WATER_REFLECTION_MODES = ["none", "world", "all"] as const;
export type AdvancedRenderingShadowMapSize = (typeof ADVANCED_RENDERING_SHADOW_MAP_SIZES)[number];
export type AdvancedRenderingShadowType = (typeof ADVANCED_RENDERING_SHADOW_TYPES)[number];
export type AdvancedRenderingToneMappingMode = (typeof ADVANCED_RENDERING_TONE_MAPPING_MODES)[number];
export type BoxVolumeRenderPath = (typeof BOX_VOLUME_RENDER_PATHS)[number];
export type AdvancedRenderingWaterReflectionMode = (typeof ADVANCED_RENDERING_WATER_REFLECTION_MODES)[number];
export interface WorldSolidBackgroundSettings {
mode: "solid";
@@ -83,6 +87,9 @@ export interface AdvancedRenderingSettings {
bloom: AdvancedRenderingBloomSettings;
toneMapping: AdvancedRenderingToneMappingSettings;
depthOfField: AdvancedRenderingDepthOfFieldSettings;
fogPath: BoxVolumeRenderPath;
waterPath: BoxVolumeRenderPath;
waterReflectionMode: AdvancedRenderingWaterReflectionMode;
}
export interface WorldSettings {
@@ -109,6 +116,8 @@ const DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_EXPOSURE = 1;
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCUS_DISTANCE = 10;
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCAL_LENGTH = 0.03;
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_BOKEH_SCALE = 1.5;
const DEFAULT_BOX_VOLUME_RENDER_PATH: BoxVolumeRenderPath = "performance";
const DEFAULT_ADVANCED_RENDERING_WATER_REFLECTION_MODE: AdvancedRenderingWaterReflectionMode = "none";
export function isAdvancedRenderingShadowMapSize(value: unknown): value is AdvancedRenderingShadowMapSize {
return ADVANCED_RENDERING_SHADOW_MAP_SIZES.includes(value as AdvancedRenderingShadowMapSize);
@@ -122,6 +131,14 @@ export function isAdvancedRenderingToneMappingMode(value: unknown): value is Adv
return ADVANCED_RENDERING_TONE_MAPPING_MODES.includes(value as AdvancedRenderingToneMappingMode);
}
export function isBoxVolumeRenderPath(value: unknown): value is BoxVolumeRenderPath {
return BOX_VOLUME_RENDER_PATHS.includes(value as BoxVolumeRenderPath);
}
export function isAdvancedRenderingWaterReflectionMode(value: unknown): value is AdvancedRenderingWaterReflectionMode {
return ADVANCED_RENDERING_WATER_REFLECTION_MODES.includes(value as AdvancedRenderingWaterReflectionMode);
}
export function createDefaultAdvancedRenderingSettings(): AdvancedRenderingSettings {
return {
enabled: false,
@@ -152,7 +169,10 @@ export function createDefaultAdvancedRenderingSettings(): AdvancedRenderingSetti
focusDistance: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCUS_DISTANCE,
focalLength: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCAL_LENGTH,
bokehScale: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_BOKEH_SCALE
}
},
fogPath: DEFAULT_BOX_VOLUME_RENDER_PATH,
waterPath: DEFAULT_BOX_VOLUME_RENDER_PATH,
waterReflectionMode: DEFAULT_ADVANCED_RENDERING_WATER_REFLECTION_MODE
};
}
@@ -241,7 +261,10 @@ export function cloneAdvancedRenderingSettings(settings: AdvancedRenderingSettin
},
depthOfField: {
...settings.depthOfField
}
},
fogPath: settings.fogPath,
waterPath: settings.waterPath,
waterReflectionMode: settings.waterReflectionMode
};
}
@@ -295,7 +318,10 @@ export function areAdvancedRenderingSettingsEqual(left: AdvancedRenderingSetting
left.depthOfField.enabled === right.depthOfField.enabled &&
left.depthOfField.focusDistance === right.depthOfField.focusDistance &&
left.depthOfField.focalLength === right.depthOfField.focalLength &&
left.depthOfField.bokehScale === right.depthOfField.bokehScale
left.depthOfField.bokehScale === right.depthOfField.bokehScale &&
left.fogPath === right.fogPath &&
left.waterPath === right.waterPath &&
left.waterReflectionMode === right.waterReflectionMode
);
}

View File

@@ -0,0 +1,501 @@
import { createOpaqueId } from "../core/ids";
import { isHexColorString } from "../document/world-settings";
export const PLAYER_START_COLLIDER_MODES = ["capsule", "box", "none"];
export const ENTITY_KIND_ORDER = [
"pointLight",
"spotLight",
"playerStart",
"soundEmitter",
"triggerVolume",
"teleportTarget",
"interactable"
];
export const DEFAULT_POINT_LIGHT_POSITION = {
x: 0,
y: 0,
z: 0
};
export const DEFAULT_POINT_LIGHT_COLOR_HEX = "#ffffff";
export const DEFAULT_POINT_LIGHT_INTENSITY = 1.25;
export const DEFAULT_POINT_LIGHT_DISTANCE = 8;
export const DEFAULT_SPOT_LIGHT_POSITION = {
x: 0,
y: 0,
z: 0
};
export const DEFAULT_SPOT_LIGHT_DIRECTION = {
x: 0,
y: -1,
z: 0
};
export const DEFAULT_SPOT_LIGHT_COLOR_HEX = "#ffffff";
export const DEFAULT_SPOT_LIGHT_INTENSITY = 1.5;
export const DEFAULT_SPOT_LIGHT_DISTANCE = 12;
export const DEFAULT_SPOT_LIGHT_ANGLE_DEGREES = 35;
export const DEFAULT_ENTITY_POSITION = {
x: 0,
y: 0,
z: 0
};
export const DEFAULT_PLAYER_START_POSITION = DEFAULT_ENTITY_POSITION;
export const DEFAULT_PLAYER_START_YAW_DEGREES = 0;
export const DEFAULT_PLAYER_START_COLLIDER_MODE = "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 = {
x: 0.6,
y: 1.8,
z: 0.6
};
export const DEFAULT_SOUND_EMITTER_AUDIO_ASSET_ID = null;
export const DEFAULT_SOUND_EMITTER_VOLUME = 1;
export const DEFAULT_SOUND_EMITTER_GAIN = DEFAULT_SOUND_EMITTER_VOLUME;
export const DEFAULT_SOUND_EMITTER_REF_DISTANCE = 6;
export const DEFAULT_SOUND_EMITTER_RADIUS = DEFAULT_SOUND_EMITTER_REF_DISTANCE;
export const DEFAULT_SOUND_EMITTER_MAX_DISTANCE = 24;
export const DEFAULT_TRIGGER_VOLUME_SIZE = {
x: 2,
y: 2,
z: 2
};
export const DEFAULT_TELEPORT_TARGET_YAW_DEGREES = 0;
export const DEFAULT_INTERACTABLE_RADIUS = 1.5;
export const DEFAULT_INTERACTABLE_PROMPT = "Use";
function cloneVec3(vector) {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function areVec3Equal(left, right) {
return left.x === right.x && left.y === right.y && left.z === right.z;
}
function assertFiniteVec3(vector, label) {
if (!Number.isFinite(vector.x) || !Number.isFinite(vector.y) || !Number.isFinite(vector.z)) {
throw new Error(`${label} must be finite on every axis.`);
}
}
function assertPositiveFiniteNumber(value, label) {
if (!Number.isFinite(value) || value <= 0) {
throw new Error(`${label} must be a finite number greater than zero.`);
}
}
function assertPositiveFiniteVec3(vector, label) {
assertFiniteVec3(vector, label);
if (vector.x <= 0 || vector.y <= 0 || vector.z <= 0) {
throw new Error(`${label} must remain positive on every axis.`);
}
}
function assertNonNegativeFiniteNumber(value, label) {
if (!Number.isFinite(value) || value < 0) {
throw new Error(`${label} must be a finite number greater than or equal to zero.`);
}
}
function assertHexColorString(value, label) {
if (!isHexColorString(value)) {
throw new Error(`${label} must use #RRGGBB format.`);
}
}
function assertNonZeroVec3(vector, label) {
if (vector.x === 0 && vector.y === 0 && vector.z === 0) {
throw new Error(`${label} must not be the zero vector.`);
}
}
function assertBoolean(value, label) {
if (typeof value !== "boolean") {
throw new Error(`${label} must be a boolean.`);
}
}
export function isPlayerStartColliderMode(value) {
return PLAYER_START_COLLIDER_MODES.includes(value);
}
export function clonePlayerStartColliderSettings(settings) {
return {
mode: settings.mode,
eyeHeight: settings.eyeHeight,
capsuleRadius: settings.capsuleRadius,
capsuleHeight: settings.capsuleHeight,
boxSize: cloneVec3(settings.boxSize)
};
}
export function getPlayerStartColliderHeight(settings) {
switch (settings.mode) {
case "capsule":
return settings.capsuleHeight;
case "box":
return settings.boxSize.y;
case "none":
return null;
}
}
export function createPlayerStartColliderSettings(overrides = {}) {
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) {
if (audioAssetId === undefined || audioAssetId === null) {
return null;
}
const trimmedAudioAssetId = audioAssetId.trim();
if (trimmedAudioAssetId.length === 0) {
throw new Error("Sound Emitter audio asset id must be non-empty when authored.");
}
return trimmedAudioAssetId;
}
export function normalizeEntityName(name) {
if (name === undefined || name === null) {
return undefined;
}
const trimmedName = name.trim();
return trimmedName.length === 0 ? undefined : trimmedName;
}
export function normalizeYawDegrees(yawDegrees) {
const normalizedYaw = yawDegrees % 360;
return normalizedYaw < 0 ? normalizedYaw + 360 : normalizedYaw;
}
export function normalizeInteractablePrompt(prompt) {
const normalizedPrompt = prompt.trim();
if (normalizedPrompt.length === 0) {
throw new Error("Interactable prompt must be non-empty.");
}
return normalizedPrompt;
}
export function createPointLightEntity(overrides = {}) {
const position = cloneVec3(overrides.position ?? DEFAULT_POINT_LIGHT_POSITION);
const colorHex = overrides.colorHex ?? DEFAULT_POINT_LIGHT_COLOR_HEX;
const intensity = overrides.intensity ?? DEFAULT_POINT_LIGHT_INTENSITY;
const distance = overrides.distance ?? DEFAULT_POINT_LIGHT_DISTANCE;
assertFiniteVec3(position, "Point Light position");
assertHexColorString(colorHex, "Point Light color");
assertNonNegativeFiniteNumber(intensity, "Point Light intensity");
assertPositiveFiniteNumber(distance, "Point Light distance");
return {
id: overrides.id ?? createOpaqueId("entity-point-light"),
kind: "pointLight",
name: normalizeEntityName(overrides.name),
position,
colorHex,
intensity,
distance
};
}
export function createSpotLightEntity(overrides = {}) {
const position = cloneVec3(overrides.position ?? DEFAULT_SPOT_LIGHT_POSITION);
const direction = cloneVec3(overrides.direction ?? DEFAULT_SPOT_LIGHT_DIRECTION);
const colorHex = overrides.colorHex ?? DEFAULT_SPOT_LIGHT_COLOR_HEX;
const intensity = overrides.intensity ?? DEFAULT_SPOT_LIGHT_INTENSITY;
const distance = overrides.distance ?? DEFAULT_SPOT_LIGHT_DISTANCE;
const angleDegrees = overrides.angleDegrees ?? DEFAULT_SPOT_LIGHT_ANGLE_DEGREES;
assertFiniteVec3(position, "Spot Light position");
assertFiniteVec3(direction, "Spot Light direction");
assertNonZeroVec3(direction, "Spot Light direction");
assertHexColorString(colorHex, "Spot Light color");
assertNonNegativeFiniteNumber(intensity, "Spot Light intensity");
assertPositiveFiniteNumber(distance, "Spot Light distance");
if (!Number.isFinite(angleDegrees) || angleDegrees <= 0 || angleDegrees >= 180) {
throw new Error("Spot Light angle must be a finite degree value between 0 and 180.");
}
return {
id: overrides.id ?? createOpaqueId("entity-spot-light"),
kind: "spotLight",
name: normalizeEntityName(overrides.name),
position,
direction,
colorHex,
intensity,
distance,
angleDegrees
};
}
export function createPlayerStartEntity(overrides = {}) {
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");
if (!Number.isFinite(yawDegrees)) {
throw new Error("Player Start yaw must be a finite number.");
}
return {
id: overrides.id ?? createOpaqueId("entity-player-start"),
kind: "playerStart",
name: normalizeEntityName(overrides.name),
position,
yawDegrees: normalizeYawDegrees(yawDegrees),
collider
};
}
export function createSoundEmitterEntity(overrides = {}) {
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
const audioAssetId = normalizeSoundEmitterAudioAssetId(overrides.audioAssetId ?? DEFAULT_SOUND_EMITTER_AUDIO_ASSET_ID);
const volume = overrides.volume ?? DEFAULT_SOUND_EMITTER_VOLUME;
const refDistance = overrides.refDistance ?? DEFAULT_SOUND_EMITTER_REF_DISTANCE;
const maxDistance = overrides.maxDistance ?? DEFAULT_SOUND_EMITTER_MAX_DISTANCE;
const autoplay = overrides.autoplay ?? false;
const loop = overrides.loop ?? false;
assertFiniteVec3(position, "Sound Emitter position");
assertNonNegativeFiniteNumber(volume, "Sound Emitter volume");
assertPositiveFiniteNumber(refDistance, "Sound Emitter ref distance");
assertPositiveFiniteNumber(maxDistance, "Sound Emitter max distance");
if (maxDistance < refDistance) {
throw new Error("Sound Emitter max distance must be greater than or equal to ref distance.");
}
assertBoolean(autoplay, "Sound Emitter autoplay");
assertBoolean(loop, "Sound Emitter loop");
return {
id: overrides.id ?? createOpaqueId("entity-sound-emitter"),
kind: "soundEmitter",
name: normalizeEntityName(overrides.name),
position,
audioAssetId,
volume,
refDistance,
maxDistance,
autoplay,
loop
};
}
export function createTriggerVolumeEntity(overrides = {}) {
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
const size = cloneVec3(overrides.size ?? DEFAULT_TRIGGER_VOLUME_SIZE);
const triggerOnEnter = overrides.triggerOnEnter ?? true;
const triggerOnExit = overrides.triggerOnExit ?? false;
assertFiniteVec3(position, "Trigger Volume position");
assertPositiveFiniteVec3(size, "Trigger Volume size");
assertBoolean(triggerOnEnter, "Trigger Volume triggerOnEnter");
assertBoolean(triggerOnExit, "Trigger Volume triggerOnExit");
return {
id: overrides.id ?? createOpaqueId("entity-trigger-volume"),
kind: "triggerVolume",
name: normalizeEntityName(overrides.name),
position,
size,
triggerOnEnter,
triggerOnExit
};
}
export function createTeleportTargetEntity(overrides = {}) {
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
const yawDegrees = overrides.yawDegrees ?? DEFAULT_TELEPORT_TARGET_YAW_DEGREES;
assertFiniteVec3(position, "Teleport Target position");
if (!Number.isFinite(yawDegrees)) {
throw new Error("Teleport Target yaw must be a finite number.");
}
return {
id: overrides.id ?? createOpaqueId("entity-teleport-target"),
kind: "teleportTarget",
name: normalizeEntityName(overrides.name),
position,
yawDegrees: normalizeYawDegrees(yawDegrees)
};
}
export function createInteractableEntity(overrides = {}) {
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
const radius = overrides.radius ?? DEFAULT_INTERACTABLE_RADIUS;
const prompt = normalizeInteractablePrompt(overrides.prompt ?? DEFAULT_INTERACTABLE_PROMPT);
const enabled = overrides.enabled ?? true;
assertFiniteVec3(position, "Interactable position");
assertPositiveFiniteNumber(radius, "Interactable radius");
assertBoolean(enabled, "Interactable enabled");
return {
id: overrides.id ?? createOpaqueId("entity-interactable"),
kind: "interactable",
name: normalizeEntityName(overrides.name),
position,
radius,
prompt,
enabled
};
}
export const ENTITY_REGISTRY = {
pointLight: {
kind: "pointLight",
label: "Point Light",
description: "Authored local point light that illuminates nearby geometry in a spherical radius.",
createDefaultEntity: createPointLightEntity
},
spotLight: {
kind: "spotLight",
label: "Spot Light",
description: "Authored local spotlight with an explicit direction and cone angle.",
createDefaultEntity: createSpotLightEntity
},
playerStart: {
kind: "playerStart",
label: "Player Start",
description: "Primary authored spawn point for first-person runtime navigation.",
createDefaultEntity: createPlayerStartEntity
},
soundEmitter: {
kind: "soundEmitter",
label: "Sound Emitter",
description: "Authored positional audio source wired to an audio asset and configurable for looping, volume, and distance falloff.",
createDefaultEntity: createSoundEmitterEntity
},
triggerVolume: {
kind: "triggerVolume",
label: "Trigger Volume",
description: "Axis-aligned authored trigger volume for enter and exit events.",
createDefaultEntity: createTriggerVolumeEntity
},
teleportTarget: {
kind: "teleportTarget",
label: "Teleport Target",
description: "Explicit authored teleport destination with a facing direction.",
createDefaultEntity: createTeleportTargetEntity
},
interactable: {
kind: "interactable",
label: "Interactable",
description: "Explicit authored interaction point for later click and use behavior.",
createDefaultEntity: createInteractableEntity
}
};
export function isEntityKind(value) {
return typeof value === "string" && Object.prototype.hasOwnProperty.call(ENTITY_REGISTRY, value);
}
export function getEntityRegistryEntry(kind) {
return ENTITY_REGISTRY[kind];
}
export function createDefaultEntityInstance(kind, overrides = {}) {
switch (kind) {
case "pointLight":
return createPointLightEntity(overrides);
case "spotLight":
return createSpotLightEntity(overrides);
case "playerStart":
return createPlayerStartEntity(overrides);
case "soundEmitter":
return createSoundEmitterEntity(overrides);
case "triggerVolume":
return createTriggerVolumeEntity(overrides);
case "teleportTarget":
return createTeleportTargetEntity(overrides);
case "interactable":
return createInteractableEntity(overrides);
}
}
export function cloneEntityInstance(entity) {
switch (entity.kind) {
case "pointLight":
return createPointLightEntity(entity);
case "spotLight":
return createSpotLightEntity(entity);
case "playerStart":
return createPlayerStartEntity(entity);
case "soundEmitter":
return createSoundEmitterEntity(entity);
case "triggerVolume":
return createTriggerVolumeEntity(entity);
case "teleportTarget":
return createTeleportTargetEntity(entity);
case "interactable":
return createInteractableEntity(entity);
}
}
export function cloneEntityRegistry(entities) {
return Object.fromEntries(Object.entries(entities).map(([entityId, entity]) => [entityId, cloneEntityInstance(entity)]));
}
export function areEntityInstancesEqual(left, right) {
if (left.kind !== right.kind || left.id !== right.id || left.name !== right.name || !areVec3Equal(left.position, right.position)) {
return false;
}
switch (left.kind) {
case "pointLight": {
const typedRight = right;
return (left.colorHex === typedRight.colorHex &&
left.intensity === typedRight.intensity &&
left.distance === typedRight.distance);
}
case "spotLight": {
const typedRight = right;
return (areVec3Equal(left.direction, typedRight.direction) &&
left.colorHex === typedRight.colorHex &&
left.intensity === typedRight.intensity &&
left.distance === typedRight.distance &&
left.angleDegrees === typedRight.angleDegrees);
}
case "playerStart": {
const typedRight = right;
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;
return (left.audioAssetId === typedRight.audioAssetId &&
left.volume === typedRight.volume &&
left.refDistance === typedRight.refDistance &&
left.maxDistance === typedRight.maxDistance &&
left.autoplay === typedRight.autoplay &&
left.loop === typedRight.loop);
}
case "triggerVolume": {
const typedRight = right;
return (areVec3Equal(left.size, typedRight.size) &&
left.triggerOnEnter === typedRight.triggerOnEnter &&
left.triggerOnExit === typedRight.triggerOnExit);
}
case "teleportTarget": {
const typedRight = right;
return left.yawDegrees === typedRight.yawDegrees;
}
case "interactable": {
const typedRight = right;
return left.radius === typedRight.radius && left.prompt === typedRight.prompt && left.enabled === typedRight.enabled;
}
}
}
export function compareEntityInstances(left, right) {
const leftOrder = ENTITY_KIND_ORDER.indexOf(left.kind);
const rightOrder = ENTITY_KIND_ORDER.indexOf(right.kind);
if (leftOrder !== rightOrder) {
return leftOrder - rightOrder;
}
return left.id.localeCompare(right.id);
}
export function getEntityInstances(entities) {
return Object.values(entities).sort(compareEntityInstances);
}
export function getEntitiesOfKind(entities, kind) {
return getEntityInstances(entities).filter((entity) => entity.kind === kind);
}
export function getPlayerStartEntities(entities) {
return getEntitiesOfKind(entities, "playerStart");
}
export function getPrimaryPlayerStartEntity(entities) {
return getPlayerStartEntities(entities)[0] ?? null;
}
export function getEntityKindLabel(kind) {
return getEntityRegistryEntry(kind).label;
}

View File

@@ -27,11 +27,75 @@ export interface SpotLightEntity extends PositionedEntity {
export interface PlayerStartEntity extends PositionedEntity {
kind: "playerStart";
yawDegrees: number;
navigationMode: PlayerStartNavigationMode;
inputBindings: PlayerStartInputBindings;
collider: PlayerStartColliderSettings;
}
export interface SceneEntryEntity extends PositionedEntity {
kind: "sceneEntry";
yawDegrees: number;
}
export const PLAYER_START_COLLIDER_MODES = ["capsule", "box", "none"] as const;
export type PlayerStartColliderMode = (typeof PLAYER_START_COLLIDER_MODES)[number];
export const PLAYER_START_NAVIGATION_MODES = [
"firstPerson",
"thirdPerson"
] as const;
export type PlayerStartNavigationMode =
(typeof PLAYER_START_NAVIGATION_MODES)[number];
export const PLAYER_START_MOVEMENT_ACTIONS = [
"moveForward",
"moveBackward",
"moveLeft",
"moveRight"
] as const;
export type PlayerStartMovementAction =
(typeof PLAYER_START_MOVEMENT_ACTIONS)[number];
export type PlayerStartKeyboardBindingCode = string;
export const PLAYER_START_GAMEPAD_BINDINGS = [
"leftStickUp",
"leftStickDown",
"leftStickLeft",
"leftStickRight",
"dpadUp",
"dpadDown",
"dpadLeft",
"dpadRight"
] as const;
export type PlayerStartGamepadBinding =
(typeof PLAYER_START_GAMEPAD_BINDINGS)[number];
export const PLAYER_START_GAMEPAD_CAMERA_LOOK_BINDINGS = [
"rightStick"
] as const;
export type PlayerStartGamepadCameraLookBinding =
(typeof PLAYER_START_GAMEPAD_CAMERA_LOOK_BINDINGS)[number];
export interface PlayerStartKeyboardBindings {
moveForward: PlayerStartKeyboardBindingCode;
moveBackward: PlayerStartKeyboardBindingCode;
moveLeft: PlayerStartKeyboardBindingCode;
moveRight: PlayerStartKeyboardBindingCode;
}
export interface PlayerStartGamepadBindings {
moveForward: PlayerStartGamepadBinding;
moveBackward: PlayerStartGamepadBinding;
moveLeft: PlayerStartGamepadBinding;
moveRight: PlayerStartGamepadBinding;
cameraLook: PlayerStartGamepadCameraLookBinding;
}
export interface PlayerStartInputBindings {
keyboard: PlayerStartKeyboardBindings;
gamepad: PlayerStartGamepadBindings;
}
export interface PlayerStartInputBindingOverrides {
keyboard?: Partial<PlayerStartKeyboardBindings>;
gamepad?: Partial<PlayerStartGamepadBindings>;
}
export interface PlayerStartColliderSettings {
mode: PlayerStartColliderMode;
@@ -70,14 +134,25 @@ export interface InteractableEntity extends PositionedEntity {
enabled: boolean;
}
export interface SceneExitEntity extends PositionedEntity {
kind: "sceneExit";
radius: number;
prompt: string;
enabled: boolean;
targetSceneId: string;
targetEntryEntityId: string;
}
export type EntityInstance =
| PointLightEntity
| SpotLightEntity
| PlayerStartEntity
| SceneEntryEntity
| SoundEmitterEntity
| TriggerVolumeEntity
| TeleportTargetEntity
| InteractableEntity;
| InteractableEntity
| SceneExitEntity;
export type EntityKind = EntityInstance["kind"];
@@ -92,10 +167,12 @@ export const ENTITY_KIND_ORDER = [
"pointLight",
"spotLight",
"playerStart",
"sceneEntry",
"soundEmitter",
"triggerVolume",
"teleportTarget",
"interactable"
"interactable",
"sceneExit"
] as const;
export const DEFAULT_POINT_LIGHT_POSITION: Vec3 = {
x: 0,
@@ -128,6 +205,24 @@ 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_NAVIGATION_MODE: PlayerStartNavigationMode =
"firstPerson";
export const DEFAULT_PLAYER_START_KEYBOARD_BINDINGS: PlayerStartKeyboardBindings =
{
moveForward: "KeyW",
moveBackward: "KeyS",
moveLeft: "KeyA",
moveRight: "KeyD"
};
export const DEFAULT_PLAYER_START_GAMEPAD_BINDINGS: PlayerStartGamepadBindings =
{
moveForward: "leftStickUp",
moveBackward: "leftStickDown",
moveLeft: "leftStickLeft",
moveRight: "leftStickRight",
cameraLook: "rightStick"
};
export const DEFAULT_SCENE_ENTRY_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;
@@ -151,6 +246,8 @@ export const DEFAULT_TRIGGER_VOLUME_SIZE: Vec3 = {
export const DEFAULT_TELEPORT_TARGET_YAW_DEGREES = 0;
export const DEFAULT_INTERACTABLE_RADIUS = 1.5;
export const DEFAULT_INTERACTABLE_PROMPT = "Use";
export const DEFAULT_SCENE_EXIT_RADIUS = 1.5;
export const DEFAULT_SCENE_EXIT_PROMPT = "Enter";
function cloneVec3(vector: Vec3): Vec3 {
return {
@@ -212,6 +309,36 @@ export function isPlayerStartColliderMode(value: string): value is PlayerStartCo
return PLAYER_START_COLLIDER_MODES.includes(value as PlayerStartColliderMode);
}
export function isPlayerStartNavigationMode(
value: string
): value is PlayerStartNavigationMode {
return PLAYER_START_NAVIGATION_MODES.includes(
value as PlayerStartNavigationMode
);
}
export function isPlayerStartKeyboardBindingCode(
value: string
): value is PlayerStartKeyboardBindingCode {
return value.trim().length > 0;
}
export function isPlayerStartGamepadBinding(
value: string
): value is PlayerStartGamepadBinding {
return PLAYER_START_GAMEPAD_BINDINGS.includes(
value as PlayerStartGamepadBinding
);
}
export function isPlayerStartGamepadCameraLookBinding(
value: string
): value is PlayerStartGamepadCameraLookBinding {
return PLAYER_START_GAMEPAD_CAMERA_LOOK_BINDINGS.includes(
value as PlayerStartGamepadCameraLookBinding
);
}
export function clonePlayerStartColliderSettings(settings: PlayerStartColliderSettings): PlayerStartColliderSettings {
return {
mode: settings.mode,
@@ -222,6 +349,120 @@ export function clonePlayerStartColliderSettings(settings: PlayerStartColliderSe
};
}
export function clonePlayerStartInputBindings(
bindings: PlayerStartInputBindings
): PlayerStartInputBindings {
return {
keyboard: {
moveForward: bindings.keyboard.moveForward,
moveBackward: bindings.keyboard.moveBackward,
moveLeft: bindings.keyboard.moveLeft,
moveRight: bindings.keyboard.moveRight
},
gamepad: {
moveForward: bindings.gamepad.moveForward,
moveBackward: bindings.gamepad.moveBackward,
moveLeft: bindings.gamepad.moveLeft,
moveRight: bindings.gamepad.moveRight,
cameraLook: bindings.gamepad.cameraLook
}
};
}
export function createPlayerStartInputBindings(
overrides: PlayerStartInputBindingOverrides = {}
): PlayerStartInputBindings {
const keyboard: PlayerStartKeyboardBindings = {
moveForward:
overrides.keyboard?.moveForward ??
DEFAULT_PLAYER_START_KEYBOARD_BINDINGS.moveForward,
moveBackward:
overrides.keyboard?.moveBackward ??
DEFAULT_PLAYER_START_KEYBOARD_BINDINGS.moveBackward,
moveLeft:
overrides.keyboard?.moveLeft ??
DEFAULT_PLAYER_START_KEYBOARD_BINDINGS.moveLeft,
moveRight:
overrides.keyboard?.moveRight ??
DEFAULT_PLAYER_START_KEYBOARD_BINDINGS.moveRight
};
const gamepad: PlayerStartGamepadBindings = {
moveForward:
overrides.gamepad?.moveForward ??
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.moveForward,
moveBackward:
overrides.gamepad?.moveBackward ??
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.moveBackward,
moveLeft:
overrides.gamepad?.moveLeft ??
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.moveLeft,
moveRight:
overrides.gamepad?.moveRight ??
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.moveRight,
cameraLook:
overrides.gamepad?.cameraLook ??
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.cameraLook
};
if (!isPlayerStartKeyboardBindingCode(keyboard.moveForward)) {
throw new Error("Player Start move-forward keyboard binding must be supported.");
}
if (!isPlayerStartKeyboardBindingCode(keyboard.moveBackward)) {
throw new Error("Player Start move-backward keyboard binding must be supported.");
}
if (!isPlayerStartKeyboardBindingCode(keyboard.moveLeft)) {
throw new Error("Player Start move-left keyboard binding must be supported.");
}
if (!isPlayerStartKeyboardBindingCode(keyboard.moveRight)) {
throw new Error("Player Start move-right keyboard binding must be supported.");
}
if (!isPlayerStartGamepadBinding(gamepad.moveForward)) {
throw new Error("Player Start move-forward gamepad binding must be supported.");
}
if (!isPlayerStartGamepadBinding(gamepad.moveBackward)) {
throw new Error("Player Start move-backward gamepad binding must be supported.");
}
if (!isPlayerStartGamepadBinding(gamepad.moveLeft)) {
throw new Error("Player Start move-left gamepad binding must be supported.");
}
if (!isPlayerStartGamepadBinding(gamepad.moveRight)) {
throw new Error("Player Start move-right gamepad binding must be supported.");
}
if (!isPlayerStartGamepadCameraLookBinding(gamepad.cameraLook)) {
throw new Error("Player Start camera-look gamepad binding must be supported.");
}
return {
keyboard,
gamepad
};
}
export function arePlayerStartInputBindingsEqual(
left: PlayerStartInputBindings,
right: PlayerStartInputBindings
): boolean {
return (
left.keyboard.moveForward === right.keyboard.moveForward &&
left.keyboard.moveBackward === right.keyboard.moveBackward &&
left.keyboard.moveLeft === right.keyboard.moveLeft &&
left.keyboard.moveRight === right.keyboard.moveRight &&
left.gamepad.moveForward === right.gamepad.moveForward &&
left.gamepad.moveBackward === right.gamepad.moveBackward &&
left.gamepad.moveLeft === right.gamepad.moveLeft &&
left.gamepad.moveRight === right.gamepad.moveRight &&
left.gamepad.cameraLook === right.gamepad.cameraLook
);
}
export function getPlayerStartColliderHeight(settings: PlayerStartColliderSettings): number | null {
switch (settings.mode) {
case "capsule":
@@ -286,6 +527,23 @@ function normalizeSoundEmitterAudioAssetId(audioAssetId: string | null | undefin
return trimmedAudioAssetId;
}
function normalizeSceneReferenceId(
value: string | null | undefined,
label: string
): string {
if (value === undefined || value === null) {
throw new Error(`${label} must be authored.`);
}
const normalizedValue = value.trim();
if (normalizedValue.length === 0) {
throw new Error(`${label} must be non-empty.`);
}
return normalizedValue;
}
export function normalizeEntityName(name: string | null | undefined): string | undefined {
if (name === undefined || name === null) {
return undefined;
@@ -369,10 +627,21 @@ export function createSpotLightEntity(
}
export function createPlayerStartEntity(
overrides: Partial<Pick<PlayerStartEntity, "id" | "name" | "position" | "yawDegrees" | "collider">> = {}
overrides: Partial<
Pick<
PlayerStartEntity,
"id" | "name" | "position" | "yawDegrees" | "navigationMode"
>
> & {
inputBindings?: PlayerStartInputBindingOverrides;
collider?: Partial<PlayerStartColliderSettings>;
} = {}
): PlayerStartEntity {
const position = cloneVec3(overrides.position ?? DEFAULT_PLAYER_START_POSITION);
const yawDegrees = overrides.yawDegrees ?? DEFAULT_PLAYER_START_YAW_DEGREES;
const navigationMode =
overrides.navigationMode ?? DEFAULT_PLAYER_START_NAVIGATION_MODE;
const inputBindings = createPlayerStartInputBindings(overrides.inputBindings);
const collider = createPlayerStartColliderSettings(overrides.collider);
assertFiniteVec3(position, "Player Start position");
@@ -381,16 +650,45 @@ export function createPlayerStartEntity(
throw new Error("Player Start yaw must be a finite number.");
}
if (!isPlayerStartNavigationMode(navigationMode)) {
throw new Error(
"Player Start navigation mode must be firstPerson or thirdPerson."
);
}
return {
id: overrides.id ?? createOpaqueId("entity-player-start"),
kind: "playerStart",
name: normalizeEntityName(overrides.name),
position,
yawDegrees: normalizeYawDegrees(yawDegrees),
navigationMode,
inputBindings,
collider
};
}
export function createSceneEntryEntity(
overrides: Partial<Pick<SceneEntryEntity, "id" | "name" | "position" | "yawDegrees">> = {}
): SceneEntryEntity {
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
const yawDegrees = overrides.yawDegrees ?? DEFAULT_SCENE_ENTRY_YAW_DEGREES;
assertFiniteVec3(position, "Scene Entry position");
if (!Number.isFinite(yawDegrees)) {
throw new Error("Scene Entry yaw must be a finite number.");
}
return {
id: overrides.id ?? createOpaqueId("entity-scene-entry"),
kind: "sceneEntry",
name: normalizeEntityName(overrides.name),
position,
yawDegrees: normalizeYawDegrees(yawDegrees)
};
}
export function createSoundEmitterEntity(
overrides: Partial<
Pick<
@@ -501,6 +799,53 @@ export function createInteractableEntity(
};
}
export function createSceneExitEntity(
overrides: Partial<
Pick<
SceneExitEntity,
| "id"
| "name"
| "position"
| "radius"
| "prompt"
| "enabled"
| "targetSceneId"
| "targetEntryEntityId"
>
> = {}
): SceneExitEntity {
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
const radius = overrides.radius ?? DEFAULT_SCENE_EXIT_RADIUS;
const prompt = normalizeInteractablePrompt(
overrides.prompt ?? DEFAULT_SCENE_EXIT_PROMPT
);
const enabled = overrides.enabled ?? true;
const targetSceneId = normalizeSceneReferenceId(
overrides.targetSceneId,
"Scene Exit target scene id"
);
const targetEntryEntityId = normalizeSceneReferenceId(
overrides.targetEntryEntityId,
"Scene Exit target entry id"
);
assertFiniteVec3(position, "Scene Exit position");
assertPositiveFiniteNumber(radius, "Scene Exit radius");
assertBoolean(enabled, "Scene Exit enabled");
return {
id: overrides.id ?? createOpaqueId("entity-scene-exit"),
kind: "sceneExit",
name: normalizeEntityName(overrides.name),
position,
radius,
prompt,
enabled,
targetSceneId,
targetEntryEntityId
};
}
export const ENTITY_REGISTRY: { [K in EntityKind]: EntityRegistryEntry<Extract<EntityInstance, { kind: K }>> } = {
pointLight: {
kind: "pointLight",
@@ -517,9 +862,17 @@ export const ENTITY_REGISTRY: { [K in EntityKind]: EntityRegistryEntry<Extract<E
playerStart: {
kind: "playerStart",
label: "Player Start",
description: "Primary authored spawn point for first-person runtime navigation.",
description:
"Primary authored spawn point for first-person or third-person runtime navigation.",
createDefaultEntity: createPlayerStartEntity
},
sceneEntry: {
kind: "sceneEntry",
label: "Scene Entry",
description:
"Explicit authored scene-transition arrival point with a facing direction.",
createDefaultEntity: createSceneEntryEntity
},
soundEmitter: {
kind: "soundEmitter",
label: "Sound Emitter",
@@ -543,6 +896,13 @@ export const ENTITY_REGISTRY: { [K in EntityKind]: EntityRegistryEntry<Extract<E
label: "Interactable",
description: "Explicit authored interaction point for later click and use behavior.",
createDefaultEntity: createInteractableEntity
},
sceneExit: {
kind: "sceneExit",
label: "Scene Exit",
description:
"Explicit authored scene-transition exit that loads a target scene entry on demand.",
createDefaultEntity: createSceneExitEntity
}
};
@@ -555,12 +915,14 @@ export function getEntityRegistryEntry<K extends EntityKind>(kind: K): EntityReg
}
export function createDefaultEntityInstance(kind: "playerStart", overrides?: Partial<PlayerStartEntity>): PlayerStartEntity;
export function createDefaultEntityInstance(kind: "sceneEntry", overrides?: Partial<SceneEntryEntity>): SceneEntryEntity;
export function createDefaultEntityInstance(kind: "pointLight", overrides?: Partial<PointLightEntity>): PointLightEntity;
export function createDefaultEntityInstance(kind: "spotLight", overrides?: Partial<SpotLightEntity>): SpotLightEntity;
export function createDefaultEntityInstance(kind: "soundEmitter", overrides?: Partial<SoundEmitterEntity>): SoundEmitterEntity;
export function createDefaultEntityInstance(kind: "triggerVolume", overrides?: Partial<TriggerVolumeEntity>): TriggerVolumeEntity;
export function createDefaultEntityInstance(kind: "teleportTarget", overrides?: Partial<TeleportTargetEntity>): TeleportTargetEntity;
export function createDefaultEntityInstance(kind: "interactable", overrides?: Partial<InteractableEntity>): InteractableEntity;
export function createDefaultEntityInstance(kind: "sceneExit", overrides?: Partial<SceneExitEntity>): SceneExitEntity;
export function createDefaultEntityInstance(kind: EntityKind, overrides: Partial<EntityInstance> = {}): EntityInstance {
switch (kind) {
case "pointLight":
@@ -569,6 +931,8 @@ export function createDefaultEntityInstance(kind: EntityKind, overrides: Partial
return createSpotLightEntity(overrides);
case "playerStart":
return createPlayerStartEntity(overrides);
case "sceneEntry":
return createSceneEntryEntity(overrides);
case "soundEmitter":
return createSoundEmitterEntity(overrides);
case "triggerVolume":
@@ -577,6 +941,8 @@ export function createDefaultEntityInstance(kind: EntityKind, overrides: Partial
return createTeleportTargetEntity(overrides);
case "interactable":
return createInteractableEntity(overrides);
case "sceneExit":
return createSceneExitEntity(overrides);
}
}
@@ -588,6 +954,8 @@ export function cloneEntityInstance(entity: EntityInstance): EntityInstance {
return createSpotLightEntity(entity);
case "playerStart":
return createPlayerStartEntity(entity);
case "sceneEntry":
return createSceneEntryEntity(entity);
case "soundEmitter":
return createSoundEmitterEntity(entity);
case "triggerVolume":
@@ -596,6 +964,8 @@ export function cloneEntityInstance(entity: EntityInstance): EntityInstance {
return createTeleportTargetEntity(entity);
case "interactable":
return createInteractableEntity(entity);
case "sceneExit":
return createSceneExitEntity(entity);
}
}
@@ -631,6 +1001,11 @@ export function areEntityInstancesEqual(left: EntityInstance, right: EntityInsta
const typedRight = right as PlayerStartEntity;
return (
left.yawDegrees === typedRight.yawDegrees &&
left.navigationMode === typedRight.navigationMode &&
arePlayerStartInputBindingsEqual(
left.inputBindings,
typedRight.inputBindings
) &&
left.collider.mode === typedRight.collider.mode &&
left.collider.eyeHeight === typedRight.collider.eyeHeight &&
left.collider.capsuleRadius === typedRight.collider.capsuleRadius &&
@@ -638,6 +1013,10 @@ export function areEntityInstancesEqual(left: EntityInstance, right: EntityInsta
areVec3Equal(left.collider.boxSize, typedRight.collider.boxSize)
);
}
case "sceneEntry": {
const typedRight = right as SceneEntryEntity;
return left.yawDegrees === typedRight.yawDegrees;
}
case "soundEmitter": {
const typedRight = right as SoundEmitterEntity;
return (
@@ -665,6 +1044,16 @@ export function areEntityInstancesEqual(left: EntityInstance, right: EntityInsta
const typedRight = right as InteractableEntity;
return left.radius === typedRight.radius && left.prompt === typedRight.prompt && left.enabled === typedRight.enabled;
}
case "sceneExit": {
const typedRight = right as SceneExitEntity;
return (
left.radius === typedRight.radius &&
left.prompt === typedRight.prompt &&
left.enabled === typedRight.enabled &&
left.targetSceneId === typedRight.targetSceneId &&
left.targetEntryEntityId === typedRight.targetEntryEntityId
);
}
}
}

View File

@@ -0,0 +1,45 @@
import { compareEntityInstances, getEntityKindLabel, getEntityInstances } from "./entity-instances";
function getSortedEntitiesByKind(entities, kind) {
return Object.values(entities)
.filter((entity) => entity.kind === kind)
.sort(compareEntityInstances);
}
function getSoundEmitterLabelSuffix(entity, assets) {
if (entity.audioAssetId === null) {
return "No Audio Asset";
}
const asset = assets?.[entity.audioAssetId];
if (asset === undefined) {
return `Missing Audio Asset (${entity.audioAssetId})`;
}
if (asset.kind !== "audio") {
return `Invalid Audio Asset (${asset.sourceName})`;
}
return asset.sourceName;
}
export function getEntityDisplayLabel(entity, entities, assets) {
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);
const numberedLabel = entityIndex <= 0 ? baseLabel : `${baseLabel} ${entityIndex + 1}`;
if (entity.kind !== "soundEmitter" || assets === undefined) {
return numberedLabel;
}
return `${numberedLabel} · ${getSoundEmitterLabelSuffix(entity, assets)}`;
}
export function getEntityDisplayLabelById(entityId, entities, assets) {
const entity = entities[entityId];
if (entity === undefined) {
return "Entity";
}
return getEntityDisplayLabel(entity, entities, assets);
}
export function getSortedEntityDisplayLabels(entities, assets) {
return getEntityInstances(entities).map((entity) => ({
entity,
label: getEntityDisplayLabel(entity, entities, assets)
}));
}

View File

@@ -0,0 +1,168 @@
import { Euler, MathUtils, Quaternion, Vector3 } from "three";
import { BOX_FACE_IDS } from "../document/brushes";
import { getBoxBrushFaceVertexIds, getBoxBrushLocalVertexPosition } from "./box-brush-mesh";
const BOX_VERTEX_SIGNS = {
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_FACE_TRANSFORM_META = {
posX: { axis: "x", sign: 1 },
negX: { axis: "x", sign: -1 },
posY: { axis: "y", sign: 1 },
negY: { axis: "y", sign: -1 },
posZ: { axis: "z", sign: 1 },
negZ: { axis: "z", sign: -1 }
};
const BOX_EDGE_TRANSFORM_META = {
edgeX_negY_negZ: {
axis: "x",
signs: { x: null, y: -1, z: -1 }
},
edgeX_posY_negZ: {
axis: "x",
signs: { x: null, y: 1, z: -1 }
},
edgeX_negY_posZ: {
axis: "x",
signs: { x: null, y: -1, z: 1 }
},
edgeX_posY_posZ: {
axis: "x",
signs: { x: null, y: 1, z: 1 }
},
edgeY_negX_negZ: {
axis: "y",
signs: { x: -1, y: null, z: -1 }
},
edgeY_posX_negZ: {
axis: "y",
signs: { x: 1, y: null, z: -1 }
},
edgeY_negX_posZ: {
axis: "y",
signs: { x: -1, y: null, z: 1 }
},
edgeY_posX_posZ: {
axis: "y",
signs: { x: 1, y: null, z: 1 }
},
edgeZ_negX_negY: {
axis: "z",
signs: { x: -1, y: -1, z: null }
},
edgeZ_posX_negY: {
axis: "z",
signs: { x: 1, y: -1, z: null }
},
edgeZ_negX_posY: {
axis: "z",
signs: { x: -1, y: 1, z: null }
},
edgeZ_posX_posY: {
axis: "z",
signs: { x: 1, y: 1, z: null }
}
};
const BOX_EDGE_VERTEX_IDS = {
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" }
};
function createBrushRotationEuler(brush) {
return new Euler(MathUtils.degToRad(brush.rotationDegrees.x), MathUtils.degToRad(brush.rotationDegrees.y), MathUtils.degToRad(brush.rotationDegrees.z), "XYZ");
}
export function transformBoxBrushWorldVectorToLocal(brush, worldVector) {
const rotation = createBrushRotationEuler(brush);
const inverseRotation = new Quaternion().setFromEuler(rotation).invert();
const localVector = new Vector3(worldVector.x, worldVector.y, worldVector.z).applyQuaternion(inverseRotation);
return {
x: localVector.x,
y: localVector.y,
z: localVector.z
};
}
export function transformBoxBrushWorldPointToLocal(brush, worldPoint) {
const rotation = createBrushRotationEuler(brush);
const inverseRotation = new Quaternion().setFromEuler(rotation).invert();
const localPoint = new Vector3(worldPoint.x - brush.center.x, worldPoint.y - brush.center.y, worldPoint.z - brush.center.z).applyQuaternion(inverseRotation);
return {
x: localPoint.x,
y: localPoint.y,
z: localPoint.z
};
}
export function transformBoxBrushLocalPointToWorld(brush, localPoint) {
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 getBoxBrushFaceTransformMeta(faceId) {
return BOX_FACE_TRANSFORM_META[faceId];
}
export function getBoxBrushEdgeTransformMeta(edgeId) {
return BOX_EDGE_TRANSFORM_META[edgeId];
}
export function getBoxBrushVertexSigns(vertexId) {
return BOX_VERTEX_SIGNS[vertexId];
}
export function getBoxBrushFaceWorldCenter(brush, faceId) {
const faceVertexIds = getBoxBrushFaceVertexIds(faceId);
const localCenter = faceVertexIds.reduce((accumulator, vertexId) => {
const vertex = getBoxBrushLocalVertexPosition(brush, vertexId);
return {
x: accumulator.x + vertex.x * 0.25,
y: accumulator.y + vertex.y * 0.25,
z: accumulator.z + vertex.z * 0.25
};
}, { x: 0, y: 0, z: 0 });
return transformBoxBrushLocalPointToWorld(brush, localCenter);
}
export function getBoxBrushFaceAxis(faceId) {
return BOX_FACE_TRANSFORM_META[faceId].axis;
}
export function getBoxBrushEdgeAxis(edgeId) {
return BOX_EDGE_TRANSFORM_META[edgeId].axis;
}
export function getBoxBrushFaceIdsForAxis(axis) {
return BOX_FACE_IDS.filter((faceId) => BOX_FACE_TRANSFORM_META[faceId].axis === axis);
}
export function getBoxBrushVertexLocalPosition(brush, vertexId) {
return getBoxBrushLocalVertexPosition(brush, vertexId);
}
export function getBoxBrushVertexWorldPosition(brush, vertexId) {
return transformBoxBrushLocalPointToWorld(brush, getBoxBrushVertexLocalPosition(brush, vertexId));
}
export function getBoxBrushEdgeWorldSegment(brush, edgeId) {
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
}
};
}

View File

@@ -1,12 +1,14 @@
import { Euler, MathUtils, Vector3 } from "three";
import { Euler, MathUtils, Quaternion, Vector3 } from "three";
import type { Vec3 } from "../core/vector";
import {
BOX_FACE_IDS,
type BoxBrush,
type BoxEdgeId,
type BoxFaceId,
type BoxVertexId
} from "../document/brushes";
import { getBoxBrushHalfSize } from "./box-brush";
import { getBoxBrushFaceVertexIds, getBoxBrushLocalVertexPosition } from "./box-brush-mesh";
type Sign = -1 | 1;
@@ -16,6 +18,22 @@ interface BoxVertexSigns {
z: Sign;
}
type BoxAxis = "x" | "y" | "z";
interface BoxFaceTransformMeta {
axis: BoxAxis;
sign: Sign;
}
interface BoxEdgeTransformMeta {
axis: BoxAxis;
signs: {
x: Sign | null;
y: Sign | null;
z: Sign | null;
};
}
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 },
@@ -27,6 +45,66 @@ const BOX_VERTEX_SIGNS: Record<BoxVertexId, BoxVertexSigns> = {
posX_posY_posZ: { x: 1, y: 1, z: 1 }
};
const BOX_FACE_TRANSFORM_META: Record<BoxFaceId, BoxFaceTransformMeta> = {
posX: { axis: "x", sign: 1 },
negX: { axis: "x", sign: -1 },
posY: { axis: "y", sign: 1 },
negY: { axis: "y", sign: -1 },
posZ: { axis: "z", sign: 1 },
negZ: { axis: "z", sign: -1 }
};
const BOX_EDGE_TRANSFORM_META: Record<BoxEdgeId, BoxEdgeTransformMeta> = {
edgeX_negY_negZ: {
axis: "x",
signs: { x: null, y: -1, z: -1 }
},
edgeX_posY_negZ: {
axis: "x",
signs: { x: null, y: 1, z: -1 }
},
edgeX_negY_posZ: {
axis: "x",
signs: { x: null, y: -1, z: 1 }
},
edgeX_posY_posZ: {
axis: "x",
signs: { x: null, y: 1, z: 1 }
},
edgeY_negX_negZ: {
axis: "y",
signs: { x: -1, y: null, z: -1 }
},
edgeY_posX_negZ: {
axis: "y",
signs: { x: 1, y: null, z: -1 }
},
edgeY_negX_posZ: {
axis: "y",
signs: { x: -1, y: null, z: 1 }
},
edgeY_posX_posZ: {
axis: "y",
signs: { x: 1, y: null, z: 1 }
},
edgeZ_negX_negY: {
axis: "z",
signs: { x: -1, y: -1, z: null }
},
edgeZ_posX_negY: {
axis: "z",
signs: { x: 1, y: -1, z: null }
},
edgeZ_negX_posY: {
axis: "z",
signs: { x: -1, y: 1, z: null }
},
edgeZ_posX_posY: {
axis: "z",
signs: { x: 1, y: 1, z: null }
}
};
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" },
@@ -58,6 +136,32 @@ function createBrushRotationEuler(brush: BoxBrush): Euler {
);
}
export function transformBoxBrushWorldVectorToLocal(brush: BoxBrush, worldVector: Vec3): Vec3 {
const rotation = createBrushRotationEuler(brush);
const inverseRotation = new Quaternion().setFromEuler(rotation).invert();
const localVector = new Vector3(worldVector.x, worldVector.y, worldVector.z).applyQuaternion(inverseRotation);
return {
x: localVector.x,
y: localVector.y,
z: localVector.z
};
}
export function transformBoxBrushWorldPointToLocal(brush: BoxBrush, worldPoint: Vec3): Vec3 {
const rotation = createBrushRotationEuler(brush);
const inverseRotation = new Quaternion().setFromEuler(rotation).invert();
const localPoint = new Vector3(worldPoint.x - brush.center.x, worldPoint.y - brush.center.y, worldPoint.z - brush.center.z).applyQuaternion(
inverseRotation
);
return {
x: localPoint.x,
y: localPoint.y,
z: localPoint.z
};
}
export function transformBoxBrushLocalPointToWorld(brush: BoxBrush, localPoint: Vec3): Vec3 {
const rotation = createBrushRotationEuler(brush);
const rotatedOffset = new Vector3(localPoint.x, localPoint.y, localPoint.z).applyEuler(rotation);
@@ -69,15 +173,49 @@ export function transformBoxBrushLocalPointToWorld(brush: BoxBrush, localPoint:
};
}
export function getBoxBrushVertexLocalPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
const halfSize = getBoxBrushHalfSize(brush);
const signs = BOX_VERTEX_SIGNS[vertexId];
export function getBoxBrushFaceTransformMeta(faceId: BoxFaceId): BoxFaceTransformMeta {
return BOX_FACE_TRANSFORM_META[faceId];
}
return {
x: signs.x * halfSize.x,
y: signs.y * halfSize.y,
z: signs.z * halfSize.z
};
export function getBoxBrushEdgeTransformMeta(edgeId: BoxEdgeId): BoxEdgeTransformMeta {
return BOX_EDGE_TRANSFORM_META[edgeId];
}
export function getBoxBrushVertexSigns(vertexId: BoxVertexId): BoxVertexSigns {
return BOX_VERTEX_SIGNS[vertexId];
}
export function getBoxBrushFaceWorldCenter(brush: BoxBrush, faceId: BoxFaceId): Vec3 {
const faceVertexIds = getBoxBrushFaceVertexIds(faceId);
const localCenter = faceVertexIds.reduce(
(accumulator, vertexId) => {
const vertex = getBoxBrushLocalVertexPosition(brush, vertexId);
return {
x: accumulator.x + vertex.x * 0.25,
y: accumulator.y + vertex.y * 0.25,
z: accumulator.z + vertex.z * 0.25
};
},
{ x: 0, y: 0, z: 0 }
);
return transformBoxBrushLocalPointToWorld(brush, localCenter);
}
export function getBoxBrushFaceAxis(faceId: BoxFaceId): BoxAxis {
return BOX_FACE_TRANSFORM_META[faceId].axis;
}
export function getBoxBrushEdgeAxis(edgeId: BoxEdgeId): BoxAxis {
return BOX_EDGE_TRANSFORM_META[edgeId].axis;
}
export function getBoxBrushFaceIdsForAxis(axis: BoxAxis): BoxFaceId[] {
return BOX_FACE_IDS.filter((faceId) => BOX_FACE_TRANSFORM_META[faceId].axis === axis);
}
export function getBoxBrushVertexLocalPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
return getBoxBrushLocalVertexPosition(brush, vertexId);
}
export function getBoxBrushVertexWorldPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {

View File

@@ -0,0 +1,401 @@
import { BufferAttribute, BufferGeometry } from "three";
import { BOX_EDGE_IDS, BOX_FACE_IDS } from "../document/brushes";
import { transformProjectedFaceUv } from "./box-face-uvs";
const FACE_VERTEX_IDS = {
posX: ["posX_negY_posZ", "posX_negY_negZ", "posX_posY_negZ", "posX_posY_posZ"],
negX: ["negX_negY_negZ", "negX_negY_posZ", "negX_posY_posZ", "negX_posY_negZ"],
posY: ["negX_posY_posZ", "posX_posY_posZ", "posX_posY_negZ", "negX_posY_negZ"],
negY: ["negX_negY_negZ", "posX_negY_negZ", "posX_negY_posZ", "negX_negY_posZ"],
posZ: ["negX_negY_posZ", "posX_negY_posZ", "posX_posY_posZ", "negX_posY_posZ"],
negZ: ["posX_negY_negZ", "negX_negY_negZ", "negX_posY_negZ", "posX_posY_negZ"]
};
const EDGE_VERTEX_IDS = {
edgeX_negY_negZ: ["negX_negY_negZ", "posX_negY_negZ"],
edgeX_posY_negZ: ["negX_posY_negZ", "posX_posY_negZ"],
edgeX_negY_posZ: ["negX_negY_posZ", "posX_negY_posZ"],
edgeX_posY_posZ: ["negX_posY_posZ", "posX_posY_posZ"],
edgeY_negX_negZ: ["negX_negY_negZ", "negX_posY_negZ"],
edgeY_posX_negZ: ["posX_negY_negZ", "posX_posY_negZ"],
edgeY_negX_posZ: ["negX_negY_posZ", "negX_posY_posZ"],
edgeY_posX_posZ: ["posX_negY_posZ", "posX_posY_posZ"],
edgeZ_negX_negY: ["negX_negY_negZ", "negX_negY_posZ"],
edgeZ_posX_negY: ["posX_negY_negZ", "posX_negY_posZ"],
edgeZ_negX_posY: ["negX_posY_negZ", "negX_posY_posZ"],
edgeZ_posX_posY: ["posX_posY_negZ", "posX_posY_posZ"]
};
const WATER_TOP_FACE_RENDER_SEGMENTS = 12;
function cloneVec3(vector) {
return { x: vector.x, y: vector.y, z: vector.z };
}
function subtractVec3(left, right) {
return {
x: left.x - right.x,
y: left.y - right.y,
z: left.z - right.z
};
}
function crossVec3(left, right) {
return {
x: left.y * right.z - left.z * right.y,
y: left.z * right.x - left.x * right.z,
z: left.x * right.y - left.y * right.x
};
}
function dotVec3(left, right) {
return left.x * right.x + left.y * right.y + left.z * right.z;
}
function getVectorLength(vector) {
return Math.sqrt(dotVec3(vector, vector));
}
function normalizeVec3(vector) {
const length = getVectorLength(vector);
if (length <= 1e-8) {
return { x: 0, y: 0, z: 0 };
}
return {
x: vector.x / length,
y: vector.y / length,
z: vector.z / length
};
}
function computeNewellNormal(vertices) {
let normal = { x: 0, y: 0, z: 0 };
for (let index = 0; index < vertices.length; index += 1) {
const current = vertices[index];
const next = vertices[(index + 1) % vertices.length];
normal.x += (current.y - next.y) * (current.z + next.z);
normal.y += (current.z - next.z) * (current.x + next.x);
normal.z += (current.x - next.x) * (current.y + next.y);
}
return normalizeVec3(normal);
}
function chooseProjectionAxes(normal) {
const absoluteNormal = {
x: Math.abs(normal.x),
y: Math.abs(normal.y),
z: Math.abs(normal.z)
};
if (absoluteNormal.x >= absoluteNormal.y && absoluteNormal.x >= absoluteNormal.z) {
return ["y", "z"];
}
if (absoluteNormal.y >= absoluteNormal.z) {
return ["x", "z"];
}
return ["x", "y"];
}
function projectVerticesTo2d(vertices, normal) {
const [uAxis, vAxis] = chooseProjectionAxes(normal);
return vertices.map((vertex) => ({
x: vertex[uAxis],
y: vertex[vAxis]
}));
}
function computeSignedArea(points) {
let area = 0;
for (let index = 0; index < points.length; index += 1) {
const current = points[index];
const next = points[(index + 1) % points.length];
area += current.x * next.y - next.x * current.y;
}
return area * 0.5;
}
function isPointInTriangle(point, triangle, orientation) {
const [a, b, c] = triangle;
const edges = [
(b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x),
(c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x),
(a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)
];
return orientation > 0 ? edges.every((value) => value >= -1e-8) : edges.every((value) => value <= 1e-8);
}
function triangulateQuad(vertices) {
const normal = computeNewellNormal(vertices);
const projected = projectVerticesTo2d(vertices, normal);
const orientation = computeSignedArea(projected);
if (Math.abs(orientation) <= 1e-8) {
throw new Error("Face projection is degenerate.");
}
const remaining = [0, 1, 2, 3];
const triangles = [];
while (remaining.length > 3) {
let earFound = false;
for (let offset = 0; offset < remaining.length; offset += 1) {
const previousIndex = remaining[(offset + remaining.length - 1) % remaining.length];
const currentIndex = remaining[offset];
const nextIndex = remaining[(offset + 1) % remaining.length];
const previousPoint = projected[previousIndex];
const currentPoint = projected[currentIndex];
const nextPoint = projected[nextIndex];
const cross = (currentPoint.x - previousPoint.x) * (nextPoint.y - previousPoint.y) -
(currentPoint.y - previousPoint.y) * (nextPoint.x - previousPoint.x);
if ((orientation > 0 && cross <= 1e-8) || (orientation < 0 && cross >= -1e-8)) {
continue;
}
const candidateTriangle = [previousPoint, currentPoint, nextPoint];
const containsOtherPoint = remaining.some((candidateIndex) => {
if (candidateIndex === previousIndex || candidateIndex === currentIndex || candidateIndex === nextIndex) {
return false;
}
return isPointInTriangle(projected[candidateIndex], candidateTriangle, orientation);
});
if (containsOtherPoint) {
continue;
}
triangles.push([previousIndex, currentIndex, nextIndex]);
remaining.splice(offset, 1);
earFound = true;
break;
}
if (!earFound) {
throw new Error("Face triangulation could not find a stable ear.");
}
}
triangles.push([remaining[0], remaining[1], remaining[2]]);
return triangles;
}
function projectLocalVertexToFaceUv(vertexPosition, faceId, faceBounds) {
switch (faceId) {
case "posX":
return {
x: faceBounds.max.z - vertexPosition.z,
y: vertexPosition.y - faceBounds.min.y
};
case "negX":
return {
x: vertexPosition.z - faceBounds.min.z,
y: vertexPosition.y - faceBounds.min.y
};
case "posY":
return {
x: vertexPosition.x - faceBounds.min.x,
y: faceBounds.max.z - vertexPosition.z
};
case "negY":
return {
x: vertexPosition.x - faceBounds.min.x,
y: vertexPosition.z - faceBounds.min.z
};
case "posZ":
return {
x: vertexPosition.x - faceBounds.min.x,
y: vertexPosition.y - faceBounds.min.y
};
case "negZ":
return {
x: faceBounds.max.x - vertexPosition.x,
y: vertexPosition.y - faceBounds.min.y
};
}
}
function getFaceUvSize(faceId, faceBounds) {
switch (faceId) {
case "posX":
case "negX":
return {
x: faceBounds.max.z - faceBounds.min.z,
y: faceBounds.max.y - faceBounds.min.y
};
case "posY":
case "negY":
return {
x: faceBounds.max.x - faceBounds.min.x,
y: faceBounds.max.z - faceBounds.min.z
};
case "posZ":
case "negZ":
return {
x: faceBounds.max.x - faceBounds.min.x,
y: faceBounds.max.y - faceBounds.min.y
};
}
}
function computeFaceBounds(vertices) {
const firstVertex = vertices[0];
const min = { ...firstVertex };
const max = { ...firstVertex };
for (const vertex of vertices.slice(1)) {
min.x = Math.min(min.x, vertex.x);
min.y = Math.min(min.y, vertex.y);
min.z = Math.min(min.z, vertex.z);
max.x = Math.max(max.x, vertex.x);
max.y = Math.max(max.y, vertex.y);
max.z = Math.max(max.z, vertex.z);
}
return { min, max };
}
function lerpNumber(start, end, amount) {
return start + (end - start) * amount;
}
function lerpVec3(start, end, amount) {
return {
x: lerpNumber(start.x, end.x, amount),
y: lerpNumber(start.y, end.y, amount),
z: lerpNumber(start.z, end.z, amount)
};
}
function interpolateQuadSurfaceVertex(corners, u, v) {
const topEdge = lerpVec3(corners[0], corners[1], u);
const bottomEdge = lerpVec3(corners[3], corners[2], u);
return lerpVec3(topEdge, bottomEdge, v);
}
function pushRenderedFaceVertex(positions, normals, uvs, indices, vertex, normal, faceId, faceBounds, uvSize, uvState) {
const projectedUv = projectLocalVertexToFaceUv(vertex, faceId, faceBounds);
const transformedUv = transformProjectedFaceUv(projectedUv, uvSize, uvState);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(transformedUv.x, transformedUv.y);
indices.push(indices.length);
}
export function getBoxBrushFaceVertexIds(faceId) {
return FACE_VERTEX_IDS[faceId];
}
export function getBoxBrushEdgeVertexIds(edgeId) {
return EDGE_VERTEX_IDS[edgeId];
}
export function getBoxBrushLocalVertexPosition(brush, vertexId) {
return cloneVec3(brush.geometry.vertices[vertexId]);
}
export function buildBoxBrushDerivedMeshData(brush) {
const diagnostics = validateBoxBrushGeometry(brush);
if (diagnostics.length > 0) {
throw new Error(diagnostics[0].message);
}
const positions = [];
const normals = [];
const uvs = [];
const indices = [];
const colliderVertices = [];
const colliderIndices = [];
const faceSurfaces = [];
const groups = [];
const vertexIndexMap = new Map();
for (const vertexId of Object.keys(brush.geometry.vertices)) {
const vertex = brush.geometry.vertices[vertexId];
vertexIndexMap.set(vertexId, colliderVertices.length / 3);
colliderVertices.push(vertex.x, vertex.y, vertex.z);
}
for (const [materialIndex, faceId] of BOX_FACE_IDS.entries()) {
const faceVertexIds = FACE_VERTEX_IDS[faceId];
const faceVertices = faceVertexIds.map((vertexId) => getBoxBrushLocalVertexPosition(brush, vertexId));
const triangles = triangulateQuad(faceVertices);
const normal = computeNewellNormal(faceVertices);
const faceBounds = computeFaceBounds(faceVertices);
const uvSize = getFaceUvSize(faceId, faceBounds);
const uvState = brush.faces[faceId].uv;
const indexStart = indices.length;
faceSurfaces.push({
faceId,
vertexIds: faceVertexIds,
triangles,
normal
});
const useSubdividedWaterTopFace = brush.volume.mode === "water" && faceId === "posY" && brush.volume.water.surfaceDisplacementEnabled;
if (useSubdividedWaterTopFace) {
const faceCorners = faceVertices;
for (let row = 0; row < WATER_TOP_FACE_RENDER_SEGMENTS; row += 1) {
const v0 = row / WATER_TOP_FACE_RENDER_SEGMENTS;
const v1 = (row + 1) / WATER_TOP_FACE_RENDER_SEGMENTS;
for (let column = 0; column < WATER_TOP_FACE_RENDER_SEGMENTS; column += 1) {
const u0 = column / WATER_TOP_FACE_RENDER_SEGMENTS;
const u1 = (column + 1) / WATER_TOP_FACE_RENDER_SEGMENTS;
const quadVertices = [
interpolateQuadSurfaceVertex(faceCorners, u0, v0),
interpolateQuadSurfaceVertex(faceCorners, u1, v0),
interpolateQuadSurfaceVertex(faceCorners, u1, v1),
interpolateQuadSurfaceVertex(faceCorners, u0, v1)
];
for (const vertex of [quadVertices[0], quadVertices[1], quadVertices[2], quadVertices[0], quadVertices[2], quadVertices[3]]) {
pushRenderedFaceVertex(positions, normals, uvs, indices, vertex, normal, faceId, faceBounds, uvSize, uvState);
}
}
}
}
else {
for (const triangle of triangles) {
for (const vertexOffset of triangle) {
pushRenderedFaceVertex(positions, normals, uvs, indices, faceVertices[vertexOffset], normal, faceId, faceBounds, uvSize, uvState);
}
}
}
groups.push({
start: indexStart,
count: indices.length - indexStart,
materialIndex
});
for (const triangle of triangles) {
colliderIndices.push(vertexIndexMap.get(faceVertexIds[triangle[0]]) ?? 0, vertexIndexMap.get(faceVertexIds[triangle[1]]) ?? 0, vertexIndexMap.get(faceVertexIds[triangle[2]]) ?? 0);
}
}
const geometry = new BufferGeometry();
geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
geometry.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3));
geometry.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2));
geometry.setIndex(indices);
for (const group of groups) {
geometry.addGroup(group.start, group.count, group.materialIndex);
}
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
const firstVertex = brush.geometry.vertices.negX_negY_negZ;
const localBounds = {
min: cloneVec3(firstVertex),
max: cloneVec3(firstVertex)
};
for (const vertex of Object.values(brush.geometry.vertices)) {
localBounds.min.x = Math.min(localBounds.min.x, vertex.x);
localBounds.min.y = Math.min(localBounds.min.y, vertex.y);
localBounds.min.z = Math.min(localBounds.min.z, vertex.z);
localBounds.max.x = Math.max(localBounds.max.x, vertex.x);
localBounds.max.y = Math.max(localBounds.max.y, vertex.y);
localBounds.max.z = Math.max(localBounds.max.z, vertex.z);
}
return {
geometry,
faceSurfaces,
edgeSegments: BOX_EDGE_IDS.map((edgeId) => {
const [startId, endId] = EDGE_VERTEX_IDS[edgeId];
return {
edgeId,
start: getBoxBrushLocalVertexPosition(brush, startId),
end: getBoxBrushLocalVertexPosition(brush, endId)
};
}),
colliderVertices: new Float32Array(colliderVertices),
colliderIndices: new Uint32Array(colliderIndices),
localBounds
};
}
export function validateBoxBrushGeometry(brush) {
const diagnostics = [];
for (const [vertexId, vertex] of Object.entries(brush.geometry.vertices)) {
if (!Number.isFinite(vertex.x) || !Number.isFinite(vertex.y) || !Number.isFinite(vertex.z)) {
diagnostics.push({
code: "invalid-box-geometry-vertex",
message: `Whitebox vertex ${vertexId} must remain finite.`
});
}
}
for (const faceId of BOX_FACE_IDS) {
const faceVertices = FACE_VERTEX_IDS[faceId].map((vertexId) => brush.geometry.vertices[vertexId]);
const normal = computeNewellNormal(faceVertices);
if (getVectorLength(normal) <= 1e-8) {
diagnostics.push({
code: "degenerate-box-face",
message: `Whitebox face ${faceId} is degenerate and cannot be triangulated.`,
faceId
});
continue;
}
try {
triangulateQuad(faceVertices);
}
catch (error) {
diagnostics.push({
code: "invalid-box-face-triangulation",
message: error instanceof Error ? `Whitebox face ${faceId} could not be triangulated: ${error.message}` : `Whitebox face ${faceId} could not be triangulated.`,
faceId
});
}
}
return diagnostics;
}

View File

@@ -0,0 +1,524 @@
import { BufferAttribute, BufferGeometry } from "three";
import type { Vec2, Vec3 } from "../core/vector";
import {
BOX_EDGE_IDS,
BOX_FACE_IDS,
type BoxBrush,
type BoxEdgeId,
type BoxFaceId,
type BoxVertexId,
type FaceUvState
} from "../document/brushes";
import { transformProjectedFaceUv } from "./box-face-uvs";
const FACE_VERTEX_IDS: Record<BoxFaceId, readonly [BoxVertexId, BoxVertexId, BoxVertexId, BoxVertexId]> = {
posX: ["posX_negY_posZ", "posX_negY_negZ", "posX_posY_negZ", "posX_posY_posZ"],
negX: ["negX_negY_negZ", "negX_negY_posZ", "negX_posY_posZ", "negX_posY_negZ"],
posY: ["negX_posY_posZ", "posX_posY_posZ", "posX_posY_negZ", "negX_posY_negZ"],
negY: ["negX_negY_negZ", "posX_negY_negZ", "posX_negY_posZ", "negX_negY_posZ"],
posZ: ["negX_negY_posZ", "posX_negY_posZ", "posX_posY_posZ", "negX_posY_posZ"],
negZ: ["posX_negY_negZ", "negX_negY_negZ", "negX_posY_negZ", "posX_posY_negZ"]
};
const EDGE_VERTEX_IDS: Record<BoxEdgeId, readonly [BoxVertexId, BoxVertexId]> = {
edgeX_negY_negZ: ["negX_negY_negZ", "posX_negY_negZ"],
edgeX_posY_negZ: ["negX_posY_negZ", "posX_posY_negZ"],
edgeX_negY_posZ: ["negX_negY_posZ", "posX_negY_posZ"],
edgeX_posY_posZ: ["negX_posY_posZ", "posX_posY_posZ"],
edgeY_negX_negZ: ["negX_negY_negZ", "negX_posY_negZ"],
edgeY_posX_negZ: ["posX_negY_negZ", "posX_posY_negZ"],
edgeY_negX_posZ: ["negX_negY_posZ", "negX_posY_posZ"],
edgeY_posX_posZ: ["posX_negY_posZ", "posX_posY_posZ"],
edgeZ_negX_negY: ["negX_negY_negZ", "negX_negY_posZ"],
edgeZ_posX_negY: ["posX_negY_negZ", "posX_negY_posZ"],
edgeZ_negX_posY: ["negX_posY_negZ", "negX_posY_posZ"],
edgeZ_posX_posY: ["posX_posY_negZ", "posX_posY_posZ"]
};
const WATER_TOP_FACE_RENDER_SEGMENTS = 12;
export interface BoxBrushGeometryDiagnostic {
code: string;
message: string;
faceId?: BoxFaceId;
}
export interface DerivedBoxBrushFaceSurface {
faceId: BoxFaceId;
vertexIds: readonly [BoxVertexId, BoxVertexId, BoxVertexId, BoxVertexId];
triangles: Array<readonly [number, number, number]>;
normal: Vec3;
}
export interface DerivedBoxBrushMeshData {
geometry: BufferGeometry;
faceSurfaces: DerivedBoxBrushFaceSurface[];
edgeSegments: Array<{ edgeId: BoxEdgeId; start: Vec3; end: Vec3 }>;
colliderVertices: Float32Array;
colliderIndices: Uint32Array;
localBounds: { min: Vec3; max: Vec3 };
}
function cloneVec3(vector: Vec3): Vec3 {
return { x: vector.x, y: vector.y, z: vector.z };
}
function dotVec3(left: Vec3, right: Vec3): number {
return left.x * right.x + left.y * right.y + left.z * right.z;
}
function getVectorLength(vector: Vec3): number {
return Math.sqrt(dotVec3(vector, vector));
}
function normalizeVec3(vector: Vec3): Vec3 {
const length = getVectorLength(vector);
if (length <= 1e-8) {
return { x: 0, y: 0, z: 0 };
}
return {
x: vector.x / length,
y: vector.y / length,
z: vector.z / length
};
}
function computeNewellNormal(vertices: Vec3[]): Vec3 {
let normal = { x: 0, y: 0, z: 0 };
for (let index = 0; index < vertices.length; index += 1) {
const current = vertices[index];
const next = vertices[(index + 1) % vertices.length];
normal.x += (current.y - next.y) * (current.z + next.z);
normal.y += (current.z - next.z) * (current.x + next.x);
normal.z += (current.x - next.x) * (current.y + next.y);
}
return normalizeVec3(normal);
}
function chooseProjectionAxes(normal: Vec3): [keyof Vec3, keyof Vec3] {
const absoluteNormal = {
x: Math.abs(normal.x),
y: Math.abs(normal.y),
z: Math.abs(normal.z)
};
if (absoluteNormal.x >= absoluteNormal.y && absoluteNormal.x >= absoluteNormal.z) {
return ["y", "z"];
}
if (absoluteNormal.y >= absoluteNormal.z) {
return ["x", "z"];
}
return ["x", "y"];
}
function projectVerticesTo2d(vertices: Vec3[], normal: Vec3): Vec2[] {
const [uAxis, vAxis] = chooseProjectionAxes(normal);
return vertices.map((vertex) => ({
x: vertex[uAxis],
y: vertex[vAxis]
}));
}
function computeSignedArea(points: Vec2[]): number {
let area = 0;
for (let index = 0; index < points.length; index += 1) {
const current = points[index];
const next = points[(index + 1) % points.length];
area += current.x * next.y - next.x * current.y;
}
return area * 0.5;
}
function isPointInTriangle(point: Vec2, triangle: [Vec2, Vec2, Vec2], orientation: number): boolean {
const [a, b, c] = triangle;
const edges = [
(b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x),
(c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x),
(a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)
];
return orientation > 0 ? edges.every((value) => value >= -1e-8) : edges.every((value) => value <= 1e-8);
}
function triangulateQuad(vertices: Vec3[]): Array<readonly [number, number, number]> {
const normal = computeNewellNormal(vertices);
const projected = projectVerticesTo2d(vertices, normal);
const orientation = computeSignedArea(projected);
if (Math.abs(orientation) <= 1e-8) {
throw new Error("Face projection is degenerate.");
}
const remaining = [0, 1, 2, 3];
const triangles: Array<readonly [number, number, number]> = [];
while (remaining.length > 3) {
let earFound = false;
for (let offset = 0; offset < remaining.length; offset += 1) {
const previousIndex = remaining[(offset + remaining.length - 1) % remaining.length];
const currentIndex = remaining[offset];
const nextIndex = remaining[(offset + 1) % remaining.length];
const previousPoint = projected[previousIndex];
const currentPoint = projected[currentIndex];
const nextPoint = projected[nextIndex];
const cross =
(currentPoint.x - previousPoint.x) * (nextPoint.y - previousPoint.y) -
(currentPoint.y - previousPoint.y) * (nextPoint.x - previousPoint.x);
if ((orientation > 0 && cross <= 1e-8) || (orientation < 0 && cross >= -1e-8)) {
continue;
}
const candidateTriangle: [Vec2, Vec2, Vec2] = [previousPoint, currentPoint, nextPoint];
const containsOtherPoint = remaining.some((candidateIndex) => {
if (candidateIndex === previousIndex || candidateIndex === currentIndex || candidateIndex === nextIndex) {
return false;
}
return isPointInTriangle(projected[candidateIndex], candidateTriangle, orientation);
});
if (containsOtherPoint) {
continue;
}
triangles.push([previousIndex, currentIndex, nextIndex]);
remaining.splice(offset, 1);
earFound = true;
break;
}
if (!earFound) {
throw new Error("Face triangulation could not find a stable ear.");
}
}
triangles.push([remaining[0], remaining[1], remaining[2]]);
return triangles;
}
function projectLocalVertexToFaceUv(vertexPosition: Vec3, faceId: BoxFaceId, faceBounds: { min: Vec3; max: Vec3 }): Vec2 {
switch (faceId) {
case "posX":
return {
x: faceBounds.max.z - vertexPosition.z,
y: vertexPosition.y - faceBounds.min.y
};
case "negX":
return {
x: vertexPosition.z - faceBounds.min.z,
y: vertexPosition.y - faceBounds.min.y
};
case "posY":
return {
x: vertexPosition.x - faceBounds.min.x,
y: faceBounds.max.z - vertexPosition.z
};
case "negY":
return {
x: vertexPosition.x - faceBounds.min.x,
y: vertexPosition.z - faceBounds.min.z
};
case "posZ":
return {
x: vertexPosition.x - faceBounds.min.x,
y: vertexPosition.y - faceBounds.min.y
};
case "negZ":
return {
x: faceBounds.max.x - vertexPosition.x,
y: vertexPosition.y - faceBounds.min.y
};
}
}
function getFaceUvSize(faceId: BoxFaceId, faceBounds: { min: Vec3; max: Vec3 }): Vec2 {
switch (faceId) {
case "posX":
case "negX":
return {
x: faceBounds.max.z - faceBounds.min.z,
y: faceBounds.max.y - faceBounds.min.y
};
case "posY":
case "negY":
return {
x: faceBounds.max.x - faceBounds.min.x,
y: faceBounds.max.z - faceBounds.min.z
};
case "posZ":
case "negZ":
return {
x: faceBounds.max.x - faceBounds.min.x,
y: faceBounds.max.y - faceBounds.min.y
};
}
}
function computeFaceBounds(vertices: Vec3[]): { min: Vec3; max: Vec3 } {
const firstVertex = vertices[0];
const min = { ...firstVertex };
const max = { ...firstVertex };
for (const vertex of vertices.slice(1)) {
min.x = Math.min(min.x, vertex.x);
min.y = Math.min(min.y, vertex.y);
min.z = Math.min(min.z, vertex.z);
max.x = Math.max(max.x, vertex.x);
max.y = Math.max(max.y, vertex.y);
max.z = Math.max(max.z, vertex.z);
}
return { min, max };
}
function lerpNumber(start: number, end: number, amount: number) {
return start + (end - start) * amount;
}
function lerpVec3(start: Vec3, end: Vec3, amount: number): Vec3 {
return {
x: lerpNumber(start.x, end.x, amount),
y: lerpNumber(start.y, end.y, amount),
z: lerpNumber(start.z, end.z, amount)
};
}
function interpolateQuadSurfaceVertex(
corners: readonly [Vec3, Vec3, Vec3, Vec3],
u: number,
v: number
): Vec3 {
const topEdge = lerpVec3(corners[0], corners[1], u);
const bottomEdge = lerpVec3(corners[3], corners[2], u);
return lerpVec3(topEdge, bottomEdge, v);
}
function pushRenderedFaceVertex(
positions: number[],
normals: number[],
uvs: number[],
indices: number[],
vertex: Vec3,
normal: Vec3,
faceId: BoxFaceId,
faceBounds: { min: Vec3; max: Vec3 },
uvSize: Vec2,
uvState: FaceUvState
) {
const projectedUv = projectLocalVertexToFaceUv(vertex, faceId, faceBounds);
const transformedUv = transformProjectedFaceUv(projectedUv, uvSize, uvState);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(transformedUv.x, transformedUv.y);
indices.push(indices.length);
}
export function getBoxBrushFaceVertexIds(faceId: BoxFaceId): readonly [BoxVertexId, BoxVertexId, BoxVertexId, BoxVertexId] {
return FACE_VERTEX_IDS[faceId];
}
export function getBoxBrushEdgeVertexIds(edgeId: BoxEdgeId): readonly [BoxVertexId, BoxVertexId] {
return EDGE_VERTEX_IDS[edgeId];
}
export function getBoxBrushLocalVertexPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
return cloneVec3(brush.geometry.vertices[vertexId]);
}
export function buildBoxBrushDerivedMeshData(brush: BoxBrush): DerivedBoxBrushMeshData {
const diagnostics = validateBoxBrushGeometry(brush);
if (diagnostics.length > 0) {
throw new Error(diagnostics[0].message);
}
const positions: number[] = [];
const normals: number[] = [];
const uvs: number[] = [];
const indices: number[] = [];
const colliderVertices: number[] = [];
const colliderIndices: number[] = [];
const faceSurfaces: DerivedBoxBrushFaceSurface[] = [];
const groups: Array<{ start: number; count: number; materialIndex: number }> = [];
const vertexIndexMap = new Map<BoxVertexId, number>();
for (const vertexId of Object.keys(brush.geometry.vertices) as BoxVertexId[]) {
const vertex = brush.geometry.vertices[vertexId];
vertexIndexMap.set(vertexId, colliderVertices.length / 3);
colliderVertices.push(vertex.x, vertex.y, vertex.z);
}
for (const [materialIndex, faceId] of BOX_FACE_IDS.entries()) {
const faceVertexIds = FACE_VERTEX_IDS[faceId];
const faceVertices = faceVertexIds.map((vertexId) => getBoxBrushLocalVertexPosition(brush, vertexId));
const triangles = triangulateQuad(faceVertices);
const normal = computeNewellNormal(faceVertices);
const faceBounds = computeFaceBounds(faceVertices);
const uvSize = getFaceUvSize(faceId, faceBounds);
const uvState = brush.faces[faceId].uv as FaceUvState;
const indexStart = indices.length;
faceSurfaces.push({
faceId,
vertexIds: faceVertexIds,
triangles,
normal
});
const useSubdividedWaterTopFace =
brush.volume.mode === "water" &&
faceId === "posY" &&
brush.volume.water.surfaceDisplacementEnabled;
if (useSubdividedWaterTopFace) {
const faceCorners = faceVertices as [Vec3, Vec3, Vec3, Vec3];
for (let row = 0; row < WATER_TOP_FACE_RENDER_SEGMENTS; row += 1) {
const v0 = row / WATER_TOP_FACE_RENDER_SEGMENTS;
const v1 = (row + 1) / WATER_TOP_FACE_RENDER_SEGMENTS;
for (let column = 0; column < WATER_TOP_FACE_RENDER_SEGMENTS; column += 1) {
const u0 = column / WATER_TOP_FACE_RENDER_SEGMENTS;
const u1 = (column + 1) / WATER_TOP_FACE_RENDER_SEGMENTS;
const quadVertices: [Vec3, Vec3, Vec3, Vec3] = [
interpolateQuadSurfaceVertex(faceCorners, u0, v0),
interpolateQuadSurfaceVertex(faceCorners, u1, v0),
interpolateQuadSurfaceVertex(faceCorners, u1, v1),
interpolateQuadSurfaceVertex(faceCorners, u0, v1)
];
for (const vertex of [quadVertices[0], quadVertices[1], quadVertices[2], quadVertices[0], quadVertices[2], quadVertices[3]]) {
pushRenderedFaceVertex(positions, normals, uvs, indices, vertex, normal, faceId, faceBounds, uvSize, uvState);
}
}
}
} else {
for (const triangle of triangles) {
for (const vertexOffset of triangle) {
pushRenderedFaceVertex(
positions,
normals,
uvs,
indices,
faceVertices[vertexOffset],
normal,
faceId,
faceBounds,
uvSize,
uvState
);
}
}
}
groups.push({
start: indexStart,
count: indices.length - indexStart,
materialIndex
});
for (const triangle of triangles) {
colliderIndices.push(
vertexIndexMap.get(faceVertexIds[triangle[0]]) ?? 0,
vertexIndexMap.get(faceVertexIds[triangle[1]]) ?? 0,
vertexIndexMap.get(faceVertexIds[triangle[2]]) ?? 0
);
}
}
const geometry = new BufferGeometry();
geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
geometry.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3));
geometry.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2));
geometry.setIndex(indices);
for (const group of groups) {
geometry.addGroup(group.start, group.count, group.materialIndex);
}
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
const firstVertex = brush.geometry.vertices.negX_negY_negZ;
const localBounds = {
min: cloneVec3(firstVertex),
max: cloneVec3(firstVertex)
};
for (const vertex of Object.values(brush.geometry.vertices)) {
localBounds.min.x = Math.min(localBounds.min.x, vertex.x);
localBounds.min.y = Math.min(localBounds.min.y, vertex.y);
localBounds.min.z = Math.min(localBounds.min.z, vertex.z);
localBounds.max.x = Math.max(localBounds.max.x, vertex.x);
localBounds.max.y = Math.max(localBounds.max.y, vertex.y);
localBounds.max.z = Math.max(localBounds.max.z, vertex.z);
}
return {
geometry,
faceSurfaces,
edgeSegments: BOX_EDGE_IDS.map((edgeId) => {
const [startId, endId] = EDGE_VERTEX_IDS[edgeId];
return {
edgeId,
start: getBoxBrushLocalVertexPosition(brush, startId),
end: getBoxBrushLocalVertexPosition(brush, endId)
};
}),
colliderVertices: new Float32Array(colliderVertices),
colliderIndices: new Uint32Array(colliderIndices),
localBounds
};
}
export function validateBoxBrushGeometry(brush: BoxBrush): BoxBrushGeometryDiagnostic[] {
const diagnostics: BoxBrushGeometryDiagnostic[] = [];
for (const [vertexId, vertex] of Object.entries(brush.geometry.vertices) as Array<[BoxVertexId, Vec3]>) {
if (!Number.isFinite(vertex.x) || !Number.isFinite(vertex.y) || !Number.isFinite(vertex.z)) {
diagnostics.push({
code: "invalid-box-geometry-vertex",
message: `Whitebox vertex ${vertexId} must remain finite.`
});
}
}
for (const faceId of BOX_FACE_IDS) {
const faceVertices = FACE_VERTEX_IDS[faceId].map((vertexId) => brush.geometry.vertices[vertexId]);
const normal = computeNewellNormal(faceVertices);
if (getVectorLength(normal) <= 1e-8) {
diagnostics.push({
code: "degenerate-box-face",
message: `Whitebox face ${faceId} is degenerate and cannot be triangulated.`,
faceId
});
continue;
}
try {
triangulateQuad(faceVertices);
} catch (error) {
diagnostics.push({
code: "invalid-box-face-triangulation",
message: error instanceof Error ? `Whitebox face ${faceId} could not be triangulated: ${error.message}` : `Whitebox face ${faceId} could not be triangulated.`,
faceId
});
}
}
return diagnostics;
}

43
src/geometry/box-brush.js Normal file
View File

@@ -0,0 +1,43 @@
import { Euler, MathUtils, Vector3 } from "three";
import { BOX_VERTEX_IDS } from "../document/brushes";
import { getBoxBrushLocalVertexPosition } from "./box-brush-mesh";
export function getBoxBrushHalfSize(brush) {
return {
x: brush.size.x * 0.5,
y: brush.size.y * 0.5,
z: brush.size.z * 0.5
};
}
export function getBoxBrushBounds(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,
max
};
}
export function getBoxBrushCornerPositions(brush) {
const rotation = new Euler(MathUtils.degToRad(brush.rotationDegrees.x), MathUtils.degToRad(brush.rotationDegrees.y), MathUtils.degToRad(brush.rotationDegrees.z), "XYZ");
const offsets = BOX_VERTEX_IDS.map((vertexId) => {
const localVertex = getBoxBrushLocalVertexPosition(brush, vertexId);
return new Vector3(localVertex.x, localVertex.y, localVertex.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
};
});
}

View File

@@ -1,7 +1,8 @@
import { Euler, MathUtils, Vector3 } from "three";
import type { Vec3 } from "../core/vector";
import type { BoxBrush } from "../document/brushes";
import { BOX_VERTEX_IDS, type BoxBrush } from "../document/brushes";
import { getBoxBrushLocalVertexPosition } from "./box-brush-mesh";
export interface BoxBrushBounds {
min: Vec3;
@@ -38,23 +39,16 @@ export function getBoxBrushBounds(brush: BoxBrush): BoxBrushBounds {
}
export function getBoxBrushCornerPositions(brush: BoxBrush): Vec3[] {
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)
];
const offsets = BOX_VERTEX_IDS.map((vertexId) => {
const localVertex = getBoxBrushLocalVertexPosition(brush, vertexId);
return new Vector3(localVertex.x, localVertex.y, localVertex.z);
});
return offsets.map((offset) => {
const rotatedOffset = offset.clone().applyEuler(rotation);

View File

@@ -0,0 +1,133 @@
import { BoxGeometry } from "three";
import { BOX_FACE_IDS, createDefaultFaceUvState } from "../document/brushes";
import { getBoxBrushHalfSize } from "./box-brush";
export function getBoxBrushFaceSize(brush, faceId) {
switch (faceId) {
case "posX":
case "negX":
return {
x: brush.size.z,
y: brush.size.y
};
case "posY":
case "negY":
return {
x: brush.size.x,
y: brush.size.z
};
case "posZ":
case "negZ":
return {
x: brush.size.x,
y: brush.size.y
};
}
}
export function createFitToFaceBoxBrushFaceUvState(brush, faceId) {
const faceSize = getBoxBrushFaceSize(brush, faceId);
return {
...createDefaultFaceUvState(),
scale: {
x: 1 / faceSize.x,
y: 1 / faceSize.y
}
};
}
export function projectBoxFaceVertexToUv(vertexPosition, brush, faceId) {
const halfSize = getBoxBrushHalfSize(brush);
switch (faceId) {
case "posX":
return {
x: halfSize.z - vertexPosition.z,
y: vertexPosition.y + halfSize.y
};
case "negX":
return {
x: vertexPosition.z + halfSize.z,
y: vertexPosition.y + halfSize.y
};
case "posY":
return {
x: vertexPosition.x + halfSize.x,
y: halfSize.z - vertexPosition.z
};
case "negY":
return {
x: vertexPosition.x + halfSize.x,
y: vertexPosition.z + halfSize.z
};
case "posZ":
return {
x: vertexPosition.x + halfSize.x,
y: vertexPosition.y + halfSize.y
};
case "negZ":
return {
x: halfSize.x - vertexPosition.x,
y: vertexPosition.y + halfSize.y
};
}
}
export function transformProjectedFaceUv(baseUv, faceSize, uvState) {
let u = (baseUv.x - faceSize.x * 0.5) * uvState.scale.x;
let v = (baseUv.y - faceSize.y * 0.5) * uvState.scale.y;
if (uvState.flipU) {
u *= -1;
}
if (uvState.flipV) {
v *= -1;
}
switch (uvState.rotationQuarterTurns) {
case 1: {
const nextU = -v;
v = u;
u = nextU;
break;
}
case 2:
u *= -1;
v *= -1;
break;
case 3: {
const nextU = v;
v = -u;
u = nextU;
break;
}
}
return {
x: u + faceSize.x * 0.5 * uvState.scale.x + uvState.offset.x,
y: v + faceSize.y * 0.5 * uvState.scale.y + uvState.offset.y
};
}
export function applyBoxBrushFaceUvsToGeometry(geometry, brush) {
const positionAttribute = geometry.getAttribute("position");
const uvAttribute = geometry.getAttribute("uv");
const indexAttribute = geometry.getIndex();
if (indexAttribute === null) {
throw new Error("BoxGeometry is expected to be indexed for face UV projection.");
}
// BoxGeometry groups follow the same px, nx, py, ny, pz, nz order as the canonical face ids.
for (const [materialIndex, faceId] of BOX_FACE_IDS.entries()) {
const group = geometry.groups.find((candidate) => candidate.materialIndex === materialIndex);
if (group === undefined) {
continue;
}
const faceSize = getBoxBrushFaceSize(brush, faceId);
const vertexIndices = new Set();
for (let indexOffset = group.start; indexOffset < group.start + group.count; indexOffset += 1) {
vertexIndices.add(indexAttribute.getX(indexOffset));
}
for (const vertexIndex of vertexIndices) {
const localVertexPosition = {
x: positionAttribute.getX(vertexIndex),
y: positionAttribute.getY(vertexIndex),
z: positionAttribute.getZ(vertexIndex)
};
const projectedUv = projectBoxFaceVertexToUv(localVertexPosition, brush, faceId);
const transformedUv = transformProjectedFaceUv(projectedUv, faceSize, brush.faces[faceId].uv);
uvAttribute.setXY(vertexIndex, transformedUv.x, transformedUv.y);
}
}
uvAttribute.needsUpdate = true;
}

View File

@@ -2,9 +2,13 @@ import { BoxGeometry } from "three";
import type { Vec2, Vec3 } from "../core/vector";
import { BOX_FACE_IDS, createDefaultFaceUvState, type BoxBrush, type BoxFaceId, type FaceUvState } from "../document/brushes";
import { getBoxBrushHalfSize } from "./box-brush";
export function getBoxBrushFaceSize(brush: BoxBrush, faceId: BoxFaceId): Vec2 {
interface BoxBrushUvProjectionSource {
size: Vec3;
faces: Record<BoxFaceId, { uv: FaceUvState }>;
}
export function getBoxBrushFaceSize(brush: BoxBrushUvProjectionSource, faceId: BoxFaceId): Vec2 {
switch (faceId) {
case "posX":
case "negX":
@@ -39,8 +43,12 @@ export function createFitToFaceBoxBrushFaceUvState(brush: BoxBrush, faceId: BoxF
};
}
export function projectBoxFaceVertexToUv(vertexPosition: Vec3, brush: BoxBrush, faceId: BoxFaceId): Vec2 {
const halfSize = getBoxBrushHalfSize(brush);
export function projectBoxFaceVertexToUv(vertexPosition: Vec3, brush: BoxBrushUvProjectionSource, faceId: BoxFaceId): Vec2 {
const halfSize = {
x: brush.size.x * 0.5,
y: brush.size.y * 0.5,
z: brush.size.z * 0.5
};
switch (faceId) {
case "posX":
@@ -113,7 +121,7 @@ export function transformProjectedFaceUv(baseUv: Vec2, faceSize: Vec2, uvState:
};
}
export function applyBoxBrushFaceUvsToGeometry(geometry: BoxGeometry, brush: BoxBrush): void {
export function applyBoxBrushFaceUvsToGeometry(geometry: BoxGeometry, brush: BoxBrushUvProjectionSource): void {
const positionAttribute = geometry.getAttribute("position");
const uvAttribute = geometry.getAttribute("uv");
const indexAttribute = geometry.getIndex();

View File

@@ -0,0 +1,36 @@
export const DEFAULT_GRID_SIZE = 1;
function assertGridSize(gridSize) {
if (!Number.isFinite(gridSize) || gridSize <= 0) {
throw new Error("Grid size must be a positive finite number.");
}
return gridSize;
}
export function snapValueToGrid(value, gridSize = DEFAULT_GRID_SIZE) {
const step = assertGridSize(gridSize);
if (!Number.isFinite(value)) {
throw new Error("Grid-snapped values must be finite numbers.");
}
return Math.round(value / step) * step;
}
function snapPositiveSizeValue(value, gridSize) {
if (!Number.isFinite(value)) {
throw new Error("Box brush size values must be finite numbers.");
}
const snappedSize = Math.round(Math.abs(value) / gridSize) * gridSize;
return snappedSize > 0 ? snappedSize : gridSize;
}
export function snapVec3ToGrid(vector, gridSize = DEFAULT_GRID_SIZE) {
return {
x: snapValueToGrid(vector.x, gridSize),
y: snapValueToGrid(vector.y, gridSize),
z: snapValueToGrid(vector.z, gridSize)
};
}
export function snapPositiveSizeToGrid(size, gridSize = DEFAULT_GRID_SIZE) {
const step = assertGridSize(gridSize);
return {
x: snapPositiveSizeValue(size.x, step),
y: snapPositiveSizeValue(size.y, step),
z: snapPositiveSizeValue(size.z, step)
};
}

View File

@@ -0,0 +1,119 @@
import { BoxGeometry, BufferGeometry, Float32BufferAttribute, Group, Mesh, MeshBasicMaterial, Vector3 } from "three";
import { ConvexGeometry } from "three/examples/jsm/geometries/ConvexGeometry.js";
const DEBUG_COLLIDER_COLORS = {
simple: 0x87d2ff,
terrain: 0x7be7b4,
static: 0xffc66d,
dynamic: 0xff8b7a
};
function createWireframeMaterial(color) {
return new MeshBasicMaterial({
color,
wireframe: true,
transparent: true,
opacity: 0.85,
depthWrite: false,
toneMapped: false
});
}
function markDebugMesh(mesh) {
mesh.userData.shadowIgnored = true;
mesh.userData.nonPickable = true;
mesh.renderOrder = 3_500;
}
function createBoxColliderDebugMesh(collider) {
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) {
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) {
const vertices = [];
const indices = [];
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) {
const group = new Group();
for (const piece of collider.pieces) {
const points = [];
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) {
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) {
if (Array.isArray(material)) {
for (const item of material) {
item.dispose();
}
return;
}
material.dispose();
}
export function disposeModelColliderDebugGroup(group) {
group.traverse((object) => {
const maybeMesh = object;
if (maybeMesh.isMesh !== true) {
return;
}
maybeMesh.geometry.dispose();
disposeMaterial(maybeMesh.material);
});
}

View File

@@ -0,0 +1,419 @@
import { Euler, Group, MathUtils, Matrix4, Mesh, Quaternion, Vector3 } from "three";
const TERRAIN_GRID_EPSILON = 1e-4;
const DYNAMIC_TRIANGLE_TARGET = 48;
const DYNAMIC_SPLIT_DEPTH_LIMIT = 3;
export class ModelColliderGenerationError extends Error {
code;
constructor(code, message) {
super(message);
this.name = "ModelColliderGenerationError";
this.code = code;
}
}
function cloneVec3(vector) {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function vector3ToVec3(vector) {
return {
x: vector.x,
y: vector.y,
z: vector.z
};
}
function createBounds(min, max) {
return {
min: vector3ToVec3(min),
max: vector3ToVec3(max)
};
}
function createModelTransform(modelInstance) {
return {
position: cloneVec3(modelInstance.position),
rotationDegrees: cloneVec3(modelInstance.rotationDegrees),
scale: cloneVec3(modelInstance.scale)
};
}
function createModelTransformMatrix(modelInstance) {
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) {
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) {
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, modelMatrix) {
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)));
}
function readIndexedVertex(position, index, matrix) {
return new Vector3(position.getX(index), position.getY(index), position.getZ(index)).applyMatrix4(matrix);
}
function getMeshGeometry(object) {
const maybeMesh = object;
if (maybeMesh.isMesh !== true) {
return null;
}
return maybeMesh.geometry;
}
function collectMeshTriangleClusters(template) {
template.updateMatrixWorld(true);
const clusters = [];
template.traverse((object) => {
const geometry = getMeshGeometry(object);
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 = [];
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) {
return clusters.flatMap((cluster) => cluster.triangles);
}
function buildTriMeshBuffers(triangles) {
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) {
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) {
return computeBoundsFromPoints(triangles.flatMap((triangle) => [triangle.a, triangle.b, triangle.c]));
}
function splitTriangleCluster(triangles, depth) {
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, depth = 0) {
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) {
return (Math.round(value / TERRAIN_GRID_EPSILON) * TERRAIN_GRID_EPSILON).toFixed(4);
}
function dedupeTriangleClusterPoints(triangles) {
const pointLookup = new Map();
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, asset) {
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, asset, loadedAsset) {
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, asset, loadedAsset) {
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();
const xValues = new Map();
const zValues = new Map();
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, asset, loadedAsset) {
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 = [];
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, asset, loadedAsset) {
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);
}
}

View File

@@ -0,0 +1,189 @@
import { createOpaqueId } from "../core/ids";
export const INTERACTION_TRIGGER_KINDS = ["enter", "exit", "click"];
function assertNonEmptyString(value, label) {
if (value.trim().length === 0) {
throw new Error(`${label} must be non-empty.`);
}
}
function cloneAction(action) {
switch (action.type) {
case "teleportPlayer":
return {
type: "teleportPlayer",
targetEntityId: action.targetEntityId
};
case "toggleVisibility":
return {
type: "toggleVisibility",
targetBrushId: action.targetBrushId,
visible: action.visible
};
case "playAnimation":
return {
type: "playAnimation",
targetModelInstanceId: action.targetModelInstanceId,
clipName: action.clipName,
loop: action.loop
};
case "stopAnimation":
return {
type: "stopAnimation",
targetModelInstanceId: action.targetModelInstanceId
};
case "playSound":
return {
type: "playSound",
targetSoundEmitterId: action.targetSoundEmitterId
};
case "stopSound":
return {
type: "stopSound",
targetSoundEmitterId: action.targetSoundEmitterId
};
}
}
export function isInteractionTriggerKind(value) {
return value === "enter" || value === "exit" || value === "click";
}
export function createTeleportPlayerInteractionLink(options) {
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
assertNonEmptyString(options.targetEntityId, "Teleport target entity id");
return {
id: options.id ?? createOpaqueId("interaction-link"),
sourceEntityId: options.sourceEntityId,
trigger: options.trigger ?? "enter",
action: {
type: "teleportPlayer",
targetEntityId: options.targetEntityId
}
};
}
export function createToggleVisibilityInteractionLink(options) {
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
assertNonEmptyString(options.targetBrushId, "Visibility target brush id");
if (options.visible !== undefined && typeof options.visible !== "boolean") {
throw new Error("Visibility action visible must be a boolean when authored.");
}
return {
id: options.id ?? createOpaqueId("interaction-link"),
sourceEntityId: options.sourceEntityId,
trigger: options.trigger ?? "enter",
action: {
type: "toggleVisibility",
targetBrushId: options.targetBrushId,
visible: options.visible
}
};
}
export function createPlayAnimationInteractionLink(options) {
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
assertNonEmptyString(options.targetModelInstanceId, "Play animation target model instance id");
assertNonEmptyString(options.clipName, "Play animation clip name");
return {
id: options.id ?? createOpaqueId("interaction-link"),
sourceEntityId: options.sourceEntityId,
trigger: options.trigger ?? "enter",
action: {
type: "playAnimation",
targetModelInstanceId: options.targetModelInstanceId,
clipName: options.clipName,
loop: options.loop
}
};
}
export function createStopAnimationInteractionLink(options) {
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
assertNonEmptyString(options.targetModelInstanceId, "Stop animation target model instance id");
return {
id: options.id ?? createOpaqueId("interaction-link"),
sourceEntityId: options.sourceEntityId,
trigger: options.trigger ?? "enter",
action: {
type: "stopAnimation",
targetModelInstanceId: options.targetModelInstanceId
}
};
}
export function createPlaySoundInteractionLink(options) {
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
assertNonEmptyString(options.targetSoundEmitterId, "Play sound target sound emitter id");
return {
id: options.id ?? createOpaqueId("interaction-link"),
sourceEntityId: options.sourceEntityId,
trigger: options.trigger ?? "enter",
action: {
type: "playSound",
targetSoundEmitterId: options.targetSoundEmitterId
}
};
}
export function createStopSoundInteractionLink(options) {
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
assertNonEmptyString(options.targetSoundEmitterId, "Stop sound target sound emitter id");
return {
id: options.id ?? createOpaqueId("interaction-link"),
sourceEntityId: options.sourceEntityId,
trigger: options.trigger ?? "enter",
action: {
type: "stopSound",
targetSoundEmitterId: options.targetSoundEmitterId
}
};
}
export function cloneInteractionLink(link) {
return {
id: link.id,
sourceEntityId: link.sourceEntityId,
trigger: link.trigger,
action: cloneAction(link.action)
};
}
export function areInteractionLinksEqual(left, right) {
if (left.id !== right.id || left.sourceEntityId !== right.sourceEntityId || left.trigger !== right.trigger) {
return false;
}
if (left.action.type !== right.action.type) {
return false;
}
switch (left.action.type) {
case "teleportPlayer":
return left.action.targetEntityId === right.action.targetEntityId;
case "toggleVisibility":
return (left.action.targetBrushId === right.action.targetBrushId &&
left.action.visible === right.action.visible);
case "playAnimation":
return (left.action.targetModelInstanceId === right.action.targetModelInstanceId &&
left.action.clipName === right.action.clipName &&
left.action.loop === right.action.loop);
case "stopAnimation":
return left.action.targetModelInstanceId === right.action.targetModelInstanceId;
case "playSound":
return left.action.targetSoundEmitterId === right.action.targetSoundEmitterId;
case "stopSound":
return left.action.targetSoundEmitterId === right.action.targetSoundEmitterId;
default: {
// Exhaustive check — TypeScript should never reach here
const _exhaustive = left.action;
void _exhaustive;
return false;
}
}
}
export function cloneInteractionLinkRegistry(links) {
return Object.fromEntries(Object.entries(links).map(([linkId, link]) => [linkId, cloneInteractionLink(link)]));
}
export function compareInteractionLinks(left, right) {
if (left.sourceEntityId !== right.sourceEntityId) {
return left.sourceEntityId.localeCompare(right.sourceEntityId);
}
if (left.trigger !== right.trigger) {
return left.trigger.localeCompare(right.trigger);
}
return left.id.localeCompare(right.id);
}
export function getInteractionLinks(links) {
return Object.values(links).sort(compareInteractionLinks);
}
export function getInteractionLinksForSource(links, sourceEntityId) {
return getInteractionLinks(links).filter((link) => link.sourceEntityId === sourceEntityId);
}

23
src/main.js Normal file
View File

@@ -0,0 +1,23 @@
import { jsx as _jsx } from "react/jsx-runtime";
import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./app/App";
import "./app/app.css";
import { createEditorStore } from "./app/editor-store";
import { getBrowserStorageAccess, loadOrCreateSceneDocument } from "./serialization/local-draft-storage";
const rootElement = document.getElementById("root");
if (rootElement === null) {
throw new Error("Expected #root element to bootstrap the editor.");
}
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.__webeditor3dEditorStore = editorStore;
}
ReactDOM.createRoot(rootElement).render(_jsx(React.StrictMode, { children: _jsx(App, { store: editorStore, initialStatusMessage: initialStatusMessage }) }));

View File

@@ -15,7 +15,7 @@ if (rootElement === null) {
const storageAccess = getBrowserStorageAccess();
const bootstrapResult = loadOrCreateSceneDocument(storageAccess.storage);
const editorStore = createEditorStore({
initialDocument: bootstrapResult.document,
initialProjectDocument: bootstrapResult.document,
initialViewportLayoutState: bootstrapResult.viewportLayoutState ?? undefined,
storage: storageAccess.storage
});

View File

@@ -0,0 +1,46 @@
export const STARTER_MATERIAL_LIBRARY = [
{
id: "starter-amber-grid",
name: "Amber Grid",
baseColorHex: "#c79a63",
accentColorHex: "#5f3820",
pattern: "grid",
tags: ["starter", "wall"]
},
{
id: "starter-concrete-checker",
name: "Concrete Checker",
baseColorHex: "#7d838c",
accentColorHex: "#5a616a",
pattern: "checker",
tags: ["starter", "floor"]
},
{
id: "starter-hazard-stripe",
name: "Hazard Stripe",
baseColorHex: "#d1a245",
accentColorHex: "#211b16",
pattern: "stripes",
tags: ["starter", "warning"]
},
{
id: "starter-night-diamond",
name: "Night Diamond",
baseColorHex: "#5a6985",
accentColorHex: "#1f2836",
pattern: "diamond",
tags: ["starter", "trim"]
}
];
export function cloneMaterialDef(material) {
return {
...material,
tags: [...material.tags]
};
}
export function cloneMaterialRegistry(materials) {
return Object.fromEntries(Object.entries(materials).map(([materialId, material]) => [materialId, cloneMaterialDef(material)]));
}
export function createStarterMaterialRegistry() {
return Object.fromEntries(STARTER_MATERIAL_LIBRARY.map((material) => [material.id, cloneMaterialDef(material)]));
}

View File

@@ -0,0 +1,73 @@
import { CanvasTexture, RepeatWrapping, SRGBColorSpace } from "three";
export function createStarterMaterialSignature(material) {
return `${material.baseColorHex}|${material.accentColorHex}|${material.pattern}`;
}
function fillMaterialPattern(context, material, size) {
context.fillStyle = material.baseColorHex;
context.fillRect(0, 0, size, size);
context.strokeStyle = material.accentColorHex;
context.fillStyle = material.accentColorHex;
switch (material.pattern) {
case "grid":
context.lineWidth = Math.max(2, size / 32);
for (let offset = 0; offset <= size; offset += size / 4) {
context.beginPath();
context.moveTo(offset, 0);
context.lineTo(offset, size);
context.stroke();
context.beginPath();
context.moveTo(0, offset);
context.lineTo(size, offset);
context.stroke();
}
break;
case "checker": {
const checkerSize = size / 4;
for (let row = 0; row < 4; row += 1) {
for (let column = 0; column < 4; column += 1) {
if ((row + column) % 2 === 0) {
context.fillRect(column * checkerSize, row * checkerSize, checkerSize, checkerSize);
}
}
}
break;
}
case "stripes":
context.lineWidth = size / 6;
for (let offset = -size; offset <= size * 2; offset += size / 3) {
context.beginPath();
context.moveTo(offset, size);
context.lineTo(offset + size, 0);
context.stroke();
}
break;
case "diamond":
context.lineWidth = Math.max(2, size / 28);
for (let offset = -size; offset <= size; offset += size / 3) {
context.beginPath();
context.moveTo(size * 0.5, offset);
context.lineTo(size - offset, size * 0.5);
context.lineTo(size * 0.5, size - offset);
context.lineTo(-offset, size * 0.5);
context.closePath();
context.stroke();
}
break;
}
}
export function createStarterMaterialTexture(material, size = 128) {
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const context = canvas.getContext("2d");
if (context === null) {
throw new Error("2D canvas context is unavailable for starter material texture generation.");
}
fillMaterialPattern(context, material, size);
const texture = new CanvasTexture(canvas);
texture.wrapS = RepeatWrapping;
texture.wrapT = RepeatWrapping;
texture.colorSpace = SRGBColorSpace;
texture.needsUpdate = true;
return texture;
}

View File

@@ -0,0 +1,136 @@
import { BasicShadowMap, DirectionalLight, HalfFloatType, Mesh, NoToneMapping, PCFShadowMap, PCFSoftShadowMap, PointLight, SpotLight, UnsignedByteType } from "three";
import { BloomEffect, DepthOfFieldEffect, EffectComposer, EffectPass, NormalPass, RenderPass, SMAAEffect, SMAAPreset, SSAOEffect, ToneMappingEffect, ToneMappingMode } from "postprocessing";
const AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE = 0.15;
const MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS = 0.02;
const MAX_AMBIENT_OCCLUSION_EFFECT_RADIUS = 0.2;
const MIN_AMBIENT_OCCLUSION_SAMPLES = 12;
const COARSE_AMBIENT_OCCLUSION_RESOLUTION_SCALE = 0.5;
const DETAIL_AMBIENT_OCCLUSION_RESOLUTION_SCALE = 0.75;
const DETAIL_AMBIENT_OCCLUSION_RADIUS_SCALE = 0.35;
const COARSE_AMBIENT_OCCLUSION_INTENSITY_SCALE = 0.45;
const DETAIL_AMBIENT_OCCLUSION_INTENSITY_SCALE = 0.35;
export function resolveBoxVolumeRenderPaths(settings) {
if (!settings.enabled) {
return {
fog: "performance",
water: "performance"
};
}
return {
fog: settings.fogPath,
water: settings.waterPath
};
}
export function getAdvancedRenderingShadowMapType(shadowType) {
switch (shadowType) {
case "basic":
return BasicShadowMap;
case "pcf":
return PCFShadowMap;
case "pcfSoft":
return PCFSoftShadowMap;
}
}
export function getAdvancedRenderingToneMappingMode(mode) {
switch (mode) {
case "none":
return ToneMappingMode.LINEAR;
case "linear":
return ToneMappingMode.LINEAR;
case "reinhard":
return ToneMappingMode.REINHARD;
case "cineon":
return ToneMappingMode.CINEON;
case "acesFilmic":
return ToneMappingMode.ACES_FILMIC;
}
}
export function configureAdvancedRenderingRenderer(renderer, settings) {
renderer.shadowMap.enabled = settings.enabled && settings.shadows.enabled;
renderer.shadowMap.type = getAdvancedRenderingShadowMapType(settings.shadows.type);
renderer.toneMapping = NoToneMapping;
renderer.toneMappingExposure = settings.toneMapping.exposure;
}
function clampAmbientOcclusionEffectRadius(radius) {
return Math.min(Math.max(radius, MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS), MAX_AMBIENT_OCCLUSION_EFFECT_RADIUS);
}
function getAmbientOcclusionSampleCount(samples) {
return Math.max(samples, MIN_AMBIENT_OCCLUSION_SAMPLES);
}
export function createAdvancedRenderingComposer(renderer, scene, camera, settings) {
// The scene is always rendered into the composer's offscreen targets first,
// so those targets need depth for correct visibility even when no effect samples it.
const composer = new EffectComposer(renderer, {
depthBuffer: true,
stencilBuffer: false,
multisampling: 0,
frameBufferType: renderer.capabilities.isWebGL2 ? HalfFloatType : UnsignedByteType
});
composer.addPass(new RenderPass(scene, camera));
const effects = [];
if (settings.ambientOcclusion.enabled) {
// postprocessing's internal depth-downsampling path writes zero normals unless
// a real normal buffer is supplied, which turns SSAO into speckled noise.
const normalPass = new NormalPass(scene, camera);
composer.addPass(normalPass);
const ambientOcclusionRadius = clampAmbientOcclusionEffectRadius(settings.ambientOcclusion.radius);
const ambientOcclusionSamples = getAmbientOcclusionSampleCount(settings.ambientOcclusion.samples);
const detailAmbientOcclusionRadius = Math.max(ambientOcclusionRadius * DETAIL_AMBIENT_OCCLUSION_RADIUS_SCALE, MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS);
composer.addPass(new EffectPass(camera, new SSAOEffect(camera, normalPass.texture, {
depthAwareUpsampling: true,
luminanceInfluence: AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE,
resolutionScale: COARSE_AMBIENT_OCCLUSION_RESOLUTION_SCALE,
samples: ambientOcclusionSamples,
radius: ambientOcclusionRadius,
intensity: settings.ambientOcclusion.intensity * COARSE_AMBIENT_OCCLUSION_INTENSITY_SCALE
}), new SSAOEffect(camera, normalPass.texture, {
depthAwareUpsampling: true,
luminanceInfluence: AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE,
resolutionScale: DETAIL_AMBIENT_OCCLUSION_RESOLUTION_SCALE,
samples: ambientOcclusionSamples,
radius: detailAmbientOcclusionRadius,
intensity: settings.ambientOcclusion.intensity * DETAIL_AMBIENT_OCCLUSION_INTENSITY_SCALE
})));
}
if (settings.bloom.enabled) {
effects.push(new BloomEffect({
intensity: settings.bloom.intensity,
luminanceThreshold: settings.bloom.threshold,
radius: settings.bloom.radius
}));
}
if (settings.depthOfField.enabled) {
effects.push(new DepthOfFieldEffect(camera, {
focusDistance: settings.depthOfField.focusDistance,
focalLength: settings.depthOfField.focalLength,
bokehScale: settings.depthOfField.bokehScale
}));
}
effects.push(new ToneMappingEffect({
mode: getAdvancedRenderingToneMappingMode(settings.toneMapping.mode)
}));
effects.push(new SMAAEffect({
preset: SMAAPreset.MEDIUM
}));
composer.addPass(new EffectPass(camera, ...effects));
return composer;
}
export function applyAdvancedRenderingRenderableShadowFlags(root, enabled) {
root.traverse((object) => {
if (object.isMesh === true && object.userData.shadowIgnored !== true) {
const mesh = object;
mesh.castShadow = enabled;
mesh.receiveShadow = enabled;
}
});
}
export function applyAdvancedRenderingLightShadowFlags(root, settings) {
const shadowEnabled = settings.enabled && settings.shadows.enabled;
root.traverse((object) => {
if (object instanceof DirectionalLight || object instanceof PointLight || object instanceof SpotLight) {
object.castShadow = shadowEnabled;
object.shadow.bias = settings.shadows.bias;
object.shadow.mapSize.set(settings.shadows.mapSize, settings.shadows.mapSize);
}
});
}

View File

@@ -20,6 +20,7 @@ import {
DepthOfFieldEffect,
EffectComposer,
EffectPass,
NormalPass,
RenderPass,
SMAAEffect,
SMAAPreset,
@@ -30,10 +31,40 @@ import {
import type {
AdvancedRenderingSettings,
BoxVolumeRenderPath,
AdvancedRenderingShadowType,
AdvancedRenderingToneMappingMode
} from "../document/world-settings";
const AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE = 0.15;
const MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS = 0.02;
const MAX_AMBIENT_OCCLUSION_EFFECT_RADIUS = 0.2;
const MIN_AMBIENT_OCCLUSION_SAMPLES = 12;
const COARSE_AMBIENT_OCCLUSION_RESOLUTION_SCALE = 0.5;
const DETAIL_AMBIENT_OCCLUSION_RESOLUTION_SCALE = 0.75;
const DETAIL_AMBIENT_OCCLUSION_RADIUS_SCALE = 0.35;
const COARSE_AMBIENT_OCCLUSION_INTENSITY_SCALE = 0.45;
const DETAIL_AMBIENT_OCCLUSION_INTENSITY_SCALE = 0.35;
export interface ResolvedBoxVolumeRenderPaths {
fog: BoxVolumeRenderPath;
water: BoxVolumeRenderPath;
}
export function resolveBoxVolumeRenderPaths(settings: AdvancedRenderingSettings): ResolvedBoxVolumeRenderPaths {
if (!settings.enabled) {
return {
fog: "performance",
water: "performance"
};
}
return {
fog: settings.fogPath,
water: settings.waterPath
};
}
export function getAdvancedRenderingShadowMapType(shadowType: AdvancedRenderingShadowType) {
switch (shadowType) {
case "basic":
@@ -67,28 +98,66 @@ export function configureAdvancedRenderingRenderer(renderer: WebGLRenderer, sett
renderer.toneMappingExposure = settings.toneMapping.exposure;
}
function clampAmbientOcclusionEffectRadius(radius: number) {
return Math.min(Math.max(radius, MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS), MAX_AMBIENT_OCCLUSION_EFFECT_RADIUS);
}
function getAmbientOcclusionSampleCount(samples: number) {
return Math.max(samples, MIN_AMBIENT_OCCLUSION_SAMPLES);
}
export function createAdvancedRenderingComposer(
renderer: WebGLRenderer,
scene: Scene,
camera: PerspectiveCamera,
settings: AdvancedRenderingSettings
): EffectComposer {
// The scene is always rendered into the composer's offscreen targets first,
// so those targets need depth for correct visibility even when no effect samples it.
const composer = new EffectComposer(renderer, {
depthBuffer: true,
stencilBuffer: false,
multisampling: 0,
frameBufferType: renderer.capabilities.isWebGL2 ? HalfFloatType : UnsignedByteType
});
composer.addPass(new RenderPass(scene, camera));
const effects: Array<SSAOEffect | BloomEffect | DepthOfFieldEffect | ToneMappingEffect | SMAAEffect> = [];
const effects: Array<BloomEffect | DepthOfFieldEffect | ToneMappingEffect | SMAAEffect> = [];
if (settings.ambientOcclusion.enabled) {
effects.push(
new SSAOEffect(camera, undefined, {
samples: settings.ambientOcclusion.samples,
radius: settings.ambientOcclusion.radius,
intensity: settings.ambientOcclusion.intensity
})
// postprocessing's internal depth-downsampling path writes zero normals unless
// a real normal buffer is supplied, which turns SSAO into speckled noise.
const normalPass = new NormalPass(scene, camera);
composer.addPass(normalPass);
const ambientOcclusionRadius = clampAmbientOcclusionEffectRadius(settings.ambientOcclusion.radius);
const ambientOcclusionSamples = getAmbientOcclusionSampleCount(settings.ambientOcclusion.samples);
const detailAmbientOcclusionRadius = Math.max(
ambientOcclusionRadius * DETAIL_AMBIENT_OCCLUSION_RADIUS_SCALE,
MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS
);
composer.addPass(
new EffectPass(
camera,
new SSAOEffect(camera, normalPass.texture, {
depthAwareUpsampling: true,
luminanceInfluence: AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE,
resolutionScale: COARSE_AMBIENT_OCCLUSION_RESOLUTION_SCALE,
samples: ambientOcclusionSamples,
radius: ambientOcclusionRadius,
intensity: settings.ambientOcclusion.intensity * COARSE_AMBIENT_OCCLUSION_INTENSITY_SCALE
}),
new SSAOEffect(camera, normalPass.texture, {
depthAwareUpsampling: true,
luminanceInfluence: AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE,
resolutionScale: DETAIL_AMBIENT_OCCLUSION_RESOLUTION_SCALE,
samples: ambientOcclusionSamples,
radius: detailAmbientOcclusionRadius,
intensity: settings.ambientOcclusion.intensity * DETAIL_AMBIENT_OCCLUSION_INTENSITY_SCALE
})
)
);
}

View File

@@ -0,0 +1,202 @@
import { BackSide, Color, ShaderMaterial, UniformsLib, UniformsUtils, Vector3 } from "three";
const MIN_FOG_HALF_SIZE = 0.05;
export function createFogQualityMaterial(options) {
const halfSize = new Vector3(Math.max(MIN_FOG_HALF_SIZE, options.halfSize.x), Math.max(MIN_FOG_HALF_SIZE, options.halfSize.y), Math.max(MIN_FOG_HALF_SIZE, options.halfSize.z));
const minHalfExtent = Math.min(halfSize.x, halfSize.y, halfSize.z);
const padding = Math.max(0, Math.min(options.padding, minHalfExtent * 0.82));
const animationUniform = { value: options.time };
const uniforms = UniformsUtils.clone(UniformsLib.fog);
uniforms["time"] = animationUniform;
uniforms["volumeFogColor"] = { value: new Color(options.colorHex) };
uniforms["volumeFogDensity"] = { value: Math.max(0, options.density) };
uniforms["volumeHalfSize"] = { value: halfSize };
uniforms["volumePadding"] = { value: padding };
uniforms["opacityMultiplier"] = { value: Math.max(0.6, Math.min(1.5, options.opacityMultiplier ?? 1)) };
uniforms["colorLift"] = { value: Math.max(0, Math.min(0.22, options.colorLift ?? 0)) };
uniforms["localCameraPosition"] = { value: new Vector3() };
const vertexShader = /* glsl */ `
varying vec3 vLocalPosition;
#include <fog_pars_vertex>
void main() {
vLocalPosition = position;
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
vec4 mvPosition = viewMatrix * worldPosition;
gl_Position = projectionMatrix * mvPosition;
#include <fog_vertex>
}
`;
const fragmentShader = /* glsl */ `
uniform vec3 volumeFogColor;
uniform float volumeFogDensity;
uniform vec3 volumeHalfSize;
uniform float volumePadding;
uniform float opacityMultiplier;
uniform float colorLift;
uniform float time;
uniform vec3 localCameraPosition;
varying vec3 vLocalPosition;
#include <fog_pars_fragment>
#define FOG_STEPS 10
float hash13(vec3 point) {
point = fract(point * 0.1031);
point += dot(point, point.yzx + 33.33);
return fract((point.x + point.y) * point.z);
}
float noise3(vec3 point) {
vec3 cell = floor(point);
vec3 local = fract(point);
vec3 smoothLocal = local * local * (3.0 - 2.0 * local);
float n000 = hash13(cell + vec3(0.0, 0.0, 0.0));
float n100 = hash13(cell + vec3(1.0, 0.0, 0.0));
float n010 = hash13(cell + vec3(0.0, 1.0, 0.0));
float n110 = hash13(cell + vec3(1.0, 1.0, 0.0));
float n001 = hash13(cell + vec3(0.0, 0.0, 1.0));
float n101 = hash13(cell + vec3(1.0, 0.0, 1.0));
float n011 = hash13(cell + vec3(0.0, 1.0, 1.0));
float n111 = hash13(cell + vec3(1.0, 1.0, 1.0));
float nx00 = mix(n000, n100, smoothLocal.x);
float nx10 = mix(n010, n110, smoothLocal.x);
float nx01 = mix(n001, n101, smoothLocal.x);
float nx11 = mix(n011, n111, smoothLocal.x);
float nxy0 = mix(nx00, nx10, smoothLocal.y);
float nxy1 = mix(nx01, nx11, smoothLocal.y);
return mix(nxy0, nxy1, smoothLocal.z);
}
float fbm(vec3 point) {
float value = 0.0;
float amplitude = 0.5;
for (int octave = 0; octave < 3; octave += 1) {
value += amplitude * noise3(point);
point = point * 2.04 + vec3(17.1, 31.7, 9.2);
amplitude *= 0.5;
}
return value;
}
vec2 intersectBox(vec3 rayOrigin, vec3 rayDirection, vec3 halfSize) {
vec3 safeDirection = sign(rayDirection) * max(abs(rayDirection), vec3(1e-4));
vec3 invDirection = 1.0 / safeDirection;
vec3 t0 = (-halfSize - rayOrigin) * invDirection;
vec3 t1 = (halfSize - rayOrigin) * invDirection;
vec3 tMin = min(t0, t1);
vec3 tMax = max(t0, t1);
float nearHit = max(max(tMin.x, tMin.y), tMin.z);
float farHit = min(min(tMax.x, tMax.y), tMax.z);
return vec2(nearHit, farHit);
}
float sampleShape(vec3 samplePosition) {
float minHalfExtent = min(min(volumeHalfSize.x, volumeHalfSize.y), volumeHalfSize.z);
float edgeSoftness = max(0.08, min(volumePadding + minHalfExtent * 0.16, minHalfExtent * 0.72));
vec3 innerHalfSize = max(volumeHalfSize - vec3(edgeSoftness), vec3(minHalfExtent * 0.18));
vec3 distanceToCore = abs(samplePosition) - innerHalfSize;
float outsideDistance = length(max(distanceToCore, 0.0));
float insideDistance = min(max(distanceToCore.x, max(distanceToCore.y, distanceToCore.z)), 0.0);
float roundedBoxDistance = outsideDistance + insideDistance;
float edgeMask = 1.0 - smoothstep(-edgeSoftness * 0.7, edgeSoftness * 1.35, roundedBoxDistance);
vec3 ellipsoidPosition = samplePosition / max(volumeHalfSize - vec3(edgeSoftness * 0.18), vec3(1e-3));
float roundedMask = 1.0 - smoothstep(0.54, 1.03, length(ellipsoidPosition * vec3(0.96, 1.08, 0.96)));
return edgeMask * mix(0.42, 1.0, roundedMask);
}
float sampleVolumeDensity(vec3 samplePosition) {
vec3 normalizedPosition = samplePosition / max(volumeHalfSize, vec3(1e-3));
float shape = sampleShape(samplePosition);
if (shape <= 1e-3) {
return 0.0;
}
vec3 drift = vec3(time * 0.1, time * 0.04, -time * 0.065);
float primary = fbm(samplePosition * 0.58 + drift);
float secondary = fbm(samplePosition * 1.18 - drift * 1.45 + vec3(4.3, 9.7, 2.1));
float wisps = noise3(samplePosition * 2.15 + vec3(0.0, time * 0.08, 0.0));
float cloud = smoothstep(0.34, 0.92, primary * 0.68 + secondary * 0.24 + wisps * 0.08);
float centerBias = 1.0 - smoothstep(0.18, 1.08, length(normalizedPosition * vec3(1.05, 0.92, 1.05)));
float verticalBias = mix(0.9, 1.08, smoothstep(-0.75, 0.35, normalizedPosition.y));
float carvedCloud = mix(0.42, 1.04, cloud) * mix(0.72, 1.0, centerBias);
return volumeFogDensity * shape * carvedCloud * verticalBias;
}
void main() {
vec3 rayDirection = normalize(vLocalPosition - localCameraPosition);
vec2 hitRange = intersectBox(localCameraPosition, rayDirection, volumeHalfSize);
float startDistance = max(hitRange.x, 0.0);
float endDistance = hitRange.y;
if (endDistance <= startDistance) {
discard;
}
float rayLength = endDistance - startDistance;
float stepLength = rayLength / float(FOG_STEPS);
float jitter = hash13(vLocalPosition * 1.73 + vec3(time * 0.17)) - 0.5;
float transmittance = 1.0;
vec3 accumulatedColor = vec3(0.0);
for (int stepIndex = 0; stepIndex < FOG_STEPS; stepIndex += 1) {
float sampleDistance = startDistance + (float(stepIndex) + 0.5 + jitter * 0.35) * stepLength;
vec3 samplePosition = localCameraPosition + rayDirection * sampleDistance;
float sampleDensity = sampleVolumeDensity(samplePosition);
if (sampleDensity <= 1e-4) {
continue;
}
vec3 normalizedPosition = samplePosition / max(volumeHalfSize, vec3(1e-3));
float forwardScatter = 1.0 - abs(dot(rayDirection, normalize(samplePosition + vec3(1e-3, 2e-3, -1e-3))));
float topLight = smoothstep(-0.2, 0.95, normalizedPosition.y);
float coolShadow = smoothstep(0.18, 0.88, noise3(samplePosition * 0.88 - vec3(time * 0.08, 0.0, time * 0.05)));
vec3 sampleColor = mix(volumeFogColor * 0.76, vec3(1.0), 0.06 + topLight * 0.12 + forwardScatter * 0.12);
sampleColor = mix(sampleColor * 0.92, sampleColor, coolShadow);
float extinction = sampleDensity * stepLength * 1.5;
float sampleAlpha = 1.0 - exp(-extinction);
accumulatedColor += transmittance * sampleColor * sampleAlpha;
transmittance *= 1.0 - sampleAlpha;
if (transmittance < 0.03) {
break;
}
}
float baseAlpha = 1.0 - transmittance;
float alpha = clamp(baseAlpha * opacityMultiplier, 0.0, 0.96);
if (alpha <= 0.01) {
discard;
}
vec3 color = accumulatedColor / max(baseAlpha, 1e-4);
color = mix(color, vec3(1.0), colorLift);
gl_FragColor = vec4(color, alpha);
#include <fog_fragment>
}
`;
return {
material: new ShaderMaterial({
vertexShader,
fragmentShader,
uniforms,
transparent: true,
depthWrite: false,
fog: true,
side: BackSide
}),
animationUniform
};
}

Some files were not shown because too many files have changed in this diff Show More