@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.
- package/LICENSE +201 -0
- package/NOTICE +9 -0
- package/README.md +45 -2
- package/materials/VERSION +1 -0
- package/materials/build.mjs +59 -0
- package/materials/physical.filamat +0 -0
- package/materials/physical_transparent.filamat +0 -0
- package/materials/src/physical.mat +90 -0
- package/materials/src/standard.mat +77 -0
- package/materials/src/unlit.mat +28 -0
- package/materials/standard.filamat +0 -0
- package/materials/standard_transparent.filamat +0 -0
- package/materials/unlit.filamat +0 -0
- package/materials/unlit_transparent.filamat +0 -0
- package/package.json +66 -3
- package/src/index.ts +3 -0
- package/src/runtime/aim.ts +40 -0
- package/src/runtime/calibration.ts +29 -0
- package/src/runtime/canvas.tsx +18 -0
- package/src/runtime/canvas_style.ts +11 -0
- package/src/runtime/color.ts +183 -0
- package/src/runtime/compiled.ts +39 -0
- package/src/runtime/compiled_canvas.tsx +37 -0
- package/src/runtime/context.ts +14 -0
- package/src/runtime/controls.ts +146 -0
- package/src/runtime/entities.ts +50 -0
- package/src/runtime/environment.ts +50 -0
- package/src/runtime/filament.ts +309 -0
- package/src/runtime/geometry.ts +195 -0
- package/src/runtime/gltf.ts +77 -0
- package/src/runtime/hooks.ts +10 -0
- package/src/runtime/index.ts +18 -0
- package/src/runtime/lights.ts +75 -0
- package/src/runtime/materials.ts +267 -0
- package/src/runtime/mount.ts +52 -0
- package/src/runtime/picking.ts +123 -0
- package/src/runtime/renderables.ts +62 -0
- package/src/runtime/rt.ts +33 -0
- package/src/runtime/scene.ts +484 -0
- package/src/runtime/transforms.ts +182 -0
- package/src/runtime/tree.ts +283 -0
- package/src/runtime/view.ts +121 -0
- package/src/types.ts +205 -0
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// The subset of the Filament 1.53 JS API this package uses, as structural
|
|
2
|
+
// interfaces. The real `filament` package is an optional peer dependency, so we
|
|
3
|
+
// never import its types; a test can pass a fake that satisfies FilamentModule.
|
|
4
|
+
|
|
5
|
+
export type Mat4 = ArrayLike<number>;
|
|
6
|
+
export type Vec3Like = ArrayLike<number>;
|
|
7
|
+
|
|
8
|
+
export interface FEntity {
|
|
9
|
+
getId(): number;
|
|
10
|
+
delete?(): void;
|
|
11
|
+
}
|
|
12
|
+
export interface FInstance {
|
|
13
|
+
delete?(): void;
|
|
14
|
+
}
|
|
15
|
+
export interface FBox {
|
|
16
|
+
center: number[];
|
|
17
|
+
halfExtent: number[];
|
|
18
|
+
}
|
|
19
|
+
export interface FBuffer {}
|
|
20
|
+
export interface FVertexBuffer extends FBuffer {
|
|
21
|
+
setBufferAt(engine: FEngine, index: number, data: ArrayBufferView): void;
|
|
22
|
+
}
|
|
23
|
+
export interface FIndexBuffer extends FBuffer {
|
|
24
|
+
setBuffer(engine: FEngine, data: ArrayBufferView): void;
|
|
25
|
+
}
|
|
26
|
+
export interface FTexture extends FBuffer {}
|
|
27
|
+
export interface FMaterialInstance {
|
|
28
|
+
setFloatParameter(name: string, v: number): void;
|
|
29
|
+
setFloat3Parameter(name: string, v: ArrayLike<number>): void;
|
|
30
|
+
setFloat4Parameter(name: string, v: ArrayLike<number>): void;
|
|
31
|
+
setBoolParameter(name: string, v: boolean): void;
|
|
32
|
+
setTextureParameter(name: string, t: FTexture, sampler: unknown): void;
|
|
33
|
+
}
|
|
34
|
+
export interface FMaterial {
|
|
35
|
+
createInstance(): FMaterialInstance;
|
|
36
|
+
}
|
|
37
|
+
export interface FRenderableBuilder {
|
|
38
|
+
geometry(slot: number, type: number, vb: FVertexBuffer, ib: FIndexBuffer): FRenderableBuilder;
|
|
39
|
+
material(slot: number, mi: FMaterialInstance): FRenderableBuilder;
|
|
40
|
+
boundingBox(box: FBox): FRenderableBuilder;
|
|
41
|
+
castShadows(on: boolean): FRenderableBuilder;
|
|
42
|
+
receiveShadows(on: boolean): FRenderableBuilder;
|
|
43
|
+
build(engine: FEngine, entity: FEntity): void;
|
|
44
|
+
}
|
|
45
|
+
export interface FLightBuilder {
|
|
46
|
+
color(rgb: number[]): FLightBuilder;
|
|
47
|
+
direction(v: number[]): FLightBuilder;
|
|
48
|
+
position(v: number[]): FLightBuilder;
|
|
49
|
+
intensity(v: number): FLightBuilder;
|
|
50
|
+
falloff(v: number): FLightBuilder;
|
|
51
|
+
spotLightCone(inner: number, outer: number): FLightBuilder;
|
|
52
|
+
castShadows(on: boolean): FLightBuilder;
|
|
53
|
+
shadowOptions(o: Record<string, unknown>): FLightBuilder;
|
|
54
|
+
build(engine: FEngine, entity: FEntity): void;
|
|
55
|
+
}
|
|
56
|
+
export interface FLightManager {
|
|
57
|
+
getInstance(e: FEntity): FInstance;
|
|
58
|
+
setIntensity(i: FInstance, v: number): void;
|
|
59
|
+
setColor(i: FInstance, v: number[]): void;
|
|
60
|
+
setPosition(i: FInstance, v: number[]): void;
|
|
61
|
+
setDirection(i: FInstance, v: number[]): void;
|
|
62
|
+
}
|
|
63
|
+
export interface FRenderableManager {
|
|
64
|
+
destroy(e: FEntity): void;
|
|
65
|
+
}
|
|
66
|
+
export interface FTransformManager {
|
|
67
|
+
create(e: FEntity): void;
|
|
68
|
+
destroy(e: FEntity): void;
|
|
69
|
+
getInstance(e: FEntity): FInstance;
|
|
70
|
+
setTransform(i: FInstance, m: Mat4): void;
|
|
71
|
+
openLocalTransformTransaction(): void;
|
|
72
|
+
commitLocalTransformTransaction(): void;
|
|
73
|
+
}
|
|
74
|
+
export interface FCamera {
|
|
75
|
+
setProjectionFov(fov: number, aspect: number, near: number, far: number, dir: number): void;
|
|
76
|
+
lookAt(eye: number[], center: number[], up: number[]): void;
|
|
77
|
+
setExposure(aperture: number, shutter: number, iso: number): void;
|
|
78
|
+
}
|
|
79
|
+
export interface FScene {
|
|
80
|
+
addEntity(e: FEntity): void;
|
|
81
|
+
addEntities(e: FEntity[]): void;
|
|
82
|
+
remove(e: FEntity): void;
|
|
83
|
+
removeEntities(e: FEntity[]): void;
|
|
84
|
+
setIndirectLight(ibl: FIndirectLight | null): void;
|
|
85
|
+
setSkybox(sky: FSkybox | null): void;
|
|
86
|
+
}
|
|
87
|
+
export interface FIndirectLight {
|
|
88
|
+
setIntensity(v: number): void;
|
|
89
|
+
}
|
|
90
|
+
export interface FIndirectLightBuilder {
|
|
91
|
+
irradianceSh(bands: number, data: number[]): FIndirectLightBuilder;
|
|
92
|
+
intensity(v: number): FIndirectLightBuilder;
|
|
93
|
+
build(engine: FEngine): FIndirectLight;
|
|
94
|
+
}
|
|
95
|
+
export interface FSkybox {}
|
|
96
|
+
export interface FColorGrading {}
|
|
97
|
+
export interface FColorGradingBuilder {
|
|
98
|
+
toneMapping(t: number): FColorGradingBuilder;
|
|
99
|
+
build(engine: FEngine): FColorGrading;
|
|
100
|
+
}
|
|
101
|
+
export interface FPickResult {
|
|
102
|
+
/** An Entity in the real binding (its typings say number); 0 or null when nothing was hit. */
|
|
103
|
+
renderable: number | FEntity | null;
|
|
104
|
+
depth: number;
|
|
105
|
+
fragCoords: number[];
|
|
106
|
+
}
|
|
107
|
+
export interface FView {
|
|
108
|
+
setScene(s: FScene): void;
|
|
109
|
+
setCamera(c: FCamera): void;
|
|
110
|
+
setViewport(v: number[]): void;
|
|
111
|
+
setColorGrading(c: FColorGrading): void;
|
|
112
|
+
setBloomOptions(o: Record<string, unknown>): void;
|
|
113
|
+
setAmbientOcclusionOptions(o: Record<string, unknown>): void;
|
|
114
|
+
setAntiAliasing(a: number): void;
|
|
115
|
+
setTemporalAntiAliasingOptions(o: Record<string, unknown>): void;
|
|
116
|
+
setMultiSampleAntiAliasingOptions(o: Record<string, unknown>): void;
|
|
117
|
+
setBlendMode(m: number): void;
|
|
118
|
+
pick(x: number, y: number, cb: (r: FPickResult) => void): void;
|
|
119
|
+
}
|
|
120
|
+
export interface FRenderer {
|
|
121
|
+
render(swapChain: FSwapChain, view: FView): void;
|
|
122
|
+
setClearOptions(o: { clearColor?: number[]; clear?: boolean; discard?: boolean }): void;
|
|
123
|
+
}
|
|
124
|
+
export interface FSwapChain {}
|
|
125
|
+
export interface FAsset {
|
|
126
|
+
loadResources(
|
|
127
|
+
onDone: (() => void) | null,
|
|
128
|
+
onFetched: ((name: string) => void) | null,
|
|
129
|
+
basePath: string | null,
|
|
130
|
+
asyncInterval?: number | null,
|
|
131
|
+
options?: object
|
|
132
|
+
): void;
|
|
133
|
+
getEntities(): FEntity[];
|
|
134
|
+
getRenderableEntities(): FEntity[];
|
|
135
|
+
getRoot(): FEntity;
|
|
136
|
+
}
|
|
137
|
+
export interface FAssetLoader {
|
|
138
|
+
createAsset(data: ArrayBufferView): FAsset | null;
|
|
139
|
+
destroyAsset(a: FAsset): void;
|
|
140
|
+
delete(): void;
|
|
141
|
+
}
|
|
142
|
+
export interface FSurfaceOrientation {
|
|
143
|
+
getQuats(count: number): ArrayBufferView;
|
|
144
|
+
delete(): void;
|
|
145
|
+
}
|
|
146
|
+
export interface FSurfaceOrientationBuilder {
|
|
147
|
+
vertexCount(n: number): FSurfaceOrientationBuilder;
|
|
148
|
+
normals(a: Float32Array, stride: number): FSurfaceOrientationBuilder;
|
|
149
|
+
uvs(a: Float32Array, stride: number): FSurfaceOrientationBuilder;
|
|
150
|
+
positions(a: Float32Array, stride: number): FSurfaceOrientationBuilder;
|
|
151
|
+
triangleCount(n: number): FSurfaceOrientationBuilder;
|
|
152
|
+
triangles16(a: Uint16Array): FSurfaceOrientationBuilder;
|
|
153
|
+
triangles32(a: Uint32Array): FSurfaceOrientationBuilder;
|
|
154
|
+
build(): FSurfaceOrientation;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export interface FEngine {
|
|
158
|
+
createCamera(e: FEntity): FCamera;
|
|
159
|
+
createMaterial(data: ArrayBufferView): FMaterial;
|
|
160
|
+
createRenderer(): FRenderer;
|
|
161
|
+
createScene(): FScene;
|
|
162
|
+
createSwapChain(): FSwapChain;
|
|
163
|
+
createView(): FView;
|
|
164
|
+
createAssetLoader(): FAssetLoader;
|
|
165
|
+
createTextureFromPng(data: ArrayBufferView, options?: object): FTexture;
|
|
166
|
+
createTextureFromJpeg(data: ArrayBufferView, options?: object): FTexture;
|
|
167
|
+
createTextureFromKtx2(data: ArrayBufferView, options?: object): FTexture;
|
|
168
|
+
createIblFromKtx1(data: ArrayBufferView): FIndirectLight;
|
|
169
|
+
createSkyFromKtx1(data: ArrayBufferView): FSkybox;
|
|
170
|
+
getLightManager(): FLightManager;
|
|
171
|
+
getRenderableManager(): FRenderableManager;
|
|
172
|
+
getTransformManager(): FTransformManager;
|
|
173
|
+
destroySwapChain(x: FSwapChain): void;
|
|
174
|
+
destroyRenderer(x: FRenderer): void;
|
|
175
|
+
destroyView(x: FView): void;
|
|
176
|
+
destroyScene(x: FScene): void;
|
|
177
|
+
destroyCameraComponent(e: FEntity): void;
|
|
178
|
+
destroyMaterial(x: FMaterial): void;
|
|
179
|
+
destroyEntity(e: FEntity): void;
|
|
180
|
+
destroyIndexBuffer(x: FIndexBuffer): void;
|
|
181
|
+
destroyVertexBuffer(x: FVertexBuffer): void;
|
|
182
|
+
destroyIndirectLight(x: FIndirectLight): void;
|
|
183
|
+
destroyMaterialInstance(x: FMaterialInstance): void;
|
|
184
|
+
destroySkybox(x: FSkybox): void;
|
|
185
|
+
destroyTexture(x: FTexture): void;
|
|
186
|
+
destroyColorGrading(x: FColorGrading): void;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Enum members used here; values come from the loaded module, never hard-coded. */
|
|
190
|
+
export type FEnum = Record<string, number>;
|
|
191
|
+
|
|
192
|
+
export interface FilamentModule {
|
|
193
|
+
init(assets: string[], onready?: (() => void) | null): void;
|
|
194
|
+
Engine: { create(canvas: HTMLCanvasElement, options?: object): FEngine; destroy(e: FEngine): void };
|
|
195
|
+
EntityManager: { get(): { create(): FEntity } };
|
|
196
|
+
RenderableManager: { Builder(count: number): FRenderableBuilder };
|
|
197
|
+
LightManager: { Builder(type: number): FLightBuilder };
|
|
198
|
+
IndirectLight: { Builder(): FIndirectLightBuilder };
|
|
199
|
+
ColorGrading: { Builder(): FColorGradingBuilder };
|
|
200
|
+
SurfaceOrientation$Builder: new () => FSurfaceOrientationBuilder;
|
|
201
|
+
VertexBuffer: { Builder(): FVertexBufferBuilder };
|
|
202
|
+
IndexBuffer: { Builder(): FIndexBufferBuilder };
|
|
203
|
+
Texture: { Builder(): FTextureBuilder };
|
|
204
|
+
TextureSampler: new (min: number, mag: number, wrap: number) => object;
|
|
205
|
+
PixelBuffer(data: ArrayBufferView, format: number, type: number): unknown;
|
|
206
|
+
LightManager$Type: FEnum;
|
|
207
|
+
RenderableManager$PrimitiveType: FEnum;
|
|
208
|
+
VertexAttribute: FEnum;
|
|
209
|
+
VertexBuffer$AttributeType: FEnum;
|
|
210
|
+
IndexBuffer$IndexType: FEnum;
|
|
211
|
+
Camera$Fov: FEnum;
|
|
212
|
+
ColorGrading$ToneMapping: FEnum & { AGX?: number };
|
|
213
|
+
View$AntiAliasing: FEnum;
|
|
214
|
+
View$BlendMode: FEnum;
|
|
215
|
+
View$BloomOptions$BlendMode?: FEnum;
|
|
216
|
+
View$QualityLevel?: FEnum;
|
|
217
|
+
Texture$Sampler: FEnum;
|
|
218
|
+
Texture$InternalFormat: FEnum;
|
|
219
|
+
PixelDataFormat: FEnum;
|
|
220
|
+
PixelDataType: FEnum;
|
|
221
|
+
MinFilter: FEnum;
|
|
222
|
+
MagFilter: FEnum;
|
|
223
|
+
WrapMode: FEnum;
|
|
224
|
+
}
|
|
225
|
+
export interface FVertexBufferBuilder {
|
|
226
|
+
vertexCount(n: number): FVertexBufferBuilder;
|
|
227
|
+
bufferCount(n: number): FVertexBufferBuilder;
|
|
228
|
+
attribute(a: number, buf: number, type: number, offset: number, stride: number): FVertexBufferBuilder;
|
|
229
|
+
normalized(a: number): FVertexBufferBuilder;
|
|
230
|
+
build(engine: FEngine): FVertexBuffer;
|
|
231
|
+
}
|
|
232
|
+
export interface FIndexBufferBuilder {
|
|
233
|
+
indexCount(n: number): FIndexBufferBuilder;
|
|
234
|
+
bufferType(t: number): FIndexBufferBuilder;
|
|
235
|
+
build(engine: FEngine): FIndexBuffer;
|
|
236
|
+
}
|
|
237
|
+
export interface FTextureBuilder {
|
|
238
|
+
width(n: number): FTextureBuilder;
|
|
239
|
+
height(n: number): FTextureBuilder;
|
|
240
|
+
levels(n: number): FTextureBuilder;
|
|
241
|
+
sampler(s: number): FTextureBuilder;
|
|
242
|
+
format(f: number): FTextureBuilder;
|
|
243
|
+
build(engine: FEngine): FTexture;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export type FilamentSource = FilamentModule | (() => FilamentModule | Promise<FilamentModule>);
|
|
247
|
+
|
|
248
|
+
type FilamentGlobal = { Filament?: FilamentModule };
|
|
249
|
+
|
|
250
|
+
function ready(mod: FilamentModule): Promise<FilamentModule> {
|
|
251
|
+
return new Promise((resolve) => {
|
|
252
|
+
mod.init([], () => {
|
|
253
|
+
// filament.js replaces its own global with the instantiated module, so
|
|
254
|
+
// the object we were given may be the pre-init stub.
|
|
255
|
+
const live = (mod as Partial<FilamentModule>).Engine ? mod : ((globalThis as FilamentGlobal).Filament ?? mod);
|
|
256
|
+
resolve(live);
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const scripts = new Map<string, Promise<FilamentModule>>();
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Loads filament.js as a classic script. It defines the global `Filament` and
|
|
265
|
+
* finds filament.wasm next to the script (it derives the directory from
|
|
266
|
+
* document.currentScript), so the build copies both into one directory and
|
|
267
|
+
* the page never bundles the engine.
|
|
268
|
+
*/
|
|
269
|
+
function loadScript(url: string): Promise<FilamentModule> {
|
|
270
|
+
let p = scripts.get(url);
|
|
271
|
+
if (!p) {
|
|
272
|
+
p = new Promise<FilamentModule>((resolve, reject) => {
|
|
273
|
+
const existing = (globalThis as FilamentGlobal).Filament;
|
|
274
|
+
if (existing && typeof existing.init === 'function') {
|
|
275
|
+
resolve(existing);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const el = document.createElement('script');
|
|
279
|
+
el.src = url;
|
|
280
|
+
el.async = true;
|
|
281
|
+
el.onload = () => {
|
|
282
|
+
const mod = (globalThis as FilamentGlobal).Filament;
|
|
283
|
+
if (mod) resolve(mod);
|
|
284
|
+
else reject(new Error(`@krate/3d: ${url} did not define the Filament global`));
|
|
285
|
+
};
|
|
286
|
+
el.onerror = () => reject(new Error(`@krate/3d: could not load Filament from ${url}`));
|
|
287
|
+
document.head.appendChild(el);
|
|
288
|
+
});
|
|
289
|
+
p.catch(() => scripts.delete(url));
|
|
290
|
+
scripts.set(url, p);
|
|
291
|
+
}
|
|
292
|
+
return p;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Resolves the Filament module: an injected one (tests, custom wasm location)
|
|
297
|
+
* or the script the build copied to `url`. The engine is never imported, so no
|
|
298
|
+
* bundler has to resolve filament.js and its Node-only branches.
|
|
299
|
+
*/
|
|
300
|
+
export async function loadFilament(source?: FilamentSource, url?: string): Promise<FilamentModule> {
|
|
301
|
+
const mod = typeof source === 'function' ? await source() : source;
|
|
302
|
+
if (mod) return ready(mod);
|
|
303
|
+
if (!url) {
|
|
304
|
+
throw new Error(
|
|
305
|
+
'@krate/3d: the Filament engine is not available. Run `npm install filament` so the build can copy filament.js and filament.wasm into the site, or pass a `filament` prop.'
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
return ready(await loadScript(url));
|
|
309
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Procedural geometry (Three.js layout and defaults) and its Filament buffers.
|
|
2
|
+
|
|
3
|
+
import type { FBox, FEngine, FIndexBuffer, FVertexBuffer, FilamentModule } from './filament.js';
|
|
4
|
+
|
|
5
|
+
export type GeometryKind = 'box' | 'sphere' | 'plane';
|
|
6
|
+
|
|
7
|
+
export interface MeshData {
|
|
8
|
+
positions: Float32Array;
|
|
9
|
+
normals: Float32Array;
|
|
10
|
+
uvs: Float32Array;
|
|
11
|
+
indices: Uint16Array | Uint32Array;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
class Builder {
|
|
15
|
+
p: number[] = [];
|
|
16
|
+
n: number[] = [];
|
|
17
|
+
uv: number[] = [];
|
|
18
|
+
i: number[] = [];
|
|
19
|
+
done(): MeshData {
|
|
20
|
+
const vertexCount = this.p.length / 3;
|
|
21
|
+
return {
|
|
22
|
+
positions: new Float32Array(this.p),
|
|
23
|
+
normals: new Float32Array(this.n),
|
|
24
|
+
uvs: new Float32Array(this.uv),
|
|
25
|
+
indices: vertexCount > 65535 ? new Uint32Array(this.i) : new Uint16Array(this.i),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Three.js BoxGeometry: 24 vertices, 12 triangles per 1x1x1 segment grid. */
|
|
31
|
+
export function buildBox(width = 1, height = 1, depth = 1): MeshData {
|
|
32
|
+
const b = new Builder();
|
|
33
|
+
const face = (u: number, v: number, w: number, udir: number, vdir: number, fw: number, fh: number, fd: number): void => {
|
|
34
|
+
const start = b.p.length / 3;
|
|
35
|
+
const hw = fw / 2;
|
|
36
|
+
const hh = fh / 2;
|
|
37
|
+
for (let iy = 0; iy < 2; iy++) {
|
|
38
|
+
const y = iy * fh - hh;
|
|
39
|
+
for (let ix = 0; ix < 2; ix++) {
|
|
40
|
+
const x = ix * fw - hw;
|
|
41
|
+
const pos = [0, 0, 0];
|
|
42
|
+
pos[u] = x * udir;
|
|
43
|
+
pos[v] = y * vdir;
|
|
44
|
+
pos[w] = fd / 2;
|
|
45
|
+
const nrm = [0, 0, 0];
|
|
46
|
+
nrm[w] = fd > 0 ? 1 : -1;
|
|
47
|
+
b.p.push(pos[0], pos[1], pos[2]);
|
|
48
|
+
b.n.push(nrm[0], nrm[1], nrm[2]);
|
|
49
|
+
b.uv.push(ix, 1 - iy);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
// Grid 1x1: vertices a=0, b=2, c=3, d=1 of the 2x2 vertex layout.
|
|
53
|
+
b.i.push(start, start + 2, start + 1, start + 2, start + 3, start + 1);
|
|
54
|
+
};
|
|
55
|
+
face(2, 1, 0, -1, -1, depth, height, width);
|
|
56
|
+
face(2, 1, 0, 1, -1, depth, height, -width);
|
|
57
|
+
face(0, 2, 1, 1, 1, width, depth, height);
|
|
58
|
+
face(0, 2, 1, 1, -1, width, depth, -height);
|
|
59
|
+
face(0, 1, 2, 1, -1, width, height, depth);
|
|
60
|
+
face(0, 1, 2, -1, -1, width, height, -depth);
|
|
61
|
+
return b.done();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Three.js SphereGeometry (full sphere). */
|
|
65
|
+
export function buildSphere(radius = 1, widthSegments = 32, heightSegments = 16): MeshData {
|
|
66
|
+
const ws = Math.max(3, Math.floor(widthSegments));
|
|
67
|
+
const hs = Math.max(2, Math.floor(heightSegments));
|
|
68
|
+
const b = new Builder();
|
|
69
|
+
for (let iy = 0; iy <= hs; iy++) {
|
|
70
|
+
const v = iy / hs;
|
|
71
|
+
const theta = v * Math.PI;
|
|
72
|
+
for (let ix = 0; ix <= ws; ix++) {
|
|
73
|
+
const u = ix / ws;
|
|
74
|
+
const phi = u * Math.PI * 2;
|
|
75
|
+
const x = -Math.cos(phi) * Math.sin(theta);
|
|
76
|
+
const y = Math.cos(theta);
|
|
77
|
+
const z = Math.sin(phi) * Math.sin(theta);
|
|
78
|
+
b.p.push(radius * x, radius * y, radius * z);
|
|
79
|
+
b.n.push(x, y, z);
|
|
80
|
+
b.uv.push(u, 1 - v);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const row = ws + 1;
|
|
84
|
+
for (let iy = 0; iy < hs; iy++) {
|
|
85
|
+
for (let ix = 0; ix < ws; ix++) {
|
|
86
|
+
const a = iy * row + ix + 1;
|
|
87
|
+
const bb = iy * row + ix;
|
|
88
|
+
const c = (iy + 1) * row + ix;
|
|
89
|
+
const d = (iy + 1) * row + ix + 1;
|
|
90
|
+
if (iy !== 0) b.i.push(a, bb, d);
|
|
91
|
+
if (iy !== hs - 1) b.i.push(bb, c, d);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return b.done();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Three.js PlaneGeometry: in the XY plane facing +Z. */
|
|
98
|
+
export function buildPlane(width = 1, height = 1, widthSegments = 1, heightSegments = 1): MeshData {
|
|
99
|
+
const gx = Math.max(1, Math.floor(widthSegments));
|
|
100
|
+
const gy = Math.max(1, Math.floor(heightSegments));
|
|
101
|
+
const b = new Builder();
|
|
102
|
+
for (let iy = 0; iy <= gy; iy++) {
|
|
103
|
+
const y = (iy * height) / gy - height / 2;
|
|
104
|
+
for (let ix = 0; ix <= gx; ix++) {
|
|
105
|
+
b.p.push((ix * width) / gx - width / 2, -y, 0);
|
|
106
|
+
b.n.push(0, 0, 1);
|
|
107
|
+
b.uv.push(ix / gx, 1 - iy / gy);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const row = gx + 1;
|
|
111
|
+
for (let iy = 0; iy < gy; iy++) {
|
|
112
|
+
for (let ix = 0; ix < gx; ix++) {
|
|
113
|
+
const a = ix + row * iy;
|
|
114
|
+
const bb = ix + row * (iy + 1);
|
|
115
|
+
const c = ix + 1 + row * (iy + 1);
|
|
116
|
+
const d = ix + 1 + row * iy;
|
|
117
|
+
b.i.push(a, bb, d, bb, c, d);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return b.done();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function buildGeometry(kind: GeometryKind, args: readonly number[] = []): MeshData {
|
|
124
|
+
switch (kind) {
|
|
125
|
+
case 'box':
|
|
126
|
+
return buildBox(args[0], args[1], args[2]);
|
|
127
|
+
case 'sphere':
|
|
128
|
+
return buildSphere(args[0], args[1], args[2]);
|
|
129
|
+
case 'plane':
|
|
130
|
+
return buildPlane(args[0], args[1], args[2], args[3]);
|
|
131
|
+
default:
|
|
132
|
+
throw new Error(`@krate/3d: unknown geometry kind "${String(kind)}"`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function boundsOf(positions: Float32Array): FBox {
|
|
137
|
+
const min = [Infinity, Infinity, Infinity];
|
|
138
|
+
const max = [-Infinity, -Infinity, -Infinity];
|
|
139
|
+
for (let i = 0; i < positions.length; i += 3) {
|
|
140
|
+
for (let k = 0; k < 3; k++) {
|
|
141
|
+
const v = positions[i + k];
|
|
142
|
+
if (v < min[k]) min[k] = v;
|
|
143
|
+
if (v > max[k]) max[k] = v;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
center: [0, 1, 2].map((k) => (min[k] + max[k]) / 2),
|
|
148
|
+
halfExtent: [0, 1, 2].map((k) => (max[k] - min[k]) / 2),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface GpuGeometry {
|
|
153
|
+
vb: FVertexBuffer;
|
|
154
|
+
ib: FIndexBuffer;
|
|
155
|
+
box: FBox;
|
|
156
|
+
indexCount: number;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Uploads positions, tangent frames (from SurfaceOrientation) and uv0. */
|
|
160
|
+
export function uploadGeometry(F: FilamentModule, engine: FEngine, data: MeshData): GpuGeometry {
|
|
161
|
+
const count = data.positions.length / 3;
|
|
162
|
+
const tri = data.indices.length / 3;
|
|
163
|
+
// filament.js wraps normals/uvs/positions/triangles* without returning the
|
|
164
|
+
// builder (and keeps the copied buffers on the JS object), so the calls are
|
|
165
|
+
// not chained and build() runs on the same object.
|
|
166
|
+
const sob = new F.SurfaceOrientation$Builder();
|
|
167
|
+
sob.vertexCount(count);
|
|
168
|
+
sob.normals(data.normals, 0);
|
|
169
|
+
sob.uvs(data.uvs, 0);
|
|
170
|
+
sob.positions(data.positions, 0);
|
|
171
|
+
sob.triangleCount(tri);
|
|
172
|
+
if (data.indices instanceof Uint32Array) sob.triangles32(data.indices);
|
|
173
|
+
else sob.triangles16(data.indices);
|
|
174
|
+
const orientation = sob.build();
|
|
175
|
+
const A = F.VertexAttribute;
|
|
176
|
+
const T = F.VertexBuffer$AttributeType;
|
|
177
|
+
const vb = F.VertexBuffer.Builder()
|
|
178
|
+
.vertexCount(count)
|
|
179
|
+
.bufferCount(3)
|
|
180
|
+
.attribute(A.POSITION, 0, T.FLOAT3, 0, 0)
|
|
181
|
+
.attribute(A.TANGENTS, 1, T.SHORT4, 0, 0)
|
|
182
|
+
.normalized(A.TANGENTS)
|
|
183
|
+
.attribute(A.UV0, 2, T.FLOAT2, 0, 0)
|
|
184
|
+
.build(engine);
|
|
185
|
+
vb.setBufferAt(engine, 0, data.positions);
|
|
186
|
+
vb.setBufferAt(engine, 1, orientation.getQuats(count));
|
|
187
|
+
vb.setBufferAt(engine, 2, data.uvs);
|
|
188
|
+
orientation.delete();
|
|
189
|
+
const ib = F.IndexBuffer.Builder()
|
|
190
|
+
.indexCount(data.indices.length)
|
|
191
|
+
.bufferType(data.indices instanceof Uint32Array ? F.IndexBuffer$IndexType.UINT : F.IndexBuffer$IndexType.USHORT)
|
|
192
|
+
.build(engine);
|
|
193
|
+
ib.setBuffer(engine, data.indices);
|
|
194
|
+
return { vb, ib, box: boundsOf(data.positions), indexCount: data.indices.length };
|
|
195
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// glTF loading through Filament's gltfio. KTX2 textures are decoded by the
|
|
2
|
+
// Ktx2Provider that filament.js wires into loadResources, so no extra setup.
|
|
3
|
+
|
|
4
|
+
import { getCurrentScene } from './context.js';
|
|
5
|
+
import type { FAsset, FEntity } from './filament.js';
|
|
6
|
+
import { defaultFetch } from './materials.js';
|
|
7
|
+
import { rt } from './rt.js';
|
|
8
|
+
import type { Scene3D } from './scene.js';
|
|
9
|
+
|
|
10
|
+
export interface GLTFState {
|
|
11
|
+
status: 'loading' | 'ready' | 'error';
|
|
12
|
+
asset: FAsset | null;
|
|
13
|
+
entities: FEntity[];
|
|
14
|
+
error: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface GLTFResult {
|
|
18
|
+
readonly status: GLTFState['status'];
|
|
19
|
+
readonly asset: FAsset | null;
|
|
20
|
+
readonly entities: FEntity[];
|
|
21
|
+
readonly error: unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface UseGLTFOptions {
|
|
25
|
+
/** Add the loaded entities to the scene (default true). */
|
|
26
|
+
add?: boolean;
|
|
27
|
+
scene?: Scene3D;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Loads a .gltf/.glb into the current scene. Fields are reactive: read them inside an effect. */
|
|
31
|
+
export function useGLTF(url: string, options: UseGLTFOptions = {}): GLTFResult {
|
|
32
|
+
const [state, setState] = rt().createSignal<GLTFState>({ status: 'loading', asset: null, entities: [], error: null });
|
|
33
|
+
const fail = (error: unknown): void => setState({ status: 'error', asset: null, entities: [], error });
|
|
34
|
+
const scene = options.scene ?? getCurrentScene();
|
|
35
|
+
if (!scene) {
|
|
36
|
+
fail(new Error('@krate/3d: useGLTF needs a <Canvas> scene'));
|
|
37
|
+
} else {
|
|
38
|
+
scene.whenReady(() => {
|
|
39
|
+
const fetchBytes = scene.opts.fetchBytes ?? defaultFetch;
|
|
40
|
+
void fetchBytes(url).then((bytes) => {
|
|
41
|
+
if (scene.disposed) return;
|
|
42
|
+
const loader = scene.getLoader();
|
|
43
|
+
const asset = loader.createAsset(bytes);
|
|
44
|
+
if (!asset) throw new Error(`@krate/3d: could not parse ${url}`);
|
|
45
|
+
const base = new URL(url, typeof document !== 'undefined' ? document.baseURI : 'http://localhost/').href;
|
|
46
|
+
asset.loadResources(
|
|
47
|
+
() => {
|
|
48
|
+
if (scene.disposed) return;
|
|
49
|
+
const entities = asset.getEntities();
|
|
50
|
+
if (options.add !== false) scene.fscene.addEntities(entities);
|
|
51
|
+
scene.track(() => {
|
|
52
|
+
scene.fscene.removeEntities(entities);
|
|
53
|
+
loader.destroyAsset(asset);
|
|
54
|
+
});
|
|
55
|
+
setState({ status: 'ready', asset, entities, error: null });
|
|
56
|
+
},
|
|
57
|
+
null,
|
|
58
|
+
base
|
|
59
|
+
);
|
|
60
|
+
}).catch(fail);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
get status() {
|
|
65
|
+
return state().status;
|
|
66
|
+
},
|
|
67
|
+
get asset() {
|
|
68
|
+
return state().asset;
|
|
69
|
+
},
|
|
70
|
+
get entities() {
|
|
71
|
+
return state().entities;
|
|
72
|
+
},
|
|
73
|
+
get error() {
|
|
74
|
+
return state().error;
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { getCurrentScene } from './context.js';
|
|
2
|
+
import type { FrameCallback } from './scene.js';
|
|
3
|
+
import { rt } from './rt.js';
|
|
4
|
+
|
|
5
|
+
/** Runs `cb(delta, time)` (seconds) every frame of the current scene, before transforms are flushed. */
|
|
6
|
+
export function useFrame(cb: FrameCallback): void {
|
|
7
|
+
const scene = getCurrentScene();
|
|
8
|
+
if (!scene) throw new Error('@krate/3d: useFrame must be used inside a <Canvas>');
|
|
9
|
+
rt().onCleanup(scene.onFrame(cb));
|
|
10
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// @krate/3d runtime: the component fallback path plus everything the compiled path shares.
|
|
2
|
+
|
|
3
|
+
export { Canvas } from './canvas.js';
|
|
4
|
+
export { OrbitControls, OrbitController } from './controls.js';
|
|
5
|
+
export { Environment, createEnvironment, setEnvironmentPresets } from './environment.js';
|
|
6
|
+
export { useGLTF } from './gltf.js';
|
|
7
|
+
export type { GLTFResult, GLTFState, UseGLTFOptions } from './gltf.js';
|
|
8
|
+
export { useFrame } from './hooks.js';
|
|
9
|
+
export { getCurrentScene } from './context.js';
|
|
10
|
+
export { Scene3D } from './scene.js';
|
|
11
|
+
export type { SceneOptions, GeometryHandle, MeshHandle, LightHandle, InitialTransform, FrameCallback } from './scene.js';
|
|
12
|
+
export { __k3d } from './compiled.js';
|
|
13
|
+
export * from './calibration.js';
|
|
14
|
+
export { srgbToLinear, colorToLinear, parseColor } from './color.js';
|
|
15
|
+
export type { CanvasMountProps } from './mount.js';
|
|
16
|
+
export type { FilamentModule, FilamentSource } from './filament.js';
|
|
17
|
+
export type { MaterialKind, MaterialParams } from './materials.js';
|
|
18
|
+
export type { LightProps as SceneLightProps } from './lights.js';
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Lights. Intensities here are already in Filament units (see calibration.ts).
|
|
2
|
+
|
|
3
|
+
import { colorToLinear } from './color.js';
|
|
4
|
+
import type { Entities } from './entities.js';
|
|
5
|
+
import type { FEngine, FEntity, FIndirectLight, FilamentModule } from './filament.js';
|
|
6
|
+
|
|
7
|
+
export type LightKind = 'directional' | 'point' | 'spot' | 'ambient';
|
|
8
|
+
export type LightColor = string | number | readonly number[];
|
|
9
|
+
|
|
10
|
+
export interface LightProps {
|
|
11
|
+
/** Filament units: lux for directional, lumens for point and spot, IBL intensity for ambient. */
|
|
12
|
+
intensity?: number;
|
|
13
|
+
/** Linear RGB triple, or a CSS/hex color converted from sRGB. */
|
|
14
|
+
color?: LightColor;
|
|
15
|
+
position?: readonly number[];
|
|
16
|
+
direction?: readonly number[];
|
|
17
|
+
castShadows?: boolean;
|
|
18
|
+
/** Point and spot falloff radius in world units. */
|
|
19
|
+
falloff?: number;
|
|
20
|
+
/** Spot cone angles in radians. */
|
|
21
|
+
inner?: number;
|
|
22
|
+
outer?: number;
|
|
23
|
+
/** Use Filament's SUN type for a directional light. */
|
|
24
|
+
sun?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function lightRgb(color: LightColor | undefined): number[] {
|
|
28
|
+
if (color === undefined) return [1, 1, 1];
|
|
29
|
+
return typeof color === 'string' || typeof color === 'number' ? colorToLinear(color) : [color[0], color[1], color[2]];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Builds a directional, point or spot light entity. `shadows` is the Canvas-level switch. */
|
|
33
|
+
export function buildLight(
|
|
34
|
+
F: FilamentModule,
|
|
35
|
+
engine: FEngine,
|
|
36
|
+
entities: Entities,
|
|
37
|
+
kind: Exclude<LightKind, 'ambient'>,
|
|
38
|
+
props: LightProps,
|
|
39
|
+
shadows: boolean
|
|
40
|
+
): FEntity {
|
|
41
|
+
const T = F.LightManager$Type;
|
|
42
|
+
const type = kind === 'directional' ? (props.sun ? T.SUN : T.DIRECTIONAL) : kind === 'point' ? T.POINT : T.SPOT;
|
|
43
|
+
const entity = entities.create();
|
|
44
|
+
const b = F.LightManager.Builder(type)
|
|
45
|
+
.color(lightRgb(props.color))
|
|
46
|
+
.intensity(props.intensity ?? 0)
|
|
47
|
+
.castShadows(shadows && !!props.castShadows);
|
|
48
|
+
if (props.direction && kind !== 'point') b.direction([...props.direction]);
|
|
49
|
+
if (props.position && kind !== 'directional') b.position([...props.position]);
|
|
50
|
+
if (kind !== 'directional' && props.falloff !== undefined) b.falloff(props.falloff);
|
|
51
|
+
if (kind === 'spot') b.spotLightCone(props.inner ?? 0, props.outer ?? Math.PI / 4);
|
|
52
|
+
b.build(engine, entity);
|
|
53
|
+
return entity;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Live update of a built light (reactive props). */
|
|
57
|
+
export function updateLight(engine: FEngine, entity: FEntity, name: string, value: number | readonly number[]): void {
|
|
58
|
+
const lm = engine.getLightManager();
|
|
59
|
+
const inst = lm.getInstance(entity);
|
|
60
|
+
if (name === 'intensity') lm.setIntensity(inst, value as number);
|
|
61
|
+
else if (name === 'color') lm.setColor(inst, lightRgb(value as LightColor));
|
|
62
|
+
else if (name === 'position') lm.setPosition(inst, [...(value as readonly number[])]);
|
|
63
|
+
else if (name === 'direction') lm.setDirection(inst, [...(value as readonly number[])]);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Uniform ambient light as a one-band spherical-harmonics IndirectLight. */
|
|
67
|
+
export function buildAmbient(F: FilamentModule, engine: FEngine, props: LightProps): FIndirectLight {
|
|
68
|
+
const [r, g, b] = lightRgb(props.color);
|
|
69
|
+
// Band 0 of the irradiance SH for uniform radiance L is 2 * sqrt(pi) * L.
|
|
70
|
+
const k = 2 * Math.sqrt(Math.PI);
|
|
71
|
+
return F.IndirectLight.Builder()
|
|
72
|
+
.irradianceSh(1, [r * k, g * k, b * k])
|
|
73
|
+
.intensity(props.intensity ?? 0)
|
|
74
|
+
.build(engine);
|
|
75
|
+
}
|