@iwsdk/create 0.4.2 → 0.5.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 (107) hide show
  1. package/README.md +103 -41
  2. package/dist/cli.js +1003 -3418
  3. package/dist/guidance/agents/.agents/skills/iwsdk-debug/SKILL.md +96 -0
  4. package/dist/guidance/agents/.agents/skills/iwsdk-depth-occlusion/SKILL.md +135 -0
  5. package/dist/guidance/agents/.agents/skills/iwsdk-grab/SKILL.md +129 -0
  6. package/dist/guidance/agents/.agents/skills/iwsdk-physics/SKILL.md +92 -0
  7. package/dist/guidance/agents/.agents/skills/iwsdk-physics/references/component-reference.md +154 -0
  8. package/dist/guidance/agents/.agents/skills/iwsdk-physics/references/tuning-and-config.md +88 -0
  9. package/dist/guidance/agents/.agents/skills/iwsdk-physics/references/workflows.md +303 -0
  10. package/dist/guidance/agents/.agents/skills/iwsdk-planner/SKILL.md +364 -0
  11. package/dist/guidance/agents/.agents/skills/iwsdk-planner/references/api-reference.md +1489 -0
  12. package/dist/guidance/agents/.agents/skills/iwsdk-planner/references/build-milestones.md +241 -0
  13. package/dist/guidance/agents/.agents/skills/iwsdk-planner/references/design-deck.md +101 -0
  14. package/dist/guidance/agents/.agents/skills/iwsdk-planner/references/grounding.md +176 -0
  15. package/dist/guidance/agents/.agents/skills/iwsdk-planner/references/ideation.md +156 -0
  16. package/dist/guidance/agents/.agents/skills/iwsdk-planner/references/verification.md +199 -0
  17. package/dist/guidance/agents/.agents/skills/iwsdk-ray/SKILL.md +159 -0
  18. package/dist/guidance/agents/.agents/skills/iwsdk-scene-composer/SKILL.md +255 -0
  19. package/dist/guidance/agents/.agents/skills/iwsdk-scene-composer/agents/openai.yaml +5 -0
  20. package/dist/guidance/agents/.agents/skills/iwsdk-scene-composer/references/asset-authoring.md +295 -0
  21. package/dist/guidance/agents/.agents/skills/iwsdk-scene-composer/references/composition-patterns.md +243 -0
  22. package/dist/guidance/agents/.agents/skills/iwsdk-scene-composer/references/image-intake.md +191 -0
  23. package/dist/guidance/agents/.agents/skills/iwsdk-scene-composer/references/review-and-stop.md +99 -0
  24. package/dist/guidance/agents/.agents/skills/iwsdk-scene-composer/references/scene-format.md +458 -0
  25. package/dist/guidance/agents/.agents/skills/iwsdk-scene-composer/references/text-intake.md +82 -0
  26. package/dist/guidance/agents/.agents/skills/iwsdk-ui/SKILL.md +208 -0
  27. package/dist/guidance/claude/.claude/agents/iwsdk-project-code-reviewer.md +450 -0
  28. package/dist/guidance/claude/.claude/rules/assets-and-manifest.md +55 -0
  29. package/dist/guidance/claude/.claude/rules/ecs-api.md +102 -0
  30. package/dist/guidance/claude/.claude/rules/scene-json.md +64 -0
  31. package/dist/guidance/claude/.claude/rules/uikitml.md +60 -0
  32. package/dist/guidance/claude/.claude/settings.json +19 -0
  33. package/dist/guidance/claude/.claude/skills/iwsdk-debug/SKILL.md +96 -0
  34. package/dist/guidance/claude/.claude/skills/iwsdk-depth-occlusion/SKILL.md +135 -0
  35. package/dist/guidance/claude/.claude/skills/iwsdk-grab/SKILL.md +129 -0
  36. package/dist/guidance/claude/.claude/skills/iwsdk-physics/SKILL.md +92 -0
  37. package/dist/guidance/claude/.claude/skills/iwsdk-physics/references/component-reference.md +154 -0
  38. package/dist/guidance/claude/.claude/skills/iwsdk-physics/references/tuning-and-config.md +88 -0
  39. package/dist/guidance/claude/.claude/skills/iwsdk-physics/references/workflows.md +303 -0
  40. package/dist/guidance/claude/.claude/skills/iwsdk-planner/SKILL.md +364 -0
  41. package/dist/guidance/claude/.claude/skills/iwsdk-planner/references/api-reference.md +1489 -0
  42. package/dist/guidance/claude/.claude/skills/iwsdk-planner/references/build-milestones.md +241 -0
  43. package/dist/guidance/claude/.claude/skills/iwsdk-planner/references/design-deck.md +101 -0
  44. package/dist/guidance/claude/.claude/skills/iwsdk-planner/references/grounding.md +176 -0
  45. package/dist/guidance/claude/.claude/skills/iwsdk-planner/references/ideation.md +156 -0
  46. package/dist/guidance/claude/.claude/skills/iwsdk-planner/references/verification.md +199 -0
  47. package/dist/guidance/claude/.claude/skills/iwsdk-ray/SKILL.md +159 -0
  48. package/dist/guidance/claude/.claude/skills/iwsdk-scene-composer/SKILL.md +255 -0
  49. package/dist/guidance/claude/.claude/skills/iwsdk-scene-composer/agents/openai.yaml +5 -0
  50. package/dist/guidance/claude/.claude/skills/iwsdk-scene-composer/references/asset-authoring.md +295 -0
  51. package/dist/guidance/claude/.claude/skills/iwsdk-scene-composer/references/composition-patterns.md +243 -0
  52. package/dist/guidance/claude/.claude/skills/iwsdk-scene-composer/references/image-intake.md +191 -0
  53. package/dist/guidance/claude/.claude/skills/iwsdk-scene-composer/references/review-and-stop.md +99 -0
  54. package/dist/guidance/claude/.claude/skills/iwsdk-scene-composer/references/scene-format.md +458 -0
  55. package/dist/guidance/claude/.claude/skills/iwsdk-scene-composer/references/text-intake.md +82 -0
  56. package/dist/guidance/claude/.claude/skills/iwsdk-ui/SKILL.md +208 -0
  57. package/dist/guidance/claude/CLAUDE.md +142 -0
  58. package/dist/guidance/codex/.codex/config.toml +2 -0
  59. package/dist/guidance/common/AGENTS.md +151 -0
  60. package/dist/guidance/copilot/.github/instructions/assets-and-manifest.instructions.md +52 -0
  61. package/dist/guidance/copilot/.github/instructions/ecs-api.instructions.md +100 -0
  62. package/dist/guidance/copilot/.github/instructions/scene-json.instructions.md +63 -0
  63. package/dist/guidance/copilot/.github/instructions/uikitml.instructions.md +59 -0
  64. package/dist/guidance/cursor/.cursor/rules/assets-and-manifest.mdc +57 -0
  65. package/dist/guidance/cursor/.cursor/rules/ecs-api.mdc +104 -0
  66. package/dist/guidance/cursor/.cursor/rules/scene-json.mdc +66 -0
  67. package/dist/guidance/cursor/.cursor/rules/uikitml.mdc +62 -0
  68. package/dist/guidance/scoped-agents/public/scenes/AGENTS.md +63 -0
  69. package/dist/guidance/scoped-agents/public/ui/AGENTS.md +59 -0
  70. package/dist/guidance/scoped-agents/src/AGENTS.md +149 -0
  71. package/dist/template/common/README.md +13 -0
  72. package/dist/template/common/gitignore.template +45 -0
  73. package/dist/template/common/index.html +16 -0
  74. package/dist/template/common/nvmrc.template +1 -0
  75. package/dist/template/common/public/audio/chime.mp3 +0 -0
  76. package/dist/template/common/public/gltf/webxr-banner/banner.gltf +68 -0
  77. package/dist/template/common/public/textures/webxr.png +0 -0
  78. package/dist/template/common/public/ui/welcome.uikitml +98 -0
  79. package/dist/template/common/src/assets.ts +54 -0
  80. package/dist/template/common/src/components.ts +11 -0
  81. package/dist/template/common/src/index.ts +19 -0
  82. package/dist/template/common/src/panel.ts +38 -0
  83. package/dist/template/common/src/robot-component.ts +10 -0
  84. package/dist/template/common/src/robot.ts +38 -0
  85. package/dist/template/common/src/vite-env.d.ts +2 -0
  86. package/dist/template/common/tsconfig.json +15 -0
  87. package/dist/template/common/vite.config.ts +27 -0
  88. package/dist/template/common-js/README.md +13 -0
  89. package/dist/template/common-js/gitignore.template +45 -0
  90. package/dist/template/common-js/index.html +16 -0
  91. package/dist/template/common-js/nvmrc.template +1 -0
  92. package/dist/template/common-js/public/audio/chime.mp3 +0 -0
  93. package/dist/template/common-js/public/gltf/webxr-banner/banner.gltf +68 -0
  94. package/dist/template/common-js/public/textures/webxr.png +0 -0
  95. package/dist/template/common-js/public/ui/welcome.uikitml +98 -0
  96. package/dist/template/common-js/src/assets.js +45 -0
  97. package/dist/template/common-js/src/components.js +9 -0
  98. package/dist/template/common-js/src/index.js +14 -0
  99. package/dist/template/common-js/src/panel.js +31 -0
  100. package/dist/template/common-js/src/robot-component.js +8 -0
  101. package/dist/template/common-js/src/robot.js +37 -0
  102. package/dist/template/common-js/vite.config.js +25 -0
  103. package/dist/template/scenes/ar.iwsdk.scene.json +96 -0
  104. package/dist/template/scenes/immersive.iwsdk.scene.json +109 -0
  105. package/package.json +23 -17
  106. package/scripts/verify-release-ready.mjs +76 -0
  107. package/LICENSE +0 -21
