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

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,267 @@
1
+ // Uber-material loading, parameter defaults and live parameter updates.
2
+
3
+ import { colorToLinear } from './color.js';
4
+ import type { FEngine, FMaterial, FMaterialInstance, FTexture, FilamentModule } from './filament.js';
5
+
6
+ export type MaterialKind = 'standard' | 'physical' | 'unlit';
7
+ /** Kind of a handle: the uber-materials, or a build-compiled shaderMaterial. */
8
+ export type HandleKind = MaterialKind | 'custom';
9
+ export type ParamValue = number | boolean | string | readonly number[];
10
+ export type MaterialParams = Record<string, ParamValue>;
11
+
12
+ const MAPS = ['baseColor', 'normal', 'ao', 'roughness', 'metallic', 'emissive'] as const;
13
+ const STANDARD_FLOATS: Record<string, number> = {
14
+ roughness: 1,
15
+ metallic: 0,
16
+ emissiveIntensity: 1,
17
+ opacity: 1,
18
+ normalScale: 1,
19
+ aoMapIntensity: 1,
20
+ };
21
+ const PHYSICAL_FLOATS: Record<string, number> = {
22
+ clearcoat: 0,
23
+ clearcoatRoughness: 0,
24
+ sheenRoughness: 1,
25
+ transmission: 0,
26
+ ior: 1.5,
27
+ };
28
+
29
+ /** Default value of every non-sampler parameter, per material kind (DESIGN.md parameter table). */
30
+ export function materialDefaults(kind: MaterialKind): Record<string, number | number[]> {
31
+ const out: Record<string, number | number[]> = { baseColor: [1, 1, 1, 1], opacity: 1 };
32
+ if (kind !== 'unlit') {
33
+ Object.assign(out, STANDARD_FLOATS, { emissive: [0, 0, 0] });
34
+ for (const m of MAPS) out[`use${m[0].toUpperCase()}${m.slice(1)}Map`] = 0;
35
+ if (kind === 'physical') Object.assign(out, PHYSICAL_FLOATS, { sheenColor: [0, 0, 0] });
36
+ } else {
37
+ out.useBaseColorMap = 0;
38
+ }
39
+ return out;
40
+ }
41
+
42
+ const COLOR_PARAMS = new Set(['baseColor', 'emissive', 'sheenColor']);
43
+ const FLOAT3 = new Set(['emissive', 'sheenColor']);
44
+
45
+ function mapNames(kind: MaterialKind): string[] {
46
+ return (kind === 'unlit' ? ['baseColor'] : [...MAPS]).map((m) => `${m}Map`);
47
+ }
48
+
49
+ /** Asset URL of a compiled material, relative to this module (bundlers rewrite the literal). */
50
+ const FILES: Record<string, () => URL> = {
51
+ standard: () => new URL('../../materials/standard.filamat', import.meta.url),
52
+ standard_transparent: () => new URL('../../materials/standard_transparent.filamat', import.meta.url),
53
+ physical: () => new URL('../../materials/physical.filamat', import.meta.url),
54
+ physical_transparent: () => new URL('../../materials/physical_transparent.filamat', import.meta.url),
55
+ unlit: () => new URL('../../materials/unlit.filamat', import.meta.url),
56
+ unlit_transparent: () => new URL('../../materials/unlit_transparent.filamat', import.meta.url),
57
+ };
58
+
59
+ export function materialUrl(kind: MaterialKind, transparent: boolean, base?: string): string {
60
+ const name = transparent ? `${kind}_transparent` : kind;
61
+ if (base !== undefined) return `${base.replace(/\/?$/, '/')}${name}.filamat`;
62
+ return FILES[name]().href;
63
+ }
64
+
65
+ /** True when the transparent (blended) variant is needed. */
66
+ export function isTransparent(params: MaterialParams): boolean {
67
+ const opacity = params.opacity;
68
+ return params.transparent === true || (typeof opacity === 'number' && opacity < 1);
69
+ }
70
+
71
+ const KNOWN = new Map<MaterialKind, Set<string>>();
72
+
73
+ /** Whether the compiled material of this kind declares the parameter (unknown names must not reach Filament). */
74
+ export function isKnownParam(kind: MaterialKind, name: string): boolean {
75
+ let set = KNOWN.get(kind);
76
+ if (!set) {
77
+ set = new Set([...Object.keys(materialDefaults(kind)), ...mapNames(kind)]);
78
+ KNOWN.set(kind, set);
79
+ }
80
+ return set.has(name);
81
+ }
82
+
83
+ function isTextureUrl(name: string, v: ParamValue): v is string {
84
+ return typeof v === 'string' && name.endsWith('Map');
85
+ }
86
+
87
+ /** Spec of a build-compiled shaderMaterial: its .filamat URL and initial uniform values. */
88
+ export interface CustomMaterialSpec {
89
+ url: string;
90
+ params?: Record<string, number | readonly number[]>;
91
+ transparent?: boolean;
92
+ }
93
+
94
+ export interface MaterialHandle {
95
+ kind: HandleKind;
96
+ /** Compiled material file of a custom material. */
97
+ url?: string;
98
+ params: MaterialParams;
99
+ transparent: boolean;
100
+ instance?: FMaterialInstance;
101
+ /** Callbacks run once the instance exists. */
102
+ waiters: Array<() => void>;
103
+ }
104
+
105
+ export class MaterialManager {
106
+ private files = new Map<string, Promise<FMaterial>>();
107
+ private materials: FMaterial[] = [];
108
+ private instances: FMaterialInstance[] = [];
109
+ private textures: FTexture[] = [];
110
+ private placeholders = new Map<string, FTexture>();
111
+ private sampler: unknown;
112
+ private disposed = false;
113
+
114
+ constructor(
115
+ private F: FilamentModule,
116
+ private engine: FEngine,
117
+ private base?: string,
118
+ private fetchBytes: (url: string) => Promise<Uint8Array> = defaultFetch
119
+ ) {}
120
+
121
+ private load(kind: HandleKind, transparent: boolean, customUrl?: string): Promise<FMaterial> {
122
+ const url = customUrl ?? materialUrl(kind as MaterialKind, transparent, this.base);
123
+ let p = this.files.get(url);
124
+ if (!p) {
125
+ p = this.fetchBytes(url).then((bytes) => {
126
+ const m = this.engine.createMaterial(bytes);
127
+ this.materials.push(m);
128
+ return m;
129
+ });
130
+ this.files.set(url, p);
131
+ }
132
+ return p;
133
+ }
134
+
135
+ /** Creates a handle without touching the engine; see start(). */
136
+ static handle(kind: MaterialKind, params: MaterialParams): MaterialHandle {
137
+ return { kind, params: { ...params }, transparent: isTransparent(params), waiters: [] };
138
+ }
139
+
140
+ /** Handle for a compiled shaderMaterial; its params are plain uniform values. */
141
+ static customHandle(spec: CustomMaterialSpec): MaterialHandle {
142
+ return { kind: 'custom', url: spec.url, params: { ...spec.params }, transparent: !!spec.transparent, waiters: [] };
143
+ }
144
+
145
+ /** Starts loading the material file and creates the instance when it is ready. */
146
+ start(handle: MaterialHandle): MaterialHandle {
147
+ void this.load(handle.kind, handle.transparent, handle.url).then(
148
+ (mat) => {
149
+ if (this.disposed) return;
150
+ const inst = mat.createInstance();
151
+ this.instances.push(inst);
152
+ handle.instance = inst;
153
+ this.applyAll(handle);
154
+ for (const w of handle.waiters.splice(0)) w();
155
+ },
156
+ (err) => console.error(err)
157
+ );
158
+ return handle;
159
+ }
160
+
161
+ private applyAll(h: MaterialHandle): void {
162
+ if (h.kind === 'custom') {
163
+ for (const [name, value] of Object.entries(h.params)) this.apply(h, name, value);
164
+ return;
165
+ }
166
+ const defaults = materialDefaults(h.kind);
167
+ const merged: MaterialParams = { ...defaults, ...h.params };
168
+ for (const name of mapNames(h.kind)) this.setPlaceholder(h, name);
169
+ for (const [name, value] of Object.entries(merged)) this.apply(h, name, value);
170
+ }
171
+
172
+ private setPlaceholder(h: MaterialHandle, name: string): void {
173
+ // A flat normal for normalMap, white for everything else.
174
+ const key = name === 'normalMap' ? 'flat' : 'white';
175
+ let tex = this.placeholders.get(key);
176
+ if (!tex) {
177
+ const F = this.F;
178
+ const px = key === 'flat' ? new Uint8Array([128, 128, 255, 255]) : new Uint8Array([255, 255, 255, 255]);
179
+ tex = F.Texture.Builder()
180
+ .width(1)
181
+ .height(1)
182
+ .levels(1)
183
+ .sampler(F.Texture$Sampler.SAMPLER_2D)
184
+ .format(F.Texture$InternalFormat.RGBA8)
185
+ .build(this.engine);
186
+ (tex as unknown as { setImage(e: FEngine, l: number, p: unknown): void }).setImage(
187
+ this.engine,
188
+ 0,
189
+ F.PixelBuffer(px, F.PixelDataFormat.RGBA, F.PixelDataType.UBYTE)
190
+ );
191
+ this.textures.push(tex);
192
+ this.placeholders.set(key, tex);
193
+ }
194
+ h.instance!.setTextureParameter(name, tex, this.getSampler());
195
+ }
196
+
197
+ private getSampler(): unknown {
198
+ const F = this.F;
199
+ return (this.sampler ??= new F.TextureSampler(F.MinFilter.LINEAR_MIPMAP_LINEAR, F.MagFilter.LINEAR, F.WrapMode.REPEAT));
200
+ }
201
+
202
+ private apply(h: MaterialHandle, name: string, value: ParamValue): void {
203
+ const inst = h.instance!;
204
+ if (h.kind === 'custom') {
205
+ // Uniforms are passed through as declared by the compiled material.
206
+ if (typeof value === 'number') inst.setFloatParameter(name, value);
207
+ else if (typeof value !== 'string' && typeof value !== 'boolean') {
208
+ if (value.length === 3) inst.setFloat3Parameter(name, value);
209
+ else if (value.length === 4) inst.setFloat4Parameter(name, value);
210
+ }
211
+ return;
212
+ }
213
+ if (!isKnownParam(h.kind, name)) return;
214
+ if (isTextureUrl(name, value)) {
215
+ void this.applyTexture(h, name, value);
216
+ return;
217
+ }
218
+ if (COLOR_PARAMS.has(name) && (typeof value === 'string' || (typeof value === 'number' && name !== 'opacity'))) {
219
+ const [r, g, b] = colorToLinear(value);
220
+ if (FLOAT3.has(name)) inst.setFloat3Parameter(name, [r, g, b]);
221
+ else inst.setFloat4Parameter(name, [r, g, b, 1]);
222
+ return;
223
+ }
224
+ if (typeof value === 'number') inst.setFloatParameter(name, value);
225
+ else if (typeof value === 'boolean') inst.setBoolParameter(name, value);
226
+ else if (value.length === 3) inst.setFloat3Parameter(name, value);
227
+ else if (value.length === 4) inst.setFloat4Parameter(name, value);
228
+ }
229
+
230
+ private async applyTexture(h: MaterialHandle, name: string, url: string): Promise<void> {
231
+ const bytes = await this.fetchBytes(url);
232
+ if (this.disposed) return;
233
+ const srgb = name === 'baseColorMap' || name === 'emissiveMap';
234
+ const e = this.engine;
235
+ const lower = url.split('?')[0].toLowerCase();
236
+ const tex = lower.endsWith('.ktx2')
237
+ ? e.createTextureFromKtx2(bytes, { srgb })
238
+ : lower.endsWith('.jpg') || lower.endsWith('.jpeg')
239
+ ? e.createTextureFromJpeg(bytes, { srgb })
240
+ : e.createTextureFromPng(bytes, { srgb });
241
+ this.textures.push(tex);
242
+ h.instance!.setTextureParameter(name, tex, this.getSampler());
243
+ h.instance!.setFloatParameter(`use${name[0].toUpperCase()}${name.slice(1)}`, 1);
244
+ }
245
+
246
+ /** Reactive update: remembers the value and writes it when the instance exists. */
247
+ set(h: MaterialHandle, name: string, value: ParamValue): void {
248
+ h.params[name] = value;
249
+ if (h.instance) this.apply(h, name, value);
250
+ }
251
+
252
+ dispose(): void {
253
+ this.disposed = true;
254
+ for (const i of this.instances) this.engine.destroyMaterialInstance(i);
255
+ for (const t of this.textures) this.engine.destroyTexture(t);
256
+ for (const m of this.materials) this.engine.destroyMaterial(m);
257
+ this.instances = [];
258
+ this.textures = [];
259
+ this.materials = [];
260
+ }
261
+ }
262
+
263
+ export async function defaultFetch(url: string): Promise<Uint8Array> {
264
+ const res = await fetch(url);
265
+ if (!res.ok) throw new Error(`@krate/3d: failed to load ${url} (${res.status})`);
266
+ return new Uint8Array(await res.arrayBuffer());
267
+ }
@@ -0,0 +1,52 @@
1
+ // Browser mount of a <Canvas>: scene creation plus the fallback tree walker.
2
+
3
+ import type { CanvasProps } from '../types.js';
4
+ import { setCurrentScene } from './context.js';
5
+ import type { FilamentSource } from './filament.js';
6
+ import { Scene3D, type SceneOptions } from './scene.js';
7
+ import { canvasStyle } from './canvas_style.js';
8
+ import { mountSceneTree } from './tree.js';
9
+
10
+ export { canvasStyle };
11
+
12
+ export interface CanvasMountProps extends CanvasProps {
13
+ /** An already loaded Filament module or loader (tests, custom wasm location). */
14
+ filament?: FilamentSource;
15
+ /** URL of the filament.js the build copied into the site. */
16
+ filamentUrl?: string;
17
+ /** Base URL of the compiled .filamat files. */
18
+ materialBase?: string;
19
+ pixelRatio?: number;
20
+ fetchBytes?: SceneOptions['fetchBytes'];
21
+ onCreated?: (scene: Scene3D) => void;
22
+ }
23
+
24
+ export function sceneOptions(props: CanvasMountProps): SceneOptions {
25
+ return {
26
+ view: {
27
+ shadows: props.shadows,
28
+ bloom: props.bloom,
29
+ ssao: props.ssao,
30
+ antialias: props.antialias,
31
+ toneMapping: props.toneMapping,
32
+ },
33
+ camera: { ...props.camera, exposure: props.exposure },
34
+ filament: props.filament,
35
+ filamentUrl: props.filamentUrl,
36
+ materialBase: props.materialBase,
37
+ pixelRatio: props.pixelRatio,
38
+ fetchBytes: props.fetchBytes,
39
+ };
40
+ }
41
+
42
+ /** Creates the scene on a canvas and mounts the children; returns the teardown. */
43
+ export function mountCanvas(canvas: HTMLCanvasElement, props: CanvasMountProps): () => void {
44
+ const scene = new Scene3D(canvas, sceneOptions(props));
45
+ setCurrentScene(scene);
46
+ const unmount = mountSceneTree(scene, props.children);
47
+ props.onCreated?.(scene);
48
+ return () => {
49
+ unmount();
50
+ scene.dispose();
51
+ };
52
+ }
@@ -0,0 +1,123 @@
1
+ // Pointer picking: view.pick() with at most one query in flight, entity to
2
+ // handler dispatch, and over/out derived from the previously hovered entity.
3
+
4
+ import type { Pointer3DEvent, PointerHandler } from '../types.js';
5
+ import type { FPickResult, FView } from './filament.js';
6
+
7
+ export type PointerEventName = 'click' | 'pointerover' | 'pointerout' | 'pointermove' | 'pointerdown' | 'pointerup';
8
+ type Handlers = Partial<Record<PointerEventName, PointerHandler>>;
9
+
10
+ interface Request {
11
+ type: 'click' | 'pointermove' | 'pointerdown' | 'pointerup';
12
+ /** Pixels, bottom-left origin (Filament). */
13
+ px: number;
14
+ py: number;
15
+ /** CSS pixels relative to the canvas, top-left origin. */
16
+ x: number;
17
+ y: number;
18
+ native: PointerEvent | MouseEvent;
19
+ }
20
+
21
+ /** The real binding hands back an Entity object (0 or null for a miss), not the number its typings promise. */
22
+ function entityId(r: FPickResult['renderable']): number {
23
+ if (typeof r === 'number') return r;
24
+ return r?.getId() ?? 0;
25
+ }
26
+
27
+ const DOM_EVENTS = ['click', 'pointermove', 'pointerdown', 'pointerup'] as const;
28
+
29
+ export class Picker {
30
+ private handlers = new Map<number, Handlers>();
31
+ private queue: Request[] = [];
32
+ private inflight = false;
33
+ private hovered = 0;
34
+ private attached = false;
35
+ private disposed = false;
36
+
37
+ constructor(
38
+ private view: FView,
39
+ private canvas: HTMLCanvasElement,
40
+ private pixelRatio: () => number
41
+ ) {}
42
+
43
+ on(entity: number, event: PointerEventName, handler: PointerHandler): void {
44
+ const h = this.handlers.get(entity) ?? {};
45
+ h[event] = handler;
46
+ this.handlers.set(entity, h);
47
+ this.attach();
48
+ }
49
+
50
+ off(entity: number): void {
51
+ this.handlers.delete(entity);
52
+ if (this.hovered === entity) this.hovered = 0;
53
+ }
54
+
55
+ private attach(): void {
56
+ if (this.attached) return;
57
+ this.attached = true;
58
+ for (const t of DOM_EVENTS) this.canvas.addEventListener(t, this.onPointer as EventListener);
59
+ this.canvas.addEventListener('pointerleave', this.onLeave);
60
+ }
61
+
62
+ private onPointer = (e: PointerEvent | MouseEvent): void => {
63
+ const rect = this.canvas.getBoundingClientRect();
64
+ const dpr = this.pixelRatio();
65
+ const x = e.clientX - rect.left;
66
+ const y = e.clientY - rect.top;
67
+ const req: Request = {
68
+ type: e.type as Request['type'],
69
+ px: x * dpr,
70
+ py: this.canvas.height - y * dpr,
71
+ x,
72
+ y,
73
+ native: e,
74
+ };
75
+ // Only the latest pointer position matters while waiting for a query.
76
+ const last = this.queue[this.queue.length - 1];
77
+ if (req.type === 'pointermove' && last?.type === 'pointermove') this.queue[this.queue.length - 1] = req;
78
+ else this.queue.push(req);
79
+ };
80
+
81
+ private onLeave = (e: Event): void => {
82
+ this.queue = this.queue.filter((r) => r.type !== 'pointermove');
83
+ const prev = this.hovered;
84
+ this.hovered = 0;
85
+ if (prev) this.fire(prev, 'pointerout', 0, 0, e as PointerEvent);
86
+ };
87
+
88
+ /** Called once per frame before render: starts the next query unless one is in flight. */
89
+ update(): void {
90
+ if (this.inflight || this.disposed) return;
91
+ const req = this.queue.shift();
92
+ if (!req) return;
93
+ this.inflight = true;
94
+ this.view.pick(req.px, req.py, (r: FPickResult) => {
95
+ this.inflight = false;
96
+ if (!this.disposed) this.resolve(req, entityId(r.renderable));
97
+ });
98
+ }
99
+
100
+ private resolve(req: Request, id: number): void {
101
+ if (req.type === 'pointermove') {
102
+ if (id !== this.hovered) {
103
+ const prev = this.hovered;
104
+ this.hovered = id;
105
+ if (prev) this.fire(prev, 'pointerout', req.x, req.y, req.native);
106
+ if (id) this.fire(id, 'pointerover', req.x, req.y, req.native);
107
+ }
108
+ }
109
+ if (id) this.fire(id, req.type, req.x, req.y, req.native);
110
+ }
111
+
112
+ private fire(entity: number, name: PointerEventName, x: number, y: number, native: PointerEvent | MouseEvent): void {
113
+ this.handlers.get(entity)?.[name]?.({ entity, x, y, nativeEvent: native } satisfies Pointer3DEvent);
114
+ }
115
+
116
+ dispose(): void {
117
+ this.disposed = true;
118
+ for (const t of DOM_EVENTS) this.canvas.removeEventListener(t, this.onPointer as EventListener);
119
+ this.canvas.removeEventListener('pointerleave', this.onLeave);
120
+ this.handlers.clear();
121
+ this.queue = [];
122
+ }
123
+ }
@@ -0,0 +1,62 @@
1
+ // Mesh renderables. Filament 1.53.4's JS bindings have Builder.instances(count)
2
+ // but no InstanceBuffer and no per-instance transform API, so real GPU
3
+ // instancing is not available: an instanced mesh is `count` renderables
4
+ // sharing one vertex/index buffer and one material instance.
5
+
6
+ import type { Entities } from './entities.js';
7
+ import type { FEngine, FEntity, FMaterialInstance, FilamentModule, Mat4 } from './filament.js';
8
+ import type { GpuGeometry } from './geometry.js';
9
+
10
+ export interface MeshFlags {
11
+ castShadow?: boolean;
12
+ receiveShadow?: boolean;
13
+ }
14
+
15
+ /** Builds one triangle-mesh renderable with a transform component; the caller adds it to the scene. */
16
+ export function buildMesh(
17
+ F: FilamentModule,
18
+ engine: FEngine,
19
+ entities: Entities,
20
+ geo: GpuGeometry,
21
+ mi: FMaterialInstance,
22
+ flags: MeshFlags = {},
23
+ shadows = false
24
+ ): FEntity {
25
+ const entity = entities.create();
26
+ F.RenderableManager.Builder(1)
27
+ .boundingBox(geo.box)
28
+ .geometry(0, F.RenderableManager$PrimitiveType.TRIANGLES, geo.vb, geo.ib)
29
+ .material(0, mi)
30
+ .castShadows(shadows && !!flags.castShadow)
31
+ .receiveShadows(shadows && !!flags.receiveShadow)
32
+ .build(engine, entity);
33
+ entities.markRenderable(entity);
34
+ const tcm = engine.getTransformManager();
35
+ tcm.create(entity);
36
+ entities.markTransform(entity);
37
+ return entity;
38
+ }
39
+
40
+ /** `count` renderables sharing geometry and material, placed by a packed array of column-major matrices. */
41
+ export function buildInstanced(
42
+ F: FilamentModule,
43
+ engine: FEngine,
44
+ entities: Entities,
45
+ geo: GpuGeometry,
46
+ mi: FMaterialInstance,
47
+ count: number,
48
+ matrices: Float32Array,
49
+ flags: MeshFlags = {},
50
+ shadows = false
51
+ ): FEntity[] {
52
+ const tcm = engine.getTransformManager();
53
+ const out: FEntity[] = [];
54
+ tcm.openLocalTransformTransaction();
55
+ for (let i = 0; i < count; i++) {
56
+ const e = buildMesh(F, engine, entities, geo, mi, flags, shadows);
57
+ tcm.setTransform(tcm.getInstance(e), matrices.subarray(i * 16, i * 16 + 16) as Mat4);
58
+ out.push(e);
59
+ }
60
+ tcm.commitLocalTransformTransaction();
61
+ return out;
62
+ }
@@ -0,0 +1,33 @@
1
+ // Like @krate/three's engine, this code is bundled for the browser as an npm
2
+ // dependency and must not import a second copy of the Krate runtime. It uses
3
+ // the page runtime, which attaches its API to the global object.
4
+
5
+ export interface KrateRuntime {
6
+ createSignal<T>(initial: T): [() => T, (next: T | ((prev: T) => T)) => void];
7
+ createEffect(fn: () => void): () => void;
8
+ onCleanup(fn: () => void): void;
9
+ untrack<T>(fn: () => T): T;
10
+ }
11
+
12
+ /**
13
+ * Returns the page's Krate runtime, or throws when it is not loaded. The reads
14
+ * are written out as `globalThis.name` on purpose: the build keeps only the
15
+ * runtime exports it can see the code read through the global object, and a
16
+ * loop over names would hide them.
17
+ */
18
+ export function rt(): KrateRuntime {
19
+ // Direct reads, not through a local alias: the build's scan sees only
20
+ // `globalThis.name` members.
21
+ const api: KrateRuntime = {
22
+ createSignal: (globalThis as unknown as KrateRuntime).createSignal,
23
+ createEffect: (globalThis as unknown as KrateRuntime).createEffect,
24
+ onCleanup: (globalThis as unknown as KrateRuntime).onCleanup,
25
+ untrack: (globalThis as unknown as KrateRuntime).untrack,
26
+ };
27
+ for (const [name, fn] of Object.entries(api)) {
28
+ if (typeof fn !== 'function') {
29
+ throw new Error(`@krate/3d: the Krate runtime is not loaded (missing ${name}). @krate/3d runs in the browser inside a Krate page.`);
30
+ }
31
+ }
32
+ return api;
33
+ }