@asyra/preset 0.5.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +2 -2
  3. package/dist/agent-activity.d.ts +61 -0
  4. package/dist/agent-activity.d.ts.map +1 -0
  5. package/dist/agent-activity.js +224 -0
  6. package/dist/agent-activity.js.map +1 -0
  7. package/dist/catalog.d.ts.map +1 -1
  8. package/dist/catalog.js +2 -2
  9. package/dist/catalog.js.map +1 -1
  10. package/dist/cleanup-reporter.d.ts.map +1 -1
  11. package/dist/cleanup-reporter.js.map +1 -1
  12. package/dist/components/fills.d.ts +3 -1
  13. package/dist/components/fills.d.ts.map +1 -1
  14. package/dist/components/fills.js +74 -0
  15. package/dist/components/fills.js.map +1 -1
  16. package/dist/components/frame.d.ts +2 -2
  17. package/dist/components/frame.d.ts.map +1 -1
  18. package/dist/components/frame.js +1 -0
  19. package/dist/components/frame.js.map +1 -1
  20. package/dist/components/group.d.ts +9 -21
  21. package/dist/components/group.d.ts.map +1 -1
  22. package/dist/components/group.js +188 -84
  23. package/dist/components/group.js.map +1 -1
  24. package/dist/components/oval.d.ts +2 -2
  25. package/dist/components/oval.d.ts.map +1 -1
  26. package/dist/components/oval.js +3 -1
  27. package/dist/components/oval.js.map +1 -1
  28. package/dist/components/rectangle.d.ts +2 -2
  29. package/dist/components/rectangle.d.ts.map +1 -1
  30. package/dist/components/rectangle.js +3 -1
  31. package/dist/components/rectangle.js.map +1 -1
  32. package/dist/components/shape-hit-area.d.ts.map +1 -1
  33. package/dist/components/shape-hit-area.js.map +1 -1
  34. package/dist/components/text.d.ts +9 -0
  35. package/dist/components/text.d.ts.map +1 -0
  36. package/dist/components/text.js +61 -0
  37. package/dist/components/text.js.map +1 -0
  38. package/dist/components/vector-compound-fill.d.ts +8 -0
  39. package/dist/components/vector-compound-fill.d.ts.map +1 -0
  40. package/dist/components/vector-compound-fill.js +149 -0
  41. package/dist/components/vector-compound-fill.js.map +1 -0
  42. package/dist/components/vector.d.ts.map +1 -1
  43. package/dist/components/vector.js +85 -565
  44. package/dist/components/vector.js.map +1 -1
  45. package/dist/composition/error.d.ts.map +1 -1
  46. package/dist/composition/error.js.map +1 -1
  47. package/dist/composition/profile-provider.d.ts +2 -1
  48. package/dist/composition/profile-provider.d.ts.map +1 -1
  49. package/dist/composition/profile-provider.js +8 -2
  50. package/dist/composition/profile-provider.js.map +1 -1
  51. package/dist/composition/resolve.d.ts +2 -0
  52. package/dist/composition/resolve.d.ts.map +1 -1
  53. package/dist/composition/resolve.js +30 -6
  54. package/dist/composition/resolve.js.map +1 -1
  55. package/dist/defaults/install.d.ts.map +1 -1
  56. package/dist/defaults/install.js +2 -1
  57. package/dist/defaults/install.js.map +1 -1
  58. package/dist/defaults/installation.d.ts.map +1 -1
  59. package/dist/defaults/installation.js +2 -0
  60. package/dist/defaults/installation.js.map +1 -1
  61. package/dist/defaults/modules/selection.d.ts.map +1 -1
  62. package/dist/defaults/modules/selection.js.map +1 -1
  63. package/dist/defaults/modules/vector-editing.d.ts.map +1 -1
  64. package/dist/defaults/modules/vector-editing.js.map +1 -1
  65. package/dist/defaults/owned-state.d.ts.map +1 -1
  66. package/dist/defaults/owned-state.js.map +1 -1
  67. package/dist/defaults/private-manager.d.ts.map +1 -1
  68. package/dist/defaults/private-manager.js +2 -1
  69. package/dist/defaults/private-manager.js.map +1 -1
  70. package/dist/events/preset-event-names.d.ts +2 -0
  71. package/dist/events/preset-event-names.d.ts.map +1 -1
  72. package/dist/events/register-events.d.ts.map +1 -1
  73. package/dist/events/register-events.js +4 -2
  74. package/dist/events/register-events.js.map +1 -1
  75. package/dist/group-bounds.d.ts +36 -0
  76. package/dist/group-bounds.d.ts.map +1 -0
  77. package/dist/group-bounds.js +141 -0
  78. package/dist/group-bounds.js.map +1 -0
  79. package/dist/index.d.ts +3 -0
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +2 -0
  82. package/dist/index.js.map +1 -1
  83. package/dist/preset.d.ts.map +1 -1
  84. package/dist/preset.js +5 -3
  85. package/dist/preset.js.map +1 -1
  86. package/dist/props/components/anchor-points-component.d.ts.map +1 -1
  87. package/dist/props/components/anchor-points-component.js.map +1 -1
  88. package/dist/props/components/children-map-property-component.d.ts.map +1 -1
  89. package/dist/props/components/children-map-property-component.js.map +1 -1
  90. package/dist/props/components/fills-component.d.ts.map +1 -1
  91. package/dist/props/components/fills-component.js +3 -2
  92. package/dist/props/components/fills-component.js.map +1 -1
  93. package/dist/props/components/position-component.js +1 -1
  94. package/dist/props/components/position-component.js.map +1 -1
  95. package/dist/props/components/strokes-component.d.ts.map +1 -1
  96. package/dist/props/components/strokes-component.js +4 -3
  97. package/dist/props/components/strokes-component.js.map +1 -1
  98. package/dist/props/components/text-component.d.ts +67 -0
  99. package/dist/props/components/text-component.d.ts.map +1 -0
  100. package/dist/props/components/text-component.js +128 -0
  101. package/dist/props/components/text-component.js.map +1 -0
  102. package/dist/props/components/vector-networks-component.d.ts.map +1 -1
  103. package/dist/props/components/vector-networks-component.js.map +1 -1
  104. package/dist/props/components/vector-points-component.d.ts.map +1 -1
  105. package/dist/props/components/vector-points-component.js.map +1 -1
  106. package/dist/props/components/vector-segments-component.d.ts.map +1 -1
  107. package/dist/props/components/vector-segments-component.js.map +1 -1
  108. package/dist/props/register-property-schemas.d.ts.map +1 -1
  109. package/dist/props/register-property-schemas.js +6 -0
  110. package/dist/props/register-property-schemas.js.map +1 -1
  111. package/dist/render-layers/selection-overlay-render-layer.d.ts.map +1 -1
  112. package/dist/render-layers/selection-overlay-render-layer.js +7 -2
  113. package/dist/render-layers/selection-overlay-render-layer.js.map +1 -1
  114. package/dist/render-layers/vector-path-editing-render-layer.d.ts.map +1 -1
  115. package/dist/render-layers/vector-path-editing-render-layer.js.map +1 -1
  116. package/dist/selection/ids.d.ts.map +1 -1
  117. package/dist/selection/ids.js.map +1 -1
  118. package/dist/selection/register-default-selections.d.ts.map +1 -1
  119. package/dist/selection/register-default-selections.js +4 -2
  120. package/dist/selection/register-default-selections.js.map +1 -1
  121. package/dist/spatial/assets/binary.d.ts +22 -0
  122. package/dist/spatial/assets/binary.d.ts.map +1 -0
  123. package/dist/spatial/assets/binary.js +132 -0
  124. package/dist/spatial/assets/binary.js.map +1 -0
  125. package/dist/spatial/assets/decode.d.ts +23 -0
  126. package/dist/spatial/assets/decode.d.ts.map +1 -0
  127. package/dist/spatial/assets/decode.js +102 -0
  128. package/dist/spatial/assets/decode.js.map +1 -0
  129. package/dist/spatial/assets/preview-worker.d.ts +13 -0
  130. package/dist/spatial/assets/preview-worker.d.ts.map +1 -0
  131. package/dist/spatial/assets/preview-worker.js +188 -0
  132. package/dist/spatial/assets/preview-worker.js.map +1 -0
  133. package/dist/spatial/assets/scene.d.ts +13 -0
  134. package/dist/spatial/assets/scene.d.ts.map +1 -0
  135. package/dist/spatial/assets/scene.js +99 -0
  136. package/dist/spatial/assets/scene.js.map +1 -0
  137. package/dist/spatial/assets/schema.d.ts +22 -0
  138. package/dist/spatial/assets/schema.d.ts.map +1 -0
  139. package/dist/spatial/assets/schema.js +93 -0
  140. package/dist/spatial/assets/schema.js.map +1 -0
  141. package/dist/spatial/bounds.d.ts +15 -0
  142. package/dist/spatial/bounds.d.ts.map +1 -0
  143. package/dist/spatial/bounds.js +94 -0
  144. package/dist/spatial/bounds.js.map +1 -0
  145. package/dist/spatial/camera-controls.d.ts +53 -0
  146. package/dist/spatial/camera-controls.d.ts.map +1 -0
  147. package/dist/spatial/camera-controls.js +208 -0
  148. package/dist/spatial/camera-controls.js.map +1 -0
  149. package/dist/spatial/components.d.ts +20 -0
  150. package/dist/spatial/components.d.ts.map +1 -0
  151. package/dist/spatial/components.js +83 -0
  152. package/dist/spatial/components.js.map +1 -0
  153. package/dist/spatial/editing.d.ts +51 -0
  154. package/dist/spatial/editing.d.ts.map +1 -0
  155. package/dist/spatial/editing.js +152 -0
  156. package/dist/spatial/editing.js.map +1 -0
  157. package/dist/spatial/emissive-bloom.d.ts +22 -0
  158. package/dist/spatial/emissive-bloom.d.ts.map +1 -0
  159. package/dist/spatial/emissive-bloom.js +197 -0
  160. package/dist/spatial/emissive-bloom.js.map +1 -0
  161. package/dist/spatial/graphics.d.ts +9 -0
  162. package/dist/spatial/graphics.d.ts.map +1 -0
  163. package/dist/spatial/graphics.js +119 -0
  164. package/dist/spatial/graphics.js.map +1 -0
  165. package/dist/spatial/lazy-engine.d.ts +6 -0
  166. package/dist/spatial/lazy-engine.d.ts.map +1 -0
  167. package/dist/spatial/lazy-engine.js +92 -0
  168. package/dist/spatial/lazy-engine.js.map +1 -0
  169. package/dist/spatial/lighting.d.ts +28 -0
  170. package/dist/spatial/lighting.d.ts.map +1 -0
  171. package/dist/spatial/lighting.js +103 -0
  172. package/dist/spatial/lighting.js.map +1 -0
  173. package/dist/spatial/opaque-frame.d.ts +11 -0
  174. package/dist/spatial/opaque-frame.d.ts.map +1 -0
  175. package/dist/spatial/opaque-frame.js +131 -0
  176. package/dist/spatial/opaque-frame.js.map +1 -0
  177. package/dist/spatial/pose.d.ts +22 -0
  178. package/dist/spatial/pose.d.ts.map +1 -0
  179. package/dist/spatial/pose.js +83 -0
  180. package/dist/spatial/pose.js.map +1 -0
  181. package/dist/spatial/presentation.d.ts +16 -0
  182. package/dist/spatial/presentation.d.ts.map +1 -0
  183. package/dist/spatial/presentation.js +66 -0
  184. package/dist/spatial/presentation.js.map +1 -0
  185. package/dist/spatial/reflection-environment.d.ts +13 -0
  186. package/dist/spatial/reflection-environment.d.ts.map +1 -0
  187. package/dist/spatial/reflection-environment.js +63 -0
  188. package/dist/spatial/reflection-environment.js.map +1 -0
  189. package/dist/spatial/registration.d.ts +6 -0
  190. package/dist/spatial/registration.d.ts.map +1 -0
  191. package/dist/spatial/registration.js +82 -0
  192. package/dist/spatial/registration.js.map +1 -0
  193. package/dist/spatial/shadow-frame.d.ts +13 -0
  194. package/dist/spatial/shadow-frame.d.ts.map +1 -0
  195. package/dist/spatial/shadow-frame.js +60 -0
  196. package/dist/spatial/shadow-frame.js.map +1 -0
  197. package/dist/spatial/spatial-contract.d.ts +10 -0
  198. package/dist/spatial/spatial-contract.d.ts.map +1 -0
  199. package/dist/spatial/spatial-contract.js +414 -0
  200. package/dist/spatial/spatial-contract.js.map +1 -0
  201. package/dist/spatial/spatial-layer.d.ts +47 -0
  202. package/dist/spatial/spatial-layer.d.ts.map +1 -0
  203. package/dist/spatial/spatial-layer.js +224 -0
  204. package/dist/spatial/spatial-layer.js.map +1 -0
  205. package/dist/spatial/surface-contract.d.ts +4 -0
  206. package/dist/spatial/surface-contract.d.ts.map +1 -0
  207. package/dist/spatial/surface-contract.js +40 -0
  208. package/dist/spatial/surface-contract.js.map +1 -0
  209. package/dist/spatial/surface-textures.d.ts +8 -0
  210. package/dist/spatial/surface-textures.d.ts.map +1 -0
  211. package/dist/spatial/surface-textures.js +46 -0
  212. package/dist/spatial/surface-textures.js.map +1 -0
  213. package/dist/spatial/three-engine.d.ts +91 -0
  214. package/dist/spatial/three-engine.d.ts.map +1 -0
  215. package/dist/spatial/three-engine.js +1127 -0
  216. package/dist/spatial/three-engine.js.map +1 -0
  217. package/dist/spatial/transmission-capture.d.ts +13 -0
  218. package/dist/spatial/transmission-capture.d.ts.map +1 -0
  219. package/dist/spatial/transmission-capture.js +215 -0
  220. package/dist/spatial/transmission-capture.js.map +1 -0
  221. package/dist/spatial-assets.d.ts +4 -0
  222. package/dist/spatial-assets.d.ts.map +1 -0
  223. package/dist/spatial-assets.js +4 -0
  224. package/dist/spatial-assets.js.map +1 -0
  225. package/dist/spatial-contract.d.ts +3 -0
  226. package/dist/spatial-contract.d.ts.map +1 -0
  227. package/dist/spatial-contract.js +3 -0
  228. package/dist/spatial-contract.js.map +1 -0
  229. package/dist/spatial-engine.d.ts +5 -0
  230. package/dist/spatial-engine.d.ts.map +1 -0
  231. package/dist/spatial-engine.js +5 -0
  232. package/dist/spatial-engine.js.map +1 -0
  233. package/dist/spatial.d.ts +9 -0
  234. package/dist/spatial.d.ts.map +1 -0
  235. package/dist/spatial.js +9 -0
  236. package/dist/spatial.js.map +1 -0
  237. package/dist/subscriptions/data-channel.d.ts.map +1 -1
  238. package/dist/subscriptions/data-channel.js +372 -124
  239. package/dist/subscriptions/data-channel.js.map +1 -1
  240. package/dist/subscriptions/render-system.d.ts.map +1 -1
  241. package/dist/subscriptions/render-system.js +4 -2
  242. package/dist/subscriptions/render-system.js.map +1 -1
  243. package/dist/subscriptions/shared-channels.d.ts.map +1 -1
  244. package/dist/subscriptions/shared-channels.js +4 -2
  245. package/dist/subscriptions/shared-channels.js.map +1 -1
  246. package/dist/subscriptions/vector-selection.d.ts +4 -0
  247. package/dist/subscriptions/vector-selection.d.ts.map +1 -0
  248. package/dist/subscriptions/vector-selection.js +175 -0
  249. package/dist/subscriptions/vector-selection.js.map +1 -0
  250. package/dist/types.d.ts +2 -0
  251. package/dist/types.d.ts.map +1 -1
  252. package/dist/ui/register-properties.d.ts.map +1 -1
  253. package/dist/ui/register-properties.js +3 -2
  254. package/dist/ui/register-properties.js.map +1 -1
  255. package/dist/vector/synthetic-handle.d.ts.map +1 -1
  256. package/dist/vector/synthetic-handle.js.map +1 -1
  257. package/package.json +43 -11
