@krate/3d 0.0.0-stage → 0.5.0-rc.13

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 (43) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +9 -0
  3. package/README.md +45 -2
  4. package/materials/VERSION +1 -0
  5. package/materials/build.mjs +59 -0
  6. package/materials/physical.filamat +0 -0
  7. package/materials/physical_transparent.filamat +0 -0
  8. package/materials/src/physical.mat +90 -0
  9. package/materials/src/standard.mat +77 -0
  10. package/materials/src/unlit.mat +28 -0
  11. package/materials/standard.filamat +0 -0
  12. package/materials/standard_transparent.filamat +0 -0
  13. package/materials/unlit.filamat +0 -0
  14. package/materials/unlit_transparent.filamat +0 -0
  15. package/package.json +66 -3
  16. package/src/index.ts +3 -0
  17. package/src/runtime/aim.ts +40 -0
  18. package/src/runtime/calibration.ts +29 -0
  19. package/src/runtime/canvas.tsx +18 -0
  20. package/src/runtime/canvas_style.ts +11 -0
  21. package/src/runtime/color.ts +183 -0
  22. package/src/runtime/compiled.ts +39 -0
  23. package/src/runtime/compiled_canvas.tsx +37 -0
  24. package/src/runtime/context.ts +14 -0
  25. package/src/runtime/controls.ts +146 -0
  26. package/src/runtime/entities.ts +50 -0
  27. package/src/runtime/environment.ts +50 -0
  28. package/src/runtime/filament.ts +309 -0
  29. package/src/runtime/geometry.ts +195 -0
  30. package/src/runtime/gltf.ts +77 -0
  31. package/src/runtime/hooks.ts +10 -0
  32. package/src/runtime/index.ts +18 -0
  33. package/src/runtime/lights.ts +75 -0
  34. package/src/runtime/materials.ts +267 -0
  35. package/src/runtime/mount.ts +52 -0
  36. package/src/runtime/picking.ts +123 -0
  37. package/src/runtime/renderables.ts +62 -0
  38. package/src/runtime/rt.ts +33 -0
  39. package/src/runtime/scene.ts +484 -0
  40. package/src/runtime/transforms.ts +182 -0
  41. package/src/runtime/tree.ts +283 -0
  42. package/src/runtime/view.ts +121 -0
  43. package/src/types.ts +205 -0
