@vim3d/threejs 0.0.1 → 0.2.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 CHANGED
@@ -1,3 +1,41 @@
1
1
  # @vim3d/threejs
2
2
 
3
- This package is reserved for a Three.js renderer for Vim3D scenes.
3
+ Draws the immutable frame snapshots produced by `@vim3d/core`. Core owns
4
+ channels, expressions, timed edits, and transforms. This package uses the
5
+ snapshot's world matrices directly for non-camera objects.
6
+
7
+ ```ts
8
+ import { compileScene } from '@vim3d/core';
9
+ import { Vim3DPlayer } from '@vim3d/threejs';
10
+
11
+ const compiled = compileScene({ path: 'scene.vim3d', text }, { readFile, frameCount: 120 });
12
+ if ('diagnostics' in compiled) throw new Error(JSON.stringify(compiled.diagnostics));
13
+
14
+ const player = new Vim3DPlayer(compiled.value, { canvas, loop: true });
15
+ player.play();
16
+ // Later: player.pause(), player.seek(60), player.step(-1), or player.stop().
17
+ // On teardown:
18
+ player.dispose();
19
+ ```
20
+
21
+ Pass a canvas (including an `OffscreenCanvas`), or supply a Three.js renderer
22
+ or any compatible `render(scene, camera)` implementation. The player disposes
23
+ only a renderer it created. Choose a snapshot camera by canonical path or
24
+ pass a host camera for an editor view. By default it renders with the first
25
+ visible snapshot camera. A supplied scheduler can drive playback without
26
+ browser animation frames.
27
+
28
+ `renderFrame` and `seek` return core's result; a diagnostic leaves the last
29
+ drawn frame unchanged. Playback stops at the final frame unless looping is
30
+ enabled. Loops require a configured frame count. `setFps` changes playback
31
+ speed only, not the scene's evaluation clock. Use `onFrame` and
32
+ `onDiagnostics` to observe playback.
33
+
34
+ If you already have a snapshot, use `Vim3DThreeScene.applyFrameSnapshot` and
35
+ render its `scene` yourself. Cameras use the snapshot's evaluated position,
36
+ direction, and up to form a rigid view without rig scale or shear.
37
+ Light colors use the snapshot's diffuse RGB and default Three.js intensity
38
+ (core does not expose an intensity field). Surface diffuse alpha controls
39
+ opacity; Phong specular RGB and shininess are mapped directly, and ambient
40
+ RGB is approximated with emissive RGB. Nulls and empty geometry are groups,
41
+ so they do not draw by themselves.
@@ -0,0 +1,64 @@
1
+ import { BoxGeometry, BufferGeometry, CircleGeometry, PlaneGeometry, RingGeometry, SphereGeometry, Vector3, } from 'three';
2
+ export function isLine(primitive) {
3
+ return primitive === 'curve' || primitive === 'ellipse' || primitive === 'circle';
4
+ }
5
+ const segments = (value, minimum) => Math.min(256, Math.max(minimum, Math.floor(value)));
6
+ function grid(args) {
7
+ const [a, b, spacing = 10, x = 0, z = 0] = args;
8
+ if (!args.length)
9
+ return new PlaneGeometry(200, 200);
10
+ if (args.length === 2)
11
+ return new PlaneGeometry(a, b);
12
+ const cellsX = Math.max(0, Math.trunc(a) - 1);
13
+ const cellsZ = Math.max(0, Math.trunc(b ?? a) - 1);
14
+ const width = cellsX * spacing, depth = cellsZ * spacing;
15
+ return new PlaneGeometry(width, depth, segments(cellsX, 1), segments(cellsZ, 1))
16
+ .rotateX(-Math.PI / 2).translate(x + width / 2, 0, z + depth / 2);
17
+ }
18
+ function ellipse(primitive, args) {
19
+ const face = primitive.endsWith('Face');
20
+ const circle = primitive.startsWith('circle');
21
+ const defaultRadii = circle ? [10, 10] : face ? [20, 10] : [10, 15];
22
+ const countOnly = args.length === 1 && primitive === 'ellipseFace';
23
+ const x = countOnly ? defaultRadii[0] : args[0] ?? defaultRadii[0];
24
+ const y = countOnly || !args.length ? defaultRadii[1]
25
+ : primitive === 'circle' && args.length === 2 ? x : args[1] ?? x;
26
+ const count = segments(countOnly ? args[0]
27
+ : primitive === 'circle' && args.length === 2 ? args[1] : args[2] ?? 32, 3);
28
+ if (face)
29
+ return new CircleGeometry(1, count).scale(x, y, 1);
30
+ return new BufferGeometry().setFromPoints(Array.from({ length: count + 1 }, (_, i) => {
31
+ const angle = i / count * Math.PI * 2;
32
+ return new Vector3(x * Math.cos(angle), y * Math.sin(angle), 0);
33
+ }));
34
+ }
35
+ export function createGeometry({ primitive, args, vertices }) {
36
+ switch (primitive) {
37
+ case 'curve': return new BufferGeometry().setFromPoints((vertices ?? []).map(point => new Vector3(...point)));
38
+ case 'cube': return new BoxGeometry(10, 10, 10).translate(5, 5, 5);
39
+ case 'grid': return grid(args);
40
+ case 'sphere': {
41
+ const [width = 10, height = width, detail = 32] = args;
42
+ return new SphereGeometry(1, segments(detail, 3), segments(detail / 2, 2)).scale(width, height, width);
43
+ }
44
+ case 'ellipse':
45
+ case 'ellipseFace':
46
+ case 'circle':
47
+ case 'circleFace': return ellipse(primitive, args);
48
+ case 'ring': {
49
+ const [x = 10, b, detail = 32, width] = args;
50
+ const y = args.length >= 3 ? b : x;
51
+ const halfWidth = width === undefined ? 0.5 : width / 0.5;
52
+ const geometry = new RingGeometry(1, 2, segments(args.length === 2 ? b : detail, 3));
53
+ const positions = geometry.attributes.position;
54
+ for (let i = 0; i < positions.count; i++) {
55
+ const px = positions.getX(i), py = positions.getY(i);
56
+ const radius = Math.hypot(px, py);
57
+ const side = radius < 1.5 ? -1 : 1;
58
+ positions.setXY(i, px / radius * (x + side * halfWidth), py / radius * (y + side * halfWidth));
59
+ }
60
+ return geometry;
61
+ }
62
+ default: throw new Error('Unsupported Vim3D geometry: ' + primitive);
63
+ }
64
+ }
package/esm/index.js CHANGED
@@ -1 +1,3 @@
1
1
  export const name = '@vim3d/threejs';