@@ -0,0 +1,1127 @@
1
+ import { createShadowFrame } from './shadow-frame.js';
2
+ import { TransmissionCapture } from './transmission-capture.js';
3
+ import { ReflectionEnvironment } from './reflection-environment.js';
4
+ import { EmissiveBloom, requireBloomRenderer } from './emissive-bloom.js';
5
+ import { DEFAULT_SPATIAL_LIGHTING, readSpatialLighting, readSpatialBloom } from './lighting.js';
6
+ import { SPATIAL_ENGINE_CAPABILITIES } from './lazy-engine.js';
7
+ import { SurfaceTextureStore } from './surface-textures.js';
8
+ import * as THREE from 'three';
9
+ import { RenderEngineCapabilities, isSpatialQuery, UnsupportedRenderEngineCapabilityError } from '@asyra/render-engine';
10
+ import { readSpatialDescriptor, sameSpatialShape, SPATIAL_PROPERTY } from './spatial-contract.js';
11
+ import { disposeObject, drawGraphics } from './graphics.js';
12
+ const unsupportedQueryCapabilities = {
13
+ 'measure-text': RenderEngineCapabilities.TEXT_MEASUREMENT,
14
+ snapshot: RenderEngineCapabilities.SNAPSHOT,
15
+ 'get-local-content-bounds': RenderEngineCapabilities.LOCAL_CONTENT_BOUNDS
16
+ };
17
+ const isUnsupportedQuery = (query) => Object.prototype.hasOwnProperty.call(unsupportedQueryCapabilities, query.type);
18
+ const usesSoftwareRenderer = (driver) => {
19
+ if (!driver.getContext || !driver.shadowMap) {
20
+ return false;
21
+ }
22
+ const gl = driver.getContext();
23
+ const extension = gl.getExtension('WEBGL_debug_renderer_info');
24
+ if (!extension) {
25
+ return false;
26
+ }
27
+ const renderer = gl.getParameter(extension.UNMASKED_RENDERER_WEBGL);
28
+ return (typeof renderer === 'string' &&
29
+ /swiftshader|llvmpipe|softpipe|software rasterizer/i.test(renderer));
30
+ };
31
+ const createDefaultDriver = () => {
32
+ const driver = new THREE.WebGLRenderer({ antialias: true, alpha: false });
33
+ driver.toneMapping = THREE.ACESFilmicToneMapping;
34
+ driver.shadowMap.enabled = true;
35
+ driver.shadowMap.type = THREE.PCFSoftShadowMap;
36
+ return driver;
37
+ };
38
+ const makeGeometry = (shape) => {
39
+ switch (shape.kind) {
40
+ case 'box':
41
+ return new THREE.BoxGeometry(...shape.size);
42
+ case 'sphere':
43
+ return new THREE.SphereGeometry(shape.radius, 32, 20);
44
+ case 'capsule':
45
+ return new THREE.CapsuleGeometry(shape.radius, shape.length, 8, 24);
46
+ case 'triangles': {
47
+ const geometry = new THREE.BufferGeometry();
48
+ // Admitted arrays are frozen. Copy by index into the final owned GPU
49
+ // buffers, avoiding generic iterable conversion and index array expansion.
50
+ for (const [name, values] of [
51
+ ['position', shape.positions],
52
+ ['color', shape.colors],
53
+ ['normal', shape.normals],
54
+ ['uv', shape.uvs]
55
+ ]) {
56
+ if (!values) {
57
+ continue;
58
+ }
59
+ const array = new Float32Array(values.length);
60
+ for (let i = 0; i < values.length; i++) {
61
+ array[i] = values[i];
62
+ }
63
+ geometry.setAttribute(name, new THREE.BufferAttribute(array, name === 'uv' ? 2 : 3));
64
+ }
65
+ const indices = shape.positions.length / 3 > 65535
66
+ ? new Uint32Array(shape.indices.length)
67
+ : new Uint16Array(shape.indices.length);
68
+ for (let i = 0; i < shape.indices.length; i++) {
69
+ indices[i] = shape.indices[i];
70
+ }
71
+ geometry.setIndex(new THREE.BufferAttribute(indices, 1));
72
+ if (!shape.normals) {
73
+ geometry.computeVertexNormals();
74
+ }
75
+ return geometry;
76
+ }
77
+ }
78
+ };
79
+ const numberProperty = (properties, key, fallback) => {
80
+ const value = properties[key];
81
+ if (value === undefined) {
82
+ return fallback;
83
+ }
84
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
85
+ throw new Error(`Invalid render property: ${key}`);
86
+ }
87
+ return value;
88
+ };
89
+ const SCREEN_PROPERTIES = new Set([
90
+ 'x',
91
+ 'y',
92
+ 'width',
93
+ 'height',
94
+ 'scaleX',
95
+ 'scaleY',
96
+ 'skewX',
97
+ 'skewY',
98
+ 'visible',
99
+ 'renderable',
100
+ 'label',
101
+ 'alpha',
102
+ 'angle',
103
+ 'rotation',
104
+ 'zIndex',
105
+ 'eventMode',
106
+ 'cursor',
107
+ 'batched',
108
+ SPATIAL_PROPERTY
109
+ ]);
110
+ /** A CUSTOM visual engine. It owns no editable state or analysis semantics. */
111
+ export class ThreeEngine {
112
+ constructor(platform = {}, options = {}) {
113
+ this.platform = platform;
114
+ this.options = options;
115
+ this.instanceDetail = new WeakMap();
116
+ this.surfaceTextures = new SurfaceTextureStore();
117
+ this.name = 'Preset CUSTOM Three.js 0.185.1';
118
+ this.capabilities = new Set(SPATIAL_ENGINE_CAPABILITIES);
119
+ this.objects = new Map();
120
+ this.resources = new Map();
121
+ this.listeners = new Set();
122
+ this.scene = new THREE.Scene();
123
+ this.screen = new THREE.Scene();
124
+ this.camera = new THREE.PerspectiveCamera(50, 1, 0.01, 1000);
125
+ this.screenCamera = new THREE.OrthographicCamera(0, 1, 0, 1, -10000, 10000);
126
+ this.driver = null;
127
+ this.reflections = new ReflectionEnvironment();
128
+ this.transmissionCapture = new TransmissionCapture();
129
+ this.root = null;
130
+ this.width = 1;
131
+ this.height = 1;
132
+ this.pixelRatio = 1;
133
+ this.frame = null;
134
+ this.frameGeneration = 0;
135
+ this.destroyed = false;
136
+ this.pointerDisposers = [];
137
+ this.camera.position.set(3, 2, 3);
138
+ this.camera.lookAt(0, 0, 0);
139
+ this.screenCamera.position.z = 100;
140
+ }
141
+ initialize(options) {
142
+ if (this.destroyed || this.driver) {
143
+ throw new Error('Engine is not available for initialization');
144
+ }
145
+ this.validateSize(options.width, options.height);
146
+ const lighting = readSpatialLighting(this.options.lighting ?? DEFAULT_SPATIAL_LIGHTING);
147
+ try {
148
+ this.driver = this.platform.createDriver?.() ?? createDefaultDriver();
149
+ this.driver.autoClear = false;
150
+ const softwareRenderer = this.options.softwareShadowFallback !== false &&
151
+ usesSoftwareRenderer(this.driver);
152
+ if (softwareRenderer && this.driver.shadowMap) {
153
+ this.driver.shadowMap.enabled = false;
154
+ }
155
+ this.pixelRatio = Math.min(options.resolution ?? globalThis.devicePixelRatio ?? 1, 2);
156
+ this.driver.setPixelRatio(this.pixelRatio);
157
+ if (this.options.bloom !== undefined) {
158
+ this.bloom = new EmissiveBloom(requireBloomRenderer(this.driver), readSpatialBloom(this.options.bloom));
159
+ }
160
+ this.driver.setClearColor(options.backgroundColor ?? 0x101b29, 1);
161
+ this.resize(options.width, options.height);
162
+ this.root = this.create('container', {});
163
+ this.scene.add(new THREE.HemisphereLight(...lighting.hemisphere));
164
+ const key = new THREE.DirectionalLight(lighting.keyColor ?? 0xffffff, lighting.keyIntensity ?? 2.6);
165
+ key.position.set(...lighting.keyPosition);
166
+ key.castShadow = !softwareRenderer && (lighting.castShadows ?? true);
167
+ key.shadow.mapSize.set(1024, 1024);
168
+ Object.assign(key.shadow.camera, {
169
+ left: -lighting.shadowExtent,
170
+ right: lighting.shadowExtent,
171
+ top: lighting.shadowExtent,
172
+ bottom: -lighting.shadowExtent,
173
+ near: 0.1,
174
+ far: lighting.shadowFar
175
+ });
176
+ // Scale receiver offset to the world-space PCF footprint, not a fixed scene unit.
177
+ key.shadow.normalBias =
178
+ (2 * lighting.shadowExtent * 1.5) / key.shadow.mapSize.x;
179
+ key.shadow.bias = -0.0001;
180
+ this.scene.add(key);
181
+ const fill = new THREE.DirectionalLight(lighting.fillColor ?? 0xffffff, lighting.fillIntensity ?? 1.2);
182
+ fill.position.set(...lighting.fillPosition);
183
+ this.scene.add(fill);
184
+ this.attachPointerListeners(this.driver.domElement);
185
+ return {
186
+ surface: this.driver.domElement,
187
+ inputTarget: this.driver.domElement,
188
+ runtime: Object.freeze({ name: this.name }),
189
+ root: this.root.handle
190
+ };
191
+ }
192
+ catch (error) {
193
+ this.destroy();
194
+ throw error;
195
+ }
196
+ }
197
+ execute(command) {
198
+ this.assertActive();
199
+ let object;
200
+ let resource;
201
+ let status = 'applied';
202
+ switch (command.type) {
203
+ case 'create-object':
204
+ object = this.create(command.objectType, command.properties ?? {}).handle;
205
+ break;
206
+ case 'update-object':
207
+ this.update(this.owned(command.object), command.properties);
208
+ break;
209
+ case 'destroy-object':
210
+ this.remove(this.owned(command.object));
211
+ break;
212
+ case 'append-child': {
213
+ const parent = this.owned(command.parent), child = this.owned(command.child);
214
+ for (let current = parent; current; current = current.parent) {
215
+ if (current === child) {
216
+ throw new Error('Render hierarchy cycle');
217
+ }
218
+ }
219
+ if (child === this.root) {
220
+ throw new Error('Cannot reparent the engine root');
221
+ }
222
+ this.detach(child);
223
+ child.parent = parent;
224
+ parent.children.push(child);
225
+ break;
226
+ }
227
+ case 'remove-child': {
228
+ const parent = this.owned(command.parent), child = this.owned(command.child);
229
+ if (child.parent === parent) {
230
+ this.detach(child);
231
+ }
232
+ else {
233
+ status = 'noop';
234
+ }
235
+ break;
236
+ }
237
+ case 'set-child-index': {
238
+ const parent = this.owned(command.parent), child = this.owned(command.child);
239
+ if (child.parent !== parent ||
240
+ !Number.isInteger(command.index) ||
241
+ command.index < 0 ||
242
+ command.index >= parent.children.length) {
243
+ throw new Error('Invalid child index');
244
+ }
245
+ parent.children.splice(parent.children.indexOf(child), 1);
246
+ parent.children.splice(command.index, 0, child);
247
+ break;
248
+ }
249
+ case 'draw': {
250
+ const record = this.owned(command.object);
251
+ if (record.type !== 'graphics') {
252
+ throw new Error('Draw requires a graphics object');
253
+ }
254
+ const content = drawGraphics(command.operations, (paint) => this.paint(paint));
255
+ this.replaceContent(record, content);
256
+ break;
257
+ }
258
+ case 'create-resource': {
259
+ if (command.descriptor.kind !== 'paint') {
260
+ throw new Error('Unsupported resource descriptor');
261
+ }
262
+ const value = command.descriptor.data;
263
+ const paint = this.paint(value);
264
+ resource = Object.freeze({});
265
+ this.resources.set(resource, paint);
266
+ break;
267
+ }
268
+ case 'destroy-resource':
269
+ if (!this.resources.delete(command.resource)) {
270
+ throw new Error('Foreign or destroyed resource handle');
271
+ }
272
+ break;
273
+ case 'resize':
274
+ this.resize(command.width, command.height);
275
+ break;
276
+ case 'set-viewport':
277
+ if (![
278
+ command.position.x,
279
+ command.position.y,
280
+ command.scale.x,
281
+ command.scale.y
282
+ ].every(Number.isFinite)) {
283
+ throw new Error('Invalid screen viewport');
284
+ }
285
+ this.screen.position.set(command.position.x, command.position.y, 0);
286
+ this.screen.scale.set(command.scale.x, command.scale.y, 1);
287
+ break;
288
+ case 'flush': {
289
+ const draw = createShadowFrame(this.requireDriver());
290
+ this.syncProjection();
291
+ this.updateInstanceDetail();
292
+ const driver = this.requireDriver();
293
+ const width = Math.max(1, Math.round(this.width * this.pixelRatio));
294
+ const height = Math.max(1, Math.round(this.height * this.pixelRatio));
295
+ this.transmissionCapture.render(driver, this.scene, this.camera, width, height, draw, () => {
296
+ driver.clear();
297
+ draw(this.scene, this.camera);
298
+ });
299
+ this.bloom?.render(this.scene, this.camera);
300
+ this.requireDriver().clearDepth();
301
+ this.requireDriver().render(this.screen, this.screenCamera);
302
+ break;
303
+ }
304
+ }
305
+ return { commandType: command.type, status, object, resource };
306
+ }
307
+ query(query) {
308
+ this.assertActive();
309
+ if (isUnsupportedQuery(query)) {
310
+ throw new UnsupportedRenderEngineCapabilityError(this.name, [
311
+ unsupportedQueryCapabilities[query.type]
312
+ ]);
313
+ }
314
+ this.syncProjection();
315
+ if (isSpatialQuery(query)) {
316
+ return this.spatialQuery(query);
317
+ }
318
+ if (query.type === 'hit-test') {
319
+ return { type: 'hit', target: this.pick(query.point), point: query.point };
320
+ }
321
+ const record = this.owned(query.object);
322
+ if (query.type === 'get-bounds') {
323
+ const bounds = new THREE.Box3().setFromObject(record.visual);
324
+ if (bounds.isEmpty()) {
325
+ return { type: 'bounds', bounds: { x: 0, y: 0, width: 0, height: 0 } };
326
+ }
327
+ const points = [];
328
+ for (const x of [bounds.min.x, bounds.max.x]) {
329
+ for (const y of [bounds.min.y, bounds.max.y]) {
330
+ for (const z of [bounds.min.z, bounds.max.z]) {
331
+ points.push(new THREE.Vector3(x, y, z));
332
+ }
333
+ }
334
+ }
335
+ if (record.spatial) {
336
+ points.forEach((p) => {
337
+ p.project(this.camera);
338
+ p.set(((p.x + 1) * this.width) / 2, ((1 - p.y) * this.height) / 2, 0);
339
+ });
340
+ }
341
+ const minX = Math.min(...points.map((p) => p.x)), minY = Math.min(...points.map((p) => p.y));
342
+ return {
343
+ type: 'bounds',
344
+ bounds: {
345
+ x: minX,
346
+ y: minY,
347
+ width: Math.max(...points.map((p) => p.x)) - minX,
348
+ height: Math.max(...points.map((p) => p.y)) - minY
349
+ }
350
+ };
351
+ }
352
+ if (record.spatial) {
353
+ throw new Error('Spatial local/global conversion requires an explicit 3D contract; screen queries are not 3D poses');
354
+ }
355
+ const point = new THREE.Vector3(query.point.x, query.point.y, 0);
356
+ if (query.type === 'to-local') {
357
+ record.visual.worldToLocal(point);
358
+ }
359
+ else {
360
+ record.visual.localToWorld(point);
361
+ }
362
+ return { type: 'point', point: { x: point.x, y: point.y } };
363
+ }
364
+ subscribeToInteraction(listener) {
365
+ if (this.destroyed) {
366
+ throw new Error('Engine is not active');
367
+ }
368
+ this.listeners.add(listener);
369
+ return () => {
370
+ this.listeners.delete(listener);
371
+ };
372
+ }
373
+ dispatchInteraction(event) {
374
+ this.assertActive();
375
+ if (event.target) {
376
+ this.owned(event.target);
377
+ }
378
+ for (const listener of [...this.listeners]) {
379
+ listener(event);
380
+ }
381
+ }
382
+ requestFrame(callback) {
383
+ this.assertActive();
384
+ this.cancelFrame();
385
+ const request = this.platform.requestFrame ??
386
+ globalThis.requestAnimationFrame.bind(globalThis);
387
+ const generation = ++this.frameGeneration;
388
+ this.frame = request((time) => {
389
+ if (this.destroyed || generation !== this.frameGeneration) {
390
+ return;
391
+ }
392
+ this.frame = null;
393
+ this.frameGeneration++;
394
+ callback(time);
395
+ });
396
+ }
397
+ cancelFrame() {
398
+ this.frameGeneration++;
399
+ if (this.frame === null) {
400
+ return;
401
+ }
402
+ const cancel = this.platform.cancelFrame ??
403
+ globalThis.cancelAnimationFrame.bind(globalThis);
404
+ cancel(this.frame);
405
+ this.frame = null;
406
+ }
407
+ destroy() {
408
+ if (this.destroyed) {
409
+ return {
410
+ destroyedObjects: 0,
411
+ destroyedResources: 0,
412
+ alreadyDestroyed: true
413
+ };
414
+ }
415
+ this.cancelFrame();
416
+ const result = {
417
+ destroyedObjects: this.objects.size,
418
+ destroyedResources: this.resources.size,
419
+ alreadyDestroyed: false
420
+ };
421
+ this.destroyed = true;
422
+ this.pointerDisposers.splice(0).forEach((dispose) => dispose());
423
+ this.listeners.clear();
424
+ for (const record of this.objects.values()) {
425
+ disposeObject(record.visual);
426
+ }
427
+ this.objects.clear();
428
+ this.resources.clear();
429
+ this.scene.traverse((object) => {
430
+ if (object instanceof THREE.Light) {
431
+ object.dispose();
432
+ }
433
+ });
434
+ this.scene.clear();
435
+ this.screen.clear();
436
+ this.reflections.dispose();
437
+ this.transmissionCapture.dispose();
438
+ this.bloom?.dispose();
439
+ this.bloom = undefined;
440
+ this.driver?.dispose();
441
+ this.driver = null;
442
+ this.root = null;
443
+ return result;
444
+ }
445
+ assertActive() {
446
+ if (this.destroyed || !this.driver) {
447
+ throw new Error('Engine is not active');
448
+ }
449
+ }
450
+ requireDriver() {
451
+ this.assertActive();
452
+ if (!this.driver) {
453
+ throw new Error('Engine driver is unavailable');
454
+ }
455
+ return this.driver;
456
+ }
457
+ owned(handle) {
458
+ const record = this.objects.get(handle);
459
+ if (!record) {
460
+ throw new Error('Foreign or destroyed object handle');
461
+ }
462
+ return record;
463
+ }
464
+ create(type, properties) {
465
+ const record = {
466
+ handle: Object.freeze({}),
467
+ type,
468
+ properties: {},
469
+ visual: new THREE.Group(),
470
+ content: null,
471
+ parent: null,
472
+ children: []
473
+ };
474
+ try {
475
+ this.update(record, properties);
476
+ }
477
+ catch (error) {
478
+ disposeObject(record.visual);
479
+ throw error;
480
+ }
481
+ this.objects.set(record.handle, record);
482
+ return record;
483
+ }
484
+ update(record, patch) {
485
+ const properties = { ...record.properties, ...patch };
486
+ for (const key of Object.keys(properties)) {
487
+ if (!SCREEN_PROPERTIES.has(key)) {
488
+ throw new Error(`Unsupported screen property: ${key}`);
489
+ }
490
+ }
491
+ if (numberProperty(properties, 'skewX', 0) !== 0 ||
492
+ numberProperty(properties, 'skewY', 0) !== 0 ||
493
+ numberProperty(properties, 'alpha', 1) !== 1) {
494
+ throw new Error('Unsupported screen skew or alpha; use spatial appearance for 3D meshes');
495
+ }
496
+ const spatial = properties[SPATIAL_PROPERTY] === undefined
497
+ ? undefined
498
+ : (this.options.readDescriptor ?? readSpatialDescriptor)(properties[SPATIAL_PROPERTY]);
499
+ if (spatial?.kind === 'camera' && record.type !== 'container') {
500
+ throw new Error('Camera requires a spatial container');
501
+ }
502
+ if (spatial?.kind === 'mesh' && record.type !== 'mesh') {
503
+ throw new Error('Spatial geometry requires a mesh');
504
+ }
505
+ if (record.type === 'mesh' && spatial?.kind !== 'mesh') {
506
+ throw new Error('CUSTOM meshes require an explicit spatial descriptor');
507
+ }
508
+ const x = numberProperty(properties, 'x', 0), y = numberProperty(properties, 'y', 0);
509
+ const sx = numberProperty(properties, 'scaleX', 1), sy = numberProperty(properties, 'scaleY', 1);
510
+ const rotation = numberProperty(properties, 'rotation', 0);
511
+ const order = numberProperty(properties, 'zIndex', 0);
512
+ let content = null;
513
+ const previous = record.spatial;
514
+ const reusable = spatial?.kind === 'mesh' &&
515
+ previous?.kind === 'mesh' &&
516
+ record.content instanceof THREE.Mesh &&
517
+ sameSpatialShape(previous.shape, spatial.shape) &&
518
+ previous.surface === spatial.surface &&
519
+ Boolean(previous.distant) === Boolean(spatial.distant) &&
520
+ (!previous.distant ||
521
+ !spatial.distant ||
522
+ sameSpatialShape(previous.distant.shape, spatial.distant.shape));
523
+ if (reusable &&
524
+ spatial?.kind === 'mesh' &&
525
+ previous?.kind === 'mesh' &&
526
+ record.content instanceof THREE.Mesh &&
527
+ (Boolean(previous.instances) !== Boolean(spatial.instances) ||
528
+ previous.instances?.length !== spatial.instances?.length)) {
529
+ const old = record.content;
530
+ content = spatial.instances
531
+ ? new THREE.InstancedMesh(old.geometry, old.material, spatial.instances.length)
532
+ : new THREE.Mesh(old.geometry, old.material);
533
+ if (spatial.distant && spatial.instances) {
534
+ const source = old.children[0];
535
+ if (!(source instanceof THREE.InstancedMesh)) {
536
+ throw new Error('Missing instance detail geometry');
537
+ }
538
+ const distant = new THREE.InstancedMesh(source.geometry, source.material, spatial.instances.length);
539
+ content.frustumCulled = false;
540
+ distant.frustumCulled = false;
541
+ content.add(distant);
542
+ }
543
+ // Geometry/material ownership transfers; retire only superseded instance buffers.
544
+ old.traverse((child) => {
545
+ if (child instanceof THREE.InstancedMesh) {
546
+ child.dispose();
547
+ }
548
+ });
549
+ old.clear();
550
+ old.removeFromParent();
551
+ record.content = null;
552
+ }
553
+ if (!content &&
554
+ spatial?.kind === 'mesh' &&
555
+ Object.prototype.hasOwnProperty.call(patch, SPATIAL_PROPERTY) &&
556
+ !reusable) {
557
+ const geometry = makeGeometry(spatial.shape);
558
+ const material = new THREE.MeshPhysicalMaterial({
559
+ color: spatial.color,
560
+ vertexColors: spatial.shape.kind === 'triangles' && Boolean(spatial.shape.colors),
561
+ opacity: spatial.opacity,
562
+ transparent: spatial.opacity < 1,
563
+ wireframe: spatial.wireframe,
564
+ side: THREE.DoubleSide,
565
+ roughness: spatial.roughness ?? 0.65,
566
+ metalness: spatial.metalness ?? 0.12,
567
+ emissive: spatial.emissive ?? 0,
568
+ emissiveIntensity: spatial.emissiveIntensity ?? 0,
569
+ depthWrite: spatial.opacity >= 1
570
+ });
571
+ this.reflections.apply(material, spatial.environmentIntensity ?? 0, this.requireDriver());
572
+ if (spatial.surface) {
573
+ this.surfaceTextures.apply(material, spatial.surface);
574
+ }
575
+ content = spatial.instances
576
+ ? new THREE.InstancedMesh(geometry, material, spatial.instances.length)
577
+ : new THREE.Mesh(geometry, material);
578
+ if (spatial.distant && spatial.instances) {
579
+ const distant = new THREE.InstancedMesh(makeGeometry(spatial.distant.shape), material.clone(), spatial.instances.length);
580
+ distant.frustumCulled = false;
581
+ content.frustumCulled = false;
582
+ content.add(distant);
583
+ geometry.computeBoundingSphere();
584
+ }
585
+ }
586
+ const previousInstances = record.spatial?.kind === 'mesh' ? record.spatial.instances : undefined;
587
+ record.properties = properties;
588
+ record.spatial = spatial;
589
+ if (content) {
590
+ this.replaceContent(record, content);
591
+ }
592
+ if (spatial?.kind === 'mesh') {
593
+ if (record.content instanceof THREE.InstancedMesh &&
594
+ spatial.instances &&
595
+ !spatial.distant &&
596
+ (content || previousInstances !== spatial.instances)) {
597
+ const matrix = new THREE.Matrix4();
598
+ const translation = new THREE.Vector3();
599
+ const rotation = new THREE.Quaternion();
600
+ const scale = new THREE.Vector3(1, 1, 1);
601
+ spatial.instances.forEach((instance, index) => {
602
+ matrix.compose(translation.fromArray(instance.position), rotation.fromArray(instance.rotation), scale.fromArray(instance.scale ?? [1, 1, 1]));
603
+ record.content.setMatrixAt(index, matrix);
604
+ });
605
+ record.content.instanceMatrix.needsUpdate = true;
606
+ record.content.computeBoundingBox();
607
+ record.content.computeBoundingSphere();
608
+ }
609
+ if (record.content instanceof THREE.Mesh) {
610
+ record.content.castShadow = spatial.castShadow ?? false;
611
+ record.content.receiveShadow = spatial.receiveShadow ?? false;
612
+ const material = record.content.material;
613
+ const transparent = spatial.opacity < 1;
614
+ if (material.transparent !== transparent ||
615
+ material.wireframe !== spatial.wireframe) {
616
+ material.needsUpdate = true;
617
+ }
618
+ material.color.setHex(spatial.color);
619
+ material.opacity = spatial.opacity;
620
+ material.transparent = transparent;
621
+ material.depthWrite = !transparent;
622
+ material.wireframe = spatial.wireframe;
623
+ material.roughness = spatial.roughness ?? 0.65;
624
+ material.metalness = spatial.metalness ?? 0.12;
625
+ const optics = spatial.optics;
626
+ const side = optics ? THREE.FrontSide : THREE.DoubleSide;
627
+ if (material.side !== side) {
628
+ material.needsUpdate = true;
629
+ }
630
+ material.side = side;
631
+ material.transmission = optics?.transmission ?? 0;
632
+ this.transmissionCapture.apply(material, optics?.captureLayer);
633
+ material.ior = optics?.ior ?? 1.5;
634
+ material.thickness = optics?.thickness ?? 0;
635
+ material.attenuationColor.setHex(optics?.attenuationColor ?? 0xffffff);
636
+ material.attenuationDistance = optics?.attenuationDistance ?? Infinity;
637
+ this.reflections.apply(material, spatial.environmentIntensity ?? 0, this.requireDriver());
638
+ material.emissive.setHex(spatial.emissive ?? 0);
639
+ material.emissiveIntensity = spatial.emissiveIntensity ?? 0;
640
+ for (const child of record.content.children) {
641
+ if (child instanceof THREE.InstancedMesh) {
642
+ ;
643
+ child.material.copy(material);
644
+ this.transmissionCapture.apply(child.material, optics?.captureLayer);
645
+ child.receiveShadow = record.content.receiveShadow;
646
+ child.castShadow = record.content.castShadow;
647
+ }
648
+ }
649
+ }
650
+ record.visual.position.fromArray(spatial.position);
651
+ record.visual.quaternion.fromArray(spatial.rotation);
652
+ record.visual.scale.fromArray(spatial.scale ?? [1, 1, 1]);
653
+ }
654
+ else {
655
+ record.visual.position.set(x, y, 0);
656
+ record.visual.rotation.set(0, 0, rotation);
657
+ record.visual.scale.set(sx, sy, 1);
658
+ }
659
+ record.visual.renderOrder = order;
660
+ }
661
+ /** Completed geometry is reused; only visible instance matrices change per frame. */
662
+ updateInstanceDetail() {
663
+ this.scene.updateMatrixWorld(true);
664
+ this.camera.updateMatrixWorld(true);
665
+ const frustum = new THREE.Frustum().setFromProjectionMatrix(new THREE.Matrix4().multiplyMatrices(this.camera.projectionMatrix, this.camera.matrixWorldInverse));
666
+ const pixelsPerUnit = (this.height *
667
+ this.pixelRatio *
668
+ Math.abs(this.camera.projectionMatrix.elements[5])) /
669
+ 2;
670
+ const matrix = new THREE.Matrix4(), world = new THREE.Matrix4(), center = new THREE.Vector3(), sphere = new THREE.Sphere();
671
+ for (const record of this.objects.values()) {
672
+ const spatial = record.spatial, full = record.content;
673
+ if (spatial?.kind !== 'mesh' ||
674
+ !spatial.distant ||
675
+ !spatial.instances ||
676
+ !(full instanceof THREE.InstancedMesh) ||
677
+ !record.visual.visible) {
678
+ continue;
679
+ }
680
+ const distant = full.children[0];
681
+ if (!(distant instanceof THREE.InstancedMesh) ||
682
+ !full.geometry.boundingSphere) {
683
+ throw new Error('Missing instance detail geometry');
684
+ }
685
+ const previous = this.instanceDetail.get(full);
686
+ if (previous &&
687
+ previous.instances === spatial.instances &&
688
+ previous.geometry === full.geometry &&
689
+ previous.height === this.height &&
690
+ previous.pixelRatio === this.pixelRatio &&
691
+ previous.pixelError === (spatial.distant.pixelError ?? 2) &&
692
+ previous.error === spatial.distant.maxError &&
693
+ previous.world.equals(record.visual.matrixWorld) &&
694
+ previous.view.equals(this.camera.matrixWorldInverse) &&
695
+ previous.projection.equals(this.camera.projectionMatrix)) {
696
+ continue;
697
+ }
698
+ let fullCount = 0, distantCount = 0;
699
+ for (const instance of spatial.instances) {
700
+ matrix.compose(new THREE.Vector3(...instance.position), new THREE.Quaternion(...instance.rotation), new THREE.Vector3(...(instance.scale ?? [1, 1, 1])));
701
+ world.multiplyMatrices(record.visual.matrixWorld, matrix);
702
+ sphere.copy(full.geometry.boundingSphere).applyMatrix4(world);
703
+ if (!frustum.intersectsSphere(sphere)) {
704
+ continue;
705
+ }
706
+ center.copy(sphere.center).applyMatrix4(this.camera.matrixWorldInverse);
707
+ const nearestDepth = Math.max(0.001, -center.z - sphere.radius);
708
+ const errorPixels = (spatial.distant.maxError *
709
+ world.getMaxScaleOnAxis() *
710
+ pixelsPerUnit) /
711
+ nearestDepth;
712
+ if (errorPixels <= (spatial.distant.pixelError ?? 2)) {
713
+ distant.setMatrixAt(distantCount++, matrix);
714
+ }
715
+ else {
716
+ full.setMatrixAt(fullCount++, matrix);
717
+ }
718
+ }
719
+ full.count = fullCount;
720
+ distant.count = distantCount;
721
+ full.instanceMatrix.needsUpdate = true;
722
+ distant.instanceMatrix.needsUpdate = true;
723
+ this.instanceDetail.set(full, {
724
+ instances: spatial.instances,
725
+ geometry: full.geometry,
726
+ height: this.height,
727
+ pixelRatio: this.pixelRatio,
728
+ pixelError: spatial.distant.pixelError ?? 2,
729
+ error: spatial.distant.maxError,
730
+ world: record.visual.matrixWorld.clone(),
731
+ view: this.camera.matrixWorldInverse.clone(),
732
+ projection: this.camera.projectionMatrix.clone()
733
+ });
734
+ }
735
+ }
736
+ replaceContent(record, content) {
737
+ if (record.content) {
738
+ disposeObject(record.content);
739
+ }
740
+ record.content = content;
741
+ record.visual.add(content);
742
+ }
743
+ detach(record) {
744
+ if (record.parent) {
745
+ record.parent.children.splice(record.parent.children.indexOf(record), 1);
746
+ }
747
+ record.parent = null;
748
+ record.visual.removeFromParent();
749
+ }
750
+ remove(record) {
751
+ if (record === this.root) {
752
+ throw new Error('Use destroy to release the engine root');
753
+ }
754
+ this.detach(record);
755
+ for (const child of [...record.children]) {
756
+ this.detach(child);
757
+ }
758
+ disposeObject(record.visual);
759
+ this.objects.delete(record.handle);
760
+ }
761
+ validateSize(width, height) {
762
+ if (!Number.isFinite(width) ||
763
+ !Number.isFinite(height) ||
764
+ width <= 0 ||
765
+ height <= 0 ||
766
+ width > 16384 ||
767
+ height > 16384) {
768
+ throw new Error('Invalid surface size');
769
+ }
770
+ }
771
+ resize(width, height) {
772
+ this.validateSize(width, height);
773
+ this.width = width;
774
+ this.height = height;
775
+ this.requireDriver().setSize(width, height);
776
+ this.bloom?.setSize(width, height, this.pixelRatio);
777
+ this.camera.aspect = width / height;
778
+ this.camera.updateProjectionMatrix();
779
+ this.screenCamera.right = width;
780
+ this.screenCamera.bottom = height;
781
+ this.screenCamera.updateProjectionMatrix();
782
+ }
783
+ syncProjection() {
784
+ let cameraCount = 0;
785
+ const walk = (record, visible, screenParent) => {
786
+ const shown = visible &&
787
+ record.properties.visible !== false &&
788
+ record.properties.renderable !== false;
789
+ record.visual.visible = shown;
790
+ if (record.spatial) {
791
+ this.scene.add(record.visual);
792
+ if (record.spatial.kind === 'camera' && shown) {
793
+ if (++cameraCount > 1) {
794
+ throw new Error('Only one active spatial camera is supported');
795
+ }
796
+ const camera = record.spatial;
797
+ this.camera.position.fromArray(camera.position);
798
+ this.camera.lookAt(...camera.target);
799
+ this.camera.fov = camera.fov;
800
+ this.camera.near = camera.near;
801
+ this.camera.far = camera.far;
802
+ this.camera.updateProjectionMatrix();
803
+ }
804
+ }
805
+ else {
806
+ screenParent.add(record.visual);
807
+ }
808
+ record.children.forEach((child) => walk(child, shown, record.spatial ? screenParent : record.visual));
809
+ };
810
+ for (const record of this.objects.values()) {
811
+ record.visual.removeFromParent();
812
+ }
813
+ if (this.root) {
814
+ walk(this.root, true, this.screen);
815
+ }
816
+ this.scene.updateMatrixWorld(true);
817
+ this.screen.updateMatrixWorld(true);
818
+ this.camera.updateMatrixWorld(true);
819
+ this.screenCamera.updateMatrixWorld(true);
820
+ }
821
+ pickScreen(point) {
822
+ if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
823
+ throw new Error('Invalid screen point');
824
+ }
825
+ if (point.x < 0 ||
826
+ point.y < 0 ||
827
+ point.x >= this.width ||
828
+ point.y >= this.height) {
829
+ return null;
830
+ }
831
+ const ray = new THREE.Raycaster();
832
+ const screenPoint = new THREE.Vector2((point.x / this.width) * 2 - 1, 1 - (point.y / this.height) * 2);
833
+ ray.setFromCamera(screenPoint, this.screenCamera);
834
+ const screenRecords = [...this.objects.values()].filter((record) => !record.spatial &&
835
+ record.type === 'graphics' &&
836
+ record.visual.visible &&
837
+ record.visual.parent !== null &&
838
+ record.properties.eventMode !== 'none');
839
+ const screenHits = ray.intersectObjects(screenRecords.map((record) => record.visual), true);
840
+ for (const intersection of screenHits) {
841
+ for (let visual = intersection.object; visual; visual = visual.parent) {
842
+ const record = screenRecords.find((item) => item.visual === visual);
843
+ if (record) {
844
+ return record.handle;
845
+ }
846
+ }
847
+ }
848
+ return null;
849
+ }
850
+ pick(point) {
851
+ const result = this.spatialQuery({ type: 'spatial-pick', point });
852
+ if (result.type !== 'spatial-pick') {
853
+ throw new Error('Invalid picking result');
854
+ }
855
+ return result.overlay ?? result.hit?.object ?? null;
856
+ }
857
+ vector(value) {
858
+ return [value.x, value.y, value.z];
859
+ }
860
+ point(value) {
861
+ if (!Array.isArray(value) ||
862
+ value.length !== 3 ||
863
+ !value.every(Number.isFinite)) {
864
+ throw new Error('Invalid spatial point');
865
+ }
866
+ return new THREE.Vector3(...value);
867
+ }
868
+ spatialRecords() {
869
+ const records = [];
870
+ const visit = (record) => {
871
+ records.push(record);
872
+ record.children.forEach(visit);
873
+ };
874
+ if (this.root) {
875
+ visit(this.root);
876
+ }
877
+ return records;
878
+ }
879
+ spatialObject(handle) {
880
+ const record = this.owned(handle);
881
+ if (!this.spatialRecords().includes(record)) {
882
+ throw new Error('Detached spatial object');
883
+ }
884
+ return record;
885
+ }
886
+ spatialMatrix(record, index, world) {
887
+ const matrix = world
888
+ ? record.visual.matrixWorld.clone()
889
+ : new THREE.Matrix4();
890
+ if (index !== undefined) {
891
+ const instances = record.spatial?.kind === 'mesh' ? record.spatial.instances : undefined;
892
+ if (!Number.isInteger(index) ||
893
+ index < 0 ||
894
+ !instances ||
895
+ index >= instances.length) {
896
+ throw new Error('Invalid source instance index');
897
+ }
898
+ const instance = instances[index];
899
+ matrix.multiply(new THREE.Matrix4().compose(new THREE.Vector3(...instance.position), new THREE.Quaternion(...instance.rotation), new THREE.Vector3(...(instance.scale ?? [1, 1, 1]))));
900
+ }
901
+ return matrix;
902
+ }
903
+ spatialQuery(query) {
904
+ if (query.type === 'spatial-pick') {
905
+ const ray = this.spatialQuery({ type: 'spatial-ray', point: query.point });
906
+ if (ray.type !== 'spatial-ray') {
907
+ throw new Error('Invalid screen ray result');
908
+ }
909
+ if (!ray.ray) {
910
+ return { type: 'spatial-pick', overlay: null, hit: null };
911
+ }
912
+ const overlay = this.pickScreen(query.point);
913
+ return {
914
+ type: 'spatial-pick',
915
+ overlay,
916
+ hit: overlay ? null : (this.spatialHits(ray.ray)[0] ?? null)
917
+ };
918
+ }
919
+ if (query.type === 'spatial-project') {
920
+ const point = this.point(query.point);
921
+ const clip = new THREE.Vector4(point.x, point.y, point.z, 1)
922
+ .applyMatrix4(this.camera.matrixWorldInverse)
923
+ .applyMatrix4(this.camera.projectionMatrix);
924
+ if (clip.w === 0) {
925
+ return {
926
+ type: 'spatial-projection',
927
+ point: null,
928
+ depth: null,
929
+ inFrustum: false
930
+ };
931
+ }
932
+ const x = clip.x / clip.w, y = clip.y / clip.w, z = clip.z / clip.w;
933
+ if (![x, y, z].every(Number.isFinite)) {
934
+ throw new Error('Nonfinite spatial projection');
935
+ }
936
+ return {
937
+ type: 'spatial-projection',
938
+ point: {
939
+ x: ((x + 1) * this.width) / 2,
940
+ y: ((1 - y) * this.height) / 2
941
+ },
942
+ depth: z,
943
+ inFrustum: clip.w > 0 && Math.abs(x) <= 1 && Math.abs(y) <= 1 && Math.abs(z) <= 1
944
+ };
945
+ }
946
+ if (query.type === 'spatial-ray') {
947
+ const { x, y } = query.point;
948
+ if (![x, y].every(Number.isFinite)) {
949
+ throw new Error('Invalid surface point');
950
+ }
951
+ if (x < 0 || y < 0 || x >= this.width || y >= this.height) {
952
+ return { type: 'spatial-ray', ray: null };
953
+ }
954
+ const ray = new THREE.Raycaster();
955
+ ray.setFromCamera(new THREE.Vector2((x / this.width) * 2 - 1, 1 - (y / this.height) * 2), this.camera);
956
+ return {
957
+ type: 'spatial-ray',
958
+ ray: {
959
+ origin: this.vector(ray.ray.origin),
960
+ direction: this.vector(ray.ray.direction)
961
+ }
962
+ };
963
+ }
964
+ if (query.type === 'spatial-raycast') {
965
+ return { type: 'spatial-hits', hits: this.spatialHits(query.ray) };
966
+ }
967
+ const record = this.spatialObject(query.object);
968
+ if (query.type === 'spatial-convert') {
969
+ if (record.spatial?.kind !== 'mesh' ||
970
+ !['local', 'world'].includes(query.to)) {
971
+ throw new Error('Invalid spatial conversion');
972
+ }
973
+ const matrix = this.spatialMatrix(record, query.instanceIndex, true);
974
+ if (query.to === 'local') {
975
+ matrix.invert();
976
+ }
977
+ return {
978
+ type: 'spatial-point',
979
+ point: this.vector(this.point(query.point).applyMatrix4(matrix))
980
+ };
981
+ }
982
+ if (!['local', 'world'].includes(query.space)) {
983
+ throw new Error('Invalid bounds space');
984
+ }
985
+ if (query.instanceIndex !== undefined) {
986
+ this.spatialMatrix(record, query.instanceIndex, false);
987
+ }
988
+ if (record.spatial?.kind !== 'mesh' ||
989
+ !(record.content instanceof THREE.Mesh)) {
990
+ return { type: 'spatial-bounds', bounds: null };
991
+ }
992
+ const geometry = record.content.geometry;
993
+ if (!geometry.boundingBox) {
994
+ geometry.computeBoundingBox();
995
+ }
996
+ const local = geometry.boundingBox;
997
+ if (!local || local.isEmpty()) {
998
+ return { type: 'spatial-bounds', bounds: null };
999
+ }
1000
+ const result = new THREE.Box3();
1001
+ let indices = [undefined];
1002
+ if (query.instanceIndex !== undefined) {
1003
+ indices = [query.instanceIndex];
1004
+ }
1005
+ else if (record.spatial.instances) {
1006
+ indices = record.spatial.instances.map((_, index) => index);
1007
+ }
1008
+ for (const index of indices) {
1009
+ result.union(local
1010
+ .clone()
1011
+ .applyMatrix4(this.spatialMatrix(record, index, query.space === 'world')));
1012
+ }
1013
+ return {
1014
+ type: 'spatial-bounds',
1015
+ bounds: { min: this.vector(result.min), max: this.vector(result.max) }
1016
+ };
1017
+ }
1018
+ spatialHits(input) {
1019
+ const origin = this.point(input.origin), direction = this.point(input.direction);
1020
+ const length = direction.length();
1021
+ if (!Number.isFinite(length) || length === 0) {
1022
+ throw new Error('Invalid spatial ray direction');
1023
+ }
1024
+ direction.divideScalar(length);
1025
+ const ray = new THREE.Raycaster(origin, direction), hits = [];
1026
+ for (const record of this.spatialRecords()) {
1027
+ const spatial = record.spatial, content = record.content;
1028
+ if (spatial?.kind !== 'mesh' ||
1029
+ !spatial.selectable ||
1030
+ !record.visual.visible ||
1031
+ record.visual.parent !== this.scene ||
1032
+ !(content instanceof THREE.Mesh)) {
1033
+ continue;
1034
+ }
1035
+ // Borrow the owned full geometry/material. No GPU resource or LoD slot is created.
1036
+ const mesh = new THREE.Mesh(content.geometry, content.material);
1037
+ const indices = spatial.instances
1038
+ ? spatial.instances.map((_, index) => index)
1039
+ : [undefined];
1040
+ for (const index of indices) {
1041
+ mesh.matrixWorld.copy(this.spatialMatrix(record, index, true));
1042
+ const intersections = [];
1043
+ mesh.raycast(ray, intersections);
1044
+ intersections.sort((a, b) => a.distance - b.distance);
1045
+ const hit = intersections[0];
1046
+ if (!hit) {
1047
+ continue;
1048
+ }
1049
+ hits.push({
1050
+ object: record.handle,
1051
+ ...(index === undefined
1052
+ ? {}
1053
+ : {
1054
+ instanceIndex: index,
1055
+ ...(spatial.instances?.[index].id === undefined
1056
+ ? {}
1057
+ : { instanceId: spatial.instances[index].id })
1058
+ }),
1059
+ distance: hit.distance,
1060
+ point: this.vector(hit.point)
1061
+ });
1062
+ }
1063
+ }
1064
+ return hits.sort((a, b) => a.distance - b.distance);
1065
+ }
1066
+ paint(paint) {
1067
+ if (!paint || typeof paint !== 'object') {
1068
+ throw new Error('Invalid paint');
1069
+ }
1070
+ let base = { color: paint.color ?? 0xffffff, alpha: paint.alpha ?? 1 };
1071
+ if (paint.resource) {
1072
+ const stored = this.resources.get(paint.resource);
1073
+ if (!stored) {
1074
+ throw new Error('Foreign or destroyed resource handle');
1075
+ }
1076
+ base = { color: stored.color, alpha: paint.alpha ?? stored.alpha };
1077
+ }
1078
+ if (!Number.isFinite(base.alpha) || base.alpha < 0 || base.alpha > 1) {
1079
+ throw new Error('Invalid paint opacity');
1080
+ }
1081
+ return base;
1082
+ }
1083
+ attachPointerListeners(canvas) {
1084
+ const types = [
1085
+ 'pointerdown',
1086
+ 'pointermove',
1087
+ 'pointerup',
1088
+ 'pointercancel',
1089
+ 'pointerover',
1090
+ 'pointerout'
1091
+ ];
1092
+ for (const type of types) {
1093
+ const handler = (event) => {
1094
+ if (this.destroyed) {
1095
+ return;
1096
+ }
1097
+ const pointer = event, rect = canvas.getBoundingClientRect();
1098
+ if (rect.width <= 0 || rect.height <= 0) {
1099
+ return;
1100
+ }
1101
+ const position = {
1102
+ x: ((pointer.clientX - rect.left) * this.width) / rect.width,
1103
+ y: ((pointer.clientY - rect.top) * this.height) / rect.height
1104
+ };
1105
+ const result = this.query({ type: 'hit-test', point: position });
1106
+ this.dispatchInteraction({
1107
+ type,
1108
+ pointerId: pointer.pointerId ?? 0,
1109
+ button: pointer.button,
1110
+ buttons: pointer.buttons,
1111
+ position,
1112
+ modifiers: {
1113
+ altKey: pointer.altKey,
1114
+ ctrlKey: pointer.ctrlKey,
1115
+ metaKey: pointer.metaKey,
1116
+ shiftKey: pointer.shiftKey
1117
+ },
1118
+ target: result.type === 'hit' ? result.target : null,
1119
+ timestamp: event.timeStamp
1120
+ });
1121
+ };
1122
+ canvas.addEventListener(type, handler);
1123
+ this.pointerDisposers.push(() => canvas.removeEventListener(type, handler));
1124
+ }
1125
+ }
1126
+ }
1127
+ //# sourceMappingURL=three-engine.js.map