@@ -0,0 +1,29 @@
1
+ // Three.js to Filament light and exposure calibration. The Go copy of these
2
+ // constants lives in packages/compiler/internal/scene3d; keep both in sync.
3
+
4
+ /** Default camera: f/16, 1/125 s, ISO 100 (EV100 about 15, sunlight near middle grey). */
5
+ export const DEFAULT_EXPOSURE = { aperture: 16, shutter: 1 / 125, iso: 100 } as const;
6
+
7
+ /** Filament directional light illuminance (lux) per Three.js intensity unit. */
8
+ export const DIRECTIONAL_LUX_PER_UNIT = 110000;
9
+ /** Luminous power (lumens) per Three.js point/spot intensity unit: 4 * pi * 1000. */
10
+ export const POINT_LUMENS_PER_UNIT = 4 * Math.PI * 1000;
11
+ /** IBL intensity per Three.js ambient intensity unit (when there is no Environment). */
12
+ export const AMBIENT_IBL_PER_UNIT = 30000;
13
+
14
+ export type LightKind = 'directional' | 'point' | 'spot' | 'ambient';
15
+
16
+ /** Converts a Three.js-scale intensity into Filament units for the given light kind. */
17
+ export function lightIntensity(kind: LightKind, threeIntensity: number): number {
18
+ switch (kind) {
19
+ case 'directional':
20
+ return threeIntensity * DIRECTIONAL_LUX_PER_UNIT;
21
+ case 'ambient':
22
+ return threeIntensity * AMBIENT_IBL_PER_UNIT;
23
+ default:
24
+ return threeIntensity * POINT_LUMENS_PER_UNIT;
25
+ }
26
+ }
27
+
28
+ /** Camera defaults, matching Three.js PerspectiveCamera. */
29
+ export const DEFAULT_CAMERA = { fov: 75, near: 0.1, far: 1000, position: [0, 0, 5], target: [0, 0, 0] } as const;
@@ -0,0 +1,18 @@
1
+ import { onCleanup, onMount } from '@krate/runtime';
2
+ import { canvasStyle, mountCanvas, type CanvasMountProps } from './mount.js';
3
+
4
+ /**
5
+ * A DOM canvas that renders its Filament scene. Scenes the compiler can
6
+ * analyse never call this: they compile to direct engine calls. This is the
7
+ * runtime fallback, which mounts the scene description in the browser.
8
+ */
9
+ // @ts-ignore TS1206: Krate removes component decorators at compile time.
10
+ @renderer
11
+ export function Canvas(props: CanvasMountProps) {
12
+ let canvas: HTMLCanvasElement | undefined;
13
+ onMount(() => {
14
+ const teardown = mountCanvas(canvas!, props);
15
+ onCleanup(teardown);
16
+ });
17
+ return <canvas ref={canvas} class={props.class} style={canvasStyle(props.style)} />;
18
+ }
@@ -0,0 +1,11 @@
1
+ // Inline style of the <canvas> element, shared by the runtime and compiled Canvas.
2
+
3
+ import type { CanvasProps } from '../types.js';
4
+
5
+ /** Inline style for the <canvas>: fills its parent unless overridden. */
6
+ export function canvasStyle(style: CanvasProps['style']): string {
7
+ const base = 'display:block;width:100%;height:100%;';
8
+ if (!style) return base;
9
+ if (typeof style === 'string') return base + style;
10
+ return base + Object.entries(style).map(([k, v]) => `${k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}:${v}`).join(';');
11
+ }
@@ -0,0 +1,183 @@
1
+ // Color helpers shared by the runtime fallback and the compiled constants.
2
+
3
+ export type Rgb = [number, number, number];
4
+
5
+ export function srgbToLinear(c: number): number {
6
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
7
+ }
8
+
9
+ /** CSS named colors (148 names, no `transparent`). */
10
+ const NAMED: Record<string, number> = {
11
+ aliceblue: 0xF0F8FF,
12
+ antiquewhite: 0xFAEBD7,
13
+ aqua: 0x00FFFF,
14
+ aquamarine: 0x7FFFD4,
15
+ azure: 0xF0FFFF,
16
+ beige: 0xF5F5DC,
17
+ bisque: 0xFFE4C4,
18
+ black: 0x000000,
19
+ blanchedalmond: 0xFFEBCD,
20
+ blue: 0x0000FF,
21
+ blueviolet: 0x8A2BE2,
22
+ brown: 0xA52A2A,
23
+ burlywood: 0xDEB887,
24
+ cadetblue: 0x5F9EA0,
25
+ chartreuse: 0x7FFF00,
26
+ chocolate: 0xD2691E,
27
+ coral: 0xFF7F50,
28
+ cornflowerblue: 0x6495ED,
29
+ cornsilk: 0xFFF8DC,
30
+ crimson: 0xDC143C,
31
+ cyan: 0x00FFFF,
32
+ darkblue: 0x00008B,
33
+ darkcyan: 0x008B8B,
34
+ darkgoldenrod: 0xB8860B,
35
+ darkgray: 0xA9A9A9,
36
+ darkgreen: 0x006400,
37
+ darkgrey: 0xA9A9A9,
38
+ darkkhaki: 0xBDB76B,
39
+ darkmagenta: 0x8B008B,
40
+ darkolivegreen: 0x556B2F,
41
+ darkorange: 0xFF8C00,
42
+ darkorchid: 0x9932CC,
43
+ darkred: 0x8B0000,
44
+ darksalmon: 0xE9967A,
45
+ darkseagreen: 0x8FBC8F,
46
+ darkslateblue: 0x483D8B,
47
+ darkslategray: 0x2F4F4F,
48
+ darkslategrey: 0x2F4F4F,
49
+ darkturquoise: 0x00CED1,
50
+ darkviolet: 0x9400D3,
51
+ deeppink: 0xFF1493,
52
+ deepskyblue: 0x00BFFF,
53
+ dimgray: 0x696969,
54
+ dimgrey: 0x696969,
55
+ dodgerblue: 0x1E90FF,
56
+ firebrick: 0xB22222,
57
+ floralwhite: 0xFFFAF0,
58
+ forestgreen: 0x228B22,
59
+ fuchsia: 0xFF00FF,
60
+ gainsboro: 0xDCDCDC,
61
+ ghostwhite: 0xF8F8FF,
62
+ gold: 0xFFD700,
63
+ goldenrod: 0xDAA520,
64
+ gray: 0x808080,
65
+ green: 0x008000,
66
+ greenyellow: 0xADFF2F,
67
+ grey: 0x808080,
68
+ honeydew: 0xF0FFF0,
69
+ hotpink: 0xFF69B4,
70
+ indianred: 0xCD5C5C,
71
+ indigo: 0x4B0082,
72
+ ivory: 0xFFFFF0,
73
+ khaki: 0xF0E68C,
74
+ lavender: 0xE6E6FA,
75
+ lavenderblush: 0xFFF0F5,
76
+ lawngreen: 0x7CFC00,
77
+ lemonchiffon: 0xFFFACD,
78
+ lightblue: 0xADD8E6,
79
+ lightcoral: 0xF08080,
80
+ lightcyan: 0xE0FFFF,
81
+ lightgoldenrodyellow: 0xFAFAD2,
82
+ lightgray: 0xD3D3D3,
83
+ lightgreen: 0x90EE90,
84
+ lightgrey: 0xD3D3D3,
85
+ lightpink: 0xFFB6C1,
86
+ lightsalmon: 0xFFA07A,
87
+ lightseagreen: 0x20B2AA,
88
+ lightskyblue: 0x87CEFA,
89
+ lightslategray: 0x778899,
90
+ lightslategrey: 0x778899,
91
+ lightsteelblue: 0xB0C4DE,
92
+ lightyellow: 0xFFFFE0,
93
+ lime: 0x00FF00,
94
+ limegreen: 0x32CD32,
95
+ linen: 0xFAF0E6,
96
+ magenta: 0xFF00FF,
97
+ maroon: 0x800000,
98
+ mediumaquamarine: 0x66CDAA,
99
+ mediumblue: 0x0000CD,
100
+ mediumorchid: 0xBA55D3,
101
+ mediumpurple: 0x9370DB,
102
+ mediumseagreen: 0x3CB371,
103
+ mediumslateblue: 0x7B68EE,
104
+ mediumspringgreen: 0x00FA9A,
105
+ mediumturquoise: 0x48D1CC,
106
+ mediumvioletred: 0xC71585,
107
+ midnightblue: 0x191970,
108
+ mintcream: 0xF5FFFA,
109
+ mistyrose: 0xFFE4E1,
110
+ moccasin: 0xFFE4B5,
111
+ navajowhite: 0xFFDEAD,
112
+ navy: 0x000080,
113
+ oldlace: 0xFDF5E6,
114
+ olive: 0x808000,
115
+ olivedrab: 0x6B8E23,
116
+ orange: 0xFFA500,
117
+ orangered: 0xFF4500,
118
+ orchid: 0xDA70D6,
119
+ palegoldenrod: 0xEEE8AA,
120
+ palegreen: 0x98FB98,
121
+ paleturquoise: 0xAFEEEE,
122
+ palevioletred: 0xDB7093,
123
+ papayawhip: 0xFFEFD5,
124
+ peachpuff: 0xFFDAB9,
125
+ peru: 0xCD853F,
126
+ pink: 0xFFC0CB,
127
+ plum: 0xDDA0DD,
128
+ powderblue: 0xB0E0E6,
129
+ purple: 0x800080,
130
+ rebeccapurple: 0x663399,
131
+ red: 0xFF0000,
132
+ rosybrown: 0xBC8F8F,
133
+ royalblue: 0x4169E1,
134
+ saddlebrown: 0x8B4513,
135
+ salmon: 0xFA8072,
136
+ sandybrown: 0xF4A460,
137
+ seagreen: 0x2E8B57,
138
+ seashell: 0xFFF5EE,
139
+ sienna: 0xA0522D,
140
+ silver: 0xC0C0C0,
141
+ skyblue: 0x87CEEB,
142
+ slateblue: 0x6A5ACD,
143
+ slategray: 0x708090,
144
+ slategrey: 0x708090,
145
+ snow: 0xFFFAFA,
146
+ springgreen: 0x00FF7F,
147
+ steelblue: 0x4682B4,
148
+ tan: 0xD2B48C,
149
+ teal: 0x008080,
150
+ thistle: 0xD8BFD8,
151
+ tomato: 0xFF6347,
152
+ turquoise: 0x40E0D0,
153
+ violet: 0xEE82EE,
154
+ wheat: 0xF5DEB3,
155
+ white: 0xFFFFFF,
156
+ whitesmoke: 0xF5F5F5,
157
+ yellow: 0xFFFF00,
158
+ yellowgreen: 0x9ACD32,
159
+ };
160
+
161
+ function hexToRgb(n: number): Rgb {
162
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
163
+ }
164
+
165
+ /** Parses a 0xRRGGBB number or CSS color (#rgb, #rrggbb, rgb(), a few names) to sRGB bytes. */
166
+ export function parseColor(input: string | number): Rgb {
167
+ if (typeof input === 'number') return hexToRgb(input);
168
+ const s = input.trim().toLowerCase();
169
+ if (s in NAMED) return hexToRgb(NAMED[s]);
170
+ let m = /^#([0-9a-f]{3})$/.exec(s);
171
+ if (m) return [...m[1]].map((h) => parseInt(h + h, 16)) as Rgb;
172
+ m = /^#([0-9a-f]{6})$/.exec(s);
173
+ if (m) return hexToRgb(parseInt(m[1], 16));
174
+ const f = /^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/.exec(s);
175
+ if (f) return [Number(f[1]), Number(f[2]), Number(f[3])];
176
+ return [255, 255, 255];
177
+ }
178
+
179
+ /** sRGB color (CSS string or 0xRRGGBB) to a linear RGB triple in 0..1. */
180
+ export function colorToLinear(input: string | number): Rgb {
181
+ const [r, g, b] = parseColor(input);
182
+ return [srgbToLinear(r / 255), srgbToLinear(g / 255), srgbToLinear(b / 255)];
183
+ }
@@ -0,0 +1,39 @@
1
+ // Entry points the compiler emits calls into (@krate/3d/runtime/compiled).
2
+ // Shape and the pre-ready queueing rule are documented in DESIGN.md.
3
+
4
+ import { aimLight } from './aim.js';
5
+ import { lightIntensity } from './calibration.js';
6
+ import { colorToLinear } from './color.js';
7
+ import { setCurrentScene } from './context.js';
8
+ import { rt } from './rt.js';
9
+ import { Scene3D, type SceneOptions } from './scene.js';
10
+
11
+ export const __k3d = {
12
+ /**
13
+ * Creates the engine for a canvas. Every method of the returned scene may be
14
+ * called immediately: calls made before Filament is ready are queued and
15
+ * replayed in order, and pos/rot/scale write the transform buffer directly.
16
+ */
17
+ scene(canvas: HTMLCanvasElement, opts: SceneOptions = {}): Scene3D {
18
+ const scene = new Scene3D(canvas, opts);
19
+ setCurrentScene(scene);
20
+ rt().onCleanup(() => scene.dispose());
21
+ return scene;
22
+ },
23
+ /** Three.js-scale light intensity to Filament units, for reactive intensities. */
24
+ intensity: lightIntensity,
25
+ /** sRGB CSS/hex color to a linear RGB triple, for reactive colors. */
26
+ color: colorToLinear,
27
+ /** Runs fn now and again when the signals it reads change (the page's createEffect). */
28
+ effect(fn: () => void): () => void {
29
+ return rt().createEffect(fn);
30
+ },
31
+ /** Light position and direction from a reactive position and target (see aim.ts). */
32
+ aimLight,
33
+ };
34
+
35
+ export type { Scene3D, SceneOptions };
36
+ export type { GeometryHandle, MeshHandle, LightHandle, InitialTransform } from './scene.js';
37
+ export type { MaterialHandle, MaterialKind, MaterialParams } from './materials.js';
38
+ export type { LightProps } from './lights.js';
39
+ export type { MeshFlags } from './renderables.js';
@@ -0,0 +1,37 @@
1
+ import { onMount } from '@krate/runtime';
2
+ import { canvasStyle } from './canvas_style.js';
3
+ import type { CanvasProps } from '../types.js';
4
+
5
+ export interface CompiledCanvasProps {
6
+ /** Compiled scene setup: creates the engine on the canvas and emits every engine call. */
7
+ setup: (canvas: HTMLCanvasElement) => void;
8
+ class?: string;
9
+ style?: CanvasProps['style'];
10
+ id?: string;
11
+ role?: string;
12
+ 'aria-label'?: string;
13
+ 'aria-hidden'?: boolean | 'true' | 'false';
14
+ }
15
+
16
+ /**
17
+ * The element the compiler replaces a `<Canvas>` with. It renders the DOM
18
+ * canvas and runs the compiled setup once it is mounted; the scene disposes
19
+ * itself with the component through the cleanup `__k3d.scene` registers.
20
+ */
21
+ export function CompiledCanvas(props: CompiledCanvasProps) {
22
+ let canvas: HTMLCanvasElement | undefined;
23
+ onMount(() => {
24
+ props.setup(canvas!);
25
+ });
26
+ return (
27
+ <canvas
28
+ ref={canvas}
29
+ class={props.class}
30
+ style={canvasStyle(props.style)}
31
+ id={props.id}
32
+ role={props.role}
33
+ aria-label={props['aria-label']}
34
+ aria-hidden={props['aria-hidden']}
35
+ />
36
+ );
37
+ }
@@ -0,0 +1,14 @@
1
+ // The scene hooks such as useGLTF and useFrame attach to.
2
+
3
+ import type { Scene3D } from './scene.js';
4
+
5
+ let current: Scene3D | undefined;
6
+
7
+ export function setCurrentScene(scene: Scene3D | undefined): void {
8
+ current = scene;
9
+ }
10
+
11
+ /** The most recently created live scene. */
12
+ export function getCurrentScene(): Scene3D | undefined {
13
+ return current && !current.disposed ? current : undefined;
14
+ }
@@ -0,0 +1,146 @@
1
+ // Orbit, zoom and pan camera controls on the scene camera's lookAt. No
2
+ // three.js dependency; the damping model follows three's OrbitControls.
3
+
4
+ import type { OrbitControlsProps, Vec3 } from '../types.js';
5
+ import { getCurrentScene } from './context.js';
6
+ import type { Scene3D } from './scene.js';
7
+
8
+ export interface Orbit {
9
+ radius: number;
10
+ /** Azimuth around +Y, from +Z. */
11
+ theta: number;
12
+ /** Polar angle from +Y. */
13
+ phi: number;
14
+ }
15
+
16
+ const EPS = 1e-6;
17
+
18
+ export function orbitFromPosition(position: readonly number[], target: readonly number[]): Orbit {
19
+ const x = position[0] - target[0];
20
+ const y = position[1] - target[1];
21
+ const z = position[2] - target[2];
22
+ const radius = Math.hypot(x, y, z) || EPS;
23
+ return { radius, theta: Math.atan2(x, z), phi: Math.acos(Math.min(1, Math.max(-1, y / radius))) };
24
+ }
25
+
26
+ export function orbitToPosition(target: readonly number[], o: Orbit): Vec3 {
27
+ const s = Math.sin(o.phi) * o.radius;
28
+ return [target[0] + s * Math.sin(o.theta), target[1] + Math.cos(o.phi) * o.radius, target[2] + s * Math.cos(o.theta)];
29
+ }
30
+
31
+ export function clampPhi(phi: number): number {
32
+ return Math.min(Math.PI - EPS, Math.max(EPS, phi));
33
+ }
34
+
35
+ /** World-space pan offset for a screen drag of (dx, dy) pixels. */
36
+ export function panOffset(o: Orbit, fovDeg: number, viewportHeight: number, dx: number, dy: number): Vec3 {
37
+ const k = (2 * o.radius * Math.tan((fovDeg * Math.PI) / 360)) / Math.max(1, viewportHeight);
38
+ // Camera right = (cos theta, 0, -sin theta); camera up in the orbit frame.
39
+ const right: Vec3 = [Math.cos(o.theta), 0, -Math.sin(o.theta)];
40
+ const up: Vec3 = [
41
+ -Math.cos(o.phi) * Math.sin(o.theta),
42
+ Math.sin(o.phi),
43
+ -Math.cos(o.phi) * Math.cos(o.theta),
44
+ ];
45
+ return [
46
+ (-dx * right[0] + dy * up[0]) * k,
47
+ (-dx * right[1] + dy * up[1]) * k,
48
+ (-dx * right[2] + dy * up[2]) * k,
49
+ ];
50
+ }
51
+
52
+ export class OrbitController {
53
+ orbit: Orbit;
54
+ target: number[];
55
+ dTheta = 0;
56
+ dPhi = 0;
57
+ damping = 0.05;
58
+ private dirty = true;
59
+ private drag: { x: number; y: number; pan: boolean } | null = null;
60
+ private off: Array<() => void> = [];
61
+
62
+ constructor(
63
+ private scene: Scene3D,
64
+ private props: () => OrbitControlsProps = () => ({})
65
+ ) {
66
+ const cam = scene.camState;
67
+ this.target = [...(props().target ?? cam.target)];
68
+ this.orbit = orbitFromPosition(cam.position, this.target);
69
+ const el = scene.canvas;
70
+ const on = <K extends keyof HTMLElementEventMap>(t: K, fn: (e: HTMLElementEventMap[K]) => void): void => {
71
+ el.addEventListener(t, fn as EventListener);
72
+ this.off.push(() => el.removeEventListener(t, fn as EventListener));
73
+ };
74
+ on('pointerdown', (e) => {
75
+ this.drag = { x: e.clientX, y: e.clientY, pan: e.button === 2 || e.shiftKey };
76
+ el.setPointerCapture?.(e.pointerId);
77
+ });
78
+ on('pointermove', (e) => {
79
+ if (!this.drag) return;
80
+ this.rotateOrPan(e.clientX - this.drag.x, e.clientY - this.drag.y, this.drag.pan);
81
+ this.drag.x = e.clientX;
82
+ this.drag.y = e.clientY;
83
+ });
84
+ on('pointerup', () => (this.drag = null));
85
+ on('wheel', (e) => {
86
+ if (this.props().enableZoom === false) return;
87
+ e.preventDefault();
88
+ this.zoom(e.deltaY);
89
+ });
90
+ on('contextmenu', (e) => e.preventDefault());
91
+ this.off.push(scene.onFrame(() => this.update()));
92
+ }
93
+
94
+ rotateOrPan(dx: number, dy: number, pan: boolean): void {
95
+ const p = this.props();
96
+ const h = Math.max(1, this.scene.canvas.clientHeight);
97
+ if (pan) {
98
+ if (p.enablePan === false) return;
99
+ const d = panOffset(this.orbit, this.scene.camState.fov, h, dx, dy);
100
+ for (let i = 0; i < 3; i++) this.target[i] += d[i];
101
+ this.dirty = true;
102
+ } else if (p.enableRotate !== false) {
103
+ this.dTheta -= (2 * Math.PI * dx) / h;
104
+ this.dPhi -= (2 * Math.PI * dy) / h;
105
+ }
106
+ }
107
+
108
+ zoom(deltaY: number): void {
109
+ const p = this.props();
110
+ const scale = deltaY > 0 ? 1 / 0.95 : 0.95;
111
+ this.dirty = true;
112
+ this.orbit.radius = Math.min(p.maxDistance ?? Infinity, Math.max(p.minDistance ?? 0, this.orbit.radius * scale));
113
+ }
114
+
115
+ /** Advances damping and auto-rotation, then pushes the pose to the camera. */
116
+ update(): void {
117
+ const p = this.props();
118
+ const o = this.orbit;
119
+ if (p.target) {
120
+ this.target = [...p.target];
121
+ this.dirty = true;
122
+ }
123
+ const idle = !this.dirty && !p.autoRotate && Math.abs(this.dTheta) < 1e-5 && Math.abs(this.dPhi) < 1e-5;
124
+ if (idle) return;
125
+ this.dirty = false;
126
+ if (p.autoRotate) this.dTheta -= ((2 * Math.PI) / 60 / 60) * (p.autoRotateSpeed ?? 2) / this.damping;
127
+ o.theta += this.dTheta * this.damping;
128
+ o.phi = clampPhi(o.phi + this.dPhi * this.damping);
129
+ this.dTheta *= 1 - this.damping;
130
+ this.dPhi *= 1 - this.damping;
131
+ this.scene.setCamera({ position: orbitToPosition(this.target, o), target: [...this.target] });
132
+ }
133
+
134
+ dispose(): void {
135
+ for (const f of this.off.splice(0)) f();
136
+ }
137
+ }
138
+
139
+ /** Attaches orbit controls to the current scene. Usable as `<OrbitControls />` inside a Canvas. */
140
+ export function OrbitControls(props: OrbitControlsProps = {}): null {
141
+ const scene = getCurrentScene();
142
+ if (!scene) throw new Error('@krate/3d: <OrbitControls> must be used inside a <Canvas>');
143
+ const controller = new OrbitController(scene, () => props);
144
+ scene.track(() => controller.dispose());
145
+ return null;
146
+ }
@@ -0,0 +1,50 @@
1
+ // Entity tracking: everything created through here is destroyed on dispose.
2
+
3
+ import type { FEngine, FEntity, FilamentModule } from './filament.js';
4
+
5
+ export class Entities {
6
+ private live = new Set<FEntity>();
7
+ /** Entities that carry a renderable or transform component. */
8
+ private components = new Map<FEntity, { renderable: boolean; transform: boolean }>();
9
+
10
+ constructor(
11
+ private F: FilamentModule,
12
+ private engine: FEngine
13
+ ) {}
14
+
15
+ create(): FEntity {
16
+ const e = this.F.EntityManager.get().create();
17
+ this.live.add(e);
18
+ return e;
19
+ }
20
+
21
+ markRenderable(e: FEntity): void {
22
+ const c = this.components.get(e) ?? { renderable: false, transform: false };
23
+ c.renderable = true;
24
+ this.components.set(e, c);
25
+ }
26
+
27
+ markTransform(e: FEntity): void {
28
+ const c = this.components.get(e) ?? { renderable: false, transform: false };
29
+ c.transform = true;
30
+ this.components.set(e, c);
31
+ }
32
+
33
+ get size(): number {
34
+ return this.live.size;
35
+ }
36
+
37
+ destroy(e: FEntity): void {
38
+ if (!this.live.delete(e)) return;
39
+ const c = this.components.get(e);
40
+ this.components.delete(e);
41
+ if (c?.renderable) this.engine.getRenderableManager().destroy(e);
42
+ if (c?.transform) this.engine.getTransformManager().destroy(e);
43
+ this.engine.destroyEntity(e);
44
+ e.delete?.();
45
+ }
46
+
47
+ destroyAll(): void {
48
+ for (const e of [...this.live]) this.destroy(e);
49
+ }
50
+ }
@@ -0,0 +1,50 @@
1
+ // Image-based lighting from a Filament KTX1 cubemap (cmgen output).
2
+
3
+ import { getCurrentScene } from './context.js';
4
+ import { defaultFetch } from './materials.js';
5
+ import type { Scene3D } from './scene.js';
6
+ import type { EnvironmentProps } from '../types.js';
7
+
8
+ const presets: Record<string, string> = {};
9
+
10
+ /** Maps preset names (`<Environment preset="studio" />`) to KTX URLs you host. */
11
+ export function setEnvironmentPresets(map: Record<string, string>): void {
12
+ Object.assign(presets, map);
13
+ }
14
+
15
+ export const DEFAULT_IBL_INTENSITY = 30000;
16
+
17
+ /** Loads the IBL (and, with `background`, the matching `_skybox.ktx`) into the scene. */
18
+ export function createEnvironment(scene: Scene3D, props: EnvironmentProps): void {
19
+ const url = props.files ?? (props.preset ? presets[props.preset] : undefined);
20
+ if (!url) {
21
+ throw new Error(
22
+ props.preset
23
+ ? `@krate/3d: no URL registered for Environment preset "${props.preset}"; call setEnvironmentPresets() or pass files`
24
+ : '@krate/3d: <Environment> needs `files` or `preset`'
25
+ );
26
+ }
27
+ if (/\.ktx2(\?|$)/i.test(url)) {
28
+ throw new Error('@krate/3d: Environment needs a KTX1 cubemap (.ktx from Filament cmgen); KTX2 is not supported for IBL');
29
+ }
30
+ scene.whenReady(() => {
31
+ const fetchBytes = scene.opts.fetchBytes ?? defaultFetch;
32
+ const skyUrl = url.replace(/_ibl\.ktx/i, '_skybox.ktx');
33
+ void Promise.all([fetchBytes(url), props.background && skyUrl !== url ? fetchBytes(skyUrl) : undefined])
34
+ .then(([iblBytes, skyBytes]) => {
35
+ if (scene.disposed) return;
36
+ const ibl = scene.engine.createIblFromKtx1(iblBytes);
37
+ ibl.setIntensity(props.intensity ?? DEFAULT_IBL_INTENSITY);
38
+ scene.setEnvironment(ibl, skyBytes ? scene.engine.createSkyFromKtx1(skyBytes) : undefined);
39
+ })
40
+ .catch((err) => (scene.opts.onError ?? console.error)(err));
41
+ });
42
+ }
43
+
44
+ /** `<Environment />` inside a Canvas. */
45
+ export function Environment(props: EnvironmentProps = {}): null {
46
+ const scene = getCurrentScene();
47
+ if (!scene) throw new Error('@krate/3d: <Environment> must be used inside a <Canvas>');
48
+ createEnvironment(scene, props);
49
+ return null;
50
+ }