2
+ export { Vim3DThreeScene } from './scene.js';
3
+ export { Vim3DPlayer } from './player.js';
package/esm/player.js ADDED
@@ -0,0 +1,171 @@
1
+ import { evaluateFrame } from '@vim3d/core';
2
+ import { Vector2, WebGLRenderer } from 'three';
3
+ import { Vim3DThreeScene } from './scene.js';
4
+ const browserScheduler = {
5
+ request: callback => globalThis.requestAnimationFrame(callback),
6
+ cancel: handle => globalThis.cancelAnimationFrame(handle),
7
+ };
8
+ function assertFps(fps) {
9
+ if (!Number.isFinite(fps) || fps <= 0)
10
+ throw new RangeError('Playback FPS must be finite and positive');
11
+ }
12
+ export class Vim3DPlayer {
13
+ scene;
14
+ options;
15
+ adapter = new Vim3DThreeScene();
16
+ renderer;
17
+ ownedRenderer;
18
+ scheduler;
19
+ rendererSize = new Vector2();
20
+ fps;
21
+ loop;
22
+ frame = 0;
23
+ rendered = false;
24
+ playing = false;
25
+ disposed = false;
26
+ handle;
27
+ startTime;
28
+ startFrame = 0;
29
+ constructor(scene, options) {
30
+ this.scene = scene;
31
+ this.options = options;
32
+ this.fps = options.fps ?? scene.fps;
33
+ assertFps(this.fps);
34
+ this.loop = options.loop ?? false;
35
+ this.scheduler = options.scheduler ?? browserScheduler;
36
+ if (!options.renderer) {
37
+ if (!options.canvas)
38
+ throw new Error('A canvas or custom renderer is required');
39
+ this.ownedRenderer = new WebGLRenderer({ canvas: options.canvas, antialias: true });
40
+ }
41
+ this.renderer = options.renderer ?? this.ownedRenderer;
42
+ }
43
+ getFrame() {
44
+ return this.frame;
45
+ }
46
+ setFps(fps) {
47
+ assertFps(fps);
48
+ this.fps = fps;
49
+ this.startTime = undefined;
50
+ }
51
+ setLoop(loop) {
52
+ this.loop = loop;
53
+ this.startTime = undefined;
54
+ }
55
+ renderFrame(frame) {
56
+ this.assertActive();
57
+ const result = this.draw(frame);
58
+ if ('value' in result)
59
+ this.startTime = undefined;
60
+ return result;
61
+ }
62
+ seek(frame) {
63
+ return this.renderFrame(frame);
64
+ }
65
+ step(delta = 1) {
66
+ if (!Number.isSafeInteger(delta))
67
+ throw new RangeError('Frame delta must be a safe integer');
68
+ return this.renderFrame(this.boundFrame(this.frame + delta));
69
+ }
70
+ play() {
71
+ this.assertActive();
72
+ if (this.playing)
73
+ return;
74
+ this.playing = true;
75
+ this.startTime = undefined;
76
+ try {
77
+ if (!this.rendered && 'diagnostics' in this.draw(this.frame)) {
78
+ this.pause();
79
+ return;
80
+ }
81
+ if (this.playing)
82
+ this.handle = this.scheduler.request(this.tick);
83
+ }
84
+ catch (error) {
85
+ this.pause();
86
+ throw error;
87
+ }
88
+ }
89
+ pause() {
90
+ this.playing = false;
91
+ if (this.handle !== undefined) {
92
+ this.scheduler.cancel(this.handle);
93
+ this.handle = undefined;
94
+ }
95
+ }
96
+ stop() {
97
+ this.pause();
98
+ return this.renderFrame(0);
99
+ }
100
+ dispose() {
101
+ if (this.disposed)
102
+ return;
103
+ this.disposed = true;
104
+ this.pause();
105
+ this.adapter.dispose();
106
+ this.ownedRenderer?.dispose();
107
+ }
108
+ assertActive() {
109
+ if (this.disposed)
110
+ throw new Error('Vim3D player has been disposed');
111
+ }
112
+ boundFrame(frame) {
113
+ const count = this.scene.frameCount;
114
+ if (!count)
115
+ return Math.max(0, frame);
116
+ if (!this.loop)
117
+ return Math.max(0, Math.min(frame, count - 1));
118
+ return ((frame % count) + count) % count;
119
+ }
120
+ draw(frame) {
121
+ const result = evaluateFrame(this.scene, frame);
122
+ if ('diagnostics' in result) {
123
+ this.options.onDiagnostics?.(result.diagnostics);
124
+ return result;
125
+ }
126
+ const snapshot = result.value;
127
+ this.adapter.applyFrameSnapshot(snapshot);
128
+ const choice = this.options.camera;
129
+ const snapshotCamera = typeof choice === 'string'
130
+ ? this.adapter.getCamera(choice) : choice === undefined ? this.adapter.getCamera() : undefined;
131
+ const camera = snapshotCamera ?? (typeof choice === 'object' ? choice : undefined);
132
+ if (!camera)
133
+ throw new Error('No render camera found' + (choice ? ': ' + choice : ''));
134
+ if (snapshotCamera && this.renderer.getSize) {
135
+ const { x, y } = this.renderer.getSize(this.rendererSize);
136
+ if (x > 0 && y > 0) {
137
+ snapshotCamera.aspect = x / y;
138
+ snapshotCamera.updateProjectionMatrix();
139
+ }
140
+ }
141
+ this.renderer.render(this.adapter.scene, camera);
142
+ this.frame = frame;
143
+ this.rendered = true;
144
+ this.options.onFrame?.(snapshot);
145
+ return result;
146
+ }
147
+ tick = (timestamp) => {
148
+ this.handle = undefined;
149
+ if (!this.playing)
150
+ return;
151
+ if (this.startTime === undefined) {
152
+ this.startTime = timestamp;
153
+ this.startFrame = this.frame;
154
+ }
155
+ const next = this.startFrame + Math.floor((timestamp - this.startTime) * this.fps / 1000);
156
+ const frame = this.boundFrame(next);
157
+ try {
158
+ if (frame !== this.frame && 'diagnostics' in this.draw(frame))
159
+ this.pause();
160
+ const count = this.scene.frameCount;
161
+ if (!this.loop && count !== undefined && next >= count - 1)
162
+ this.pause();
163
+ if (this.playing)
164
+ this.handle = this.scheduler.request(this.tick);
165
+ }
166
+ catch (error) {
167
+ this.pause();
168
+ throw error;
169
+ }
170
+ };
171
+ }
package/esm/scene.js ADDED
@@ -0,0 +1,157 @@
1
+ import { DirectionalLight, DoubleSide, Group, Line, LineBasicMaterial, Mesh, MeshPhongMaterial, PerspectiveCamera, PointLight, Scene, SpotLight, Vector3, } from 'three';
2
+ import { createGeometry, isLine } from './geometry.js';
3
+ function renderType(snapshot) {
4
+ if (snapshot.camera)
5
+ return 'camera';
6
+ if (snapshot.light)
7
+ return snapshot.light.kind;
8
+ if (!snapshot.geometry)
9
+ return 'group';
10
+ return isLine(snapshot.geometry.primitive) ? 'line' : 'mesh';
11
+ }
12
+ function createObject(type, geometry) {
13
+ switch (type) {
14
+ case 'camera': return new PerspectiveCamera();
15
+ case 'point': return new PointLight();
16
+ case 'spot': return new SpotLight();
17
+ case 'directional': return new DirectionalLight();
18
+ case 'line': return new Line(createGeometry(geometry), new LineBasicMaterial());
19
+ case 'mesh': return new Mesh(createGeometry(geometry), new MeshPhongMaterial({ side: DoubleSide }));
20
+ default: return new Group();
21
+ }
22
+ }
23
+ function applyCamera(camera, sample) {
24
+ const { position, direction, up, fovy, znear, zfar } = sample;
25
+ camera.position.fromArray(position);
26
+ camera.up.fromArray(up);
27
+ const z = new Vector3(...direction).negate().normalize();
28
+ if (z.lengthSq() === 0)
29
+ z.set(0, 0, 1);
30
+ const x = new Vector3().crossVectors(camera.up, z);
31
+ if (x.lengthSq() < Number.EPSILON) {
32
+ if (Math.abs(z.x) < 0.9)
33
+ x.set(1, 0, 0);
34
+ else
35
+ x.set(0, 1, 0);
36
+ x.cross(z);
37
+ }
38
+ x.normalize();
39
+ const y = new Vector3().crossVectors(z, x);
40
+ camera.matrix.makeBasis(x, y, z).setPosition(camera.position);
41
+ camera.quaternion.setFromRotationMatrix(camera.matrix);
42
+ camera.scale.setScalar(1);
43
+ camera.fov = fovy;
44
+ camera.near = znear;
45
+ camera.far = zfar;
46
+ camera.updateProjectionMatrix();
47
+ }
48
+ function applyMaterial(material, sample) {
49
+ const [red, green, blue, alpha] = sample?.diffuse ?? [1, 1, 1, 1];
50
+ material.color.setRGB(red, green, blue);
51
+ material.opacity = alpha;
52
+ material.transparent = alpha < 1;
53
+ material.depthWrite = !material.transparent;
54
+ if (material instanceof MeshPhongMaterial) {
55
+ const [ar, ag, ab] = sample?.ambient ?? [0, 0, 0];
56
+ const [sr, sg, sb] = sample?.specular ?? [0, 0, 0];
57
+ material.emissive.setRGB(ar, ag, ab);
58
+ material.specular.setRGB(sr, sg, sb);
59
+ material.shininess = sample?.shininess ?? 0;
60
+ }
61
+ }
62
+ function disposeEntry(object) {
63
+ object.removeFromParent();
64
+ if (object instanceof Mesh || object instanceof Line) {
65
+ object.geometry.dispose();
66
+ object.material.dispose();
67
+ }
68
+ else if (object instanceof PointLight || object instanceof SpotLight || object instanceof DirectionalLight) {
69
+ if (!(object instanceof PointLight))
70
+ object.target.removeFromParent();
71
+ object.dispose();
72
+ }
73
+ }
74
+ export class Vim3DThreeScene {
75
+ scene = new Scene();
76
+ entries = new Map();
77
+ getObject(path) {
78
+ return this.entries.get(path)?.object;
79
+ }
80
+ getCamera(path) {
81
+ if (path !== undefined) {
82
+ const object = this.getObject(path);
83
+ return object instanceof PerspectiveCamera ? object : undefined;
84
+ }
85
+ for (const { object } of this.entries.values()) {
86
+ if (object instanceof PerspectiveCamera && object.visible)
87
+ return object;
88
+ }
89
+ }
90
+ applyFrameSnapshot(snapshot) {
91
+ const seen = new Set();
92
+ for (const sample of snapshot.objects) {
93
+ const { path, geometry } = sample;
94
+ seen.add(path);
95
+ const type = renderType(sample);
96
+ let entry = this.entries.get(path);
97
+ if (!entry || entry.type !== type) {
98
+ const object = createObject(type, geometry);
99
+ if (entry)
100
+ disposeEntry(entry.object);
101
+ object.name = path;
102
+ object.matrixAutoUpdate = false;
103
+ object.matrixWorldAutoUpdate = false;
104
+ this.scene.add(object);
105
+ if (object instanceof SpotLight || object instanceof DirectionalLight)
106
+ this.scene.add(object.target);
107
+ entry = { object, type, geometry };
108
+ this.entries.set(path, entry);
109
+ }
110
+ const { object } = entry;
111
+ if (object instanceof PerspectiveCamera && sample.camera) {
112
+ applyCamera(object, sample.camera);
113
+ }
114
+ else {
115
+ object.matrix.fromArray(sample.worldMatrix);
116
+ }
117
+ object.matrixWorld.copy(object.matrix);
118
+ object.matrixWorldNeedsUpdate = true;
119
+ object.visible = sample.visible;
120
+ if (object instanceof Mesh || object instanceof Line) {
121
+ if (geometry !== entry.geometry) {
122
+ const next = createGeometry(geometry);
123
+ object.geometry.dispose();
124
+ object.geometry = next;
125
+ entry.geometry = geometry;
126
+ }
127
+ applyMaterial(object.material, sample.material);
128
+ }
129
+ else if (object instanceof PerspectiveCamera) {
130
+ object.updateMatrixWorld();
131
+ }
132
+ else if (sample.light && (object instanceof PointLight ||
133
+ object instanceof SpotLight || object instanceof DirectionalLight)) {
134
+ const { position, direction, enabled } = sample.light;
135
+ object.position.fromArray(position);
136
+ object.visible = sample.visible && enabled;
137
+ const [r, g, b] = sample.material?.diffuse ?? [1, 1, 1];
138
+ object.color.setRGB(r, g, b);
139
+ if (object instanceof SpotLight || object instanceof DirectionalLight) {
140
+ object.target.position.fromArray(direction).add(object.position);
141
+ object.target.updateMatrixWorld();
142
+ }
143
+ }
144
+ }
145
+ for (const [path, { object }] of this.entries) {
146
+ if (!seen.has(path)) {
147
+ disposeEntry(object);
148
+ this.entries.delete(path);
149
+ }
150
+ }
151
+ }
152
+ dispose() {
153
+ for (const { object } of this.entries.values())
154
+ disposeEntry(object);
155
+ this.entries.clear();
156
+ }
157
+ }
package/geometry.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { BufferGeometry } from 'three';
2
+ import type { GeometrySnapshot } from '@vim3d/core';
3
+ export declare function isLine(primitive: string): boolean;
4
+ export declare function createGeometry({ primitive, args, vertices }: GeometrySnapshot): BufferGeometry;
package/geometry.js ADDED
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isLine = isLine;
4
+ exports.createGeometry = createGeometry;
5
+ const three_1 = require("three");
6
+ function isLine(primitive) {
7
+ return primitive === 'curve' || primitive === 'ellipse' || primitive === 'circle';
8
+ }
9
+ const segments = (value, minimum) => Math.min(256, Math.max(minimum, Math.floor(value)));
10
+ function grid(args) {
11
+ const [a, b, spacing = 10, x = 0, z = 0] = args;
12
+ if (!args.length)
13
+ return new three_1.PlaneGeometry(200, 200);
14
+ if (args.length === 2)
15
+ return new three_1.PlaneGeometry(a, b);
16
+ const cellsX = Math.max(0, Math.trunc(a) - 1);
17
+ const cellsZ = Math.max(0, Math.trunc(b ?? a) - 1);
18
+ const width = cellsX * spacing, depth = cellsZ * spacing;
19
+ return new three_1.PlaneGeometry(width, depth, segments(cellsX, 1), segments(cellsZ, 1))
20
+ .rotateX(-Math.PI / 2).translate(x + width / 2, 0, z + depth / 2);
21
+ }
22
+ function ellipse(primitive, args) {
23
+ const face = primitive.endsWith('Face');
24
+ const circle = primitive.startsWith('circle');
25
+ const defaultRadii = circle ? [10, 10] : face ? [20, 10] : [10, 15];
26
+ const countOnly = args.length === 1 && primitive === 'ellipseFace';
27
+ const x = countOnly ? defaultRadii[0] : args[0] ?? defaultRadii[0];
28
+ const y = countOnly || !args.length ? defaultRadii[1]
29
+ : primitive === 'circle' && args.length === 2 ? x : args[1] ?? x;
30
+ const count = segments(countOnly ? args[0]
31
+ : primitive === 'circle' && args.length === 2 ? args[1] : args[2] ?? 32, 3);
32
+ if (face)
33
+ return new three_1.CircleGeometry(1, count).scale(x, y, 1);
34
+ return new three_1.BufferGeometry().setFromPoints(Array.from({ length: count + 1 }, (_, i) => {
35
+ const angle = i / count * Math.PI * 2;
36
+ return new three_1.Vector3(x * Math.cos(angle), y * Math.sin(angle), 0);
37
+ }));
38
+ }
39
+ function createGeometry({ primitive, args, vertices }) {
40
+ switch (primitive) {
41
+ case 'curve': return new three_1.BufferGeometry().setFromPoints((vertices ?? []).map(point => new three_1.Vector3(...point)));
42
+ case 'cube': return new three_1.BoxGeometry(10, 10, 10).translate(5, 5, 5);
43
+ case 'grid': return grid(args);
44
+ case 'sphere': {
45
+ const [width = 10, height = width, detail = 32] = args;
46
+ return new three_1.SphereGeometry(1, segments(detail, 3), segments(detail / 2, 2)).scale(width, height, width);
47
+ }
48
+ case 'ellipse':
49
+ case 'ellipseFace':
50
+ case 'circle':
51
+ case 'circleFace': return ellipse(primitive, args);
52
+ case 'ring': {
53
+ const [x = 10, b, detail = 32, width] = args;
54
+ const y = args.length >= 3 ? b : x;
55
+ const halfWidth = width === undefined ? 0.5 : width / 0.5;
56
+ const geometry = new three_1.RingGeometry(1, 2, segments(args.length === 2 ? b : detail, 3));
57
+ const positions = geometry.attributes.position;
58
+ for (let i = 0; i < positions.count; i++) {
59
+ const px = positions.getX(i), py = positions.getY(i);
60
+ const radius = Math.hypot(px, py);
61
+ const side = radius < 1.5 ? -1 : 1;
62
+ positions.setXY(i, px / radius * (x + side * halfWidth), py / radius * (y + side * halfWidth));
63
+ }
64
+ return geometry;
65
+ }
66
+ default: throw new Error('Unsupported Vim3D geometry: ' + primitive);
67
+ }
68
+ }
package/index.d.ts CHANGED
@@ -1 +1,4 @@
1
1
  export declare const name = "@vim3d/threejs";