@@ -0,0 +1,1489 @@
1
+ # IWSDK API Reference & Best Practices
2
+
3
+ Ground-truth API patterns for IWSDK app development. This file backs the
4
+ `iwsdk-planner` skill: load it whenever you are grounding a plan to real APIs,
5
+ writing IWSDK code, or reviewing it. It contains no process guidance — the
6
+ pipeline lives in `SKILL.md`; phase playbooks live in the sibling
7
+ `references/*.md` files.
8
+
9
+ **Version sensitivity:** this reference tracks the SDK at the time the skill
10
+ shipped. For any API your plan depends on, verify the signature against the
11
+ _installed_ package (`node_modules/@iwsdk/core/dist/**/*.d.ts`) — newer
12
+ methods (e.g. `GrabSystem.forceRelease`) may not exist in the version your
13
+ app has installed, and vice versa.
14
+
15
+ ## Core Architecture
16
+
17
+ IWSDK is built on three pillars:
18
+
19
+ 1. **ECS (Entity Component System)** via `elics` library
20
+ 2. **Reactive Signals** via `@preact/signals-core`
21
+ 3. **Three.js Integration** with zero-copy transform binding (super-three v0.181.0)
22
+
23
+ IWSDK is a 3D web framework with first-class XR support. `World.create()` always creates a persistent `world.player` origin and keeps `world.camera` under it, even when `xr: false` is used for browser-only apps. For first-person browser movement, move `world.player`; for orbit, editor, product, cinematic, or third-person cameras, it is fine to keep `world.player` at the origin and drive `world.camera`. Remember that `world.camera.position` is local to `world.player`, so use `camera.getWorldPosition(...)` when world-space viewer position matters.
24
+
25
+ ### Project manifest authority
26
+
27
+ Generated 0.5 projects keep JSON-safe scene, module, XR, render, input, feature,
28
+ and emulator settings in `iwsdk.config.json`. `src/index.ts` imports
29
+ `virtual:iwsdk-project`, passes it to `World.create()`, and retains explicit
30
+ system registration. The direct `World.create(container, WorldOptions)` shapes
31
+ below remain the low-level API reference; when editing a generated project,
32
+ translate their serializable fields into the manifest instead of creating a
33
+ second configuration authority in code.
34
+
35
+ Asset/component modules are selected by extensionless manifest paths and are
36
+ shared by runtime and editor. Build local public URLs from
37
+ `import.meta.env.BASE_URL`; literal `./...` URLs resolve against the managed
38
+ editor route during editor use and are not a safe project-wide convention.
39
+
40
+ Use `input.canvasPointerEvents` for browser mouse/touch canvas events. Browser canvas pointers and XR rays both feed Three/Object3D pointer events and ECS `Hovered`/`Pressed` tags on `Interactable`/`RayInteractable` entities. XR-specific input is available at `world.input.xr`; keyboard and standard browser gamepads live at `world.input.keyboard` and `world.input.browserGamepads`. Reusable systems should prefer `world.input.actions` for intent such as `locomotion.move` or `locomotion.jump`; opt into browser locomotion bindings with `features.locomotion.browserControls`.
41
+
42
+ ## Critical Best Practices
43
+
44
+ ### 1. Keep Systems Stateless
45
+
46
+ Systems should NOT store arrays of entities or maintain entity references. Use queries instead.
47
+
48
+ ```typescript
49
+ // ❌ BAD - Storing entity references
50
+ export class BadSystem extends createSystem({
51
+ items: { required: [MyComponent] },
52
+ }) {
53
+ private myEntities: Entity[] = []; // DON'T DO THIS
54
+
55
+ init() {
56
+ this.queries.items.subscribe('qualify', (entity) => {
57
+ this.myEntities.push(entity); // BAD: manually tracking entities
58
+ });
59
+ }
60
+ }
61
+
62
+ // ✅ GOOD - Use queries for entity access
63
+ export class GoodSystem extends createSystem({
64
+ items: { required: [MyComponent] },
65
+ }) {
66
+ update() {
67
+ // Query always gives current matching entities
68
+ for (const entity of this.queries.items.entities) {
69
+ // Process entity
70
+ }
71
+ }
72
+ }
73
+ ```
74
+
75
+ **Exception:** Scratch variables for temporary per-frame calculations are OK.
76
+
77
+ ### 2. Use Query Subscribe/Unsubscribe for Reactive Programming
78
+
79
+ Instead of polling or storing state, react to entity lifecycle events:
80
+
81
+ ```typescript
82
+ export class ReactiveSystem extends createSystem({
83
+ interactables: { required: [Interactable, Transform] },
84
+ }) {
85
+ init() {
86
+ // React when entities enter the query
87
+ this.queries.interactables.subscribe('qualify', (entity) => {
88
+ this.setupEventListeners(entity);
89
+ });
90
+
91
+ // React when entities leave the query
92
+ this.queries.interactables.subscribe('disqualify', (entity) => {
93
+ this.cleanupEventListeners(entity);
94
+ });
95
+ }
96
+ }
97
+ ```
98
+
99
+ ### 3. Use Signals for Reactive State
100
+
101
+ IWSDK uses `@preact/signals-core`. Prefer signals over manual state tracking:
102
+
103
+ ```typescript
104
+ // System config properties are automatically signals
105
+ export class MySystem extends createSystem(
106
+ {},
107
+ {
108
+ speed: { type: Types.Float32, default: 5.0 },
109
+ jumpHeight: { type: Types.Float32, default: 2.0 },
110
+ },
111
+ ) {
112
+ init() {
113
+ // Subscribe to config changes reactively
114
+ this.cleanupFuncs.push(
115
+ this.config.speed.subscribe((newSpeed) => {
116
+ console.log('Speed changed:', newSpeed);
117
+ }),
118
+ );
119
+ }
120
+
121
+ update(delta) {
122
+ // Read signal value with .peek() in update loops (no subscription overhead)
123
+ const currentSpeed = this.config.speed.peek();
124
+ }
125
+ }
126
+ ```
127
+
128
+ ### World Globals Signals for Cross-System Communication
129
+
130
+ Store signals in `world.globals` for state that multiple systems need to read/write:
131
+
132
+ ```typescript
133
+ // In index.ts (initialization)
134
+ import { signal } from '@preact/signals-core';
135
+
136
+ (world.globals as Record<string, unknown>).gamePaused = signal(true);
137
+ (world.globals as Record<string, unknown>).audioMasterVolume = signal(1.0);
138
+
139
+ // In any system (reading with peek() in hot paths)
140
+ const gamePaused = (this.globals.gamePaused as Signal<boolean>).peek();
141
+
142
+ // In any system (writing)
143
+ const gamePausedSignal = this.globals.gamePaused as Signal<boolean>;
144
+ gamePausedSignal.value = !gamePausedSignal.value;
145
+ ```
146
+
147
+ ### 4. Component Types (Complete List)
148
+
149
+ ```typescript
150
+ import { Types } from '@iwsdk/core';
151
+
152
+ Types.Float32; // 32-bit float
153
+ Types.Float64; // 64-bit float (for physics engine refs)
154
+ Types.Int8; // 8-bit signed integer
155
+ Types.Int16; // 16-bit signed integer
156
+ Types.Int32; // 32-bit signed integer
157
+ Types.Boolean; // true/false
158
+ Types.String; // text
159
+ Types.FilePath; // file path string (asset-referencing fields like AudioSource.src)
160
+ Types.Vec2; // [x, y] - 2 floats
161
+ Types.Vec3; // [x, y, z] - 3 floats
162
+ Types.Vec4; // [x, y, z, w] - 4 floats (quaternions)
163
+ Types.Color; // [r, g, b, a] - 4 floats (RGBA)
164
+ Types.Entity; // Reference to another entity
165
+ Types.Enum; // Enumerated value
166
+ Types.Object; // Any JS object (avoid if possible - not optimized)
167
+ ```
168
+
169
+ ### 5. Component Design Patterns
170
+
171
+ ```typescript
172
+ import { createComponent, Types } from '@iwsdk/core';
173
+
174
+ // Tag component (no data, just marks entities)
175
+ export const Interactable = createComponent('Interactable', {}, '');
176
+
177
+ // Data component with proper types
178
+ export const Health = createComponent('Health', {
179
+ current: { type: Types.Float32, default: 100 },
180
+ max: { type: Types.Float32, default: 100 },
181
+ });
182
+
183
+ // With enums
184
+ export const State = createComponent('State', {
185
+ mode: {
186
+ type: Types.Enum,
187
+ enum: { Idle: 'idle', Moving: 'moving', Attacking: 'attacking' },
188
+ default: 'idle',
189
+ },
190
+ });
191
+
192
+ // With vectors (stored as TypedArrays for performance)
193
+ export const Velocity = createComponent('Velocity', {
194
+ linear: { type: Types.Vec3, default: [0, 0, 0] },
195
+ angular: { type: Types.Vec3, default: [0, 0, 0] },
196
+ });
197
+
198
+ // With colors (RGBA, 4 components)
199
+ export const Tint = createComponent('Tint', {
200
+ color: { type: Types.Color, default: [1, 1, 1, 1] },
201
+ });
202
+ ```
203
+
204
+ ### 6. Query Patterns with Filters
205
+
206
+ ```typescript
207
+ export class DamageSystem extends createSystem({
208
+ // Basic query
209
+ enemies: { required: [Enemy] },
210
+
211
+ // With exclusions
212
+ vulnerableEnemies: {
213
+ required: [Enemy, Health],
214
+ excluded: [Invulnerable, Shield],
215
+ },
216
+
217
+ // With value filters
218
+ lowHealth: {
219
+ required: [Health],
220
+ where: [lt(Health, 'current', 20)],
221
+ },
222
+
223
+ // Complex filters
224
+ activeBosses: {
225
+ required: [Boss, Health],
226
+ where: [gt(Health, 'current', 0), eq(State, 'mode', 'attacking')],
227
+ },
228
+ }) {}
229
+
230
+ // Available filter operators: eq, ne, lt, le, gt, ge, isin, nin
231
+ ```
232
+
233
+ ### 7. System Interface (Full)
234
+
235
+ ```typescript
236
+ interface System {
237
+ // World access
238
+ world: World;
239
+
240
+ // Query results
241
+ queries: Record<string, Query>;
242
+
243
+ // Reactive config (auto-created from schema)
244
+ config: { [key]: Signal };
245
+
246
+ // Cleanup registration
247
+ cleanupFuncs: Array<() => void>;
248
+
249
+ // XR/Player access
250
+ player: XROrigin;
251
+ input: InputManager; // XR devices at input.xr, keyboard at input.keyboard, browser gamepads at input.browserGamepads, actions at input.actions
252
+
253
+ // Three.js access
254
+ scene: Scene;
255
+ camera: PerspectiveCamera;
256
+ renderer: WebGLRenderer;
257
+
258
+ // XR state
259
+ visibilityState: Signal<VisibilityState>;
260
+ xrManager: WebXRManager;
261
+ xrFrame: XRFrame;
262
+
263
+ // Shared state
264
+ globals: Record<string, any>;
265
+
266
+ // Entity creation helpers
267
+ createEntity(): Entity;
268
+ createTransformEntity(object?: Object3D, parent?: Entity): Entity;
269
+
270
+ // Lifecycle
271
+ init(): void;
272
+ update(delta: number, time: number): void;
273
+ play(): void;
274
+ stop(): void;
275
+ }
276
+ ```
277
+
278
+ ### 8. XR Input System (Critical)
279
+
280
+ ```typescript
281
+ update() {
282
+ const leftGamepad = this.input.xr.gamepads.left;
283
+ const rightGamepad = this.input.xr.gamepads.right;
284
+
285
+ // Button states
286
+ leftGamepad?.getButtonPressed(InputComponent.Trigger); // Currently pressed
287
+ leftGamepad?.getButtonDown(InputComponent.Trigger); // Just pressed this frame
288
+ leftGamepad?.getButtonUp(InputComponent.Trigger); // Just released this frame
289
+ leftGamepad?.getButtonValue(InputComponent.Trigger); // Analog value 0-1
290
+ leftGamepad?.getButtonTouched(InputComponent.Trigger); // Finger touching
291
+
292
+ // Special select button (primary action)
293
+ leftGamepad?.getSelectStart(); // Primary button just pressed
294
+ leftGamepad?.getSelectEnd(); // Primary button just released
295
+ leftGamepad?.getSelecting(); // Primary button held
296
+
297
+ // Thumbstick/touchpad axes
298
+ const axes = leftGamepad?.getAxesValues(InputComponent.Thumbstick);
299
+ console.log(axes?.x, axes?.y); // -1 to 1 range
300
+
301
+ // Directional axes state
302
+ leftGamepad?.getAxesEnteringUp(InputComponent.Thumbstick);
303
+ leftGamepad?.getAxesEnteringDown(InputComponent.Thumbstick);
304
+ leftGamepad?.getAxesEnteringLeft(InputComponent.Thumbstick);
305
+ leftGamepad?.getAxesEnteringRight(InputComponent.Thumbstick);
306
+ }
307
+ ```
308
+
309
+ **InputComponent Enum:**
310
+
311
+ ```typescript
312
+ import { InputComponent } from '@iwsdk/core';
313
+
314
+ InputComponent.Trigger; // 'xr-standard-trigger'
315
+ InputComponent.Squeeze; // 'xr-standard-squeeze'
316
+ InputComponent.Touchpad; // 'xr-standard-touchpad'
317
+ InputComponent.Thumbstick; // 'xr-standard-thumbstick'
318
+ InputComponent.A_Button; // 'a-button'
319
+ InputComponent.B_Button; // 'b-button'
320
+ InputComponent.X_Button; // 'x-button'
321
+ InputComponent.Y_Button; // 'y-button'
322
+ InputComponent.Thumbrest; // 'thumbrest'
323
+ InputComponent.Menu; // 'menu'
324
+ ```
325
+
326
+ ### 9. Player/XROrigin Access (Critical)
327
+
328
+ ```typescript
329
+ // Accessing player spatial hierarchy in a system
330
+ this.player; // XROrigin (Group) - VR rig root
331
+ this.player.head; // Head tracking (viewer pose)
332
+ this.player.raySpaces.left; // Left controller ray origin
333
+ this.player.raySpaces.right; // Right controller ray origin
334
+ this.player.gripSpaces.left; // Left controller grip position
335
+ this.player.gripSpaces.right; // Right controller grip position
336
+ this.player.secondaryRaySpaces.left; // Secondary left ray
337
+ this.player.secondaryRaySpaces.right; // Secondary right ray
338
+ this.player.secondaryGripSpaces.left; // Secondary left grip
339
+ this.player.secondaryGripSpaces.right; // Secondary right grip
340
+
341
+ // Getting world positions
342
+ const headPos = new Vector3();
343
+ this.player.head.getWorldPosition(headPos);
344
+
345
+ const rightHandPos = new Vector3();
346
+ this.player.gripSpaces.right.getWorldPosition(rightHandPos);
347
+ ```
348
+
349
+ ### 10. Audio System
350
+
351
+ ```typescript
352
+ import {
353
+ AudioSource,
354
+ PlaybackMode,
355
+ AudioUtils,
356
+ InstanceStealPolicy,
357
+ DistanceModel,
358
+ } from '@iwsdk/core';
359
+
360
+ // Adding audio to an entity
361
+ entity.addComponent(AudioSource, {
362
+ src: 'audio/click.mp3',
363
+ positional: true, // 3D spatial audio
364
+ loop: false,
365
+ autoplay: false,
366
+ volume: 0.5,
367
+ refDistance: 1,
368
+ rolloffFactor: 1,
369
+ maxDistance: 10000,
370
+ maxInstances: 1,
371
+ playbackMode: PlaybackMode.Restart,
372
+ });
373
+
374
+ // Playing audio
375
+ AudioUtils.play(entity);
376
+ ```
377
+
378
+ **PlaybackMode:**
379
+
380
+ ```typescript
381
+ PlaybackMode.Restart; // Stop current and restart
382
+ PlaybackMode.Overlap; // Always start new instance
383
+ PlaybackMode.Ignore; // Ignore if already playing
384
+ PlaybackMode.FadeRestart; // Fade out current, start new
385
+ ```
386
+
387
+ **InstanceStealPolicy:**
388
+
389
+ ```typescript
390
+ InstanceStealPolicy.Oldest; // Steal oldest instance
391
+ InstanceStealPolicy.Quietest; // Steal quietest instance
392
+ InstanceStealPolicy.Furthest; // Steal furthest instance
393
+ ```
394
+
395
+ **DistanceModel:**
396
+
397
+ ```typescript
398
+ DistanceModel.Linear; // Linear falloff
399
+ DistanceModel.Inverse; // Inverse falloff
400
+ DistanceModel.Exponential; // Exponential falloff
401
+ ```
402
+
403
+ ### 11. Physics System
404
+
405
+ **PhysicsBody - motion properties:**
406
+
407
+ ```typescript
408
+ import { PhysicsBody, PhysicsState, PhysicsSystem } from '@iwsdk/core';
409
+
410
+ entity.addComponent(PhysicsBody, {
411
+ state: PhysicsState.Dynamic, // Static, Dynamic, Kinematic
412
+ linearDamping: 0.0,
413
+ angularDamping: 0.0,
414
+ gravityFactor: 1.0,
415
+ centerOfMass: [Infinity, Infinity, Infinity], // Infinity = auto-compute
416
+ });
417
+ ```
418
+
419
+ **PhysicsState:**
420
+
421
+ ```typescript
422
+ PhysicsState.Static; // Immovable (walls, floors)
423
+ PhysicsState.Dynamic; // Affected by physics
424
+ PhysicsState.Kinematic; // Moved by code, affects others
425
+ ```
426
+
427
+ **PhysicsShape - collision shape AND material properties:**
428
+
429
+ ```typescript
430
+ import { PhysicsShape, PhysicsShapeType } from '@iwsdk/core';
431
+
432
+ entity.addComponent(PhysicsShape, {
433
+ shape: PhysicsShapeType.Auto, // Auto-detect from geometry
434
+ dimensions: [0, 0, 0], // Shape-specific dimensions
435
+ density: 1.0, // Affects mass
436
+ restitution: 0.0, // Bounciness (0-1)
437
+ friction: 0.5, // Sliding behavior
438
+ });
439
+ ```
440
+
441
+ **PhysicsShapeType:**
442
+
443
+ ```typescript
444
+ PhysicsShapeType.Sphere; // dimensions[0] = radius
445
+ PhysicsShapeType.Box; // dimensions = [width, height, depth]
446
+ PhysicsShapeType.Cylinder; // dimensions[0] = radius, dimensions[1] = height
447
+ PhysicsShapeType.Capsules; // dimensions[0] = radius, dimensions[1] = total height (>= 2 * radius)
448
+ PhysicsShapeType.ConvexHull; // Convex wrapper around mesh
449
+ PhysicsShapeType.TriMesh; // Exact mesh geometry (expensive)
450
+ PhysicsShapeType.Auto; // Auto-detect from Three.js geometry
451
+ ```
452
+
453
+ **Teleporting / re-posing an existing body:** use the live physics system rather than
454
+ removing and re-adding components. It updates Havok and the Object3D immediately and
455
+ clears velocity by default:
456
+
457
+ ```typescript
458
+ const physics = world.getSystem(PhysicsSystem);
459
+ physics.setBodyTransform(entity, {
460
+ position: homePosition,
461
+ quaternion: homeQuaternion,
462
+ });
463
+ ```
464
+
465
+ Writing only the Transform of a dynamic body is clobbered by the next physics frame.
466
+ `gravityFactor`, `linearDamping`, and `angularDamping` are reactive; motion `state` and
467
+ shape construction still require deliberate body lifecycle handling.
468
+
469
+ ### 12. Grabbable Components
470
+
471
+ ```typescript
472
+ import {
473
+ OneHandGrabbable,
474
+ TwoHandsGrabbable,
475
+ DistanceGrabbable,
476
+ MovementMode,
477
+ } from '@iwsdk/core';
478
+
479
+ // Basic single-hand grab
480
+ entity.addComponent(OneHandGrabbable, {});
481
+
482
+ // Constrained manipulation
483
+ entity.addComponent(OneHandGrabbable, {
484
+ rotate: true,
485
+ rotateMin: [0, -Math.PI, 0],
486
+ rotateMax: [0, Math.PI, 0],
487
+ translate: true,
488
+ translateMin: [-2, 0, -2],
489
+ translateMax: [2, 3, 2],
490
+ });
491
+
492
+ // Two-hand manipulation (with scaling)
493
+ entity.addComponent(TwoHandsGrabbable, {
494
+ rotate: true,
495
+ translate: true,
496
+ scale: true,
497
+ scaleMin: [0.5, 0.5, 0.5],
498
+ scaleMax: [2, 2, 2],
499
+ });
500
+
501
+ // ⚠️ One handle per entity: OneHandGrabbable, TwoHandsGrabbable, and
502
+ // DistanceGrabbable are MUTUALLY EXCLUSIVE on the same entity (GrabSystem
503
+ // creates a single Handle; near-grab denies ray pointers, distance-grab
504
+ // denies grab pointers). Pick one per entity — DistanceGrabbable with
505
+ // MoveTowardsTarget covers both near and far pickup via trigger.
506
+
507
+ // Distance grab
508
+ entity.addComponent(DistanceGrabbable, {
509
+ rotate: true,
510
+ translate: true,
511
+ scale: true,
512
+ movementMode: MovementMode.MoveTowardsTarget, // MoveTowardsTarget | MoveAtSource | RotateAtSource | MoveFromTarget
513
+ returnToOrigin: false, // Snap back when released
514
+ moveSpeedFactor: 0.1, // MoveTowardsTarget pull lerp: alpha = factor * delta * 100, NOT clamped — keep <= 0.03 if frames can hitch (background tabs/CI) or the pull overshoots and diverges
515
+ });
516
+
517
+ // Force-release / hand lookup (game reset, weapon swap, recoil, etc.)
518
+ import { GrabSystem } from '@iwsdk/core';
519
+ const grab = world.getSystem(GrabSystem);
520
+ grab.forceRelease(entity); // drop a held entity safely (no-op if not held)
521
+ const hand = grab.getHolderHand(entity); // 'left' | 'right' | null ('left' for two-hand grabs)
522
+ ```
523
+
524
+ ### 13. Environment/Lighting
525
+
526
+ ```typescript
527
+ import {
528
+ DomeGradient,
529
+ DomeTexture,
530
+ IBLGradient,
531
+ IBLTexture,
532
+ } from '@iwsdk/core';
533
+
534
+ // Gradient sky dome (RGBA colors - 4 components)
535
+ entity.addComponent(DomeGradient, {
536
+ sky: [0.2423, 0.6172, 0.8308, 1.0], // RGBA
537
+ equator: [0.6584, 0.7084, 0.7913, 1.0], // RGBA
538
+ ground: [0.807, 0.7758, 0.7454, 1.0], // RGBA
539
+ intensity: 1.0,
540
+ });
541
+
542
+ // HDR texture sky
543
+ entity.addComponent(DomeTexture, {
544
+ src: './textures/sky.hdr',
545
+ });
546
+
547
+ // Image-based lighting from gradient
548
+ entity.addComponent(IBLGradient, {
549
+ sky: [0.6902, 0.749, 0.7843, 1.0], // RGBA
550
+ equator: [0.6584, 0.7084, 0.7913, 1.0], // RGBA
551
+ ground: [0.807, 0.7758, 0.7454, 1.0], // RGBA
552
+ intensity: 1.0,
553
+ });
554
+
555
+ // IBL from texture
556
+ entity.addComponent(IBLTexture, {
557
+ src: 'room', // or URL to HDR
558
+ intensity: 1.0,
559
+ rotation: [0, 0, 0],
560
+ });
561
+ ```
562
+
563
+ **Critical Environment Usage Notes:**
564
+
565
+ 1. **Environment components MUST be added to the level root entity**, not arbitrary entities. The `EnvironmentSystem` queries require `LevelRoot`:
566
+
567
+ ```typescript
568
+ // ❌ BAD - Added to a random entity (silently ignored)
569
+ someEntity.addComponent(DomeGradient, { ... });
570
+
571
+ // ✅ GOOD - Added to the level root
572
+ const root = world.activeLevel.value;
573
+ root.addComponent(DomeGradient, { sky: [0.24, 0.62, 0.83, 1.0], ... });
574
+ ```
575
+
576
+ 2. **After changing environment properties, MUST set `_needsUpdate: true`** — changes are silently ignored without it:
577
+
578
+ ```typescript
579
+ root.getVectorView(DomeGradient, 'sky').set([0.1, 0.2, 0.8, 1.0]);
580
+ root.setValue(DomeGradient, '_needsUpdate', true); // Required! (scalar — setValue OK)
581
+ ```
582
+
583
+ 3. **Background vs IBL are separate**: `DomeTexture`/`DomeGradient` controls the visible sky. `IBLTexture`/`IBLGradient` controls scene lighting (reflections, ambient). You can mix them:
584
+
585
+ ```typescript
586
+ root.addComponent(DomeTexture, { src: './envs/sky.hdr', intensity: 0.9 });
587
+ root.addComponent(IBLTexture, { src: 'room', intensity: 1.2 }); // Lighting only
588
+ ```
589
+
590
+ 4. **In AR sessions**, backgrounds (dome) are automatically hidden but IBL remains active for realistic lighting on virtual objects.
591
+
592
+ ### 14. Asset Loading
593
+
594
+ ```typescript
595
+ import { AssetManager, AssetType } from '@iwsdk/core';
596
+
597
+ const publicAssetUrl = (path: string) =>
598
+ `${import.meta.env.BASE_URL}${path.replace(/^\/+/u, '')}`;
599
+
600
+ const world = await World.create(container, {
601
+ assets: {
602
+ myModel: {
603
+ url: publicAssetUrl('models/scene.glb'),
604
+ type: AssetType.GLTF,
605
+ priority: 'critical',
606
+ },
607
+ mySound: {
608
+ url: publicAssetUrl('audio/click.mp3'),
609
+ type: AssetType.Audio,
610
+ priority: 'background',
611
+ },
612
+ myTexture: {
613
+ url: publicAssetUrl('textures/wood.jpg'),
614
+ type: AssetType.Texture,
615
+ },
616
+ myHDR: {
617
+ url: publicAssetUrl('textures/env.hdr'),
618
+ type: AssetType.HDRTexture,
619
+ },
620
+ },
621
+ });
622
+
623
+ // Access preloaded assets
624
+ const model = AssetManager.getGLTF('myModel');
625
+ // `getGLTF` returns a fresh clone of `scene`/`scenes` per call, so the
626
+ // same key safely backs multiple entities. Use `{ shared: true }` for
627
+ // the cached instance.
628
+ const texture = AssetManager.getTexture('myTexture');
629
+ const audio = AssetManager.getAudio('mySound');
630
+ ```
631
+
632
+ **AssetType Enum:**
633
+
634
+ ```typescript
635
+ AssetType.GLTF; // 3D models
636
+ AssetType.Audio; // Sound files
637
+ AssetType.Texture; // Images
638
+ AssetType.HDRTexture; // HDR environment maps
639
+ ```
640
+
641
+ ### 15. VisibilityState
642
+
643
+ ```typescript
644
+ import { VisibilityState } from '@iwsdk/core';
645
+
646
+ VisibilityState.NonImmersive; // Browser mode (no XR)
647
+ VisibilityState.Hidden; // XR but not rendering
648
+ VisibilityState.Visible; // Full XR experience
649
+ VisibilityState.VisibleBlurred; // XR but focus lost
650
+
651
+ this.world.visibilityState.subscribe((state) => {
652
+ switch (state) {
653
+ case VisibilityState.NonImmersive:
654
+ // Show 2D fallback UI
655
+ break;
656
+ case VisibilityState.Visible:
657
+ // Full XR experience
658
+ break;
659
+ case VisibilityState.VisibleBlurred:
660
+ // Pause game, show overlay
661
+ break;
662
+ }
663
+ });
664
+ ```
665
+
666
+ ### XR Session Optimization
667
+
668
+ Configure frame rate and foveation when the XR session becomes visible:
669
+
670
+ ```typescript
671
+ this.world.visibilityState.subscribe((state) => {
672
+ if (state === VisibilityState.Visible) {
673
+ this.world.session?.updateTargetFrameRate(72); // Request 72 FPS
674
+ this.world.renderer.xr.setFoveation(1); // Max foveation for performance
675
+ }
676
+ });
677
+ ```
678
+
679
+ ### 16. Locomotion Configuration
680
+
681
+ ```typescript
682
+ import { LocomotionSystem, TurningMethod } from '@iwsdk/core';
683
+
684
+ const locomotion = world.getSystem(LocomotionSystem);
685
+
686
+ // All config properties are signals
687
+ locomotion.config.slidingSpeed.value = 3.0;
688
+ locomotion.config.turningMethod.value = TurningMethod.SmoothTurn; // SnapTurn = 1, SmoothTurn = 2 — always use the enum, not raw numbers
689
+ locomotion.config.turningAngle.value = 45;
690
+ locomotion.config.turningSpeed.value = 180;
691
+ locomotion.config.comfortAssist.value = 0.5;
692
+ locomotion.config.rayGravity.value = -0.4;
693
+ locomotion.config.jumpHeight.value = 1.5;
694
+ locomotion.config.jumpCooldown.value = 0.1;
695
+ locomotion.config.maxDropDistance.value = 5.0;
696
+ locomotion.config.useWorker.value = true;
697
+ locomotion.config.enableJumping.value = true; // Enable/disable jumping entirely
698
+ locomotion.config.initialPlayerPosition.value = [0, 0, 0]; // Starting position
699
+ ```
700
+
701
+ **EnvironmentType** (used with `LocomotionEnvironment` component):
702
+
703
+ ```typescript
704
+ import { EnvironmentType } from '@iwsdk/core';
705
+
706
+ EnvironmentType.STATIC; // Fixed geometry (walls, floors) — default
707
+ EnvironmentType.KINEMATIC; // Moving platforms (elevators, conveyors)
708
+ ```
709
+
710
+ ### 17. Scene Understanding (AR)
711
+
712
+ ```typescript
713
+ import { XRPlane, XRMesh, XRAnchor } from '@iwsdk/core';
714
+
715
+ // Enable in World.create
716
+ World.create(container, {
717
+ xr: {
718
+ sessionMode: SessionMode.ImmersiveAR,
719
+ features: { planeDetection: true, meshDetection: true },
720
+ },
721
+ features: {
722
+ sceneUnderstanding: true,
723
+ },
724
+ });
725
+
726
+ // Query detected planes/meshes
727
+ export class MyARSystem extends createSystem({
728
+ planes: { required: [XRPlane] },
729
+ meshes: { required: [XRMesh] },
730
+ anchors: { required: [XRAnchor] },
731
+ }) {
732
+ init() {
733
+ this.queries.planes.subscribe('qualify', (entity) => {
734
+ // New plane detected
735
+ const plane = entity.object3D;
736
+ });
737
+ }
738
+ }
739
+ ```
740
+
741
+ ### 18. Feature Configuration (Critical!)
742
+
743
+ **Only enable features that your experience actually uses.** Features have prerequisites - enabling them without proper setup causes problems.
744
+
745
+ #### Feature Decision Matrix
746
+
747
+ | Feature | Enable When | Prerequisites | If Missing |
748
+ | -------------------- | ------------------------------------- | ------------------------------------------ | ------------------------------ |
749
+ | `locomotion` | Player needs to move (teleport/slide) | Collision geometry in scene (floor, walls) | **Player falls through world** |
750
+ | `physics` | Objects need dynamic simulation | PhysicsShape + PhysicsBody components | Wasted overhead |
751
+ | `grabbing` | Objects are grabbable | Grabbable components on entities | Wasted overhead |
752
+ | `sceneUnderstanding` | AR with real-world surfaces | AR session mode | Feature won't work |
753
+ | `environmentRaycast` | AR object placement | AR session + hit-test support | Feature won't work |
754
+ | `spatialUI` | Rendering UIKitML assets | Manifest `AssetType.UIKitML` entries | No UI renders |
755
+
756
+ #### Locomotion Requires Environment Setup
757
+
758
+ ```typescript
759
+ // ❌ BAD - Locomotion enabled but no collision geometry
760
+ const world = await World.create(container, {
761
+ features: {
762
+ locomotion: true, // Player will fall through the floor!
763
+ },
764
+ });
765
+
766
+ // ✅ GOOD - Locomotion with proper environment
767
+ const world = await World.create(container, {
768
+ level: './scenes/vr.iwsdk.scene.json', // Scene has collision meshes
769
+ features: {
770
+ locomotion: true,
771
+ physics: true, // Physics provides collision detection
772
+ },
773
+ });
774
+
775
+ // ✅ GOOD - Static experience, no locomotion needed
776
+ const world = await World.create(container, {
777
+ features: {
778
+ locomotion: false, // Player stays at origin
779
+ grabbing: true, // Can still interact with objects
780
+ },
781
+ });
782
+ ```
783
+
784
+ #### VR vs AR Feature Sets
785
+
786
+ ```typescript
787
+ // VR Experience - typically needs locomotion
788
+ const vrWorld = await World.create(container, {
789
+ xr: { sessionMode: SessionMode.ImmersiveVR },
790
+ features: {
791
+ locomotion: true, // Move around virtual space
792
+ grabbing: true,
793
+ physics: true,
794
+ },
795
+ });
796
+
797
+ // AR Experience - player moves physically, no virtual locomotion
798
+ const arWorld = await World.create(container, {
799
+ xr: {
800
+ sessionMode: SessionMode.ImmersiveAR,
801
+ features: { planeDetection: true, hitTest: true },
802
+ },
803
+ features: {
804
+ locomotion: false, // Player walks in real world
805
+ sceneUnderstanding: true, // Detect real surfaces
806
+ environmentRaycast: true, // Place objects on surfaces
807
+ grabbing: true,
808
+ },
809
+ });
810
+ ```
811
+
812
+ ### 19. World Initialization Pattern
813
+
814
+ ```typescript
815
+ import { World, SessionMode } from '@iwsdk/core';
816
+
817
+ const publicAssetUrl = (path: string) =>
818
+ `${import.meta.env.BASE_URL}${path.replace(/^\/+/u, '')}`;
819
+
820
+ const world = await World.create(container, {
821
+ render: {
822
+ fov: 50,
823
+ near: 0.1,
824
+ far: 200,
825
+ stencil: false, // Enable stencil buffer if needed
826
+ },
827
+
828
+ assets: {
829
+ myModel: {
830
+ url: publicAssetUrl('models/scene.glb'),
831
+ type: AssetType.GLTF,
832
+ },
833
+ },
834
+
835
+ level: './scenes/main.iwsdk.scene.json',
836
+
837
+ xr: {
838
+ sessionMode: SessionMode.ImmersiveVR,
839
+ referenceSpace: { type: 'local-floor' },
840
+ // Structured feature flags — NOT raw string arrays. Each accepts a
841
+ // boolean or { required: true }.
842
+ features: { handTracking: true, planeDetection: true },
843
+ offer: 'once', // 'none' | 'once' | 'always' (default: 'always')
844
+ },
845
+
846
+ // Enable feature systems - ONLY what you need!
847
+ features: {
848
+ locomotion: true, // Only if scene has collision geometry
849
+ // OR object form:
850
+ // locomotion: {
851
+ // useWorker: true,
852
+ // initialPlayerPosition: [0, 0, 0],
853
+ // comfortAssistLevel: 0.5, // option key; maps to the LocomotionSystem 'comfortAssist' config signal
854
+ // turningMethod: TurningMethod.SnapTurn,
855
+ // enableJumping: true,
856
+ // },
857
+ grabbing: true, // Only if objects are grabbable
858
+ // OR object form: grabbing: { useHandPinchForGrab: true },
859
+ physics: true, // Only if using dynamic physics
860
+ sceneUnderstanding: true, // OR: { showWireFrame: true }
861
+ environmentRaycast: true, // AR hit-test against real-world surfaces
862
+ camera: true, // Camera video access (requires XR session)
863
+ spatialUI: {
864
+ forwardHtmlEvents: true,
865
+ preferredColorScheme: 'dark',
866
+ },
867
+ },
868
+ });
869
+
870
+ // Register custom systems
871
+ world.registerSystem(MySystem);
872
+
873
+ // Launch/exit XR
874
+ world.launchXR();
875
+ world.exitXR();
876
+ ```
877
+
878
+ Background and image-based lighting are authored explicitly with dome and IBL
879
+ components on the level root. IWSDK does not synthesize missing environment
880
+ components; starter scenes include gradient defaults.
881
+
882
+ ### Post-Creation Initialization Sequence
883
+
884
+ After `World.create()`, follow this order for proper initialization:
885
+
886
+ ```typescript
887
+ // 1. Create subsystems (physics engine, networking, etc.)
888
+ const simulator = await RaceSimulator.create({ useWorker: true });
889
+
890
+ // 2. Store shared state in world.globals
891
+ world.globals.raceSimulator = simulator;
892
+ (world.globals as Record<string, unknown>).carProxies = new Map();
893
+ (world.globals as Record<string, unknown>).gamePaused = signal(true);
894
+
895
+ // 3. Register components
896
+ world
897
+ .registerComponent(VehiclePhysicsLink)
898
+ .registerComponent(VehiclePhysicsState);
899
+
900
+ // 4. Setup scene (creates entities)
901
+ await setupScene(world, simulator, { aiCount: 5 });
902
+
903
+ // 5. Register systems with priorities
904
+ world
905
+ .registerSystem(PlayerInputSystem, { priority: 0 })
906
+ .registerSystem(PhysicsStepSystem, { priority: 10 });
907
+ ```
908
+
909
+ ### 20. Transform Entity Creation
910
+
911
+ ```typescript
912
+ // Create entity with Object3D binding
913
+ const entity = world.createTransformEntity(mesh, {
914
+ parent: parentEntity, // Optional parent
915
+ persistent: false, // false = destroyed with level
916
+ });
917
+
918
+ // Transform component automatically syncs with Object3D (zero-copy)
919
+ entity.object3D.position.set(0, 1, 0);
920
+
921
+ // Component API for vector fields: getVectorView ONLY — in elics 3.4.x
922
+ // setValue/getValue THROW for Vec2/Vec3/Vec4/Color fields. setValue is
923
+ // fine for scalars, booleans, strings, and enums.
924
+ const posView = entity.getVectorView(Transform, 'position');
925
+ posView.set([0, 1, 0]); // write
926
+ posView[0] += delta; // direct array element write
927
+ ```
928
+
929
+ ### 21. Panel UI Pattern
930
+
931
+ ```typescript
932
+ import { UIKit, UIKitMLAsset, VisibilityState } from '@iwsdk/core';
933
+
934
+ // "settings-panel" is the stable scene node id. Its content.asset points to
935
+ // an AssetType.UIKitML manifest entry.
936
+ const panel = world.requireSceneObject<UIKitMLAsset>('settings-panel');
937
+ const saveButton = panel.requireElementById<UIKit.Text>('save-button');
938
+ const xrButton = panel.requireElementById<UIKit.Text>('xr-button');
939
+
940
+ saveButton.addEventListener('click', () => {
941
+ // Apply settings and play feedback here.
942
+ });
943
+
944
+ const unsubscribe = world.visibilityState.subscribe((state) => {
945
+ const is2D = state === VisibilityState.NonImmersive;
946
+ xrButton.setProperties({ display: is2D ? 'flex' : 'none' });
947
+ });
948
+
949
+ // Retain unsubscribe and call it when the owning feature/system is destroyed.
950
+ ```
951
+
952
+ The manifest ID identifies the reusable UIKitML definition; the scene node ID
953
+ identifies a placed instance; element IDs identify controls inside it. For code-owned
954
+ instances, retain the object returned by the asset manager:
955
+
956
+ ```typescript
957
+ const panel = await world.assets.instantiate<UIKitMLAsset>('settings-panel');
958
+ const entity = world.createTransformEntity(panel);
959
+ panel.requireElementById('save-button').addEventListener('click', save);
960
+ ```
961
+
962
+ Do not discover application panels through internal `PanelDocument` storage or
963
+ transient ECS indices.
964
+
965
+ ### 22. Environment Raycasting (AR Hit-Test)
966
+
967
+ `EnvironmentRaycastTarget` makes an entity automatically follow XR hit-test results (raycast against real-world surfaces). The entity is positioned at the hit point and oriented to match the surface normal.
968
+
969
+ ```typescript
970
+ import { EnvironmentRaycastTarget, RaycastSpace } from '@iwsdk/core';
971
+
972
+ // Reticle that follows right controller ray
973
+ const reticle = world.createTransformEntity(reticleMesh);
974
+ reticle.addComponent(EnvironmentRaycastTarget, {
975
+ space: RaycastSpace.Right, // Ray source
976
+ maxDistance: 100, // Max raycast distance in meters
977
+ });
978
+
979
+ // For phone AR: tap-to-place (uses screen touch)
980
+ const marker = world.createTransformEntity(markerMesh);
981
+ marker.addComponent(EnvironmentRaycastTarget, {
982
+ space: RaycastSpace.Screen, // Tracks screen touch
983
+ });
984
+
985
+ // Read hit-test result (e.g., to spawn an object on trigger press)
986
+ const xrResult = entity.getValue(EnvironmentRaycastTarget, 'xrHitTestResult');
987
+ if (xrResult && gamepad?.getSelectStart()) {
988
+ spawnObject(entity.object3D.position.clone());
989
+ }
990
+ ```
991
+
992
+ **RaycastSpace:**
993
+
994
+ ```typescript
995
+ RaycastSpace.Left; // Left controller's target ray
996
+ RaycastSpace.Right; // Right controller's target ray (default)
997
+ RaycastSpace.Viewer; // Head/gaze direction
998
+ RaycastSpace.Screen; // Phone AR screen touch (tap-to-place)
999
+ ```
1000
+
1001
+ **Prerequisites:** `features: { environmentRaycast: true }` and `xr.features: { hitTest: true }` in AR session mode.
1002
+
1003
+ ### 23. Follower Component
1004
+
1005
+ Makes an entity follow another Object3D (typically the player's head for head-locked UI).
1006
+
1007
+ ```typescript
1008
+ import { Follower, FollowBehavior } from '@iwsdk/core';
1009
+
1010
+ entity.addComponent(Follower, {
1011
+ target: world.player.head, // Must be an Object3D
1012
+ offsetPosition: [0, -0.2, -0.8], // Offset in target's local space
1013
+ behavior: FollowBehavior.PivotY, // Rotation behavior
1014
+ maxAngle: 30, // Degrees before snapping forward
1015
+ tolerance: 0.4, // Meters of positional slack
1016
+ speed: 1, // Lerp speed
1017
+ });
1018
+ ```
1019
+
1020
+ **FollowBehavior:**
1021
+
1022
+ ```typescript
1023
+ FollowBehavior.FaceTarget; // Fully face the target
1024
+ FollowBehavior.PivotY; // Only rotate around Y axis (default)
1025
+ FollowBehavior.NoRotation; // Follow position only, no rotation
1026
+ ```
1027
+
1028
+ **Note:** `target` must be an `Object3D` instance (e.g., `world.player.head`), not an entity.
1029
+
1030
+ ### 24. CameraSource Component
1031
+
1032
+ Access device camera video as a texture. Useful for mixed reality effects or photo capture.
1033
+
1034
+ ```typescript
1035
+ import {
1036
+ CameraSource,
1037
+ CameraFacing,
1038
+ CameraState,
1039
+ CameraUtils,
1040
+ } from '@iwsdk/core';
1041
+
1042
+ // Add camera to an entity
1043
+ entity.addComponent(CameraSource, {
1044
+ // Input fields (user-configurable)
1045
+ deviceId: '', // Empty = auto-select based on facing
1046
+ facing: CameraFacing.Back, // Preferred camera direction
1047
+ width: 1920, // Requested resolution
1048
+ height: 1080,
1049
+ frameRate: 30,
1050
+ });
1051
+
1052
+ // Read-only output fields (managed by CameraSystem):
1053
+ // state: CameraState.Inactive | .Starting | .Active | .Error
1054
+ // texture: VideoTexture (apply to materials)
1055
+ // videoElement: HTMLVideoElement (advanced use)
1056
+ ```
1057
+
1058
+ **CameraFacing:**
1059
+
1060
+ ```typescript
1061
+ CameraFacing.Back; // Rear-facing camera
1062
+ CameraFacing.Front; // Front-facing (selfie) camera
1063
+ CameraFacing.Unknown; // Any available camera (default)
1064
+ ```
1065
+
1066
+ **CameraState:**
1067
+
1068
+ ```typescript
1069
+ CameraState.Inactive; // Not started
1070
+ CameraState.Starting; // Async initialization in progress
1071
+ CameraState.Active; // Stream running
1072
+ CameraState.Error; // Failed to start
1073
+ ```
1074
+
1075
+ **CameraUtils** static class:
1076
+
1077
+ ```typescript
1078
+ // List available cameras (requests permission on first call)
1079
+ const devices = await CameraUtils.getDevices();
1080
+ const backCam = CameraUtils.findByFacing(devices, CameraFacing.Back);
1081
+
1082
+ // Capture current frame as canvas (for snapshot/processing)
1083
+ const canvas = CameraUtils.captureFrame(cameraEntity);
1084
+ if (canvas) {
1085
+ const texture = new CanvasTexture(canvas);
1086
+ }
1087
+ ```
1088
+
1089
+ **Requires:** `features: { camera: true }`. Camera stream only activates during XR sessions.
1090
+
1091
+ ### 25. PhysicsManipulation Component
1092
+
1093
+ Applies forces or velocity changes to physics bodies. **One-shot component** — `PhysicsSystem` applies the values and auto-removes it each frame.
1094
+
1095
+ ```typescript
1096
+ import { PhysicsManipulation } from '@iwsdk/core';
1097
+
1098
+ // Apply an impulse force
1099
+ entity.addComponent(PhysicsManipulation, {
1100
+ force: [0, 10, 0], // Force vector (one-shot impulse)
1101
+ linearVelocity: [0, 0, 0], // Set linear velocity directly
1102
+ angularVelocity: [0, 0, 0], // Set angular velocity directly
1103
+ });
1104
+ // PhysicsSystem applies these values and auto-removes PhysicsManipulation
1105
+
1106
+ // For sustained forces, re-add the component each frame:
1107
+ update() {
1108
+ if (!entity.hasComponent(PhysicsManipulation)) {
1109
+ entity.addComponent(PhysicsManipulation, { force: [0, 5, 0] });
1110
+ }
1111
+ }
1112
+ ```
1113
+
1114
+ ### 26. ScreenSpace Usage Notes
1115
+
1116
+ `ScreenSpace` positions the UIKit document under a manifest-backed UIKitML entity
1117
+ relative to the screen in non-XR (browser) mode. It is intentional application
1118
+ behavior, not a temporary preview technique; use the editor's isolated preview for
1119
+ development.
1120
+
1121
+ **All position/size values are CSS strings**, not numbers:
1122
+
1123
+ ```typescript
1124
+ import { ScreenSpace } from '@iwsdk/core';
1125
+
1126
+ entity.addComponent(ScreenSpace, {
1127
+ width: '400px', // Explicit CSS size: '400px', '50vw', calc(...)
1128
+ height: '300px', // Explicit CSS size: '300px', '40vh', calc(...)
1129
+ top: '20px', // CSS position or 'auto'
1130
+ left: '20px', // CSS position or 'auto'
1131
+ bottom: 'auto',
1132
+ right: 'auto',
1133
+ zOffset: 0.2, // Distance in meters from camera near plane (NOT CSS)
1134
+ });
1135
+ ```
1136
+
1137
+ **How it works:** The system creates hidden DOM elements and uses `getComputedStyle()` to convert CSS values → pixels → meters. Use explicit dimensions (`calc()`, `vw`, `vh`, `%`, etc.); unconstrained `auto` dimensions fall back to a small viewport-relative size and warn.
1138
+
1139
+ **XR behavior:** When entering XR, `ScreenSpaceUISystem` automatically moves the panel back to world space. When exiting XR, it re-positions to screen space.
1140
+
1141
+ ### 27. Entity API
1142
+
1143
+ ```typescript
1144
+ // Destroy entity only (components removed, Object3D detached)
1145
+ entity.destroy();
1146
+
1147
+ // Destroy entity AND dispose GPU resources (geometry, materials, textures)
1148
+ // Use for entities with meshes/materials that need proper GPU cleanup
1149
+ entity.dispose();
1150
+
1151
+ // Get all component classes attached to this entity
1152
+ entity.getComponents();
1153
+ ```
1154
+
1155
+ **`dispose()` vs `destroy()`:** Use `dispose()` when the entity has meshes, materials, or textures that should be freed from GPU memory. Use `destroy()` when GPU resources are shared or managed elsewhere. Use `dispose()` with caution when resources may be shared across multiple entities.
1156
+
1157
+ ### 28. Utility Functions
1158
+
1159
+ ```typescript
1160
+ import { setWorldPosition, setWorldQuaternion } from '@iwsdk/core';
1161
+
1162
+ // Set world-space position (correctly handles parent transform chain)
1163
+ setWorldPosition(object3D, worldPosition);
1164
+
1165
+ // Set world-space quaternion (correctly handles parent transforms including non-uniform scale)
1166
+ setWorldQuaternion(object3D, worldQuaternion);
1167
+ ```
1168
+
1169
+ These are useful when you need to position an object in world space but it's nested under transformed parents. They compute the correct local transform to achieve the desired world transform.
1170
+
1171
+ ```typescript
1172
+ // Level root helpers on World:
1173
+ world.getActiveRoot(); // Returns active level's Object3D (or scene)
1174
+ world.getPersistentRoot(); // Returns the scene Object3D
1175
+ ```
1176
+
1177
+ ## Core Components Reference (30 Total)
1178
+
1179
+ | Component | Purpose |
1180
+ | ------------------------ | ----------------------------------------------- |
1181
+ | Transform | Position, rotation, scale |
1182
+ | Visibility | Show/hide objects |
1183
+ | LevelTag | Marks level membership |
1184
+ | LevelRoot | Level root marker |
1185
+ | Interactable | Marks interactive objects |
1186
+ | Hovered | Currently hovered |
1187
+ | Pressed | Currently pressed/grabbed |
1188
+ | OneHandGrabbable | Single-hand manipulation |
1189
+ | TwoHandsGrabbable | Two-hand manipulation |
1190
+ | DistanceGrabbable | Grab from distance |
1191
+ | Handle | Manipulation handle |
1192
+ | PhysicsBody | Physics motion properties |
1193
+ | PhysicsShape | Collision shape + material |
1194
+ | PhysicsManipulation | Force/velocity application |
1195
+ | DomeGradient | Gradient sky |
1196
+ | DomeTexture | Textured sky |
1197
+ | IBLGradient | Gradient IBL lighting |
1198
+ | IBLTexture | Texture IBL lighting |
1199
+ | PanelUI | Legacy component-backed UI loader compatibility |
1200
+ | PanelDocument | Internal loaded UI document state |
1201
+ | ScreenSpace | Screen-attached UI |
1202
+ | Follower | Object following |
1203
+ | XRPlane | Detected AR planes |
1204
+ | XRMesh | Detected AR meshes |
1205
+ | XRAnchor | Spatial anchors |
1206
+ | AudioSource | Audio configuration |
1207
+ | CameraSource | Camera device |
1208
+ | DepthOccludable | Depth-based occlusion for AR |
1209
+ | LocomotionEnvironment | Locomotion settings |
1210
+ | EnvironmentRaycastTarget | AR environment hit-test target |
1211
+
1212
+ ## Core Systems Reference (20 Total)
1213
+
1214
+ | System | Priority | Purpose |
1215
+ | ------------------------ | -------- | --------------------------------------------------------------------------------------------------- |
1216
+ | LocomotionSystem | -5 | Movement (teleport/slide/turn) |
1217
+ | InputSystem | -4 | Interactable state management |
1218
+ | GrabSystem | -3 | Grab handling |
1219
+ | PhysicsSystem | -2 | Physics simulation |
1220
+ | SceneUnderstandingSystem | -1 | AR plane/mesh detection |
1221
+ | EnvironmentRaycastSystem | -1 | AR environment raycasting |
1222
+ | PanelUISystem | -3.8 | UI panels |
1223
+ | ScreenSpaceUISystem | -3.75 | Screen UI |
1224
+ | CanvasPointerSystem | -3.5 | DOM pointer → scene forwarding (registered when input.canvasPointerEvents is enabled — the default) |
1225
+ | CameraSystem | default | Camera access |
1226
+ | LevelSystem | default | Level loading |
1227
+ | EnvironmentSystem | default | Lighting/sky |
1228
+ | AudioSystem | default | Spatial audio |
1229
+ | TransformSystem | default | Transform sync |
1230
+ | VisibilitySystem | default | Visibility sync |
1231
+ | FollowSystem | default | Object following |
1232
+ | TurnSystem | default | Rotation |
1233
+ | TeleportSystem | default | Teleportation |
1234
+ | SlideSystem | default | Smooth movement |
1235
+ | DepthSensingSystem | default | Depth occlusion for AR |
1236
+
1237
+ ### Custom System Priority Guidelines
1238
+
1239
+ Register custom systems with priorities following input→simulation→rendering pipeline:
1240
+
1241
+ ```
1242
+ Priority 0-9: Input capture (player input, AI decisions)
1243
+ Priority 10-19: Simulation (physics step, game logic)
1244
+ Priority 20-29: Visual sync (sync Three.js objects to physics)
1245
+ Priority 30+: Low-priority updates (UI, HUD, ambient effects)
1246
+ ```
1247
+
1248
+ Example:
1249
+
1250
+ ```typescript
1251
+ world
1252
+ .registerSystem(PlayerInputSystem, { priority: 0 })
1253
+ .registerSystem(AIDriverSystem, { priority: 1 })
1254
+ .registerSystem(PhysicsStepSystem, { priority: 10 })
1255
+ .registerSystem(VehicleSyncSystem, { priority: 20 })
1256
+ .registerSystem(DashboardSystem, { priority: 35 });
1257
+ ```
1258
+
1259
+ ## Project Structure
1260
+
1261
+ ```
1262
+ my-iwsdk-project/
1263
+ ├── iwsdk.config.json # Declarative project/world authority
1264
+ ├── src/
1265
+ │ ├── index.ts # World.create() plus system registration
1266
+ │ ├── assets.ts # defineAssets() project catalog
1267
+ │ ├── components.ts # defineComponents() declarations
1268
+ │ ├── systems/
1269
+ │ │ ├── ui-system.ts # Panel/UI management
1270
+ │ │ └── game-system.ts # Game logic
1271
+ │ └── components/
1272
+ │ └── custom.ts # Custom component definitions
1273
+ ├── public/
1274
+ │ ├── scenes/ # Native IWSDK scene JSON files
1275
+ │ ├── audio/ # Audio files
1276
+ │ └── ui/ # Runtime-loaded .uikitml files and fonts
1277
+ ├── vite.config.ts
1278
+ └── package.json
1279
+ ```
1280
+
1281
+ ## What IWSDK Provides (Don't Rebuild These)
1282
+
1283
+ Before writing custom code, check if IWSDK already provides the functionality. Rebuilding built-in features wastes time and produces inferior results (missing BVH acceleration, XR compatibility, comfort features, etc.).
1284
+
1285
+ ### Reinvention Risk Table
1286
+
1287
+ | What you might build from scratch | What IWSDK already provides |
1288
+ | ------------------------------------- | ---------------------------------------------------------------------------- |
1289
+ | GLTF loading with GLTFLoader | `AssetManager.loadGLTF()` or a `defineAssets()` project catalog |
1290
+ | Ray/line mesh for controller pointing | `RayPointer` — cylinder + gradient shader + cursor circle (auto) |
1291
+ | Hover/click detection with Raycaster | `Interactable` + `Hovered` + `Pressed` components |
1292
+ | Custom skybox sphere | `DomeGradient` or `DomeTexture` component |
1293
+ | PBR environment lighting | `IBLGradient` or `IBLTexture` component |
1294
+ | Teleport arc + landing marker | `LocomotionSystem` — full visuals included |
1295
+ | Comfort vignette for motion | `LocomotionSystem` — `comfortAssist` config |
1296
+ | Controller 3D models | Auto-loaded from WebXR Input Profiles |
1297
+ | Hand tracking meshes | `AnimatedHand` with skeletal mesh + outline |
1298
+ | Object grab + manipulation | `OneHandGrabbable` / `TwoHandsGrabbable` / `DistanceGrabbable` |
1299
+ | Hit-test against real world | `EnvironmentRaycastTarget` component |
1300
+ | Spatial audio | `AudioSource` component with pooling |
1301
+ | Camera feed texture | `CameraSource` component |
1302
+ | Depth occlusion shader | `DepthOccludable` component |
1303
+ | HUD / screen-space UI | `ScreenSpace` component with CSS units |
1304
+ | Follow-head billboard | `Follower` component |
1305
+ | Scene cleanup on level change | `LevelSystem` + `LevelTag` (automatic) |
1306
+ | Gamepad button debouncing | `StatefulGamepad` — `getButtonDown()` / `getButtonUp()` |
1307
+ | Manual GPU cleanup with traverse | `entity.dispose()` — destroys entity + cleans up geometry/materials/textures |
1308
+ | Manual world-space positioning | `setWorldPosition()` / `setWorldQuaternion()` utilities |
1309
+ | Manual XR hit-test setup | `EnvironmentRaycastTarget` component + `EnvironmentRaycastSystem` |
1310
+ | Manual camera video feed | `CameraSource` component + `CameraUtils` static class |
1311
+
1312
+ ### Asset Loading (AssetManager)
1313
+
1314
+ **Always use AssetManager** — never use raw `GLTFLoader`, `TextureLoader`, etc. AssetManager handles DRACO/KTX2 decoder setup, caching, and de-duplication automatically.
1315
+
1316
+ **Manifest pattern (preload at startup):**
1317
+
1318
+ ```typescript
1319
+ const publicAssetUrl = (path: string) =>
1320
+ `${import.meta.env.BASE_URL}${path.replace(/^\/+/u, '')}`;
1321
+
1322
+ const world = await World.create(container, {
1323
+ assets: {
1324
+ myModel: {
1325
+ url: publicAssetUrl('models/scene.glb'),
1326
+ type: AssetType.GLTF,
1327
+ priority: 'critical',
1328
+ },
1329
+ mySound: {
1330
+ url: publicAssetUrl('audio/click.mp3'),
1331
+ type: AssetType.Audio,
1332
+ priority: 'background',
1333
+ },
1334
+ myTexture: {
1335
+ url: publicAssetUrl('textures/wood.jpg'),
1336
+ type: AssetType.Texture,
1337
+ },
1338
+ myHDR: {
1339
+ url: publicAssetUrl('textures/env.hdr'),
1340
+ type: AssetType.HDRTexture,
1341
+ },
1342
+ },
1343
+ });
1344
+
1345
+ // Retrieve preloaded assets (synchronous — already loaded)
1346
+ const gltf = AssetManager.getGLTF('myModel');
1347
+ // `getGLTF` returns a fresh clone of `scene`/`scenes` per call, so the
1348
+ // same key safely backs multiple entities. Pass `{ shared: true }` to
1349
+ // get the cached instance.
1350
+ const texture = AssetManager.getTexture('myTexture');
1351
+ const audio = AssetManager.getAudio('mySound');
1352
+ ```
1353
+
1354
+ **Runtime loading (on-demand):**
1355
+
1356
+ ```typescript
1357
+ // Load at runtime when not known at startup
1358
+ const gltf = await AssetManager.loadGLTF(
1359
+ './models/dynamic.glb',
1360
+ 'dynamicModel',
1361
+ );
1362
+ const texture = await AssetManager.loadTexture(
1363
+ './textures/new.jpg',
1364
+ 'newTexture',
1365
+ );
1366
+ ```
1367
+
1368
+ **Supported AssetTypes:** `GLTF`, `Audio`, `Texture`, `HDRTexture`
1369
+
1370
+ ### Entity Parenting & Level Lifecycle
1371
+
1372
+ **Always use `createTransformEntity`** — never `scene.add()`. Entities created with `createTransformEntity` get a `Transform` component, participate in ECS queries, and are automatically managed by the level system.
1373
+
1374
+ ```typescript
1375
+ // Basic entity with parent
1376
+ const entity = world.createTransformEntity(mesh, parentEntity);
1377
+
1378
+ // With options object
1379
+ const entity = world.createTransformEntity(mesh, {
1380
+ parent: parentEntity,
1381
+ persistent: false, // false (default) = destroyed when level changes
1382
+ });
1383
+
1384
+ // Persistent entity — survives level changes
1385
+ const hud = world.createTransformEntity(hudMesh, {
1386
+ parent: world.sceneEntity,
1387
+ persistent: true,
1388
+ });
1389
+ ```
1390
+
1391
+ **Level lifecycle:**
1392
+
1393
+ - Entities with `LevelTag` are automatically destroyed when `world.loadLevel()` is called
1394
+ - Non-persistent entities created via `createTransformEntity` automatically get `LevelTag`
1395
+ - Use `persistent: true` for entities that should survive level transitions (HUDs, audio managers, etc.)
1396
+ - `world.loadLevel(url)` destroys all level-tagged entities, then loads the new native scene document
1397
+
1398
+ **Warning:** Parenting an Object3D under another Object3D that is NOT an entity's `object3D` will silently reparent it to the scene root and log a warning.
1399
+
1400
+ ### Input & Interaction
1401
+
1402
+ **Interactable → Hovered/Pressed flow:**
1403
+
1404
+ 1. Add `Interactable` component to any entity that should respond to pointer input
1405
+ 2. `InputSystem` automatically performs BVH-accelerated raycasting each frame
1406
+ 3. When a ray hits an Interactable entity, `Hovered` tag is added
1407
+ 4. When the user presses the select button while hovering, `Pressed` tag is added
1408
+ 5. Query for `Hovered`/`Pressed` in your system to react to interactions
1409
+
1410
+ ```typescript
1411
+ // Setup
1412
+ entity.addComponent(Interactable);
1413
+
1414
+ // In your system — react to interactions
1415
+ export class MyInteractionSystem extends createSystem({
1416
+ hovered: { required: [MyComponent, Hovered] },
1417
+ pressed: { required: [MyComponent, Pressed] },
1418
+ }) {
1419
+ init() {
1420
+ this.queries.pressed.subscribe('qualify', (entity) => {
1421
+ // Entity was just clicked/selected
1422
+ });
1423
+ }
1424
+ }
1425
+ ```
1426
+
1427
+ **StatefulGamepad API** (accessed via `this.input.xr.gamepads.left` / `.right`):
1428
+
1429
+ - `getButtonDown(InputComponent.Trigger)` — true on the frame the button was pressed
1430
+ - `getButtonUp(InputComponent.Trigger)` — true on the frame the button was released
1431
+ - `getButtonPressed(InputComponent.Trigger)` — true while held
1432
+ - `getButtonValue(InputComponent.Trigger)` — analog 0-1
1433
+ - `getAxesValues(InputComponent.Thumbstick)` — `{ x, y }` in -1 to 1 range
1434
+ - `getAxesEnteringUp/Down/Left/Right(InputComponent.Thumbstick)` — directional flick detection
1435
+
1436
+ ### Built-in Visuals (Don't Recreate)
1437
+
1438
+ These visuals are automatically created and managed by IWSDK systems:
1439
+
1440
+ - **RayPointer** — Cylinder mesh with gradient shader + circular cursor at hit point. Created automatically by `InputSystem` for each connected controller.
1441
+ - **AnimatedController** — GLTF controller models auto-loaded from the WebXR Input Profiles registry. Matches the user's actual hardware.
1442
+ - **AnimatedHand** — Skeletal hand mesh with outline shader for hand tracking mode. Auto-managed by the input system.
1443
+ - **Teleport visuals** — Parabolic arc + landing circle indicator. Rendered by `LocomotionSystem` when teleport mode is active.
1444
+ - **Comfort vignette** — Screen-edge darkening during smooth locomotion. Controlled by `locomotion.config.comfortAssist` (0 = off, 1 = maximum).
1445
+ - **DomeGradient / DomeTexture** — Sky dome rendering. Add the component to an entity; `EnvironmentSystem` handles the rest.
1446
+
1447
+ ## Anti-Patterns to Avoid
1448
+
1449
+ 1. **DON'T** store entity arrays in systems - use queries
1450
+ 2. **DON'T** poll for state changes - use signal subscriptions
1451
+ 3. **DON'T** manually track component additions/removals - use query subscribe
1452
+ 4. **DON'T** create entities in update() without proper lifecycle management
1453
+ 5. **DON'T** use `Types.Object` for data that could be typed (use Vec3, Float32, etc.)
1454
+ 6. **DON'T** forget cleanup functions for subscriptions and resources
1455
+ 7. **DON'T** mutate live query Sets while iterating: if your loop body removes AND re-adds required components, the re-qualified entity is revisited by the same iteration — an infinite loop. Iterate `Array.from(query.entities)` instead
1456
+ 8. **DON'T** enable locomotion without collision geometry - player falls through world
1457
+ 9. **DON'T** enable features you don't use - adds overhead and can cause bugs
1458
+ 10. **DON'T** confuse PhysicsBody (motion) with PhysicsShape (collision + material)
1459
+ 11. **DON'T** use raw `GLTFLoader`/`TextureLoader` — use `AssetManager` for caching, DRACO/KTX2 setup
1460
+ 12. **DON'T** use `scene.add()` — use `createTransformEntity()` for proper ECS integration
1461
+ 13. **DON'T** use `new Raycaster()` — use `Interactable` component for BVH-accelerated XR interaction
1462
+ 14. **DON'T** add environment components (`DomeGradient`/`IBLTexture`/etc.) to arbitrary entities — must go on the level root (`world.activeLevel.value`)
1463
+ 15. **DON'T** forget `_needsUpdate` after changing environment properties — changes are silently ignored without `entity.setValue(DomeGradient, '_needsUpdate', true)`
1464
+ 16. **DON'T** use `entity.destroy()` for objects with GPU resources — use `entity.dispose()` which also cleans up geometry/materials/textures
1465
+ 17. **DON'T** pass numbers to `ScreenSpace` — all position/size values are CSS strings like `'400px'` or `'50vw'`
1466
+
1467
+ ## Performance Tips
1468
+
1469
+ 1. Use `getVectorView()` for direct TypedArray access (zero-copy)
1470
+ 2. Batch query enumeration (don't create intermediate arrays)
1471
+ 3. Use tag components for cheap boolean queries
1472
+ 4. Leverage query filters (`where`) to reduce iteration scope
1473
+ 5. System config signals auto-deduplicate (no callback if value unchanged)
1474
+ 6. Physics and locomotion can run in Web Workers for heavy scenes
1475
+ 7. Use `PhysicsShapeType.Auto` to let IWSDK pick optimal collision shape
1476
+
1477
+ ## When Planning a New Feature
1478
+
1479
+ 1. **Determine feature flags** - What built-in features does this need? (locomotion, physics, grabbing, etc.)
1480
+ 2. **Check prerequisites** - If using locomotion, is collision geometry set up?
1481
+ 3. **Identify components needed** - What data does this feature require?
1482
+ 4. **Design queries** - How will systems find relevant entities?
1483
+ 5. **Plan reactivity** - What changes should trigger updates?
1484
+ 6. **Consider lifecycle** - When are entities created/destroyed?
1485
+ 7. **Map to existing systems** - Can built-in systems (grab, physics, etc.) help?
1486
+ 8. **VR vs AR** - Does this work differently in each mode?
1487
+ 9. **Input handling** - What controller/hand inputs are needed?
1488
+ 10. **Audio feedback** - What sounds should play on interactions?
1489
+ 11. **Select 3D assets** - What models are needed? (see the Asset Strategy section in `build-milestones.md`)