@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/src/core.js ADDED
@@ -0,0 +1,384 @@
1
+ // @clarity-js/three — core: the DOM ↔ scene-graph bridge, reactive prop binding,
2
+ // vectors, refs, events and resource caches.
3
+ //
4
+ // Every 3D component returns a hidden <clarity-3d> element that carries its
5
+ // three.js object. The DOM tree mirrors the scene graph: when an element is
6
+ // connected, its object is added to the object of the nearest <clarity-3d>
7
+ // ancestor; when it is disconnected, it is removed. So <list>, <when>, keyed
8
+ // reordering and nesting all work through Clarity's normal DOM reconciliation,
9
+ // with no virtual tree and no diffing of the scene.
10
+
11
+ import * as THREE from 'three';
12
+ import { effect, untrack, isReactive, _toNode } from '@ozsarman/clarityjs/runtime';
13
+
14
+ export const TAG = 'clarity-3d';
15
+
16
+ // ─── Prop reading / binding ──────────────────────────────────────────────────
17
+
18
+ /** Event props (onClick, onPointerOver …) are never treated as getters. */
19
+ const isEventKey = (k) => /^on[A-Z]/.test(k);
20
+
21
+ /** A prop is dynamic when it is a signal/computed or a getter function. */
22
+ export function isDynamic(v) {
23
+ return isReactive(v) || typeof v === 'function';
24
+ }
25
+
26
+ /** Read a prop that may be a signal, a computed, a getter or a plain value. */
27
+ export function read(v) {
28
+ if (isReactive(v)) return v.get();
29
+ if (typeof v === 'function') return v();
30
+ return v;
31
+ }
32
+
33
+ /**
34
+ * Apply `value` to the scene through `apply(v)`: once for a plain value, and
35
+ * again whenever a reactive value changes (the effect belongs to the current
36
+ * component and is disposed with it). Each change requests a render.
37
+ */
38
+ export function bind(el, value, apply) {
39
+ if (value === undefined) return;
40
+ if (isDynamic(value)) {
41
+ effect(() => {
42
+ const v = read(value);
43
+ untrack(() => apply(v));
44
+ invalidateEl(el);
45
+ });
46
+ } else {
47
+ apply(value);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * A callback prop. The compiler wraps an expression that reads state in a
53
+ * computed, so onCreated={ (api) => ready = true } arrives as a computed whose
54
+ * value is the function; unwrap it without calling it.
55
+ */
56
+ export function callback(v) {
57
+ if (isReactive(v)) v = v.peek();
58
+ return typeof v === 'function' ? v : null;
59
+ }
60
+
61
+ /** Combine several props into one bindable value (dynamic if any part is). */
62
+ export function combine(...vals) {
63
+ return vals.some(isDynamic) ? () => vals.map(read) : vals;
64
+ }
65
+
66
+ // ─── Vectors ─────────────────────────────────────────────────────────────────
67
+
68
+ const num = (v, d = 0) => {
69
+ const n = Number(v);
70
+ return Number.isFinite(n) ? n : d;
71
+ };
72
+
73
+ /** Set a Vector3 / Euler from [x,y,z], {x,y,z}, a number (all axes) or a Vector3. */
74
+ export function setVec(target, v) {
75
+ if (v == null) return;
76
+ if (typeof v === 'number') { target.set(v, v, v); return; }
77
+ if (Array.isArray(v)) { target.set(num(v[0]), num(v[1]), num(v[2])); return; }
78
+ if (typeof v === 'object') {
79
+ target.set(
80
+ 'x' in v ? num(v.x) : target.x,
81
+ 'y' in v ? num(v.y) : target.y,
82
+ 'z' in v ? num(v.z) : target.z,
83
+ );
84
+ }
85
+ }
86
+
87
+ /** [x,y,z] array of a Vector3-like, rounded for readable AI/debug output. */
88
+ export function vec3(v, digits = 3) {
89
+ const f = 10 ** digits;
90
+ return [Math.round(v.x * f) / f, Math.round(v.y * f) / f, Math.round(v.z * f) / f];
91
+ }
92
+
93
+ // ─── The <clarity-3d> element ────────────────────────────────────────────────
94
+
95
+ const _warned = new Set();
96
+ function warnOnce(key, msg) {
97
+ if (_warned.has(key)) return;
98
+ _warned.add(key);
99
+ console.warn(msg);
100
+ }
101
+
102
+ function nearest3d(el) {
103
+ let p = el.parentElement;
104
+ while (p && !p.__c3obj) p = p.parentElement;
105
+ return p;
106
+ }
107
+
108
+ /** Called when a <clarity-3d> element is connected: add its object to the parent object. */
109
+ export function attach(el) {
110
+ const obj = el.__c3obj;
111
+ if (!obj || el.__c3kind === 'scene') return;
112
+ const p = nearest3d(el);
113
+ if (!p) {
114
+ warnOnce('orphan', '[clarity-three] a 3D component is not inside <Scene> — it will not be rendered.');
115
+ return;
116
+ }
117
+ const parentObj = p.__c3obj;
118
+ const ctx = p.__c3ctx ?? null;
119
+ if (obj.parent !== parentObj) parentObj.add(obj);
120
+ for (const x of el.__c3extras ?? []) if (x.parent !== parentObj) parentObj.add(x);
121
+ el.__c3parent = parentObj;
122
+ el.__c3ctx = ctx;
123
+ if (ctx) {
124
+ ctx._attached(el);
125
+ ctx.invalidate();
126
+ }
127
+ if (el.__c3onAttach) el.__c3onAttach(ctx);
128
+ }
129
+
130
+ /** Called when a <clarity-3d> element is disconnected: remove its object from the scene. */
131
+ export function detach(el) {
132
+ const obj = el.__c3obj;
133
+ if (!obj || el.__c3kind === 'scene') return;
134
+ const parentObj = el.__c3parent;
135
+ if (parentObj) {
136
+ if (obj.parent === parentObj) parentObj.remove(obj);
137
+ for (const x of el.__c3extras ?? []) if (x.parent === parentObj) parentObj.remove(x);
138
+ }
139
+ const ctx = el.__c3ctx;
140
+ if (ctx) {
141
+ ctx._detached(el);
142
+ ctx.invalidate();
143
+ }
144
+ if (el.__c3onDetach) el.__c3onDetach(ctx);
145
+ el.__c3parent = null;
146
+ el.__c3ctx = null;
147
+ }
148
+
149
+ let _defined = false;
150
+ function ensureElement() {
151
+ if (_defined) return true;
152
+ if (typeof customElements === 'undefined' || typeof HTMLElement === 'undefined') return false;
153
+ if (!customElements.get(TAG)) {
154
+ customElements.define(TAG, class Clarity3DElement extends HTMLElement {
155
+ connectedCallback() { attach(this); }
156
+ disconnectedCallback() { detach(this); }
157
+ });
158
+ }
159
+ _defined = true;
160
+ return true;
161
+ }
162
+
163
+ /** Request a render of the scene this element belongs to. */
164
+ export function invalidateEl(el) {
165
+ const ctx = el && (el.__c3ctx ?? (el.__c3kind === 'scene' ? el.__c3ctx : null));
166
+ if (ctx) ctx.invalidate();
167
+ }
168
+
169
+ /** Swap the three.js object an element carries (e.g. a reactive <Primitive object>). */
170
+ export function swapObject(el, obj) {
171
+ if (el.__c3obj === obj) return;
172
+ const connected = el.isConnected && el.__c3parent;
173
+ if (connected) detach(el);
174
+ el.__c3obj = obj;
175
+ if (connected) attach(el);
176
+ }
177
+
178
+ /** Append children (Clarity's { default: [...] } slot, an array or a node). */
179
+ export function appendChildren(el, children) {
180
+ const list = children == null ? []
181
+ : Array.isArray(children) ? children
182
+ : (typeof children === 'object' && 'default' in children && !children.nodeType) ? children.default
183
+ : [children];
184
+ const n = _toNode(list);
185
+ if (n) el.appendChild(n);
186
+ }
187
+
188
+ // ─── Common Object3D props ───────────────────────────────────────────────────
189
+
190
+ const EVENT_PROPS = ['onClick', 'onDoubleClick', 'onPointerDown', 'onPointerUp', 'onPointerMove', 'onPointerOver', 'onPointerOut', 'onContextMenu'];
191
+ const AXIS_PROP = /^(position|rotation|scale)-([xyz])$/;
192
+
193
+ function assignRef(ref, value) {
194
+ if (!ref) return;
195
+ if (typeof ref === 'function') ref(value);
196
+ else if (ref._type === 'signal' && typeof ref.set === 'function') ref.set(value);
197
+ else if (typeof ref === 'object' && 'current' in ref) ref.current = value;
198
+ }
199
+
200
+ /**
201
+ * Create the hidden element for a 3D object and bind the props every object
202
+ * shares: name, position, rotation, scale (also position-x …), lookAt, visible,
203
+ * castShadow, receiveShadow, renderOrder, userData, ref, pointer events, children.
204
+ */
205
+ export function node3d(kind, obj, props = {}) {
206
+ ensureElement();
207
+ const el = typeof document !== 'undefined' ? document.createElement(TAG) : { setAttribute() {}, appendChild() {} };
208
+ el.setAttribute('data-kind', kind);
209
+ el.__c3obj = obj;
210
+ el.__c3kind = kind;
211
+ if (el.style) el.style.display = 'none';
212
+
213
+ bind(el, props.name, (v) => {
214
+ obj.name = v == null ? '' : String(v);
215
+ if (el.setAttribute) { if (v == null) el.removeAttribute?.('data-name'); else el.setAttribute('data-name', obj.name); }
216
+ });
217
+ if (props.position !== undefined) bind(el, props.position, (v) => setVec(obj.position, v));
218
+ if (props.rotation !== undefined) bind(el, props.rotation, (v) => setVec(obj.rotation, v));
219
+ if (props.scale !== undefined) bind(el, props.scale, (v) => setVec(obj.scale, v));
220
+ for (const k of Object.keys(props)) {
221
+ const m = AXIS_PROP.exec(k);
222
+ if (m) bind(el, props[k], (v) => { obj[m[1]][m[2]] = num(v); });
223
+ }
224
+ if (props.lookAt !== undefined) {
225
+ bind(el, props.lookAt, (v) => {
226
+ if (v == null) return;
227
+ const t = Array.isArray(v) ? new THREE.Vector3(num(v[0]), num(v[1]), num(v[2])) : new THREE.Vector3(num(v.x), num(v.y), num(v.z));
228
+ obj.lookAt(t);
229
+ });
230
+ }
231
+ bind(el, props.visible, (v) => { obj.visible = v !== false; });
232
+ bind(el, props.castShadow, (v) => { obj.castShadow = !!v; });
233
+ bind(el, props.receiveShadow, (v) => { obj.receiveShadow = !!v; });
234
+ bind(el, props.renderOrder, (v) => { obj.renderOrder = num(v); });
235
+ bind(el, props.userData, (v) => { if (v && typeof v === 'object') Object.assign(obj.userData, v); });
236
+
237
+ const handlers = {};
238
+ let any = false;
239
+ for (const k of EVENT_PROPS) {
240
+ const fn = callback(props[k]);
241
+ if (fn) { handlers[k] = fn; any = true; }
242
+ }
243
+ if (any) obj.userData.__c3h = handlers;
244
+
245
+ assignRef(props.ref, obj);
246
+ return el;
247
+ }
248
+
249
+ // ─── Geometry & material factories ───────────────────────────────────────────
250
+
251
+ export const GEOMETRIES = {
252
+ box: THREE.BoxGeometry,
253
+ sphere: THREE.SphereGeometry,
254
+ plane: THREE.PlaneGeometry,
255
+ circle: THREE.CircleGeometry,
256
+ cylinder: THREE.CylinderGeometry,
257
+ cone: THREE.ConeGeometry,
258
+ capsule: THREE.CapsuleGeometry,
259
+ torus: THREE.TorusGeometry,
260
+ torusKnot: THREE.TorusKnotGeometry,
261
+ ring: THREE.RingGeometry,
262
+ icosahedron: THREE.IcosahedronGeometry,
263
+ dodecahedron: THREE.DodecahedronGeometry,
264
+ octahedron: THREE.OctahedronGeometry,
265
+ tetrahedron: THREE.TetrahedronGeometry,
266
+ };
267
+
268
+ /** → [geometry, ownedByUs] */
269
+ export function makeGeometry(kind, args) {
270
+ if (kind && kind.isBufferGeometry) return [kind, false];
271
+ const name = kind ?? 'box';
272
+ const C = GEOMETRIES[name];
273
+ if (!C) throw new Error(`[clarity-three] unknown geometry "${name}" — use one of ${Object.keys(GEOMETRIES).join(', ')} or pass a THREE.BufferGeometry`);
274
+ return [new C(...(Array.isArray(args) ? args : args == null ? [] : [args])), true];
275
+ }
276
+
277
+ export const MATERIALS = {
278
+ standard: THREE.MeshStandardMaterial,
279
+ physical: THREE.MeshPhysicalMaterial,
280
+ basic: THREE.MeshBasicMaterial,
281
+ lambert: THREE.MeshLambertMaterial,
282
+ phong: THREE.MeshPhongMaterial,
283
+ toon: THREE.MeshToonMaterial,
284
+ normal: THREE.MeshNormalMaterial,
285
+ depth: THREE.MeshDepthMaterial,
286
+ };
287
+
288
+ /** → [material, ownedByUs] */
289
+ export function makeMaterial(kind) {
290
+ if (kind && kind.isMaterial) return [kind, false];
291
+ const name = kind ?? 'standard';
292
+ const C = MATERIALS[name];
293
+ if (!C) throw new Error(`[clarity-three] unknown material "${name}" — use one of ${Object.keys(MATERIALS).join(', ')} or pass a THREE.Material`);
294
+ return [new C(), true];
295
+ }
296
+
297
+ /** Material props a <Mesh> forwards (besides any other key the material has). */
298
+ export const MATERIAL_PROPS = [
299
+ 'color', 'emissive', 'emissiveIntensity', 'specular', 'shininess', 'metalness', 'roughness',
300
+ 'opacity', 'transparent', 'wireframe', 'flatShading', 'side', 'depthWrite', 'depthTest',
301
+ 'map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'alphaMap', 'aoMap',
302
+ 'envMapIntensity', 'clearcoat', 'clearcoatRoughness', 'transmission', 'ior', 'thickness',
303
+ 'sheen', 'iridescence', 'toneMapped', 'fog', 'alphaTest', 'vertexColors',
304
+ ];
305
+
306
+ const SIDES = { front: THREE.FrontSide, back: THREE.BackSide, double: THREE.DoubleSide };
307
+ const RECOMPILE = new Set(['flatShading', 'transparent', 'vertexColors', 'side', 'fog']);
308
+
309
+ /** Set one material parameter; texture props accept a URL (cached, ref-counted). */
310
+ export function setMaterialParam(mat, key, value, owned) {
311
+ if (!mat) return;
312
+ if (key.endsWith('Map') || key === 'map') {
313
+ const prev = owned.get(key);
314
+ let tex = value ?? null;
315
+ if (typeof value === 'string') tex = acquireTexture(value, key === 'map' || key === 'emissiveMap');
316
+ if (prev && prev !== value) { releaseTexture(prev); owned.delete(key); }
317
+ if (typeof value === 'string') owned.set(key, value);
318
+ const had = !!mat[key];
319
+ mat[key] = tex;
320
+ if (had !== !!tex) mat.needsUpdate = true;
321
+ return;
322
+ }
323
+ if (mat[key] && mat[key].isColor) {
324
+ if (value != null) mat[key].set(value);
325
+ return;
326
+ }
327
+ if (key === 'side') {
328
+ mat.side = typeof value === 'string' ? (SIDES[value] ?? THREE.FrontSide) : (value ?? THREE.FrontSide);
329
+ mat.needsUpdate = true;
330
+ return;
331
+ }
332
+ if (key === 'opacity') {
333
+ mat.opacity = num(value, 1);
334
+ if (!owned.has('__explicitTransparent')) {
335
+ const t = mat.opacity < 1;
336
+ if (mat.transparent !== t) { mat.transparent = t; mat.needsUpdate = true; }
337
+ }
338
+ return;
339
+ }
340
+ if (key === 'transparent') owned.set('__explicitTransparent', true);
341
+ if (key in mat) {
342
+ mat[key] = value;
343
+ if (RECOMPILE.has(key)) mat.needsUpdate = true;
344
+ }
345
+ }
346
+
347
+ // ─── Texture cache (ref-counted by URL) ──────────────────────────────────────
348
+
349
+ const _textures = new Map(); // url → { tex, refs }
350
+ let _texLoader = null;
351
+
352
+ export function acquireTexture(url, srgb = true) {
353
+ let e = _textures.get(url);
354
+ if (!e) {
355
+ _texLoader ??= new THREE.TextureLoader();
356
+ const tex = _texLoader.load(url, () => { for (const ctx of _contexts) ctx.invalidate(); });
357
+ if (srgb) tex.colorSpace = THREE.SRGBColorSpace;
358
+ e = { tex, refs: 0 };
359
+ _textures.set(url, e);
360
+ }
361
+ e.refs++;
362
+ return e.tex;
363
+ }
364
+
365
+ export function releaseTexture(url) {
366
+ const e = _textures.get(url);
367
+ if (!e) return;
368
+ if (--e.refs <= 0) {
369
+ e.tex.dispose();
370
+ _textures.delete(url);
371
+ }
372
+ }
373
+
374
+ /** @internal — how many textures the cache holds (tests). */
375
+ export function _textureCount() { return _textures.size; }
376
+
377
+ // ─── Live scene contexts ─────────────────────────────────────────────────────
378
+
379
+ export const _contexts = new Set();
380
+
381
+ /** Request a render of every live <Scene> (after changing three.js objects by hand). */
382
+ export function invalidate() {
383
+ for (const ctx of _contexts) ctx.invalidate();
384
+ }
@@ -0,0 +1,28 @@
1
+ // @clarity-js/three — describeScene(): the scene as plain data, for AI agents,
2
+ // tests and debugging. Pair it with ai:readable to let an agent "see" a game.
3
+
4
+ import * as THREE from 'three';
5
+ import { vec3 } from './core.js';
6
+
7
+ /**
8
+ * describeScene(sceneOrApi, { all = false, digits = 2 })
9
+ * → [{ name, type, position: [x, y, z] (world), visible, data? }]
10
+ *
11
+ * Only named objects are listed unless `all` is true. `object.userData.ai` (set it with
12
+ * the userData prop: userData={{ ai: { hp: 3 } }}) is copied into `data`.
13
+ */
14
+ export function describeScene(target, { all = false, digits = 2 } = {}) {
15
+ const scene = target && target.isObject3D ? target : target?.scene;
16
+ if (!scene) return [];
17
+ const out = [];
18
+ const wp = new THREE.Vector3();
19
+ scene.traverse((o) => {
20
+ if (o === scene) return;
21
+ if (!all && !o.name) return;
22
+ o.getWorldPosition(wp);
23
+ const entry = { name: o.name, type: o.type, position: vec3(wp, digits), visible: o.visible };
24
+ if (o.userData && o.userData.ai !== undefined) entry.data = o.userData.ai;
25
+ out.push(entry);
26
+ });
27
+ return out;
28
+ }
package/src/index.js ADDED
@@ -0,0 +1,29 @@
1
+ // @clarity-js/three — declarative, signal-driven three.js scenes for Clarity.js.
2
+ //
3
+ // import { Scene, Mesh, DirectionalLight, AmbientLight, frame } from '@clarity-js/three'
4
+ //
5
+ // component Spinner() {
6
+ // state angle = 0
7
+ // onMount { frame((dt) => { angle += dt }) }
8
+ // render {
9
+ // <Scene camera={ { position: [0, 1.5, 4] } } background="#0b1020" shadows>
10
+ // <AmbientLight intensity={ 0.4 } />
11
+ // <DirectionalLight position={ [3, 5, 2] } castShadow />
12
+ // <Mesh geometry="box" color="tomato" rotation-y={ angle } castShadow />
13
+ // </Scene>
14
+ // }
15
+ // }
16
+ //
17
+ // A changed signal updates only the three.js property bound to it; nothing is
18
+ // re-rendered or diffed. Scenes render on demand through the shared frame clock.
19
+
20
+ export { Scene, createRenderer, setRendererFactory } from './Scene.js';
21
+ export {
22
+ Mesh, Group, Primitive, Camera,
23
+ AmbientLight, HemisphereLight, DirectionalLight, PointLight, SpotLight,
24
+ } from './objects.js';
25
+ export { Model, loadGLTF, clearModelCache, setGLTFLoader } from './Model.js';
26
+ export { describeScene } from './describe.js';
27
+ export { invalidate, GEOMETRIES, MATERIALS } from './core.js';
28
+ export { frame, frame as useFrame, clock } from '@ozsarman/clarityjs/game-loop';
29
+ export * as THREE from 'three';
package/src/objects.js ADDED
@@ -0,0 +1,188 @@
1
+ // @clarity-js/three — scene objects: Mesh, Group, Primitive, lights, Camera.
2
+
3
+ import * as THREE from 'three';
4
+ import { _component, onDispose } from '@ozsarman/clarityjs/runtime';
5
+ import {
6
+ node3d, bind, combine, read, isDynamic, setVec, appendChildren, swapObject,
7
+ makeGeometry, makeMaterial, setMaterialParam, MATERIAL_PROPS, releaseTexture,
8
+ } from './core.js';
9
+
10
+ /**
11
+ * <Mesh geometry="box" args={[1, 1, 1]} material="standard" color="tomato" position={[0, 1, 0]} />
12
+ *
13
+ * geometry: box | sphere | plane | circle | cylinder | cone | capsule | torus | torusKnot |
14
+ * ring | icosahedron | dodecahedron | octahedron | tetrahedron, or a THREE.BufferGeometry
15
+ * args: constructor arguments of that geometry
16
+ * material: standard (default) | physical | basic | lambert | phong | toon | normal | depth,
17
+ * or a THREE.Material
18
+ * Material props: color, emissive, emissiveIntensity, metalness, roughness, opacity, wireframe,
19
+ * map (URL or texture), side, flatShading … — every one may be reactive.
20
+ * Geometry and material created here are disposed when the component unmounts.
21
+ */
22
+ export function Mesh(props = {}) {
23
+ return _component(() => {
24
+ const mesh = new THREE.Mesh();
25
+ const el = node3d('mesh', mesh, props);
26
+
27
+ let ownGeo = null;
28
+ bind(el, combine(props.geometry, props.args), ([g, args]) => {
29
+ const [geo, owned] = makeGeometry(g, args);
30
+ if (ownGeo && ownGeo !== geo) ownGeo.dispose();
31
+ ownGeo = owned ? geo : null;
32
+ mesh.geometry = geo;
33
+ });
34
+
35
+ let ownMat = null;
36
+ const params = new Map(); // last value of every material prop
37
+ const texOwned = new Map(); // material key → texture URL we hold
38
+ bind(el, props.material, (m) => {
39
+ const [mat, owned] = makeMaterial(m);
40
+ if (ownMat && ownMat !== mat) ownMat.dispose();
41
+ ownMat = owned ? mat : null;
42
+ mesh.material = mat;
43
+ for (const [k, v] of params) setMaterialParam(mat, k, v, texOwned);
44
+ });
45
+ if (props.material === undefined) {
46
+ const [mat] = makeMaterial('standard');
47
+ ownMat = mat;
48
+ mesh.material = mat;
49
+ }
50
+ for (const k of MATERIAL_PROPS) {
51
+ if (props[k] === undefined) continue;
52
+ bind(el, props[k], (v) => {
53
+ params.set(k, v);
54
+ setMaterialParam(mesh.material, k, v, texOwned);
55
+ });
56
+ }
57
+
58
+ onDispose(() => {
59
+ ownGeo?.dispose();
60
+ ownMat?.dispose();
61
+ for (const url of texOwned.values()) if (typeof url === 'string') releaseTexture(url);
62
+ texOwned.clear();
63
+ });
64
+
65
+ appendChildren(el, props.children);
66
+ return el;
67
+ }, 'Mesh');
68
+ }
69
+
70
+ /** <Group position rotation scale> … </Group> — a transform node for its children. */
71
+ export function Group(props = {}) {
72
+ return _component(() => {
73
+ const el = node3d('group', new THREE.Group(), props);
74
+ appendChildren(el, props.children);
75
+ return el;
76
+ }, 'Group');
77
+ }
78
+
79
+ /**
80
+ * <Primitive object={myObject3D} /> — put any three.js object (a loaded model, a custom
81
+ * mesh, an InstancedMesh, Points …) into the scene. `object` may be reactive.
82
+ * The object is not disposed on unmount — whoever created it owns it.
83
+ */
84
+ export function Primitive(props = {}) {
85
+ return _component(() => {
86
+ const first = read(props.object) ?? new THREE.Object3D();
87
+ const el = node3d('primitive', first, { ...props, object: undefined });
88
+ if (isDynamic(props.object)) bind(el, props.object, (o) => swapObject(el, o ?? new THREE.Object3D()));
89
+ appendChildren(el, props.children);
90
+ return el;
91
+ }, 'Primitive');
92
+ }
93
+
94
+ // ─── Lights ──────────────────────────────────────────────────────────────────
95
+
96
+ function shadowProps(el, light, props) {
97
+ bind(el, props.shadowMapSize, (v) => {
98
+ if (!light.shadow || v == null) return;
99
+ light.shadow.mapSize.set(Number(v), Number(v));
100
+ light.shadow.map?.dispose();
101
+ light.shadow.map = null;
102
+ });
103
+ bind(el, props.shadowBias, (v) => { if (light.shadow && v != null) light.shadow.bias = Number(v); });
104
+ bind(el, props.shadowCameraSize, (v) => {
105
+ const c = light.shadow?.camera;
106
+ if (!c || v == null || !c.isOrthographicCamera) return;
107
+ const s = Number(v);
108
+ c.left = -s; c.right = s; c.top = s; c.bottom = -s;
109
+ c.updateProjectionMatrix();
110
+ });
111
+ }
112
+
113
+ function makeLight(name, Ctor, extra) {
114
+ const Light = (props = {}) => _component(() => {
115
+ const light = new Ctor();
116
+ const el = node3d(name, light, props);
117
+ bind(el, props.color, (v) => { if (v != null) light.color.set(v); });
118
+ bind(el, props.intensity, (v) => { if (v != null) light.intensity = Number(v); });
119
+ if (extra) extra(el, light, props);
120
+ onDispose(() => light.dispose?.());
121
+ return el;
122
+ }, name);
123
+ Object.defineProperty(Light, 'name', { value: name });
124
+ return Light;
125
+ }
126
+
127
+ function withTarget(el, light, props) {
128
+ el.__c3extras = [light.target];
129
+ bind(el, props.target, (v) => { if (v != null) setVec(light.target.position, v); });
130
+ }
131
+
132
+ /** <AmbientLight color intensity /> */
133
+ export const AmbientLight = makeLight('AmbientLight', THREE.AmbientLight);
134
+
135
+ /** <HemisphereLight color groundColor intensity /> — sky/ground light. */
136
+ export const HemisphereLight = makeLight('HemisphereLight', THREE.HemisphereLight, (el, l, p) => {
137
+ bind(el, p.groundColor, (v) => { if (v != null) l.groundColor.set(v); });
138
+ });
139
+
140
+ /** <DirectionalLight color intensity position target castShadow shadowMapSize shadowCameraSize /> */
141
+ export const DirectionalLight = makeLight('DirectionalLight', THREE.DirectionalLight, (el, l, p) => {
142
+ if (p.position === undefined) l.position.set(5, 10, 5);
143
+ withTarget(el, l, p);
144
+ shadowProps(el, l, p);
145
+ });
146
+
147
+ /** <PointLight color intensity distance decay position castShadow /> */
148
+ export const PointLight = makeLight('PointLight', THREE.PointLight, (el, l, p) => {
149
+ bind(el, p.distance, (v) => { if (v != null) l.distance = Number(v); });
150
+ bind(el, p.decay, (v) => { if (v != null) l.decay = Number(v); });
151
+ shadowProps(el, l, p);
152
+ });
153
+
154
+ /** <SpotLight color intensity distance angle penumbra decay position target castShadow /> */
155
+ export const SpotLight = makeLight('SpotLight', THREE.SpotLight, (el, l, p) => {
156
+ bind(el, p.distance, (v) => { if (v != null) l.distance = Number(v); });
157
+ bind(el, p.angle, (v) => { if (v != null) l.angle = Number(v); });
158
+ bind(el, p.penumbra, (v) => { if (v != null) l.penumbra = Number(v); });
159
+ bind(el, p.decay, (v) => { if (v != null) l.decay = Number(v); });
160
+ withTarget(el, l, p);
161
+ shadowProps(el, l, p);
162
+ });
163
+
164
+ // ─── Camera ──────────────────────────────────────────────────────────────────
165
+
166
+ /**
167
+ * <Camera fov near far position lookAt active /> — a perspective camera in the scene
168
+ * graph (it can sit inside a <Group> and follow it). While `active` (default true)
169
+ * the <Scene> renders through it instead of its own camera.
170
+ */
171
+ export function Camera(props = {}) {
172
+ return _component(() => {
173
+ const cam = new THREE.PerspectiveCamera(50, 1, 0.1, 1000);
174
+ const el = node3d('camera', cam, props);
175
+ bind(el, props.fov, (v) => { if (v != null) { cam.fov = Number(v); cam.updateProjectionMatrix(); } });
176
+ bind(el, props.near, (v) => { if (v != null) { cam.near = Number(v); cam.updateProjectionMatrix(); } });
177
+ bind(el, props.far, (v) => { if (v != null) { cam.far = Number(v); cam.updateProjectionMatrix(); } });
178
+ let active = true;
179
+ let ctxRef = null;
180
+ bind(el, props.active, (v) => {
181
+ active = v !== false;
182
+ if (ctxRef) ctxRef.setCamera(active ? cam : null);
183
+ });
184
+ el.__c3onAttach = (ctx) => { ctxRef = ctx; if (ctx && active) ctx.setCamera(cam); };
185
+ el.__c3onDetach = (ctx) => { if (ctx && ctx.camera === cam) ctx.setCamera(null); ctxRef = null; };
186
+ return el;
187
+ }, 'Camera');
188
+ }