2
+ export { Vim3DThreeScene } from './scene.js';
3
+ export { Vim3DPlayer } from './player.js';
4
+ export type { FrameRenderer, FrameScheduler, PlayerOptions } from './player.js';
package/index.js CHANGED
@@ -1,4 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.name = void 0;
3
+ exports.Vim3DPlayer = exports.Vim3DThreeScene = exports.name = void 0;
4
4
  exports.name = '@vim3d/threejs';
5
+ var scene_js_1 = require("./scene.js");
6
+ Object.defineProperty(exports, "Vim3DThreeScene", { enumerable: true, get: function () { return scene_js_1.Vim3DThreeScene; } });
7
+ var player_js_1 = require("./player.js");
8
+ Object.defineProperty(exports, "Vim3DPlayer", { enumerable: true, get: function () { return player_js_1.Vim3DPlayer; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vim3d/threejs",
3
- "version": "0.0.1",
3
+ "version": "0.2.0",
4
4
  "description": "A Three.js renderer for Vim3D scenes.",
5
5
  "author": "Dan Lynch <pyramation@gmail.com>",
6
6
  "homepage": "https://github.com/pyramation/vim3d/tree/master/js/packages/threejs",
@@ -20,14 +20,23 @@
20
20
  "bugs": {
21
21
  "url": "https://github.com/pyramation/vim3d/issues"
22
22
  },
23
- "scripts": {
24
- "build": "makage build && cp scripts/esm-package.json dist/esm/package.json",
25
- "clean": "makage clean",
26
- "test": "node --test test/*.test.mjs"
23
+ "dependencies": {
24
+ "@vim3d/core": "^0.2.0"
25
+ },
26
+ "peerDependencies": {
27
+ "three": ">=0.170.0 <1.0.0"
27
28
  },
28
29
  "devDependencies": {
29
- "@types/node": "^22.0.0",
30
+ "@types/three": "^0.185.4",
30
31
  "makage": "^0.8.0",
31
- "typescript": "^5.9.3"
32
+ "three": "^0.185.1"
33
+ },
34
+ "scripts": {
35
+ "clean": "makage clean",
36
+ "build": "makage build && cp scripts/esm-package.json dist/esm/package.json",
37
+ "build:dev": "makage build --dev && cp scripts/esm-package.json dist/esm/package.json",
38
+ "lint": "eslint . --fix",
39
+ "test": "jest",
40
+ "test:watch": "jest --watch"
32
41
  }
33
- }
42
+ }
package/player.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { type CompiledScene, type Diagnostic, type FrameSnapshot, type Result } from '@vim3d/core';
2
+ import { WebGLRenderer, type Camera } from 'three';
3
+ import { Vim3DThreeScene } from './scene.js';
4
+ export type FrameRenderer = Pick<WebGLRenderer, 'render'> & Partial<Pick<WebGLRenderer, 'getSize'>>;
5
+ export interface FrameScheduler {
6
+ request(callback: (timestamp: number) => void): number;
7
+ cancel(handle: number): void;
8
+ }
9
+ export interface PlayerOptions {
10
+ readonly canvas?: HTMLCanvasElement | OffscreenCanvas;
11
+ readonly renderer?: FrameRenderer;
12
+ readonly camera?: string | Camera;
13
+ readonly scheduler?: FrameScheduler;
14
+ readonly fps?: number;
15
+ readonly loop?: boolean;
16
+ readonly onFrame?: (snapshot: FrameSnapshot) => void;
17
+ readonly onDiagnostics?: (diagnostics: readonly Diagnostic[]) => void;
18
+ }
19
+ export declare class Vim3DPlayer {
20
+ private readonly scene;
21
+ private readonly options;
22
+ readonly adapter: Vim3DThreeScene;
23
+ readonly renderer: FrameRenderer;
24
+ private readonly ownedRenderer?;
25
+ private readonly scheduler;
26
+ private readonly rendererSize;
27
+ private fps;
28
+ private loop;
29
+ private frame;
30
+ private rendered;
31
+ private playing;
32
+ private disposed;
33
+ private handle?;
34
+ private startTime?;
35
+ private startFrame;
36
+ constructor(scene: CompiledScene, options: PlayerOptions);
37
+ getFrame(): number;
38
+ setFps(fps: number): void;
39
+ setLoop(loop: boolean): void;
40
+ renderFrame(frame: number): Result<FrameSnapshot>;
41
+ seek(frame: number): Result<FrameSnapshot>;
42
+ step(delta?: number): Result<FrameSnapshot>;
43
+ play(): void;
44
+ pause(): void;
45
+ stop(): Result<FrameSnapshot>;
46
+ dispose(): void;
47
+ private assertActive;
48
+ private boundFrame;
49
+ private draw;
50
+ private readonly tick;
51
+ }
package/player.js ADDED
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Vim3DPlayer = void 0;
4
+ const core_1 = require("@vim3d/core");
5
+ const three_1 = require("three");
6
+ const scene_js_1 = require("./scene.js");
7
+ const browserScheduler = {
8
+ request: callback => globalThis.requestAnimationFrame(callback),
9
+ cancel: handle => globalThis.cancelAnimationFrame(handle),
10
+ };
11
+ function assertFps(fps) {
12
+ if (!Number.isFinite(fps) || fps <= 0)
13
+ throw new RangeError('Playback FPS must be finite and positive');
14
+ }
15
+ class Vim3DPlayer {
16
+ scene;
17
+ options;
18
+ adapter = new scene_js_1.Vim3DThreeScene();
19
+ renderer;
20
+ ownedRenderer;
21
+ scheduler;
22
+ rendererSize = new three_1.Vector2();
23
+ fps;
24
+ loop;
25
+ frame = 0;
26
+ rendered = false;
27
+ playing = false;
28
+ disposed = false;
29
+ handle;
30
+ startTime;
31
+ startFrame = 0;
32
+ constructor(scene, options) {
33
+ this.scene = scene;
34
+ this.options = options;
35
+ this.fps = options.fps ?? scene.fps;
36
+ assertFps(this.fps);
37
+ this.loop = options.loop ?? false;
38
+ this.scheduler = options.scheduler ?? browserScheduler;
39
+ if (!options.renderer) {
40
+ if (!options.canvas)
41
+ throw new Error('A canvas or custom renderer is required');
42
+ this.ownedRenderer = new three_1.WebGLRenderer({ canvas: options.canvas, antialias: true });
43
+ }
44
+ this.renderer = options.renderer ?? this.ownedRenderer;
45
+ }
46
+ getFrame() {
47
+ return this.frame;
48
+ }
49
+ setFps(fps) {
50
+ assertFps(fps);
51
+ this.fps = fps;
52
+ this.startTime = undefined;
53
+ }
54
+ setLoop(loop) {
55
+ this.loop = loop;
56
+ this.startTime = undefined;
57
+ }
58
+ renderFrame(frame) {
59
+ this.assertActive();
60
+ const result = this.draw(frame);
61
+ if ('value' in result)
62
+ this.startTime = undefined;
63
+ return result;
64
+ }
65
+ seek(frame) {
66
+ return this.renderFrame(frame);
67
+ }
68
+ step(delta = 1) {
69
+ if (!Number.isSafeInteger(delta))
70
+ throw new RangeError('Frame delta must be a safe integer');
71
+ return this.renderFrame(this.boundFrame(this.frame + delta));
72
+ }
73
+ play() {
74
+ this.assertActive();
75
+ if (this.playing)
76
+ return;
77
+ this.playing = true;
78
+ this.startTime = undefined;
79
+ try {
80
+ if (!this.rendered && 'diagnostics' in this.draw(this.frame)) {
81
+ this.pause();
82
+ return;
83
+ }
84
+ if (this.playing)
85
+ this.handle = this.scheduler.request(this.tick);
86
+ }
87
+ catch (error) {
88
+ this.pause();
89
+ throw error;
90
+ }
91
+ }
92
+ pause() {
93
+ this.playing = false;
94
+ if (this.handle !== undefined) {
95
+ this.scheduler.cancel(this.handle);
96
+ this.handle = undefined;
97
+ }
98
+ }
99
+ stop() {
100
+ this.pause();
101
+ return this.renderFrame(0);
102
+ }
103
+ dispose() {
104
+ if (this.disposed)
105
+ return;
106
+ this.disposed = true;
107
+ this.pause();
108
+ this.adapter.dispose();
109
+ this.ownedRenderer?.dispose();
110
+ }
111
+ assertActive() {
112
+ if (this.disposed)
113
+ throw new Error('Vim3D player has been disposed');
114
+ }
115
+ boundFrame(frame) {
116
+ const count = this.scene.frameCount;
117
+ if (!count)
118
+ return Math.max(0, frame);
119
+ if (!this.loop)
120
+ return Math.max(0, Math.min(frame, count - 1));
121
+ return ((frame % count) + count) % count;
122
+ }
123
+ draw(frame) {
124
+ const result = (0, core_1.evaluateFrame)(this.scene, frame);
125
+ if ('diagnostics' in result) {
126
+ this.options.onDiagnostics?.(result.diagnostics);
127
+ return result;
128
+ }
129
+ const snapshot = result.value;
130
+ this.adapter.applyFrameSnapshot(snapshot);
131
+ const choice = this.options.camera;
132
+ const snapshotCamera = typeof choice === 'string'
133
+ ? this.adapter.getCamera(choice) : choice === undefined ? this.adapter.getCamera() : undefined;
134
+ const camera = snapshotCamera ?? (typeof choice === 'object' ? choice : undefined);
135
+ if (!camera)
136
+ throw new Error('No render camera found' + (choice ? ': ' + choice : ''));
137
+ if (snapshotCamera && this.renderer.getSize) {
138
+ const { x, y } = this.renderer.getSize(this.rendererSize);
139
+ if (x > 0 && y > 0) {
140
+ snapshotCamera.aspect = x / y;
141
+ snapshotCamera.updateProjectionMatrix();
142
+ }
143
+ }
144
+ this.renderer.render(this.adapter.scene, camera);
145
+ this.frame = frame;
146
+ this.rendered = true;
147
+ this.options.onFrame?.(snapshot);
148
+ return result;
149
+ }
150
+ tick = (timestamp) => {
151
+ this.handle = undefined;
152
+ if (!this.playing)
153
+ return;
154
+ if (this.startTime === undefined) {
155
+ this.startTime = timestamp;
156
+ this.startFrame = this.frame;
157
+ }
158
+ const next = this.startFrame + Math.floor((timestamp - this.startTime) * this.fps / 1000);
159
+ const frame = this.boundFrame(next);
160
+ try {
161
+ if (frame !== this.frame && 'diagnostics' in this.draw(frame))
162
+ this.pause();
163
+ const count = this.scene.frameCount;
164
+ if (!this.loop && count !== undefined && next >= count - 1)
165
+ this.pause();
166
+ if (this.playing)
167
+ this.handle = this.scheduler.request(this.tick);
168
+ }
169
+ catch (error) {
170
+ this.pause();
171
+ throw error;
172
+ }
173
+ };
174
+ }
175
+ exports.Vim3DPlayer = Vim3DPlayer;
package/scene.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { Object3D, PerspectiveCamera, Scene } from 'three';
2
+ import type { FrameSnapshot } from '@vim3d/core';
3
+ export declare class Vim3DThreeScene {
4
+ readonly scene: Scene;
5
+ private readonly entries;
6
+ getObject(path: string): Object3D | undefined;
7
+ getCamera(path?: string): PerspectiveCamera | undefined;
8
+ applyFrameSnapshot(snapshot: FrameSnapshot): void;
9
+ dispose(): void;
10
+ }
package/scene.js ADDED
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Vim3DThreeScene = void 0;
4
+ const three_1 = require("three");
5
+ const geometry_js_1 = require("./geometry.js");
6
+ function renderType(snapshot) {
7
+ if (snapshot.camera)
8
+ return 'camera';
9
+ if (snapshot.light)
10
+ return snapshot.light.kind;
11
+ if (!snapshot.geometry)
12
+ return 'group';
13
+ return (0, geometry_js_1.isLine)(snapshot.geometry.primitive) ? 'line' : 'mesh';
14
+ }
15
+ function createObject(type, geometry) {
16
+ switch (type) {
17
+ case 'camera': return new three_1.PerspectiveCamera();
18
+ case 'point': return new three_1.PointLight();
19
+ case 'spot': return new three_1.SpotLight();
20
+ case 'directional': return new three_1.DirectionalLight();
21
+ case 'line': return new three_1.Line((0, geometry_js_1.createGeometry)(geometry), new three_1.LineBasicMaterial());
22
+ case 'mesh': return new three_1.Mesh((0, geometry_js_1.createGeometry)(geometry), new three_1.MeshPhongMaterial({ side: three_1.DoubleSide }));
23
+ default: return new three_1.Group();
24
+ }
25
+ }
26
+ function applyCamera(camera, sample) {
27
+ const { position, direction, up, fovy, znear, zfar } = sample;
28
+ camera.position.fromArray(position);
29
+ camera.up.fromArray(up);
30
+ const z = new three_1.Vector3(...direction).negate().normalize();
31
+ if (z.lengthSq() === 0)
32
+ z.set(0, 0, 1);
33
+ const x = new three_1.Vector3().crossVectors(camera.up, z);
34
+ if (x.lengthSq() < Number.EPSILON) {
35
+ if (Math.abs(z.x) < 0.9)
36
+ x.set(1, 0, 0);
37
+ else
38
+ x.set(0, 1, 0);
39
+ x.cross(z);
40
+ }
41
+ x.normalize();
42
+ const y = new three_1.Vector3().crossVectors(z, x);
43
+ camera.matrix.makeBasis(x, y, z).setPosition(camera.position);
44
+ camera.quaternion.setFromRotationMatrix(camera.matrix);
45
+ camera.scale.setScalar(1);
46
+ camera.fov = fovy;
47
+ camera.near = znear;
48
+ camera.far = zfar;
49
+ camera.updateProjectionMatrix();
50
+ }
51
+ function applyMaterial(material, sample) {
52
+ const [red, green, blue, alpha] = sample?.diffuse ?? [1, 1, 1, 1];
53
+ material.color.setRGB(red, green, blue);
54
+ material.opacity = alpha;
55
+ material.transparent = alpha < 1;
56
+ material.depthWrite = !material.transparent;
57
+ if (material instanceof three_1.MeshPhongMaterial) {
58
+ const [ar, ag, ab] = sample?.ambient ?? [0, 0, 0];
59
+ const [sr, sg, sb] = sample?.specular ?? [0, 0, 0];
60
+ material.emissive.setRGB(ar, ag, ab);
61
+ material.specular.setRGB(sr, sg, sb);
62
+ material.shininess = sample?.shininess ?? 0;
63
+ }
64
+ }
65
+ function disposeEntry(object) {
66
+ object.removeFromParent();
67
+ if (object instanceof three_1.Mesh || object instanceof three_1.Line) {
68
+ object.geometry.dispose();
69
+ object.material.dispose();
70
+ }
71
+ else if (object instanceof three_1.PointLight || object instanceof three_1.SpotLight || object instanceof three_1.DirectionalLight) {
72
+ if (!(object instanceof three_1.PointLight))
73
+ object.target.removeFromParent();
74
+ object.dispose();
75
+ }
76
+ }
77
+ class Vim3DThreeScene {
78
+ scene = new three_1.Scene();
79
+ entries = new Map();
80
+ getObject(path) {
81
+ return this.entries.get(path)?.object;
82
+ }
83
+ getCamera(path) {
84
+ if (path !== undefined) {
85
+ const object = this.getObject(path);
86
+ return object instanceof three_1.PerspectiveCamera ? object : undefined;
87
+ }
88
+ for (const { object } of this.entries.values()) {
89
+ if (object instanceof three_1.PerspectiveCamera && object.visible)
90
+ return object;
91
+ }
92
+ }
93
+ applyFrameSnapshot(snapshot) {
94
+ const seen = new Set();
95
+ for (const sample of snapshot.objects) {
96
+ const { path, geometry } = sample;
97
+ seen.add(path);
98
+ const type = renderType(sample);
99
+ let entry = this.entries.get(path);
100
+ if (!entry || entry.type !== type) {
101
+ const object = createObject(type, geometry);
102
+ if (entry)
103
+ disposeEntry(entry.object);
104
+ object.name = path;
105
+ object.matrixAutoUpdate = false;
106
+ object.matrixWorldAutoUpdate = false;
107
+ this.scene.add(object);
108
+ if (object instanceof three_1.SpotLight || object instanceof three_1.DirectionalLight)
109
+ this.scene.add(object.target);
110
+ entry = { object, type, geometry };
111
+ this.entries.set(path, entry);
112
+ }
113
+ const { object } = entry;
114
+ if (object instanceof three_1.PerspectiveCamera && sample.camera) {
115
+ applyCamera(object, sample.camera);
116
+ }
117
+ else {
118
+ object.matrix.fromArray(sample.worldMatrix);
119
+ }
120
+ object.matrixWorld.copy(object.matrix);
121
+ object.matrixWorldNeedsUpdate = true;
122
+ object.visible = sample.visible;
123
+ if (object instanceof three_1.Mesh || object instanceof three_1.Line) {
124
+ if (geometry !== entry.geometry) {
125
+ const next = (0, geometry_js_1.createGeometry)(geometry);
126
+ object.geometry.dispose();
127
+ object.geometry = next;
128
+ entry.geometry = geometry;
129
+ }
130
+ applyMaterial(object.material, sample.material);
131
+ }
132
+ else if (object instanceof three_1.PerspectiveCamera) {
133
+ object.updateMatrixWorld();
134
+ }
135
+ else if (sample.light && (object instanceof three_1.PointLight ||
136
+ object instanceof three_1.SpotLight || object instanceof three_1.DirectionalLight)) {
137
+ const { position, direction, enabled } = sample.light;
138
+ object.position.fromArray(position);
139
+ object.visible = sample.visible && enabled;
140
+ const [r, g, b] = sample.material?.diffuse ?? [1, 1, 1];
141
+ object.color.setRGB(r, g, b);
142
+ if (object instanceof three_1.SpotLight || object instanceof three_1.DirectionalLight) {
143
+ object.target.position.fromArray(direction).add(object.position);
144
+ object.target.updateMatrixWorld();
145
+ }
146
+ }
147
+ }
148
+ for (const [path, { object }] of this.entries) {
149
+ if (!seen.has(path)) {
150
+ disposeEntry(object);
151
+ this.entries.delete(path);
152
+ }
153
+ }
154
+ }
155
+ dispose() {
156
+ for (const { object } of this.entries.values())
157
+ disposeEntry(object);
158
+ this.entries.clear();
159
+ }
160
+ }
161
+ exports.Vim3DThreeScene = Vim3DThreeScene;
package/esm/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const name = "@vim3d/threejs";