@clarity-js/three 0.0.0-stage → 0.1.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.
- package/README.md +103 -2
- package/index.d.ts +181 -0
- package/package.json +30 -4
- package/src/Model.js +148 -0
- package/src/Scene.js +369 -0
- package/src/core.js +384 -0
- package/src/describe.js +28 -0
- package/src/index.js +29 -0
- package/src/objects.js +188 -0
package/README.md
CHANGED
|
@@ -1,3 +1,104 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @clarity-js/three
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Declarative three.js scenes for [Clarity.js](https://clarity-js.com). Every prop can be bound
|
|
4
|
+
to a signal, and a changed signal updates only the three.js property bound to it. Nothing is
|
|
5
|
+
re-rendered or diffed.
|
|
6
|
+
|
|
7
|
+
```clarity
|
|
8
|
+
import { Scene, Mesh, AmbientLight, DirectionalLight } from '@clarity-js/three'
|
|
9
|
+
import { frame } from '@ozsarman/clarityjs/game-loop'
|
|
10
|
+
|
|
11
|
+
component Spinner() {
|
|
12
|
+
state angle = 0
|
|
13
|
+
state hot = false
|
|
14
|
+
onMount { frame((dt) => { angle += dt }) }
|
|
15
|
+
render {
|
|
16
|
+
<Scene camera={ { position: [0, 1.5, 4] } } background="#0b1020" shadows>
|
|
17
|
+
<AmbientLight intensity={ 0.4 } />
|
|
18
|
+
<DirectionalLight position={ [3, 5, 2] } castShadow />
|
|
19
|
+
<Mesh geometry="box" color={ hot ? "tomato" : "#6c63ff" } rotation-y={ angle }
|
|
20
|
+
castShadow on:click={ hot = !hot } />
|
|
21
|
+
</Scene>
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm i @clarity-js/three three
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
`three` is a peer dependency (r170 or newer). The package needs `@ozsarman/clarityjs` 0.12 or newer.
|
|
31
|
+
|
|
32
|
+
## How it works
|
|
33
|
+
|
|
34
|
+
Each 3D component returns a hidden `<clarity-3d>` element that holds its three.js object.
|
|
35
|
+
The DOM tree mirrors the scene graph: when the element is connected, its object is added to the
|
|
36
|
+
nearest 3D parent; when it is removed, so is the object. As a result `<list>`, `<when>`, keyed
|
|
37
|
+
reordering and nesting work through Clarity's normal reconciliation.
|
|
38
|
+
|
|
39
|
+
- **Rendering on demand.** A scene renders when a bound prop changes, while `frame()` callbacks
|
|
40
|
+
run, or after `invalidate()`. It does not draw 60 frames a second while idle. Set `frameloop`
|
|
41
|
+
to `'always'` or `'demand'` to change this.
|
|
42
|
+
- **Renderer.** `renderer="auto"` (the default) uses WebGPU when the browser can provide an
|
|
43
|
+
adapter and the classic WebGLRenderer otherwise. The WebGPU renderer is a dynamic import, so
|
|
44
|
+
browsers without WebGPU never download it. `'webgpu'` and `'webgl'` force one of them.
|
|
45
|
+
`api.backend` reports `'webgpu'`, `'webgl2'` or `'webgl'`.
|
|
46
|
+
- **Cleanup.** Geometries, materials and URL textures created by a component are disposed when
|
|
47
|
+
it unmounts. Unmounting `<Scene>` disposes the renderer.
|
|
48
|
+
|
|
49
|
+
## Components
|
|
50
|
+
|
|
51
|
+
| Component | Props (all reactive unless noted) |
|
|
52
|
+
|---|---|
|
|
53
|
+
| `<Scene>` | `camera {fov, near, far, position, lookAt}`, `background`, `fog {color, near, far}`, `shadows`, `renderer`, `frameloop`, `toneMapping`, `dpr`, `controls="orbit"`, `effects` (post-processing pipeline), `onCreated(api)`, `ref` |
|
|
54
|
+
| `<Mesh>` | `geometry` (box, sphere, plane, cylinder, cone, capsule, torus, torusKnot, ring, circle, icosahedron, …, or a `BufferGeometry`), `args`, `material` (standard, physical, basic, lambert, phong, toon, normal, or a `Material`), `color`, `emissive`, `metalness`, `roughness`, `opacity`, `wireframe`, `map` (URL or texture), … |
|
|
55
|
+
| `<Group>` | transform node for its children |
|
|
56
|
+
| `<Primitive object={…}>` | any existing `Object3D` (loaded model, `InstancedMesh`, `Points`, …) |
|
|
57
|
+
| `<Model src="x.glb">` | glTF/GLB, cached per URL, cloned per instance (skinned meshes work); `animation` (clip name or index, cross-fades), `animationSpeed`, `onLoad`, `onError`; children show while loading |
|
|
58
|
+
| `<Camera>` | a camera in the scene graph; becomes the active camera while `active` |
|
|
59
|
+
| `<AmbientLight>` `<HemisphereLight>` `<DirectionalLight>` `<PointLight>` `<SpotLight>` | `color`, `intensity`, shadows: `castShadow`, `shadowMapSize`, `shadowCameraSize`, `shadowBias` |
|
|
60
|
+
|
|
61
|
+
Every object accepts `name`, `position`, `rotation`, `scale` (arrays, `{x,y,z}` or a number),
|
|
62
|
+
`position-x` / `rotation-y` / …, `lookAt`, `visible`, `castShadow`, `receiveShadow`, `userData`,
|
|
63
|
+
`ref` (receives the three.js object) and pointer events: `on:click`, `onPointerOver`,
|
|
64
|
+
`onPointerOut`, `onPointerDown`, `onPointerUp`, `onPointerMove`, `onDoubleClick`. Events bubble
|
|
65
|
+
from the hit object up through its groups, and `e.stopPropagation()` stops them.
|
|
66
|
+
|
|
67
|
+
## Game loop and input
|
|
68
|
+
|
|
69
|
+
`frame((dt, elapsed) => …)` (also exported as `useFrame`) runs on Clarity's shared frame clock.
|
|
70
|
+
Scenes render right after the frame callbacks, in the same tick. The `clock` can be paused,
|
|
71
|
+
stepped (`clock.step(1/60)`), fast-forwarded (`clock.advance(10)`) and slowed down
|
|
72
|
+
(`clock.timeScale`). This makes a game deterministic, both for tests and for AI agents.
|
|
73
|
+
|
|
74
|
+
`createInput()` from `@ozsarman/clarityjs/input` provides keyboard, gamepad, pointer and
|
|
75
|
+
on-screen joystick input as signals: `input.axis('x')`, `input.key('Space')`,
|
|
76
|
+
`input.onPress('KeyP', fn)`, `input.joystick(el)`.
|
|
77
|
+
|
|
78
|
+
## Games that AI agents can play
|
|
79
|
+
|
|
80
|
+
A component's AI contract is how an agent sees and acts on a game:
|
|
81
|
+
|
|
82
|
+
```clarity
|
|
83
|
+
ai:readable = [status, score, player, enemies]
|
|
84
|
+
ai:actionable = [start, steer]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Reads return copies, so an agent cannot change state by mutating what it read. Writes go
|
|
88
|
+
through actions only. `describeScene(api)` lists the named objects with their world positions,
|
|
89
|
+
and `userData={ { ai: {...} } }` adds per-object data. See the **Orb Run** demo
|
|
90
|
+
(`website/demos-src/src/OrbRun.clarity`): it has an in-page AI pilot, and its `window.clarity`
|
|
91
|
+
bridge gives outside agents the same contract plus the clock.
|
|
92
|
+
|
|
93
|
+
## Escape hatches
|
|
94
|
+
|
|
95
|
+
- `ref={ mesh }` gives you the three.js object. Change it directly inside `frame()` for hot
|
|
96
|
+
paths with thousands of objects. The scene keeps rendering while frame callbacks run.
|
|
97
|
+
- `invalidate()` requests a render after manual changes in `frameloop="demand"` scenes.
|
|
98
|
+
- `THREE` is re-exported: `import { THREE } from '@clarity-js/three'`.
|
|
99
|
+
- `setGLTFLoader(loader)` lets you use a loader with Draco or KTX2 attached.
|
|
100
|
+
- `effects={ ({ renderer, scene, camera }) => composer }` renders through an EffectComposer (bloom,
|
|
101
|
+
grading …); return an object with `render(dt)`, `setSize(w, h)` and `dispose()`. Custom GLSL
|
|
102
|
+
(`ShaderMaterial`, `onBeforeCompile`) needs the WebGL renderer: set `renderer="webgl"`.
|
|
103
|
+
- See the **Coral Light** demo (`website/demos-src/src/CoralLight.clarity`, `src/reef/`) for a full
|
|
104
|
+
game: a procedural instanced reef in `<Primitive>`, pearls as a `<list>`, bloom via `effects`.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Type definitions for @clarity-js/three
|
|
2
|
+
|
|
3
|
+
import type * as THREE_NS from 'three';
|
|
4
|
+
|
|
5
|
+
/** A prop may be a plain value, a signal/computed, or a getter function. */
|
|
6
|
+
export type Reactive<T> = T | { get(): T } | (() => T);
|
|
7
|
+
export type Vec3 = [number, number, number] | { x?: number; y?: number; z?: number } | number;
|
|
8
|
+
export type ColorValue = string | number | THREE_NS.Color;
|
|
9
|
+
type Ref<T> = { set(v: T): void } | ((v: T) => void) | { current: T | null };
|
|
10
|
+
|
|
11
|
+
export interface PointerEvent3D {
|
|
12
|
+
type: string;
|
|
13
|
+
/** The object whose handler is running (the event bubbles up the scene graph). */
|
|
14
|
+
object: THREE_NS.Object3D;
|
|
15
|
+
/** The object the ray actually hit. */
|
|
16
|
+
hit?: THREE_NS.Object3D;
|
|
17
|
+
point?: THREE_NS.Vector3;
|
|
18
|
+
distance?: number;
|
|
19
|
+
uv?: THREE_NS.Vector2;
|
|
20
|
+
face?: THREE_NS.Face | null;
|
|
21
|
+
nativeEvent: Event;
|
|
22
|
+
stopPropagation(): void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface Object3DProps {
|
|
26
|
+
name?: Reactive<string>;
|
|
27
|
+
position?: Reactive<Vec3>;
|
|
28
|
+
rotation?: Reactive<Vec3>;
|
|
29
|
+
scale?: Reactive<Vec3>;
|
|
30
|
+
'position-x'?: Reactive<number>; 'position-y'?: Reactive<number>; 'position-z'?: Reactive<number>;
|
|
31
|
+
'rotation-x'?: Reactive<number>; 'rotation-y'?: Reactive<number>; 'rotation-z'?: Reactive<number>;
|
|
32
|
+
'scale-x'?: Reactive<number>; 'scale-y'?: Reactive<number>; 'scale-z'?: Reactive<number>;
|
|
33
|
+
lookAt?: Reactive<Vec3>;
|
|
34
|
+
visible?: Reactive<boolean>;
|
|
35
|
+
castShadow?: Reactive<boolean>;
|
|
36
|
+
receiveShadow?: Reactive<boolean>;
|
|
37
|
+
renderOrder?: Reactive<number>;
|
|
38
|
+
/** Merged into object.userData; userData.ai is reported by describeScene(). */
|
|
39
|
+
userData?: Reactive<Record<string, unknown>>;
|
|
40
|
+
ref?: Ref<THREE_NS.Object3D>;
|
|
41
|
+
children?: unknown;
|
|
42
|
+
onClick?: (e: PointerEvent3D) => void;
|
|
43
|
+
onDoubleClick?: (e: PointerEvent3D) => void;
|
|
44
|
+
onPointerDown?: (e: PointerEvent3D) => void;
|
|
45
|
+
onPointerUp?: (e: PointerEvent3D) => void;
|
|
46
|
+
onPointerMove?: (e: PointerEvent3D) => void;
|
|
47
|
+
onPointerOver?: (e: PointerEvent3D) => void;
|
|
48
|
+
onPointerOut?: (e: PointerEvent3D) => void;
|
|
49
|
+
onContextMenu?: (e: PointerEvent3D) => void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type GeometryName = 'box' | 'sphere' | 'plane' | 'circle' | 'cylinder' | 'cone' | 'capsule' | 'torus' |
|
|
53
|
+
'torusKnot' | 'ring' | 'icosahedron' | 'dodecahedron' | 'octahedron' | 'tetrahedron';
|
|
54
|
+
export type MaterialName = 'standard' | 'physical' | 'basic' | 'lambert' | 'phong' | 'toon' | 'normal' | 'depth';
|
|
55
|
+
|
|
56
|
+
export interface MeshProps extends Object3DProps {
|
|
57
|
+
geometry?: Reactive<GeometryName | THREE_NS.BufferGeometry>;
|
|
58
|
+
/** Constructor arguments of the geometry, e.g. [width, height, depth] for a box. */
|
|
59
|
+
args?: Reactive<unknown[]>;
|
|
60
|
+
material?: Reactive<MaterialName | THREE_NS.Material>;
|
|
61
|
+
color?: Reactive<ColorValue>;
|
|
62
|
+
emissive?: Reactive<ColorValue>;
|
|
63
|
+
emissiveIntensity?: Reactive<number>;
|
|
64
|
+
metalness?: Reactive<number>;
|
|
65
|
+
roughness?: Reactive<number>;
|
|
66
|
+
opacity?: Reactive<number>;
|
|
67
|
+
transparent?: Reactive<boolean>;
|
|
68
|
+
wireframe?: Reactive<boolean>;
|
|
69
|
+
flatShading?: Reactive<boolean>;
|
|
70
|
+
side?: Reactive<'front' | 'back' | 'double' | number>;
|
|
71
|
+
/** A URL (loaded once, shared, freed when unused) or a THREE.Texture. Same for the other *Map props. */
|
|
72
|
+
map?: Reactive<string | THREE_NS.Texture | null>;
|
|
73
|
+
normalMap?: Reactive<string | THREE_NS.Texture | null>;
|
|
74
|
+
roughnessMap?: Reactive<string | THREE_NS.Texture | null>;
|
|
75
|
+
metalnessMap?: Reactive<string | THREE_NS.Texture | null>;
|
|
76
|
+
emissiveMap?: Reactive<string | THREE_NS.Texture | null>;
|
|
77
|
+
[materialProp: string]: unknown;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface EffectsPipeline {
|
|
81
|
+
render(dt: number): void;
|
|
82
|
+
setSize?(width: number, height: number): void;
|
|
83
|
+
setPixelRatio?(ratio: number): void;
|
|
84
|
+
dispose?(): void;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface SceneApi {
|
|
88
|
+
scene: THREE_NS.Scene;
|
|
89
|
+
readonly camera: THREE_NS.Camera;
|
|
90
|
+
readonly renderer: unknown;
|
|
91
|
+
/** 'webgpu' | 'webgl2' (WebGPU renderer on its WebGL backend) | 'webgl' | 'custom' */
|
|
92
|
+
readonly backend: string | null;
|
|
93
|
+
readonly controls: unknown;
|
|
94
|
+
readonly effects: EffectsPipeline | null;
|
|
95
|
+
readonly renders: number;
|
|
96
|
+
canvas: HTMLCanvasElement;
|
|
97
|
+
el: HTMLElement;
|
|
98
|
+
invalidate(): void;
|
|
99
|
+
screenshot(type?: string): string;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface SceneProps {
|
|
103
|
+
camera?: Reactive<{ fov?: number; near?: number; far?: number; zoom?: number; position?: Vec3; lookAt?: Vec3 }>;
|
|
104
|
+
background?: Reactive<ColorValue | THREE_NS.Texture | null>;
|
|
105
|
+
fog?: Reactive<{ color?: ColorValue; near?: number; far?: number } | [ColorValue, number, number] | null>;
|
|
106
|
+
shadows?: Reactive<boolean | 'basic' | 'vsm'>;
|
|
107
|
+
/** 'auto' (default): WebGPU when the browser has an adapter, else WebGL. */
|
|
108
|
+
renderer?: 'auto' | 'webgpu' | 'webgl' | ((canvas: HTMLCanvasElement, opts: object) => unknown);
|
|
109
|
+
/** 'auto' (default): render on change and while frame() callbacks run; 'always'; 'demand' (only on change/invalidate()). */
|
|
110
|
+
frameloop?: Reactive<'auto' | 'always' | 'demand'>;
|
|
111
|
+
toneMapping?: Reactive<'aces' | 'agx' | 'neutral' | 'linear' | 'cineon' | 'reinhard' | 'none'>;
|
|
112
|
+
/** Maximum device pixel ratio (default 2). */
|
|
113
|
+
dpr?: Reactive<number>;
|
|
114
|
+
antialias?: boolean;
|
|
115
|
+
alpha?: boolean;
|
|
116
|
+
controls?: 'orbit' | ((camera: THREE_NS.Camera, canvas: HTMLCanvasElement) => unknown);
|
|
117
|
+
/**
|
|
118
|
+
* Post-processing: return a pipeline that renders instead of renderer.render — e.g. an
|
|
119
|
+
* EffectComposer with UnrealBloomPass. setSize/setPixelRatio are called on resize.
|
|
120
|
+
*/
|
|
121
|
+
effects?: (ctx: { renderer: unknown; scene: THREE_NS.Scene; camera: THREE_NS.Camera; canvas: HTMLCanvasElement }) =>
|
|
122
|
+
EffectsPipeline | Promise<EffectsPipeline>;
|
|
123
|
+
/** Set to false to keep the cursor unchanged over clickable meshes. */
|
|
124
|
+
cursor?: Reactive<boolean>;
|
|
125
|
+
width?: Reactive<string>;
|
|
126
|
+
height?: Reactive<string>;
|
|
127
|
+
class?: Reactive<string>;
|
|
128
|
+
style?: Reactive<string>;
|
|
129
|
+
onCreated?: (api: SceneApi) => void;
|
|
130
|
+
ref?: Ref<SceneApi>;
|
|
131
|
+
children?: unknown;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface LightProps extends Object3DProps {
|
|
135
|
+
color?: Reactive<ColorValue>;
|
|
136
|
+
intensity?: Reactive<number>;
|
|
137
|
+
}
|
|
138
|
+
export interface ShadowLightProps extends LightProps {
|
|
139
|
+
shadowMapSize?: Reactive<number>;
|
|
140
|
+
shadowBias?: Reactive<number>;
|
|
141
|
+
/** Half-size of a directional light's shadow camera. */
|
|
142
|
+
shadowCameraSize?: Reactive<number>;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export declare function Scene(props?: SceneProps): HTMLElement;
|
|
146
|
+
export declare function Mesh(props?: MeshProps): HTMLElement;
|
|
147
|
+
export declare function Group(props?: Object3DProps): HTMLElement;
|
|
148
|
+
export declare function Primitive(props?: Object3DProps & { object: Reactive<THREE_NS.Object3D> }): HTMLElement;
|
|
149
|
+
export declare function Camera(props?: Object3DProps & { fov?: Reactive<number>; near?: Reactive<number>; far?: Reactive<number>; active?: Reactive<boolean> }): HTMLElement;
|
|
150
|
+
export declare function AmbientLight(props?: LightProps): HTMLElement;
|
|
151
|
+
export declare function HemisphereLight(props?: LightProps & { groundColor?: Reactive<ColorValue> }): HTMLElement;
|
|
152
|
+
export declare function DirectionalLight(props?: ShadowLightProps & { target?: Reactive<Vec3> }): HTMLElement;
|
|
153
|
+
export declare function PointLight(props?: ShadowLightProps & { distance?: Reactive<number>; decay?: Reactive<number> }): HTMLElement;
|
|
154
|
+
export declare function SpotLight(props?: ShadowLightProps & { distance?: Reactive<number>; angle?: Reactive<number>; penumbra?: Reactive<number>; decay?: Reactive<number>; target?: Reactive<Vec3> }): HTMLElement;
|
|
155
|
+
|
|
156
|
+
export interface ModelProps extends Object3DProps {
|
|
157
|
+
src: Reactive<string>;
|
|
158
|
+
/** Clip name or index; changing it cross-fades. */
|
|
159
|
+
animation?: Reactive<string | number | null>;
|
|
160
|
+
animationSpeed?: Reactive<number>;
|
|
161
|
+
onLoad?: (model: { scene: THREE_NS.Object3D; animations: THREE_NS.AnimationClip[]; gltf: unknown }) => void;
|
|
162
|
+
onError?: (error: unknown) => void;
|
|
163
|
+
}
|
|
164
|
+
export declare function Model(props: ModelProps): HTMLElement;
|
|
165
|
+
export declare function loadGLTF(src: string): Promise<{ scene: THREE_NS.Group; animations: THREE_NS.AnimationClip[] }>;
|
|
166
|
+
export declare function clearModelCache(src?: string): Promise<void>;
|
|
167
|
+
export declare function setGLTFLoader(loader: unknown): void;
|
|
168
|
+
|
|
169
|
+
export interface SceneEntry { name: string; type: string; position: [number, number, number]; visible: boolean; data?: unknown; }
|
|
170
|
+
/** Named objects with world positions (all objects with { all: true }); userData.ai → data. */
|
|
171
|
+
export declare function describeScene(sceneOrApi: THREE_NS.Object3D | SceneApi, options?: { all?: boolean; digits?: number }): SceneEntry[];
|
|
172
|
+
|
|
173
|
+
export declare function createRenderer(canvas: HTMLCanvasElement, options?: { renderer?: SceneProps['renderer']; antialias?: boolean; alpha?: boolean }): Promise<unknown>;
|
|
174
|
+
export declare function setRendererFactory(factory: ((canvas: HTMLCanvasElement, opts: object) => unknown) | null): void;
|
|
175
|
+
/** Request a render of every live <Scene> (after changing three.js objects by hand). */
|
|
176
|
+
export declare function invalidate(): void;
|
|
177
|
+
export declare const GEOMETRIES: Record<GeometryName, unknown>;
|
|
178
|
+
export declare const MATERIALS: Record<MaterialName, unknown>;
|
|
179
|
+
|
|
180
|
+
export { frame, frame as useFrame, clock } from '@ozsarman/clarityjs/game-loop';
|
|
181
|
+
export * as THREE from 'three';
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarity-js/three",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Declarative, signal-driven three.js scenes for Clarity.js — WebGPU with WebGL fallback, glTF models, picking, a shared frame clock and AI-readable scene state.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"module": "./src/index.js",
|
|
8
|
+
"types": "./index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./index.d.ts",
|
|
12
|
+
"import": "./src/index.js",
|
|
13
|
+
"default": "./src/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": ["src/", "index.d.ts", "README.md"],
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"keywords": ["clarity", "@ozsarman/clarityjs", "three", "threejs", "webgpu", "webgl", "3d", "game", "signals", "ai-native"],
|
|
19
|
+
"author": "Özdemir Şarman",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"@ozsarman/clarityjs": ">=0.12.0",
|
|
23
|
+
"three": ">=0.170.0"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "https://gitlab.com/ozsarman/clarity.js.git",
|
|
28
|
+
"directory": "packages/clarity-three"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://clarity-js.com/docs/three",
|
|
31
|
+
"engines": { "node": ">=18.0.0" }
|
|
32
|
+
}
|
package/src/Model.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// @clarity-js/three — <Model>: glTF / GLB models with a shared cache and animations.
|
|
2
|
+
|
|
3
|
+
import * as THREE from 'three';
|
|
4
|
+
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
|
5
|
+
import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';
|
|
6
|
+
import { _component, onDispose } from '@ozsarman/clarityjs/runtime';
|
|
7
|
+
import { node3d, bind, read, callback, appendChildren } from './core.js';
|
|
8
|
+
|
|
9
|
+
const _cache = new Map(); // url → Promise<gltf>
|
|
10
|
+
let _loader = null;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Use your own configured loader (e.g. with DRACOLoader / KTX2Loader attached).
|
|
14
|
+
* setGLTFLoader(loader) — any object with loadAsync(url) or load(url, onLoad, onProgress, onError)
|
|
15
|
+
*/
|
|
16
|
+
export function setGLTFLoader(loader) { _loader = loader; }
|
|
17
|
+
|
|
18
|
+
/** Load (once) and cache a glTF/GLB file. Every <Model> with the same src shares it. */
|
|
19
|
+
export function loadGLTF(src) {
|
|
20
|
+
let p = _cache.get(src);
|
|
21
|
+
if (!p) {
|
|
22
|
+
const loader = _loader ?? (_loader = new GLTFLoader());
|
|
23
|
+
p = (loader.loadAsync
|
|
24
|
+
? loader.loadAsync(src)
|
|
25
|
+
: new Promise((res, rej) => loader.load(src, res, undefined, rej)));
|
|
26
|
+
p.catch(() => _cache.delete(src));
|
|
27
|
+
_cache.set(src, p);
|
|
28
|
+
}
|
|
29
|
+
return p;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Free a cached model's GPU resources (all of them when src is omitted). */
|
|
33
|
+
export async function clearModelCache(src) {
|
|
34
|
+
const urls = src ? [src] : [..._cache.keys()];
|
|
35
|
+
for (const u of urls) {
|
|
36
|
+
const p = _cache.get(u);
|
|
37
|
+
_cache.delete(u);
|
|
38
|
+
try {
|
|
39
|
+
const gltf = await p;
|
|
40
|
+
gltf.scene.traverse((o) => {
|
|
41
|
+
o.geometry?.dispose?.();
|
|
42
|
+
const mats = Array.isArray(o.material) ? o.material : o.material ? [o.material] : [];
|
|
43
|
+
for (const m of mats) {
|
|
44
|
+
for (const v of Object.values(m)) if (v && v.isTexture) v.dispose();
|
|
45
|
+
m.dispose();
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
} catch { /* failed loads hold nothing */ }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* <Model src="/hero.glb" position scale rotation castShadow receiveShadow
|
|
54
|
+
* animation="Run" animationSpeed={1} onLoad={({ scene, animations }) => …} onError />
|
|
55
|
+
*
|
|
56
|
+
* Instances are cloned with SkeletonUtils, so skinned/animated models can appear many
|
|
57
|
+
* times. `animation` (clip name or index, reactive) cross-fades between clips.
|
|
58
|
+
* `src` may be reactive; while a model is loading the children (e.g. a placeholder
|
|
59
|
+
* <Mesh>) are shown.
|
|
60
|
+
*/
|
|
61
|
+
export function Model(props = {}) {
|
|
62
|
+
return _component(() => {
|
|
63
|
+
const group = new THREE.Group();
|
|
64
|
+
const el = node3d('model', group, props);
|
|
65
|
+
const placeholder = new THREE.Group();
|
|
66
|
+
group.add(placeholder);
|
|
67
|
+
let inst = null;
|
|
68
|
+
let mixer = null;
|
|
69
|
+
let clips = [];
|
|
70
|
+
let action = null;
|
|
71
|
+
let token = 0;
|
|
72
|
+
let disposed = false;
|
|
73
|
+
|
|
74
|
+
const shadows = () => {
|
|
75
|
+
if (!inst) return;
|
|
76
|
+
const cs = read(props.castShadow), rs = read(props.receiveShadow);
|
|
77
|
+
inst.traverse((o) => {
|
|
78
|
+
if (!o.isMesh) return;
|
|
79
|
+
if (cs !== undefined) o.castShadow = !!cs;
|
|
80
|
+
if (rs !== undefined) o.receiveShadow = !!rs;
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const play = (which) => {
|
|
85
|
+
if (!mixer || which == null || which === false) {
|
|
86
|
+
if (action) { action.fadeOut(0.2); action = null; }
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const clip = typeof which === 'number' ? clips[which] : THREE.AnimationClip.findByName(clips, String(which));
|
|
90
|
+
if (!clip) { console.warn(`[clarity-three] <Model> has no animation "${which}". Available: ${clips.map((c) => c.name).join(', ') || 'none'}`); return; }
|
|
91
|
+
const next = mixer.clipAction(clip);
|
|
92
|
+
if (next === action) return;
|
|
93
|
+
next.reset().fadeIn(action ? 0.25 : 0).play();
|
|
94
|
+
if (action) action.fadeOut(0.25);
|
|
95
|
+
action = next;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const detachMixer = () => {
|
|
99
|
+
if (!mixer) return;
|
|
100
|
+
mixer.stopAllAction();
|
|
101
|
+
el.__c3ctx?._removeMixer(mixer);
|
|
102
|
+
el.__c3mixer = null;
|
|
103
|
+
mixer = null;
|
|
104
|
+
action = null;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
bind(el, props.src, (src) => {
|
|
108
|
+
const my = ++token;
|
|
109
|
+
if (!src) return;
|
|
110
|
+
loadGLTF(src).then((gltf) => {
|
|
111
|
+
if (disposed || my !== token) return;
|
|
112
|
+
detachMixer();
|
|
113
|
+
if (inst) group.remove(inst);
|
|
114
|
+
inst = SkeletonUtils.clone(gltf.scene);
|
|
115
|
+
placeholder.visible = false;
|
|
116
|
+
group.add(inst);
|
|
117
|
+
shadows();
|
|
118
|
+
clips = gltf.animations ?? [];
|
|
119
|
+
if (clips.length) {
|
|
120
|
+
mixer = new THREE.AnimationMixer(inst);
|
|
121
|
+
el.__c3mixer = mixer;
|
|
122
|
+
el.__c3ctx?._addMixer(mixer);
|
|
123
|
+
mixer.timeScale = Number(read(props.animationSpeed) ?? 1);
|
|
124
|
+
play(read(props.animation));
|
|
125
|
+
}
|
|
126
|
+
el.__c3ctx?._attached(el);
|
|
127
|
+
el.__c3ctx?.invalidate();
|
|
128
|
+
callback(props.onLoad)?.({ scene: inst, animations: clips, gltf });
|
|
129
|
+
}).catch((e) => {
|
|
130
|
+
if (disposed || my !== token) return;
|
|
131
|
+
const onError = callback(props.onError);
|
|
132
|
+
if (onError) onError(e);
|
|
133
|
+
else console.error(`[clarity-three] could not load model ${src}:`, e?.message ?? e);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
bind(el, props.animation, (v) => play(v));
|
|
137
|
+
bind(el, props.animationSpeed, (v) => { if (mixer && v != null) mixer.timeScale = Number(v); });
|
|
138
|
+
bind(el, () => [read(props.castShadow), read(props.receiveShadow)], shadows);
|
|
139
|
+
|
|
140
|
+
onDispose(() => { disposed = true; detachMixer(); });
|
|
141
|
+
|
|
142
|
+
// Children are a placeholder shown until the model has loaded.
|
|
143
|
+
const holder = node3d('group', placeholder, {});
|
|
144
|
+
appendChildren(holder, props.children);
|
|
145
|
+
el.appendChild(holder);
|
|
146
|
+
return el;
|
|
147
|
+
}, 'Model');
|
|
148
|
+
}
|