@vim3d/threejs 0.1.0 → 0.2.1

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/player.js ADDED
@@ -0,0 +1,197 @@
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
+ liveChannels = new Map();
24
+ fps;
25
+ loop;
26
+ frame = 0;
27
+ rendered = false;
28
+ playing = false;
29
+ disposed = false;
30
+ handle;
31
+ startTime;
32
+ startFrame = 0;
33
+ constructor(scene, options) {
34
+ this.scene = scene;
35
+ this.options = options;
36
+ this.fps = options.fps ?? scene.fps;
37
+ assertFps(this.fps);
38
+ this.loop = options.loop ?? false;
39
+ this.scheduler = options.scheduler ?? browserScheduler;
40
+ if (!options.renderer) {
41
+ if (!options.canvas)
42
+ throw new Error('A canvas or custom renderer is required');
43
+ this.ownedRenderer = new three_1.WebGLRenderer({ canvas: options.canvas, antialias: true });
44
+ }
45
+ this.renderer = options.renderer ?? this.ownedRenderer;
46
+ for (const [name, provider] of Object.entries(options.liveChannels ?? {})) {
47
+ this.liveChannels.set(name, provider);
48
+ }
49
+ }
50
+ setLiveChannel(name, provider) {
51
+ this.assertActive();
52
+ if (provider)
53
+ this.liveChannels.set(name, provider);
54
+ else
55
+ this.liveChannels.delete(name);
56
+ }
57
+ getFrame() {
58
+ return this.frame;
59
+ }
60
+ setFps(fps) {
61
+ assertFps(fps);
62
+ this.fps = fps;
63
+ this.startTime = undefined;
64
+ }
65
+ setLoop(loop) {
66
+ this.loop = loop;
67
+ this.startTime = undefined;
68
+ }
69
+ renderFrame(frame) {
70
+ this.assertActive();
71
+ const result = this.draw(frame);
72
+ if ('value' in result)
73
+ this.startTime = undefined;
74
+ return result;
75
+ }
76
+ seek(frame) {
77
+ return this.renderFrame(frame);
78
+ }
79
+ step(delta = 1) {
80
+ if (!Number.isSafeInteger(delta))
81
+ throw new RangeError('Frame delta must be a safe integer');
82
+ return this.renderFrame(this.boundFrame(this.frame + delta));
83
+ }
84
+ play() {
85
+ this.assertActive();
86
+ if (this.playing)
87
+ return;
88
+ this.playing = true;
89
+ this.startTime = undefined;
90
+ try {
91
+ if (!this.rendered && 'diagnostics' in this.draw(this.frame)) {
92
+ this.pause();
93
+ return;
94
+ }
95
+ if (this.playing)
96
+ this.handle = this.scheduler.request(this.tick);
97
+ }
98
+ catch (error) {
99
+ this.pause();
100
+ throw error;
101
+ }
102
+ }
103
+ pause() {
104
+ this.playing = false;
105
+ if (this.handle !== undefined) {
106
+ this.scheduler.cancel(this.handle);
107
+ this.handle = undefined;
108
+ }
109
+ }
110
+ stop() {
111
+ this.pause();
112
+ return this.renderFrame(0);
113
+ }
114
+ dispose() {
115
+ if (this.disposed)
116
+ return;
117
+ this.disposed = true;
118
+ this.pause();
119
+ this.adapter.dispose();
120
+ this.ownedRenderer?.dispose();
121
+ }
122
+ assertActive() {
123
+ if (this.disposed)
124
+ throw new Error('Vim3D player has been disposed');
125
+ }
126
+ boundFrame(frame) {
127
+ const count = this.scene.frameCount;
128
+ if (!count)
129
+ return Math.max(0, frame);
130
+ if (!this.loop)
131
+ return Math.max(0, Math.min(frame, count - 1));
132
+ return ((frame % count) + count) % count;
133
+ }
134
+ draw(frame) {
135
+ let evaluateOptions;
136
+ const validFrame = Number.isSafeInteger(frame) && frame >= 0
137
+ && (this.scene.frameCount === undefined || frame < this.scene.frameCount);
138
+ if (validFrame && this.liveChannels.size) {
139
+ const time = frame / this.scene.fps;
140
+ const sampled = {};
141
+ for (const [name, provider] of this.liveChannels) {
142
+ sampled[name] = provider.sample(frame, time);
143
+ }
144
+ evaluateOptions = { liveChannels: sampled };
145
+ }
146
+ const result = (0, core_1.evaluateFrame)(this.scene, frame, evaluateOptions);
147
+ if ('diagnostics' in result) {
148
+ this.options.onDiagnostics?.(result.diagnostics);
149
+ return result;
150
+ }
151
+ const snapshot = result.value;
152
+ this.adapter.applyFrameSnapshot(snapshot);
153
+ const choice = this.options.camera;
154
+ const snapshotCamera = typeof choice === 'string'
155
+ ? this.adapter.getCamera(choice) : choice === undefined ? this.adapter.getCamera() : undefined;
156
+ const camera = snapshotCamera ?? (typeof choice === 'object' ? choice : undefined);
157
+ if (!camera)
158
+ throw new Error('No render camera found' + (choice ? ': ' + choice : ''));
159
+ if (snapshotCamera && this.renderer.getSize) {
160
+ const { x, y } = this.renderer.getSize(this.rendererSize);
161
+ if (x > 0 && y > 0) {
162
+ snapshotCamera.aspect = x / y;
163
+ snapshotCamera.updateProjectionMatrix();
164
+ }
165
+ }
166
+ this.renderer.render(this.adapter.scene, camera);
167
+ this.frame = frame;
168
+ this.rendered = true;
169
+ this.options.onFrame?.(snapshot);
170
+ return result;
171
+ }
172
+ tick = (timestamp) => {
173
+ this.handle = undefined;
174
+ if (!this.playing)
175
+ return;
176
+ if (this.startTime === undefined) {
177
+ this.startTime = timestamp;
178
+ this.startFrame = this.frame;
179
+ }
180
+ const next = this.startFrame + Math.floor((timestamp - this.startTime) * this.fps / 1000);
181
+ const frame = this.boundFrame(next);
182
+ try {
183
+ if (frame !== this.frame && 'diagnostics' in this.draw(frame))
184
+ this.pause();
185
+ const count = this.scene.frameCount;
186
+ if (!this.loop && count !== undefined && next >= count - 1)
187
+ this.pause();
188
+ if (this.playing)
189
+ this.handle = this.scheduler.request(this.tick);
190
+ }
191
+ catch (error) {
192
+ this.pause();
193
+ throw error;
194
+ }
195
+ };
196
+ }
197
+ 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,172 @@
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.proceduralGeometry !== undefined)
12
+ return 'procedural';
13
+ if (!snapshot.geometry)
14
+ return 'group';
15
+ return (0, geometry_js_1.isLine)(snapshot.geometry.primitive) ? 'line' : 'mesh';
16
+ }
17
+ function createObject(type, geometry) {
18
+ switch (type) {
19
+ case 'camera': return new three_1.PerspectiveCamera();
20
+ case 'point': return new three_1.PointLight();
21
+ case 'spot': return new three_1.SpotLight();
22
+ case 'directional': return new three_1.DirectionalLight();
23
+ case 'line': return new three_1.Line((0, geometry_js_1.createGeometry)(geometry), new three_1.LineBasicMaterial());
24
+ case 'mesh': return new three_1.Mesh((0, geometry_js_1.createGeometry)(geometry), new three_1.MeshPhongMaterial({ side: three_1.DoubleSide }));
25
+ default: return new three_1.Group();
26
+ }
27
+ }
28
+ function applyCamera(camera, sample) {
29
+ const { position, direction, up, fovy, znear, zfar } = sample;
30
+ camera.position.fromArray(position);
31
+ camera.up.fromArray(up);
32
+ const z = new three_1.Vector3(...direction).negate().normalize();
33
+ if (z.lengthSq() === 0)
34
+ z.set(0, 0, 1);
35
+ const x = new three_1.Vector3().crossVectors(camera.up, z);
36
+ if (x.lengthSq() < Number.EPSILON) {
37
+ if (Math.abs(z.x) < 0.9)
38
+ x.set(1, 0, 0);
39
+ else
40
+ x.set(0, 1, 0);
41
+ x.cross(z);
42
+ }
43
+ x.normalize();
44
+ const y = new three_1.Vector3().crossVectors(z, x);
45
+ camera.matrix.makeBasis(x, y, z).setPosition(camera.position);
46
+ camera.quaternion.setFromRotationMatrix(camera.matrix);
47
+ camera.scale.setScalar(1);
48
+ camera.fov = fovy;
49
+ camera.near = znear;
50
+ camera.far = zfar;
51
+ camera.updateProjectionMatrix();
52
+ }
53
+ function applyMaterial(material, sample) {
54
+ const [red, green, blue, alpha] = sample?.diffuse ?? [1, 1, 1, 1];
55
+ material.color.setRGB(red, green, blue);
56
+ material.opacity = alpha;
57
+ material.transparent = alpha < 1;
58
+ material.depthWrite = !material.transparent;
59
+ if (material instanceof three_1.MeshPhongMaterial) {
60
+ const [ar, ag, ab] = sample?.ambient ?? [0, 0, 0];
61
+ const [sr, sg, sb] = sample?.specular ?? [0, 0, 0];
62
+ material.emissive.setRGB(ar, ag, ab);
63
+ material.specular.setRGB(sr, sg, sb);
64
+ material.shininess = sample?.shininess ?? 0;
65
+ }
66
+ }
67
+ function disposeEntry({ object, proceduralMaterial }) {
68
+ object.removeFromParent();
69
+ if (proceduralMaterial) {
70
+ (0, geometry_js_1.disposeProceduralGeometry)(object);
71
+ proceduralMaterial.dispose();
72
+ }
73
+ else if (object instanceof three_1.Mesh || object instanceof three_1.Line) {
74
+ object.geometry.dispose();
75
+ object.material.dispose();
76
+ }
77
+ else if (object instanceof three_1.PointLight || object instanceof three_1.SpotLight || object instanceof three_1.DirectionalLight) {
78
+ if (!(object instanceof three_1.PointLight))
79
+ object.target.removeFromParent();
80
+ object.dispose();
81
+ }
82
+ }
83
+ class Vim3DThreeScene {
84
+ scene = new three_1.Scene();
85
+ entries = new Map();
86
+ getObject(path) {
87
+ return this.entries.get(path)?.object;
88
+ }
89
+ getCamera(path) {
90
+ if (path !== undefined) {
91
+ const object = this.getObject(path);
92
+ return object instanceof three_1.PerspectiveCamera ? object : undefined;
93
+ }
94
+ for (const { object } of this.entries.values()) {
95
+ if (object instanceof three_1.PerspectiveCamera && object.visible)
96
+ return object;
97
+ }
98
+ }
99
+ applyFrameSnapshot(snapshot) {
100
+ const seen = new Set();
101
+ for (const sample of snapshot.objects) {
102
+ const { path, geometry } = sample;
103
+ seen.add(path);
104
+ const type = renderType(sample);
105
+ let entry = this.entries.get(path);
106
+ if (!entry || entry.type !== type) {
107
+ const object = createObject(type, geometry);
108
+ if (entry)
109
+ disposeEntry(entry);
110
+ object.name = path;
111
+ object.matrixAutoUpdate = false;
112
+ object.matrixWorldAutoUpdate = false;
113
+ this.scene.add(object);
114
+ if (object instanceof three_1.SpotLight || object instanceof three_1.DirectionalLight)
115
+ this.scene.add(object.target);
116
+ entry = { object, type, geometry,
117
+ ...(type === 'procedural' && { proceduralMaterial: new three_1.MeshPhongMaterial({ side: three_1.DoubleSide }) }) };
118
+ this.entries.set(path, entry);
119
+ }
120
+ const { object } = entry;
121
+ if (object instanceof three_1.PerspectiveCamera && sample.camera) {
122
+ applyCamera(object, sample.camera);
123
+ }
124
+ else {
125
+ object.matrix.fromArray(sample.worldMatrix);
126
+ }
127
+ object.matrixWorld.copy(object.matrix);
128
+ object.matrixWorldNeedsUpdate = true;
129
+ object.visible = sample.visible;
130
+ if (entry.proceduralMaterial && object instanceof three_1.Group) {
131
+ applyMaterial(entry.proceduralMaterial, sample.material);
132
+ (0, geometry_js_1.updateProceduralGeometry)(object, sample.proceduralGeometry, entry.proceduralMaterial);
133
+ }
134
+ else if (object instanceof three_1.Mesh || object instanceof three_1.Line) {
135
+ if (geometry !== entry.geometry) {
136
+ const next = (0, geometry_js_1.createGeometry)(geometry);
137
+ object.geometry.dispose();
138
+ object.geometry = next;
139
+ entry.geometry = geometry;
140
+ }
141
+ applyMaterial(object.material, sample.material);
142
+ }
143
+ else if (object instanceof three_1.PerspectiveCamera) {
144
+ object.updateMatrixWorld();
145
+ }
146
+ else if (sample.light && (object instanceof three_1.PointLight ||
147
+ object instanceof three_1.SpotLight || object instanceof three_1.DirectionalLight)) {
148
+ const { position, direction, enabled } = sample.light;
149
+ object.position.fromArray(position);
150
+ object.visible = sample.visible && enabled;
151
+ const [r, g, b] = sample.material?.diffuse ?? [1, 1, 1];
152
+ object.color.setRGB(r, g, b);
153
+ if (object instanceof three_1.SpotLight || object instanceof three_1.DirectionalLight) {
154
+ object.target.position.fromArray(direction).add(object.position);
155
+ object.target.updateMatrixWorld();
156
+ }
157
+ }
158
+ }
159
+ for (const [path, entry] of this.entries) {
160
+ if (!seen.has(path)) {
161
+ disposeEntry(entry);
162
+ this.entries.delete(path);
163
+ }
164
+ }
165
+ }
166
+ dispose() {
167
+ for (const entry of this.entries.values())
168
+ disposeEntry(entry);
169
+ this.entries.clear();
170
+ }
171
+ }
172
+ exports.Vim3DThreeScene = Vim3DThreeScene;